repo_name
stringlengths
7
79
path
stringlengths
8
206
copies
stringclasses
36 values
size
stringlengths
2
6
content
stringlengths
55
523k
license
stringclasses
15 values
hash
stringlengths
32
32
line_mean
float64
7.18
99.5
line_max
int64
16
979
alpha_frac
float64
0.3
0.87
ratio
float64
2.01
8.07
autogenerated
bool
1 class
config_or_test
bool
2 classes
has_no_keywords
bool
2 classes
has_few_assignments
bool
1 class
ajalt/clikt
clikt/src/commonMain/kotlin/com/github/ajalt/clikt/parameters/options/Option.kt
1
6593
package com.github.ajalt.clikt.parameters.options import com.github.ajalt.clikt.completion.CompletionCandidates import com.github.ajalt.clikt.core.* import com.github.ajalt.clikt.mpp.isLetterOrDigit import com.github.ajalt.clikt.output.HelpFormatter import com.github.ajalt.clikt.parsers.OptionParser import com.github.ajalt.clikt.sources.ValueSource import kotlin.properties.ReadOnlyProperty import kotlin.reflect.KProperty /** * An optional command line parameter that takes a fixed number of values. * * Options can take any fixed number of values, including 0. */ interface Option { /** A name representing the values for this option that can be displayed to the user. */ fun metavar(context: Context): String? /** The description of this option, usually a single line. */ val optionHelp: String /** The parser for this option's values. */ val parser: OptionParser /** The names that can be used to invoke this option. They must start with a punctuation character. */ val names: Set<String> /** Names that can be used for a secondary purpose, like disabling flag options. */ val secondaryNames: Set<String> /** The number of values that must be given to this option. */ val nvalues: Int /** If true, this option should not appear in help output. */ val hidden: Boolean /** Extra information about this option to pass to the help formatter. */ val helpTags: Map<String, String> /** Optional set of strings to use when the user invokes shell autocomplete on a value for this option. */ val completionCandidates: CompletionCandidates get() = CompletionCandidates.None /** Optional explicit key to use when looking this option up from a [ValueSource] */ val valueSourceKey: String? /** Information about this option for the help output. */ fun parameterHelp(context: Context): HelpFormatter.ParameterHelp.Option? = when { hidden -> null else -> HelpFormatter.ParameterHelp.Option(names, secondaryNames, metavar(context), optionHelp, nvalues, helpTags, groupName = (this as? StaticallyGroupedOption)?.groupName ?: (this as? GroupableOption)?.parameterGroup?.groupName ) } /** * Called after this command's argv is parsed to transform and store the option's value. * * You cannot refer to other parameter values during this call, since they might not have been * finalized yet. * * @param context The context for this parse * @param invocations A possibly empty list of invocations of this option. */ fun finalize(context: Context, invocations: List<OptionParser.Invocation>) /** * Called after all of a command's parameters have been [finalize]d to perform validation of the final value. */ fun postValidate(context: Context) } /** An option that functions as a property delegate */ interface OptionDelegate<T> : GroupableOption, ReadOnlyProperty<ParameterHolder, T> { /** * The value for this option. * * An exception should be thrown if this property is accessed before [finalize] is called. */ val value: T /** Implementations must call [ParameterHolder.registerOption] */ operator fun provideDelegate(thisRef: ParameterHolder, prop: KProperty<*>): ReadOnlyProperty<ParameterHolder, T> override fun getValue(thisRef: ParameterHolder, property: KProperty<*>): T = value } internal fun inferOptionNames(names: Set<String>, propertyName: String): Set<String> { if (names.isNotEmpty()) { val invalidName = names.find { !it.matches(Regex("""[\-@/+]{1,2}[\w\-_]+""")) } require(invalidName == null) { "Invalid option name \"$invalidName\"" } return names } val normalizedName = "--" + propertyName.replace(Regex("""[a-z][A-Z]""")) { "${it.value[0]}-${it.value[1]}" }.lowercase() return setOf(normalizedName) } internal fun inferEnvvar(names: Set<String>, envvar: String?, autoEnvvarPrefix: String?): String? { if (envvar != null) return envvar if (names.isEmpty() || autoEnvvarPrefix == null) return null val name = splitOptionPrefix(names.maxByOrNull { it.length }!!).second if (name.isEmpty()) return null return autoEnvvarPrefix + "_" + name.replace(Regex("\\W"), "_").uppercase() } /** Split an option token into a pair of prefix to simple name. */ internal fun splitOptionPrefix(name: String): Pair<String, String> = when { name.length < 2 || isLetterOrDigit(name[0]) -> "" to name name.length > 2 && name[0] == name[1] -> name.slice(0..1) to name.substring(2) else -> name.substring(0, 1) to name.substring(1) } internal fun <EachT, AllT> deprecationTransformer( message: String? = "", error: Boolean = false, transformAll: CallsTransformer<EachT, AllT>, ): CallsTransformer<EachT, AllT> = { if (it.isNotEmpty()) { val msg = when (message) { null -> "" "" -> "${if (error) "ERROR" else "WARNING"}: option ${option.longestName()} is deprecated" else -> message } if (error) { throw CliktError(msg) } else if (message != null) { message(msg) } } transformAll(it) } internal fun Option.longestName(): String? = names.maxByOrNull { it.length } internal sealed class FinalValue { data class Parsed(val values: List<OptionParser.Invocation>) : FinalValue() data class Sourced(val values: List<ValueSource.Invocation>) : FinalValue() data class Envvar(val key: String, val value: String) : FinalValue() } internal fun Option.getFinalValue( context: Context, invocations: List<OptionParser.Invocation>, envvar: String?, ): FinalValue { return when { invocations.isNotEmpty() -> FinalValue.Parsed(invocations) context.readEnvvarBeforeValueSource -> { readEnvVar(context, envvar) ?: readValueSource(context) } else -> { readValueSource(context) ?: readEnvVar(context, envvar) } } ?: FinalValue.Parsed(emptyList()) } private fun Option.readValueSource(context: Context): FinalValue? { return context.valueSource?.getValues(context, this)?.ifEmpty { null } ?.let { FinalValue.Sourced(it) } } private fun Option.readEnvVar(context: Context, envvar: String?): FinalValue? { val env = inferEnvvar(names, envvar, context.autoEnvvarPrefix) ?: return null return context.readEnvvar(env)?.let { FinalValue.Envvar(env, it) } }
apache-2.0
be633ee9f619debf1423269af7f04db4
36.890805
116
0.670105
4.191354
false
false
false
false
BoD/Ticker
buildSrc/src/main/kotlin/Globals.kt
1
1116
object Versions { // Misc and plugins const val GRADLE = "6.7" const val KOTLIN = "1.4.10" const val BEN_MANES_VERSIONS_PLUGIN = "0.36.0" const val ANDROID_GRADLE_PLUGIN = "4.1.1" // App dependencies const val ANDROIDX_APPCOMPAT = "1.2.0" const val ANDROIDX_EMOJI = "1.1.0" const val ANDROIDX_MULTIDEX = "2.0.1" const val ANDROIDX_CONSTRAINT_LAYOUT = "2.0.4" const val ANDROIDX_CORE_KTX = "1.3.2" const val MATERIAL = "1.2.1" const val RX_JAVA = "2.2.20" const val RX_KOTLIN = "2.4.0" const val KPREFS = "1.6.0" const val LIB_TICKER = "1.5.1" const val SLF4J = "1.7.30" const val KLAXON = "5.4" const val GLIDE = "4.11.0" const val SUNRISE_SUNSET = "1.1.1" const val GRPC = "1.33.1" // Testing dependencies const val ESPRESSO = "3.3.0" const val JUNIT = "4.13.1" } object AppConfig { const val APPLICATION_ID = "org.jraf.android.ticker" const val COMPILE_SDK = 30 const val TARGET_SDK = 30 const val MIN_SDK = 19 var buildNumber: Int = 0 val buildProperties = mutableMapOf<String, String>() }
gpl-3.0
2520ff11361c20a75592b57eeb5be469
28.394737
56
0.61828
2.868895
false
false
false
false
clkim/demoKotlinAndroid2017
app/src/main/kotlin/net/gouline/dagger2demo/activity/AlbumSearchActivity.kt
1
7256
package net.gouline.dagger2demo.activity import android.app.SearchManager import android.content.Context import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.support.v7.widget.LinearLayoutManager import android.support.v7.widget.SearchView import android.util.Log import android.view.Menu import android.view.View import android.view.inputmethod.InputMethodManager import dagger.android.AndroidInjection import io.reactivex.Observable import io.reactivex.android.schedulers.AndroidSchedulers import io.reactivex.disposables.CompositeDisposable import io.reactivex.disposables.Disposable import io.reactivex.schedulers.Schedulers import kotlinx.android.synthetic.main.activity_album_search.* import net.gouline.dagger2demo.DemoApplication import net.gouline.dagger2demo.R import net.gouline.dagger2demo.rest.ITunesService import javax.inject.Inject /** * Activity for search iTunes albums by artist name. * * * Created by mgouline on 23/04/15. * Converted by clkim to Kotlin from original java, * then substantially refactored, e.g. RecyclerView, * hiding soft keyboard, hiding prompt in textview when * album list is not empty, handling orientation change * e.g. caching what has been fetched, using Retrofit 2, * RxJava/RxAndroid and life-cycle handling, Picasso... * * Added basic unit tests for Activity, written in Java * AlbumSearchActivityTest * To run it, connect a device via USB to dev machine, * then in Android Studio > Run AlbumSearchActivityTest * * Acknowledgements: * Mike Gouline's blog on Dagger 2 * Sittiphol Phanvilai’s blog on Retrofit 2 * Dan Lew’s blogs “Grokking RxJava” and on RxAndroid 1.0 * Edwin Jose and NILANCHALA for RecyclerView examples */ class AlbumSearchActivity : AppCompatActivity(), SearchView.OnQueryTextListener { // iTunes api service (Retrofit2, injected in by Dagger2) @Inject lateinit var mITunesService: ITunesService // injected properties using Kotlin Android Extensions // from ids in the layout file activity_album_search.xml // recycler_view: RecyclerView // empty_view: TextView // adapter for recycler view private var mAlbumViewAdapter: AlbumViewAdapter? = null // composite disposable used to dispose rxjava2 disposables (was rxjava1 subscriptions) private var mCompositeDisposable: CompositeDisposable? = null // object with "static" member property used by Log.x companion object { private val TAG = AlbumSearchActivity::class.simpleName } override fun onCreate(savedInstanceState: Bundle?) { // ref https://google.github.io/dagger/android.html // gets a DispatchingAndroidInjector<Activity> gotten from DemoApplication // and passes this Activity to inject() AndroidInjection.inject(this) // do that before calling super.onCreate() super.onCreate(savedInstanceState) setContentView(R.layout.activity_album_search) mAlbumViewAdapter = AlbumViewAdapter() // id of RecyclerView in layout, using Kotlin Android Extensions this.recycler_view.adapter = mAlbumViewAdapter this.recycler_view.layoutManager = LinearLayoutManager(this) // Reference - http://blog.danlew.net/2014/10/08/grokking-rxjava-part-4/ // we follow the pattern in above blog reference, although we have just one disposable // (was subscription in rxjava1) in this demo app mCompositeDisposable = CompositeDisposable() // if there is an Observable cached, use it to display album items from prior api call; // checking for null cache seems ok instead of checking for zero count, e.g. // DemoApplication.albumItemObservableCache?.count()?.blockingGet()?.toLong() ?: 0L // because we're not expiring the cache in the replay() call -- in which case the cache // is not null but is empty and so we don't want to just display cached results if (DemoApplication.albumItemObservableCache != null) { displayCachedResults(DemoApplication.albumItemObservableCache) // hide prompt-textview setPromptVisibility(View.GONE) } } override fun onCreateOptionsMenu(menu: Menu): Boolean { menuInflater.inflate(R.menu.activity_album_search, menu) val searchManager = getSystemService(Context.SEARCH_SERVICE) as SearchManager val searchView = menu.findItem(R.id.menu_item_search).actionView as SearchView searchView.setSearchableInfo(searchManager.getSearchableInfo(componentName)) searchView.setOnQueryTextListener(this) return true } override fun onQueryTextSubmit(term: String): Boolean { if (term.isNotEmpty()) { fetchResults(term) // hide soft keyboard (getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager) .hideSoftInputFromWindow(this.recycler_view.applicationWindowToken, 0) } return true } override fun onQueryTextChange(s: String): Boolean { // show prompt-textview if search term is blanked out and no album items are displayed if (s.isNotEmpty()) setPromptVisibility(View.GONE) else if (s.isEmpty() && mAlbumViewAdapter?.itemCount == 0) setPromptVisibility(View.VISIBLE) return false } override fun onDestroy() { super.onDestroy() mCompositeDisposable?.dispose() } private fun fetchResults(term: String) { // clear the items in recyclerview adapter mAlbumViewAdapter?.clear() // cache newly fetched Observable DemoApplication.albumItemObservableCache = // using the injected Retrofit service mITunesService.search(term, "album") .subscribeOn(Schedulers.io()) .flatMapIterable { it.results } .map { AlbumItem(it.collectionName, it.artworkUrl100) } .replay().autoConnect() // equivalent to operator cache() but seems preferred, ref: https://speakerdeck.com/dlew/common-rxjava-mistakes displayCachedResults(DemoApplication.albumItemObservableCache) } private fun displayCachedResults(cache: Observable<AlbumItem>) { // subscribe to the Observable so as to display the album items val disposable: Disposable = cache .observeOn(AndroidSchedulers.mainThread()) .subscribe( { mAlbumViewAdapter?.addAlbumItem(it) mAlbumViewAdapter?.notifyItemInserted( mAlbumViewAdapter?.itemCount?.minus(1) ?: 0) }, { Log.w(TAG, "Retrieve albums failed\n" + it.message, it) }) // add the disposable to the CompositeDisposable // so we can do lifecycle dispose mCompositeDisposable?.add(disposable) } private fun setPromptVisibility(visibility: Int) { // using id of TextView - Kotlin Android Extensions // this contains the prompt to search for artists' albums this.empty_view.visibility = visibility } }
mit
452bb5c3ffdf4ddb5ac565a7b8eddd6e
40.417143
159
0.693709
4.910569
false
false
false
false
LorittaBot/Loritta
web/showtime/showtime-frontend/src/jsMain/kotlin/net/perfectdreams/loritta/cinnamon/showtime/frontend/views/HomeView.kt
1
1665
package net.perfectdreams.loritta.cinnamon.showtime.frontend.views import kotlinx.coroutines.delay import net.perfectdreams.dokyo.elements.HomeElements import net.perfectdreams.loritta.cinnamon.showtime.frontend.ShowtimeFrontend import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.get import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.offset import net.perfectdreams.loritta.cinnamon.showtime.frontend.utils.extensions.onClick import org.w3c.dom.HTMLDivElement import org.w3c.dom.HTMLImageElement class HomeView(val showtime: ShowtimeFrontend) : DokyoView() { override suspend fun onLoad() { val blinkingPose = HomeElements.blinkingPose.get<HTMLImageElement>() val blushingPose = HomeElements.blushingPose.get<HTMLImageElement>() showtime.launch { while (true) { blinkingPose.style.visibility = "" delay(7000) blushingPose.style.visibility = "" blinkingPose.style.visibility = "visible" delay(140) } } val selfie = HomeElements.lorittaSelfie.get<HTMLDivElement>() selfie.onClick { val offset = selfie.offset() val x = (it.asDynamic().pageX - offset.left) / blushingPose.offsetWidth // Se usar "selfie.offsetWidth", sempre irá retornar 0 pois as imagens são absolutas val y = (it.asDynamic().pageY - offset.top) / selfie.offsetHeight // debug("x: $x; y: $y") if (x in 0.22..0.32 && y in 0.29..0.39) { blushingPose.style.visibility = "visible" } } } }
agpl-3.0
6851519272797727859e3a98f0bfd43a
40.6
168
0.669874
4.026634
false
false
false
false
LorittaBot/Loritta
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/commands/vanilla/fun/FaustaoCommand.kt
1
2774
package net.perfectdreams.loritta.morenitta.commands.vanilla.`fun` import club.minnced.discord.webhook.send.WebhookMessageBuilder import net.perfectdreams.loritta.morenitta.LorittaBot import net.perfectdreams.loritta.morenitta.commands.AbstractCommand import net.perfectdreams.loritta.morenitta.commands.CommandContext import net.perfectdreams.loritta.morenitta.utils.WebhookUtils import net.perfectdreams.loritta.common.locale.BaseLocale import net.perfectdreams.loritta.common.locale.LocaleKeyData import net.perfectdreams.loritta.morenitta.utils.OutdatedCommandUtils class FaustaoCommand(loritta: LorittaBot) : AbstractCommand(loritta, "faustão", listOf("faustao"), net.perfectdreams.loritta.common.commands.CommandCategory.FUN) { private val frases = listOf( "Que isso bicho, ó u cara lá ó", "Vamos ver as vídeo cassetadas!", "Voltamos já com vídeo cassetadas!", "ERRRROOOOOOOOOUUUUUUUU!!!!", "E agora, pra desligar essa merda aí, meu. Porra ligou, agora desliga! Tá pegando fogo, bicho!", "TÁ PEGANDO FOGO, BICHO!", "OLOCO!", "Essa fera ai, bicho!", "Essa fera ai, meu!", "Você destruiu o meu ovo! \uD83C\uDF73", "Ih Serjão, sujou! \uD83C\uDFC3\uD83D\uDCA8", "ERROU! ⚠", "Você vai morrer ⚰", "Olha o tamanho da criança", "Oito e sete", "Ô loco meu!", "É brincadera, bicho!", "Se vira nos 30!", "Quem sabe faz ao vivo!", "A TV é chata no domingo, é para quem não tem dinheiro nem o que fazer. Eu trabalho no domingo por isso. O domingo é chato. Para quem pode viajar e passear, o domingo é maravilhoso.", "Logo após os reclames do plim-plim!", "Olha só o que faz a maldita manguaça, bicho!", "{user} é bom tanto no pessoal quanto no profissional.", "Essa fera {user} aqui no domingão!") private val avatars = listOf( "http://i.imgur.com/PS61w6I.png", "http://i.imgur.com/ofr6Tkj.png", "http://i.imgur.com/nABrbqD.png", "http://i.imgur.com/igpGeyg.png", "http://i.imgur.com/db2TFRm.png", "http://i.imgur.com/RAPYIU9.png", "http://i.imgur.com/rVmgwZC.png", "http://i.imgur.com/z7Ec5I3.png") override fun getDescriptionKey() = LocaleKeyData("commands.command.faustao.description") override suspend fun run(context: CommandContext,locale: BaseLocale) { OutdatedCommandUtils.sendOutdatedCommandMessage(context, locale, "summon faustao") val temmie = WebhookUtils.getOrCreateWebhook(loritta, context.event.channel, "Faustão") val mensagem = frases[LorittaBot.RANDOM.nextInt(frases.size)].replace("{user}", context.userHandle.asMention) context.sendMessage(temmie, WebhookMessageBuilder() .setUsername("Faustão") .setContent(mensagem) .setAvatarUrl(avatars[LorittaBot.RANDOM.nextInt(avatars.size)]) .build()) } }
agpl-3.0
f1a08970b1b1f8b3b01e81410f3bcc32
41.859375
186
0.735959
2.826804
false
false
false
false
proxer/ProxerAndroid
src/main/kotlin/me/proxer/app/base/BaseActivity.kt
1
4534
package me.proxer.app.base import android.os.Bundle import android.view.MenuItem import android.view.View import android.view.ViewGroup import android.widget.TextView import androidx.annotation.StyleRes import androidx.appcompat.app.AppCompatActivity import androidx.core.app.ActivityCompat import androidx.core.os.bundleOf import com.google.android.material.snackbar.Snackbar import com.rubengees.rxbus.RxBus import com.uber.autodispose.android.lifecycle.scope import com.uber.autodispose.autoDisposable import kotterknife.bindView import me.proxer.app.R import me.proxer.app.util.ErrorUtils import me.proxer.app.util.compat.TaskDescriptionCompat import me.proxer.app.util.data.PreferenceHelper import me.proxer.app.util.data.StorageHelper import me.proxer.app.util.extension.androidUri import me.proxer.app.util.extension.fallbackHandleLink import me.proxer.app.util.extension.recursiveChildren import me.proxer.app.util.extension.safeInject import me.zhanghai.android.customtabshelper.CustomTabsHelperFragment import okhttp3.HttpUrl import kotlin.properties.Delegates /** * @author Ruben Gees */ @Suppress("UnnecessaryAbstractClass") abstract class BaseActivity : AppCompatActivity(), CustomTabsAware { private companion object { private const val STATE = "activity_state" } protected open val theme @StyleRes get() = preferenceHelper.themeContainer.theme.main protected open val root: ViewGroup by bindView(R.id.root) protected val bus by safeInject<RxBus>() protected val storageHelper by safeInject<StorageHelper>() protected val preferenceHelper by safeInject<PreferenceHelper>() private var customTabsHelper by Delegates.notNull<CustomTabsHelperFragment>() override fun onCreate(savedInstanceState: Bundle?) { // This needs to be called before super.onCreate(), because otherwise Fragments might not see the // restored state in time. savedInstanceState?.getBundle(STATE)?.let { state -> intent.putExtras(state) } getTheme().applyStyle(theme, true) TaskDescriptionCompat.setTaskDescription(this, preferenceHelper.themeContainer.theme.primaryColor(this)) super.onCreate(savedInstanceState) customTabsHelper = CustomTabsHelperFragment.attachTo(this) preferenceHelper.themeObservable .autoDisposable(this.scope()) .subscribe { ActivityCompat.recreate(this) } } override fun onOptionsItemSelected(item: MenuItem): Boolean { when (item.itemId) { android.R.id.home -> onBackPressed() } return super.onOptionsItemSelected(item) } override fun onSaveInstanceState(outState: Bundle) { super.onSaveInstanceState(outState) intent.extras?.let { state -> outState.putBundle(STATE, state) } } override fun onBackPressed() { // Workaround for memory leak on Android 10: https://twitter.com/Piwai/status/1169274624749658112 if (isTaskRoot && supportFragmentManager.backStackEntryCount == 0) { finishAfterTransition() } else { super.onBackPressed() } } override fun setLikelyUrl(url: HttpUrl): Boolean { return customTabsHelper.mayLaunchUrl(url.androidUri(), bundleOf(), emptyList()) } override fun showPage(url: HttpUrl, forceBrowser: Boolean, skipCheck: Boolean) { customTabsHelper.fallbackHandleLink(this, url, forceBrowser, skipCheck) } fun snackbar( message: CharSequence, duration: Int = Snackbar.LENGTH_LONG, actionMessage: Int = ErrorUtils.ErrorAction.ACTION_MESSAGE_DEFAULT, actionCallback: View.OnClickListener? = null, maxLines: Int = -1 ) { Snackbar.make(root, message, duration).apply { when (actionMessage) { ErrorUtils.ErrorAction.ACTION_MESSAGE_DEFAULT -> { val multilineActionMessage = getString(R.string.error_action_retry).replace(" ", "\n") setAction(multilineActionMessage, actionCallback) } ErrorUtils.ErrorAction.ACTION_MESSAGE_HIDE -> setAction(null, null) else -> setAction(actionMessage, actionCallback) } if (maxLines >= 0) { (view as ViewGroup).recursiveChildren .filterIsInstance(TextView::class.java) .forEach { it.maxLines = maxLines } } show() } } }
gpl-3.0
b541a5b781277d97fc2a6dbcd688f404
33.876923
112
0.694971
4.7827
false
false
false
false
ohmae/CdsExtractor
src/main/java/net/mm2d/android/upnp/cds/chapter/PanasonicFetcherFactory.kt
2
3565
/* * Copyright (c) 2017 大前良介 (OHMAE Ryosuke) * * This software is released under the MIT License. * http://opensource.org/licenses/MIT */ package net.mm2d.android.upnp.cds.chapter import io.reactivex.Single import io.reactivex.SingleEmitter import io.reactivex.schedulers.Schedulers import net.mm2d.android.upnp.cds.CdsObject import net.mm2d.upnp.HttpClient import net.mm2d.upnp.util.XmlUtils import net.mm2d.upnp.util.forEachElement import org.w3c.dom.Element import org.w3c.dom.Node import org.xml.sax.SAXException import java.io.IOException import java.net.URL import java.util.* import java.util.concurrent.TimeUnit import javax.xml.parsers.ParserConfigurationException /** * @author [大前良介 (OHMAE Ryosuke)](mailto:[email protected]) */ internal class PanasonicFetcherFactory : FetcherFactory { override fun create(cdsObject: CdsObject): Single<List<Int>>? { val url = cdsObject.getValue(CHAPTER_INFO) if (url.isNullOrEmpty()) { return null } return Single.create { emitter: SingleEmitter<List<Int>> -> try { val xml = HttpClient(false).downloadString(URL(url)) emitter.onSuccess(parseChapterInfo(xml)) } catch (ignored: Exception) { emitter.onSuccess(emptyList()) } }.subscribeOn(Schedulers.io()) } @Throws(ParserConfigurationException::class, SAXException::class, IOException::class) private fun parseChapterInfo(xml: String): List<Int> { if (xml.isEmpty()) { return emptyList() } val root = XmlUtils.newDocument(false, xml).documentElement if (root == null || root.nodeName != ROOT_NODE) { return emptyList() } val content = root.findChildElementByNodeName(LIST_NODE) ?: return emptyList() val result = ArrayList<Int>() content.firstChild.forEachElement { element -> if (element.nodeName == ITEM_NODE) { element.findChildElementByNodeName(TIME_NODE) ?.textContent ?.parseTimeNode() ?.let { result.add(it) } } } return result } private fun Node.findChildElementByNodeName(localName: String): Element? { firstChild?.forEachElement { if (localName == it.nodeName) { return it } } return null } /** * 時間を表現する文字列をミリ秒に変換する。 * * フォーマット:00:00:00.000 * * @receiver 時間文字列 * @return ミリ秒 */ private fun String?.parseTimeNode(): Int? { if (this.isNullOrEmpty()) return null val times = this.split(':') if (times.size != 3) return null val hours = times[0].toIntOrNull() ?: return null val minutes = times[1].toIntOrNull() ?: return null val seconds = times[2].toFloatOrNull() ?: return null return (hours * ONE_HOUR + minutes * ONE_MINUTE + seconds * ONE_SECOND).toInt() } companion object { private const val CHAPTER_INFO = "res@pxn:ChapterList" private const val ROOT_NODE = "result" private const val LIST_NODE = "chapterList" private const val ITEM_NODE = "item" private const val TIME_NODE = "timeCode" private val ONE_SECOND = TimeUnit.SECONDS.toMillis(1) private val ONE_MINUTE = TimeUnit.MINUTES.toMillis(1) private val ONE_HOUR = TimeUnit.HOURS.toMillis(1) } }
mit
3c8e02522b2f0d27fbbb4fec95f92b89
32.451923
89
0.62288
4.05951
false
false
false
false
gatheringhallstudios/MHGenDatabase
app/src/main/java/com/ghstudios/android/data/classes/MonsterToQuest.kt
1
291
package com.ghstudios.android.data.classes /* * Class for MonsterToQuest */ class MonsterToQuest { var id: Long = -1 var monster: Monster? = null var quest: Quest? = null var habitat: Habitat? = null var isUnstable: Boolean = false var isHyper: Boolean = false }
mit
f0df2d824e910fb8d7f0a74056eba213
19.785714
42
0.666667
3.592593
false
false
false
false
nsk-mironov/smuggler
smuggler-compiler/src/main/java/com/joom/smuggler/compiler/common/AccessExtensions.kt
1
817
package com.joom.smuggler.compiler.common import org.objectweb.asm.Opcodes internal val Int.isPublic: Boolean get() = this and Opcodes.ACC_PUBLIC != 0 internal val Int.isPrivate: Boolean get() = this and Opcodes.ACC_PRIVATE != 0 internal val Int.isProtected: Boolean get() = this and Opcodes.ACC_PROTECTED != 0 internal val Int.isInterface: Boolean get() = this and Opcodes.ACC_INTERFACE != 0 internal val Int.isAnnotation: Boolean get() = this and Opcodes.ACC_ANNOTATION != 0 internal val Int.isAbstract: Boolean get() = this and Opcodes.ACC_ABSTRACT != 0 internal val Int.isSynthetic: Boolean get() = this and Opcodes.ACC_SYNTHETIC != 0 internal val Int.isStatic: Boolean get() = this and Opcodes.ACC_STATIC != 0 internal val Int.isFinal: Boolean get() = this and Opcodes.ACC_FINAL != 0
mit
b9364ed256780033fdb914e8d9f689da
26.233333
46
0.731946
3.713636
false
false
false
false
samuelclay/NewsBlur
clients/android/NewsBlur/src/com/newsblur/widget/WidgetRemoteViewsFactory.kt
1
9394
package com.newsblur.widget import android.appwidget.AppWidgetManager import android.content.Context import android.content.Intent import android.graphics.Color import android.os.Bundle import android.os.CancellationSignal import android.text.TextUtils import android.view.View import android.widget.RemoteViews import android.widget.RemoteViewsService.RemoteViewsFactory import com.newsblur.R import com.newsblur.database.BlurDatabaseHelper import com.newsblur.di.IconLoader import com.newsblur.di.ThumbnailLoader import com.newsblur.domain.Feed import com.newsblur.domain.Story import com.newsblur.network.APIManager import com.newsblur.util.* import dagger.hilt.EntryPoint import dagger.hilt.InstallIn import dagger.hilt.android.EntryPointAccessors import dagger.hilt.components.SingletonComponent import java.util.* import kotlin.math.min class WidgetRemoteViewsFactory(context: Context, intent: Intent) : RemoteViewsFactory { private val context: Context private val apiManager: APIManager private val dbHelper: BlurDatabaseHelper private val iconLoader: ImageLoader private val thumbnailLoader: ImageLoader private var fs: FeedSet? = null private val appWidgetId: Int private var dataCompleted = false private val storyItems: MutableList<Story> = ArrayList() private val cancellationSignal = CancellationSignal() init { Log.d(TAG, "Constructor") val hiltEntryPoint = EntryPointAccessors .fromApplication(context.applicationContext, WidgetRemoteViewsFactoryEntryPoint::class.java) this.context = context this.apiManager = hiltEntryPoint.apiManager() this.dbHelper = hiltEntryPoint.dbHelper() this.iconLoader = hiltEntryPoint.iconLoader() this.thumbnailLoader = hiltEntryPoint.thumbnailLoader() appWidgetId = intent.getIntExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, AppWidgetManager.INVALID_APPWIDGET_ID) } /** * The system calls onCreate() when creating your factory for the first time. * This is where you set up any connections and/or cursors to your data source. * * * Heavy lifting, * for example downloading or creating content etc, should be deferred to onDataSetChanged() * or getViewAt(). Taking more than 20 seconds in this call will result in an ANR. */ override fun onCreate() { Log.d(TAG, "onCreate") WidgetUtils.enableWidgetUpdate(context) } /** * Allowed to run synchronous calls */ override fun getViewAt(position: Int): RemoteViews { Log.d(TAG, "getViewAt $position") val story = storyItems[position] val rv = WidgetRemoteViews(context.packageName, R.layout.view_widget_story_item) rv.setTextViewText(R.id.story_item_title, story.title) rv.setTextViewText(R.id.story_item_content, story.shortContent) rv.setTextViewText(R.id.story_item_author, story.authors) rv.setTextViewText(R.id.story_item_feedtitle, story.extern_feedTitle) val time: CharSequence = StoryUtils.formatShortDate(context, story.timestamp) rv.setTextViewText(R.id.story_item_date, time) // image dimensions same as R.layout.view_widget_story_item iconLoader.displayWidgetImage(story.extern_faviconUrl, R.id.story_item_feedicon, UIUtils.dp2px(context, 19), rv) if (PrefsUtils.getThumbnailStyle(context) != ThumbnailStyle.OFF && !TextUtils.isEmpty(story.thumbnailUrl)) { thumbnailLoader.displayWidgetImage(story.thumbnailUrl, R.id.story_item_thumbnail, UIUtils.dp2px(context, 64), rv) } else { rv.setViewVisibility(R.id.story_item_thumbnail, View.GONE) } rv.setViewBackgroundColor(R.id.story_item_favicon_borderbar_1, UIUtils.decodeColourValue(story.extern_feedColor, Color.GRAY)) rv.setViewBackgroundColor(R.id.story_item_favicon_borderbar_2, UIUtils.decodeColourValue(story.extern_feedFade, Color.LTGRAY)) // set fill-intent which is used to fill in the pending intent template // set on the collection view in WidgetProvider val extras = Bundle() extras.putString(WidgetUtils.EXTRA_ITEM_ID, story.storyHash) val fillInIntent = Intent() fillInIntent.putExtras(extras) rv.setOnClickFillInIntent(R.id.view_widget_item, fillInIntent) return rv } /** * This allows for the use of a custom loading view which appears between the time that * [.getViewAt] is called and returns. If null is returned, a default loading * view will be used. * * @return The RemoteViews representing the desired loading view. */ override fun getLoadingView(): RemoteViews? = null /** * @return The number of types of Views that will be returned by this factory. */ override fun getViewTypeCount(): Int = 1 /** * @param position The position of the item within the data set whose row id we want. * @return The id of the item at the specified position. */ override fun getItemId(position: Int): Long = storyItems[position].hashCode().toLong() /** * @return True if the same id always refers to the same object. */ override fun hasStableIds(): Boolean = true override fun onDataSetChanged() { Log.d(TAG, "onDataSetChanged") // if user logged out don't try to update widget if (!WidgetUtils.isLoggedIn(context)) { Log.d(TAG, "onDataSetChanged - not logged in") return } if (dataCompleted) { // we have all the stories data, just let the widget redraw Log.d(TAG, "onDataSetChanged - redraw widget") dataCompleted = false } else { setFeedSet() if (fs == null) { Log.d(TAG, "onDataSetChanged - null feed set. Show empty view") setStories(arrayOf(), HashMap(0)) return } Log.d(TAG, "onDataSetChanged - fetch stories") val response = apiManager.getStories(fs, 1, StoryOrder.NEWEST, ReadFilter.ALL) if (response?.stories == null) { Log.d(TAG, "Error fetching widget stories") } else { Log.d(TAG, "Fetched widget stories") processStories(response.stories) dbHelper.insertStories(response, true) } } } /** * Called when the last RemoteViewsAdapter that is associated with this factory is * unbound. */ override fun onDestroy() { Log.d(TAG, "onDestroy") cancellationSignal.cancel() WidgetUtils.disableWidgetUpdate(context) PrefsUtils.removeWidgetData(context) } /** * @return Count of items. */ override fun getCount(): Int = min(storyItems.size, WidgetUtils.STORIES_LIMIT) private fun processStories(stories: Array<Story>) { Log.d(TAG, "processStories") val feedMap = HashMap<String, Feed>() NBScope.executeAsyncTask( doInBackground = { dbHelper.getFeedsCursor(cancellationSignal) }, onPostExecute = { while (it != null && it.moveToNext()) { val feed = Feed.fromCursor(it) if (feed.active) { feedMap[feed.feedId] = feed } } setStories(stories, feedMap) } ) } private fun setStories(stories: Array<Story>, feedMap: HashMap<String, Feed>) { Log.d(TAG, "setStories") for (story in stories) { val storyFeed = feedMap[story.feedId] storyFeed?.let { bindStoryValues(story, it) } } storyItems.clear() storyItems.addAll(mutableListOf(*stories)) // we have the data, notify data set changed dataCompleted = true invalidate() } private fun bindStoryValues(story: Story, feed: Feed) { story.thumbnailUrl = Story.guessStoryThumbnailURL(story) story.extern_faviconBorderColor = feed.faviconBorder story.extern_faviconUrl = feed.faviconUrl story.extern_feedTitle = feed.title story.extern_feedFade = feed.faviconFade story.extern_feedColor = feed.faviconColor } private fun invalidate() { Log.d(TAG, "Invalidate app widget with id: $appWidgetId") val appWidgetManager = AppWidgetManager.getInstance(context) appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetId, R.id.widget_list) } private fun setFeedSet() { val feedIds = PrefsUtils.getWidgetFeedIds(context) fs = if (feedIds == null || feedIds.isNotEmpty()) { FeedSet.widgetFeeds(feedIds) } else { // no feeds selected. Widget will show tap to config view null } } companion object { private const val TAG = "WidgetRemoteViewsFactory" } @EntryPoint @InstallIn(SingletonComponent::class) interface WidgetRemoteViewsFactoryEntryPoint { fun apiManager(): APIManager fun dbHelper(): BlurDatabaseHelper @IconLoader fun iconLoader(): ImageLoader @ThumbnailLoader fun thumbnailLoader(): ImageLoader } }
mit
2b55da0ace2716bf83e239d2ad4e59c3
36.883065
134
0.655099
4.593643
false
false
false
false
Ribesg/Pure
src/main/kotlin/fr/ribesg/minecraft/pure/util/FileUtils.kt
1
8904
package fr.ribesg.minecraft.pure.util import com.tonicsystems.jarjar.Main import fr.ribesg.minecraft.pure.common.Log import fr.ribesg.minecraft.pure.common.MCVersion import fr.ribesg.minecraft.pure.use import java.io.File import java.io.FileOutputStream import java.io.IOException import java.net.Proxy import java.net.URL import java.nio.channels.Channels import java.nio.file.Files import java.nio.file.Path import java.nio.file.Paths import java.nio.file.StandardCopyOption import java.util.zip.ZipEntry import java.util.zip.ZipFile import java.util.zip.ZipInputStream import java.util.zip.ZipOutputStream /** * Used to download things. * * @author Ribesg */ object FileUtils { private val MAX_DOWNLOAD_ATTEMPTS = 5 /** * Proxy used for downloads */ var proxy: Proxy? = null /** * Downloads a file. * * @param destFolder the folder in which the file will be saved * @param srcUrl the URL to the file to download * @param fileName the final name of the saved file * @param wantedHash the required hash for the file or null if there is none * * @return the path to the downloaded file */ fun download(destFolder: Path, srcUrl: URL, fileName: String, wantedHash: String?): Path { if ((!Files.exists(destFolder) || !Files.isDirectory(destFolder)) && !destFolder.toFile().mkdirs()) { throw IOException("Folder " + destFolder.toString() + " doesn't exist and cannot be created") } val finalFile = File(destFolder.toFile(), fileName) var attempt = 1 while (true) { try { use( Channels.newChannel( if (proxy == null) { srcUrl.openStream() } else { srcUrl.openConnection(this.proxy!!).inputStream } ), FileOutputStream(finalFile) ) { src, dst -> Log.debug("Downloading $srcUrl ...") dst.channel.transferFrom(src, 0, Long.MAX_VALUE) if (wantedHash != null) { Log.debug("Done! Checking hash...") val hash = HashUtils.hashSha256(finalFile.toPath()) if (hash.equals(wantedHash)) { Log.debug("The downloaded file is correct!") } else { Log.warn("The downloaded file is incorrect!") throw IOException( "Download file hash doesn't match awaited hash\nAwaited: $wantedHash\nReceived: $hash" ) } } else { Log.debug("Done!") } } break } catch(e: IOException) { Log.warn("Attempt n°$attempt failed!") if (attempt == FileUtils.MAX_DOWNLOAD_ATTEMPTS) { throw IOException("Failed to download file", e) } else { Log.debug("Error was: ", e) } } attempt++; } return finalFile.toPath() } /** * Relocates classes in a jar file, building a new modified jar. * * @param inputJar input jar file * @param outputJar output jar file * @param version Minecraft version of those jar files * @param checkHash if we check for file hashes or not * * @throws IOException if anything goes wrong */ fun relocateJarContent(inputJar: Path, outputJar: Path, version: MCVersion, checkHash: Boolean) { val prefix = version.name().toLowerCase() val rulesFilePath = inputJar.toAbsolutePath().toString() + ".tmp" // Create JarJar rules file val rulesFile = Paths.get(rulesFilePath).toFile() if (rulesFile.exists()) { if (!rulesFile.delete()) { throw IOException("Failed to remove old rules file $rulesFilePath") } } if (!rulesFile.createNewFile()) { throw IOException("Failed to create rules file $rulesFilePath") } // Generate and write rules use ( ZipFile(inputJar.toFile()), Files.newBufferedWriter(rulesFile.toPath()) ) { zipFile, writer -> val enumeration = zipFile.entries() var entry: ZipEntry var entryName: String while (enumeration.hasMoreElements()) { entry = enumeration.nextElement() entryName = entry.name if (!entryName.contains("META-INF")) { if (entry.isDirectory) { writer.write("rule " + entryName.replace('/', '.') + "* $prefix.@0\n") } else if (!entryName.contains("/") || entryName.startsWith("net/minecraft/server")) { if (entryName.endsWith(".class")) { val filteredName = entryName.replace(".class", "").replace('/', '.') if (filteredName.contains(".")) { writer.write("rule $filteredName $prefix.@0\n") } else { writer.write("rule $filteredName $prefix.net.minecraft.server.@0\n") } } } } } } // Execute JarJar try { Log.debug("Executing JarJar...") Main.main(arrayOf( "process", rulesFilePath, inputJar.toString(), outputJar.toString() )) Log.debug("Done!") // Remove junk in final jar FileUtils.removePrefixedBy( outputJar, "META-INF", // All "null" // Alpha 0.2.8 ) if (checkHash) { val wantedHash = version.getRemappedHash() val hash = HashUtils.hashSha256(outputJar) if (hash.equals(wantedHash)) { Log.debug("The remapped file is correct!") } else { throw IOException( "Remapped file hash doesn't match awaited hash\nAwaited: $wantedHash\nReceived: $hash" ) } } } catch (e: Exception) { throw IOException("Failed to execute JarJar", e) } finally { if (!rulesFile.delete()) { Log.warn("Failed to remove rules file after execution") } } } /** * Removes any file in the provided zip file whose path starts with * one of the provided prefixes. * * @param prefixes the prefixes * @param zip the file * * @throws IOException if anything goes wrong */ fun removePrefixedBy(zip: Path, vararg prefixes: String) { if (prefixes.size() == 0) { return // Nothing to do! } // Rename original file to tmp file val tmp = Paths.get(zip.toAbsolutePath().toString() + ".tmp") Files.move(zip, tmp, StandardCopyOption.REPLACE_EXISTING) // Rebuild original file from tmp file while filtering content try { use( ZipInputStream(Files.newInputStream(tmp)), ZipOutputStream(Files.newOutputStream(zip)) ) { input, output -> val buffer = ByteArray(1024) var read: Int var ignore: Boolean var entry: ZipEntry? = input.nextEntry while (entry != null) { val entryName = entry.name ignore = false for (prefix in prefixes) { if (entryName.startsWith(prefix)) { ignore = true break } } if (!ignore) { // Create entry in new file output.putNextEntry(ZipEntry(entry)) // Copy content of entry to new file read = input.read(buffer) while (read > 0) { output.write(buffer, 0, read) read = input.read(buffer) } } entry = input.nextEntry } } } finally { if (!tmp.toFile().delete()) { Log.warn("Failed to remove tmp file after execution") } } } }
gpl-3.0
261e1fa7f6487ab1c68b77689bc256b9
35.191057
118
0.491969
5.096165
false
false
false
false
mozilla-mobile/focus-android
app/src/main/java/org/mozilla/focus/state/AppState.kt
1
3784
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.focus.state import android.os.Bundle import mozilla.components.feature.top.sites.TopSite import mozilla.components.lib.state.State import org.mozilla.focus.settings.permissions.permissionoptions.SitePermission import java.util.UUID /** * Global state of the application. * * @property screen The currently displayed screen. * @property topSites The list of [TopSite] to display on the Home screen. * @property sitePermissionOptionChange A flag which reflects the state of site permission rules, * whether they have been updated or not * @property secretSettingsEnabled A flag which reflects the state of debug secret settings * @property showEraseTabsCfr A flag which reflects the state erase tabs CFR * @property showStartBrowsingTabsCfr A flag which reflects the state of start browsing CFR * @property showSearchWidgetSnackbar A flag which reflects the state of search widget snackbar */ data class AppState( val screen: Screen, val topSites: List<TopSite> = emptyList(), val sitePermissionOptionChange: Boolean = false, val secretSettingsEnabled: Boolean = false, val showEraseTabsCfr: Boolean = false, val showSearchWidgetSnackbar: Boolean = false, val showTrackingProtectionCfrForTab: Map<String, Boolean> = emptyMap(), val showStartBrowsingTabsCfr: Boolean = false, ) : State /** * A group of screens that the app can display. * * @property id A unique ID for identifying a screen. Only if this ID changes the screen is * considered a new screen that requires a navigation (as opposed to the state of the screen * changing). */ sealed class Screen { open val id = UUID.randomUUID().toString() /** * First run onboarding. */ object FirstRun : Screen() /** * Second screen from new onboarding flow. */ object OnboardingSecondScreen : Screen() /** * The home screen. */ object Home : Screen() /** * Browser screen. * * @property tabId The ID of the displayed tab. * @property showTabs Whether to show the tabs tray. */ data class Browser( val tabId: String, val showTabs: Boolean, ) : Screen() { // Whenever the showTabs property changes we want to treat this as a new screen and force // a navigation. override val id: String = "${super.id}_$showTabs}" } /** * Editing the URL of a tab. */ data class EditUrl( val tabId: String, ) : Screen() /** * The application is locked (and requires unlocking). * * @param bundle it is used for app navigation. If the user can unlock with success he should * be redirected to a certain screen.It comes from the external intent. */ data class Locked(val bundle: Bundle? = null) : Screen() data class SitePermissionOptionsScreen(val sitePermission: SitePermission) : Screen() data class Settings( val page: Page = Page.Start, ) : Screen() { enum class Page { Start, General, Privacy, Search, Advanced, Mozilla, About, Locale, PrivacyExceptions, PrivacyExceptionsRemove, CookieBanner, SitePermissions, Studies, SecretSettings, SearchList, SearchRemove, SearchAdd, SearchAutocomplete, SearchAutocompleteList, SearchAutocompleteAdd, SearchAutocompleteRemove, } } }
mpl-2.0
25f7933e8c165b94ec5c97887f732844
30.272727
97
0.655391
4.570048
false
false
false
false
spark/photon-tinker-android
cloudsdk/src/main/java/io/particle/android/sdk/cloud/ParticleDevice.kt
1
28054
package io.particle.android.sdk.cloud import android.annotation.SuppressLint import android.os.Parcel import android.os.Parcelable import androidx.annotation.WorkerThread import io.particle.android.sdk.cloud.Responses.ReadDoubleVariableResponse import io.particle.android.sdk.cloud.Responses.ReadIntVariableResponse import io.particle.android.sdk.cloud.Responses.ReadObjectVariableResponse import io.particle.android.sdk.cloud.Responses.ReadStringVariableResponse import io.particle.android.sdk.cloud.Responses.ReadVariableResponse import io.particle.android.sdk.cloud.exceptions.ParticleCloudException import io.particle.android.sdk.cloud.models.DeviceStateChange import io.particle.android.sdk.utils.Preconditions import io.particle.android.sdk.utils.Py.list import io.particle.android.sdk.utils.TLog import io.particle.android.sdk.utils.buildIntValueMap import io.particle.android.sdk.utils.join import okio.buffer import okio.source import org.greenrobot.eventbus.EventBus import org.json.JSONException import org.json.JSONObject import retrofit.RetrofitError import retrofit.mime.TypedByteArray import retrofit.mime.TypedFile import java.io.File import java.io.IOException import java.io.InputStream import java.util.* import java.util.concurrent.CopyOnWriteArrayList // don't warn about public APIs not being referenced inside this module, or about // the _default locale_ in a bunch of backend code @SuppressLint("DefaultLocale") class ParticleDevice internal constructor( private val mainApi: ApiDefs.CloudApi, val cloud: ParticleCloud, @field:Volatile internal var deviceState: DeviceState ) : Parcelable { private val subscriptions = CopyOnWriteArrayList<Long>() @Volatile var isFlashing = false private set /** * Device ID string */ val id: String get() = deviceState.deviceId /** * Device name. Device can be renamed in the cloud via #setName(String) */ /** * Rename the device in the cloud. If renaming fails name will stay the same. */ var name: String get() { return deviceState.name ?: "" } @WorkerThread @Throws(ParticleCloudException::class) set(newName) { cloud.rename(this.deviceState.deviceId, newName) } /** * Is device connected to the cloud? */ val isConnected: Boolean get() { return deviceState.isConnected ?: false } /** * Get an immutable set of all the function names exposed by device */ // no need for a defensive copy, this is an immutable set val functions: Set<String> get() { return deviceState.functions } /** * Get an immutable map of exposed variables on device with their respective types. */ // no need for a defensive copy, this is an immutable set val variables: Map<String, VariableType> get() { return deviceState.variables } /** Device firmware version string */ val version: String? get() { return deviceState.systemFirmwareVersion } val deviceType: ParticleDeviceType? get() { return deviceState.deviceType } val platformID: Int? get() { return deviceState.platformId } val productID: Int? get() { return deviceState.productId } val isCellular: Boolean? get() { return deviceState.cellular } val imei: String? get() { return deviceState.imei } val lastIccid: String? get() { return deviceState.lastIccid } val iccid: String? get() { return deviceState.iccid } val currentBuild: String? get() { return deviceState.currentBuild } val defaultBuild: String? get() { return deviceState.defaultBuild } val ipAddress: String? get() { return deviceState.ipAddress } val lastAppName: String? get() { return deviceState.lastAppName } val status: String? get() { return deviceState.status } val lastHeard: Date? get() { return deviceState.lastHeard } val serialNumber: String? get() { return deviceState.serialNumber } val mobileSecret: String? get() { return deviceState.mobileSecret } var notes: String? get() { return deviceState.notes } @WorkerThread @Throws(ParticleCloudException::class) set(newNote) { try { mainApi.setDeviceNote(id, newNote ?: "") } catch (e: RetrofitError) { throw ParticleCloudException(e) } } val isRunningTinker: Boolean get() { val lowercaseFunctions = list<String>() for (func in deviceState.functions) { lowercaseFunctions.add(func.toLowerCase()) } val tinkerFunctions = list("analogread", "analogwrite", "digitalread", "digitalwrite") return isConnected && lowercaseFunctions.containsAll(tinkerFunctions) } // included for Java backwards compat: the method was named getID(), // and the new Kotlin property generates a method named getId() @Deprecated( message = "Use #id property / #getId() instead", replaceWith = ReplaceWith( "getId()", "io.particle.android.sdk.cloud.ParticleDevice" ) ) fun getID(): String { return id } enum class ParticleDeviceType(val intValue: Int) { OTHER(Integer.MIN_VALUE), CORE(0), PHOTON(6), P1(8), RASPBERRY_PI(31), RED_BEAR_DUO(88), BLUZ(103), DIGISTUMP_OAK(82), ELECTRON(10), ESP32(11), ARGON(12), BORON(13), XENON(14), A_SOM(22), B_SOM(23), X_SOM(24), B5_SOM(25); companion object { private val intValueMap = buildIntValueMap(values()) { state -> state.intValue } @JvmStatic fun fromInt(intValue: Int): ParticleDeviceType { return intValueMap.get(intValue, ParticleDeviceType.OTHER) } } } enum class ParticleDeviceState { CAME_ONLINE, FLASH_STARTED, FLASH_SUCCEEDED, FLASH_FAILED, APP_HASH_UPDATED, ENTERED_SAFE_MODE, SAFE_MODE_UPDATER, WENT_OFFLINE, UNKNOWN } enum class VariableType { INT, DOUBLE, STRING, BOOLEAN } class FunctionDoesNotExistException(functionName: String) : Exception("Function $functionName does not exist on this device") class VariableDoesNotExistException(variableName: String) : Exception("Variable $variableName does not exist on this device") enum class KnownApp constructor(val appName: String) { TINKER("tinker") } @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated("Deprecated: field no longer available from the Particle devices API") fun requiresUpdate(): Boolean { return false } @WorkerThread @Throws(ParticleCloudException::class) fun getCurrentDataUsage(): Float { // FIXME: create a proper GSON model for this. var maxUsage = 0f try { val response = mainApi.getCurrentDataUsage(deviceState.lastIccid!!) val result = JSONObject(String((response.body as TypedByteArray).bytes)) val usages = result.getJSONArray("usage_by_day") for (i in 0 until usages.length()) { val usageElement = usages.getJSONObject(i) if (usageElement.has("mbs_used_cumulative")) { val usage = usageElement.getDouble("mbs_used_cumulative") if (usage > maxUsage) { maxUsage = usage.toFloat() } } } } catch (e: JSONException) { throw ParticleCloudException(e) } catch (e: RetrofitError) { throw ParticleCloudException(e) } return maxUsage } /** * Return the value for `variableName` on this Particle device. * * * Unless you specifically require generic handling, it is recommended that you use the * `get(type)Variable` methods instead, e.g.: `getIntVariable()`. * These type-specific methods don't require extra casting or type checking on your part, and * they more clearly and succinctly express your intent. */ @WorkerThread @Throws(ParticleCloudException::class, IOException::class, VariableDoesNotExistException::class) fun getVariable(variableName: String): Any? { val requester = object : VariableRequester<Any?, ReadObjectVariableResponse>(this) { override fun callApi(variableName: String): ReadObjectVariableResponse { return mainApi.getVariable(deviceState.deviceId, variableName) } } return requester.getVariable(variableName) } /** * Return the value for `variableName` as an int. * * * Where practical, this method is recommended over the generic [.getVariable]. * See the javadoc on that method for details. */ @WorkerThread @Throws( ParticleCloudException::class, IOException::class, VariableDoesNotExistException::class, ClassCastException::class ) fun getIntVariable(variableName: String): Int { val requester = object : VariableRequester<Int, ReadIntVariableResponse>(this) { override fun callApi(variableName: String): ReadIntVariableResponse { return mainApi.getIntVariable(deviceState.deviceId, variableName) } } return requester.getVariable(variableName) } /** * Return the value for `variableName` as a String. * * * Where practical, this method is recommended over the generic [.getVariable]. * See the javadoc on that method for details. */ @WorkerThread @Throws( ParticleCloudException::class, IOException::class, VariableDoesNotExistException::class, ClassCastException::class ) fun getStringVariable(variableName: String): String { val requester = object : VariableRequester<String, ReadStringVariableResponse>(this) { override fun callApi(variableName: String): ReadStringVariableResponse { return mainApi.getStringVariable(deviceState.deviceId, variableName) } } return requester.getVariable(variableName) } /** * Return the value for `variableName` as a double. * * Where practical, this method is recommended over the generic [.getVariable]. * See the javadoc on that method for details. */ @WorkerThread @Throws( ParticleCloudException::class, IOException::class, VariableDoesNotExistException::class, ClassCastException::class ) fun getDoubleVariable(variableName: String): Double { val requester = object : VariableRequester<Double, ReadDoubleVariableResponse>(this) { override fun callApi(variableName: String): ReadDoubleVariableResponse { return mainApi.getDoubleVariable(deviceState.deviceId, variableName) } } return requester.getVariable(variableName) } /** * Call a function on the device * * @param functionName Function name * @param args Array of arguments to pass to the function on the device. * Arguments must not be more than MAX_PARTICLE_FUNCTION_ARG_LENGTH chars * in length. If any arguments are longer, a runtime exception will be thrown. * @return result code: a value of 1 indicates success */ @WorkerThread @Throws(ParticleCloudException::class, IOException::class, FunctionDoesNotExistException::class) @JvmOverloads fun callFunction(functionName: String, args: List<String>? = null): Int { var argz = args // TODO: check response of calling a non-existent function if (!deviceState.functions.contains(functionName)) { throw FunctionDoesNotExistException(functionName) } // null is accepted here, but it won't be in the Retrofit API call later if (args == null) { argz = list() } val argsString = join(argz, ',') Preconditions.checkArgument( (argsString?.length ?: 0) < MAX_PARTICLE_FUNCTION_ARG_LENGTH, String.format( "Arguments '%s' exceed max args length of %d", argsString, MAX_PARTICLE_FUNCTION_ARG_LENGTH ) ) val response: Responses.CallFunctionResponse try { response = mainApi.callFunction( deviceState.deviceId, functionName, FunctionArgs(argsString) ) } catch (e: RetrofitError) { throw ParticleCloudException(e) } if (!response.connected) { cloud.onDeviceNotConnected(deviceState) throw IOException("Device is not connected.") } else { return response.returnValue } } /** * Subscribe to events from this device * * @param eventNamePrefix (optional, may be null) a filter to match against for events. If * null or an empty string, all device events will be received by the handler * trigger eventHandler * @param handler The handler for the events received for this subscription. * @return the subscription ID * (see [ParticleCloud.subscribeToAllEvents] for more info */ @Throws(IOException::class) fun subscribeToEvents(eventNamePrefix: String?, handler: ParticleEventHandler): Long { log.d("Subscribing to events with prefix: $eventNamePrefix for device ${deviceState.deviceId}") return cloud.subscribeToDeviceEvents(eventNamePrefix, deviceState.deviceId, handler) } /** * Unsubscribe from events. * * @param eventListenerID The ID of the subscription to be cancelled. (returned from * [.subscribeToEvents] */ @Throws(ParticleCloudException::class) fun unsubscribeFromEvents(eventListenerID: Long) { cloud.unsubscribeFromEventWithID(eventListenerID) } /** * Remove device from current logged in user account */ @WorkerThread @Throws(ParticleCloudException::class) fun unclaim() { try { cloud.unclaimDevice(deviceState.deviceId) } catch (e: RetrofitError) { throw ParticleCloudException(e) } } @WorkerThread @Throws(ParticleCloudException::class) fun flashKnownApp(knownApp: KnownApp) { performFlashingChange { mainApi.flashKnownApp(deviceState.deviceId, knownApp.appName) } } @WorkerThread @Throws(ParticleCloudException::class) fun flashBinaryFile(file: File) { performFlashingChange { mainApi.flashFile( deviceState.deviceId, TypedFile("application/octet-stream", file) ) } } @WorkerThread @Throws(ParticleCloudException::class, IOException::class) fun flashBinaryFile(stream: InputStream) { val bytes = stream.source().buffer().readByteArray() performFlashingChange { mainApi.flashFile(deviceState.deviceId, TypedFakeFile(bytes)) } } @WorkerThread @Throws(ParticleCloudException::class) fun flashCodeFile(file: File) { performFlashingChange { mainApi.flashFile( deviceState.deviceId, TypedFile("multipart/form-data", file) ) } } @WorkerThread @Throws(ParticleCloudException::class, IOException::class) fun flashCodeFile(stream: InputStream) { val bytes = stream.source().buffer().readByteArray() performFlashingChange { mainApi.flashFile( deviceState.deviceId, TypedFakeFile(bytes, "multipart/form-data", "code.ino") ) } } @WorkerThread @Throws(ParticleCloudException::class) fun refresh() { // just calling this get method will update everything as expected. log.i("refresh() for device ${deviceState.deviceId}") cloud.getDevice(deviceState.deviceId) } // FIXME: ugh. these "cloud.notifyDeviceChanged();" calls are a hint that flashing maybe // should just live in a class of its own, or that it should just be a delegate on // ParticleCloud. Review this later. @Throws(ParticleCloudException::class) private fun performFlashingChange(flashingChange: () -> Unit) { try { //listens for flashing event, on success unsubscribe from listening. subscribeToSystemEvent("spark/flash/status", object : SimpleParticleEventHandler { override fun onEvent(eventName: String, particleEvent: ParticleEvent) { if ("success" == particleEvent.dataPayload) { isFlashing = false try { [email protected]() cloud.unsubscribeFromEventWithHandler(this) } catch (e: ParticleCloudException) { // not much else we can really do here... log.w("Unable to reset flashing state for %s" + deviceState.deviceId, e) } } else { isFlashing = true } cloud.notifyDeviceChanged() } }) subscribeToSystemEvent("spark/device/app-hash", object : SimpleParticleEventHandler { override fun onEvent(eventName: String, particleEvent: ParticleEvent) { isFlashing = false try { [email protected]() cloud.unsubscribeFromEventWithHandler(this) } catch (e: ParticleCloudException) { // not much else we can really do here... log.w("Unable to reset flashing state for %s" + deviceState.deviceId, e) } cloud.notifyDeviceChanged() } }) flashingChange() } catch (e: RetrofitError) { throw ParticleCloudException(e) } catch (e: IOException) { throw ParticleCloudException(e) } } /** * Subscribes to system events of current device. Events emitted to EventBus listener. * * @throws ParticleCloudException Failure to subscribe to system events. * @see [EventBus](https://github.com/greenrobot/EventBus) */ @WorkerThread @Throws(ParticleCloudException::class) fun subscribeToSystemEvents() { try { val eventBus = EventBus.getDefault() subscriptions.add( subscribeToSystemEvent("spark/status") { _, particleEvent -> particleEvent.dataPayload?.let { sendUpdateStatusChange(eventBus, particleEvent.dataPayload) } } ) subscriptions.add( subscribeToSystemEvent("spark/flash/status") { _, particleEvent -> particleEvent.dataPayload?.let { sendUpdateFlashChange(eventBus, particleEvent.dataPayload) } } ) subscriptions.add( subscribeToSystemEvent("spark/device/app-hash") { _, _ -> sendSystemEventBroadcast( DeviceStateChange( this@ParticleDevice, ParticleDeviceState.APP_HASH_UPDATED ), eventBus ) } ) subscriptions.add( subscribeToSystemEvent("spark/status/safe-mode") { _, _ -> sendSystemEventBroadcast( DeviceStateChange( this@ParticleDevice, ParticleDeviceState.SAFE_MODE_UPDATER ), eventBus ) } ) subscriptions.add( subscribeToSystemEvent("spark/safe-mode-updater/updating") { _, _ -> sendSystemEventBroadcast( DeviceStateChange( this@ParticleDevice, ParticleDeviceState.ENTERED_SAFE_MODE ), eventBus ) } ) } catch (e: IOException) { val ex = ParticleCloudException(e) log.d("Failed to auto-subscribe to system events", ex) throw ex } } @WorkerThread @Throws(ParticleCloudException::class) fun startStopSignaling(shouldSignal: Boolean) { val signalInt = if (shouldSignal) 1 else 0 try { mainApi.shoutRainbows(deviceState.deviceId, signalInt) } catch (e: RetrofitError) { throw ParticleCloudException(e) } } /** * Ping the device, updating its online/offline state * * @return true if online, else false */ @WorkerThread @Throws(ParticleCloudException::class) fun pingDevice(): Boolean { try { val response = mainApi.pingDevice(deviceState.deviceId, "requisite_put_body") // FIXME: update device state here after switching to Kotlin return response.online } catch (e: RetrofitError) { throw ParticleCloudException(e) } } private fun sendSystemEventBroadcast(deviceStateChange: DeviceStateChange, eventBus: EventBus) { cloud.sendSystemEventBroadcast(deviceStateChange) eventBus.post(deviceStateChange) } /** * Unsubscribes from system events of current device. * * @throws ParticleCloudException Failure to unsubscribe from system events. */ @Throws(ParticleCloudException::class) fun unsubscribeFromSystemEvents() { for (subscriptionId in subscriptions) { unsubscribeFromEvents(subscriptionId!!) } } @Throws(IOException::class) private fun subscribeToSystemEvent( eventNamePrefix: String, particleEventHandler: SimpleParticleEventHandler ): Long { //Error would be handled in same way for every event name prefix, thus only simple onEvent listener is needed return subscribeToEvents(eventNamePrefix, object : ParticleEventHandler { override fun onEvent(eventName: String, particleEvent: ParticleEvent) { particleEventHandler.onEvent(eventName, particleEvent) } override fun onEventError(e: Exception) { log.d("Event error in system event handler") } }) } @Throws(IOException::class) private fun subscribeToSystemEvent( eventNamePrefix: String, particleEventHandler: (String, ParticleEvent) -> Unit ): Long { log.d("subscribeToSystemEvent: $eventNamePrefix") //Error would be handled in same way for every event name prefix, thus only simple onEvent listener is needed return subscribeToEvents(eventNamePrefix, object : ParticleEventHandler { override fun onEvent(eventName: String, particleEvent: ParticleEvent) { particleEventHandler(eventName, particleEvent) } override fun onEventError(e: Exception) { log.d("Event error in system event handler") } }) } private fun sendUpdateStatusChange(eventBus: EventBus, data: String) { val deviceStateChange = when (data) { "online" -> DeviceStateChange(this, ParticleDeviceState.CAME_ONLINE) "offline" -> DeviceStateChange(this, ParticleDeviceState.WENT_OFFLINE) else -> { throw IllegalArgumentException("Unrecognized status string: $data") } } sendSystemEventBroadcast(deviceStateChange, eventBus) } private fun sendUpdateFlashChange(eventBus: EventBus, data: String) { val deviceStateChange = when (data) { "started" -> DeviceStateChange(this, ParticleDeviceState.FLASH_STARTED) "success" -> DeviceStateChange(this, ParticleDeviceState.FLASH_SUCCEEDED) else -> { throw IllegalArgumentException("Unrecognized flash change string: $data") } } sendSystemEventBroadcast(deviceStateChange, eventBus) } override fun toString(): String { return "ParticleDevice{" + "deviceState=" + deviceState + "}" } //region Parcelable override fun writeToParcel(dest: Parcel, flags: Int) { dest.writeParcelable(deviceState, flags) } override fun describeContents(): Int { return 0 } override fun equals(other: Any?): Boolean { if (this === other) return true if (javaClass != other?.javaClass) return false other as ParticleDevice if (deviceState != other.deviceState) return false return true } override fun hashCode(): Int { return deviceState.hashCode() } //endregion private class TypedFakeFile @JvmOverloads constructor( bytes: ByteArray, mimeType: String = "application/octet-stream", private val fileName: String = "tinker_firmware.bin" ) : TypedByteArray(mimeType, bytes) { override fun fileName(): String { return fileName } } /** * Constructs a new typed byte array. Sets mimeType to `application/unknown` if absent. * * @throws NullPointerException if bytes are null */ private abstract class VariableRequester<T, R : ReadVariableResponse<T>> internal constructor( private val device: ParticleDevice ) { @WorkerThread internal abstract fun callApi(variableName: String): R @WorkerThread @Throws( ParticleCloudException::class, IOException::class, VariableDoesNotExistException::class ) internal fun getVariable(variableName: String): T { if (!device.deviceState.variables.containsKey(variableName)) { throw VariableDoesNotExistException(variableName) } val reply: R try { reply = callApi(variableName) } catch (e: RetrofitError) { throw ParticleCloudException(e) } if (!reply.coreInfo.connected) { // FIXME: we should be doing this "connected" check on _any_ reply that comes back // with a "coreInfo" block. device.cloud.onDeviceNotConnected(device.deviceState) throw IOException("Device is not connected.") } else { return reply.result } } } companion object { private const val MAX_PARTICLE_FUNCTION_ARG_LENGTH = 622 private val log = TLog.get(ParticleDevice::class.java) @JvmField val CREATOR: Parcelable.Creator<ParticleDevice> = object : Parcelable.Creator<ParticleDevice> { override fun createFromParcel(`in`: Parcel): ParticleDevice { val sdkProvider = ParticleCloudSDK.getSdkProvider() val deviceState = `in`.readParcelable<DeviceState>(DeviceState::class.java.classLoader) return sdkProvider.particleCloud.getDeviceFromState(deviceState!!) } override fun newArray(size: Int): Array<ParticleDevice?> { return arrayOfNulls(size) } } } }
apache-2.0
d672a76851ad520a4da4290927f9c98d
32.63789
117
0.611856
5.023098
false
false
false
false
Shashi-Bhushan/General
cp-trials/src/main/kotlin/in/shabhushan/cp_trials/DuplicateCounter.kt
1
685
package `in`.shabhushan.cp_trials object DuplicateCounter { fun duplicateCount(text: String): Int { val frequency = mutableMapOf<Char, Int>() text.toCharArray().map { it.toLowerCase() } .forEach { if (frequency.containsKey(it)) frequency[it] = frequency[it]!!.plus(1) else frequency[it] = 1 } return frequency.filter { it.value > 1 }.size } fun duplicateCount2(text: String) = text.groupBy { it.toLowerCase() }.filter { it.value.size > 1 }.size fun main() { val text = "dA" + "c".repeat(10) + "b".repeat(100) + "a".repeat(1000) println(duplicateCount2(text)) println(duplicateCount2("abcdeA")) } }
gpl-2.0
06ee5131f2d428ddec8f43024c30fd48
30.136364
118
0.616058
3.643617
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UISegmentedControl.kt
1
6871
package com.yy.codex.uikit import android.content.Context import android.graphics.Matrix import android.graphics.Path import android.util.AttributeSet import android.view.View import com.yy.codex.coreanimation.CAShapeLayer import java.util.* /** * Created by adi on 17/2/7. */ class UISegmentedItem(val title: String) { var enabled = true } class UISegmentedControl : UIControl { constructor(context: Context, view: View) : super(context, view) constructor(context: Context) : super(context) constructor(context: Context, attrs: AttributeSet) : super(context, attrs) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int) : super(context, attrs, defStyleAttr) constructor(context: Context, attrs: AttributeSet, defStyleAttr: Int, defStyleRes: Int) : super(context, attrs, defStyleAttr, defStyleRes) override fun init() { super.init() contentView = UIView(context) contentView.constraint = UIConstraint.full() addSubview(contentView) initBorderView() addSubview(borderView) } override fun intrinsicContentSize(): CGSize { return CGSize(0.0, 28.0); } override fun tintColorDidChanged() { super.tintColorDidChanged() borderView.layer.borderColor = tintColor ?: UIColor.clearColor } override fun layoutSubviews() { super.layoutSubviews() resetItemsView() } /* public */ var items: List<UISegmentedItem> = listOf() set(value) { field = value selectedIndex = 0 resetItemsView() } var selectedColor: UIColor = UIColor.whiteColor var selectedIndex = 0 set(value) { field = value if (field < contentButtons.count()) { contentButtons.forEach { it.select = false } contentButtons[field].select = true } } var font: UIFont? = null set(value) { field = value resetItemsView() } var textColor: UIColor? = null set(value) { field = value resetItemsView() } /* props */ lateinit private var contentView: UIView lateinit private var borderView: UIView private var contentButtons: List<UIButton> = listOf() private fun initBorderView() { borderView = UIView(context) borderView.constraint = UIConstraint.full() borderView.userInteractionEnabled = false borderView.wantsLayer = true borderView.layer.borderWidth = 1.0 borderView.layer.borderColor = tintColor ?: UIColor.clearColor borderView.layer.cornerRadius = 6.0 } private fun createLeftMask(width: Float): Path { val maskPath = Path() maskPath.moveTo(width, 0.0f) maskPath.cubicTo(width, 0.0f, width, 2.5f, width, 6f) maskPath.cubicTo(width, 10.72f, width, 17.28f, width, 22.0f) maskPath.cubicTo(width, 25.5f, width, 28.0f, width, 28.0f) maskPath.lineTo(6.45f, 28.0f) maskPath.cubicTo(2.89f, 28.0f, 0.0f, 25.31f, 0.0f, 22.0f) maskPath.lineTo(0.0f, 6.0f) maskPath.cubicTo(0.0f, 2.69f, 2.89f, 0.0f, 6.45f, 0.0f) maskPath.lineTo(width, 0.0f) maskPath.close() return maskPath } private fun createRightMask(width: Float): Path { val maskPath = Path() maskPath.moveTo(0.0f, 0.0f) maskPath.cubicTo(0.0f, 0.0f, 0.0f, 2.5f, 0.0f, 6f) maskPath.cubicTo(0.0f, 10.72f, 0.0f, 17.28f, 0.0f, 22.0f) maskPath.cubicTo(0.0f, 25.5f, 0.0f, 28.0f, 0.0f, 28.0f) maskPath.lineTo(width - 6.45f, 28.0f) maskPath.cubicTo(width - 2.89f, 28.0f, width, 25.31f, width, 22.0f) maskPath.lineTo(width, 6.0f) maskPath.cubicTo(width, 2.69f, width - 2.89f, 0.0f, width - 6.45f, 0.0f) maskPath.lineTo(0.0f, 0.0f) maskPath.close() return maskPath } private fun resetItemsView() { contentButtons.forEach(UIView::removeFromSuperview) val buttons = items.mapIndexed { idx, it -> val button = UIButton(context) button.wantsLayer = true button.font = font ?: UIFont(14.0f) button.tag = idx button.addTarget(this, "onItemButtonTouchUpInside:", Event.TouchUpInside) if (idx == 0) { val maskLayer = CAShapeLayer() maskLayer.frame = CGRect(0.0, 0.0, frame.width / items.count() + 1, frame.height) maskLayer.path = createLeftMask((frame.width / items.count() + 1).toFloat()) maskLayer.fillColor = UIColor.blackColor button.layer.mask = maskLayer button.layer.clipToBounds = true } else if (idx == items.count() - 1) { val maskLayer = CAShapeLayer() maskLayer.frame = CGRect(0.0, 0.0, frame.width / items.count() + 1, frame.height) maskLayer.path = createRightMask((frame.width / items.count() + 1).toFloat()) maskLayer.fillColor = UIColor.blackColor button.layer.mask = maskLayer button.layer.clipToBounds = true } button.constraint = UIConstraint.horizonStack(idx, items.count()) button.constraint?.width = button.constraint?.width + " + 2" button.setTitle(it.title, State.Normal) button.setTitleColor(textColor ?: tintColor ?: UIColor.clearColor, State.Normal) button.setTitleColor(textColor ?: tintColor ?: UIColor.clearColor, EnumSet.of(State.Normal, State.Highlighted)) button.setTitleColor(selectedColor, State.Selected) button.setTitleColor(selectedColor, EnumSet.of(State.Selected, State.Highlighted)) button.setBackgroundColor(UIColor.clearColor, State.Normal) button.setBackgroundColor((tintColor ?: UIColor.clearColor).colorWithAlpha(0.25), EnumSet.of(State.Normal, State.Highlighted)) button.setBackgroundColor((tintColor ?: UIColor.clearColor).colorWithAlpha(0.75), EnumSet.of(State.Selected, State.Highlighted)) button.setBackgroundColor(tintColor ?: UIColor.clearColor, State.Selected) button.select = idx == selectedIndex if (idx > 0) { val line = UIPixelLine(context) line.vertical = true line.frame = CGRect(0.0,0.0,1.0,28.0) line.color = tintColor ?: UIColor.clearColor button.addSubview(line) } return@mapIndexed button } buttons.forEach { contentView.addSubview(it) } contentButtons = buttons } private fun onItemButtonTouchUpInside(sender: UIButton) { (sender.tag as? Int)?.let { selectedIndex = it } } }
gpl-3.0
22e28710b25b40b08250846008a1b62d
36.145946
142
0.612429
3.903977
false
false
false
false
yyued/CodeX-UIKit-Android
library/src/main/java/com/yy/codex/uikit/UIActivity.kt
1
1473
package com.yy.codex.uikit import android.app.Activity import android.os.Bundle import android.view.KeyEvent /** * Created by PonyCui_Home on 2017/1/23. */ open class UIActivity : Activity() { var mainResponder: UIResponder? = null lateinit internal var keyboardManager: UIKeyboardManager var viewController: UIViewController? = null set(value) { value?.let { mainResponder = it field = it setContentView(it.view) } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) keyboardManager = UIKeyboardManager(this) keyboardManager.registerListener() } override fun onDestroy() { super.onDestroy() keyboardManager.unregisterListener() } override fun dispatchKeyEvent(event: KeyEvent?): Boolean { val event = event ?: return false mainResponder?.let { if (UIResponder.firstResponder == null) { UIResponder.firstResponder = UIResponder.findFirstResponder(it) } UIResponder.firstResponder?.let { when (event.action) { KeyEvent.ACTION_DOWN -> it.keyboardPressDown(UIKeyEvent(event.keyCode)) KeyEvent.ACTION_UP -> if (!event.isCanceled) it.keyboardPressUp(UIKeyEvent(event.keyCode)) } } } return true } }
gpl-3.0
90e81a8a6f3ecc01f34a958fc143903b
27.901961
110
0.604888
4.91
false
false
false
false
alygin/intellij-rust
src/main/kotlin/org/rust/ide/intentions/FillMatchArmsIntention.kt
1
2276
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.ide.intentions import com.intellij.openapi.editor.Editor import com.intellij.openapi.project.Project import com.intellij.psi.PsiElement import org.rust.ide.utils.isNullOrEmpty import org.rust.lang.core.psi.* import org.rust.lang.core.psi.ext.parentOfType import org.rust.lang.core.resolve.StdKnownItems import org.rust.lang.core.types.ty.TyEnum import org.rust.lang.core.types.type class FillMatchArmsIntention : RsElementBaseIntentionAction<FillMatchArmsIntention.Context>() { override fun getText(): String = familyName override fun getFamilyName(): String = "Fill match arms" override fun findApplicableContext(project: Project, editor: Editor, element: PsiElement): Context? { val matchExpr = element.parentOfType<RsMatchExpr>() ?: return null if (!matchExpr.matchBody?.matchArmList.isNullOrEmpty()) return null val type = matchExpr.expr?.type as? TyEnum ?: return null // TODO: check enum variants can be used without enum name qualifier val name = if (!isStdOptionOrResult(type.item)) { type.item.name ?: return null } else null val variants = type.item.enumBody?.enumVariantList ?: return null return Context(matchExpr, name, variants) } override fun invoke(project: Project, editor: Editor, ctx: Context) { val (expr, name, variants) = ctx var body = RsPsiFactory(project).createMatchBody(name, variants) body = (expr.matchBody?.replace(body) ?: expr.addAfter(body, expr.expr)) as RsMatchBody val lbraceOffset = (body.matchArmList.firstOrNull()?.expr as? RsBlockExpr) ?.block?.lbrace?.textOffset ?: return editor.caretModel.moveToOffset(lbraceOffset + 1) } private fun isStdOptionOrResult(element: RsEnumItem): Boolean { val knownItems = StdKnownItems.relativeTo(element) val option = knownItems.findOptionItem() val result = knownItems.findResultItem() return element == option || element == result } data class Context( val matchExpr: RsMatchExpr, val enumName: String?, val variants: List<RsEnumVariant> ) }
mit
22e74c27fa08dbf5bc6e3175bfb84fd0
38.929825
105
0.704306
4.246269
false
false
false
false
CodeIntelligenceTesting/jazzer
agent/src/main/java/com/code_intelligence/jazzer/instrumentor/ClassInstrumentor.kt
1
1936
// Copyright 2021 Code Intelligence GmbH // // 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.code_intelligence.jazzer.instrumentor import com.code_intelligence.jazzer.runtime.CoverageMap fun extractClassFileMajorVersion(classfileBuffer: ByteArray): Int { return ((classfileBuffer[6].toInt() and 0xff) shl 8) or (classfileBuffer[7].toInt() and 0xff) } class ClassInstrumentor constructor(bytecode: ByteArray) { var instrumentedBytecode = bytecode private set fun coverage(initialEdgeId: Int): Int { val edgeCoverageInstrumentor = EdgeCoverageInstrumentor( defaultEdgeCoverageStrategy, defaultCoverageMap, initialEdgeId, ) instrumentedBytecode = edgeCoverageInstrumentor.instrument(instrumentedBytecode) return edgeCoverageInstrumentor.numEdges } fun traceDataFlow(instrumentations: Set<InstrumentationType>) { instrumentedBytecode = TraceDataFlowInstrumentor(instrumentations).instrument(instrumentedBytecode) } fun hooks(hooks: Iterable<Hook>) { instrumentedBytecode = HookInstrumentor( hooks, java6Mode = extractClassFileMajorVersion(instrumentedBytecode) < 51 ).instrument(instrumentedBytecode) } companion object { val defaultEdgeCoverageStrategy = StaticMethodStrategy() val defaultCoverageMap = CoverageMap::class.java } }
apache-2.0
4c5834eb4acc51fd4d1159228295a48f
35.528302
107
0.731405
4.768473
false
false
false
false
aptyr/github-to-firebase-example
app/src/main/java/com/aptyr/clonegithubtofirebase/ui/LoginActivity.kt
1
2910
package com.aptyr.clonegithubtofirebase.ui /** * Copyright (C) 2016 Aptyr (github.com/aptyr) * * 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. */ import android.content.Intent import android.os.Bundle import android.view.View import android.widget.Toast import kotlinx.android.synthetic.main.activity_login.* import com.aptyr.clonegithubtofirebase.R import com.aptyr.clonegithubtofirebase.flowcontroller.FlowController import com.aptyr.clonegithubtofirebase.presenter.login.LoginPresenter import com.aptyr.clonegithubtofirebase.presenter.login.LoginPresenterImpl import com.aptyr.clonegithubtofirebase.ui.BaseActivity import com.aptyr.clonegithubtofirebase.view.LoginView import com.aptyr.clonegithubtofirebase.viewmodel.LoginViewModel class LoginActivity : BaseActivity(), LoginView { override val presenter: LoginPresenter = LoginPresenterImpl(this) override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_login) presenter.activity(this) signInButton.setOnClickListener { FlowController.instance.googleSignInView(this, presenter.googleApiClient) } } public override fun onStart() { super.onStart() presenter.start() } public override fun onStop() { super.onStop() presenter.stop() } override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) { super.onActivityResult(requestCode, resultCode, data) presenter.onActivityResult(requestCode, resultCode, data) } override fun signInFail() { Toast.makeText(this, "Can't sign in user.", Toast.LENGTH_SHORT).show() } override fun authFail() { Toast.makeText(this, "Can't authenticate in user.", Toast.LENGTH_SHORT).show() } override fun signedIn(viewModel: LoginViewModel) { signInButton.visibility = View.GONE avatar.visibility = View.VISIBLE greeting.visibility = View.VISIBLE viewModel.avatar(avatar) greeting.text = viewModel.greet FlowController.instance.firebaseUsersView(this) } override fun signedOut() { signInButton.visibility = View.VISIBLE avatar.visibility = View.GONE greeting.visibility = View.GONE } override fun progressView(visibility: Int) { progressView.visibility = visibility } }
apache-2.0
6757442dd622777430cd2e2f1d031ec6
32.45977
117
0.730241
4.369369
false
false
false
false
wordpress-mobile/WordPress-Stores-Android
plugins/woocommerce/src/main/kotlin/org/wordpress/android/fluxc/network/rest/wpcom/wc/tracker/TrackerRestClient.kt
2
2072
package org.wordpress.android.fluxc.network.rest.wpcom.wc.tracker import android.content.Context import com.android.volley.RequestQueue import org.wordpress.android.fluxc.Dispatcher import org.wordpress.android.fluxc.generated.endpoint.WOOCOMMERCE import org.wordpress.android.fluxc.model.SiteModel import org.wordpress.android.fluxc.network.UserAgent import org.wordpress.android.fluxc.network.rest.wpcom.BaseWPComRestClient import org.wordpress.android.fluxc.network.rest.wpcom.auth.AccessToken import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackError import org.wordpress.android.fluxc.network.rest.wpcom.jetpacktunnel.JetpackTunnelGsonRequestBuilder.JetpackResponse.JetpackSuccess import org.wordpress.android.fluxc.network.rest.wpcom.wc.WooPayload import org.wordpress.android.fluxc.network.rest.wpcom.wc.toWooError import javax.inject.Inject import javax.inject.Named import javax.inject.Singleton @Singleton internal class TrackerRestClient @Inject constructor( appContext: Context, dispatcher: Dispatcher, @Named("regular") requestQueue: RequestQueue, accessToken: AccessToken, userAgent: UserAgent, private val requestBuilder: JetpackTunnelGsonRequestBuilder ) : BaseWPComRestClient(appContext, dispatcher, requestQueue, accessToken, userAgent) { suspend fun sendTelemetry(appVersion: String, site: SiteModel): WooPayload<Unit> { val url = WOOCOMMERCE.tracker.pathWcTelemetry val response = requestBuilder.syncPostRequest( restClient = this, site = site, url = url, clazz = Unit::class.java, body = mapOf( "platform" to "android", "version" to appVersion ) ) return when (response) { is JetpackSuccess -> WooPayload(Unit) is JetpackError -> WooPayload(response.error.toWooError()) } } }
gpl-2.0
e83ac436312ed30b9832fafef6b94cb8
42.166667
130
0.757722
4.741419
false
false
false
false
Slashgear/ksort
src/main/kotlin/com/slashgear/HeapSort.kt
1
795
package com.slashgear object HeapSort : SortAlgorithm { override fun <T : Comparable<T>> sort(arr: MutableList<T>): MutableList<T> { for (i in arr.size / 2 downTo 0) { sift(arr, i, arr.size - 1) } for (i in arr.size - 1 downTo 1) { arr.swap(i, 0) sift(arr, 0, i - 1) } return arr } private fun <T : Comparable<T>> sift(arr: MutableList<T>, start: Int, end: Int): MutableList<T> { var k = start var j = 2 * k while (j <= end) { if (j < end && arr[j] < arr[j + 1]) { j += 1 } if (arr[k] >= arr[j]) return arr arr.swap(k, j); k = j j = 2 * k } return arr } }
mit
8f427d489e8be38d6740e45ffe17ddb2
24.645161
101
0.422642
3.456522
false
false
false
false
SerCeMan/franky
franky-intellij/src/main/kotlin/me/serce/franky/ui/jvmsListPanel.kt
1
3983
package me.serce.franky.ui import com.intellij.openapi.editor.colors.EditorColorsManager import com.intellij.util.ui.UIUtil import com.intellij.util.ui.components.BorderLayoutPanel import me.serce.franky.jvm.AttachableJVM import me.serce.franky.jvm.JVMAttachService import me.serce.franky.util.Lifetime import me.serce.franky.util.subscribeUI import rx.Observable import rx.Subscription import rx.lang.kotlin.PublishSubject import rx.schedulers.Schedulers import java.awt.Component import java.awt.Dimension import java.awt.event.MouseAdapter import java.awt.event.MouseEvent import java.util.concurrent.TimeUnit import javax.swing.DefaultListCellRenderer import javax.swing.DefaultListModel import javax.swing.JLabel import javax.swing.JList interface JvmsListViewModel : HasComponent { val connectJvmPublisher: Observable<AttachableJVM> } class JvmsListViewModelImpl(val lifetime: Lifetime) : JvmsListViewModel { private class JvmsListState { val jvms = PublishSubject<List<AttachableJVM>>() val jvmPublisher = PublishSubject<AttachableJVM>() } private val state = JvmsListState() private val view = JvmsListView(state) private val model = JvmsController(lifetime, state) override val connectJvmPublisher = state.jvmPublisher override fun createComponent() = view.createComponent() private class JvmsController(val lifetime: Lifetime, val state: JvmsListState) { val attachService = JVMAttachService.getInstance() init { Observable.interval(0, 5, TimeUnit.SECONDS, Schedulers.io()) .map { attachService.attachableJVMs() } .subscribe { state.jvms.onNext(it) } .unsubscibeOn(lifetime) } } private class JvmsListView(val state: JvmsListState) : View { val listModel = DefaultListModel<AttachableJVM>() val jvmsList = JList<AttachableJVM>().apply { model = listModel background = UIUtil.getListBackground() addMouseListener(object : MouseAdapter() { override fun mouseClicked(e: MouseEvent) { if (e.clickCount == 2) { state.jvmPublisher.onNext(selectedValue) } } }) } val mainPanel = BorderLayoutPanel() var loadingLabel: BorderLayoutPanel? = borderLayoutPanel { addToTop(JLabel("Loading...")) } init { state.jvms.subscribeUI { jvms -> if (loadingLabel != null) { mainPanel.remove(loadingLabel) mainPanel.addToCenter(jvmsList) loadingLabel = null } if (jvms != listModel.elements().toList()) { listModel.removeAllElements() jvms?.forEach { listModel.addElement(it) } } } jvmsList.cellRenderer = object : DefaultListCellRenderer() { override fun getListCellRendererComponent(list: JList<*>?, value: Any?, index: Int, isSelected: Boolean, cellHasFocus: Boolean): Component? { return super.getListCellRendererComponent(list, value, index, isSelected, cellHasFocus).apply { value as AttachableJVM? if (value != null) { text = "[${value.id}] ${value.name}" toolTipText = text } } } } } override fun createComponent() = mainPanel.apply { preferredSize = Dimension(200, 0) addToTop(jbLabel { text = "Running JVMs" }) addToCenter(loadingLabel) } } } fun Subscription.unsubscibeOn(lifetime: Lifetime): Subscription = apply { lifetime += { unsubscribe() } }
apache-2.0
6aeb52456a93884a02adcd55cdee9e62
33.634783
157
0.605825
4.960149
false
false
false
false
sabi0/intellij-community
platform/testGuiFramework/src/com/intellij/testGuiFramework/fixtures/ComboBoxFixture.kt
1
3899
/* * Copyright 2000-2017 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.testGuiFramework.fixtures import com.intellij.testGuiFramework.framework.Timeouts import com.intellij.testGuiFramework.impl.GuiTestUtilKt.waitUntil import org.fest.swing.core.Robot import org.fest.swing.exception.ComponentLookupException import org.fest.swing.exception.LocationUnavailableException import org.fest.swing.fixture.JComboBoxFixture import org.fest.swing.timing.Timeout import javax.swing.JButton import javax.swing.JComboBox class ComboBoxFixture(robot: Robot, comboBox: JComboBox<*>) : JComboBoxFixture(robot, comboBox) { fun expand(): ComboBoxFixture { val arrowButton = target().components.firstOrNull { it is JButton } ?: throw ComponentLookupException( "Unable to find bounded arrow button for a combobox") robot().click(arrowButton) return this } //We are waiting for a item to be shown in dropdown list. It is necessary for a async comboboxes fun selectItem(itemName: String, timeout: Timeout = Timeouts.defaultTimeout): ComboBoxFixture { waitUntil("item '$itemName' will be appeared in dropdown list", timeout) { doSelectItem { super.selectItem(itemName) } } return this } //We are waiting for a item to be shown in dropdown list. It is necessary for a async comboboxes fun selectItem(itemIndex: Int, timeout: Timeout = Timeouts.defaultTimeout): ComboBoxFixture { waitUntil("item with index $itemIndex will be appeared in dropdown list", timeout) { doSelectItem { super.selectItem(itemIndex) } } return this } override fun selectItem(index: Int): ComboBoxFixture { return selectItem(index) } /** * Returns list of rendered values * Nulls are not allowed - a rendered value cannot be a null * */ fun listItems(): List<String> { return (0 until target().itemCount).map { driver().value(target(), it).toString() } } private fun doSelectItem(selectItemFunction: () -> Unit): Boolean { return try { selectItemFunction() true } catch (e: Exception) { when (e) { is LocationUnavailableException -> false is IndexOutOfBoundsException -> false else -> throw e } } } /** * JComboBox.getSelectedIndex assumes that an item in the model cannot be null * *This function copies body of [JComboBox.getSelectedIndex] but with null allowed * */ val selectedIndex: Int get() { val noSelectedIndex = -1 val model = (target() as? JComboBox)?.model ?: throw IllegalStateException("ComboBoxFixture wraps not a JComboBox") val selectedItem = model.selectedItem return (0 until model.size) .firstOrNull { model.getElementAt(it) == selectedItem } ?: noSelectedIndex } /** * 1. selectedItem should return visible value of value from Cell Renderer * 2. to workaround problem with selected `null` value [selectedIndex] is used * */ override fun selectedItem(): String? { return getRenderedValueAtIndex(selectedIndex) } /** * Returns rendered value got through Cell Renderer * might differ from value got from the component itself * * @return rendered value at the specified index * */ private fun getRenderedValueAtIndex(index: Int) = driver().value(target(), index) }
apache-2.0
023ce91a45c8303e3432e6889fdc6439
33.513274
106
0.709156
4.576291
false
false
false
false
AlbRoehm/habitica-android
Habitica/src/main/java/com/habitrpg/android/habitica/extensions/AlertDialog-Extensions.kt
1
1196
package com.habitrpg.android.habitica.extensions import android.app.AlertDialog import android.content.DialogInterface import com.habitrpg.android.habitica.R public fun AlertDialog.Builder.setOkButton(listener: ((DialogInterface, Int) -> Unit)? = null): AlertDialog.Builder { this.setPositiveButton(R.string.ok, { dialog, which -> listener?.invoke(dialog, which) }) return this } public fun AlertDialog.Builder.setCloseButton(listener: ((DialogInterface, Int) -> Unit)? = null): AlertDialog.Builder { this.setPositiveButton(R.string.close, { dialog, which -> listener?.invoke(dialog, which) }) return this } public fun AlertDialog.setOkButton(whichButton: Int = AlertDialog.BUTTON_POSITIVE, listener: ((DialogInterface, Int) -> Unit)? = null) { this.setButton(whichButton, context.getString(R.string.ok), { dialog, which -> listener?.invoke(dialog, which) }) } public fun AlertDialog.setCloseButton(whichButton: Int = AlertDialog.BUTTON_POSITIVE, listener: ((DialogInterface, Int) -> Unit)? = null) { this.setButton(whichButton, context.getString(R.string.close), { dialog, which -> listener?.invoke(dialog, which) }) }
gpl-3.0
15cda3392cf716b4c340c65f8293f824
37.612903
139
0.719064
4.040541
false
false
false
false
mopsalarm/Pr0
app/src/main/java/com/pr0gramm/app/orm/CachedVote.kt
1
2870
package com.pr0gramm.app.orm import com.pr0gramm.app.Logger import com.pr0gramm.app.db.CachedVoteQueries import com.pr0gramm.app.time import com.squareup.sqldelight.runtime.coroutines.asFlow import com.squareup.sqldelight.runtime.coroutines.mapToList import com.squareup.sqldelight.runtime.coroutines.mapToOneOrDefault import kotlinx.coroutines.flow.Flow import kotlinx.coroutines.flow.combine import kotlinx.coroutines.flow.flowOf import java.util.* import kotlin.collections.HashMap /** * A cached vote. */ data class CachedVote(val itemId: Long, val type: Type, val vote: Vote) { enum class Type { ITEM, COMMENT, TAG } companion object { private val logger = Logger("CachedVote") private val allTypes = Type.values() private fun voteId(type: Type, itemId: Long): Long { return itemId * 10 + type.ordinal } private fun toCachedVote(itemId: Long, itemType: Int, voteValue: Int): CachedVote { return CachedVote(itemId, type = allTypes[itemType], vote = Vote.ofVoteValue(voteValue)) } fun find(cv: CachedVoteQueries, type: Type, itemId: Long): Flow<CachedVote> { return cv.findOne(voteId(type, itemId), this::toCachedVote) .asFlow() .mapToOneOrDefault(CachedVote(itemId, type, Vote.NEUTRAL)) } fun find(cv: CachedVoteQueries, type: Type, ids: List<Long>): Flow<List<CachedVote>> { if (ids.isEmpty()) { return flowOf(listOf()) } // lookup votes in chunks, as sqlite can check at most 1000 parameters at once. val flows: List<Flow<List<CachedVote>>> = ids.chunked(512) .map { chunk -> chunk.map { voteId(type, it) } } .map { chunk -> cv.findSome(chunk, this::toCachedVote) } .map { it.asFlow().mapToList() } return combine(flows) { votes -> votes.asList().flatten() } } fun quickSave(cv: CachedVoteQueries, type: Type, itemId: Long, vote: Vote) { cv.saveVote(voteId(type, itemId), itemId, type.ordinal, vote.voteValue) } fun clear(cv: CachedVoteQueries) { cv.deleteAll() } fun count(cv: CachedVoteQueries): Map<Type, Map<Vote, Int>> { val result = HashMap<Type, EnumMap<Vote, Int>>() logger.time("Counting number of votes") { cv.count().executeAsList().forEach { count -> val type = allTypes[count.itemType] val vote = Vote.ofVoteValue(count.voteValue) val votes = result.getOrPut(type, { EnumMap<Vote, Int>(Vote::class.java) }) votes[vote] = (votes[vote] ?: 0) + count.count.toInt() } } return result } } }
mit
afb9c894a93a03a76c28823f2b24053b
35.329114
100
0.600348
4.135447
false
false
false
false
kartikarora/Transfer.sh
transfer/src/main/java/me/kartikarora/transfersh/presenter/TransferActivityPresenter.kt
1
8974
package me.kartikarora.transfersh.presenter import android.content.Intent import android.content.pm.PackageManager import android.database.Cursor import android.net.Uri import android.os.Bundle import android.text.TextUtils import android.view.Menu import androidx.loader.app.LoaderManager import androidx.loader.content.Loader import com.google.android.gms.ads.AdRequest import com.google.android.material.bottomsheet.BottomSheetBehavior import com.google.firebase.analytics.FirebaseAnalytics import me.kartikarora.transfersh.R import me.kartikarora.transfersh.actions.IntentAction import me.kartikarora.transfersh.activities.AboutActivity import me.kartikarora.transfersh.activities.SplashActivity.PREF_URL_FLAG import me.kartikarora.transfersh.activities.TransferActivity.PREF_GRID_VIEW_FLAG import me.kartikarora.transfersh.adapters.FileGridAdapter import me.kartikarora.transfersh.applications.TransferApplication import me.kartikarora.transfersh.contracts.TransferActivityContract import me.kartikarora.transfersh.custom.CountingTypedFile import me.kartikarora.transfersh.helpers.UtilsHelper import me.kartikarora.transfersh.models.TransferActivityModel import me.kartikarora.transfersh.network.NetworkResponseListener import retrofit.RetrofitError import retrofit.client.Response import java.io.File import java.util.* public class TransferActivityPresenter(view: TransferActivityContract.View) : TransferActivityContract.Presenter, LoaderManager.LoaderCallbacks<Cursor> { private val mModel: TransferActivityContract.Model private lateinit var mFirebaseAnalyticsTracker: FirebaseAnalytics private val mView: TransferActivityContract.View = view init { mModel = TransferActivityModel() mModel.injectContext(mView.getContextFromView()) mView.initView() } override fun onCreate(application: TransferApplication) { mFirebaseAnalyticsTracker = application.defaultTracker mView.loadDataFromLoader() } override fun onResume(intent: Intent) { buildAdRequest() when (intent.action) { Intent.ACTION_SEND -> { val dataUri: Uri = intent.getParcelableExtra(Intent.EXTRA_STREAM) initiateFileUploadFromUri(Objects.requireNonNull(dataUri)) } Intent.ACTION_SEND_MULTIPLE -> { val dataUris: ArrayList<Uri> = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM) for (uri in Objects.requireNonNull(dataUris)) { initiateFileUploadFromUri(uri) } } IntentAction.ACTION_REUPLOAD -> { val id: Long = intent.getLongExtra("file_id", -1) if (id != -1L) { val uri = mModel.getUriFromFileIdToReuploadFile(id) initiateFileUploadFromUri(uri) mView.notifyAdapterOfDataSetChange() } } } } override fun checkIfServerIsResponsive(serverUrl: String) { mView.showPleaseWaitDialog() mModel.pingServerForResponse(serverUrl, object : NetworkResponseListener { override fun success(response: Response) { if (response.status == 200) { val headerList = response.headers for (header in headerList) { if (!TextUtils.isEmpty(header.name) && header.name.equals("server", ignoreCase = true)) { val value = header.value if (value.toLowerCase().contains("transfer.sh")) { mModel.storeStringInPreference(PREF_URL_FLAG, serverUrl) mView.hidePleaseWaitDialog() } else { mView.hidePleaseWaitDialog() mView.showServerUrlChangeAlertDialog(serverUrl) } } } } } override fun failure(error: RetrofitError) { mView.hidePleaseWaitDialog() mView.showServerUrlChangeAlertDialog(serverUrl) } }) } override fun initiateFileUploadFromUri(uri: Uri) { val baseUrl = mModel.getStringFromPreference((PREF_URL_FLAG)) val fileToUpload: File = mModel.getFileFromContentResolverUsingUri(uri) val name = fileToUpload.name mView.setUploadingFileNameInBottomSheet(name) val mimeType: String = mModel.getMimeTypeOfFileUsingUriFromContentResolver(uri) val multipartTypedOutput = mModel.createMultipartDataFromFileToUpload(fileToUpload, mimeType, CountingTypedFile.FileUploadListener { val percentage = mModel.getPercentageFromValue(it, fileToUpload.length()) mView.setUploadProgressPercentage(percentage) }) mView.setBottomSheetState(BottomSheetBehavior.STATE_EXPANDED) mModel.uploadMultipartTypedOutputToRemoteServer(baseUrl, name, multipartTypedOutput, object : NetworkResponseListener { override fun success(response: Response) { val shareableUrl = mModel.getShareableUrlFromResponse(response) mModel.saveUploadedFileMetaToDatabase(fileToUpload, shareableUrl, uri) mView.showSnackbarWithAction("$name.toString() $mView.getStringFromResource(R.string.uploaded)", R.string.share, Intent().setAction(Intent.ACTION_SEND) .putExtra(Intent.EXTRA_TEXT, shareableUrl) .setType("text/plain") .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK) ) mView.setBottomSheetState(BottomSheetBehavior.STATE_HIDDEN) } override fun failure(error: RetrofitError) { error.printStackTrace() mView.setBottomSheetState(BottomSheetBehavior.STATE_HIDDEN) mView.setUploadProgressPercentage(0) mView.setUploadingFileNameInBottomSheet("") mView.showSnackbar(R.string.something_went_wrong) } }) } override fun initiateServerUrlChange() { val serverURL = mModel.getStringFromPreference(PREF_URL_FLAG) mView.showServerUrlChangeAlertDialog(serverURL) } override fun buildAdRequest(): AdRequest { return AdRequest.Builder().build() } override fun onCreateLoader(id: Int, args: Bundle?): Loader<Cursor> { return mModel.getCursorLoader() } override fun onLoadFinished(loader: Loader<Cursor>, data: Cursor?) { val adapter = FileGridAdapter(mView.getActivityFromView(), data, mFirebaseAnalyticsTracker, mModel.getBooleanFromPreference(PREF_GRID_VIEW_FLAG)) mView.initGrid(adapter) if (null != data && data.count == 0) { mView.hideGridView() } else { mView.showGridView() } } override fun onLoaderReset(loader: Loader<Cursor>) { mView.resetGrid() } override fun getLoaderCallbacks(): LoaderManager.LoaderCallbacks<Cursor> { return this } override fun snackBarActionClicked(intent: Intent) { mModel.fireIntent(intent) } override fun optionsItemSelected(itemId: Int) { when (itemId) { R.id.action_about -> { mModel.fireIntent(AboutActivity.createIntent(mView.getContextFromView())) } R.id.action_view_grid -> { mModel.storeBooleanInPreference(PREF_GRID_VIEW_FLAG, true) mView.setColumnCountOfGridView(mView.getIntFromResource(R.integer.column_count)) } R.id.action_view_list -> { mModel.storeBooleanInPreference(PREF_GRID_VIEW_FLAG, false) mView.setColumnCountOfGridView(1) } R.id.action_set_server_url -> { initiateServerUrlChange() } } } override fun computeCorrectMenuItem(menu: Menu) { val showAsGrid = mModel.getBooleanFromPreference(PREF_GRID_VIEW_FLAG) menu.getItem(0).isVisible = !showAsGrid menu.getItem(1).isVisible = showAsGrid } override fun onPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) { if (requestCode == FileGridAdapter.PERM_REQUEST_CODE && grantResults.isNotEmpty()) { if (grantResults[0] == PackageManager.PERMISSION_GRANTED) { mView.tellAdapterThatPermissionWasGranted() } } } override fun trackEvent(vararg params: String) { UtilsHelper.getInstance().trackEvent(mFirebaseAnalyticsTracker, *params) } }
apache-2.0
51b67c4774a4436073279d531a9ee931
41.535545
153
0.638734
4.93348
false
false
false
false
micabyte/lib_base
src/main/java/com/micabytes/util/StringUtils.kt
2
753
package com.micabytes.util import com.micabytes.Game import com.micabytes.R import java.util.* fun ArrayList<String>.toText(): String { val c = Game.instance if (isEmpty()) return "" if (size == 1) return get(0) if (size == 2) return get(0) + GameConstants.WHITESPACE + c.getString(R.string.stringhandler_and1) + GameConstants.WHITESPACE + get(1) val ret = StringBuilder() for (i in 0 until size - 1) { ret.append(get(i)) if (i < size - 2) { ret.append(c.getString(R.string.stringhandler_comma)) ret.append(GameConstants.WHITESPACE) } else { ret.append(c.getString(R.string.stringhandler_and2)) ret.append(GameConstants.WHITESPACE) } } ret.append(get(size - 1)) return ret.toString() }
apache-2.0
df92db020826f988fe154cb09e9bcc1b
26.925926
123
0.667995
3.24569
false
false
false
false
android/android-studio-poet
aspoet/src/main/kotlin/com/google/androidstudiopoet/generators/SourceModuleGenerator.kt
1
5391
/* * Copyright 2017 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file * except in compliance with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the * License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the specific language governing * permissions and limitations under the License. */ package com.google.androidstudiopoet.generators import com.google.androidstudiopoet.JsonConfigGenerator import com.google.androidstudiopoet.generators.android_modules.AndroidModuleGenerator import com.google.androidstudiopoet.generators.project.GradlePropertiesGenerator import com.google.androidstudiopoet.generators.project.GradleSettingsGenerator import com.google.androidstudiopoet.generators.project.GradlewGenerator import com.google.androidstudiopoet.generators.project.ProjectBuildGradleGenerator import com.google.androidstudiopoet.models.ModuleBlueprint import com.google.androidstudiopoet.models.ProjectBlueprint import com.google.androidstudiopoet.writers.FileWriter import kotlinx.coroutines.Job import kotlinx.coroutines.launch import kotlinx.coroutines.runBlocking import java.io.File import java.util.* import kotlin.system.measureTimeMillis class SourceModuleGenerator(private val moduleBuildGradleGenerator: ModuleBuildGradleGenerator, private val moduleBuildBazelGenerator: ModuleBuildBazelGenerator, private val bazelWorkspaceGenerator: BazelWorkspaceGenerator, private val gradleSettingsGenerator: GradleSettingsGenerator, private val gradlePropertiesGenerator: GradlePropertiesGenerator, private val projectBuildGradleGenerator: ProjectBuildGradleGenerator, private val androidModuleGenerator: AndroidModuleGenerator, private val packagesGenerator: PackagesGenerator, private val dependencyGraphGenerator: DependencyGraphGenerator, private val jsonConfigGenerator: JsonConfigGenerator, private val fileWriter: FileWriter) { fun generate(projectBlueprint: ProjectBlueprint) = runBlocking { fileWriter.delete(projectBlueprint.projectRoot) fileWriter.mkdir(projectBlueprint.projectRoot) GradlewGenerator.generateGradleW(projectBlueprint.projectRoot, projectBlueprint) projectBuildGradleGenerator.generate(projectBlueprint.buildGradleBlueprint) gradleSettingsGenerator.generate(projectBlueprint.projectName, projectBlueprint.allModulesNames, projectBlueprint.projectRoot) gradlePropertiesGenerator.generate(projectBlueprint.gradlePropertiesBlueprint) if (projectBlueprint.generateBazelFiles != null && projectBlueprint.generateBazelFiles) { bazelWorkspaceGenerator.generate(projectBlueprint.bazelWorkspaceBlueprint) } print("Writing modules...") val timeSpent = measureTimeMillis { // TODO: use topological sort (as generated in hasCircularDependencies) to reduce the need of cached methodToCall val allJobs = mutableListOf<Job>() projectBlueprint.moduleBlueprints.asReversed().forEach { blueprint -> val job = launch { writeModule(blueprint) } allJobs.add(job) } var randomCount: Long = 0 projectBlueprint.androidModuleBlueprints.asReversed().forEach { blueprint -> val random = Random(randomCount++) val job = launch { androidModuleGenerator.generate(blueprint, random) } allJobs.add(job) } // Wait for jobs to finish and write progress var nextPercentage = 0 var jobsDone = 0 for (job in allJobs) { job.join() jobsDone++ val currentPercentage = (100 * jobsDone) / allJobs.size if (currentPercentage >= nextPercentage) { nextPercentage = currentPercentage + 1 print(String.format("\rWriting modules... %3d%%", currentPercentage)) } } } println("\rWriting modules... done in $timeSpent ms") dependencyGraphGenerator.generate(projectBlueprint) jsonConfigGenerator.generate(projectBlueprint) } private fun writeModule(moduleBlueprint: ModuleBlueprint) { val moduleRootFile = File(moduleBlueprint.moduleRoot) moduleRootFile.mkdir() writeLibsFolder(moduleRootFile) moduleBuildGradleGenerator.generate(moduleBlueprint.buildGradleBlueprint) moduleBlueprint.buildBazelBlueprint?.let { moduleBuildBazelGenerator.generate(it) } packagesGenerator.writePackages(moduleBlueprint.packagesBlueprint) } private fun writeLibsFolder(moduleRootFile: File) { // write libs val libRoot = moduleRootFile.toString() + "/libs/" File(libRoot).mkdir() } }
apache-2.0
520dd71dbaca2bc6b720c101698191b8
45.878261
134
0.691523
5.574974
false
false
false
false
clappr/clappr-android
clappr/src/main/kotlin/io/clappr/player/components/Playback.kt
1
7193
package io.clappr.player.components import android.os.Bundle import io.clappr.player.base.ClapprOption.* import io.clappr.player.base.Event.* import io.clappr.player.base.EventData import io.clappr.player.base.InternalEvent.DID_UPDATE_OPTIONS import io.clappr.player.base.NamedType import io.clappr.player.base.Options import io.clappr.player.base.UIObject import io.clappr.player.components.Playback.MediaType.LIVE import io.clappr.player.components.Playback.MediaType.UNKNOWN import io.clappr.player.log.Logger import org.json.JSONException import org.json.JSONObject typealias PlaybackSupportCheck = (String, String?) -> Boolean typealias PlaybackFactory = (String, String?, Options) -> Playback data class PlaybackEntry( val name: String = "", val supportsSource: PlaybackSupportCheck, val factory: PlaybackFactory ) abstract class Playback( var source: String, var mimeType: String? = null, options: Options = Options(), override val name: String = "", val supportsSource: PlaybackSupportCheck = { _, _ -> false } ) : UIObject(), NamedType { enum class MediaType { UNKNOWN, VOD, LIVE } enum class State { NONE, IDLE, PLAYING, PAUSED, STALLING, ERROR } init { require(supportsSource(source, mimeType)) { "Attempt to initialize a playback with an unsupported source" } } var options: Options = options set(options) { field = options trigger(DID_UPDATE_OPTIONS.value) } open val mediaType: MediaType get() = UNKNOWN open val duration: Double get() = Double.NaN open val position: Double get() = Double.NaN open val state: State get() = State.NONE open val canPlay: Boolean get() = false open val canPause: Boolean get() = false open val canSeek: Boolean get() = false open val isDvrAvailable: Boolean get() = false open val isDvrInUse: Boolean get() = false open val bitrate: Long get() = 0 open val avgBitrate: Long get() = 0 open val currentDate: Long? = null open val currentTime: Long? = null /** * Playback volume. Its not the device volume. * If the playback has this capability. You can set the volume from 0.0f to 1.0f. * Where 0.0f is muted and 1.0f is the playback maximum volume. * PS.: If you set a volume less than 0.0f we'll set the volume to 0.0f * PS.: If you set a volume greater than 1.0f we'll set the volume to 1.0f */ open var volume: Float? = null val availableAudios = mutableSetOf<String>() val availableSubtitles = mutableSetOf<String>() protected var internalSelectedAudio: String? = null open var selectedAudio: String? /** * @throws IllegalArgumentException when audio is not available */ set(value) { require(value in availableAudios) { "Audio not available" } internalSelectedAudio = value val data = Bundle().apply { putString(EventData.UPDATED_AUDIO.value, value) } trigger(DID_UPDATE_AUDIO.value, data) trigger(MEDIA_OPTIONS_UPDATE.value) } get() = internalSelectedAudio protected var internalSelectedSubtitle = SubtitleLanguage.OFF.value open var selectedSubtitle: String /** * @throws IllegalArgumentException when subtitle is not available */ set(value) { require(value in availableSubtitles) { "Subtitle not available" } internalSelectedSubtitle = value val data = Bundle().apply { putString(EventData.UPDATED_SUBTITLE.value, value) } trigger(DID_UPDATE_SUBTITLE.value, data) trigger(MEDIA_OPTIONS_UPDATE.value) } get() = internalSelectedSubtitle override fun render(): UIObject { if (mediaType != LIVE) configureStartAt() if (!play()) once(READY.value) { play() } return this } open fun destroy() { stopListening() } open fun play(): Boolean { return false } open fun pause(): Boolean { return false } open fun stop(): Boolean { return false } open fun seek(seconds: Int): Boolean { return false } open fun seekToLivePosition(): Boolean { return false } open fun load(source: String, mimeType: String? = null): Boolean { val supported = supportsSource(source, mimeType) if (supported) { this.source = source this.mimeType = mimeType } return supported } open fun startAt(seconds: Int) = false private val defaultAudio: String? get() = options[DEFAULT_AUDIO.value] as? String private val defaultSubtitle: String? get() = options[DEFAULT_SUBTITLE.value] as? String private val selectedAudioFromMediaOptions get() = selectedMediaOptions ?.firstOrNull { (_, type) -> type == AUDIO_TYPE }?.let { (value, _) -> value } private val selectedSubtitleFromMediaOptions get() = selectedMediaOptions ?.firstOrNull { (_, type) -> type == SUBTITLE_TYPE }?.let { (value, _) -> value } private val selectedMediaOptions: List<Pair<String, String>>? get() = try { options[SELECTED_MEDIA_OPTIONS.value]?.let { selectedMediaOptions -> val jsonObject = JSONObject(selectedMediaOptions as? String) val jsonArray = jsonObject.getJSONArray(MEDIA_OPTIONS_ARRAY_KEY) (0 until jsonArray.length()) .map { jsonArray.getJSONObject(it) } .map { val type = it.getString(MEDIA_OPTIONS_TYPE_KEY) val name = it.getString(MEDIA_OPTIONS_NAME_KEY) name to type } } } catch (jsonException: JSONException) { Logger.error(name, "Parser Json Exception ${jsonException.message}") null } fun setupInitialMediasFromClapprOptions() { val audio = defaultAudio ?: selectedAudioFromMediaOptions audio?.toLowerCase() .takeIf { it in availableAudios } ?.let { selectedAudio = it } val subtitle = defaultSubtitle ?: selectedSubtitleFromMediaOptions subtitle?.toLowerCase() .takeIf { it in availableSubtitles } ?.let { selectedSubtitle = it } } private fun configureStartAt() { if (options.containsKey(START_AT.value)) once(READY.value) { (options[START_AT.value] as? Number)?.let { startAt(it.toInt()) } options.remove(START_AT.value) } } companion object { private const val MEDIA_OPTIONS_ARRAY_KEY = "media_option" private const val MEDIA_OPTIONS_NAME_KEY = "name" private const val MEDIA_OPTIONS_TYPE_KEY = "type" private const val AUDIO_TYPE = "AUDIO" private const val SUBTITLE_TYPE = "SUBTITLE" } }
bsd-3-clause
589082ad71885737d96e413a0992c209
28.600823
93
0.611428
4.51538
false
false
false
false
RanKKI/PSNine
app/src/main/java/xyz/rankki/psnine/common/config/PSNineTypes.kt
1
309
package xyz.rankki.psnine.common.config class PSNineTypes { companion object { const val Gene = 0x01 const val News = 0x02 const val Home = 0x03 const val Guide = 0x04 const val OpenBox = 0x05 const val Discount = 0x06 const val Plus = 0x07 } }
apache-2.0
826bfd8d3e826ec593b0228aa8a64f4d
22.846154
39
0.598706
3.722892
false
true
false
false
cwoolner/flex-poker
src/main/kotlin/com/flexpoker/table/query/handlers/PotAmountIncreasedEventHandler.kt
1
1569
package com.flexpoker.table.query.handlers import com.flexpoker.framework.event.EventHandler import com.flexpoker.framework.pushnotifier.PushNotificationPublisher import com.flexpoker.pushnotifications.TableUpdatedPushNotification import com.flexpoker.table.command.events.PotAmountIncreasedEvent import com.flexpoker.table.query.repository.TableRepository import org.springframework.stereotype.Component import javax.inject.Inject @Component class PotAmountIncreasedEventHandler @Inject constructor( private val tableRepository: TableRepository, private val pushNotificationPublisher: PushNotificationPublisher ) : EventHandler<PotAmountIncreasedEvent> { override fun handle(event: PotAmountIncreasedEvent) { handleUpdatingTable(event) handlePushNotifications(event) } private fun handleUpdatingTable(event: PotAmountIncreasedEvent) { val tableDTO = tableRepository.fetchById(event.aggregateId) val updatedPots = tableDTO.pots!! .map { if (it.isOpen) { it.copy(amount = it.amount + event.amountIncreased) } else { it } }.toSet() val updatedTable = tableDTO.copy(version = event.version, pots = updatedPots) tableRepository.save(updatedTable) } private fun handlePushNotifications(event: PotAmountIncreasedEvent) { val pushNotification = TableUpdatedPushNotification(event.gameId, event.aggregateId) pushNotificationPublisher.publish(pushNotification) } }
gpl-2.0
cc13564305db73539f3ad4f24027b2a4
37.292683
92
0.734226
5.336735
false
false
false
false
scana/ok-gradle
plugin/src/test/java/me/scana/okgradle/data/JitPackRepositoryTest.kt
1
3207
package me.scana.okgradle.data import com.google.gson.Gson import com.google.gson.GsonBuilder import me.scana.okgradle.data.repository.* import org.junit.Test import kotlin.test.assertEquals import kotlin.test.assertNull import kotlin.test.assertTrue class JitPackRepositoryTest { val mockOkHttpClient = MockOkHttpClient() val networkClient = NetworkClient(mockOkHttpClient.instance()) val gson: Gson = GsonBuilder() .registerTypeAdapter(Spellcheck::class.java, SpellcheckDeserializer()) .create() val repository = JitPackRepository(networkClient, gson) @Test fun `searches and parses results`() { mockOkHttpClient.returnsJson( """{ "com.andreabaccega:android-form-edittext" : [ "1.3.4", "1.3.3" ], "com.github.alamops:materialedittext" : [ "2.1.5" ], "com.github.alfredlibrary:text" : [ "1.2" ], "com.github.anshulagarwal06:passwordedittext" : [ "v1.0" ], "com.github.apache:commons-text" : [ "commons-text-1.1" ], "com.github.Beni84:passwordedittext" : [ "0.1.0" ], "com.github.BlackBoxVision:datetimepicker-edittext" : [ "v0.3.3", "v0.3.2", "v0.3.1", "v0.3.0", "v0.2.0", "v0.1.0", "v0.0.2", "v0.0.1" ], "com.github.blackcat27:currencyedittext" : [ "2.0.1", "v1.4.4" ], "com.github.Cielsk:clearable-edittext" : [ "0.0.3", "0.0.2", "v0.0.1-alpha03" ], "com.github.DarrenWorks:havemaxbytesedittext" : [ "test0.1" ] } """ ) val result = repository.search("query").blockingGet() as SearchResult.Success assertNull(result.suggestion) assertEquals(10, result.artifacts.size) val artifact = result.artifacts[6] assertEquals("v0.3.3", artifact.version) assertEquals("datetimepicker-edittext", artifact.name) } @Test fun `returns empty result on empty query`() { mockOkHttpClient.returnsJson( """{ "com.andreabaccega:android-form-edittext" : [ "1.3.4", "1.3.3" ], "com.github.alamops:materialedittext" : [ "2.1.5" ], "com.github.alfredlibrary:text" : [ "1.2" ], "com.github.anshulagarwal06:passwordedittext" : [ "v1.0" ], "com.github.apache:commons-text" : [ "commons-text-1.1" ], "com.github.Beni84:passwordedittext" : [ "0.1.0" ], "com.github.BlackBoxVision:datetimepicker-edittext" : [ "v0.3.3", "v0.3.2", "v0.3.1", "v0.3.0", "v0.2.0", "v0.1.0", "v0.0.2", "v0.0.1" ], "com.github.blackcat27:currencyedittext" : [ "2.0.1", "v1.4.4" ], "com.github.Cielsk:clearable-edittext" : [ "0.0.3", "0.0.2", "v0.0.1-alpha03" ], "com.github.DarrenWorks:havemaxbytesedittext" : [ "test0.1" ] } """ ) val result = repository.search("").blockingGet() as SearchResult.Success assertNull(result.suggestion) assertTrue(result.artifacts.isEmpty()) } }
apache-2.0
8e7c9a7a36e18d189c77a3dcd901d1e0
44.828571
157
0.558466
3.309598
false
true
false
false
dsmiley/hhypermap-bop
bop-core/webservice/src/main/kotlin/edu/harvard/gis/hhypermap/bopws/utils.kt
2
2834
/* * Copyright 2016 President and Fellows of Harvard College * * 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 edu.harvard.gis.hhypermap.bopws import org.locationtech.spatial4j.context.SpatialContext import org.locationtech.spatial4j.shape.Point import org.locationtech.spatial4j.shape.Rectangle import java.time.Instant import java.time.LocalDate import java.time.LocalDateTime import java.time.ZoneOffset import javax.ws.rs.WebApplicationException val SOLR_RANGE_PATTERN = Regex("""\[(\S+) TO (\S+)\]""").toPattern() fun parseSolrRangeAsPair(str: String): Pair<String, String> { val matcher = SOLR_RANGE_PATTERN.matcher(str) if (matcher.matches()) { return Pair(matcher.group(1), matcher.group(2)) } else { throw WebApplicationException("Regex $SOLR_RANGE_PATTERN couldn't parse $str", 400) } } // Time stuff fun parseDateTimeRange(aTimeFilter: String?): Pair<Instant?, Instant?> { val (startStr, endStr) = parseSolrRangeAsPair(aTimeFilter ?: "[* TO *]") return Pair(parseDateTime(startStr), parseDateTime(endStr)).apply { if (first != null && second != null && (first as Instant).isAfter(second)) { throw WebApplicationException("Start must come before End: $aTimeFilter", 400) } } } fun parseDateTime(str: String): Instant? { return when { str == "*" -> null // open-ended str.contains('T') -> LocalDateTime.parse(str).toInstant(ZoneOffset.UTC) // "2016-05-15T00:00:00" else -> LocalDate.parse(str).atStartOfDay(ZoneOffset.UTC).toInstant() // "2016-05-15" } } // Spatial stuff: val SPATIAL4J_CTX = SpatialContext.GEO val spatial4jShapeFactory = SPATIAL4J_CTX.shapeFactory fun toLatLon(center: Point): String { return "${center.y},${center.x}" } /** [lat,lon TO lat,lon] */ fun parseGeoBox(geoBoxStr: String): Rectangle { val (fromPtStr, toPtStr) = parseSolrRangeAsPair(geoBoxStr) val fromPt = parseLatLon(fromPtStr) val toPt = parseLatLon(toPtStr) return spatial4jShapeFactory.rect(fromPt, toPt); } fun parseLatLon(latLonStr: String): Point { try { val cIdx = latLonStr.indexOf(','); val lat = latLonStr.substring(0, cIdx).toDouble() val lon = latLonStr.substring(cIdx + 1).toDouble() return spatial4jShapeFactory.pointXY(lon, lat) } catch(e: Exception) { throw WebApplicationException(e.toString(), 400) } }
apache-2.0
4e6f73cfde64df049d4123dbf96aa1fc
32.352941
100
0.722301
3.435152
false
false
false
false
is00hcw/anko
dsl/static/src/common/Logger.kt
2
3842
/* * Copyright 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. */ @file:JvmMultifileClass @file:JvmName("LoggerKt") package org.jetbrains.anko import android.util.Log public interface AnkoLogger { public val loggerTag: String get() { val tag = javaClass.simpleName return if (tag.length() <= 23) { tag } else { tag.substring(0, 23) } } } public fun AnkoLogger.verbose(message: Any?, thr: Throwable? = null) { log(this, message, thr, Log.VERBOSE, { tag, msg -> Log.v(tag, msg) }, { tag, msg, thr -> Log.v(tag, msg, thr) }) } public fun AnkoLogger.debug(message: Any?, thr: Throwable? = null) { log(this, message, thr, Log.DEBUG, { tag, msg -> Log.d(tag, msg) }, { tag, msg, thr -> Log.d(tag, msg, thr) }) } public fun AnkoLogger.info(message: Any?, thr: Throwable? = null) { log(this, message, thr, Log.INFO, { tag, msg -> Log.i(tag, msg) }, { tag, msg, thr -> Log.i(tag, msg, thr) }) } public fun AnkoLogger.warn(message: Any?, thr: Throwable? = null) { log(this, message, thr, Log.WARN, { tag, msg -> Log.w(tag, msg) }, { tag, msg, thr -> Log.w(tag, msg, thr) }) } public fun AnkoLogger.error(message: Any?, thr: Throwable? = null) { log(this, message, thr, Log.ERROR, { tag, msg -> Log.e(tag, msg) }, { tag, msg, thr -> Log.e(tag, msg, thr) }) } private inline fun log( logger: AnkoLogger, message: Any?, thr: Throwable?, level: Int, f: (String, String) -> Unit, fThrowable: (String, String, Throwable) -> Unit) { val tag = logger.loggerTag if (Log.isLoggable(tag, level)) { if (thr != null) { fThrowable(tag, message?.toString() ?: "null", thr) } else { f(tag, message?.toString() ?: "null") } } } public fun AnkoLogger.wtf(message: Any?, thr: Throwable? = null) { if (thr != null) { Log.wtf(loggerTag, message?.toString() ?: "null", thr) } else { Log.wtf(loggerTag, message?.toString() ?: "null") } } public inline fun AnkoLogger.verbose(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.VERBOSE)) { Log.v(tag, message()?.toString() ?: "null") } } public inline fun AnkoLogger.debug(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.DEBUG)) { Log.d(tag, message()?.toString() ?: "null") } } public inline fun AnkoLogger.info(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.INFO)) { Log.i(tag, message()?.toString() ?: "null") } } public inline fun AnkoLogger.warn(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.WARN)) { Log.w(tag, message()?.toString() ?: "null") } } public inline fun AnkoLogger.error(message: () -> Any?) { val tag = loggerTag if (Log.isLoggable(tag, Log.ERROR)) { Log.e(tag, message()?.toString() ?: "null") } } public inline fun AnkoLogger.wtf(message: () -> Any?) { Log.v(loggerTag, message()?.toString() ?: "null") } public fun Throwable.getStackTraceString(): String = Log.getStackTraceString(this)
apache-2.0
a6f4367ec60c4a9ebd1cbba30ae31f34
28.790698
82
0.584331
3.52154
false
false
false
false
Morphling-library/MorphlingBuilder
sources/morphling-builder-ide-plugin/src/main/java/com/morphling/builder/plugin/action/LauncherActionHelper.kt
1
1941
package com.morphling.builder.plugin.action import com.intellij.notification.NotificationType import com.intellij.openapi.project.Project import com.intellij.openapi.ui.Messages import com.morphling.builder.plugin.components.BuilderLogger import com.morphling.builder.plugin.components.MorphlingBuilderComponent import com.morphling.builder.plugin.manager.MorphlingSettings import com.morphling.builder.plugin.misc.BuilderUtils import java.io.File interface LauncherGradleInvoker { fun invoke(project: Project, runPath: String, gradle: String) } class LauncherActionHelper(private val mProject: Project) { private val logger: BuilderLogger get() = MorphlingBuilderComponent.getLogger(mProject) fun execute(invoker: LauncherGradleInvoker, tips: String = "") { val settings = MorphlingSettings.getInstance(mProject).getSettings() if (settings.mLauncherPath.isEmpty()) { Messages.showMessageDialog( mProject, "Please set Launcher project path!", "", Messages.getErrorIcon()) return } val runPath = File(settings.mLauncherPath).parent val gradle = BuilderUtils.getGradleExeFilePath(runPath) logger.info("Launcher project path: ${settings.mLauncherPath}") logger.info("Gradle path: $gradle") BuilderUtils.runOnSubThread { invoker.invoke(mProject, runPath, gradle) if (tips.isNotEmpty()) { MorphlingBuilderComponent.getInstance(mProject).notification.createNotification( tips, NotificationType.INFORMATION) } } } fun execute(tips: String, vararg commands: String) { execute(object : LauncherGradleInvoker { override fun invoke(project: Project, runPath: String, gradle: String) { BuilderUtils.executeCmd(mProject, runPath, gradle, *commands) } }, tips) } }
apache-2.0
07738a42f49cd66437017f5dd801848e
35.641509
96
0.695003
4.567059
false
false
false
false
vanita5/twittnuker
twittnuker/src/main/kotlin/de/vanita5/twittnuker/loader/statuses/MediaStatusesSearchLoader.kt
1
4916
/* * 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.loader.statuses import android.content.Context import android.support.annotation.WorkerThread import org.mariotaku.ktextension.isNullOrEmpty import de.vanita5.microblog.library.MicroBlog import de.vanita5.microblog.library.MicroBlogException import de.vanita5.microblog.library.twitter.model.Paging import de.vanita5.microblog.library.twitter.model.SearchQuery import de.vanita5.microblog.library.twitter.model.Status import de.vanita5.microblog.library.twitter.model.UniversalSearchQuery import de.vanita5.twittnuker.annotation.AccountType import de.vanita5.twittnuker.annotation.FilterScope import de.vanita5.twittnuker.extension.model.api.toParcelable import de.vanita5.twittnuker.extension.model.newMicroBlogInstance import de.vanita5.twittnuker.extension.model.official import de.vanita5.twittnuker.model.AccountDetails import de.vanita5.twittnuker.model.ParcelableStatus import de.vanita5.twittnuker.model.UserKey import de.vanita5.twittnuker.model.pagination.PaginatedList import de.vanita5.twittnuker.util.database.ContentFiltersUtils open class MediaStatusesSearchLoader( context: Context, accountKey: UserKey?, private val query: String?, adapterData: List<ParcelableStatus>?, savedStatusesArgs: Array<String>?, tabPosition: Int, fromUser: Boolean, override val isGapEnabled: Boolean, loadingMore: Boolean ) : AbsRequestStatusesLoader(context, accountKey, adapterData, savedStatusesArgs, tabPosition, fromUser, loadingMore) { @Throws(MicroBlogException::class) override fun getStatuses(account: AccountDetails, paging: Paging): PaginatedList<ParcelableStatus> { return getMicroBlogStatuses(account, paging).mapMicroBlogToPaginated { it.toParcelable(account, profileImageSize) } } @WorkerThread override fun shouldFilterStatus(status: ParcelableStatus): Boolean { if (status.media.isNullOrEmpty()) return true val allowed = query?.split(' ')?.toTypedArray() return ContentFiltersUtils.isFiltered(context.contentResolver, status, true, FilterScope.SEARCH_RESULTS, allowed) } override fun processPaging(paging: Paging, details: AccountDetails, loadItemLimit: Int) { if (details.type == AccountType.STATUSNET) { paging.rpp(loadItemLimit) pagination?.applyTo(paging) } else { super.processPaging(paging, details, loadItemLimit) } } protected open fun processQuery(details: AccountDetails, query: String): String { if (details.type == AccountType.TWITTER) { if (details.extras?.official ?: false) { return TweetSearchLoader.smQuery("$query filter:media", pagination) } return "$query filter:media exclude:retweets" } return query } private fun getMicroBlogStatuses(account: AccountDetails, paging: Paging): List<Status> { if (query == null) throw MicroBlogException("Empty query") val queryText = processQuery(account, query) val microBlog = account.newMicroBlogInstance(context, MicroBlog::class.java) when (account.type) { AccountType.TWITTER -> { if (account.extras?.official ?: false) { val universalQuery = UniversalSearchQuery(queryText) universalQuery.setModules(UniversalSearchQuery.Module.TWEET) universalQuery.setResultType(UniversalSearchQuery.ResultType.RECENT) universalQuery.setPaging(paging) val searchResult = microBlog.universalSearch(universalQuery) return searchResult.modules.mapNotNull { it.status?.data } } val searchQuery = SearchQuery(queryText) searchQuery.paging(paging) return microBlog.search(searchQuery) } } throw MicroBlogException("Not implemented") } }
gpl-3.0
fcd198942555327d6b49774d139c3874
41.756522
104
0.709927
4.731473
false
false
false
false
alexcustos/linkasanote
app/src/main/java/com/bytesforge/linkasanote/sync/operations/nextcloud/GetServerInfoOperation.kt
1
2209
/* * LaaNo Android application * * @author Aleksandr Borisenko <[email protected]> * Copyright (C) 2017 Aleksandr Borisenko * * 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.bytesforge.linkasanote.sync.operations.nextcloud import android.content.Context import com.owncloud.android.lib.common.OwnCloudClient import com.owncloud.android.lib.common.operations.RemoteOperation import com.owncloud.android.lib.common.operations.RemoteOperationResult import com.owncloud.android.lib.resources.status.GetRemoteStatusOperation import com.owncloud.android.lib.resources.status.OwnCloudVersion class GetServerInfoOperation( private val serverUrl: String?, private val context: Context) : RemoteOperation() { private val serverInfo = ServerInfo() override fun run(ocClient: OwnCloudClient): RemoteOperationResult { val statusOperation = GetRemoteStatusOperation(context) val result = statusOperation.execute(ocClient) if (result.isSuccess) { serverInfo.version = result.data[0] as OwnCloudVersion serverInfo.isSecure = result.code == RemoteOperationResult.ResultCode.OK_SSL serverInfo.baseUrl = serverUrl val data = ArrayList<Any>() data.add(serverInfo) result.data = data } return result } class ServerInfo { @JvmField var version: OwnCloudVersion? = null @JvmField var baseUrl: String? = null @JvmField var isSecure = false val isSet: Boolean get() = version != null && baseUrl != null } }
gpl-3.0
b90a1d69899ad08335156bb2e4fd20b5
37.77193
88
0.714803
4.554639
false
false
false
false
slartus/4pdaClient-plus
forpdaapi/src/main/java/org/softeg/slartus/forpdaapi/vo/MentionsResult.kt
1
956
package org.softeg.slartus.forpdaapi.vo import org.softeg.slartus.forpdaapi.parsers.MentionItem import java.io.Serializable import kotlin.math.max class MentionsResult : Serializable { private var pagesCount: Int = 0 private var lastPageStartCount: Int = 0 var mentions = emptyList<MentionItem>() private var currentPage: Int = 0 fun setPagesCount(pagesCount: String) { this.pagesCount = Integer.parseInt(pagesCount) + 1 } fun setLastPageStartCount(value: String) { this.lastPageStartCount = max(Integer.parseInt(value), lastPageStartCount) } fun setCurrentPage(currentPage: String) { this.currentPage = Integer.parseInt(currentPage) } fun getPagesCount(): Int { return pagesCount } fun getCurrentPage(): Int { return currentPage } fun getPostsPerPageCount(): Int { return if (pagesCount>1) lastPageStartCount/(pagesCount-1) else 0 } }
apache-2.0
9e47071f79bfd2338b8184df32d041be
24.864865
82
0.695607
4.12069
false
false
false
false
wendigo/chrome-reactive-kotlin
src/main/kotlin/pl/wendigo/chrome/api/audits/Types.kt
1
20422
package pl.wendigo.chrome.api.audits /** * Information about a cookie that is affected by an inspector issue. * * @link [Audits#AffectedCookie](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-AffectedCookie) type documentation. */ @kotlinx.serialization.Serializable data class AffectedCookie( /** * The following three properties uniquely identify a cookie */ val name: String, /** * */ val path: String, /** * */ val domain: String ) /** * Information about a request that is affected by an inspector issue. * * @link [Audits#AffectedRequest](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-AffectedRequest) type documentation. */ @kotlinx.serialization.Serializable data class AffectedRequest( /** * The unique request id. */ val requestId: pl.wendigo.chrome.api.network.RequestId, /** * */ val url: String? = null ) /** * Information about the frame affected by an inspector issue. * * @link [Audits#AffectedFrame](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-AffectedFrame) type documentation. */ @kotlinx.serialization.Serializable data class AffectedFrame( /** * */ val frameId: pl.wendigo.chrome.api.page.FrameId ) /** * * * @link [Audits#SameSiteCookieExclusionReason](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-SameSiteCookieExclusionReason) type documentation. */ @kotlinx.serialization.Serializable enum class SameSiteCookieExclusionReason { @kotlinx.serialization.SerialName("ExcludeSameSiteUnspecifiedTreatedAsLax") EXCLUDESAMESITEUNSPECIFIEDTREATEDASLAX, @kotlinx.serialization.SerialName("ExcludeSameSiteNoneInsecure") EXCLUDESAMESITENONEINSECURE, @kotlinx.serialization.SerialName("ExcludeSameSiteLax") EXCLUDESAMESITELAX, @kotlinx.serialization.SerialName("ExcludeSameSiteStrict") EXCLUDESAMESITESTRICT; } /** * * * @link [Audits#SameSiteCookieWarningReason](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-SameSiteCookieWarningReason) type documentation. */ @kotlinx.serialization.Serializable enum class SameSiteCookieWarningReason { @kotlinx.serialization.SerialName("WarnSameSiteUnspecifiedCrossSiteContext") WARNSAMESITEUNSPECIFIEDCROSSSITECONTEXT, @kotlinx.serialization.SerialName("WarnSameSiteNoneInsecure") WARNSAMESITENONEINSECURE, @kotlinx.serialization.SerialName("WarnSameSiteUnspecifiedLaxAllowUnsafe") WARNSAMESITEUNSPECIFIEDLAXALLOWUNSAFE, @kotlinx.serialization.SerialName("WarnSameSiteStrictLaxDowngradeStrict") WARNSAMESITESTRICTLAXDOWNGRADESTRICT, @kotlinx.serialization.SerialName("WarnSameSiteStrictCrossDowngradeStrict") WARNSAMESITESTRICTCROSSDOWNGRADESTRICT, @kotlinx.serialization.SerialName("WarnSameSiteStrictCrossDowngradeLax") WARNSAMESITESTRICTCROSSDOWNGRADELAX, @kotlinx.serialization.SerialName("WarnSameSiteLaxCrossDowngradeStrict") WARNSAMESITELAXCROSSDOWNGRADESTRICT, @kotlinx.serialization.SerialName("WarnSameSiteLaxCrossDowngradeLax") WARNSAMESITELAXCROSSDOWNGRADELAX; } /** * * * @link [Audits#SameSiteCookieOperation](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-SameSiteCookieOperation) type documentation. */ @kotlinx.serialization.Serializable enum class SameSiteCookieOperation { @kotlinx.serialization.SerialName("SetCookie") SETCOOKIE, @kotlinx.serialization.SerialName("ReadCookie") READCOOKIE; } /** * This information is currently necessary, as the front-end has a difficult time finding a specific cookie. With this, we can convey specific error information without the cookie. * * @link [Audits#SameSiteCookieIssueDetails](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-SameSiteCookieIssueDetails) type documentation. */ @kotlinx.serialization.Serializable data class SameSiteCookieIssueDetails( /** * */ val cookie: AffectedCookie, /** * */ val cookieWarningReasons: List<SameSiteCookieWarningReason>, /** * */ val cookieExclusionReasons: List<SameSiteCookieExclusionReason>, /** * Optionally identifies the site-for-cookies and the cookie url, which may be used by the front-end as additional context. */ val operation: SameSiteCookieOperation, /** * */ val siteForCookies: String? = null, /** * */ val cookieUrl: String? = null, /** * */ val request: AffectedRequest? = null ) /** * * * @link [Audits#MixedContentResolutionStatus](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-MixedContentResolutionStatus) type documentation. */ @kotlinx.serialization.Serializable enum class MixedContentResolutionStatus { @kotlinx.serialization.SerialName("MixedContentBlocked") MIXEDCONTENTBLOCKED, @kotlinx.serialization.SerialName("MixedContentAutomaticallyUpgraded") MIXEDCONTENTAUTOMATICALLYUPGRADED, @kotlinx.serialization.SerialName("MixedContentWarning") MIXEDCONTENTWARNING; } /** * * * @link [Audits#MixedContentResourceType](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-MixedContentResourceType) type documentation. */ @kotlinx.serialization.Serializable enum class MixedContentResourceType { @kotlinx.serialization.SerialName("Audio") AUDIO, @kotlinx.serialization.SerialName("Beacon") BEACON, @kotlinx.serialization.SerialName("CSPReport") CSPREPORT, @kotlinx.serialization.SerialName("Download") DOWNLOAD, @kotlinx.serialization.SerialName("EventSource") EVENTSOURCE, @kotlinx.serialization.SerialName("Favicon") FAVICON, @kotlinx.serialization.SerialName("Font") FONT, @kotlinx.serialization.SerialName("Form") FORM, @kotlinx.serialization.SerialName("Frame") FRAME, @kotlinx.serialization.SerialName("Image") IMAGE, @kotlinx.serialization.SerialName("Import") IMPORT, @kotlinx.serialization.SerialName("Manifest") MANIFEST, @kotlinx.serialization.SerialName("Ping") PING, @kotlinx.serialization.SerialName("PluginData") PLUGINDATA, @kotlinx.serialization.SerialName("PluginResource") PLUGINRESOURCE, @kotlinx.serialization.SerialName("Prefetch") PREFETCH, @kotlinx.serialization.SerialName("Resource") RESOURCE, @kotlinx.serialization.SerialName("Script") SCRIPT, @kotlinx.serialization.SerialName("ServiceWorker") SERVICEWORKER, @kotlinx.serialization.SerialName("SharedWorker") SHAREDWORKER, @kotlinx.serialization.SerialName("Stylesheet") STYLESHEET, @kotlinx.serialization.SerialName("Track") TRACK, @kotlinx.serialization.SerialName("Video") VIDEO, @kotlinx.serialization.SerialName("Worker") WORKER, @kotlinx.serialization.SerialName("XMLHttpRequest") XMLHTTPREQUEST, @kotlinx.serialization.SerialName("XSLT") XSLT; } /** * * * @link [Audits#MixedContentIssueDetails](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-MixedContentIssueDetails) type documentation. */ @kotlinx.serialization.Serializable data class MixedContentIssueDetails( /** * The type of resource causing the mixed content issue (css, js, iframe, form,...). Marked as optional because it is mapped to from blink::mojom::RequestContextType, which will be replaced by network::mojom::RequestDestination */ val resourceType: MixedContentResourceType? = null, /** * The way the mixed content issue is being resolved. */ val resolutionStatus: MixedContentResolutionStatus, /** * The unsafe http url causing the mixed content issue. */ val insecureURL: String, /** * The url responsible for the call to an unsafe url. */ val mainResourceURL: String, /** * The mixed content request. Does not always exist (e.g. for unsafe form submission urls). */ val request: AffectedRequest? = null, /** * Optional because not every mixed content issue is necessarily linked to a frame. */ val frame: AffectedFrame? = null ) /** * Enum indicating the reason a response has been blocked. These reasons are refinements of the net error BLOCKED_BY_RESPONSE. * * @link [Audits#BlockedByResponseReason](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-BlockedByResponseReason) type documentation. */ @kotlinx.serialization.Serializable enum class BlockedByResponseReason { @kotlinx.serialization.SerialName("CoepFrameResourceNeedsCoepHeader") COEPFRAMERESOURCENEEDSCOEPHEADER, @kotlinx.serialization.SerialName("CoopSandboxedIFrameCannotNavigateToCoopPage") COOPSANDBOXEDIFRAMECANNOTNAVIGATETOCOOPPAGE, @kotlinx.serialization.SerialName("CorpNotSameOrigin") CORPNOTSAMEORIGIN, @kotlinx.serialization.SerialName("CorpNotSameOriginAfterDefaultedToSameOriginByCoep") CORPNOTSAMEORIGINAFTERDEFAULTEDTOSAMEORIGINBYCOEP, @kotlinx.serialization.SerialName("CorpNotSameSite") CORPNOTSAMESITE; } /** * Details for a request that has been blocked with the BLOCKED_BY_RESPONSE code. Currently only used for COEP/COOP, but may be extended to include some CSP errors in the future. * * @link [Audits#BlockedByResponseIssueDetails](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-BlockedByResponseIssueDetails) type documentation. */ @kotlinx.serialization.Serializable data class BlockedByResponseIssueDetails( /** * */ val request: AffectedRequest, /** * */ val parentFrame: AffectedFrame? = null, /** * */ val blockedFrame: AffectedFrame? = null, /** * */ val reason: BlockedByResponseReason ) /** * * * @link [Audits#HeavyAdResolutionStatus](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-HeavyAdResolutionStatus) type documentation. */ @kotlinx.serialization.Serializable enum class HeavyAdResolutionStatus { @kotlinx.serialization.SerialName("HeavyAdBlocked") HEAVYADBLOCKED, @kotlinx.serialization.SerialName("HeavyAdWarning") HEAVYADWARNING; } /** * * * @link [Audits#HeavyAdReason](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-HeavyAdReason) type documentation. */ @kotlinx.serialization.Serializable enum class HeavyAdReason { @kotlinx.serialization.SerialName("NetworkTotalLimit") NETWORKTOTALLIMIT, @kotlinx.serialization.SerialName("CpuTotalLimit") CPUTOTALLIMIT, @kotlinx.serialization.SerialName("CpuPeakLimit") CPUPEAKLIMIT; } /** * * * @link [Audits#HeavyAdIssueDetails](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-HeavyAdIssueDetails) type documentation. */ @kotlinx.serialization.Serializable data class HeavyAdIssueDetails( /** * The resolution status, either blocking the content or warning. */ val resolution: HeavyAdResolutionStatus, /** * The reason the ad was blocked, total network or cpu or peak cpu. */ val reason: HeavyAdReason, /** * The frame that was blocked. */ val frame: AffectedFrame ) /** * * * @link [Audits#ContentSecurityPolicyViolationType](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-ContentSecurityPolicyViolationType) type documentation. */ @kotlinx.serialization.Serializable enum class ContentSecurityPolicyViolationType { @kotlinx.serialization.SerialName("kInlineViolation") KINLINEVIOLATION, @kotlinx.serialization.SerialName("kEvalViolation") KEVALVIOLATION, @kotlinx.serialization.SerialName("kURLViolation") KURLVIOLATION, @kotlinx.serialization.SerialName("kTrustedTypesSinkViolation") KTRUSTEDTYPESSINKVIOLATION, @kotlinx.serialization.SerialName("kTrustedTypesPolicyViolation") KTRUSTEDTYPESPOLICYVIOLATION; } /** * * * @link [Audits#SourceCodeLocation](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-SourceCodeLocation) type documentation. */ @kotlinx.serialization.Serializable data class SourceCodeLocation( /** * */ val scriptId: pl.wendigo.chrome.api.runtime.ScriptId? = null, /** * */ val url: String, /** * */ val lineNumber: Int, /** * */ val columnNumber: Int ) /** * * * @link [Audits#ContentSecurityPolicyIssueDetails](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-ContentSecurityPolicyIssueDetails) type documentation. */ @kotlinx.serialization.Serializable data class ContentSecurityPolicyIssueDetails( /** * The url not included in allowed sources. */ val blockedURL: String? = null, /** * Specific directive that is violated, causing the CSP issue. */ val violatedDirective: String, /** * */ val isReportOnly: Boolean, /** * */ val contentSecurityPolicyViolationType: ContentSecurityPolicyViolationType, /** * */ val frameAncestor: AffectedFrame? = null, /** * */ val sourceCodeLocation: SourceCodeLocation? = null, /** * */ val violatingNodeId: pl.wendigo.chrome.api.dom.BackendNodeId? = null ) /** * * * @link [Audits#SharedArrayBufferIssueType](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-SharedArrayBufferIssueType) type documentation. */ @kotlinx.serialization.Serializable enum class SharedArrayBufferIssueType { @kotlinx.serialization.SerialName("TransferIssue") TRANSFERISSUE, @kotlinx.serialization.SerialName("CreationIssue") CREATIONISSUE; } /** * Details for a issue arising from an SAB being instantiated in, or transfered to a context that is not cross-origin isolated. * * @link [Audits#SharedArrayBufferIssueDetails](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-SharedArrayBufferIssueDetails) type documentation. */ @kotlinx.serialization.Serializable data class SharedArrayBufferIssueDetails( /** * */ val sourceCodeLocation: SourceCodeLocation, /** * */ val isWarning: Boolean, /** * */ val type: SharedArrayBufferIssueType ) /** * * * @link [Audits#TwaQualityEnforcementViolationType](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-TwaQualityEnforcementViolationType) type documentation. */ @kotlinx.serialization.Serializable enum class TwaQualityEnforcementViolationType { @kotlinx.serialization.SerialName("kHttpError") KHTTPERROR, @kotlinx.serialization.SerialName("kUnavailableOffline") KUNAVAILABLEOFFLINE, @kotlinx.serialization.SerialName("kDigitalAssetLinks") KDIGITALASSETLINKS; } /** * * * @link [Audits#TrustedWebActivityIssueDetails](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-TrustedWebActivityIssueDetails) type documentation. */ @kotlinx.serialization.Serializable data class TrustedWebActivityIssueDetails( /** * The url that triggers the violation. */ val url: String, /** * */ val violationType: TwaQualityEnforcementViolationType, /** * */ val httpStatusCode: Int? = null, /** * The package name of the Trusted Web Activity client app. This field is only used when violation type is kDigitalAssetLinks. */ val packageName: String? = null, /** * The signature of the Trusted Web Activity client app. This field is only used when violation type is kDigitalAssetLinks. */ val signature: String? = null ) /** * * * @link [Audits#LowTextContrastIssueDetails](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-LowTextContrastIssueDetails) type documentation. */ @kotlinx.serialization.Serializable data class LowTextContrastIssueDetails( /** * */ val violatingNodeId: pl.wendigo.chrome.api.dom.BackendNodeId, /** * */ val violatingNodeSelector: String, /** * */ val contrastRatio: Double, /** * */ val thresholdAA: Double, /** * */ val thresholdAAA: Double, /** * */ val fontSize: String, /** * */ val fontWeight: String ) /** * Details for a CORS related issue, e.g. a warning or error related to CORS RFC1918 enforcement. * * @link [Audits#CorsIssueDetails](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-CorsIssueDetails) type documentation. */ @kotlinx.serialization.Serializable data class CorsIssueDetails( /** * */ val corsErrorStatus: pl.wendigo.chrome.api.network.CorsErrorStatus, /** * */ val isWarning: Boolean, /** * */ val request: AffectedRequest, /** * */ val resourceIPAddressSpace: pl.wendigo.chrome.api.network.IPAddressSpace? = null, /** * */ val clientSecurityState: pl.wendigo.chrome.api.network.ClientSecurityState? = null ) /** * A unique identifier for the type of issue. Each type may use one of the optional fields in InspectorIssueDetails to convey more specific information about the kind of issue. * * @link [Audits#InspectorIssueCode](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-InspectorIssueCode) type documentation. */ @kotlinx.serialization.Serializable enum class InspectorIssueCode { @kotlinx.serialization.SerialName("SameSiteCookieIssue") SAMESITECOOKIEISSUE, @kotlinx.serialization.SerialName("MixedContentIssue") MIXEDCONTENTISSUE, @kotlinx.serialization.SerialName("BlockedByResponseIssue") BLOCKEDBYRESPONSEISSUE, @kotlinx.serialization.SerialName("HeavyAdIssue") HEAVYADISSUE, @kotlinx.serialization.SerialName("ContentSecurityPolicyIssue") CONTENTSECURITYPOLICYISSUE, @kotlinx.serialization.SerialName("SharedArrayBufferIssue") SHAREDARRAYBUFFERISSUE, @kotlinx.serialization.SerialName("TrustedWebActivityIssue") TRUSTEDWEBACTIVITYISSUE, @kotlinx.serialization.SerialName("LowTextContrastIssue") LOWTEXTCONTRASTISSUE, @kotlinx.serialization.SerialName("CorsIssue") CORSISSUE; } /** * This struct holds a list of optional fields with additional information specific to the kind of issue. When adding a new issue code, please also add a new optional field to this type. * * @link [Audits#InspectorIssueDetails](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-InspectorIssueDetails) type documentation. */ @kotlinx.serialization.Serializable data class InspectorIssueDetails( /** * */ val sameSiteCookieIssueDetails: SameSiteCookieIssueDetails? = null, /** * */ val mixedContentIssueDetails: MixedContentIssueDetails? = null, /** * */ val blockedByResponseIssueDetails: BlockedByResponseIssueDetails? = null, /** * */ val heavyAdIssueDetails: HeavyAdIssueDetails? = null, /** * */ val contentSecurityPolicyIssueDetails: ContentSecurityPolicyIssueDetails? = null, /** * */ val sharedArrayBufferIssueDetails: SharedArrayBufferIssueDetails? = null, /** * */ val twaQualityEnforcementDetails: TrustedWebActivityIssueDetails? = null, /** * */ val lowTextContrastIssueDetails: LowTextContrastIssueDetails? = null, /** * */ val corsIssueDetails: CorsIssueDetails? = null ) /** * An inspector issue reported from the back-end. * * @link [Audits#InspectorIssue](https://chromedevtools.github.io/devtools-protocol/tot/Audits#type-InspectorIssue) type documentation. */ @kotlinx.serialization.Serializable data class InspectorIssue( /** * */ val code: InspectorIssueCode, /** * */ val details: InspectorIssueDetails )
apache-2.0
e21e80d59bebba96f6093be24ddcd803
24.337469
175
0.70331
4.248388
false
false
false
false
peervalhoegen/SudoQ
sudoq-app/sudoqapp/src/main/kotlin/de/sudoq/persistence/profile/ProfileBE.kt
2
2744
package de.sudoq.persistence.profile import de.sudoq.model.game.GameSettings import de.sudoq.model.profile.AppSettings import de.sudoq.model.profile.Statistics import de.sudoq.persistence.XmlAttribute import de.sudoq.persistence.XmlTree import de.sudoq.persistence.Xmlable import de.sudoq.persistence.game.GameSettingsBE import de.sudoq.persistence.game.GameSettingsMapper class ProfileBE(val id: Int) : Xmlable { var currentGame: Int = 0 var name: String? = null var assistances = GameSettings() var statistics: IntArray? = null var appSettings = AppSettings() constructor(id: Int, currentGame: Int, name: String, assistances: GameSettings, statistics: IntArray, appSettings: AppSettings) : this(id) { this.currentGame = currentGame this.name = name this.assistances = assistances this.statistics = statistics this.appSettings = appSettings } /** * {@inheritDoc} */ override fun fillFromXml(xmlTreeRepresentation: XmlTree) { currentGame = xmlTreeRepresentation.getAttributeValue("currentGame")!!.toInt() name = xmlTreeRepresentation.getAttributeValue("name") for (sub in xmlTreeRepresentation) { if (sub.name == "gameSettings") { val gameSettingsBE = GameSettingsBE() gameSettingsBE.fillFromXml(sub) assistances = GameSettingsMapper.fromBE(gameSettingsBE) } if (sub.name == "appSettings") { val appSettingsBE = AppSettingsBE() appSettingsBE.fillFromXml(sub) appSettings = AppSettingsMapper.fromBE(appSettingsBE) } } statistics = IntArray(Statistics.values().size) for (stat in Statistics.values()) { statistics!![stat.ordinal] = xmlTreeRepresentation.getAttributeValue(stat.name)!!.toInt() } } /** * {@inheritDoc} */ override fun toXmlTree(): XmlTree { val representation = XmlTree("profile") representation.addAttribute(XmlAttribute("id", id.toString())) representation.addAttribute(XmlAttribute("currentGame", currentGame.toString())) representation.addAttribute(XmlAttribute("name", name!!)) representation.addChild(GameSettingsMapper.toBE(assistances).toXmlTree()) for (stat in Statistics.values()) { representation.addAttribute( XmlAttribute( stat.name, statistics!![stat.ordinal].toString() + "" ) ) } representation.addChild(AppSettingsMapper.toBE(appSettings).toXmlTree()) return representation } }
gpl-3.0
7c3417250eb57bd0415b1b9409c41416
33.3
88
0.638484
5.034862
false
false
false
false
sksamuel/scrimage
scrimage-tests/src/test/kotlin/com/sksamuel/scrimage/core/RatioTest.kt
1
948
@file:Suppress("BlockingMethodInNonBlockingContext") package com.sksamuel.scrimage.core import com.sksamuel.scrimage.ImmutableImage import io.kotest.core.spec.style.FunSpec import io.kotest.matchers.shouldBe import java.awt.image.BufferedImage class RatioTest : FunSpec({ test("ratio happy path") { val awt1 = BufferedImage(200, 400, BufferedImage.TYPE_INT_ARGB) 0.5 shouldBe ImmutableImage.fromAwt(awt1).ratio() val awt2 = BufferedImage(400, 200, BufferedImage.TYPE_INT_ARGB) 2 shouldBe ImmutableImage.fromAwt(awt2).ratio() val awt3 = BufferedImage(333, 333, BufferedImage.TYPE_INT_ARGB) 1 shouldBe ImmutableImage.fromAwt(awt3).ratio() val awt4 = BufferedImage(333, 111, BufferedImage.TYPE_INT_ARGB) 3.0 shouldBe ImmutableImage.fromAwt(awt4).ratio() val awt5 = BufferedImage(111, 333, BufferedImage.TYPE_INT_ARGB) 1 / 3.0 shouldBe ImmutableImage.fromAwt(awt5).ratio() } })
apache-2.0
e1a97c199d7fb29cb9268707e6ec0e85
32.857143
69
0.736287
3.838057
false
true
false
false
kittinunf/Fuel
fuel-json/src/main/kotlin/com/github/kittinunf/fuel/json/FuelJson.kt
1
1038
package com.github.kittinunf.fuel.json import com.github.kittinunf.fuel.core.FuelError import com.github.kittinunf.fuel.core.Request import com.github.kittinunf.fuel.core.Response import com.github.kittinunf.fuel.core.ResponseDeserializable import com.github.kittinunf.fuel.core.ResponseHandler import com.github.kittinunf.fuel.core.response import com.github.kittinunf.result.Result import org.json.JSONArray import org.json.JSONObject class FuelJson(val content: String) { fun obj(): JSONObject = JSONObject(content) fun array(): JSONArray = JSONArray(content) } fun Request.responseJson(handler: (Request, Response, Result<FuelJson, FuelError>) -> Unit) = response(jsonDeserializer(), handler) fun Request.responseJson(handler: ResponseHandler<FuelJson>) = response(jsonDeserializer(), handler) fun Request.responseJson() = response(jsonDeserializer()) fun jsonDeserializer() = object : ResponseDeserializable<FuelJson> { override fun deserialize(response: Response): FuelJson = FuelJson(String(response.data)) }
mit
7d71503471a3ab5f9fc741c9844f6188
37.444444
100
0.797688
4.070588
false
false
false
false
Undin/intellij-rust
src/main/kotlin/org/rust/cargo/toolchain/impl/CargoMetadata.kt
2
21966
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.toolchain.impl import com.fasterxml.jackson.annotation.JsonProperty import com.intellij.openapi.diagnostic.Logger import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.vfs.* import com.intellij.openapi.vfs.newvfs.RefreshQueue import com.intellij.psi.SingleRootFileViewProvider import com.intellij.util.PathUtil import com.intellij.util.io.exists import com.intellij.util.text.SemVer import org.rust.cargo.CfgOptions import org.rust.cargo.project.workspace.* import org.rust.cargo.project.workspace.CargoWorkspace.Edition import org.rust.cargo.project.workspace.CargoWorkspace.LibKind import org.rust.openapiext.RsPathManager import org.rust.openapiext.findFileByMaybeRelativePath import org.rust.stdext.HashCode import org.rust.stdext.mapNotNullToSet import org.rust.stdext.mapToSet import java.io.IOException import java.nio.file.Files import java.nio.file.Path import java.nio.file.StandardCopyOption import java.util.* private val LOG: Logger = logger<CargoMetadata>() typealias PathConverter = (String) -> String /** * Classes mirroring JSON output of `cargo metadata`. * Attribute names and snake_case are crucial. * * Some information available in JSON is not represented here */ object CargoMetadata { data class Project( /** * All packages, including dependencies */ val packages: List<Package>, /** * A graph of dependencies */ val resolve: Resolve, /** * Version of the format (currently 1) */ val version: Int, /** * Ids of packages that are members of the cargo workspace */ val workspace_members: List<String>, /** * Path to workspace root folder */ val workspace_root: String ) { fun convertPaths(converter: PathConverter): Project = copy( packages = packages.map { it.convertPaths(converter) }, workspace_root = converter(workspace_root) ) } data class Package( val name: String, /** * SemVer version */ val version: String, val authors: List<String>, val description: String?, val repository: String?, val license: String?, val license_file: String?, /** * Where did this package comes from? Local file system, crates.io, github repository. * * Will be `null` for the root package and path dependencies. */ val source: String?, /** * A unique id. * There may be several packages with the same name, but different version/source. * The triple (name, version, source) is unique. */ val id: PackageId, /** * Path to Cargo.toml */ val manifest_path: String, /** * Artifacts that can be build from this package. * This is a list of crates that can be build from the package. */ val targets: List<Target>, /** * Code edition of current package. * * Can be "2015", "2018" or null. Null value can be got from old version of cargo * so it is the same as "2015" */ val edition: String?, /** * Features available in this package (excluding optional dependencies). * The entry named "default" defines which features are enabled by default. */ val features: Map<FeatureName, List<FeatureDep>>, /** * Dependencies as they listed in the package `Cargo.toml`, without package resolution or * any additional data. */ val dependencies: List<RawDependency> ) { fun convertPaths(converter: PathConverter): Package = copy( manifest_path = converter(manifest_path), targets = targets.map { it.convertPaths(converter) } ) } data class RawDependency( /** A `package` name (non-normalized) of the dependency */ val name: String, /** Non-null if renamed. Non-normalized (i.e. can contain "-") */ val rename: String?, val kind: String?, val target: String?, val optional: Boolean, val uses_default_features: Boolean, val features: List<String> ) data class Target( /** * Kind of a target. Can be a singleton list ["bin"], * ["example], ["test"], ["example"], ["custom-build"], ["bench"]. * * Can also be a list of one or more of "lib", "rlib", "dylib", "staticlib" */ val kind: List<String>, /** * Name */ val name: String, /** * Path to the root module of the crate (aka crate root) */ val src_path: String, /** * List of crate types * * See [linkage](https://doc.rust-lang.org/reference/linkage.html) */ val crate_types: List<String>, /** * Code edition of current target. * * Can be "2015", "2018" or null. Null value can be got from old version of cargo * so it is the same as "2015" */ val edition: String?, /** * Indicates whether or not * [documentation examples](https://doc.rust-lang.org/rustdoc/documentation-tests.html) * are tested by default by `cargo test`. This is only relevant for libraries, it has * no effect on other targets. The default is `true` for the library. * * See [docs](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-doctest-field) */ val doctest: Boolean?, /** * Specifies which package features the target needs in order to be built. This is only relevant * for the `[[bin]]`, `[[bench]]`, `[[test]]`, and `[[example]]` sections, it has no effect on `[lib]`. * * See [docs](https://doc.rust-lang.org/cargo/reference/cargo-targets.html#the-required-features-field) */ @Suppress("KDocUnresolvedReference") @JsonProperty("required-features") val required_features: List<String>? ) { val cleanKind: TargetKind get() = when (kind.singleOrNull()) { "bin" -> TargetKind.BIN "example" -> TargetKind.EXAMPLE "test" -> TargetKind.TEST "bench" -> TargetKind.BENCH "proc-macro" -> TargetKind.LIB "custom-build" -> TargetKind.CUSTOM_BUILD else -> if (kind.any { it.endsWith("lib") }) TargetKind.LIB else TargetKind.UNKNOWN } val cleanCrateTypes: List<CrateType> get() = crate_types.map { when (it) { "bin" -> CrateType.BIN "lib" -> CrateType.LIB "dylib" -> CrateType.DYLIB "staticlib" -> CrateType.STATICLIB "cdylib" -> CrateType.CDYLIB "rlib" -> CrateType.RLIB "proc-macro" -> CrateType.PROC_MACRO else -> CrateType.UNKNOWN } } fun convertPaths(converter: PathConverter): Target = copy( src_path = converter(src_path) ) } enum class TargetKind { LIB, BIN, TEST, EXAMPLE, BENCH, CUSTOM_BUILD, UNKNOWN } /** * Represents possible variants of generated artifact binary * corresponded to `--crate-type` compiler attribute * * See [linkage](https://doc.rust-lang.org/reference/linkage.html) */ enum class CrateType { BIN, LIB, DYLIB, STATICLIB, CDYLIB, RLIB, PROC_MACRO, UNKNOWN } /** * A rooted graph of dependencies, represented as adjacency list */ data class Resolve( val nodes: List<ResolveNode> ) data class ResolveNode( val id: PackageId, /** * Id's of dependent packages */ val dependencies: List<PackageId>, /** * List of dependency info * * Contains additional info compared with [dependencies] like custom package name. */ val deps: List<Dep>?, /** * Enabled features (including optional dependencies) */ val features: List<String>? ) data class Dep( /** * Id of dependent package */ val pkg: PackageId, /** * Dependency name that should be used in code as extern crate name */ val name: String?, /** * Used to distinguish `[dependencies]`, `[dev-dependencies]` and `[build-dependencies]`. * It's a list because a dependency can be used in both `[dependencies]` and `[build-dependencies]`. * `null` on old cargo only. */ @Suppress("KDocUnresolvedReference") val dep_kinds: List<DepKindInfo>? ) data class DepKindInfo( val kind: String?, val target: String? ) { fun clean(): CargoWorkspace.DepKindInfo = CargoWorkspace.DepKindInfo( when (kind) { "dev" -> CargoWorkspace.DepKind.Development "build" -> CargoWorkspace.DepKind.Build else -> CargoWorkspace.DepKind.Normal }, target ) } fun clean( project: Project, buildMessages: BuildMessages? = null ): CargoWorkspaceData { val fs = LocalFileSystem.getInstance() val workspaceRoot = fs.refreshAndFindFileByPath(project.workspace_root) requireNotNull(workspaceRoot) { "`cargo metadata` reported a workspace path which does not exist at `${project.workspace_root}`" } val members = project.workspace_members val packageIdToNode = project.resolve.nodes.associateBy { it.id } val packages = project.packages.map { pkg -> // resolve contains all enabled features for each package val resolveNode = packageIdToNode[pkg.id] if (resolveNode == null) { LOG.error("Could not find package with `id` '${pkg.id}' in `resolve` section of the `cargo metadata` output.") } val enabledFeatures = resolveNode?.features.orEmpty().toSet() // features enabled by Cargo val pkgBuildMessages = buildMessages?.get(pkg.id).orEmpty() pkg.clean(fs, pkg.id in members, enabledFeatures, pkgBuildMessages) } adjustFileSizeLimitForFilesInOutDirs(packages) return CargoWorkspaceData( packages, project.resolve.nodes.associate { node -> val dependencySet = if (node.deps != null) { node.deps.mapToSet { (pkgId, name, depKinds) -> val depKindsLowered = depKinds?.map { it.clean() } ?: listOf(CargoWorkspace.DepKindInfo(CargoWorkspace.DepKind.Unclassified)) CargoWorkspaceData.Dependency(pkgId, name, depKindsLowered) } } else { node.dependencies.mapToSet { CargoWorkspaceData.Dependency(it) } } node.id to dependencySet }, project.packages.associate { it.id to it.dependencies }, workspaceRoot.url ) } /** * Rust buildscripts (`build.rs`) often generate files that are larger than the default IntelliJ size limit. * The default filesize limit is specified by [com.intellij.openapi.util.io.FileUtilRt.DEFAULT_INTELLISENSE_LIMIT] * or "idea.max.intellisense.filesize" system property. * Here we ensure that the file size limit is not less than [ADJUSTED_FILE_SIZE_LIMIT_FOR_OUTPUT_FILES] for * cargo generated files. */ private fun adjustFileSizeLimitForFilesInOutDirs(packages: List<CargoWorkspaceData.Package>) { if (PersistentFSConstants.getMaxIntellisenseFileSize() >= ADJUSTED_FILE_SIZE_LIMIT_FOR_OUTPUT_FILES) return val outDirs = packages .mapNotNull { it.outDirUrl } .mapNotNullToSet { VirtualFileManager.getInstance().refreshAndFindFileByUrl(it) } if (outDirs.isEmpty()) return RefreshQueue.getInstance().refresh(false, true, null, outDirs) for (outDir in outDirs) { VfsUtilCore.visitChildrenRecursively(outDir, object : VirtualFileVisitor<ArrayList<VirtualFile>>() { override fun visitFile(outFile: VirtualFile): Boolean { if (!outFile.isDirectory && outFile.length <= ADJUSTED_FILE_SIZE_LIMIT_FOR_OUTPUT_FILES) { SingleRootFileViewProvider.doNotCheckFileSizeLimit(outFile) } return true } }) } } // Experimentally verified that 8Mb works with the default IDEA -Xmx768M. Larger values may // lead to OOM, please verify before adjusting private const val ADJUSTED_FILE_SIZE_LIMIT_FOR_OUTPUT_FILES: Int = 8 * 1024 * 1024 private fun Package.clean( fs: LocalFileSystem, isWorkspaceMember: Boolean, enabledFeatures: Set<String>, buildMessages: List<CompilerMessage> ): CargoWorkspaceData.Package { val rootPath = PathUtil.getParentPath(manifest_path) val root = fs.refreshAndFindFileByPath(rootPath) ?.let { if (isWorkspaceMember) it else it.canonicalFile } ?: throw CargoMetadataException("`cargo metadata` reported a package which does not exist at `$manifest_path`") val features = features.toMutableMap() // Backcompat Cargo 1.59.0: optional dependencies are features implicitly. // Since 1.60.0 these implicit features are returned from cargo as usual val allFeatureDependencies = features.values.flatten().toSet() for (dependency in dependencies) { val featureName = dependency.rename ?: dependency.name if (dependency.optional && featureName !in features) { val depFeatureName = "dep:$featureName" if (depFeatureName !in allFeatureDependencies) { features[featureName] = listOf(depFeatureName) } } } val buildScriptMessage = buildMessages.find { it is BuildScriptMessage } as? BuildScriptMessage val procMacroArtifact = getProcMacroArtifact(buildMessages) val cfgOptions = buildScriptMessage?.cfgs?.let { CfgOptions.parse(it) } val envFromBuildscript = buildScriptMessage?.env.orEmpty() .filter { it.size == 2 } .associate { (key, value) -> key to value } val semver = SemVer.parseFromText(version) // https://doc.rust-lang.org/cargo/reference/environment-variables.html#environment-variables-cargo-sets-for-crates val env: Map<String, String> = envFromBuildscript + mapOf( "CARGO_MANIFEST_DIR" to rootPath, "CARGO" to "cargo", // TODO get from toolchain "CARGO_PKG_VERSION" to version, "CARGO_PKG_VERSION_MAJOR" to semver?.major?.toString().orEmpty(), "CARGO_PKG_VERSION_MINOR" to semver?.minor?.toString().orEmpty(), "CARGO_PKG_VERSION_PATCH" to semver?.patch?.toString().orEmpty(), "CARGO_PKG_VERSION_PRE" to semver?.preRelease.orEmpty(), "CARGO_PKG_AUTHORS" to authors.joinToString(separator = ";"), "CARGO_PKG_NAME" to name, "CARGO_PKG_DESCRIPTION" to description.orEmpty(), "CARGO_PKG_REPOSITORY" to repository.orEmpty(), "CARGO_PKG_LICENSE" to license.orEmpty(), "CARGO_PKG_LICENSE_FILE" to license_file.orEmpty(), "CARGO_CRATE_NAME" to name.replace('-', '_'), ) val outDir = buildScriptMessage?.out_dir ?.let { root.fileSystem.refreshAndFindFileByPath(it) } ?.let { if (isWorkspaceMember) it else it.canonicalFile } return CargoWorkspaceData.Package( id, root.url, name, version, targets.mapNotNull { it.clean(root, isWorkspaceMember) }, source, origin = if (isWorkspaceMember) PackageOrigin.WORKSPACE else PackageOrigin.DEPENDENCY, edition = edition.cleanEdition(), features = features, enabledFeatures = enabledFeatures, cfgOptions = cfgOptions, env = env, outDirUrl = outDir?.url, procMacroArtifact = procMacroArtifact ) } private fun getProcMacroArtifact(buildMessages: List<CompilerMessage>): CargoWorkspaceData.ProcMacroArtifact? { val procMacroArtifacts = buildMessages .filterIsInstance<CompilerArtifactMessage>() .filter { it.target.kind.contains("proc-macro") && it.target.crate_types.contains("proc-macro") } val procMacroArtifactPath = procMacroArtifacts .flatMap { it.filenames } .find { file -> DYNAMIC_LIBRARY_EXTENSIONS.any { file.endsWith(it) } } return procMacroArtifactPath?.let { val originPath = Path.of(procMacroArtifactPath) val hash = try { HashCode.ofFile(originPath) } catch (e: IOException) { LOG.warn(e) return@let null } val path = copyProcMacroArtifactToTempDir(originPath, hash) CargoWorkspaceData.ProcMacroArtifact(path, hash) } } /** * Copy the artifact to a temporary directory in order to allow a user to overwrite or delete the artifact. * * It's `@Synchronized` because it can be called from different IDEA projects simultaneously, * and different projects may want to write the same files */ @Synchronized private fun copyProcMacroArtifactToTempDir(originPath: Path, hash: HashCode): Path { return try { val temp = RsPathManager.tempPluginDirInSystem().resolve("proc_macros") Files.createDirectories(temp) // throws IOException val filename = originPath.fileName.toString() val extension = PathUtil.getFileExtension(filename) val targetPath = temp.resolve("$filename.$hash.$extension") if (!targetPath.exists() || Files.size(originPath) != Files.size(targetPath)) { Files.copy(originPath, targetPath, StandardCopyOption.REPLACE_EXISTING) // throws IOException } targetPath } catch (e: IOException) { LOG.warn(e) originPath } } private val DYNAMIC_LIBRARY_EXTENSIONS: List<String> = listOf(".dll", ".so", ".dylib") private fun Target.clean(root: VirtualFile, isWorkspaceMember: Boolean): CargoWorkspaceData.Target? { val mainFile = root.findFileByMaybeRelativePath(src_path) ?.let { if (isWorkspaceMember) it else it.canonicalFile } return mainFile?.let { CargoWorkspaceData.Target( it.url, name, makeTargetKind(cleanKind, cleanCrateTypes), edition.cleanEdition(), doctest = doctest ?: true, requiredFeatures = required_features.orEmpty() ) } } private fun makeTargetKind(target: TargetKind, crateTypes: List<CrateType>): CargoWorkspace.TargetKind { return when (target) { TargetKind.LIB -> CargoWorkspace.TargetKind.Lib(crateTypes.toLibKinds()) TargetKind.BIN -> CargoWorkspace.TargetKind.Bin TargetKind.TEST -> CargoWorkspace.TargetKind.Test TargetKind.EXAMPLE -> if (crateTypes.contains(CrateType.BIN)) { CargoWorkspace.TargetKind.ExampleBin } else { CargoWorkspace.TargetKind.ExampleLib(crateTypes.toLibKinds()) } TargetKind.BENCH -> CargoWorkspace.TargetKind.Bench TargetKind.CUSTOM_BUILD -> CargoWorkspace.TargetKind.CustomBuild TargetKind.UNKNOWN -> CargoWorkspace.TargetKind.Unknown } } private fun List<CrateType>.toLibKinds(): EnumSet<LibKind> { return EnumSet.copyOf(map { when (it) { CrateType.LIB -> LibKind.LIB CrateType.DYLIB -> LibKind.DYLIB CrateType.STATICLIB -> LibKind.STATICLIB CrateType.CDYLIB -> LibKind.CDYLIB CrateType.RLIB -> LibKind.RLIB CrateType.PROC_MACRO -> LibKind.PROC_MACRO CrateType.BIN -> LibKind.UNKNOWN CrateType.UNKNOWN -> LibKind.UNKNOWN } }) } private fun String?.cleanEdition(): Edition = when (this) { Edition.EDITION_2015.presentation -> Edition.EDITION_2015 Edition.EDITION_2018.presentation -> Edition.EDITION_2018 Edition.EDITION_2021.presentation -> Edition.EDITION_2021 else -> Edition.EDITION_2015 } fun Project.replacePaths(replacer: (String) -> String): Project = copy( packages = packages.map { it.replacePaths(replacer) }, workspace_root = replacer(workspace_root) ) private fun Package.replacePaths(replacer: (String) -> String): Package = copy( manifest_path = replacer(manifest_path), targets = targets.map { it.replacePaths(replacer) } ) private fun Target.replacePaths(replacer: (String) -> String): Target = copy(src_path = replacer(src_path)) }
mit
931cd0ed358186db0f611099e35bbb96
35.732441
138
0.594692
4.675607
false
false
false
false
brianwernick/RecyclerExt
library/src/main/kotlin/com/devbrackets/android/recyclerext/adapter/viewholder/MenuViewHolder.kt
1
3449
/* * Copyright (C) 2016 Brian Wernick * * 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.devbrackets.android.recyclerext.adapter.viewholder import android.view.Menu import android.view.MenuItem import android.view.View import androidx.annotation.IdRes import androidx.annotation.MenuRes import androidx.appcompat.widget.PopupMenu /** * A simple ViewHolder that extends [ClickableViewHolder] to provide the * functionality for providing and registering for popup menu selection events */ abstract class MenuViewHolder(itemView: View) : ClickableViewHolder(itemView), PopupMenu.OnMenuItemClickListener { /** * Used to listen for menu item selections */ interface OnMenuItemSelectedListener { fun onMenuItemSelected(viewHolder: MenuViewHolder, menuItem: MenuItem): Boolean } private var onMenuItemSelectedListener: OnMenuItemSelectedListener? = null /** * Retrieves the id for the view that will be used to show the * popup menu when clicked. * * @return The resource id for the menu view */ @get:IdRes protected abstract val menuViewId: Int /** * Retrieves the id for the xml menu resource that specifies * the options for the popup menu. * * @return The resource id for the xml menu */ @get:MenuRes protected abstract val menuResourceId: Int fun setOnMenuItemSelectedListener(listener: OnMenuItemSelectedListener?) { onMenuItemSelectedListener = listener } init { initializeMenuClickListener() } override fun onMenuItemClick(item: MenuItem): Boolean { return onMenuItemSelectedListener?.onMenuItemSelected(this, item) == true } /** * Registers the view specified with [.getMenuViewId] to * show the popup menu specified with [.getMenuResourceId] */ protected fun initializeMenuClickListener() { val menuView = itemView.findViewById<View>(menuViewId) menuView?.setOnClickListener(MenuClickListener()) } /** * Shows the menu specified with the `menuResourceId` starting * at the `anchor` * * @param anchor The view to show the popup menu from * @param menuResourceId The resource id for the menu to show */ protected fun showMenu(anchor: View, @MenuRes menuResourceId: Int) { val menu = PopupMenu(anchor.context, anchor) val inflater = menu.menuInflater inflater.inflate(menuResourceId, menu.menu) onPreparePopupMenu(menu.menu) menu.setOnMenuItemClickListener(this) menu.show() } /** * Allows the user to customize the popup menu specified with [.getMenuResourceId] * before it is shown * * @param menu The menu to customize */ protected fun onPreparePopupMenu(menu: Menu) { //Purposefully left blank } /** * A simple click listener class to handle menu view clicks */ protected inner class MenuClickListener : View.OnClickListener { override fun onClick(view: View) { showMenu(view, menuResourceId) } } }
apache-2.0
2abe972af1291fb76963de69997f7ec8
29.530973
114
0.732676
4.586436
false
false
false
false
deva666/anko
anko/library/generator/src/org/jetbrains/android/anko/generator/ServiceGenerator.kt
2
1880
/* * Copyright 2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.jetbrains.android.anko.generator import org.objectweb.asm.tree.FieldNode class ServiceGenerator : Generator<ServiceElement> { override fun generate(state: GenerationState): Iterable<ServiceElement> { return state.classTree.findNode("android/content/Context")?.data?.fields ?.filter { it.name.endsWith("_SERVICE") } ?.map { val service = state.classTree.findNode("android", it.toServiceClassName())?.data if (service != null && service in state.availableClasses) { ServiceElement(service, it.name) } else null } ?.filterNotNull() ?.sortedBy { it.simpleName } ?: emptyList() } private fun FieldNode.toServiceClassName(): String { var nextCapital = true val builder = StringBuilder() for (char in name.replace("_SERVICE", "_MANAGER").toCharArray()) when (char) { '_' -> nextCapital = true else -> builder.append( if (nextCapital) { nextCapital = false; char } else Character.toLowerCase(char) ) } return builder.toString() } }
apache-2.0
fab332b854040db9385dc351bff15b78
36.62
100
0.607447
4.783715
false
false
false
false
androidx/androidx
health/connect/connect-client/src/main/java/androidx/health/connect/client/records/ExerciseLapRecord.kt
3
2956
/* * Copyright (C) 2022 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.health.connect.client.records import androidx.health.connect.client.records.metadata.Metadata import androidx.health.connect.client.units.Length import androidx.health.connect.client.units.meters import java.time.Instant import java.time.ZoneOffset /** * Captures the time of a lap within an exercise. A lap is explicitly marked segment within an * exercise session (such as pool length while swimming or a track lap while running). Each record * contains the start / stop time of the lap. */ public class ExerciseLapRecord( override val startTime: Instant, override val startZoneOffset: ZoneOffset?, override val endTime: Instant, override val endZoneOffset: ZoneOffset?, /** Length of the lap, in meters. Optional field. Valid range: 0-1000000 meters. */ public val length: Length? = null, override val metadata: Metadata = Metadata.EMPTY, ) : IntervalRecord { init { length?.requireNotLess(other = length.zero(), name = "length") length?.requireNotMore(other = MAX_LAP_LENGTH, name = "length") require(startTime.isBefore(endTime)) { "startTime must be before endTime." } } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun equals(other: Any?): Boolean { if (this === other) return true if (other !is ExerciseLapRecord) return false if (length != other.length) return false if (startTime != other.startTime) return false if (startZoneOffset != other.startZoneOffset) return false if (endTime != other.endTime) return false if (endZoneOffset != other.endZoneOffset) return false if (metadata != other.metadata) return false return true } /* * Generated by the IDE: Code -> Generate -> "equals() and hashCode()". */ override fun hashCode(): Int { var result = length?.hashCode() ?: 0 result = 31 * result + startTime.hashCode() result = 31 * result + (startZoneOffset?.hashCode() ?: 0) result = 31 * result + endTime.hashCode() result = 31 * result + (endZoneOffset?.hashCode() ?: 0) result = 31 * result + metadata.hashCode() return result } private companion object { private val MAX_LAP_LENGTH = 1000_000.meters } }
apache-2.0
0dda3db5e4f7682a90738e55384366af
36.897436
98
0.679296
4.418535
false
false
false
false
androidx/androidx
compose/runtime/runtime-rxjava3/src/main/java/androidx/compose/runtime/rxjava3/RxJava3Adapter.kt
3
6133
/* * Copyright 2020 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package androidx.compose.runtime.rxjava3 import androidx.compose.runtime.Composable import androidx.compose.runtime.DisposableEffect import androidx.compose.runtime.State import androidx.compose.runtime.mutableStateOf import androidx.compose.runtime.remember import io.reactivex.rxjava3.core.Completable import io.reactivex.rxjava3.core.Flowable import io.reactivex.rxjava3.core.Maybe import io.reactivex.rxjava3.core.Observable import io.reactivex.rxjava3.core.Single import io.reactivex.rxjava3.disposables.Disposable import io.reactivex.rxjava3.plugins.RxJavaPlugins /** * Subscribes to this [Observable] and represents its values via [State]. Every time there would * be new value posted into the [Observable] the returned [State] will be updated causing * recomposition of every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Observable.onErrorReturn] or [Observable.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava3.samples.ObservableSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Suppress("UPPER_BOUND_VIOLATED_BASED_ON_JAVA_ANNOTATIONS") @Composable fun <R, T : R> Observable<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Flowable] and represents its values via [State]. Every time there would * be new value posted into the [Flowable] the returned [State] will be updated causing * recomposition of every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Flowable.onErrorReturn] or [Flowable.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava3.samples.FlowableSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Suppress("UPPER_BOUND_VIOLATED_BASED_ON_JAVA_ANNOTATIONS") @Composable fun <R, T : R> Flowable<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Single] and represents its value via [State]. Once the value would be * posted into the [Single] the returned [State] will be updated causing recomposition of * every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Single.onErrorReturn] or [Single.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava3.samples.SingleSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Suppress("UPPER_BOUND_VIOLATED_BASED_ON_JAVA_ANNOTATIONS") @Composable fun <R, T : R> Single<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Maybe] and represents its value via [State]. Once the value would be * posted into the [Maybe] the returned [State] will be updated causing recomposition of * every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Maybe.onErrorComplete], [Maybe.onErrorReturn] or [Maybe.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava3.samples.MaybeSample * * @param initial The initial value for the returned [State] which will be asynchronously updated * with the real one once we receive it from the stream */ @Composable fun <R, T : R> Maybe<T>.subscribeAsState(initial: R): State<R> = asState(initial) { subscribe(it) } /** * Subscribes to this [Completable] and represents its completed state via [State]. Once the * [Completable] will be completed the returned [State] will be updated with `true` value * causing recomposition of every [State.value] usage. * * The internal observer will be automatically disposed when this composable disposes. * * Note that errors are not handled and the default [RxJavaPlugins.onError] logic will be * used. To handle the error in a more meaningful way you can use operators like * [Completable.onErrorComplete] or [Completable.onErrorResumeNext]. * * @sample androidx.compose.runtime.rxjava3.samples.CompletableSample */ @Composable fun Completable.subscribeAsState(): State<Boolean> = asState(false) { callback -> subscribe { callback(true) } } @Composable private inline fun <T, S> S.asState( initial: T, crossinline subscribe: S.((T) -> Unit) -> Disposable ): State<T> { val state = remember { mutableStateOf(initial) } DisposableEffect(this) { val disposable = subscribe { state.value = it } onDispose { disposable.dispose() } } return state }
apache-2.0
8f9334561b74fd5cf3ce2e75ece9edc4
41.303448
97
0.753791
4.180641
false
false
false
false
pedroSG94/rtmp-rtsp-stream-client-java
rtsp/src/main/java/com/pedro/rtsp/utils/Extensions.kt
1
1636
/* * Copyright (C) 2021 pedroSG94. * * 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.pedro.rtsp.utils import android.util.Base64 import java.nio.ByteBuffer fun ByteArray.encodeToString(flags: Int = Base64.NO_WRAP): String { return Base64.encodeToString(this, flags) } fun ByteBuffer.getData(): ByteArray { val startCodeSize = this.getVideoStartCodeSize() val bytes = ByteArray(this.capacity() - startCodeSize) this.position(startCodeSize) this.get(bytes, 0, bytes.size) return bytes } fun ByteArray.setLong(n: Long, begin: Int, end: Int) { var value = n for (i in end - 1 downTo begin step 1) { this[i] = (value % 256).toByte() value = value shr 8 } } fun ByteBuffer.getVideoStartCodeSize(): Int { var startCodeSize = 0 if (this.get(0).toInt() == 0x00 && this.get(1).toInt() == 0x00 && this.get(2).toInt() == 0x00 && this.get(3).toInt() == 0x01) { //match 00 00 00 01 startCodeSize = 4 } else if (this.get(0).toInt() == 0x00 && this.get(1).toInt() == 0x00 && this.get(2).toInt() == 0x01) { //match 00 00 01 startCodeSize = 3 } return startCodeSize }
apache-2.0
20635b792b18475fa75ad550fb4a59bd
29.314815
75
0.687042
3.373196
false
false
false
false
minecraft-dev/MinecraftDev
src/main/kotlin/nbt/tags/TagEnd.kt
1
569
/* * Minecraft Dev for IntelliJ * * https://minecraftdev.org * * Copyright (c) 2022 minecraft-dev * * MIT License */ package com.demonwav.mcdev.nbt.tags import java.io.DataOutputStream object TagEnd : NbtTag { override val payloadSize = 0 override val typeId = NbtTypeId.END override fun write(stream: DataOutputStream) {} override fun toString() = toString(StringBuilder(), 0, WriterState.COMPOUND).toString() override fun toString(sb: StringBuilder, indentLevel: Int, writerState: WriterState) = sb override fun copy() = this }
mit
e46ee03f59da2ace9ba23b8d4b68373b
20.884615
93
0.710018
4.035461
false
false
false
false
bjzhou/Coolapk
app/src/main/kotlin/bjzhou/coolapk/app/model/Comment.kt
1
1990
package bjzhou.coolapk.app.model /** * Created by bjzhou on 14-8-7. */ class Comment { var id: Long = 0 //694703 var uid: Long = 0 //311581 var forwardid: Int = 0 //0 var username: String? = null //\u6cdb\u6cdb var type: Int = 0 //9 var ttype: String? = null //apk var tid: Int = 0 //3504 var ttitle: String? = null //PPTV var tpic: String? = null //http; //\/\/image.coolapk.com\/apk_logo\/2013\/0126\/com.pplive.androidphone.png var turl: String? = null //\/apk\/com.pplive.androidphone var tinfo: String? = null //4.0.0 var messagelength: Int = 0 //18 var message: String? = null //4.0.0VIP\u7248\uff0c\u90a3\u4f4d\u9ad8\u624b\u5c3d\u663e\u795e\u901a //pic; // var issummary: Int = 0 //0 var istag: Int = 0 //0 //tags; // //videothumb; // //videourl; // var fromid: Int = 0 //3504 var fromname: String? = null //\u9177\u5e02\u573a var ip: String? = null //113.57.190.18 var likenum: Int = 0 //0 var replynum: Int = 0 //3 var forwardnum: Int = 0 //0 var reportnum: Int = 0 //0 var recommend: Int = 0 //0 var status: Int = 0 //1 var dateline: Long = 0 //1406832065 var lastupdate: Long = 0 //1406868014 var feedUrl: String? = null //\/feed\/694703 //linkTarget; // var title: String = "" //\u6cdb\u6cdb \u6765\u81ea\u5e94\u7528 PPTV \u7684\u8bc4\u8bba var info: String? = null //\u6765\u81ea\u5e94\u7528 <a href=\u0022\/apk\/com.pplive.androidphone\u0022>PPTV<\/a> \u7684\u8bc4\u8bba //pics; //[] var replyRowsCount: Int = 0 //3 var replyRowsMore: Int = 0 //0 var queryTid: Int = 0 //3504 var queryCid: Int = 0 //0 var queryPage: Int = 0 //1 var fromtype: String? = null //apk //fromtitle; // //frompic; // //fromurl; // //userurl; // var useravatar: String? = null //http; //\/\/avatar.coolapk.com\/avatar.php?uid=311581&type=virtual&size=small //from; // var subrows: List<Reply>? = null }
gpl-2.0
5a0f7883d94306a0bef728b680b6faf1
33.912281
135
0.598492
2.696477
false
false
false
false
inorichi/tachiyomi-extensions
src/ru/desu/src/eu/kanade/tachiyomi/extension/ru/desu/DesuActivity.kt
1
1364
package eu.kanade.tachiyomi.extension.ru.desu import android.app.Activity import android.content.ActivityNotFoundException import android.content.Intent import android.os.Bundle import android.util.Log import kotlin.system.exitProcess /** * Springboard that accepts https://desu.me/manga/xxx intents and redirects them to * the main tachiyomi process. The idea is to not install the intent filter unless * you have this extension installed, but still let the main tachiyomi app control * things. */ class DesuActivity : Activity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val pathSegments = intent?.data?.pathSegments if (pathSegments != null && pathSegments.size > 1) { val titleid = pathSegments[1] val mainIntent = Intent().apply { action = "eu.kanade.tachiyomi.SEARCH" putExtra("query", "${Desu.PREFIX_SLUG_SEARCH}$titleid") putExtra("filter", packageName) } try { startActivity(mainIntent) } catch (e: ActivityNotFoundException) { Log.e("DesuActivity", e.toString()) } } else { Log.e("DesuActivity", "could not parse uri from intent $intent") } finish() exitProcess(0) } }
apache-2.0
d8d3c7b9991c217145527f1f7776be0c
33.1
83
0.638563
4.623729
false
false
false
false
android/views-widgets-samples
ConstraintLayoutExamples/motionlayout/src/main/java/com/google/androidstudio/motionlayoutexample/fragmentsdemo/FragmentExampleActivity.kt
1
3988
/* * Copyright (C) 2018 The Android Open Source Project * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.androidstudio.motionlayoutexample.fragmentsdemo import android.os.Bundle import android.view.View import androidx.appcompat.app.AppCompatActivity import androidx.constraintlayout.motion.widget.MotionLayout import androidx.constraintlayout.motion.widget.MotionScene import androidx.fragment.app.Fragment import com.google.androidstudio.motionlayoutexample.R import kotlinx.android.synthetic.main.main_activity.* class FragmentExampleActivity : AppCompatActivity(), View.OnClickListener, MotionLayout.TransitionListener { private var lastProgress = 0f private var fragment : Fragment? = null private var last : Float = 0f override fun onTransitionChange(p0: MotionLayout?, p1: Int, p2: Int, p3: Float) { if (p3 - lastProgress > 0) { // from start to end val atEnd = Math.abs(p3 - 1f) < 0.1f if (atEnd && fragment is MainFragment) { val transaction = supportFragmentManager.beginTransaction() transaction .setCustomAnimations(R.animator.show, 0) fragment = SecondFragment.newInstance().also { transaction .setCustomAnimations(R.animator.show, 0) .replace(R.id.container, it) .commitNow() } } } else { // from end to start val atStart = p3 < 0.9f if (atStart && fragment is SecondFragment) { val transaction = supportFragmentManager.beginTransaction() transaction .setCustomAnimations(0, R.animator.hide) fragment = MainFragment.newInstance().also { transaction .replace(R.id.container, it) .commitNow() } } } lastProgress = p3 } override fun onTransitionTrigger(p0: MotionLayout?, p1: Int, p2: Boolean, p3: Float) { } override fun onTransitionStarted(p0: MotionLayout?, p1: Int, p2: Int) { } override fun onTransitionCompleted(p0: MotionLayout?, p1: Int) { } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.main_activity) if (savedInstanceState == null) { fragment = MainFragment.newInstance().also { supportFragmentManager.beginTransaction() .replace(R.id.container, it) .commitNow() } } motionLayout.setTransitionListener(this) } override fun onClick(view: View?) { if (view?.id == R.id.toggle) { val transaction = supportFragmentManager.beginTransaction() fragment = if (fragment == null || fragment is MainFragment) { last = 1f transaction .setCustomAnimations(R.animator.show, 0) SecondFragment.newInstance() } else { transaction .setCustomAnimations(0, R.animator.hide) MainFragment.newInstance() }.also { transaction .replace(R.id.container, it) .commitNow() } } } }
apache-2.0
a0093add67d9e15d0ee108eb38df0ade
36.271028
108
0.596038
5.01005
false
false
false
false
westnordost/osmagent
app/src/main/java/de/westnordost/streetcomplete/quests/railway_crossing/AddRailwayCrossingBarrier.kt
1
943
package de.westnordost.streetcomplete.quests.railway_crossing import de.westnordost.streetcomplete.R import de.westnordost.streetcomplete.data.osm.SimpleOverpassQuestType import de.westnordost.streetcomplete.data.osm.changes.StringMapChangesBuilder import de.westnordost.streetcomplete.data.osm.download.OverpassMapDataDao class AddRailwayCrossingBarrier(o: OverpassMapDataDao) : SimpleOverpassQuestType<String>(o) { override val tagFilters = "nodes with railway=level_crossing and !crossing:barrier" override val commitMessage = "Add type of barrier for railway crossing" override val icon = R.drawable.ic_quest_railway override fun getTitle(tags: Map<String, String>) = R.string.quest_railway_crossing_barrier_title override fun createForm() = AddRailwayCrossingBarrierForm() override fun applyAnswerTo(answer: String, changes: StringMapChangesBuilder) { changes.add("crossing:barrier", answer) } }
gpl-3.0
f483d83118598af9e47dc9c5277ba635
43.904762
100
0.800636
4.555556
false
false
false
false
rhdunn/xquery-intellij-plugin
src/lang-xquery/main/uk/co/reecedunn/intellij/plugin/xquery/psi/impl/plugin/PluginUsingDeclPsiImpl.kt
1
2173
/* * Copyright (C) 2019-2021 Reece H. Dunn * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package uk.co.reecedunn.intellij.plugin.xquery.psi.impl.plugin import com.intellij.extapi.psi.ASTWrapperPsiElement import com.intellij.lang.ASTNode import com.intellij.psi.PsiElement import uk.co.reecedunn.intellij.plugin.core.sequences.children import uk.co.reecedunn.intellij.plugin.xdm.types.XdmNode import uk.co.reecedunn.intellij.plugin.xdm.types.XsAnyUriValue import uk.co.reecedunn.intellij.plugin.xdm.types.XsNCNameValue import uk.co.reecedunn.intellij.plugin.xdm.types.XsQNameValue import uk.co.reecedunn.intellij.plugin.xpm.lang.validation.XpmSyntaxValidationElement import uk.co.reecedunn.intellij.plugin.xpm.optree.namespace.XdmNamespaceType import uk.co.reecedunn.intellij.plugin.xquery.ast.plugin.PluginUsingDecl class PluginUsingDeclPsiImpl(node: ASTNode) : ASTWrapperPsiElement(node), PluginUsingDecl, XpmSyntaxValidationElement { // region XdmNamespaceNode override val namespacePrefix: XsNCNameValue? get() = children().filterIsInstance<XsQNameValue>().firstOrNull()?.localName override val namespaceUri: XsAnyUriValue? get() = children().filterIsInstance<XsAnyUriValue>().firstOrNull() override val parentNode: XdmNode? = null // endregion // region XpmNamespaceDeclaration override fun accepts(namespaceType: XdmNamespaceType): Boolean { return namespaceType === XdmNamespaceType.DefaultFunctionRef // Usage only, not declaration. } // endregion // region XpmSyntaxValidationElement override val conformanceElement: PsiElement get() = firstChild // endregion }
apache-2.0
97984f0d55116792d89fbd6c6c92c1ff
38.509091
119
0.774045
4.398785
false
false
false
false
database-rider/database-rider
rider-examples/rider-kotlin/src/test/kotlin/com/github/trks1970/H2JPAConfig.kt
1
2558
package com.github.trks1970 import org.hibernate.boot.model.naming.CamelCaseToUnderscoresNamingStrategy import org.hibernate.cfg.AvailableSettings import org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy import org.springframework.context.annotation.Bean import org.springframework.data.jpa.repository.config.EnableJpaRepositories import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseBuilder import org.springframework.jdbc.datasource.embedded.EmbeddedDatabaseType import org.springframework.orm.jpa.JpaTransactionManager import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter import org.springframework.transaction.PlatformTransactionManager import org.springframework.transaction.annotation.EnableTransactionManagement import java.util.Properties import javax.persistence.EntityManagerFactory import javax.sql.DataSource @EnableJpaRepositories @EnableTransactionManagement class H2JPAConfig { @Bean fun dataSource(): DataSource { val builder = EmbeddedDatabaseBuilder() return builder .setType(EmbeddedDatabaseType.H2) .setName("testdb;DATABASE_TO_UPPER=false") .build() } @Bean fun entityManagerFactory(): LocalContainerEntityManagerFactoryBean { val vendorAdapter = HibernateJpaVendorAdapter() val factory = LocalContainerEntityManagerFactoryBean() factory.jpaVendorAdapter = vendorAdapter factory.setPackagesToScan("com.github.trks1970") factory.persistenceUnitName = "test" factory.dataSource = dataSource() factory.setJpaProperties(hibernateProperties()) return factory } @Bean fun transactionManager(entityManagerFactory: EntityManagerFactory?): PlatformTransactionManager { val txManager = JpaTransactionManager() txManager.entityManagerFactory = entityManagerFactory return txManager } private fun hibernateProperties(): Properties { val properties = Properties() properties[AvailableSettings.DIALECT] = org.hibernate.dialect.H2Dialect::class.qualifiedName properties["javax.persistence.schema-generation.database.action"] = "drop-and-create" properties[AvailableSettings.PHYSICAL_NAMING_STRATEGY] = CamelCaseToUnderscoresNamingStrategy::class.qualifiedName properties[AvailableSettings.IMPLICIT_NAMING_STRATEGY] = SpringImplicitNamingStrategy::class.qualifiedName return properties } }
apache-2.0
cfbfd16b0359abb73acbaf6b6c7f9b3e
43.103448
122
0.786943
5.105788
false
false
false
false
WillowChat/Hopper
src/main/kotlin/chat/willow/hopper/routes/connection/ConnectionStopRouteHandler.kt
1
1934
package chat.willow.hopper.routes.connection import chat.willow.hopper.connections.IHopperConnections import chat.willow.hopper.logging.loggerFor import chat.willow.hopper.routes.* import chat.willow.hopper.routes.shared.EmptyBody import chat.willow.hopper.routes.shared.ErrorResponseBody import chat.willow.hopper.websocket.IWebSocketUserTracker import chat.willow.hopper.websocket.messages.ConnectionStopped import com.squareup.moshi.Moshi import spark.Request data class ConnectionStopContext(val authenticatedContext: AuthenticatedContext, val id: String) { companion object Builder: IContextBuilder<ConnectionStopContext> { override fun build(request: Request): ConnectionStopContext? { val authContext = AuthenticatedContext.Builder.build(request) ?: return null val id = request.params("connection_id") ?: return null return ConnectionStopContext(authContext, id) } } } class ConnectionStopRouteHandler(moshi: Moshi, private val connections: IHopperConnections, private val tracker: IWebSocketUserTracker) : JsonRouteHandler<EmptyBody, EmptyBody, ConnectionStopContext>( EmptyBody, EmptyBody, moshi.stringSerialiser(), ConnectionStopContext.Builder ) { private val LOGGER = loggerFor<ConnectionStopRouteHandler>() override fun handle(request: EmptyBody, context: ConnectionStopContext): RouteResult<EmptyBody, ErrorResponseBody> { LOGGER.info("handling GET /connection/<id>/stop: $request") // todo: sanity check id val server = connections[context.id] ?: return jsonFailure(404, message = "couldn't find a server with id ${context.id}") connections.stop(context.id) tracker.send(ConnectionStopped.Payload(id = context.id), user = context.authenticatedContext.user) return RouteResult.success(value = EmptyBody) } }
isc
0e6913d0709bf77d6d85f0b498cc150f
39.3125
137
0.734747
4.626794
false
false
false
false
jiaminglu/kotlin-native
backend.native/tests/external/codegen/box/reflection/mapping/fakeOverrides/javaFieldGetterSetter.kt
1
664
// TODO: muted automatically, investigate should it be ran for JS or not // IGNORE_BACKEND: JS, NATIVE // WITH_REFLECT // KT-8131 Cannot find backing field in ancestor class via reflection import kotlin.reflect.* import kotlin.reflect.jvm.* open class TestBase { var id = 0L } class TestChild : TestBase() fun box(): String { val property = TestChild::class.memberProperties.first { it.name == "id" } as KMutableProperty<*> if (property.javaField == null) return "Fail: no field" if (property.javaGetter == null) return "Fail: no getter" if (property.javaSetter == null) return "Fail: no setter" return "OK" }
apache-2.0
81ccb1390a2168fb2596612b08e272ae
24.538462
101
0.673193
3.83815
false
true
false
false
StepicOrg/stepic-android
app/src/main/java/org/stepik/android/cache/visited_courses/dao/VisitedCourseDao.kt
2
1131
package org.stepik.android.cache.visited_courses.dao import androidx.room.Dao import androidx.room.Query import androidx.room.Insert import androidx.room.Transaction import androidx.room.OnConflictStrategy import io.reactivex.Completable import io.reactivex.Flowable import org.stepik.android.domain.visited_courses.model.VisitedCourse @Dao abstract class VisitedCourseDao { @Query("SELECT * FROM VisitedCourse ORDER BY id DESC LIMIT 20") abstract fun getVisitedCourses(): Flowable<List<VisitedCourse>> @Query("SELECT COALESCE(MAX(id), 0) FROM VisitedCourse") abstract fun getMaxId(): Long @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun saveVisitedCourses(visitedCourses: List<VisitedCourse>) @Insert(onConflict = OnConflictStrategy.REPLACE) abstract fun saveVisitedCourse(visitedCourse: VisitedCourse) @Query("DELETE FROM VisitedCourse") abstract fun removeVisitedCourses(): Completable @Transaction open fun saveVisitedCourse(courseId: Long) { val id = getMaxId() return saveVisitedCourse(VisitedCourse(id = id + 1, course = courseId)) } }
apache-2.0
3f8fb5f269d41383216a17f82d03f4ad
32.294118
79
0.769231
4.400778
false
false
false
false
spkingr/50-android-kotlin-projects-in-100-days
ProjectTapHoldCounter/app/src/main/java/me/liuqingwen/android/projecttapholdcounter/MainActivity.kt
1
2162
package me.liuqingwen.android.projecttapholdcounter import android.os.Bundle import android.support.v7.app.AppCompatActivity import android.view.Menu import android.view.MenuItem import android.view.MotionEvent import kotlinx.android.synthetic.main.layout_activity_main.* import org.jetbrains.anko.AnkoLogger import org.jetbrains.anko.toast import java.util.* import kotlin.concurrent.timerTask import kotlin.properties.Delegates class MainActivity : AppCompatActivity(), AnkoLogger { private var count by Delegates.observable(0) { _, _, new -> this.labelNumber.text = new.toString() } private var timer:Timer? = null private var countTask:TimerTask? = null override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.layout_activity_main) this.init() } private fun init() { this.buttonTap.setOnLongClickListener { if(this.timer == null || this.countTask == null) { this.timer = Timer() this.countTask = timerTask { runOnUiThread { [email protected] ++ } } } this.timer!!.schedule(this.countTask, 0, 100) true } this.buttonTap.setOnTouchListener { _, motionEvent -> if(motionEvent.action == MotionEvent.ACTION_UP) { this.timer?.cancel() this.timer = null this.countTask?.cancel() this.countTask = null } false } } override fun onCreateOptionsMenu(menu: Menu?): Boolean { this.menuInflater.inflate(R.menu.menu_main, menu) return super.onCreateOptionsMenu(menu) } override fun onOptionsItemSelected(item: MenuItem?): Boolean { when(item?.itemId) { R.id.menuReset -> this.count = 0 else -> this.toast("Error while item selected!") } return super.onOptionsItemSelected(item) } }
mit
f99ca3ed915c5dc2b916331d7b529cec
27.826667
64
0.590194
4.804444
false
false
false
false
CarlosEsco/tachiyomi
core/src/main/java/eu/kanade/tachiyomi/core/preference/PreferenceStore.kt
1
1136
package eu.kanade.tachiyomi.core.preference interface PreferenceStore { fun getString(key: String, defaultValue: String = ""): Preference<String> fun getLong(key: String, defaultValue: Long = 0): Preference<Long> fun getInt(key: String, defaultValue: Int = 0): Preference<Int> fun getFloat(key: String, defaultValue: Float = 0f): Preference<Float> fun getBoolean(key: String, defaultValue: Boolean = false): Preference<Boolean> fun getStringSet(key: String, defaultValue: Set<String> = emptySet()): Preference<Set<String>> fun <T> getObject( key: String, defaultValue: T, serializer: (T) -> String, deserializer: (String) -> T, ): Preference<T> } inline fun <reified T : Enum<T>> PreferenceStore.getEnum( key: String, defaultValue: T, ): Preference<T> { return getObject( key = key, defaultValue = defaultValue, serializer = { it.name }, deserializer = { try { enumValueOf(it) } catch (e: IllegalArgumentException) { defaultValue } }, ) }
apache-2.0
211e5aadcb1142107eb6e292de98e290
26.707317
98
0.610035
4.35249
false
false
false
false
jkcclemens/khttp
src/test/kotlin/khttp/KHttpAsyncHeadSpec.kt
1
2277
/* * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package khttp import khttp.responses.Response import org.awaitility.kotlin.await import org.spekframework.spek2.Spek import org.spekframework.spek2.style.specification.describe import java.util.concurrent.TimeUnit import kotlin.test.assertEquals class KHttpAsyncHeadSpec : Spek({ describe("an async head request") { var error: Throwable? = null var response: Response? = null async.head("https://httpbin.org/get", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the status code") { if (error != null) throw error!! val status = response!!.statusCode it("should be 200") { assertEquals(200, status) } } } describe("an async head request to a redirecting URL") { var error: Throwable? = null var response: Response? = null async.head("https://httpbin.org/redirect/2", onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the status code") { if (error != null) throw error!! val status = response!!.statusCode it("should be 302") { assertEquals(302, status) } } } describe("an async head request to a redirecting URL, specifically allowing redirects") { var error: Throwable? = null var response: Response? = null async.head("https://httpbin.org/redirect/2", allowRedirects = true, onError = { error = this }, onResponse = { response = this }) await.atMost(5, TimeUnit.SECONDS) .until { response != null } context("accessing the status code") { if (error != null) throw error!! val status = response!!.statusCode it("should be 200") { assertEquals(200, status) } } } })
mpl-2.0
75bd92f28c61c1fe06eae49c1f9775e8
34.578125
137
0.592446
4.447266
false
false
false
false
Heiner1/AndroidAPS
app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt
1
6132
package info.nightscout.androidaps.dialogs import android.content.Context import android.os.Bundle import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import com.google.common.base.Joiner import info.nightscout.androidaps.R import info.nightscout.androidaps.activities.ErrorHelperActivity import info.nightscout.androidaps.database.entities.ValueWithUnit import info.nightscout.androidaps.database.entities.UserEntry.Action import info.nightscout.androidaps.database.entities.UserEntry.Sources import info.nightscout.androidaps.databinding.DialogExtendedbolusBinding import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.CommandQueue import info.nightscout.androidaps.interfaces.Constraint import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.configBuilder.ConstraintChecker import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.HtmlHelper import info.nightscout.shared.SafeParse import info.nightscout.androidaps.utils.alertDialogs.OKDialog import info.nightscout.androidaps.extensions.formatColor import info.nightscout.androidaps.utils.ToastUtils import info.nightscout.androidaps.utils.protection.ProtectionCheck import info.nightscout.androidaps.utils.protection.ProtectionCheck.Protection.BOLUS import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.shared.logging.LTag import java.text.DecimalFormat import java.util.* import javax.inject.Inject import kotlin.math.abs class ExtendedBolusDialog : DialogFragmentWithDate() { @Inject lateinit var ctx: Context @Inject lateinit var rh: ResourceHelper @Inject lateinit var constraintChecker: ConstraintChecker @Inject lateinit var commandQueue: CommandQueue @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var uel: UserEntryLogger @Inject lateinit var protectionCheck: ProtectionCheck private var queryingProtection = false private var _binding: DialogExtendedbolusBinding? = null // This property is only valid between onCreateView and onDestroyView. private val binding get() = _binding!! override fun onSaveInstanceState(savedInstanceState: Bundle) { super.onSaveInstanceState(savedInstanceState) savedInstanceState.putDouble("insulin", binding.insulin.value) savedInstanceState.putDouble("duration", binding.duration.value) } override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View { onCreateViewGeneral() _binding = DialogExtendedbolusBinding.inflate(inflater, container, false) return binding.root } override fun onViewCreated(view: View, savedInstanceState: Bundle?) { super.onViewCreated(view, savedInstanceState) val pumpDescription = activePlugin.activePump.pumpDescription val maxInsulin = constraintChecker.getMaxExtendedBolusAllowed().value() val extendedStep = pumpDescription.extendedBolusStep binding.insulin.setParams(savedInstanceState?.getDouble("insulin") ?: extendedStep, extendedStep, maxInsulin, extendedStep, DecimalFormat("0.00"), false, binding.okcancel.ok) val extendedDurationStep = pumpDescription.extendedBolusDurationStep val extendedMaxDuration = pumpDescription.extendedBolusMaxDuration binding.duration.setParams(savedInstanceState?.getDouble("duration") ?: extendedDurationStep, extendedDurationStep, extendedMaxDuration, extendedDurationStep, DecimalFormat("0"), false, binding.okcancel.ok) binding.insulinLabel.labelFor = binding.insulin.editTextId binding.durationLabel.labelFor = binding.duration.editTextId } override fun onDestroyView() { super.onDestroyView() _binding = null } override fun submit(): Boolean { if (_binding == null) return false val insulin = SafeParse.stringToDouble(binding.insulin.text) val durationInMinutes = binding.duration.value.toInt() val actions: LinkedList<String> = LinkedList() val insulinAfterConstraint = constraintChecker.applyExtendedBolusConstraints(Constraint(insulin)).value() actions.add(rh.gs(R.string.formatinsulinunits, insulinAfterConstraint)) actions.add(rh.gs(R.string.duration) + ": " + rh.gs(R.string.format_mins, durationInMinutes)) if (abs(insulinAfterConstraint - insulin) > 0.01) actions.add(rh.gs(R.string.constraintapllied).formatColor(context, rh, R.attr.warningColor)) activity?.let { activity -> OKDialog.showConfirmation(activity, rh.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), { uel.log(Action.EXTENDED_BOLUS, Sources.ExtendedBolusDialog, ValueWithUnit.Insulin(insulinAfterConstraint), ValueWithUnit.Minute(durationInMinutes)) commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() { override fun run() { if (!result.success) { ErrorHelperActivity.runAlarm(ctx, result.comment, rh.gs(R.string.treatmentdeliveryerror), R.raw.boluserror) } } }) }, null) } return true } override fun onResume() { super.onResume() if(!queryingProtection) { queryingProtection = true activity?.let { activity -> val cancelFail = { queryingProtection = false aapsLogger.debug(LTag.APS, "Dialog canceled on resume protection: ${this.javaClass.name}") ToastUtils.showToastInUiThread(ctx, R.string.dialog_canceled) dismiss() } protectionCheck.queryProtection(activity, BOLUS, { queryingProtection = false }, cancelFail, cancelFail) } } } }
agpl-3.0
76dc19763779e7b0a63659dbb9a824cb
46.169231
149
0.723581
5.084577
false
false
false
false
Heiner1/AndroidAPS
automation/src/main/java/info/nightscout/androidaps/plugins/general/automation/actions/ActionRunAutotune.kt
1
4616
package info.nightscout.androidaps.plugins.general.automation.actions import android.widget.LinearLayout import androidx.annotation.DrawableRes import dagger.android.HasAndroidInjector import info.nightscout.androidaps.automation.R import info.nightscout.androidaps.data.PumpEnactResult import info.nightscout.androidaps.interfaces.ActivePlugin import info.nightscout.androidaps.interfaces.Autotune import info.nightscout.androidaps.interfaces.ProfileFunction import info.nightscout.androidaps.interfaces.ResourceHelper import info.nightscout.androidaps.logging.UserEntryLogger import info.nightscout.androidaps.plugins.general.automation.elements.InputDuration import info.nightscout.androidaps.plugins.general.automation.elements.InputProfileName import info.nightscout.androidaps.plugins.general.automation.elements.LabelWithElement import info.nightscout.androidaps.plugins.general.automation.elements.LayoutBuilder import info.nightscout.androidaps.queue.Callback import info.nightscout.androidaps.utils.JsonHelper import info.nightscout.shared.logging.LTag import info.nightscout.shared.sharedPreferences.SP import org.json.JSONObject import javax.inject.Inject class ActionRunAutotune(injector: HasAndroidInjector) : Action(injector) { @Inject lateinit var resourceHelper: ResourceHelper @Inject lateinit var autotunePlugin: Autotune @Inject lateinit var profileFunction: ProfileFunction @Inject lateinit var activePlugin: ActivePlugin @Inject lateinit var sp: SP var defaultValue = 0 private var inputProfileName = InputProfileName(rh, activePlugin, "", true) private var daysBack = InputDuration(0, InputDuration.TimeUnit.DAYS) override fun friendlyName(): Int = R.string.autotune_run override fun shortDescription(): String = resourceHelper.gs(R.string.autotune_profile_name, inputProfileName.value) @DrawableRes override fun icon(): Int = R.drawable.ic_actions_profileswitch override fun doAction(callback: Callback) { val autoSwitch = sp.getBoolean(R.string.key_autotune_auto, false) val profileName = if (inputProfileName.value == rh.gs(R.string.active)) "" else inputProfileName.value var message = if (autoSwitch) R.string.autotune_run_with_autoswitch else R.string.autotune_run_without_autoswitch Thread { if (!autotunePlugin.calculationRunning) { autotunePlugin.atLog("[Automation] Run Autotune $profileName, ${daysBack.value} days, Autoswitch $autoSwitch") autotunePlugin.aapsAutotune(daysBack.value, autoSwitch, profileName) if (!autotunePlugin.lastRunSuccess) { message = R.string.autotune_run_with_error aapsLogger.error(LTag.AUTOMATION, "Error during Autotune Run") } callback.result(PumpEnactResult(injector).success(autotunePlugin.lastRunSuccess).comment(message)).run() } else { message = R.string.autotune_run_cancelled aapsLogger.debug(LTag.AUTOMATION, "Autotune run detected, Autotune Run Cancelled") callback.result(PumpEnactResult(injector).success(false).comment(message)).run() } }.start() return } override fun generateDialog(root: LinearLayout) { if (defaultValue == 0) defaultValue = sp.getInt(R.string.key_autotune_default_tune_days, 5) daysBack.value = defaultValue LayoutBuilder() .add(LabelWithElement(rh, rh.gs(R.string.autotune_select_profile), "", inputProfileName)) .add(LabelWithElement(rh, rh.gs(R.string.autotune_tune_days), "", daysBack)) .build(root) } override fun hasDialog(): Boolean = true override fun toJSON(): String { val data = JSONObject() .put("profileToTune", inputProfileName.value) .put("tunedays", daysBack.value) return JSONObject() .put("type", this.javaClass.name) .put("data", data) .toString() } override fun fromJSON(data: String): Action { val o = JSONObject(data) inputProfileName.value = JsonHelper.safeGetString(o, "profileToTune", "") defaultValue = JsonHelper.safeGetInt(o, "tunedays") if (defaultValue == 0) defaultValue = sp.getInt(R.string.key_autotune_default_tune_days, 5) daysBack.value = defaultValue return this } override fun isValid(): Boolean = profileFunction.getProfile() != null && activePlugin.getSpecificPluginsListByInterface(Autotune::class.java).first().isEnabled() }
agpl-3.0
32705c5d71502246850563feda302b04
47.6
166
0.719021
4.672065
false
false
false
false
PolymerLabs/arcs
src/tools/tests/goldens/generated-schemas.wasm.kt
1
22090
/* ktlint-disable */ @file:Suppress("PackageName", "TopLevelName") package arcs.golden // // GENERATED CODE -- DO NOT EDIT // import arcs.sdk.wasm.* typealias Gold_Data = AbstractGold.Gold_Data typealias Gold_Data_Slice = AbstractGold.Gold_Data_Slice typealias Gold_AllPeople = AbstractGold.Gold_AllPeople typealias Gold_AllPeople_Slice = AbstractGold.Gold_AllPeople_Slice typealias Gold_Alias = AbstractGold.Gold_Alias typealias Gold_Alias_Slice = AbstractGold.Gold_Alias_Slice typealias Gold_Collection = AbstractGold.Foo typealias Gold_Collection_Slice = AbstractGold.FooSlice typealias Gold_QCollection = AbstractGold.Gold_QCollection typealias Gold_QCollection_Slice = AbstractGold.Gold_QCollection_Slice @Generated("src/tools/schema2kotlin.ts") abstract class AbstractGold : WasmParticleImpl() { val handles: Handles = Handles(this) interface Gold_Data_Slice : WasmEntity { val num: Double val txt: String val lnk: String val flg: Boolean } @Suppress("UNCHECKED_CAST") class Gold_Data( num: Double = 0.0, txt: String = "", lnk: String = "", flg: Boolean = false ) : WasmEntity, Gold_Data_Slice { override var num = num get() = field private set(_value) { field = _value } override var txt = txt get() = field private set(_value) { field = _value } override var lnk = lnk get() = field private set(_value) { field = _value } override var flg = flg get() = field private set(_value) { field = _value } override var entityId = "" fun copy( num: Double = this.num, txt: String = this.txt, lnk: String = this.lnk, flg: Boolean = this.flg ) = Gold_Data(num = num, txt = txt, lnk = lnk, flg = flg) fun reset() { num = 0.0 txt = "" lnk = "" flg = false } override fun encodeEntity(): NullTermByteArray { val encoder = StringEncoder() encoder.encode("", entityId) num.let { encoder.encode("num:N", num) } txt.let { encoder.encode("txt:T", txt) } lnk.let { encoder.encode("lnk:U", lnk) } flg.let { encoder.encode("flg:B", flg) } return encoder.toNullTermByteArray() } override fun toString() = "Gold_Data(num = $num, txt = $txt, lnk = $lnk, flg = $flg)" companion object : WasmEntitySpec<Gold_Data> { override fun decode(encoded: ByteArray): Gold_Data? { if (encoded.isEmpty()) return null val decoder = StringDecoder(encoded) val entityId = decoder.decodeText() decoder.validate("|") var num = 0.0 var txt = "" var lnk = "" var flg = false var i = 0 while (i < 4 && !decoder.done()) { val _name = decoder.upTo(':').toUtf8String() when (_name) { "num" -> { decoder.validate("N") num = decoder.decodeNum() } "txt" -> { decoder.validate("T") txt = decoder.decodeText() } "lnk" -> { decoder.validate("U") lnk = decoder.decodeText() } "flg" -> { decoder.validate("B") flg = decoder.decodeBool() } else -> { // Ignore unknown fields until type slicing is fully implemented. when (decoder.chomp(1).toUtf8String()) { "T", "U" -> decoder.decodeText() "N" -> decoder.decodeNum() "B" -> decoder.decodeBool() } i-- } } decoder.validate("|") i++ } val _rtn = Gold_Data().copy( num = num, txt = txt, lnk = lnk, flg = flg ) _rtn.entityId = entityId return _rtn } } } interface Gold_AllPeople_Slice : WasmEntity { val name: String val age: Double val lastCall: Double val address: String val favoriteColor: String val birthDayMonth: Double val birthDayDOM: Double } @Suppress("UNCHECKED_CAST") class Gold_AllPeople( name: String = "", age: Double = 0.0, lastCall: Double = 0.0, address: String = "", favoriteColor: String = "", birthDayMonth: Double = 0.0, birthDayDOM: Double = 0.0 ) : WasmEntity, Gold_AllPeople_Slice { override var name = name get() = field private set(_value) { field = _value } override var age = age get() = field private set(_value) { field = _value } override var lastCall = lastCall get() = field private set(_value) { field = _value } override var address = address get() = field private set(_value) { field = _value } override var favoriteColor = favoriteColor get() = field private set(_value) { field = _value } override var birthDayMonth = birthDayMonth get() = field private set(_value) { field = _value } override var birthDayDOM = birthDayDOM get() = field private set(_value) { field = _value } override var entityId = "" fun copy( name: String = this.name, age: Double = this.age, lastCall: Double = this.lastCall, address: String = this.address, favoriteColor: String = this.favoriteColor, birthDayMonth: Double = this.birthDayMonth, birthDayDOM: Double = this.birthDayDOM ) = Gold_AllPeople( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM ) fun reset() { name = "" age = 0.0 lastCall = 0.0 address = "" favoriteColor = "" birthDayMonth = 0.0 birthDayDOM = 0.0 } override fun encodeEntity(): NullTermByteArray { val encoder = StringEncoder() encoder.encode("", entityId) name.let { encoder.encode("name:T", name) } age.let { encoder.encode("age:N", age) } lastCall.let { encoder.encode("lastCall:N", lastCall) } address.let { encoder.encode("address:T", address) } favoriteColor.let { encoder.encode("favoriteColor:T", favoriteColor) } birthDayMonth.let { encoder.encode("birthDayMonth:N", birthDayMonth) } birthDayDOM.let { encoder.encode("birthDayDOM:N", birthDayDOM) } return encoder.toNullTermByteArray() } override fun toString() = "Gold_AllPeople(name = $name, age = $age, lastCall = $lastCall, address = $address, favoriteColor = $favoriteColor, birthDayMonth = $birthDayMonth, birthDayDOM = $birthDayDOM)" companion object : WasmEntitySpec<Gold_AllPeople> { override fun decode(encoded: ByteArray): Gold_AllPeople? { if (encoded.isEmpty()) return null val decoder = StringDecoder(encoded) val entityId = decoder.decodeText() decoder.validate("|") var name = "" var age = 0.0 var lastCall = 0.0 var address = "" var favoriteColor = "" var birthDayMonth = 0.0 var birthDayDOM = 0.0 var i = 0 while (i < 7 && !decoder.done()) { val _name = decoder.upTo(':').toUtf8String() when (_name) { "name" -> { decoder.validate("T") name = decoder.decodeText() } "age" -> { decoder.validate("N") age = decoder.decodeNum() } "lastCall" -> { decoder.validate("N") lastCall = decoder.decodeNum() } "address" -> { decoder.validate("T") address = decoder.decodeText() } "favoriteColor" -> { decoder.validate("T") favoriteColor = decoder.decodeText() } "birthDayMonth" -> { decoder.validate("N") birthDayMonth = decoder.decodeNum() } "birthDayDOM" -> { decoder.validate("N") birthDayDOM = decoder.decodeNum() } else -> { // Ignore unknown fields until type slicing is fully implemented. when (decoder.chomp(1).toUtf8String()) { "T", "U" -> decoder.decodeText() "N" -> decoder.decodeNum() "B" -> decoder.decodeBool() } i-- } } decoder.validate("|") i++ } val _rtn = Gold_AllPeople().copy( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM ) _rtn.entityId = entityId return _rtn } } } interface Gold_Alias_Slice : WasmEntity { val val_: String } @Suppress("UNCHECKED_CAST") class Gold_Alias(val_: String = "") : WasmEntity, Gold_Alias_Slice { override var val_ = val_ get() = field private set(_value) { field = _value } override var entityId = "" fun copy(val_: String = this.val_) = Gold_Alias(val_ = val_) fun reset() { val_ = "" } override fun encodeEntity(): NullTermByteArray { val encoder = StringEncoder() encoder.encode("", entityId) val_.let { encoder.encode("val:T", val_) } return encoder.toNullTermByteArray() } override fun toString() = "Gold_Alias(val_ = $val_)" companion object : WasmEntitySpec<Gold_Alias> { override fun decode(encoded: ByteArray): Gold_Alias? { if (encoded.isEmpty()) return null val decoder = StringDecoder(encoded) val entityId = decoder.decodeText() decoder.validate("|") var val_ = "" var i = 0 while (i < 1 && !decoder.done()) { val _name = decoder.upTo(':').toUtf8String() when (_name) { "val" -> { decoder.validate("T") val_ = decoder.decodeText() } else -> { // Ignore unknown fields until type slicing is fully implemented. when (decoder.chomp(1).toUtf8String()) { "T", "U" -> decoder.decodeText() "N" -> decoder.decodeNum() "B" -> decoder.decodeBool() } i-- } } decoder.validate("|") i++ } val _rtn = Gold_Alias().copy( val_ = val_ ) _rtn.entityId = entityId return _rtn } } } interface FooSlice : WasmEntity { val num: Double } @Suppress("UNCHECKED_CAST") class Foo(num: Double = 0.0) : WasmEntity, FooSlice { override var num = num get() = field private set(_value) { field = _value } override var entityId = "" fun copy(num: Double = this.num) = Foo(num = num) fun reset() { num = 0.0 } override fun encodeEntity(): NullTermByteArray { val encoder = StringEncoder() encoder.encode("", entityId) num.let { encoder.encode("num:N", num) } return encoder.toNullTermByteArray() } override fun toString() = "Foo(num = $num)" companion object : WasmEntitySpec<Foo> { override fun decode(encoded: ByteArray): Foo? { if (encoded.isEmpty()) return null val decoder = StringDecoder(encoded) val entityId = decoder.decodeText() decoder.validate("|") var num = 0.0 var i = 0 while (i < 1 && !decoder.done()) { val _name = decoder.upTo(':').toUtf8String() when (_name) { "num" -> { decoder.validate("N") num = decoder.decodeNum() } else -> { // Ignore unknown fields until type slicing is fully implemented. when (decoder.chomp(1).toUtf8String()) { "T", "U" -> decoder.decodeText() "N" -> decoder.decodeNum() "B" -> decoder.decodeBool() } i-- } } decoder.validate("|") i++ } val _rtn = Foo().copy( num = num ) _rtn.entityId = entityId return _rtn } } } interface Gold_QCollection_Slice : Gold_AllPeople_Slice { } @Suppress("UNCHECKED_CAST") class Gold_QCollection( name: String = "", age: Double = 0.0, lastCall: Double = 0.0, address: String = "", favoriteColor: String = "", birthDayMonth: Double = 0.0, birthDayDOM: Double = 0.0 ) : WasmEntity, Gold_QCollection_Slice { override var name = name get() = field private set(_value) { field = _value } override var age = age get() = field private set(_value) { field = _value } override var lastCall = lastCall get() = field private set(_value) { field = _value } override var address = address get() = field private set(_value) { field = _value } override var favoriteColor = favoriteColor get() = field private set(_value) { field = _value } override var birthDayMonth = birthDayMonth get() = field private set(_value) { field = _value } override var birthDayDOM = birthDayDOM get() = field private set(_value) { field = _value } override var entityId = "" fun copy( name: String = this.name, age: Double = this.age, lastCall: Double = this.lastCall, address: String = this.address, favoriteColor: String = this.favoriteColor, birthDayMonth: Double = this.birthDayMonth, birthDayDOM: Double = this.birthDayDOM ) = Gold_QCollection( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM ) fun reset() { name = "" age = 0.0 lastCall = 0.0 address = "" favoriteColor = "" birthDayMonth = 0.0 birthDayDOM = 0.0 } override fun encodeEntity(): NullTermByteArray { val encoder = StringEncoder() encoder.encode("", entityId) name.let { encoder.encode("name:T", name) } age.let { encoder.encode("age:N", age) } lastCall.let { encoder.encode("lastCall:N", lastCall) } address.let { encoder.encode("address:T", address) } favoriteColor.let { encoder.encode("favoriteColor:T", favoriteColor) } birthDayMonth.let { encoder.encode("birthDayMonth:N", birthDayMonth) } birthDayDOM.let { encoder.encode("birthDayDOM:N", birthDayDOM) } return encoder.toNullTermByteArray() } override fun toString() = "Gold_QCollection(name = $name, age = $age, lastCall = $lastCall, address = $address, favoriteColor = $favoriteColor, birthDayMonth = $birthDayMonth, birthDayDOM = $birthDayDOM)" companion object : WasmEntitySpec<Gold_QCollection> { override fun decode(encoded: ByteArray): Gold_QCollection? { if (encoded.isEmpty()) return null val decoder = StringDecoder(encoded) val entityId = decoder.decodeText() decoder.validate("|") var name = "" var age = 0.0 var lastCall = 0.0 var address = "" var favoriteColor = "" var birthDayMonth = 0.0 var birthDayDOM = 0.0 var i = 0 while (i < 7 && !decoder.done()) { val _name = decoder.upTo(':').toUtf8String() when (_name) { "name" -> { decoder.validate("T") name = decoder.decodeText() } "age" -> { decoder.validate("N") age = decoder.decodeNum() } "lastCall" -> { decoder.validate("N") lastCall = decoder.decodeNum() } "address" -> { decoder.validate("T") address = decoder.decodeText() } "favoriteColor" -> { decoder.validate("T") favoriteColor = decoder.decodeText() } "birthDayMonth" -> { decoder.validate("N") birthDayMonth = decoder.decodeNum() } "birthDayDOM" -> { decoder.validate("N") birthDayDOM = decoder.decodeNum() } else -> { // Ignore unknown fields until type slicing is fully implemented. when (decoder.chomp(1).toUtf8String()) { "T", "U" -> decoder.decodeText() "N" -> decoder.decodeNum() "B" -> decoder.decodeBool() } i-- } } decoder.validate("|") i++ } val _rtn = Gold_QCollection().copy( name = name, age = age, lastCall = lastCall, address = address, favoriteColor = favoriteColor, birthDayMonth = birthDayMonth, birthDayDOM = birthDayDOM ) _rtn.entityId = entityId return _rtn } } } class Handles( particle: WasmParticleImpl ) { val data: WasmSingletonImpl<Gold_Data> = WasmSingletonImpl<Gold_Data>(particle, "data", Gold_Data) val allPeople: WasmCollectionImpl<Gold_AllPeople> = WasmCollectionImpl<Gold_AllPeople>(particle, "allPeople", Gold_AllPeople) val qCollection: WasmCollectionImpl<Gold_QCollection> = WasmCollectionImpl<Gold_QCollection>(particle, "qCollection", Gold_QCollection) val alias: WasmSingletonImpl<Gold_Alias> = WasmSingletonImpl<Gold_Alias>(particle, "alias", Gold_Alias) val collection: WasmCollectionImpl<Foo> = WasmCollectionImpl<Foo>(particle, "collection", Foo) } }
bsd-3-clause
378267e3b7b21fd626a0c339f27c5a12
31.970149
190
0.442961
5.03648
false
false
false
false
suntabu/MoonRover
src/main/kotlin/suntabu/moonrover/simulateObj/controlCenter.kt
1
1968
package suntabu.moonrover.simulateObj import suntabu.moonrover.CONTROL_INTERVAL import suntabu.moonrover.models.Message import suntabu.moonrover.utils.Vector2 import java.io.File /** * Created by gouzhun on 2017/2/10. */ class ControlCenter() { var roversInfo: MutableMap<Int, MutableList<Message>> = mutableMapOf() var printInfos:MutableMap<Int,PrintInfo> = mutableMapOf() fun startup() { val runnable = Runnable { while (true) { //println("send a message") roversInfo.forEach { // println("Rover ${it.key} run at ${it.value.last()}" ) predictRover(it.value.last()) } Thread.sleep(CONTROL_INTERVAL) } } Thread(runnable).start() } fun receivedMessage(msg: Message) { if (roversInfo.containsKey(msg.fromId)) { var list = roversInfo[msg.fromId] if (list == null) { list = mutableListOf() } list.add(msg) } roversInfo.put(msg.fromId, mutableListOf(msg)) } fun predictRover(msg:Message){ var pi:PrintInfo? if (printInfos.containsKey(msg.fromId)){ pi = printInfos[msg.fromId] }else{ pi = PrintInfo() pi?.id = msg.fromId printInfos.put(msg.fromId,pi) } pi?.reportPos = msg.pos pi?.direction= Vector2.from(msg.speed,msg.angle) pi?.predictPos = msg.pos + pi?.direction!! * ((System.currentTimeMillis() - msg.time)/1000f) println("Rover " +pi?.id + "\t\t\treport pos: " + pi?.reportPos + "\t\t\tpredictPos: " + pi?.predictPos + "\t\t\tdirection: " + pi?.direction) } } class PrintInfo{ var id:Int = 0 var reportPos:Vector2 = Vector2() var predictPos:Vector2 = Vector2() var direction :Vector2 = Vector2() }
apache-2.0
e16fa1de8097ad1f413d1fdaa32e2749
24.558442
100
0.553862
3.836257
false
false
false
false
Maccimo/intellij-community
platform/lang-impl/src/com/intellij/ui/AsyncImageIcon.kt
4
3805
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.ui import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.ScalableIcon import com.intellij.ui.icons.CopyableIcon import com.intellij.ui.scale.ScaleContext import com.intellij.util.IconUtil import com.intellij.util.concurrency.EdtExecutorService import com.intellij.util.ui.StartupUiUtil import org.jetbrains.annotations.ApiStatus import java.awt.Component import java.awt.Graphics import java.awt.Image import java.awt.Rectangle import java.util.concurrent.CompletableFuture import javax.swing.Icon /** * Provide a way to show [Image] loaded in background as [Icon] * Icon size will be taken from placeholder [defaultIcon] and should be loaded and scaled to size with [imageLoader] * This implementation takes all scales into account * * @see [ScalingDeferredSquareImageIcon] * if it is better for the case to use single thread shared with all [DeferredIconImpl] instances to load the [Image] * */ @ApiStatus.Experimental class AsyncImageIcon( defaultIcon: Icon, private val scale: Float = 1.0f, private val imageLoader: (ScaleContext, Int, Int) -> CompletableFuture<Image?> ) : Icon, ScalableIcon, CopyableIcon { private val defaultIcon = IconUtil.scale(defaultIcon, null, scale) private val repaintScheduler = RepaintScheduler() // Icon can be located on different monitors (with different ScaleContext), // so it is better to cache image for each private val imageRequestsCache = ScaleContext.Cache { scaleCtx -> imageLoader(scaleCtx, iconWidth, iconHeight).also { it.thenRunAsync({ repaintScheduler.scheduleRepaint(iconWidth, iconHeight) }, EdtExecutorService.getInstance()) } } override fun getIconHeight() = defaultIcon.iconHeight override fun getIconWidth() = defaultIcon.iconWidth override fun paintIcon(c: Component?, g: Graphics, x: Int, y: Int) { val imageRequest = imageRequestsCache.getOrProvide(ScaleContext.create(c))!! if (!imageRequest.isDone && c != null) { repaintScheduler.requestRepaint(c, x, y) } val image = try { imageRequest.getNow(null) } catch (error: Throwable) { LOG.debug("Image loading failed", error) null } if (image == null) { defaultIcon.paintIcon(c, g, x, y) } else { val bounds = Rectangle(x, y, iconWidth, iconHeight) StartupUiUtil.drawImage(g, image, bounds, c) } } override fun copy(): Icon = AsyncImageIcon(defaultIcon, scale, imageLoader) override fun getScale(): Float = scale override fun scale(scaleFactor: Float): Icon = AsyncImageIcon(defaultIcon, scaleFactor, imageLoader) companion object { private val LOG = logger<AsyncImageIcon>() } } private class RepaintScheduler { // We collect repaintRequests for the icon to understand which Components should be repainted when icon is loaded // We can receive paintIcon few times for the same component but with different x, y // Only the last request should be scheduled private val repaintRequests = mutableMapOf<Component, DeferredIconRepaintScheduler.RepaintRequest>() fun requestRepaint(c: Component, x: Int, y: Int) { repaintRequests[c] = repaintScheduler.createRepaintRequest(c, x, y) } fun scheduleRepaint(width: Int, height: Int) { for ((_, repaintRequest) in repaintRequests) { repaintScheduler.scheduleRepaint(repaintRequest, width, height, alwaysSchedule = false) } repaintRequests.clear() } companion object { // Scheduler for all DelegatingIcon instances. It repaints components that contain these icons in a batch private val repaintScheduler = DeferredIconRepaintScheduler() } }
apache-2.0
c064646a69df74df60df99c153802681
35.247619
158
0.745598
4.309173
false
false
false
false
just-4-fun/holomorph
src/main/kotlin/just4fun/holomorph/types/map.kt
1
2565
package just4fun.holomorph.types import just4fun.holomorph.* import just4fun.kotlinkit.Result import just4fun.holomorph.forms.MapConsumer import just4fun.holomorph.forms.MapProvider /* MAP */ open class MapType<K: Any, V: Any>(val keyType: Type<K>, val valueType: Type<V>): Type<MutableMap<*, *>>, Producer<MutableMap<*, *>>, EntryHelperDefault<MutableMap<*, *>> { override val typeKlas = MutableMap::class override val typeName: String get() = "${typeKlas.simpleName}<${keyType.typeName},${valueType.typeName}>" open fun nameToKey(name: String) = keyType.fromEntry(name) open fun keyToName(key: K) = key.toString() override fun newInstance() = mutableMapOf<K, V>() override fun asInstance(v: Any): MutableMap<*, *>? = when (v) { is Map<*, *> -> v as? MutableMap<*, *> else -> evalError(v, this) } @Suppress("UNCHECKED_CAST") override fun equal(v1: MutableMap<*, *>?, v2: MutableMap<*, *>?): Boolean { return v1 === v2 || (v1 != null && v2 != null && v1.size == v2.size && run { v1.entries.all { entry -> v2.containsKey(entry.key) && valueType.equal(entry.value as V, v2[entry.key] as V) } }) } @Suppress("UNCHECKED_CAST") override fun copy(v: MutableMap<*, *>?, deep: Boolean) = if (!deep || v == null) v else { val m = newInstance() as MutableMap<Any, Any?> v.forEach { entry -> m[entry.key as Any] = valueType.copy(entry.value as? V, deep) } m } @Suppress("UNCHECKED_CAST") override fun toString(v: MutableMap<*, *>?, sequenceSizeLimit: Int): String { return if (v == null) "null" else v.map { e -> "${e.key}=${valueType.toString(e.value as? V, sequenceSizeLimit)}" }.joinToString(",", "{", "}", sequenceSizeLimit) } override fun <D: Any> instanceFrom(input: D, factory: EntryProviderFactory<D>): Result<MutableMap<*, *>> = Produce(factory(input), MapConsumer(this)) override fun <D: Any> instanceTo(input: MutableMap<*, *>, factory: EntryConsumerFactory<D>): Result<D> = Produce(MapProvider(input, this), factory()) override fun fromEntries(subEntries: EnclosedEntries, expectNames: Boolean): MutableMap<*, *>? { return if (expectNames) subEntries.intercept(MapConsumer(this, false)) else null } override fun toEntry(value: MutableMap<*, *>, name: String?, entryBuilder: EntryBuilder): Entry { return entryBuilder.StartEntry(name, true, MapProvider(value, this, false)) } override fun toString() = typeName override fun hashCode(): Int = typeKlas.hashCode() + keyType.typeKlas.hashCode() * 31 + valueType.typeKlas.hashCode() * 31 override fun equals(other: Any?) = this === other }
apache-2.0
5e576cab00b0795bbcd57f690591547a
41.766667
172
0.682651
3.47561
false
false
false
false
micolous/metrodroid
src/commonTest/kotlin/au/id/micolous/metrodroid/test/ISO7816Test.kt
1
1929
/* * ISO7816Test.kt * * Copyright 2018 Michael Farrell <[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 au.id.micolous.metrodroid.test import au.id.micolous.metrodroid.card.iso7816.ISO7816Card import au.id.micolous.metrodroid.serializers.JsonKotlinFormat import au.id.micolous.metrodroid.transit.mobib.MobibTransitData import kotlin.test.Test import kotlin.test.assertEquals class ISO7816Test : CardReaderWithAssetDumpsTest(JsonKotlinFormat) { @Test fun testIso7816Card() = runAsync { // Load up a Mobib card that is basically empty val card = loadCard<ISO7816Card>("iso7816/mobib_blank.json") val cardIso7816 = card.iso7816!! // Environment check assertEquals(MobibTransitData.NAME, card.parseTransitIdentity()?.name) // Load the card into the emulator val vcard = VirtualISO7816Card(card) // Try to dump the tag from the emulator val rcard = ISO7816Card.dumpTag(vcard, MockFeedbackInterface.get()) // Check that we got an expected number of applications assertEquals(cardIso7816.applications.size, rcard.applications.size) assertEquals(cardIso7816, rcard) val identity = rcard.parseTransitIdentity() assertEquals(MobibTransitData.NAME, identity?.name) } }
gpl-3.0
5af7a8063fbe227a6a1e0d86248688ab
37.58
78
0.733022
4.130621
false
true
false
false
micolous/metrodroid
src/commonTest/kotlin/au/id/micolous/metrodroid/test/FarebotJsonTest.kt
1
1890
/* * FarebotJsonTest.kt * * Copyright 2019 Google * * 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 au.id.micolous.metrodroid.test import au.id.micolous.metrodroid.card.cepascompat.CEPASCard import au.id.micolous.metrodroid.multi.Log import au.id.micolous.metrodroid.serializers.JsonKotlinFormat import au.id.micolous.metrodroid.serializers.AutoJsonFormat import au.id.micolous.metrodroid.transit.TransitCurrency import au.id.micolous.metrodroid.transit.ezlinkcompat.EZLinkCompatTransitData import kotlin.test.Test import kotlin.test.assertEquals /** * Contains tests for the Farebot Json format. */ class FarebotJsonTest : CardReaderWithAssetDumpsTest(AutoJsonFormat) { @Test fun testFarebotJson() { val cards = importer.readCards(loadAsset("farebot/farebot.json")) var ctr = 0 for (card in cards!!) { val json = JsonKotlinFormat.writeCard(card) Log.d("FarebotJsonTest", "reserial[$ctr] = " + json) val expected = loadSmallAssetBytes("farebot/metrodroid_$ctr.json") assertEquals<String>(expected = String(expected).trim(), actual = json.toString().trim(), message = "Wrong reserialization for card $ctr") ctr++ } } }
gpl-3.0
f5933cb51fe28f1f5dd660860b27070f
38.375
78
0.710053
4.090909
false
true
false
false
square/picasso
picasso-sample/src/main/java/com/example/picasso/SampleListDetailAdapter.kt
1
2273
/* * Copyright (C) 2022 Square, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.example.picasso import android.content.Context import android.view.LayoutInflater import android.view.View import android.view.ViewGroup import android.widget.BaseAdapter import android.widget.ImageView import android.widget.TextView internal class SampleListDetailAdapter(private val context: Context) : BaseAdapter() { private val layoutInflater = LayoutInflater.from(context) private val urls = Data.URLS.toList() override fun getView( position: Int, view: View?, parent: ViewGroup ): View { val newView: View val holder: ViewHolder if (view == null) { newView = layoutInflater.inflate(R.layout.sample_list_detail_item, parent, false) holder = ViewHolder( image = newView.findViewById(R.id.photo), text = newView.findViewById(R.id.url) ) newView.tag = holder } else { newView = view holder = newView.tag as ViewHolder } // Get the image URL for the current position. val url = getItem(position) holder.text.text = url // Trigger the download of the URL asynchronously into the image view. PicassoInitializer.get() .load(url) .placeholder(R.drawable.placeholder) .error(R.drawable.error) .resizeDimen(R.dimen.list_detail_image_size, R.dimen.list_detail_image_size) .centerInside() .tag(context) .into(holder.image) return newView } override fun getCount(): Int = urls.size override fun getItem(position: Int): String = urls[position] override fun getItemId(position: Int): Long = position.toLong() internal class ViewHolder( val image: ImageView, val text: TextView ) }
apache-2.0
aac2294cbc5793f77bd9bd9d37126048
28.907895
87
0.704355
4.140255
false
false
false
false
iMeiji/Daily
app/src/main/java/com/meiji/daily/data/local/converter/ZhuanlanBeanConverter.kt
1
1516
package com.meiji.daily.data.local.converter import android.arch.persistence.room.TypeConverter import com.meiji.daily.bean.ZhuanlanBean import com.squareup.moshi.JsonAdapter import com.squareup.moshi.Moshi import com.squareup.moshi.Types /** * Created by Meiji on 2017/11/28. */ class ZhuanlanBeanConverter { private val mMoshi = Moshi.Builder().build() private val mCreatorAdapter: JsonAdapter<ZhuanlanBean.Creator> private var mAvatarAdapter: JsonAdapter<ZhuanlanBean.Avatar> private var mTopicAdapter: JsonAdapter<List<ZhuanlanBean.Topic>> init { mCreatorAdapter = mMoshi.adapter(ZhuanlanBean.Creator::class.java) mAvatarAdapter = mMoshi.adapter(ZhuanlanBean.Avatar::class.java) val type = Types.newParameterizedType(List::class.java, ZhuanlanBean.Topic::class.java) mTopicAdapter = mMoshi.adapter<List<ZhuanlanBean.Topic>>(type) } @TypeConverter fun fromCreator(c: ZhuanlanBean.Creator): String = mCreatorAdapter.toJson(c) @TypeConverter fun toCreator(s: String): ZhuanlanBean.Creator = mCreatorAdapter.fromJson(s)!! @TypeConverter fun fromTopicList(l: List<ZhuanlanBean.Topic>): String = mTopicAdapter.toJson(l) @TypeConverter fun toTopicList(s: String): List<ZhuanlanBean.Topic> = mTopicAdapter.fromJson(s)!! @TypeConverter fun fromAvatar(a: ZhuanlanBean.Avatar): String = mAvatarAdapter.toJson(a) @TypeConverter fun toAvatar(s: String): ZhuanlanBean.Avatar = mAvatarAdapter.fromJson(s)!! }
apache-2.0
d467b546b4ddef291ad30fa3c3d004f2
32.688889
95
0.748681
3.887179
false
false
false
false
florent37/Flutter-AssetsAudioPlayer
android/src/main/kotlin/com/github/florent37/assets_audio_player/notification/NotificationService.kt
1
15522
package com.github.florent37.assets_audio_player.notification import android.app.Notification import android.app.NotificationChannel import android.app.PendingIntent import android.app.Service import android.content.Context import android.content.Intent import android.content.pm.PackageManager import android.graphics.Bitmap import android.media.MediaMetadata import android.os.Build import android.os.IBinder import android.support.v4.media.MediaMetadataCompat import android.support.v4.media.session.PlaybackStateCompat import android.support.v4.media.session.PlaybackStateCompat.ACTION_SEEK_TO import androidx.core.app.NotificationCompat import androidx.core.app.NotificationManagerCompat import androidx.media.session.MediaButtonReceiver import com.github.florent37.assets_audio_player.R import com.google.android.exoplayer2.C import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.GlobalScope import kotlinx.coroutines.launch import kotlin.math.abs import android.app.PendingIntent.FLAG_UPDATE_CURRENT import android.app.PendingIntent.FLAG_IMMUTABLE class NotificationService : Service() { companion object { const val NOTIFICATION_ID = 1 const val CHANNEL_ID = "assets_audio_player" const val MEDIA_SESSION_TAG = "assets_audio_player" const val EXTRA_PLAYER_ID = "playerId" const val EXTRA_NOTIFICATION_ACTION = "notificationAction" const val TRACK_ID = "trackID"; const val manifestIcon = "assets.audio.player.notification.icon" const val manifestIconPlay = "assets.audio.player.notification.icon.play" const val manifestIconPause = "assets.audio.player.notification.icon.pause" const val manifestIconPrev = "assets.audio.player.notification.icon.prev" const val manifestIconNext = "assets.audio.player.notification.icon.next" const val manifestIconStop = "assets.audio.player.notification.icon.stop" private var stateCompat : PlaybackStateCompat? = null fun timeDiffer(old: PlaybackStateCompat?, new: PlaybackStateCompat, minDifferenceMS: Long) : Boolean { if(old == null){ return true } val currentPos = old.position return abs(new.position - currentPos) > minDifferenceMS } fun updatePosition(context: Context, isPlaying: Boolean, currentPositionMs: Long, speed: Float) { MediaButtonsReceiver.getMediaSessionCompat(context).let { mediaSession -> val state = if (isPlaying) PlaybackStateCompat.STATE_PLAYING else PlaybackStateCompat.STATE_PAUSED val newState = PlaybackStateCompat.Builder() .setActions(ACTION_SEEK_TO) .setState(state, currentPositionMs, if (isPlaying) speed else 0f) .build() if( //pause -> play, play-> pause stateCompat?.state != newState.state || //speed changed stateCompat?.playbackSpeed != speed || //seek timeDiffer(stateCompat, newState, 2000) ){ stateCompat = newState mediaSession.setPlaybackState(stateCompat) } } } private fun MediaMetadataCompat.Builder.putStringIfNotNull(key: String, value: String?) : MediaMetadataCompat.Builder { return if(value != null) this.putString(key, value) else this } fun updateNotifMetaData(context: Context, display: Boolean, durationMs: Long, title: String? = null, artist: String? = null, album: String? = null ) { val mediaSession = MediaButtonsReceiver.getMediaSessionCompat(context) if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { val builder = MediaMetadataCompat.Builder() //for samsung devices https://github.com/florent37/Flutter-AssetsAudioPlayer/issues/205 .putStringIfNotNull(MediaMetadata.METADATA_KEY_TITLE, title) .putStringIfNotNull(MediaMetadata.METADATA_KEY_ARTIST, artist) .putStringIfNotNull(MediaMetadata.METADATA_KEY_ALBUM, album) if (!display || durationMs == 0L /* livestream */) { builder.putLong(MediaMetadata.METADATA_KEY_DURATION, C.TIME_UNSET) } else { builder.putLong(MediaMetadata.METADATA_KEY_DURATION, durationMs) } mediaSession.setMetadata(builder.build()) } } } override fun onStartCommand(intent: Intent, flags: Int, startId: Int): Int { if (intent.action == Intent.ACTION_MEDIA_BUTTON) { MediaButtonsReceiver.getMediaSessionCompat(applicationContext).let { MediaButtonReceiver.handleIntent(it, intent) } } when (val notificationAction = intent.getSerializableExtra(EXTRA_NOTIFICATION_ACTION)) { is NotificationAction.Show -> { displayNotification(notificationAction) } is NotificationAction.Hide -> { hideNotif() } } return START_NOT_STICKY } private fun createReturnIntent(forAction: String, forPlayer: String, audioMetas: AudioMetas): Intent { return Intent(this, NotificationActionReceiver::class.java) .setAction(forAction) .putExtra(EXTRA_PLAYER_ID, forPlayer) .putExtra(TRACK_ID, audioMetas.trackID) } private fun displayNotification(action: NotificationAction.Show) { GlobalScope.launch(Dispatchers.Main) { val image = ImageDownloader.loadBitmap(context = applicationContext, imageMetas = action.audioMetas.image) if(image != null){ displayNotification(action, image) //display without image for now return@launch } val imageOnLoadError = ImageDownloader.loadBitmap(context = applicationContext, imageMetas = action.audioMetas.imageOnLoadError) if(imageOnLoadError != null){ displayNotification(action, imageOnLoadError) //display without image for now return@launch } val imageFromManifest = ImageDownloader.loadHolderBitmapFromManifest(context = applicationContext) if(imageFromManifest != null){ displayNotification(action, imageFromManifest) //display without image for now return@launch } displayNotification(action, null) //display without image } } private fun getSmallIcon(context: Context): Int { return getCustomIconOrDefault(context, manifestIcon, null, R.drawable.exo_icon_circular_play) } private fun getPlayIcon(context: Context, resourceName: String?): Int { return getCustomIconOrDefault(context, manifestIconPlay, resourceName, R.drawable.exo_icon_play) } private fun getPauseIcon(context: Context, resourceName: String?): Int { return getCustomIconOrDefault(context, manifestIconPause, resourceName, R.drawable.exo_icon_pause) } private fun getNextIcon(context: Context, resourceName: String?): Int { return getCustomIconOrDefault(context, manifestIconNext, resourceName, R.drawable.exo_icon_next) } private fun getPrevIcon(context: Context, resourceName: String?): Int { return getCustomIconOrDefault(context, manifestIconPrev, resourceName, R.drawable.exo_icon_previous) } private fun getStopIcon(context: Context, resourceName: String?): Int { return getCustomIconOrDefault(context, manifestIconStop, resourceName, R.drawable.exo_icon_stop) } private fun getCustomIconOrDefault(context: Context, manifestName: String, resourceName: String?, defaultIcon: Int): Int { try { // by resource name val customIconFromName = getResourceID(resourceName) if (customIconFromName != null) { return customIconFromName } //by manifest val appInfos = context.packageManager.getApplicationInfo(context.packageName, PackageManager.GET_META_DATA) val customIconFromManifest = appInfos.metaData.get(manifestName) as? Int if (customIconFromManifest != null) { return customIconFromManifest } } catch (t: Throwable) { //print(t) } //if customIconFromName is null or customIconFromManifest is null return defaultIcon } private fun getResourceID(iconName: String?): Int? { return iconName?.let { name -> resources.getIdentifier(name, "drawable", applicationContext.packageName) } } private fun displayNotification(action: NotificationAction.Show, bitmap: Bitmap?) { createNotificationChannel() val mediaSession = MediaButtonsReceiver.getMediaSessionCompat(applicationContext) val notificationSettings = action.notificationSettings updateNotifMetaData( context = applicationContext, display = notificationSettings.seekBarEnabled, title = action.audioMetas.title, artist = action.audioMetas.artist, album = action.audioMetas.album, durationMs = action.durationMs ) val toggleIntent = createReturnIntent(forAction = NotificationAction.ACTION_TOGGLE, forPlayer = action.playerId, audioMetas = action.audioMetas) .putExtra(EXTRA_NOTIFICATION_ACTION, action.copyWith( isPlaying = !action.isPlaying )) val pendingToggleIntent = PendingIntent.getBroadcast(this, 0, toggleIntent, FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT) MediaButtonReceiver.handleIntent(mediaSession, toggleIntent) val context = this val notification = NotificationCompat.Builder(this, CHANNEL_ID) //prev .apply { if (notificationSettings.prevEnabled) { addAction(getPrevIcon(context, action.notificationSettings.previousIcon), "prev", PendingIntent.getBroadcast(context, 0, createReturnIntent(forAction = NotificationAction.ACTION_PREV, forPlayer = action.playerId, audioMetas = action.audioMetas), FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT) ) } } //play/pause .apply { if (notificationSettings.playPauseEnabled) { addAction( if (action.isPlaying) getPauseIcon(context, action.notificationSettings.pauseIcon) else getPlayIcon(context, action.notificationSettings.playIcon), if (action.isPlaying) "pause" else "play", pendingToggleIntent ) } } //next .apply { if (notificationSettings.nextEnabled) { addAction(getNextIcon(context, action.notificationSettings.nextIcon), "next", PendingIntent.getBroadcast(context, 0, createReturnIntent(forAction = NotificationAction.ACTION_NEXT, forPlayer = action.playerId, audioMetas = action.audioMetas), FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT) ) } } //stop .apply { if (notificationSettings.stopEnabled) { addAction(getStopIcon(context, action.notificationSettings.stopIcon), "stop", PendingIntent.getBroadcast(context, 0, createReturnIntent(forAction = NotificationAction.ACTION_STOP, forPlayer = action.playerId, audioMetas = action.audioMetas), FLAG_IMMUTABLE or FLAG_UPDATE_CURRENT) ) } } .setStyle(androidx.media.app.NotificationCompat.MediaStyle() .also { when (notificationSettings.numberEnabled()) { 1 -> it.setShowActionsInCompactView(0) 2 -> it.setShowActionsInCompactView(0, 1) 3 -> it.setShowActionsInCompactView(0, 1, 2) 4 -> it.setShowActionsInCompactView(0, 1, 2, 3) else -> it.setShowActionsInCompactView() } } .setShowCancelButton(true) .setMediaSession(mediaSession.sessionToken) ) .setSmallIcon(getSmallIcon(context)) .setVisibility(NotificationCompat.VISIBILITY_PUBLIC) .setPriority(NotificationCompat.PRIORITY_MAX) .setContentTitle(action.audioMetas.title) .setContentText(action.audioMetas.artist) .setOnlyAlertOnce(true) .also { if (!action.audioMetas.album.isNullOrEmpty()) { it.setSubText(action.audioMetas.album) } } .setContentIntent(PendingIntent.getBroadcast(this, 0, createReturnIntent(forAction = NotificationAction.ACTION_SELECT, forPlayer = action.playerId, audioMetas = action.audioMetas), FLAG_IMMUTABLE or PendingIntent.FLAG_CANCEL_CURRENT)) .also { if (bitmap != null) { it.setLargeIcon(bitmap) } } .setShowWhen(false) .build() startForeground(NOTIFICATION_ID, notification) //fix for https://github.com/florent37/Flutter-AssetsAudioPlayer/issues/139 if (!action.isPlaying && Build.VERSION.SDK_INT >= 24) { stopForeground(2) } } private fun createNotificationChannel() { if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { val serviceChannel = NotificationChannel( CHANNEL_ID, "Foreground Service Channel", android.app.NotificationManager.IMPORTANCE_LOW ).apply { description = "assets_audio_player" setShowBadge(false) lockscreenVisibility = Notification.VISIBILITY_PUBLIC } NotificationManagerCompat.from(applicationContext).createNotificationChannel( serviceChannel ) } } private fun hideNotif() { NotificationManagerCompat.from(applicationContext).cancel(NOTIFICATION_ID) stopForeground(true) stopSelf() } override fun onTaskRemoved(rootIntent: Intent) { hideNotif() } override fun onCreate() { super.onCreate() } override fun onBind(intent: Intent?): IBinder? { return null } override fun onDestroy() { super.onDestroy() } }
apache-2.0
36c74ab1800a8e5610b7c02fa7a98431
42.723944
234
0.605334
5.350569
false
false
false
false
GunoH/intellij-community
plugins/markdown/core/src/org/intellij/plugins/markdown/ui/MarkdownNotifications.kt
7
1754
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.intellij.plugins.markdown.ui import com.intellij.notification.NotificationGroupManager import com.intellij.notification.NotificationType import com.intellij.openapi.project.Project import com.intellij.openapi.util.NlsContexts import org.jetbrains.annotations.NonNls /** * Use these methods for creating and firing notifications instead of manually obtaining notification group. */ internal object MarkdownNotifications { val group get() = requireNotNull(NotificationGroupManager.getInstance().getNotificationGroup("Markdown")) fun showError( project: Project?, id: @NonNls String?, @NlsContexts.NotificationTitle title: String = "", @NlsContexts.NotificationContent message: String ) { val notification = group.createNotification(title, message, NotificationType.ERROR) id?.let { notification.setDisplayId(it) } notification.notify(project) } fun showWarning( project: Project?, id: @NonNls String?, @NlsContexts.NotificationTitle title: String = "", @NlsContexts.NotificationContent message: String ) { val notification = group.createNotification(title, message, NotificationType.WARNING) id?.let { notification.setDisplayId(it) } notification.notify(project) } fun showInfo( project: Project?, id: @NonNls String?, @NlsContexts.NotificationTitle title: String = "", @NlsContexts.NotificationContent message: String ) { val notification = group.createNotification(title, message, NotificationType.INFORMATION) id?.let { notification.setDisplayId(it) } notification.notify(project) } }
apache-2.0
f9fe0677e34848056d99b65bada916f4
34.795918
140
0.754276
4.766304
false
false
false
false
GunoH/intellij-community
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/bridgeEntities/roots.kt
1
9385
// 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.bridgeEntities import com.intellij.workspaceModel.storage.* import com.intellij.workspaceModel.storage.EntitySource import com.intellij.workspaceModel.storage.GeneratedCodeApiVersion import com.intellij.workspaceModel.storage.MutableEntityStorage import com.intellij.workspaceModel.storage.WorkspaceEntity import com.intellij.workspaceModel.storage.impl.containers.toMutableWorkspaceList import com.intellij.workspaceModel.storage.url.VirtualFileUrl import org.jetbrains.deft.ObjBuilder import org.jetbrains.deft.Type import org.jetbrains.deft.annotations.Child interface ContentRootEntity : WorkspaceEntity { val module: ModuleEntity @EqualsBy val url: VirtualFileUrl val excludedUrls: List<@Child ExcludeUrlEntity> val excludedPatterns: List<String> val sourceRoots: List<@Child SourceRootEntity> @Child val sourceRootOrder: SourceRootOrderEntity? //region generated code @GeneratedCodeApiVersion(1) interface Builder : ContentRootEntity, WorkspaceEntity.Builder<ContentRootEntity>, ObjBuilder<ContentRootEntity> { override var entitySource: EntitySource override var module: ModuleEntity override var url: VirtualFileUrl override var excludedUrls: List<ExcludeUrlEntity> override var excludedPatterns: MutableList<String> override var sourceRoots: List<SourceRootEntity> override var sourceRootOrder: SourceRootOrderEntity? } companion object : Type<ContentRootEntity, Builder>() { operator fun invoke(url: VirtualFileUrl, excludedPatterns: List<String>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): ContentRootEntity { val builder = builder() builder.url = url builder.excludedPatterns = excludedPatterns.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: ContentRootEntity, modification: ContentRootEntity.Builder.() -> Unit) = modifyEntity( ContentRootEntity.Builder::class.java, entity, modification) //endregion val ExcludeUrlEntity.contentRoot: ContentRootEntity? by WorkspaceEntity.extension() interface SourceRootEntity : WorkspaceEntity { val contentRoot: ContentRootEntity val url: VirtualFileUrl val rootType: String @Child val customSourceRootProperties: CustomSourceRootPropertiesEntity? val javaSourceRoots: List<@Child JavaSourceRootPropertiesEntity> val javaResourceRoots: List<@Child JavaResourceRootPropertiesEntity> //region generated code @GeneratedCodeApiVersion(1) interface Builder : SourceRootEntity, WorkspaceEntity.Builder<SourceRootEntity>, ObjBuilder<SourceRootEntity> { override var entitySource: EntitySource override var contentRoot: ContentRootEntity override var url: VirtualFileUrl override var rootType: String override var customSourceRootProperties: CustomSourceRootPropertiesEntity? override var javaSourceRoots: List<JavaSourceRootPropertiesEntity> override var javaResourceRoots: List<JavaResourceRootPropertiesEntity> } companion object : Type<SourceRootEntity, Builder>() { operator fun invoke(url: VirtualFileUrl, rootType: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SourceRootEntity { val builder = builder() builder.url = url builder.rootType = rootType builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: SourceRootEntity, modification: SourceRootEntity.Builder.() -> Unit) = modifyEntity( SourceRootEntity.Builder::class.java, entity, modification) //endregion interface SourceRootOrderEntity : WorkspaceEntity { val contentRootEntity: ContentRootEntity val orderOfSourceRoots: List<VirtualFileUrl> //region generated code @GeneratedCodeApiVersion(1) interface Builder : SourceRootOrderEntity, WorkspaceEntity.Builder<SourceRootOrderEntity>, ObjBuilder<SourceRootOrderEntity> { override var entitySource: EntitySource override var contentRootEntity: ContentRootEntity override var orderOfSourceRoots: MutableList<VirtualFileUrl> } companion object : Type<SourceRootOrderEntity, Builder>() { operator fun invoke(orderOfSourceRoots: List<VirtualFileUrl>, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): SourceRootOrderEntity { val builder = builder() builder.orderOfSourceRoots = orderOfSourceRoots.toMutableWorkspaceList() builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: SourceRootOrderEntity, modification: SourceRootOrderEntity.Builder.() -> Unit) = modifyEntity( SourceRootOrderEntity.Builder::class.java, entity, modification) //endregion interface CustomSourceRootPropertiesEntity: WorkspaceEntity { val sourceRoot: SourceRootEntity val propertiesXmlTag: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : CustomSourceRootPropertiesEntity, WorkspaceEntity.Builder<CustomSourceRootPropertiesEntity>, ObjBuilder<CustomSourceRootPropertiesEntity> { override var entitySource: EntitySource override var sourceRoot: SourceRootEntity override var propertiesXmlTag: String } companion object : Type<CustomSourceRootPropertiesEntity, Builder>() { operator fun invoke(propertiesXmlTag: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): CustomSourceRootPropertiesEntity { val builder = builder() builder.propertiesXmlTag = propertiesXmlTag builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: CustomSourceRootPropertiesEntity, modification: CustomSourceRootPropertiesEntity.Builder.() -> Unit) = modifyEntity( CustomSourceRootPropertiesEntity.Builder::class.java, entity, modification) //endregion interface JavaSourceRootPropertiesEntity : WorkspaceEntity { val sourceRoot: SourceRootEntity val generated: Boolean val packagePrefix: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : JavaSourceRootPropertiesEntity, WorkspaceEntity.Builder<JavaSourceRootPropertiesEntity>, ObjBuilder<JavaSourceRootPropertiesEntity> { override var entitySource: EntitySource override var sourceRoot: SourceRootEntity override var generated: Boolean override var packagePrefix: String } companion object : Type<JavaSourceRootPropertiesEntity, Builder>() { operator fun invoke(generated: Boolean, packagePrefix: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): JavaSourceRootPropertiesEntity { val builder = builder() builder.generated = generated builder.packagePrefix = packagePrefix builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: JavaSourceRootPropertiesEntity, modification: JavaSourceRootPropertiesEntity.Builder.() -> Unit) = modifyEntity( JavaSourceRootPropertiesEntity.Builder::class.java, entity, modification) //endregion interface JavaResourceRootPropertiesEntity: WorkspaceEntity { val sourceRoot: SourceRootEntity val generated: Boolean val relativeOutputPath: String //region generated code @GeneratedCodeApiVersion(1) interface Builder : JavaResourceRootPropertiesEntity, WorkspaceEntity.Builder<JavaResourceRootPropertiesEntity>, ObjBuilder<JavaResourceRootPropertiesEntity> { override var entitySource: EntitySource override var sourceRoot: SourceRootEntity override var generated: Boolean override var relativeOutputPath: String } companion object : Type<JavaResourceRootPropertiesEntity, Builder>() { operator fun invoke(generated: Boolean, relativeOutputPath: String, entitySource: EntitySource, init: (Builder.() -> Unit)? = null): JavaResourceRootPropertiesEntity { val builder = builder() builder.generated = generated builder.relativeOutputPath = relativeOutputPath builder.entitySource = entitySource init?.invoke(builder) return builder } } //endregion } //region generated code fun MutableEntityStorage.modifyEntity(entity: JavaResourceRootPropertiesEntity, modification: JavaResourceRootPropertiesEntity.Builder.() -> Unit) = modifyEntity( JavaResourceRootPropertiesEntity.Builder::class.java, entity, modification) //endregion
apache-2.0
abf88a986fc2a9212eec920c9782cf9c
37.150407
161
0.741289
5.913674
false
false
false
false
GunoH/intellij-community
platform/platform-impl/src/com/intellij/openapi/application/impl/ExpirableExecutorImpl.kt
8
2512
// 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.application.impl import com.intellij.openapi.Disposable import com.intellij.openapi.application.ExpirableExecutor import com.intellij.openapi.application.constraints.ConstrainedExecution.ContextConstraint import com.intellij.openapi.application.constraints.Expiration import kotlinx.coroutines.async import kotlinx.coroutines.launch import kotlinx.coroutines.withContext import java.util.concurrent.Executor import java.util.function.BooleanSupplier import kotlin.coroutines.ContinuationInterceptor import kotlin.coroutines.CoroutineContext internal class ExpirableExecutorImpl private constructor(constraints: Array<ContextConstraint>, cancellationConditions: Array<BooleanSupplier>, expirableHandles: Set<Expiration>, private val executor: Executor) : ExpirableExecutor, BaseExpirableExecutorMixinImpl<ExpirableExecutorImpl>(constraints, cancellationConditions, expirableHandles, executor) { constructor (executor: Executor) : this(emptyArray(), emptyArray(), emptySet(), executor) override fun cloneWith(constraints: Array<ContextConstraint>, cancellationConditions: Array<BooleanSupplier>, expirationSet: Set<Expiration>): ExpirableExecutorImpl = ExpirableExecutorImpl(constraints, cancellationConditions, expirationSet, executor) override fun dispatchLaterUnconstrained(runnable: Runnable) = executor.execute(runnable) } fun ExpirableExecutor.withConstraint(constraint: ContextConstraint): ExpirableExecutor = (this as ExpirableExecutorImpl).withConstraint(constraint) fun ExpirableExecutor.withConstraint(constraint: ContextConstraint, parentDisposable: Disposable): ExpirableExecutor = (this as ExpirableExecutorImpl).withConstraint(constraint, parentDisposable) /** * A [context][CoroutineContext] to be used with the standard [launch], [async], [withContext] coroutine builders. * Contains: [ContinuationInterceptor]. */ @Suppress("DeprecatedCallableAddReplaceWith") @Deprecated(message = "Do not use: coroutine cancellation must not be handled by a dispatcher.") fun ExpirableExecutor.coroutineDispatchingContext(): ContinuationInterceptor = (this as ExpirableExecutorImpl).asCoroutineDispatcher()
apache-2.0
40b51dffc80c718d7e054c04c57d8af2
53.608696
143
0.763535
5.607143
false
false
false
false
GunoH/intellij-community
plugins/kotlin/project-wizard/idea/src/org/jetbrains/kotlin/tools/projectWizard/IntelliJKotlinNewProjectWizard.kt
3
3901
// 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.tools.projectWizard import com.intellij.ide.JavaUiBundle import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logAddSampleCodeChanged import com.intellij.ide.projectWizard.NewProjectWizardCollector.BuildSystem.logSdkChanged import com.intellij.ide.projectWizard.NewProjectWizardConstants.BuildSystem.INTELLIJ import com.intellij.ide.projectWizard.generators.AssetsNewProjectWizardStep import com.intellij.ide.starters.local.StandardAssetsProvider import com.intellij.ide.wizard.AbstractNewProjectWizardStep import com.intellij.ide.wizard.GitNewProjectWizardData.Companion.gitData import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.name import com.intellij.ide.wizard.NewProjectWizardBaseData.Companion.path import com.intellij.ide.wizard.NewProjectWizardStep import com.intellij.ide.wizard.chain import com.intellij.openapi.module.StdModuleTypes import com.intellij.openapi.observable.util.bindBooleanStorage import com.intellij.openapi.project.Project import com.intellij.openapi.projectRoots.JavaSdkType import com.intellij.openapi.projectRoots.Sdk import com.intellij.openapi.projectRoots.SdkTypeId import com.intellij.openapi.projectRoots.impl.DependentSdkType import com.intellij.openapi.roots.ui.configuration.sdkComboBox import com.intellij.ui.UIBundle.* import com.intellij.ui.dsl.builder.* import org.jetbrains.kotlin.tools.projectWizard.plugins.buildSystem.BuildSystemType internal class IntelliJKotlinNewProjectWizard : BuildSystemKotlinNewProjectWizard { override val name = INTELLIJ override val ordinal = 0 override fun createStep(parent: KotlinNewProjectWizard.Step) = Step(parent).chain(::AssetsStep) class Step(parent: KotlinNewProjectWizard.Step) : AbstractNewProjectWizardStep(parent), BuildSystemKotlinNewProjectWizardData by parent { private val sdkProperty = propertyGraph.property<Sdk?>(null) private val addSampleCodeProperty = propertyGraph.property(true) .bindBooleanStorage("NewProjectWizard.addSampleCodeState") private val sdk by sdkProperty private val addSampleCode by addSampleCodeProperty override fun setupUI(builder: Panel) { with(builder) { row(JavaUiBundle.message("label.project.wizard.new.project.jdk")) { val sdkTypeFilter = { it: SdkTypeId -> it is JavaSdkType && it !is DependentSdkType } sdkComboBox(context, sdkProperty, StdModuleTypes.JAVA.id, sdkTypeFilter) .columns(COLUMNS_MEDIUM) .whenItemSelectedFromUi { logSdkChanged(sdk) } } row { checkBox(message("label.project.wizard.new.project.add.sample.code")) .bindSelected(addSampleCodeProperty) .whenStateChangedFromUi { logAddSampleCodeChanged(it) } }.topGap(TopGap.SMALL) kmpWizardLink(context) } } override fun setupProject(project: Project) = KotlinNewProjectWizard.generateProject( project = project, projectPath = "$path/$name", projectName = name, sdk = sdk, buildSystemType = BuildSystemType.Jps, addSampleCode = addSampleCode ) } private class AssetsStep(parent: NewProjectWizardStep) : AssetsNewProjectWizardStep(parent) { override fun setupAssets(project: Project) { outputDirectory = "$path/$name" if (gitData?.git == true) { addAssets(StandardAssetsProvider().getIntelliJIgnoreAssets()) } } } }
apache-2.0
8f654b392370d4a94587d8b5acf9b92b
45.452381
158
0.717508
5.236242
false
false
false
false
zsmb13/KotlinVerbalExpressions
src/main/kotlin/co/zsmb/verbalexpressions/VerEx.kt
1
4327
package co.zsmb.verbalexpressions import java.util.regex.Pattern class VerEx { companion object { private val symbols = mapOf( 'd' to Pattern.UNIX_LINES, 'i' to Pattern.CASE_INSENSITIVE, 'x' to Pattern.COMMENTS, 'm' to Pattern.MULTILINE, 's' to Pattern.DOTALL, 'u' to Pattern.UNICODE_CASE, 'U' to Pattern.UNICODE_CHARACTER_CLASS ) } private var prefixes = StringBuilder() private var source = StringBuilder() private var suffixes = StringBuilder() private var modifiers = Pattern.MULTILINE //// COMPUTED PROPERTIES //// val pattern: Pattern get() = Pattern.compile("$prefixes$source$suffixes", modifiers) //// TESTS //// fun test(toTest: String?) = if (toTest == null) false else pattern.matcher(toTest).find() fun testExact(toTest: String?) = if (toTest == null) false else pattern.matcher(toTest).matches() //// COMPOSITION //// fun startOfLine(enabled: Boolean = true): VerEx { prefixes = StringBuilder(if (enabled) "^" else "") return this } fun endOfLine(enabled: Boolean = true): VerEx { suffixes = StringBuilder(if (enabled) "$" else "") return this } fun find(str: String) = then(str) fun then(str: String) = add("(?:${sanitize(str)})") fun maybe(str: String) = add("(?:${sanitize(str)})?") fun anything() = add("(?:.*)") fun anythingBut(str: String) = add("(?:[^${sanitize(str)}]*)") fun something() = add("(?:.+)") fun somethingBut(str: String) = add("(?:[^${sanitize(str)}]+)") fun lineBreak() = add("""(?:(?:\n)|(?:\r\n))""") fun br() = lineBreak() fun tab() = add("""\t""") fun word() = add("""\w+""") fun anyOf(str: String) = add("(?:[${sanitize(str)}])") fun any(str: String) = anyOf(str) fun withAnyCase(enabled: Boolean = true) = updateModifier('i', enabled) fun searchOneLine(enabled: Boolean = true) = updateModifier('m', !enabled) fun or(str: String): VerEx { prefixes.append("(") source.append(")|(").append(str).append(")").append(suffixes) suffixes = StringBuilder() return this } fun multiple(str: String, min: Int? = null, max: Int? = null): VerEx { then(str) return times(min ?: 1, max) } fun times(min: Int, max: Int? = null): VerEx { if (max != null && min > max) { throw IllegalArgumentException("Min count ($min) can't be less than max count ($max).") } return add("{$min,${max ?: ""}}") } fun exactly(count: Int) = times(count, count) fun atLeast(min: Int) = times(min) fun replace(source: String, replacement: String): String = pattern.matcher(source).replaceAll(replacement) fun range(vararg args: Pair<Any, Any>) = add(args.joinToString(prefix = "[", postfix = "]", separator = "") { "${it.first}-${it.second}" }) fun beginCapture() = add("(") fun endCapture() = add(")") fun whiteSpace() = add("""\s""") fun oneOrMore() = add("+") fun zeroOrMore() = add("*") fun addModifier(modifier: Char): VerEx { symbols[modifier]?.let { modifiers = modifiers or it } return this } fun removeModifier(modifier: Char): VerEx { symbols[modifier]?.let { modifiers = modifiers and it.inv() } return this } fun addModifier(modifier: String): VerEx { if (modifier.length != 1) { throw IllegalArgumentException("Modifier has to be a single character") } return addModifier(modifier[0]) } fun removeModifier(modifier: String): VerEx { if (modifier.length != 1) { throw IllegalArgumentException("Modifier has to be a single character") } return removeModifier(modifier[0]) } //// PRIVATE HELPERS //// private fun add(str: String): VerEx { source.append(str) return this } private fun sanitize(str: String) = str.replace("[\\W]".toRegex(), """\\$0""") private fun updateModifier(modifier: Char, enabled: Boolean) = if (enabled) addModifier(modifier) else removeModifier(modifier) }
mit
c4a96db86e24d510ed20e848efe224fd
26.56051
110
0.565981
4.176641
false
true
false
false
himikof/intellij-rust
src/test/kotlin/org/rust/cargo/runconfig/producers/RunConfigurationProducerTest.kt
1
13944
/* * Use of this source code is governed by the MIT license that can be * found in the LICENSE file. */ package org.rust.cargo.runconfig.producers import com.intellij.execution.RunManager import com.intellij.execution.actions.ConfigurationContext import com.intellij.execution.actions.RunConfigurationProducer import com.intellij.execution.configurations.ConfigurationTypeUtil import com.intellij.openapi.application.ApplicationInfo import com.intellij.openapi.application.ApplicationManager import com.intellij.openapi.util.JDOMUtil import com.intellij.psi.PsiElement import com.intellij.testFramework.LightProjectDescriptor import org.assertj.core.api.Assertions.assertThat import org.jdom.Element import org.rust.cargo.project.workspace.CargoProjectWorkspaceService import org.rust.cargo.project.workspace.CargoWorkspace import org.rust.cargo.project.workspace.impl.CargoProjectWorkspaceServiceImpl import org.rust.cargo.runconfig.command.CargoCommandConfiguration import org.rust.cargo.runconfig.command.CargoCommandConfigurationType import org.rust.cargo.runconfig.command.CargoExecutableRunConfigurationProducer import org.rust.cargo.runconfig.test.CargoTestRunConfigurationProducer import org.rust.cargo.toolchain.impl.CleanCargoMetadata import org.rust.lang.RsTestBase import org.rust.lang.core.psi.RsFile import org.rust.lang.core.psi.RsFunction import org.rust.lang.core.psi.ext.RsMod import org.rust.lang.core.psi.ext.parentOfType class RunConfigurationProducerTest : RsTestBase() { override val dataPath: String get() { val info = ApplicationInfo.getInstance() // BACKCOMPAT: 2017.1 // HACK: IDEA 2017.2 produces a little bit different configuration xml // so fixtures for 2017.1 were moved into separate folder val compatibilityFolder = if (info.majorVersion == "2017" && info.minorVersion == "1") "/2017.1" else "" return "org/rust/cargo/runconfig/producers/fixtures$compatibilityFolder" } // We need to override this because we call [CargoProjectWorkspaceServiceImpl.setRawWorkspace]. override fun getProjectDescriptor(): LightProjectDescriptor = LightProjectDescriptor() fun testExecutableProducerWorksForBin() { testProject { bin("hello", "src/main.rs").open() } checkOnTopLevel<RsFile>() } fun testExecutableProducerWorksForExample() { testProject { example("hello", "example/hello.rs").open() } checkOnLeaf() } fun testExecutableProducerDisabledForLib() { testProject { lib("hello", "src/lib.rs").open() } checkOnLeaf() } fun testExecutableProducerRemembersContext() { testProject { bin("foo", "bin/foo.rs") bin("bar", "bin/bar.rs") } openFileInEditor("bin/foo.rs") val ctx1 = myFixture.file openFileInEditor("bin/bar.rs") val ctx2 = myFixture.file doTestRemembersContext(CargoExecutableRunConfigurationProducer(), ctx1, ctx2) } fun testTestProducerWorksForAnnotatedFunctions() { testProject { lib("foo", "src/lib.rs", "#[test]\nfn test_foo() { as<caret>sert!(true); }").open() } checkOnTopLevel<RsFunction>() } fun `test producer use complete function path`() { testProject { lib("foo", "src/lib.rs", """ mod foo_mod { #[test] fn test_foo() { as<caret>sert!(true); } } """).open() } checkOnTopLevel<RsFunction>() } fun testTestProducerDisableForNonAnnotatedFunctions() { testProject { lib("foo", "src/lib.rs", "fn test_foo() { <caret>assert!(true); }").open() } checkOnLeaf() } fun testTestProducerRemembersContext() { testProject { lib("foo", "src/lib.rs", """ #[test] fn test_foo() { assert_eq!(2 + 2, 4); } #[test] fn test_bar() { assert_eq!(2 * 2, 4); } """).open() } val ctx1 = myFixture.findElementByText("+", PsiElement::class.java) val ctx2 = myFixture.findElementByText("*", PsiElement::class.java) doTestRemembersContext(CargoTestRunConfigurationProducer(), ctx1, ctx2) } fun testTestProducerWorksForModules() { testProject { lib("foo", "src/lib.rs", """ mod foo { #[test] fn bar() {} #[test] fn baz() {} fn quux() {<caret>} } """).open() } checkOnTopLevel<RsMod>() } fun testTestProducerWorksForFiles() { testProject { test("foo", "tests/foo.rs").open() } checkOnElement<RsFile>() } fun testTestProducerWorksForRootModule() { testProject { lib("foo", "src/lib.rs", """ #[test] fn bar() {} #[test] fn baz() {} fn quux() {<caret>} """).open() } checkOnLeaf() } fun testMeaningfulConfigurationName() { testProject { lib("foo", "src/lib.rs", "mod bar;") file("src/bar/mod.rs", """ mod tests { fn quux() <caret>{} #[test] fn baz() {} } """).open() } checkOnLeaf() } fun testTestProducerAddsBinName() { testProject { bin("foo", "src/bin/foo.rs", "#[test]\nfn test_foo() { as<caret>sert!(true); }").open() } checkOnLeaf() } fun testMainFnIsMoreSpecificThanTestMod() { testProject { bin("foo", "src/main.rs", """ fn main() { <caret> } fn foo() {} #[test] fn test_foo() {} """).open() } checkOnLeaf() } fun testMainModAndTestModHaveSameSpecificity() { testProject { bin("foo", "src/main.rs", """ fn main() {} fn foo() { <caret> } #[test] fn test_foo() {} """).open() } checkOnLeaf() } fun testHyphenInNameWorks() { testProject { example("hello-world", "example/hello.rs").open() } checkOnLeaf() } fun `test executable configuration uses default environment`() { testProject { bin("hello", "src/main.rs").open() } modifyTemplateConfiguration { cargoCommandLine = cargoCommandLine.copy(environmentVariables = mapOf("FOO" to "BAR")) } checkOnTopLevel<RsFile>() } fun `test test configuration uses default environment`() { testProject { lib("foo", "src/lib.rs", "#[test]\nfn test_foo() { as<caret>sert!(true); }").open() } modifyTemplateConfiguration { cargoCommandLine = cargoCommandLine.copy(environmentVariables = mapOf("FOO" to "BAR")) } checkOnTopLevel<RsFunction>() } private fun modifyTemplateConfiguration(f: CargoCommandConfiguration.() -> Unit) { val configurationType = ConfigurationTypeUtil.findConfigurationType(CargoCommandConfigurationType::class.java) val factory = configurationType.factory val template = RunManager.getInstance(project).getConfigurationTemplate(factory).configuration as CargoCommandConfiguration template.f() } private fun checkOnLeaf() = checkOnElement<PsiElement>() inline private fun <reified T : PsiElement> checkOnTopLevel() { checkOnElement<T>() checkOnElement<PsiElement>() } private inline fun <reified T : PsiElement> checkOnElement() { val configurationContext = ConfigurationContext( myFixture.file.findElementAt(myFixture.caretOffset)?.parentOfType<T>(strict = false) ) val configurations = configurationContext.configurationsFromContext.orEmpty().map { it.configuration } val serialized = configurations.map { config -> Element("configuration").apply { setAttribute("name", config.name) setAttribute("class", config.javaClass.simpleName) config.writeExternal(this) } } val root = Element("configurations") serialized.forEach { root.addContent(it) } //BACKCOMPAT: in 2017.2, a module is saved to XML as well if (ApplicationManager.getApplication().isEAP) return assertSameLinesWithFile("$testDataPath/${getTestName(true)}.xml", JDOMUtil.writeElement(root)) } private fun doTestRemembersContext( producer: RunConfigurationProducer<CargoCommandConfiguration>, ctx1: PsiElement, ctx2: PsiElement ) { val contexts = listOf(ConfigurationContext(ctx1), ConfigurationContext(ctx2)) val configsFromContext = contexts.map { it.configurationsFromContext!!.single() } configsFromContext.forEach { check(it.isProducedBy(producer.javaClass)) } val configs = configsFromContext.map { it.configuration as CargoCommandConfiguration } for (i in 0..1) { assertThat(producer.isConfigurationFromContext(configs[i], contexts[i])).isTrue() assertThat(producer.isConfigurationFromContext(configs[i], contexts[1 - i])).isFalse() } } private fun testProject(description: TestProjectBuilder.() -> Unit) { val testProject = TestProjectBuilder() testProject.description() testProject.build() } private inner class TestProjectBuilder { private inner class File( val path: String, val code: String, val caretOffset: Int? ) private inner class Target( val name: String, val file: File, val kind: CargoWorkspace.TargetKind ) private var targets = arrayListOf<Target>() private var files = arrayListOf<File>() private var toOpen: File? = null private val helloWorld = """fn main() { println!("Hello, World!") }""" private val simpleTest = """#[test] fn test_simple() { assert_eq!(2 + 2, 5) }""" private val hello = """pub fn hello() -> String { return "Hello, World!".to_string() }""" fun bin(name: String, path: String, code: String = helloWorld): TestProjectBuilder { addTarget(name, CargoWorkspace.TargetKind.BIN, path, code) return this } fun example(name: String, path: String, code: String = helloWorld): TestProjectBuilder { addTarget(name, CargoWorkspace.TargetKind.EXAMPLE, path, code) return this } fun test(name: String, path: String, code: String = simpleTest): TestProjectBuilder { addTarget(name, CargoWorkspace.TargetKind.TEST, path, code) return this } fun lib(name: String, path: String, code: String = hello): TestProjectBuilder { addTarget(name, CargoWorkspace.TargetKind.LIB, path, code) return this } fun file(path: String, code: String): TestProjectBuilder { addFile(path, code) return this } fun open(): TestProjectBuilder { require(toOpen == null) toOpen = files.last() return this } fun build() { myFixture.addFileToProject("Cargo.toml", """ [project] name = "test" version = 0.0.1 """) files.forEach { myFixture.addFileToProject(it.path, it.code) } toOpen?.let { toOpen -> openFileInEditor(toOpen.path) if (toOpen.caretOffset != null) { myFixture.editor.caretModel.moveToOffset(toOpen.caretOffset) } } val metadataService = CargoProjectWorkspaceService.getInstance(myFixture.module) as CargoProjectWorkspaceServiceImpl val projectDescription = CargoWorkspace.deserialize( CleanCargoMetadata( packages = listOf( CleanCargoMetadata.Package( id = "test-package 0.0.1", url = myFixture.tempDirFixture.getFile(".")!!.url, name = "test-package", version = "0.0.1", targets = targets.map { CleanCargoMetadata.Target( myFixture.tempDirFixture.getFile(it.file.path)!!.url, it.name, it.kind ) }, source = null, manifestPath = "/somewhere/test-package/Cargo.toml", isWorkspaceMember = true ) ), dependencies = emptyList() ) ) metadataService.setRawWorkspace(projectDescription) } private fun addTarget(name: String, kind: CargoWorkspace.TargetKind, path: String, code: String) { val file = addFile(path, code) targets.add(Target(name, file, kind)) } private fun addFile(path: String, code: String): File { val caret = code.indexOf("<caret>") val offset = if (caret == -1) null else caret val cleanedCode = code.replace("<caret>", "") val file = File(path, cleanedCode, offset) files.add(file) return file } } }
mit
ec52711e28aec12f164c3447538dd3db
33.686567
131
0.573723
4.889201
false
true
false
false
jk1/intellij-community
platform/projectModel-impl/src/com/intellij/openapi/module/impl/ExternalModuleListStorage.kt
4
2243
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.openapi.module.impl import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.module.Module import com.intellij.openapi.project.Project 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 org.jdom.Element /** * todo rename component state name to "ExternalProjectModuleManager" for consistency (2018.1 release) */ @State(name = "ExternalModuleListStorage", storages = [(Storage("modules.xml"))], externalStorageOnly = true) internal class ExternalModuleListStorage(private val project: Project) : PersistentStateComponent<Element>, ProjectModelElement { var loadedState: Set<ModulePath>? = null private set override fun getState(): Element { val e = Element("state") if (!project.isExternalStorageEnabled) { return e } val moduleManager = ModuleManagerImpl.getInstanceImpl(project) moduleManager.writeExternal(e, getFilteredModuleList(project, moduleManager.modules, true)) return e } override fun loadState(state: Element) { loadedState = ModuleManagerImpl.getPathsToModuleFiles(state) } override fun getExternalSource(): ProjectModelExternalSource? { val externalProjectSystemRegistry = ExternalProjectSystemRegistry.getInstance() for (module in ModuleManagerImpl.getInstanceImpl(project).modules) { externalProjectSystemRegistry.getExternalSource(module)?.let { return it } } return null } } fun getFilteredModuleList(project: Project, modules: Array<Module>, isExternal: Boolean): List<Module> { if (!project.isExternalStorageEnabled) { return modules.asList() } val externalProjectSystemRegistry = ExternalProjectSystemRegistry.getInstance() return modules.filter { (externalProjectSystemRegistry.getExternalSource(it) != null) == isExternal } }
apache-2.0
25a786af3e482da1266c7a984be5c191
39.071429
140
0.786001
4.940529
false
false
false
false
google/accompanist
sample/src/main/java/com/google/accompanist/sample/pager/NestedPagersSample.kt
1
2807
/* * 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 * * 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.accompanist.sample.pager import android.os.Bundle import androidx.activity.ComponentActivity import androidx.activity.compose.setContent import androidx.compose.foundation.layout.aspectRatio import androidx.compose.foundation.layout.fillMaxSize import androidx.compose.foundation.layout.fillMaxWidth import androidx.compose.foundation.layout.padding import androidx.compose.material.MaterialTheme import androidx.compose.material.Scaffold import androidx.compose.material.Surface import androidx.compose.material.Text import androidx.compose.material.TopAppBar import androidx.compose.runtime.Composable import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import com.google.accompanist.pager.ExperimentalPagerApi import com.google.accompanist.pager.HorizontalPager import com.google.accompanist.pager.VerticalPager import com.google.accompanist.sample.AccompanistSampleTheme import com.google.accompanist.sample.R class NestedPagersSample : ComponentActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContent { AccompanistSampleTheme { Surface { Sample() } } } } } @OptIn(ExperimentalPagerApi::class) @Composable private fun Sample() { Scaffold( topBar = { TopAppBar( title = { Text(stringResource(R.string.pagers_title_nested)) }, backgroundColor = MaterialTheme.colors.surface, ) }, modifier = Modifier.fillMaxSize() ) { padding -> VerticalPager( count = 10, modifier = Modifier.fillMaxSize().padding(padding), ) { HorizontalPager( count = 5, modifier = Modifier .fillMaxWidth() .aspectRatio(1f) ) { page -> PagerSampleItem( page = page, modifier = Modifier .fillMaxWidth(0.8f) .aspectRatio(1f) ) } } } }
apache-2.0
3343a34db494c8bb92830b4eeb5d98c4
32.023529
79
0.662629
4.924561
false
false
false
false
ktorio/ktor
ktor-utils/jvm/src/io/ktor/util/pipeline/StackTraceRecoverJvm.kt
1
451
/* * Copyright 2014-2019 JetBrains s.r.o and contributors. Use of this source code is governed by the Apache 2.0 license. */ package io.ktor.util.pipeline import io.ktor.utils.io.* internal actual fun Throwable.withCause(cause: Throwable?): Throwable { if (cause == null || this.cause == cause) { return this } val result = tryCopyException(this, cause) ?: return this result.stackTrace = stackTrace return result }
apache-2.0
4bf645aaf22ad59d3107dd372a1f833c
24.055556
119
0.691796
3.887931
false
false
false
false
Kerooker/rpg-npc-generator
app/src/main/java/me/kerooker/rpgnpcgenerator/view/MainActivity.kt
1
4676
package me.kerooker.rpgnpcgenerator.view import android.content.Intent import android.net.Uri import android.os.Bundle import android.view.ViewGroup.LayoutParams import androidx.appcompat.app.AppCompatActivity import androidx.navigation.findNavController import androidx.navigation.ui.setupWithNavController import com.google.android.gms.ads.AdRequest import com.google.android.gms.ads.AdSize import com.google.android.gms.ads.AdView import com.google.android.gms.ads.rewarded.RewardItem import com.google.android.gms.ads.rewarded.RewardedAd import com.google.android.gms.ads.rewarded.RewardedAdCallback import com.google.android.gms.ads.rewarded.RewardedAdLoadCallback import kotlinx.android.synthetic.main.activity_main.bottom_ad_container import kotlinx.android.synthetic.main.activity_main.bottom_navigation_view import kotlinx.android.synthetic.main.activity_main.toolbar import me.kerooker.rpgnpcgenerator.R import me.kerooker.rpgnpcgenerator.databinding.ActivityMainBinding import me.kerooker.rpgnpcgenerator.viewmodel.admob.AdmobViewModel import org.koin.android.ext.android.inject import splitties.alertdialog.alertDialog import splitties.alertdialog.messageResource import splitties.alertdialog.negativeButton import splitties.alertdialog.neutralButton import splitties.alertdialog.onShow import splitties.alertdialog.positiveButton import splitties.alertdialog.titleResource class MainActivity : AppCompatActivity() { private val admobViewModel by inject<AdmobViewModel>() private lateinit var rewardedAd: RewardedAd override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) val binding = ActivityMainBinding.inflate(layoutInflater).apply { lifecycleOwner = this@MainActivity shouldShowAd = admobViewModel.shouldShowAd } setContentView(binding.root) val navController = findNavController(R.id.nav_host_fragment) bottom_navigation_view.setupWithNavController(navController) setSupportActionBar(toolbar) } override fun onResume() { super.onResume() setupBottomAd() createRewardedAd() } private fun setupBottomAd() { if(admobViewModel.shouldShowAd.value == false) return val view = AdView(this) view.adSize = AdSize.SMART_BANNER view.adUnitId = admobViewModel.bannerAdId bottom_ad_container.removeAllViews() bottom_ad_container.addView(view, LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) view.loadAd(AdRequest.Builder().build()) } private fun createRewardedAd() { rewardedAd = RewardedAd(this, admobViewModel.rewardedAdId).apply { loadAd(AdRequest.Builder().build(), object : RewardedAdLoadCallback() { override fun onRewardedAdLoaded() { setupDismissAdsDialog() } }) } } private fun setupDismissAdsDialog() { if(!admobViewModel.shouldSuggestRemovingAds()) return suggestRemovingAds() admobViewModel.suggestedRemovingAds() } private fun suggestRemovingAds() { alertDialog { titleResource = R.string.disable_ads_title messageResource = R.string.disable_ads_message positiveButton(R.string.go_pro) { goPro() } negativeButton(R.string.watch_ad_remove_ad) { watchAd() } neutralButton(R.string.not_now) { it.dismiss() } }.onShow { positiveButton.setBackgroundColor(context.resources.getColor(android.R.color.transparent)) negativeButton.setBackgroundColor(context.resources.getColor(android.R.color.transparent)) neutralButton.setBackgroundColor(context.resources.getColor(android.R.color.transparent)) positiveButton.setTextColor(context.resources.getColor(R.color.colorPrimary)) negativeButton.setTextColor(context.resources.getColor(R.color.colorAccent)) neutralButton.setTextColor(context.resources.getColor(R.color.colorPrimary)) }.show() } private fun watchAd() { rewardedAd.show(this, object : RewardedAdCallback() { override fun onUserEarnedReward(item: RewardItem) { admobViewModel.watchedRewardedAd() } }) } private fun goPro() { startActivity( Intent( Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=me.kerooker.rpgcharactergeneratorpro") ) ) } }
apache-2.0
fad4100ffabb4d78c1b7c4fcd8700efb
37.327869
111
0.701668
4.694779
false
false
false
false
mikepenz/FastAdapter
fastadapter/src/main/java/com/mikepenz/fastadapter/MutableSubItemList.kt
1
1771
package com.mikepenz.fastadapter /** * MutableList proxy which will properly set and remove the parent for items added/set/removed. * This is important as otherwise collapsing will not work properly (does not resolve parent relationships) */ class MutableSubItemList<E : ISubItem<*>>(val parent: IParentItem<*>, val list: MutableList<E> = mutableListOf()) : MutableList<E> by list { override fun remove(element: E): Boolean { return list.remove(element).also { removed -> if (removed) element.parent = null } } override fun removeAt(index: Int): E { return list.removeAt(index).also { element -> element.parent = null } } override fun removeAll(elements: Collection<E>): Boolean { elements.filter { list.contains(it) }.forEach { it.parent = null } return list.removeAll(elements) } override fun add(element: E): Boolean { element.parent = parent return list.add(element) } override fun add(index: Int, element: E) { element.parent = parent return list.add(index, element) } override fun addAll(index: Int, elements: Collection<E>): Boolean { elements.forEach { it.parent = parent } return list.addAll(index, elements) } override fun addAll(elements: Collection<E>): Boolean { elements.forEach { it.parent = parent } return list.addAll(elements) } override fun set(index: Int, element: E): E { element.parent = parent return list.set(index, element).also { oldElement -> oldElement.parent = null } } override fun clear() { list.forEach { it.parent = null } list.clear() } fun setNewList(newList: List<E>) { clear() addAll(newList) } }
apache-2.0
62ac4b1ec823b6a18bc86761d5751eba
30.642857
140
0.640316
4.216667
false
false
false
false
JonathanxD/CodeAPI
src/main/kotlin/com/github/jonathanxd/kores/base/ArrayLoad.kt
1
3737
/* * Kores - Java source and Bytecode generation framework <https://github.com/JonathanxD/Kores> * * The MIT License (MIT) * * Copyright (c) 2020 TheRealBuggy/JonathanxD (https://github.com/JonathanxD/) <[email protected]> * Copyright (c) contributors * * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the "Software"), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN * THE SOFTWARE. */ package com.github.jonathanxd.kores.base import com.github.jonathanxd.kores.Instruction import com.github.jonathanxd.kores.builder.self import com.github.jonathanxd.kores.type.isArray import java.lang.reflect.Type /** * * Loads a value of type [valueType] at [index] from array [target] of type [arrayType]. * * @property index Index to access * @property valueType Type of value */ data class ArrayLoad( override val arrayType: Type, override val target: Instruction, val index: Instruction, val valueType: Type ) : ArrayAccess, TypedInstruction { init { check(arrayType.isArray) { "arrayType is not an array type!" } } override val type: Type get() = this.valueType override fun builder(): Builder = Builder(this) class Builder() : ArrayAccess.Builder<ArrayLoad, Builder>, Typed.Builder<ArrayLoad, Builder> { lateinit var arrayType: Type lateinit var target: Instruction lateinit var index: Instruction lateinit var valueType: Type constructor(defaults: ArrayLoad) : this() { this.arrayType = defaults.arrayType this.target = defaults.target this.index = defaults.index this.valueType = defaults.valueType } override fun type(value: Type): Builder = self() override fun arrayType(value: Type): Builder { this.arrayType = value return this } override fun target(value: Instruction): Builder { this.target = value return this } /** * See [ArrayLoad.index] */ fun index(value: Instruction): Builder { this.index = value return this } /** * See [ArrayLoad.valueType] */ fun valueType(value: Type): Builder { this.valueType = value return this } override fun build(): ArrayLoad = ArrayLoad(this.arrayType, this.target, this.index, this.valueType) companion object { @JvmStatic fun builder(): Builder = Builder() @JvmStatic fun builder(defaults: ArrayLoad): Builder = Builder(defaults) } } }
mit
6947b16ff48f0460f298890ad0b7b8ff
31.495652
118
0.640353
4.64801
false
false
false
false
awsdocs/aws-doc-sdk-examples
kotlin/services/support/src/main/kotlin/com/example/support/HelloSupport.kt
1
1967
// snippet-sourcedescription:[HelloSupport.kt demonstrates how to create a Service Client and perform a single operation.] // snippet-keyword:[AWS SDK for Kotlin] // snippet-service:[AWS Support] /* Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. SPDX-License-Identifier: Apache-2.0 */ package com.example.support import aws.sdk.kotlin.services.support.SupportClient import aws.sdk.kotlin.services.support.model.DescribeServicesRequest // snippet-start:[support.kotlin.hello.main] /** Before running this Kotlin code example, set up your development environment, including your credentials. For more information, see the following documentation topic: https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html In addition, you must have the AWS Business Support Plan to use the AWS Support Java API. For more information, see: https://aws.amazon.com/premiumsupport/plans/ This Kotlin example performs the following task: 1. Gets and displays available services. */ suspend fun main() { displaySomeServices() } // Return a List that contains a Service name and Category name. suspend fun displaySomeServices() { val servicesRequest = DescribeServicesRequest { language = "en" } SupportClient { region = "us-west-2" }.use { supportClient -> val response = supportClient.describeServices(servicesRequest) println("Get the first 10 services") var index = 1 response.services?.forEach { service -> if (index == 11) { return@forEach } println("The Service name is: " + service.name) // Get the categories for this service. service.categories?.forEach { cat -> println("The category name is ${cat.name}") index++ } } } } // snippet-end:[support.kotlin.hello.main]
apache-2.0
18025286a682800aaa45bd2806d8c13c
29.725806
122
0.667514
4.29476
false
false
false
false
tateisu/SubwayTooter
app/src/main/java/jp/juggler/subwaytooter/actpost/CompletionHelper.kt
1
21405
package jp.juggler.subwaytooter.actpost import android.content.SharedPreferences import android.os.Handler import android.text.* import android.text.style.ForegroundColorSpan import android.view.View import androidx.appcompat.app.AppCompatActivity import jp.juggler.subwaytooter.App1 import jp.juggler.subwaytooter.R import jp.juggler.subwaytooter.api.entity.TootTag import jp.juggler.subwaytooter.dialog.ActionsDialog import jp.juggler.subwaytooter.dialog.launchEmojiPicker import jp.juggler.subwaytooter.emoji.CustomEmoji import jp.juggler.subwaytooter.emoji.EmojiBase import jp.juggler.subwaytooter.emoji.UnicodeEmoji import jp.juggler.subwaytooter.pref.PrefB import jp.juggler.subwaytooter.span.NetworkEmojiSpan import jp.juggler.subwaytooter.table.AcctSet import jp.juggler.subwaytooter.table.SavedAccount import jp.juggler.subwaytooter.table.TagSet import jp.juggler.subwaytooter.util.DecodeOptions import jp.juggler.subwaytooter.util.EmojiDecoder import jp.juggler.subwaytooter.util.PopupAutoCompleteAcct import jp.juggler.subwaytooter.view.MyEditText import jp.juggler.util.* import kotlin.math.min // 入力補完機能 class CompletionHelper( private val activity: AppCompatActivity, private val pref: SharedPreferences, private val handler: Handler, ) { companion object { private val log = LogCategory("CompletionHelper") private val reCharsNotEmoji = "[^0-9A-Za-z_-]".asciiRegex() // 無視するスパン // ($を.に変換済) val ignoreSpans = setOf( "android.text.Selection.END", "android.text.Selection.START", "android.widget.Editor.SpanController", "android.widget.TextView.ChangeWatcher", "androidx.emoji2.text.SpannableBuilder.WatcherWrapper", "androidx.emoji2.viewsintegration.EmojiKeyListener", "android.text.DynamicLayout.ChangeWatcher", "android.text.method.TextKeyListener", "android.text.method.Touch.DragState", "android.text.style.SpellCheckSpan", ) private val reRemoveSpan = """\Qandroid.text.style.\E.+Span""".toRegex() private fun matchUserNameOrAsciiDomain(cp: Int): Boolean { if (cp >= 0x7f) return false val c = cp.toChar() return '0' <= c && c <= '9' || 'A' <= c && c <= 'Z' || 'a' <= c && c <= 'z' || c == '_' || c == '-' || c == '.' } // Letter | Mark | Decimal_Number | Connector_Punctuation private fun matchIdnWord(cp: Int) = when (Character.getType(cp).toByte()) { // Letter // LCはエイリアスなので文字から得られることはないはず Character.UPPERCASE_LETTER, Character.LOWERCASE_LETTER, Character.TITLECASE_LETTER, Character.MODIFIER_LETTER, Character.OTHER_LETTER, -> true // Mark Character.NON_SPACING_MARK, Character.COMBINING_SPACING_MARK, Character.ENCLOSING_MARK, -> true // Decimal_Number Character.DECIMAL_DIGIT_NUMBER -> true // Connector_Punctuation Character.CONNECTOR_PUNCTUATION -> true else -> false } } interface Callback2 { fun onTextUpdate() fun canOpenPopup(): Boolean } private val pickerCaptionEmoji: String by lazy { activity.getString(R.string.open_picker_emoji) } private var callback2: Callback2? = null private var et: MyEditText? = null private var popup: PopupAutoCompleteAcct? = null private var formRoot: View? = null private var bMainScreen: Boolean = false private var accessInfo: SavedAccount? = null private val onEmojiListLoad: (list: List<CustomEmoji>) -> Unit = { if (popup?.isShowing == true) procTextChanged.run() } private val procTextChanged: Runnable = Runnable { val et = this.et if (et == null || et.selectionStart != et.selectionEnd || callback2?.canOpenPopup() != true) { // EditTextを特定できない // 範囲選択中 // 何らかの理由でポップアップが許可されていない closeAcctPopup() } else { checkMention(et, et.text.toString()) } } private fun checkMention(et: MyEditText, src: String) { // 選択範囲末尾からスキャン var countAtmark = 0 var start: Int = -1 val end = et.selectionEnd var i = end while (i > 0) { val cp = src.codePointBefore(i) i -= Character.charCount(cp) if (cp == '@'.code) { start = i if (++countAtmark >= 2) break else continue } else if (countAtmark == 1) { // @username@host の username部分はUnicodeを含まない if (matchUserNameOrAsciiDomain(cp)) continue else break } else { // @username@host のhost 部分か、 @username のusername部分 // ここはUnicodeを含むかもしれない if (matchUserNameOrAsciiDomain(cp) || matchIdnWord(cp)) continue else break } } if (start == -1) { checkTag(et, src) return } // 最低でも2文字ないと補完しない if (end - start < 2) { closeAcctPopup() return } val limit = 100 val s = src.substring(start, end) val acctList = AcctSet.searchPrefix(s, limit) log.d("search for $s, result=${acctList.size}") if (acctList.isEmpty()) { closeAcctPopup() } else { openPopup()?.setList(et, start, end, acctList, null, null) } } private fun checkTag(et: MyEditText, src: String) { val end = et.selectionEnd val lastSharp = src.lastIndexOf('#', end - 1) if (lastSharp == -1 || end - lastSharp < 2) { checkEmoji(et, src) return } val part = src.substring(lastSharp + 1, end) if (!TootTag.isValid(part, accessInfo?.isMisskey == true)) { checkEmoji(et, src) return } val limit = 100 val s = src.substring(lastSharp + 1, end) val tagList = TagSet.searchPrefix(s, limit) log.d("search for $s, result=${tagList.size}") if (tagList.isEmpty()) { closeAcctPopup() } else { openPopup()?.setList(et, lastSharp, end, tagList, null, null) } } private fun checkEmoji(et: MyEditText, src: String) { val end = et.selectionEnd val lastColon = src.lastIndexOf(':', end - 1) if (lastColon == -1 || end - lastColon < 1) { closeAcctPopup() return } if (!EmojiDecoder.canStartShortCode(src, lastColon)) { // : の手前は始端か改行か空白でなければならない log.d("checkEmoji: invalid character before shortcode.") closeAcctPopup() return } val part = src.substring(lastColon + 1, end) if (part.isEmpty()) { // :を入力した直後は候補は0で、「閉じる」と「絵文字を選ぶ」だけが表示されたポップアップを出す openPopup()?.setList( et, lastColon, end, null, pickerCaptionEmoji, openPickerEmoji ) return } if (reCharsNotEmoji.containsMatchIn(part)) { // 範囲内に絵文字に使えない文字がある closeAcctPopup() return } val codeList = ArrayList<CharSequence>() val limit = 100 // カスタム絵文字の候補を部分一致検索 codeList.addAll(customEmojiCodeList(accessInfo, limit, part)) // 通常の絵文字を部分一致で検索 val remain = limit - codeList.size if (remain > 0) { val s = src.substring(lastColon + 1, end) .lowercase() .replace('-', '_') val matches = EmojiDecoder.searchShortCode(activity, s, remain) log.d("checkEmoji: search for $s, result=${matches.size}") codeList.addAll(matches) } openPopup()?.setList( et, lastColon, end, codeList, pickerCaptionEmoji, openPickerEmoji ) } // カスタム絵文字の候補を作る private fun customEmojiCodeList( accessInfo: SavedAccount?, @Suppress("SameParameterValue") limit: Int, needle: String, ) = buildList<CharSequence> { accessInfo ?: return@buildList val customList = App1.custom_emoji_lister.tryGetList( accessInfo, withAliases = true, callback = onEmojiListLoad ) ?: return@buildList for (item in customList) { if (size >= limit) break if (!item.shortcode.contains(needle)) continue val sb = SpannableStringBuilder() sb.append(' ') sb.setSpan( NetworkEmojiSpan(item.url), 0, sb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) sb.append(' ') if (item.alias != null) { val start = sb.length sb.append(":") sb.append(item.alias) sb.append(": → ") sb.setSpan( ForegroundColorSpan(activity.attrColor(R.attr.colorTimeSmall)), start, sb.length, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE ) } sb.append(':') sb.append(item.shortcode) sb.append(':') add(sb) } } private fun openPopup(): PopupAutoCompleteAcct? { var popup = [email protected] if (popup?.isShowing == true) return popup val et = [email protected] ?: return null val formRoot = [email protected] ?: return null popup = PopupAutoCompleteAcct(activity, et, formRoot, bMainScreen) [email protected] = popup return popup } fun setInstance(accessInfo: SavedAccount?) { this.accessInfo = accessInfo accessInfo?.let { App1.custom_emoji_lister.tryGetList( it, callback = onEmojiListLoad ) } if (popup?.isShowing == true) procTextChanged.run() } fun closeAcctPopup() { popup?.dismiss() popup = null } fun onScrollChanged() { popup?.takeIf { it.isShowing }?.updatePosition() } fun onDestroy() { handler.removeCallbacks(procTextChanged) closeAcctPopup() } fun attachEditText( formRoot: View, et: MyEditText, bMainScreen: Boolean, callback2: Callback2, ) { this.formRoot = formRoot this.et = et this.callback2 = callback2 this.bMainScreen = bMainScreen et.addTextChangedListener(object : TextWatcher { override fun beforeTextChanged( s: CharSequence, start: Int, count: Int, after: Int, ) { } override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) { handler.removeCallbacks(procTextChanged) handler.postDelayed(procTextChanged, if (popup?.isShowing == true) 100L else 500L) } override fun afterTextChanged(s: Editable) { // ペースト時に余計な装飾を取り除く val spans = s.getSpans(0, s.length, Any::class.java) val isImeComposing = spans.any { it?.javaClass?.name == "android.view.inputmethod.ComposingText" } if (!isImeComposing) { spans?.filter { val name = (it?.javaClass?.name ?: "").replace('$', '.') when { ignoreSpans.contains(name) -> false reRemoveSpan.matches(name) -> { log.i("span remove $name") true } else -> { log.i("span keep $name") false } } } ?.map { Triple(it, s.getSpanStart(it), s.getSpanEnd(it)) } ?.sortedBy { -it.second } ?.forEach { s.removeSpan(it.first) } } [email protected]?.onTextUpdate() } }) // 範囲選択されてるならポップアップは閉じる et.onSelectionChange = { selStart, selEnd -> if (selStart != selEnd) { log.d("onSelectionChange: range selected") closeAcctPopup() } } // 全然動いてなさそう… // et.setCustomSelectionActionModeCallback( action_mode_callback ); } private fun SpannableStringBuilder.appendEmoji( emoji: EmojiBase, bInstanceHasCustomEmoji: Boolean, ) = appendEmoji(bInstanceHasCustomEmoji, emoji) private fun SpannableStringBuilder.appendEmoji( bInstanceHasCustomEmoji: Boolean, emoji: EmojiBase, ): SpannableStringBuilder { val separator = EmojiDecoder.customEmojiSeparator() when (emoji) { is CustomEmoji -> { // カスタム絵文字は常にshortcode表現 if (!EmojiDecoder.canStartShortCode(this, this.length)) append(separator) this.append(SpannableString(":${emoji.shortcode}:")) // セパレータにZWSPを使う設定なら、補完した次の位置にもZWSPを追加する。連続して入力補完できるようになる。 if (separator != ' ') append(separator) } is UnicodeEmoji -> { if (!bInstanceHasCustomEmoji) { // 古いタンスだとshortcodeを使う。見た目は絵文字に変える。 if (!EmojiDecoder.canStartShortCode(this, this.length)) append(separator) this.append(DecodeOptions(activity).decodeEmoji(":${emoji.unifiedName}:")) // セパレータにZWSPを使う設定なら、補完した次の位置にもZWSPを追加する。連続して入力補完できるようになる。 if (separator != ' ') append(separator) } else { // 十分に新しいタンスなら絵文字のunicodeを使う。見た目は絵文字に変える。 this.append(DecodeOptions(activity).decodeEmoji(emoji.unifiedCode)) } } } return this } private val openPickerEmoji: Runnable = Runnable { launchEmojiPicker( activity, accessInfo, closeOnSelected = PrefB.bpEmojiPickerCloseOnSelected(pref) ) { emoji, bInstanceHasCustomEmoji -> val et = [email protected] ?: return@launchEmojiPicker val src = et.text ?: "" val srcLength = src.length val end = min(srcLength, et.selectionEnd) val start = src.lastIndexOf(':', end - 1) if (start == -1 || end - start < 1) return@launchEmojiPicker val sb = SpannableStringBuilder() .append(src.subSequence(0, start)) .appendEmoji(emoji, bInstanceHasCustomEmoji) val newSelection = sb.length if (end < srcLength) sb.append(src.subSequence(end, srcLength)) et.text = sb et.setSelection(newSelection) procTextChanged.run() // キーボードを再度表示する App1.getAppState( activity, "PostHelper/EmojiPicker/cb" ).handler.post { et.showKeyboard() } } } fun openEmojiPickerFromMore() { launchEmojiPicker( activity, accessInfo, closeOnSelected = PrefB.bpEmojiPickerCloseOnSelected(pref) ) { emoji, bInstanceHasCustomEmoji -> val et = [email protected] ?: return@launchEmojiPicker val src = et.text ?: "" val srcLength = src.length val start = min(srcLength, et.selectionStart) val end = min(srcLength, et.selectionEnd) val sb = SpannableStringBuilder() .append(src.subSequence(0, start)) .appendEmoji(emoji, bInstanceHasCustomEmoji) val newSelection = sb.length if (end < srcLength) sb.append(src.subSequence(end, srcLength)) et.text = sb et.setSelection(newSelection) procTextChanged.run() } } private fun SpannableStringBuilder.appendHashTag(tagWithoutSharp: String): SpannableStringBuilder { val separator = ' ' if (!EmojiDecoder.canStartHashtag(this, this.length)) append(separator) this.append('#').append(tagWithoutSharp) append(separator) return this } fun openFeaturedTagList(list: List<TootTag>?) { val ad = ActionsDialog() list?.forEach { tag -> ad.addAction("#${tag.name}") { val et = this.et ?: return@addAction val src = et.text ?: "" val srcLength = src.length val start = min(srcLength, et.selectionStart) val end = min(srcLength, et.selectionEnd) val sb = SpannableStringBuilder() .append(src.subSequence(0, start)) .appendHashTag(tag.name) val newSelection = sb.length if (end < srcLength) sb.append(src.subSequence(end, srcLength)) et.text = sb et.setSelection(newSelection) procTextChanged.run() } } ad.addAction(activity.getString(R.string.input_sharp_itself)) { val et = this.et ?: return@addAction val src = et.text ?: "" val srcLength = src.length val start = min(srcLength, et.selectionStart) val end = min(srcLength, et.selectionEnd) val sb = SpannableStringBuilder() sb.append(src.subSequence(0, start)) if (!EmojiDecoder.canStartHashtag(sb, sb.length)) sb.append(' ') sb.append('#') val newSelection = sb.length if (end < srcLength) sb.append(src.subSequence(end, srcLength)) et.text = sb et.setSelection(newSelection) procTextChanged.run() } ad.show(activity, activity.getString(R.string.featured_hashtags)) } // final ActionMode.Callback action_mode_callback = new ActionMode.Callback() { // @Override public boolean onCreateActionMode( ActionMode actionMode, Menu menu ){ // actionMode.getMenuInflater().inflate(R.menu.toot_long_tap, menu); // return true; // } // @Override public void onDestroyActionMode( ActionMode actionMode ){ // // } // @Override public boolean onPrepareActionMode( ActionMode actionMode, Menu menu ){ // return false; // } // // @Override // public boolean onActionItemClicked( ActionMode actionMode, MenuItem item ){ // if (item.getItemId() == R.id.action_pick_emoji) { // actionMode.finish(); // EmojiPicker.open( activity, instance, new EmojiPicker.Callback() { // @Override public void onPickedEmoji( String name ){ // int end = et.getSelectionEnd(); // String src = et.getText().toString(); // CharSequence svInsert = ":" + name + ":"; // src = src.substring( 0, end ) + svInsert + " " + ( end >= src.length() ? "" : src.substring( end ) ); // et.setText( src ); // et.setSelection( end + svInsert.length() + 1 ); // // proc_text_changed.run(); // } // } ); // return true; // } // // return false; // } // }; }
apache-2.0
d580c958eeca588b6e110880fb7a59f3
32.548986
113
0.533271
4.411777
false
false
false
false
DreierF/MyTargets
app/src/main/java/de/dreier/mytargets/utils/LongSparseArrayUtils.kt
1
1195
/* * Copyright (C) 2018 Florian Dreier * * This file is part of MyTargets. * * MyTargets is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 * as published by the Free Software Foundation. * * MyTargets is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. */ package de.dreier.mytargets.utils import androidx.collection.LongSparseArray inline fun <reified T> List<Pair<Long, T>>.toSparseArray(): LongSparseArray<T> { val array = LongSparseArray<T>(size) for ((key, value) in this) { array.put(key, value) } return array } inline fun <reified T, R> LongSparseArray<T>.map(transform: (Pair<Long, T>) -> R): List<R> { val list = ArrayList<R>(size()) for (i in 0 until size()) { val key = keyAt(i) val value = get(key)!! list.add(transform.invoke(Pair(key, value))) } return list } fun <T> LongSparseArray<T>.contains(key: Long): Boolean { return indexOfKey(key) >= 0 }
gpl-2.0
4551435af99dc2520de061a83defed3a
28.875
92
0.680335
3.793651
false
false
false
false
BenAlderfer/percent-calculatorv2
app/src/main/java/com/alderferstudios/percentcalculatorv2/activity/SettingsActivity.kt
1
18777
package com.alderferstudios.percentcalculatorv2.activity import android.content.SharedPreferences import android.os.Bundle import android.preference.PreferenceFragment import android.preference.PreferenceManager import android.view.MenuItem import com.alderferstudios.percentcalculatorv2.R import com.alderferstudios.percentcalculatorv2.activity.OneItemActivity.Companion.editor import com.alderferstudios.percentcalculatorv2.activity.OneItemActivity.Companion.shared import com.alderferstudios.percentcalculatorv2.util.MiscUtil import com.alderferstudios.percentcalculatorv2.util.PrefConstants /** * Settings screen */ class SettingsActivity : BaseActivity(), SharedPreferences.OnSharedPreferenceChangeListener { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_settings) try { supportActionBar?.setDisplayHomeAsUpEnabled(true) } catch (e: NullPointerException) { e.printStackTrace() } needsActRestart = shared?.getBoolean(PrefConstants.NEEDS_ACTIVITY_RESTART, false) == true needsFullRestart = shared?.getBoolean(PrefConstants.NEEDS_FULL_RESTART, false) == true if (MiscUtil.isLandscape(this)) { /* getFragmentManager().beginTransaction() .replace(R.id.frame1, new LandscapePrefsFragment1()).commit(); getFragmentManager().beginTransaction() .replace(R.id.frame2, new LandscapePrefsFragment2()).commit();*/ } else { fragmentManager.beginTransaction() .replace(R.id.framePort, PrefsFragment()).commit() } shared?.registerOnSharedPreferenceChangeListener(this) } override fun onOptionsItemSelected(item: MenuItem): Boolean { onBackPressed() return true } /** * Restarts the activity if the theme or color was changed * Removes leading zeros from percent limit and tax * Cannot be done in fragment b/c fragments are static * @param sharedPreferences the shared prefs * @param key the name of the pref */ override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { if (key == PrefConstants.THEME_LIST || key == PrefConstants.COLOR_LIST) { onRestart() } if (key == PrefConstants.PERCENT_INPUT) { //removes leading zeros and puts it back, remakes edit for use later editor?.putString(PrefConstants.PERCENT_INPUT, removeLeadingZeroes(shared?.getString(PrefConstants.PERCENT_INPUT, "") ?: "")) editor?.apply() } if (key == PrefConstants.TAX_INPUT) { //removes leading zeros and puts it back, remakes edit for use later editor?.putString(PrefConstants.TAX_INPUT, removeLeadingZeroes(shared?.getString(PrefConstants.TAX_INPUT, "") ?: "")) editor?.apply() } } /** * Overridden to apply activity specific themes * Applies the correct colors based on the theme * Makes some changes on Lollipop */ override fun applyTheme() { themeChoice = shared?.getString(PrefConstants.THEME_LIST, "Light") colorChoice = shared?.getString(PrefConstants.COLOR_LIST, "Green") if (colorChoice == "Dynamic") { when (themeChoice) { "Dark" -> setTheme(R.style.GreenDark) "Black and White" -> setTheme(R.style.BlackAndWhite) else -> setTheme(R.style.GreenLight) } } else { super.applyTheme() } } /** * Removes any leading zeros * * @param string the String to edit * @return the String without leading zeros */ private fun removeLeadingZeroes(string: String): String { var s = string while (s.substring(0, 1) == "0") { s = s.substring(1) } return s } override fun onRestart() { editor?.putBoolean(PrefConstants.NEEDS_ACTIVITY_RESTART, needsActRestart) //saves variables in case it needs to restart for color/theme change editor?.putBoolean(PrefConstants.NEEDS_FULL_RESTART, needsFullRestart) editor?.apply() super.onRestart() } open class PCFragment : PreferenceFragment(), SharedPreferences.OnSharedPreferenceChangeListener { /** * Sets the summaries on start */ protected open fun setSummaries() { setPercentStartSummary() //starting percent setPercentMaxSummary() //max percent setTaxBoxSummary() //Tax box setTaxSummary() //Tax number setAfterBoxSummary() //Calculate after tax box setSaveBoxSummary() //Save box setSplitSummary() //Split list setCombinedBoxSummary() //Combined box setThemeListSummary() //Theme list setColorListSummary() //Color box } /** * Sets the summaries on change */ override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { when (key) { PrefConstants.PERCENT_START -> setPercentStartSummary() PrefConstants.PERCENT_MAX -> setPercentMaxSummary() PrefConstants.TAX_BOX -> setTaxBoxSummary() PrefConstants.TAX_INPUT -> setTaxSummary() PrefConstants.AFTER_BOX -> setAfterBoxSummary() PrefConstants.SAVE_BOX -> { setSaveBoxSummary() needsActRestart = true } PrefConstants.SPLIT_LIST -> setSplitSummary() PrefConstants.COMBINED_BOX -> { setCombinedBoxSummary() needsFullRestart = true } PrefConstants.THEME_LIST -> setThemeListSummary() PrefConstants.COLOR_LIST -> setColorListSummary() } } /** * Sets the summary for the starting percent * String needs to be acquired differently since its being added */ protected fun setPercentStartSummary() { if (isAdded) { //must check if the fragment is added to the activity val p = findPreference(PrefConstants.PERCENT_START) if (p != null) { val percentStart = shared?.getString(PrefConstants.PERCENT_START, "0") val percentMax = shared?.getString(PrefConstants.PERCENT_MAX, "30") if (percentStart == null || percentMax == null) { return } when { percentStart == "" -> MiscUtil.showToast(activity, getString(R.string.start_percent_incorrect)) percentStart.toInt() >= percentMax.toInt() -> { MiscUtil.showToast(activity, getString(R.string.start_greater_than_max)) if (percentMax.toInt() > 1) { editor?.putString(PrefConstants.PERCENT_START, (percentMax.toInt() - 1).toString()) } else { editor?.putString(PrefConstants.PERCENT_START, "0") } editor?.apply() } else -> p.summary = resources.getString(R.string.percentStartDesc, percentStart) + "%" } } } } /** * Sets the summary for the max percent * String needs to be acquired differently since its being added */ protected fun setPercentMaxSummary() { if (isAdded) { //must check if the fragment is added to the activity val p = findPreference(PrefConstants.PERCENT_MAX) if (p != null) { val percentStart = shared?.getString(PrefConstants.PERCENT_START, "0") val percentMax = shared?.getString(PrefConstants.PERCENT_MAX, "30") if (percentStart == null || percentMax == null) { return } when { percentStart == "" -> MiscUtil.showToast(activity, getString(R.string.max_percent_incorrect)) percentMax.toInt() <= percentStart.toInt() -> { MiscUtil.showToast(activity, getString(R.string.max_less_than_start)) if (percentStart.toInt() > 0) { editor?.putString(PrefConstants.PERCENT_MAX, (percentStart.toInt() + 1).toString()) } else { editor?.putString(PrefConstants.PERCENT_MAX, "1") } editor?.apply() } else -> p.summary = resources.getString(R.string.percentLimitDesc, percentMax) + "%" } } } } /** * Sets the summary for the tax box */ protected fun setTaxBoxSummary() { if (isAdded) { //must check if the fragment is added to the activity val p = findPreference(PrefConstants.TAX_BOX) if (p != null) { if (shared?.getBoolean(PrefConstants.TAX_BOX, false) == true) { p.setSummary(R.string.enabledTaxDesc) } else { p.setSummary(R.string.disabledTaxDesc) } } } } /** * Sets the summary for the tax * String needs to be acquired differently since its being added */ protected fun setTaxSummary() { if (isAdded) { //must check if the fragment is added to the activity val p = findPreference(PrefConstants.TAX_INPUT) if (p != null) { p.summary = resources.getString(R.string.taxDesc, (shared?.getString(PrefConstants.TAX_INPUT, "6") ?: "6") + "%") } } } /** * Sets the summary for the after box */ protected fun setAfterBoxSummary() { if (isAdded) { //must check if the fragment is added to the activity val p = findPreference(PrefConstants.AFTER_BOX) if (p != null) { if (shared?.getBoolean(PrefConstants.AFTER_BOX, false) == true) { p.setSummary(R.string.enabledAfterTaxDesc) } else { p.setSummary(R.string.disabledAfterTaxDesc) } } } } /** * Sets the summary for the save box */ protected fun setSaveBoxSummary() { if (isAdded) { //must check if the fragment is added to the activity val p = findPreference(PrefConstants.SAVE_BOX) if (p != null) { if (shared?.getBoolean(PrefConstants.SAVE_BOX, false) == true) { p.setSummary(R.string.enabledSaveDesc) } else { p.setSummary(R.string.disabledSaveDesc) } } } } /** * Sets the summary for the split list */ protected fun setSplitSummary() { if (isAdded) { //must check if the fragment is added to the activity val p = findPreference(PrefConstants.SPLIT_LIST) if (p != null) { p.summary = resources.getString(R.string.splitDesc, shared?.getString(PrefConstants.SPLIT_LIST, PrefConstants.SPLIT_TIP) ?: PrefConstants.SPLIT_TIP) } } } /** * Sets the summary for the combined box */ protected fun setCombinedBoxSummary() { if (isAdded) { //must check if the fragment is added to the activity val p = findPreference(PrefConstants.COMBINED_BOX) if (p != null) { if (shared?.getBoolean(PrefConstants.COMBINED_BOX, false) == true) { p.setSummary(R.string.enabledCombinedDesc) } else { p.setSummary(R.string.disabledCombinedDesc) } } } } /** * Sets the summary for the theme list * String needs to be acquired differently since its being added */ protected fun setThemeListSummary() { if (isAdded) { //must check if the fragment is added to the activity val p = findPreference(PrefConstants.THEME_LIST) if (p != null) { p.summary = resources.getString(R.string.themeDesc, shared?.getString(PrefConstants.THEME_LIST, "Light") ?: "Light") } } } /** * Sets the summary for the color list * String needs to be acquired differently since its being added */ protected fun setColorListSummary() { if (isAdded) { //must check if the fragment is added to the activity val p = findPreference(PrefConstants.COLOR_LIST) if (p != null) { p.summary = resources.getString(R.string.colorDesc, shared?.getString(PrefConstants.COLOR_LIST, "Dynamic") ?: "Dynamic") } } } } /** * The portrait fragment, contains everything */ class PrefsFragment : PCFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) PreferenceManager.setDefaultValues(activity, R.xml.prefs, false) addPreferencesFromResource(R.xml.prefs) setSummaries() shared?.registerOnSharedPreferenceChangeListener(this) } } /** * Left landscape fragment, contains functionality tweaks */ class LandscapePrefsFragment1 : PCFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) PreferenceManager.setDefaultValues(activity, R.xml.prefs, false) addPreferencesFromResource(R.xml.land_prefs1) setSummaries() shared?.registerOnSharedPreferenceChangeListener(this) } /** * Sets the summaries on start */ override fun setSummaries() { setPercentStartSummary() //starting percent setPercentMaxSummary() //max percent setTaxBoxSummary() //Tax box setTaxSummary() //Tax number setAfterBoxSummary() //Calculate after tax box setSaveBoxSummary() //Save box } /** * Sets the summaries on change */ override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { when (key) { PrefConstants.PERCENT_START -> setPercentStartSummary() PrefConstants.PERCENT_MAX -> setPercentMaxSummary() PrefConstants.TAX_BOX -> setTaxBoxSummary() PrefConstants.TAX_INPUT -> setTaxSummary() PrefConstants.AFTER_BOX -> setAfterBoxSummary() PrefConstants.SAVE_BOX -> { setSaveBoxSummary() needsActRestart = true } } } } /*@Override public void onBackPressed() { editor.putBoolean("didJustGoBack", true); //saves back action editor.apply(); if (needsFullRestart) //if combined pref was changed, restart app { editor.putBoolean("needsFullRestart", false); //resets variable editor.apply(); Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage(getBaseContext().getPackageName()); i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); finish(); startActivity(i); } else if (needsActRestart) { Intent last = new Intent(this, CostActivity.class); //remakes last activity, defaults to Cost switch (caller) { case "percent": last = new Intent(this, PercentActivity.class); break; case "split": last = new Intent(this, SplitActivity.class); break; case "results": last = new Intent(this, ResultsActivity.class); break; case "combined": last = new Intent(this, CombinedActivity.class); break; } editor.putBoolean("needsActRestart", false); //resets variable editor.apply(); last.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); startActivity(last); } else super.onBackPressed(); }*/ /** * Right landscape fragment, contains split and design tweaks */ class LandscapePrefsFragment2 : PCFragment() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) PreferenceManager.setDefaultValues(activity, R.xml.prefs, false) addPreferencesFromResource(R.xml.land_prefs2) setSummaries() shared?.registerOnSharedPreferenceChangeListener(this) } /** * Sets the summaries */ override fun setSummaries() { setSplitSummary() //Split list setCombinedBoxSummary() //Combined box setThemeListSummary() //Theme list setColorListSummary() //Color box } override fun onSharedPreferenceChanged(sharedPreferences: SharedPreferences, key: String) { when (key) { PrefConstants.SPLIT_LIST -> setSplitSummary() PrefConstants.COMBINED_BOX -> { setCombinedBoxSummary() needsFullRestart = true } PrefConstants.THEME_LIST -> setThemeListSummary() PrefConstants.COLOR_LIST -> setColorListSummary() } } } companion object { private var needsActRestart: Boolean = false private var needsFullRestart: Boolean = false } }
gpl-3.0
31018ca3fd259252d3dcedc31a2986d7
38.120833
153
0.552325
5.253777
false
false
false
false
JetBrains/intellij-community
plugins/kotlin/gradle/gradle/src/org/jetbrains/kotlin/idea/gradle/configuration/kpm/ModuleDataInitializer.kt
1
2214
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license. package org.jetbrains.kotlin.idea.gradle.configuration.kpm import com.intellij.openapi.extensions.ExtensionPointName import com.intellij.openapi.externalSystem.model.DataNode import com.intellij.openapi.externalSystem.model.project.ModuleData import com.intellij.openapi.externalSystem.model.project.ProjectData import org.gradle.tooling.model.idea.IdeaModule import org.jetbrains.kotlin.config.ExternalSystemRunTask import org.jetbrains.kotlin.gradle.idea.kpm.IdeaKpmFragment import org.jetbrains.kotlin.gradle.idea.kpm.IdeaKpmProject import org.jetbrains.plugins.gradle.service.project.ProjectResolverContext interface ModuleDataInitializer { fun initialize( gradleModule: IdeaModule, mainModuleNode: DataNode<ModuleData>, projectDataNode: DataNode<ProjectData>, resolverCtx: ProjectResolverContext, initializerContext: Context ) interface Context { //TODO replace with Key-Value registry with proper visibility and immutability var model: IdeaKpmProject? var jdkName: String? var moduleGroup: Array<String>? var mainModuleConfigPath: String? var mainModuleFileDirectoryPath: String? var sourceSetToRunTasks: Map<IdeaKpmFragment, Collection<ExternalSystemRunTask>> companion object { @JvmStatic val EMPTY: Context get() = object : Context { override var model: IdeaKpmProject? = null override var jdkName: String? = null override var moduleGroup: Array<String>? = null override var mainModuleConfigPath: String? = null override var mainModuleFileDirectoryPath: String? = null override var sourceSetToRunTasks: Map<IdeaKpmFragment, Collection<ExternalSystemRunTask>> = emptyMap() } } } companion object { @JvmField val EP_NAME: ExtensionPointName<ModuleDataInitializer> = ExtensionPointName.create("org.jetbrains.kotlin.kpm.moduleInitialize") } }
apache-2.0
80b6f2e1b2b855180e87767ab3e8ba21
42.411765
122
0.70551
5.309353
false
true
false
false
zaviyalov/intellij-cleaner
src/main/kotlin/com/github/zaviyalov/intellijcleaner/controller/StageController.kt
1
4578
/* * Copyright (c) 2016 Anton Zaviyalov */ package com.github.zaviyalov.intellijcleaner.controller import com.github.zaviyalov.intellijcleaner.controller.companion.AbstractControllerCompanion import com.github.zaviyalov.intellijcleaner.model.Directory import com.github.zaviyalov.intellijcleaner.util.directory.deleteDirectory import com.github.zaviyalov.intellijcleaner.util.directory.formatSize import com.github.zaviyalov.intellijcleaner.util.directory.listDirectories import com.github.zaviyalov.intellijcleaner.util.loadWindowPreferences import com.github.zaviyalov.intellijcleaner.util.saveWindowPreferences import javafx.application.Platform import javafx.beans.property.SimpleBooleanProperty import javafx.beans.property.SimpleStringProperty import javafx.collections.FXCollections import javafx.collections.ListChangeListener import javafx.collections.ObservableList import javafx.event.EventHandler import javafx.fxml.FXML import javafx.scene.control.* import javafx.stage.Stage import org.controlsfx.control.StatusBar @Suppress("unused") class StageController : AbstractController() { @FXML private val directoryData: ObservableList<Directory> = FXCollections.observableArrayList<Directory>({ arrayOf(it.checkedProperty(), it.pathProperty(), it.sizeProperty()) }) @FXML lateinit private var start: Button @FXML lateinit private var delete: Button @FXML lateinit private var tableView: TableView<Directory> @FXML lateinit private var checkedColumn: TableColumn<Directory, Boolean> @FXML lateinit private var pathColumn: TableColumn<Directory, String> @FXML lateinit private var sizeColumn: TableColumn<Directory, Number> @FXML lateinit private var statusBar: StatusBar @FXML private val scanned = SimpleBooleanProperty(false) private val statusTextProperty = SimpleStringProperty("Ready") @FXML override fun initialize() { tableView.items = directoryData updateData() start.disableProperty().bind(scanned) delete.disableProperty().bind(!scanned) tableView.disableProperty().bind(!scanned) statusBar.textProperty().bind(statusTextProperty) directoryData.addListener(ListChangeListener { statusTextProperty.value = statusBarText() }) } @FXML private fun handleStartButtonAction() { if (directoryData.isNotEmpty()) { directoryData.forEach { it.processSize() } directoryData.dropLast(1).forEach { it.checked = true } directoryData.last().checked = false scanned.value = true } else { Alert(Alert.AlertType.WARNING, "Nothing to scan!").showAndWait() } } @FXML private fun handleDeleteButtonAction() { fun callDeleteDirectories() { val filtered = directoryData.filter { it.checked == true } filtered.forEach(::deleteDirectory) directoryData.removeAll(filtered) } if (directoryData.last().checked) { Alert(Alert.AlertType.WARNING, "You're going to delete current IntelliJ IDEA directory. Continue?", ButtonType.YES, ButtonType.NO) .showAndWait() .filter { it == ButtonType.YES } .ifPresent { callDeleteDirectories() } } else { callDeleteDirectories() } tableView.refresh() } @FXML private fun handleSettingsAction() { val stage = Stage() SettingsStageController.load(stage, tableView.scene.window, this) stage.showAndWait() } @FXML private fun handleAboutAction() { val stage = Stage() AboutStageController.load(stage, tableView.scene.window, this) stage.showAndWait() } @FXML private fun handleExitAction() { Platform.exit() } private fun statusBarText() = "Total: ${formatSize(directoryData.filter { it.checked }.map { it.size }.sum())}" fun updateData() { directoryData.clear() directoryData.addAll(listDirectories()) scanned.value = false } companion object : AbstractControllerCompanion<StageController>() { override val FXML_PATH: String = "stage.fxml" override val WINDOW_TITLE = "IntelliJ Cleaner" override fun load(stage: Stage): StageController { val result = super.load(stage) stage.onCloseRequest = EventHandler { stage.saveWindowPreferences() } stage.loadWindowPreferences() return result } } }
mit
52cff7775f5c0daf735b95b2c9956745
36.227642
115
0.692661
4.808824
false
false
false
false
allotria/intellij-community
platform/platform-impl/src/com/intellij/internal/statistic/collectors/fus/actions/persistence/ActionsEventLogGroup.kt
2
2259
// 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.internal.statistic.collectors.fus.actions.persistence import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventField import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.eventLog.events.VarargEventId import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector class ActionsEventLogGroup : CounterUsagesCollector() { override fun getGroup(): EventLogGroup = GROUP companion object { const val ACTION_INVOKED_EVENT_ID = "action.invoked" @JvmField val GROUP = EventLogGroup("actions", 60) @JvmField val ACTION_ID = EventFields.StringValidatedByCustomRule("action_id", "action") @JvmField val ACTION_CLASS = EventFields.StringValidatedByCustomRule("class", "class_name") @JvmField val ACTION_PARENT = EventFields.StringValidatedByCustomRule("parent", "class_name") @JvmField val TOGGLE_ACTION = EventFields.Boolean("enable") @JvmField val CONTEXT_MENU = EventFields.Boolean("context_menu") @JvmField val DUMB = EventFields.Boolean("dumb") @JvmField val ADDITIONAL = EventFields.createAdditionalDataField(GROUP.id, ACTION_INVOKED_EVENT_ID) @JvmField val ACTION_INVOKED = registerActionInvokedEvent(GROUP, ACTION_INVOKED_EVENT_ID, ADDITIONAL, EventFields.Language) @JvmStatic fun registerActionInvokedEvent(group: EventLogGroup, eventId: String, vararg extraFields: EventField<*>): VarargEventId { return group.registerVarargEvent( eventId, EventFields.PluginInfoFromInstance, EventFields.InputEvent, EventFields.ActionPlace, EventFields.CurrentFile, TOGGLE_ACTION, CONTEXT_MENU, DUMB, ACTION_ID, ACTION_CLASS, ACTION_PARENT, *extraFields ) } @JvmField val CUSTOM_ACTION_INVOKED = GROUP.registerEvent( "custom.action.invoked", EventFields.StringValidatedByCustomRule("action_id", "action"), EventFields.InputEvent) } }
apache-2.0
f402549bb23805691ab95656225afd61
32.731343
140
0.733953
4.70625
false
false
false
false
allotria/intellij-community
platform/vcs-log/impl/src/com/intellij/vcs/log/history/VcsDirectoryRenamesProvider.kt
4
3660
// Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.intellij.vcs.log.history import com.intellij.openapi.components.PersistentStateComponent import com.intellij.openapi.components.State import com.intellij.openapi.components.Storage import com.intellij.openapi.components.service import com.intellij.openapi.project.Project import com.intellij.openapi.vcs.FilePath import com.intellij.openapi.vfs.LocalFileSystem import com.intellij.openapi.vfs.VirtualFile import com.intellij.util.xmlb.annotations.Attribute import com.intellij.util.xmlb.annotations.Tag import com.intellij.util.xmlb.annotations.XCollection import com.intellij.vcs.log.CommitId import com.intellij.vcs.log.impl.HashImpl import com.intellij.vcs.log.util.VcsLogUtil import com.intellij.vcsUtil.VcsFileUtil import com.intellij.vcsUtil.VcsUtil import java.util.concurrent.atomic.AtomicReference @State(name = "VcsDirectoryRenames", storages = [Storage(value = "vcs.xml")]) internal class VcsDirectoryRenamesProvider : PersistentStateComponent<Array<RenameRecord>> { private val renames: AtomicReference<Map<EdgeData<CommitId>, EdgeData<FilePath>>> = AtomicReference(emptyMap()) val renamesMap: Map<EdgeData<CommitId>, EdgeData<FilePath>> get() = renames.get() override fun getState(): Array<RenameRecord>? { return renames.get().entries.groupBy({ it.value }) { it.key }.map { entry -> val paths = entry.key val commits = entry.value val root = commits.first().parent.root RenameRecord(root.path, VcsFileUtil.relativePath(root, paths.parent), VcsFileUtil.relativePath(root, paths.child), commits.map { Hashes(it) }.toTypedArray()) }.toTypedArray() } override fun loadState(state: Array<RenameRecord>) { renames.set(state.flatMap { record -> record.getCommitsAndPaths() }.toMap(linkedMapOf())) } companion object { @JvmStatic fun getInstance(project: Project): VcsDirectoryRenamesProvider = project.service() } } @Tag("hashes") internal data class Hashes(@Attribute("parentHash") val parentHash: String, @Attribute("childHash") val childHash: String) { internal constructor() : this("", "") internal constructor(edgeData: EdgeData<CommitId>) : this(edgeData.parent.hash.asString(), edgeData.child.hash.asString()) fun getCommitIds(rootFile: VirtualFile): EdgeData<CommitId>? { if (!VcsLogUtil.HASH_REGEX.matcher(parentHash).matches() || !VcsLogUtil.HASH_REGEX.matcher(childHash).matches()) return null return EdgeData(CommitId(HashImpl.build(parentHash), rootFile), CommitId(HashImpl.build(childHash), rootFile)) } } @Tag("rename") internal class RenameRecord(@Attribute("root") val root: String, @Attribute("parentPath") val parentPath: String, @Attribute("childPath") val childPath: String, @XCollection(propertyElementName = "hashesList") val hashes: Array<Hashes>) { internal constructor() : this("", "", "", emptyArray()) private val rootFile by lazy { LocalFileSystem.getInstance().findFileByPath(root) } private fun getPaths(root: VirtualFile) = EdgeData(VcsUtil.getFilePath(root, parentPath, true), VcsUtil.getFilePath(root, childPath, true)) private fun getCommits(root: VirtualFile) = hashes.mapNotNull { it.getCommitIds(root) } fun getCommitsAndPaths(): List<Pair<EdgeData<CommitId>, EdgeData<FilePath>>> { return rootFile?.let { root -> val paths = getPaths(root) getCommits(root).map { Pair(it, paths) } } ?: emptyList() } }
apache-2.0
82815daa72c3c13da10714e5970d3b72
43.646341
140
0.730328
4.24102
false
false
false
false
benoitletondor/EasyBudget
Android/EasyBudget/app/src/main/java/com/benoitletondor/easybudgetapp/cloudstorage/FirebaseStorage.kt
1
3312
/* * Copyright 2022 Benoit LETONDOR * * 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.benoitletondor.easybudgetapp.cloudstorage import android.net.Uri import com.google.firebase.storage.StorageException import kotlinx.coroutines.suspendCancellableCoroutine import java.io.File import java.util.* import kotlin.coroutines.resume import kotlin.coroutines.resumeWithException class FirebaseStorage(private val storage: com.google.firebase.storage.FirebaseStorage) : CloudStorage { override suspend fun uploadFile(file: File, path: String) { uploadFile(file, path, null) } override suspend fun uploadFile(file: File, path: String, progressListener: ((Double) -> Unit)?) = suspendCancellableCoroutine<Unit> { continuation -> val reference = storage.reference.child(path) reference.putFile(Uri.fromFile(file)).addOnSuccessListener { continuation.resume(Unit) }.addOnFailureListener { error -> continuation.resumeWithException(error) }.addOnProgressListener { taskSnapshot -> progressListener?.invoke(taskSnapshot.bytesTransferred.toDouble() / taskSnapshot.totalByteCount.toDouble()) } } override suspend fun getFileMetaData(path: String) = suspendCancellableCoroutine<FileMetaData?> { continuation -> val reference = storage.reference.child(path) reference.metadata.addOnSuccessListener { metadata -> continuation.resume(FileMetaData(path, Date(metadata.updatedTimeMillis))) }.addOnFailureListener { error -> if( error.isFileNotFoundError() ) { continuation.resume(null) } else { continuation.resumeWithException(error) } } } override suspend fun downloadFile(path: String, toFile: File) = suspendCancellableCoroutine<Unit> { continuation -> val reference = storage.reference.child(path) reference.getFile(toFile).addOnSuccessListener { continuation.resume(Unit) }.addOnFailureListener { error -> continuation.resumeWithException(error) } } override suspend fun deleteFile(path: String): Boolean = suspendCancellableCoroutine { continuation -> val reference = storage.reference.child(path) reference.delete().addOnSuccessListener { continuation.resume(true) }.addOnFailureListener { error -> if( error.isFileNotFoundError() ) { continuation.resume(false) } else { continuation.resumeWithException(error) } } } } private fun Throwable.isFileNotFoundError(): Boolean = this is StorageException && this.errorCode == StorageException.ERROR_OBJECT_NOT_FOUND
apache-2.0
48228dab994aae797fdc52772aa48fa9
37.523256
154
0.690519
5.126935
false
false
false
false
code-helix/slatekit
src/lib/kotlin/slatekit-tests/src/test/kotlin/test/setup/MyAuthProvider.kt
1
1039
/** * <slate_header> * url: www.slatekit.com * git: www.github.com/code-helix/slatekit * org: www.codehelix.co * author: Kishore Reddy * copyright: 2016 CodeHelix Solutions Inc. * license: refer to website and/or github * about: A tool-kit, utility library and server-backend * mantra: Simplicity above all else * </slate_header> */ package test.setup import slatekit.apis.support.Authenticator import slatekit.common.info.ApiKey import slatekit.requests.Request // ======================================================================================= // AUTH PROVIDER: Implement your own custom authentication/permission provider. // NOTE: You can also use own pre-built authorization provider which has // support for users, roles, permissions // ======================================================================================= class MyAuthProvider(val user:String, val roles:String, keys:List<ApiKey>?) : Authenticator(keys ?: listOf()) { override fun getUserRoles(cmd: Request):String{ return roles } }
apache-2.0
8b6026d7a4882dde8d365ab5a190ad4d
32.516129
109
0.618864
4.557018
false
false
false
false
leafclick/intellij-community
plugins/gradle/testSources/org/jetbrains/plugins/gradle/execution/GradleRunAnythingProviderTestCase.kt
1
3378
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package org.jetbrains.plugins.gradle.execution import com.intellij.ide.actions.runAnything.RunAnythingContext import com.intellij.ide.actions.runAnything.activity.RunAnythingProvider import com.intellij.openapi.actionSystem.DataContext import com.intellij.openapi.actionSystem.impl.SimpleDataContext import com.intellij.openapi.module.ModuleManager import com.intellij.openapi.util.text.StringUtil import groovyjarjarcommonscli.Option import org.jetbrains.plugins.gradle.importing.GradleImportingTestCase import org.jetbrains.plugins.gradle.service.execution.cmd.GradleCommandLineOptionsProvider import org.junit.runners.Parameterized abstract class GradleRunAnythingProviderTestCase : GradleImportingTestCase() { private lateinit var myDataContext: DataContext private lateinit var provider: GradleRunAnythingProvider override fun setUp() { super.setUp() provider = GradleRunAnythingProvider() myDataContext = SimpleDataContext.getProjectContext(myProject) } fun getRootProjectTasks(prefix: String = "") = listOf("init", "wrapper").map { prefix + it } fun getCommonTasks(prefix: String = "") = listOf("components", "projects", "dependentComponents", "buildEnvironment", "dependencyInsight", "dependencies", "prepareKotlinBuildScriptModel", "help", "model", "properties", "tasks").map { prefix + it } fun getGradleOptions(prefix: String = ""): List<String> { val options = GradleCommandLineOptionsProvider.getSupportedOptions().options.filterIsInstance<Option>() val longOptions = options.mapNotNull { it.longOpt }.map { "--$it" } val shortOptions = options.mapNotNull { it.opt }.map { "-$it" } return (longOptions + shortOptions).map { prefix + it } } fun withVariantsFor(command: String, moduleName: String, action: (List<String>) -> Unit) { val moduleManager = ModuleManager.getInstance(myProject) val module = moduleManager.findModuleByName(moduleName) requireNotNull(module) { "Module '$moduleName' not found at ${moduleManager.modules.map { it.name }}" } withVariantsFor(RunAnythingContext.ModuleContext(module), command, action) } fun withVariantsFor(command: String, action: (List<String>) -> Unit) { withVariantsFor(RunAnythingContext.ProjectContext(myProject), command, action) } private fun withVariantsFor(context: RunAnythingContext, command: String, action: (List<String>) -> Unit) { val contextKey = RunAnythingProvider.EXECUTING_CONTEXT.name val dataContext = SimpleDataContext.getSimpleContext(contextKey, context, myDataContext) val variants = provider.getValues(dataContext, "gradle $command") action(variants.map { StringUtil.trimStart(it, "gradle ") }) } fun createTestJavaClass(name: String) { createProjectSubFile("src/test/java/org/jetbrains/$name.java", """ package org.jetbrains; import org.junit.Test; public class $name { @Test public void test() {} } """.trimIndent()) } companion object { /** * It's sufficient to run the test against one gradle version */ @Parameterized.Parameters(name = "with Gradle-{0}") @JvmStatic fun tests(): Collection<Array<out String>> = arrayListOf(arrayOf(BASE_GRADLE_VERSION)) } }
apache-2.0
360c0152886a150aaaa2cbfe23b30bc4
43.460526
140
0.746596
4.534228
false
true
false
false
zdary/intellij-community
platform/platform-impl/src/com/intellij/featureStatistics/fusCollectors/WSLInstallationsCollector.kt
2
2253
// 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.featureStatistics.fusCollectors import com.intellij.execution.ExecutionException import com.intellij.execution.configurations.GeneralCommandLine import com.intellij.execution.util.ExecUtil import com.intellij.execution.wsl.WSLDistribution import com.intellij.internal.statistic.beans.MetricEvent import com.intellij.internal.statistic.eventLog.EventLogGroup import com.intellij.internal.statistic.eventLog.events.EventFields import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector import com.intellij.openapi.diagnostic.logger import com.intellij.openapi.util.SystemInfo import java.nio.charset.StandardCharsets class WSLInstallationsCollector : ApplicationUsagesCollector() { companion object { private val group = EventLogGroup("wsl.installations", 1) private val installationCountEvent = group.registerEvent("count", EventFields.Int("version"), EventFields.Int("count")) private val LOG = logger<WSLInstallationsCollector>() } override fun getGroup(): EventLogGroup { return Companion.group } override fun getMetrics(): Set<MetricEvent> { if (!SystemInfo.isWin10OrNewer) return emptySet() val wslExe = WSLDistribution.findWslExe() ?: return emptySet() val output = try { ExecUtil.execAndGetOutput(GeneralCommandLine(wslExe.toString(), "-l", "-v").withCharset(StandardCharsets.UTF_16LE), 10_000) } catch(e: ExecutionException) { LOG.info("Failed to run wsl: " + e.message) return emptySet() } if (output.exitCode != 0) { LOG.info("Failed to run wsl: exit code ${output.exitCode}, stderr ${output.stderr}") return emptySet() } //C:\JetBrains>wsl -l -v // NAME STATE VERSION //* Ubuntu Running 2 val installations = output.stdoutLines .drop(1) .groupBy { it.substringAfterLast(' ') } return installations.mapNotNullTo(HashSet()) { (versionString, distributions) -> versionString.toIntOrNull()?.let { version -> installationCountEvent.metric(version, distributions.size) } } } }
apache-2.0
f8b53a403692156252e31cfa3f39da8b
39.232143
140
0.73502
4.51503
false
false
false
false
leafclick/intellij-community
python/python-psi-impl/src/com/jetbrains/python/codeInsight/typing/PyProtocols.kt
1
3101
// Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file. package com.jetbrains.python.codeInsight.typing import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.PROTOCOL import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider.PROTOCOL_EXT import com.jetbrains.python.psi.AccessDirection import com.jetbrains.python.psi.PyClass import com.jetbrains.python.psi.PyPossibleClassMember import com.jetbrains.python.psi.PyTypedElement import com.jetbrains.python.psi.resolve.PyResolveContext import com.jetbrains.python.psi.resolve.RatedResolveResult import com.jetbrains.python.psi.types.PyClassLikeType import com.jetbrains.python.psi.types.PyClassType import com.jetbrains.python.psi.types.PyType import com.jetbrains.python.psi.types.TypeEvalContext fun isProtocol(classLikeType: PyClassLikeType, context: TypeEvalContext): Boolean = containsProtocol(classLikeType.getSuperClassTypes(context)) fun isProtocol(cls: PyClass, context: TypeEvalContext): Boolean = containsProtocol(cls.getSuperClassTypes(context)) fun matchingProtocolDefinitions(expected: PyType?, actual: PyType?, context: TypeEvalContext): Boolean = expected is PyClassLikeType && actual is PyClassLikeType && expected.isDefinition && actual.isDefinition && isProtocol(expected, context) && isProtocol(actual, context) typealias ProtocolAndSubclassElements = Pair<PyTypedElement, List<RatedResolveResult>?> fun inspectProtocolSubclass(protocol: PyClassType, subclass: PyClassType, context: TypeEvalContext): List<ProtocolAndSubclassElements> { val subclassAsInstance = subclass.toInstance() val resolveContext = PyResolveContext.defaultContext().withTypeEvalContext(context) val result = mutableListOf<Pair<PyTypedElement, List<RatedResolveResult>?>>() protocol.toInstance().visitMembers( { e -> if (e is PyTypedElement) { if (e is PyPossibleClassMember) { val cls = e.containingClass if (cls != null && !isProtocol(cls, context)) { return@visitMembers true } } val name = e.name ?: return@visitMembers true val resolveResults = subclassAsInstance.resolveMember(name, null, AccessDirection.READ, resolveContext) result.add(Pair(e, resolveResults)) } true }, true, context ) return result } private fun containsProtocol(types: List<PyClassLikeType?>) = types.any { type -> val classQName = type?.classQName PROTOCOL == classQName || PROTOCOL_EXT == classQName }
apache-2.0
7bba74da5a3db7c4c9858ed875a648af
47.453125
143
0.643018
5.449912
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/callableReference/property/simpleMutableTopLevel.kt
5
382
data class Box(val value: String) var pr = Box("first") fun box(): String { val property = ::pr if (property.get() != Box("first")) return "Fail value: ${property.get()}" if (property.name != "pr") return "Fail name: ${property.name}" property.set(Box("second")) if (property.get().value != "second") return "Fail value 2: ${property.get()}" return "OK" }
apache-2.0
bbcc5252d87c67d1933c142ab3765b0d
30.833333
82
0.60733
3.380531
false
false
false
false
JuliusKunze/kotlin-native
backend.native/tests/external/codegen/box/coroutines/controlFlow/whileStatement.kt
2
1019
// WITH_RUNTIME // WITH_COROUTINES import helpers.* import kotlin.coroutines.experimental.* import kotlin.coroutines.experimental.intrinsics.* class Controller { var result = "" suspend fun <T> suspendWithResult(value: T): T = suspendCoroutineOrReturn { c -> c.resume(value) COROUTINE_SUSPENDED } } fun builder(c: suspend Controller.() -> Unit): String { val controller = Controller() c.startCoroutine(controller, EmptyContinuation) return controller.result } fun box(): String { var value = builder { var x = 1 while (suspendWithResult(x) <= 3) { result += x++ } result += "." } if (value != "123.") return "fail: suspend as while condition: $value" value = builder { var x = 1 while (x <= 3) { result += suspendWithResult(x++) result += ";" } result += "." } if (value != "1;2;3;.") return "fail: suspend in while body: $value" return "OK" }
apache-2.0
2236fa158d67f4a0abef080a28acf8ea
22.159091
84
0.57213
4.142276
false
false
false
false
FirebaseExtended/mlkit-material-android
app/src/main/java/com/google/firebase/ml/md/kotlin/productsearch/BottomSheetScrimView.kt
1
6056
/* * Copyright 2019 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.firebase.ml.md.kotlin.productsearch import android.content.Context import android.graphics.Bitmap import android.graphics.Canvas import android.graphics.Color import android.graphics.Paint import android.graphics.RectF import android.util.AttributeSet import android.view.View import androidx.core.content.ContextCompat import com.google.common.base.Preconditions.checkArgument import com.google.firebase.ml.md.R /** Draws the scrim of bottom sheet with object thumbnail highlighted. */ class BottomSheetScrimView(context: Context, attrs: AttributeSet) : View(context, attrs) { private val scrimPaint: Paint private val thumbnailPaint: Paint private val boxPaint: Paint private val thumbnailHeight: Int private val thumbnailMargin: Int private val boxCornerRadius: Int private var thumbnailBitmap: Bitmap? = null private var thumbnailRect: RectF? = null private var downPercentInCollapsed: Float = 0f init { val resources = context.resources scrimPaint = Paint().apply { color = ContextCompat.getColor(context, R.color.dark) } thumbnailPaint = Paint() boxPaint = Paint().apply { style = Paint.Style.STROKE strokeWidth = resources.getDimensionPixelOffset(R.dimen.object_thumbnail_stroke_width).toFloat() color = Color.WHITE } thumbnailHeight = resources.getDimensionPixelOffset(R.dimen.object_thumbnail_height) thumbnailMargin = resources.getDimensionPixelOffset(R.dimen.object_thumbnail_margin) boxCornerRadius = resources.getDimensionPixelOffset(R.dimen.bounding_box_corner_radius) } /** * Translates the object thumbnail up or down along with bottom sheet's sliding movement, with * keeping thumbnail size fixed. */ fun updateWithThumbnailTranslate( thumbnailBitmap: Bitmap, collapsedStateHeight: Int, slideOffset: Float, bottomSheet: View ) { this.thumbnailBitmap = thumbnailBitmap val currentSheetHeight: Float if (slideOffset < 0) { downPercentInCollapsed = -slideOffset currentSheetHeight = collapsedStateHeight * (1 + slideOffset) } else { downPercentInCollapsed = 0f currentSheetHeight = collapsedStateHeight + (bottomSheet.height - collapsedStateHeight) * slideOffset } thumbnailRect = RectF().apply { val thumbnailWidth = thumbnailBitmap.width.toFloat() / thumbnailBitmap.height.toFloat() * thumbnailHeight.toFloat() left = thumbnailMargin.toFloat() top = height.toFloat() - currentSheetHeight - thumbnailMargin.toFloat() - thumbnailHeight.toFloat() right = left + thumbnailWidth bottom = top + thumbnailHeight } invalidate() } /** * Translates the object thumbnail from original bounding box location to at where the bottom * sheet is settled as COLLAPSED state, with its size scales gradually. * * * It's only used by sliding the sheet up from hidden state to collapsed state. */ fun updateWithThumbnailTranslateAndScale( thumbnailBitmap: Bitmap, collapsedStateHeight: Int, slideOffset: Float, srcThumbnailRect: RectF ) { checkArgument( slideOffset <= 0, "Scale mode works only when the sheet is between hidden and collapsed states." ) this.thumbnailBitmap = thumbnailBitmap this.downPercentInCollapsed = 0f thumbnailRect = RectF().apply { val dstX = thumbnailMargin.toFloat() val dstY = (height - collapsedStateHeight - thumbnailMargin - thumbnailHeight).toFloat() val dstHeight = thumbnailHeight.toFloat() val dstWidth = srcThumbnailRect.width() / srcThumbnailRect.height() * dstHeight val dstRect = RectF(dstX, dstY, dstX + dstWidth, dstY + dstHeight) val progressToCollapsedState = 1 + slideOffset left = srcThumbnailRect.left + (dstRect.left - srcThumbnailRect.left) * progressToCollapsedState top = srcThumbnailRect.top + (dstRect.top - srcThumbnailRect.top) * progressToCollapsedState right = srcThumbnailRect.right + (dstRect.right - srcThumbnailRect.right) * progressToCollapsedState bottom = srcThumbnailRect.bottom + (dstRect.bottom - srcThumbnailRect.bottom) * progressToCollapsedState } invalidate() } override fun onDraw(canvas: Canvas) { super.onDraw(canvas) // Draws the dark background. val bitmap = thumbnailBitmap ?: return val rect = thumbnailRect ?: return canvas.drawRect(0f, 0f, width.toFloat(), height.toFloat(), scrimPaint) if (downPercentInCollapsed < DOWN_PERCENT_TO_HIDE_THUMBNAIL) { val alpha = ((1 - downPercentInCollapsed / DOWN_PERCENT_TO_HIDE_THUMBNAIL) * 255).toInt() // Draws the object thumbnail. thumbnailPaint.alpha = alpha canvas.drawBitmap(bitmap, null, rect, thumbnailPaint) // Draws the bounding box. boxPaint.alpha = alpha canvas.drawRoundRect(rect, boxCornerRadius.toFloat(), boxCornerRadius.toFloat(), boxPaint) } } companion object { private const val DOWN_PERCENT_TO_HIDE_THUMBNAIL = 0.42f } }
apache-2.0
9b9d95f7b4ad72d8c0ce780ce4ef7a1a
37.329114
116
0.676354
4.742365
false
false
false
false