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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
telegram-bots/telegram-channels-feed
|
tg/src/main/kotlin/com/github/telegram_bots/channels_feed/tg/service/updater/PostsUpdater.kt
|
1
|
7190
|
package com.github.telegram_bots.channels_feed.tg.service.updater
import com.github.badoualy.telegram.api.TelegramClient
import com.github.badoualy.telegram.tl.api.TLMessage
import com.github.badoualy.telegram.tl.exception.RpcErrorException
import com.github.telegram_bots.channels_feed.tg.config.properties.ProcessingProperties
import com.github.telegram_bots.channels_feed.tg.domain.Channel
import com.github.telegram_bots.channels_feed.tg.domain.ProcessedPostGroup
import com.github.telegram_bots.channels_feed.tg.domain.RawPostData
import com.github.telegram_bots.channels_feed.tg.service.ChannelRepository
import com.github.telegram_bots.channels_feed.tg.service.job.*
import com.github.telegram_bots.channels_feed.tg.service.processor.PostProcessor
import com.github.telegram_bots.channels_feed.tg.util.randomDelay
import io.reactivex.Completable
import io.reactivex.Flowable
import io.reactivex.Maybe
import io.reactivex.Single
import io.reactivex.disposables.Disposable
import io.reactivex.rxkotlin.zipWith
import io.reactivex.schedulers.Schedulers
import mu.KLogging
import org.springframework.cloud.stream.annotation.EnableBinding
import org.springframework.cloud.stream.messaging.Source
import org.springframework.stereotype.Service
import java.util.concurrent.TimeUnit
import javax.annotation.PreDestroy
@Service
@EnableBinding(Source::class)
class PostsUpdater(
private val props: ProcessingProperties,
private val client: TelegramClient,
private val source: Source,
private val repository: ChannelRepository,
private val processors: Collection<PostProcessor>
) : AbstractUpdater("posts-updater") {
companion object : KLogging()
@PreDestroy
override fun onDestroy() {
super.onDestroy()
client.close()
}
override fun run(): Completable {
return iterateChannels()
.flatMapSingle(this::resolve)
.flatMapMaybe(this::download)
.flatMapSingle(this::prepare)
.flatMap(this::process)
.flatMapSingle(this::sendToQueue)
.flatMapCompletable(this::markAsDownloaded)
.doOnSubscribe(this::onSubscribe)
.doOnTerminate(this::onTerminate)
}
private fun iterateChannels(): Flowable<Channel> {
return repository.list()
.repeatWhen { it.delay(1, TimeUnit.SECONDS) }
.concatMap {
Single.just(it)
.randomDelay(
delayMin = props.postsIntervalMin,
delayMax = props.postsIntervalMax,
unit = props.postsIntervalTimeUnit,
scheduler = scheduler
)
.toFlowable()
}
.doOnNext { logger.info { "[PROCESS CHANNEL] $it" } }
}
private fun resolve(channel: Channel): Single<Channel> {
return Maybe.just(channel)
.filter(Channel::isEmpty)
.concatMap { ch ->
Single.just(ch)
.randomDelay(
delayMin = props.channelsIntervalMin,
delayMax = props.channelsIntervalMax,
unit = props.channelsIntervalTimeUnit,
scheduler = scheduler
)
.flatMap(ResolveChannelInfoJob(client))
.flatMap(ResolveChannelCreationDateJob(client))
.flatMap(ResolveChannelLastPostIdJob(client))
.flatMap { repository.update(it).andThen(Single.just(it)) }
.retry(this::retry)
.doOnSuccess { logger.info { "[RESOLVE CHANNEL] $ch" } }
.doOnSubscribe { client.accountUpdateStatus(false) }
.doOnSuccess { client.accountUpdateStatus(true) }
.toMaybe()
}
.toSingle(channel)
}
private fun download(channel: Channel): Maybe<Pair<Channel, List<TLMessage>>> {
return Single.just(channel)
.retry(this::retry)
.flatMapPublisher(DownloadPostsJob(client, props.postsBatchSize))
.toList()
.filter(List<TLMessage>::isNotEmpty)
.zipWith(Maybe.just(channel), { msgs, ch -> ch to msgs })
.doOnSuccess { (ch, msgs) -> logger.info { "[DOWNLOAD POSTS] ${msgs.size}x $ch" } }
.doOnSubscribe { client.accountUpdateStatus(false) }
.doOnComplete { client.accountUpdateStatus(true) }
}
private fun prepare(pair: Pair<Channel, List<TLMessage>>): Single<List<RawPostData>> {
val (channel, msgs) = pair
return Flowable.fromIterable(msgs)
.zipWith(Single.just(channel).repeat())
.map { (msg, ch) -> RawPostData(ch, msg) }
.toList()
.doOnSubscribe { logger.info { "[PREPARE POSTS] ${msgs.size}x $channel" } }
}
private fun process(list: List<RawPostData>): Flowable<Pair<RawPostData, ProcessedPostGroup>> {
return Flowable.fromIterable(list)
.flatMapSingle { raw ->
Single.just(raw)
.subscribeOn(Schedulers.computation())
.flatMap(ProcessPostJob(processors))
.zipWith(Single.just(raw), { p, r -> r to p })
}
.sorted { (_, group1), (_, group2) -> group1.postId.compareTo(group2.postId) }
.doOnSubscribe { logger.info { "[PROCESS POSTS] ${list.size}x ${list.firstOrNull()?.channel}" } }
}
private fun sendToQueue(pair: Pair<RawPostData, ProcessedPostGroup>): Single<RawPostData> {
val (raw, processed) = pair
return Single.just(processed)
.subscribeOn(Schedulers.single())
.flatMapCompletable(SendPostToQueueJob(source))
.doOnSubscribe { logger.debug { "[SEND TO QUEUE] $processed" } }
.andThen(Single.just(raw))
}
private fun markAsDownloaded(raw: RawPostData): Completable {
return Single.just(raw)
.subscribeOn(Schedulers.io())
.map { (channel, msg) -> channel.copy(lastPostId = msg.id) }
.doOnSuccess { logger.debug { "[MARK DOWNLOADED] $it" } }
.flatMapCompletable(repository::update)
}
private fun onSubscribe(disposable: Disposable) = logger.info { "[START PROCESSING]" }
private fun onTerminate() = logger.info { "[STOP PROCESSING]" }
private fun retry(count: Int, throwable: Throwable): Boolean {
return when {
count < 10 && throwable is RpcErrorException && throwable.code == 420 -> {
TimeUnit.SECONDS.sleep(throwable.tagInteger.toLong() / 2)
return true
}
else -> false
}
}
}
|
mit
|
82eb8d4c4c963689a181011fe9b7b709
| 43.110429 | 113 | 0.585675 | 4.858108 | false | false | false | false |
rhdunn/xquery-intellij-plugin
|
src/plugin-marklogic/main/uk/co/reecedunn/intellij/plugin/marklogic/query/rest/MarkLogicRunQuery.kt
|
1
|
5734
|
/*
* Copyright (C) 2018-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.marklogic.query.rest
import com.google.gson.JsonObject
import com.intellij.lang.Language
import com.intellij.openapi.vfs.VirtualFile
import org.apache.http.client.methods.HttpUriRequest
import org.apache.http.client.methods.RequestBuilder
import uk.co.reecedunn.intellij.plugin.core.http.HttpStatusException
import uk.co.reecedunn.intellij.plugin.core.http.mime.MimeResponse
import uk.co.reecedunn.intellij.plugin.core.http.toStringMessage
import uk.co.reecedunn.intellij.plugin.core.lang.getLanguageMimeTypes
import uk.co.reecedunn.intellij.plugin.core.vfs.decode
import uk.co.reecedunn.intellij.plugin.intellij.lang.XPathSubset
import uk.co.reecedunn.intellij.plugin.marklogic.resources.MarkLogicQueries
import uk.co.reecedunn.intellij.plugin.processor.query.QueryError
import uk.co.reecedunn.intellij.plugin.processor.query.QueryResults
import uk.co.reecedunn.intellij.plugin.processor.query.QueryServer
import uk.co.reecedunn.intellij.plugin.processor.query.http.BuildableQuery
import uk.co.reecedunn.intellij.plugin.processor.query.http.HttpConnection
import uk.co.reecedunn.intellij.plugin.processor.run.RunnableQuery
import uk.co.reecedunn.intellij.plugin.processor.run.StoppableQuery
import uk.co.reecedunn.intellij.plugin.processor.validate.ValidatableQuery
import uk.co.reecedunn.intellij.plugin.xdm.types.impl.values.XsDuration
import uk.co.reecedunn.intellij.plugin.xdm.types.impl.values.toXsDuration
import uk.co.reecedunn.intellij.plugin.xpm.module.path.XpmModuleUri
import uk.co.reecedunn.intellij.plugin.xquery.lang.XQuery
internal class MarkLogicRunQuery(
private val builder: RequestBuilder,
private val queryParams: JsonObject,
private val queryFile: VirtualFile,
private val connection: HttpConnection,
private val processor: MarkLogicQueryProcessor,
private var queryId: String?
) : RunnableQuery, ValidatableQuery, BuildableQuery, StoppableQuery {
private var variables: JsonObject = JsonObject()
private var types: JsonObject = JsonObject()
override var rdfOutputFormat: Language? = null
override var updating: Boolean = false
override var xpathSubset: XPathSubset = XPathSubset.XPath
override var server: String = ""
override var database: String = ""
override var modulePath: String = ""
private var contextValue: String = ""
private var contextPath: String = ""
override fun bindVariable(name: String, value: Any?, type: String?) {
variables.addProperty(name, value as String? ?: "")
types.addProperty(name, type)
}
override fun bindContextItem(value: Any?, type: String?) {
// NOTE: Only supported for XSLT files.
when (value) {
is XpmModuleUri -> contextPath = value.path
is VirtualFile -> contextValue = value.decode()!!
else -> contextValue = value.toString()
}
}
@Suppress("DuplicatedCode")
override fun request(): HttpUriRequest {
val params = queryParams.deepCopy()
params.addProperty("vars", variables.toString())
params.addProperty("types", types.toString())
params.addProperty("rdf-output-format", rdfOutputFormat?.getLanguageMimeTypes()?.get(0) ?: "")
params.addProperty("updating", updating.toString())
params.addProperty("server", if (server == QueryServer.NONE) "" else server)
params.addProperty("database", if (database == QueryServer.NONE) "" else database)
params.addProperty("module-root", modulePath)
params.addProperty("context-value", contextValue)
params.addProperty("context-path", contextPath)
builder.addParameter("vars", params.toString())
builder.charset = Charsets.UTF_8
return builder.build()
}
override fun run(): QueryResults {
val (statusLine, message) = connection.execute(request()).toStringMessage()
return if (queryId != null) {
val results = MimeResponse(message).queryResults(queryFile).iterator()
val duration = (results.next().value as String).toXsDuration() ?: XsDuration.ZERO
QueryResults(statusLine, results.asSequence().toList(), duration)
} else {
// The query has been cancelled.
QueryResults(QueryResults.OK, listOf(), XsDuration.ZERO)
}
}
override fun validate(): QueryError? {
val (statusLine, message) = connection.execute(request()).toStringMessage()
if (statusLine.statusCode != 200) {
throw HttpStatusException(statusLine.statusCode, statusLine.reasonPhrase)
}
return try {
MimeResponse(message).queryResults(queryFile)
null
} catch (e: QueryError) {
e
}
}
@Suppress("DuplicatedCode")
override fun stop() {
val query = processor.createRunnableQuery(MarkLogicQueries.Request.Cancel, XQuery)
query.bindVariable("server", "App-Services", "xs:string")
query.bindVariable("queryId", queryId, "xs:string")
queryId = null
query.run()
}
override fun close() {
}
}
|
apache-2.0
|
ec9a72c166efbfa3d70ebc21d0aac2a6
| 39.957143 | 102 | 0.715731 | 4.367098 | false | false | false | false |
PoweRGbg/AndroidAPS
|
app/src/main/java/info/nightscout/androidaps/dialogs/ExtendedBolusDialog.kt
|
3
|
4433
|
package info.nightscout.androidaps.dialogs
import android.content.Intent
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.MainApp
import info.nightscout.androidaps.R
import info.nightscout.androidaps.activities.ErrorHelperActivity
import info.nightscout.androidaps.interfaces.Constraint
import info.nightscout.androidaps.plugins.configBuilder.ConfigBuilderPlugin
import info.nightscout.androidaps.queue.Callback
import info.nightscout.androidaps.utils.HtmlHelper
import info.nightscout.androidaps.utils.OKDialog
import info.nightscout.androidaps.utils.SafeParse
import kotlinx.android.synthetic.main.dialog_extendedbolus.*
import kotlinx.android.synthetic.main.okcancel.*
import java.text.DecimalFormat
import java.util.*
import kotlin.math.abs
class ExtendedBolusDialog : DialogFragmentWithDate() {
override fun onSaveInstanceState(savedInstanceState: Bundle) {
super.onSaveInstanceState(savedInstanceState)
savedInstanceState.putDouble("actions_extendedbolus_insulin", actions_extendedbolus_insulin.value)
savedInstanceState.putDouble("actions_extendedbolus_duration", actions_extendedbolus_duration.value)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
onCreateViewGeneral()
return inflater.inflate(R.layout.dialog_extendedbolus, container, false)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
val pumpDescription = ConfigBuilderPlugin.getPlugin().activePump?.pumpDescription ?: return
val maxInsulin = MainApp.getConstraintChecker().maxExtendedBolusAllowed.value()
val extendedStep = pumpDescription.extendedBolusStep
actions_extendedbolus_insulin.setParams(savedInstanceState?.getDouble("actions_extendedbolus_insulin")
?: extendedStep, extendedStep, maxInsulin, extendedStep, DecimalFormat("0.00"), false, ok)
val extendedDurationStep = pumpDescription.extendedBolusDurationStep
val extendedMaxDuration = pumpDescription.extendedBolusMaxDuration
actions_extendedbolus_duration.setParams(savedInstanceState?.getDouble("actions_extendedbolus_duration")
?: extendedDurationStep, extendedDurationStep, extendedMaxDuration, extendedDurationStep, DecimalFormat("0"), false, ok)
}
override fun submit(): Boolean {
val insulin = SafeParse.stringToDouble(actions_extendedbolus_insulin.text)
val durationInMinutes = SafeParse.stringToInt(actions_extendedbolus_duration.text)
val actions: LinkedList<String> = LinkedList()
val insulinAfterConstraint = MainApp.getConstraintChecker().applyExtendedBolusConstraints(Constraint(insulin)).value()
actions.add(MainApp.gs(R.string.formatinsulinunits, insulinAfterConstraint))
actions.add(MainApp.gs(R.string.duration) + ": " + MainApp.gs(R.string.format_mins, durationInMinutes))
if (abs(insulinAfterConstraint - insulin) > 0.01)
actions.add("<font color='" + MainApp.gc(R.color.warning) + "'>" + MainApp.gs(R.string.constraintapllied) + "</font>")
activity?.let { activity ->
OKDialog.showConfirmation(activity, MainApp.gs(R.string.extended_bolus), HtmlHelper.fromHtml(Joiner.on("<br/>").join(actions)), Runnable {
log.debug("USER ENTRY: EXTENDED BOLUS $insulinAfterConstraint duration: $durationInMinutes")
ConfigBuilderPlugin.getPlugin().commandQueue.extendedBolus(insulinAfterConstraint, durationInMinutes, object : Callback() {
override fun run() {
if (!result.success) {
val i = Intent(MainApp.instance(), ErrorHelperActivity::class.java)
i.putExtra("soundid", R.raw.boluserror)
i.putExtra("status", result.comment)
i.putExtra("title", MainApp.gs(R.string.treatmentdeliveryerror))
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
MainApp.instance().startActivity(i)
}
}
})
}, null)
}
return true
}
}
|
agpl-3.0
|
1dda5287a77e6c7f2e610c6163d25944
| 52.421687 | 150 | 0.711482 | 5.031782 | false | false | false | false |
jiaminglu/kotlin-native
|
backend.native/tests/external/codegen/box/reflection/properties/privateClassVal.kt
|
1
|
759
|
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_REFLECT
import kotlin.reflect.*
import kotlin.reflect.jvm.isAccessible
class Result {
private val value = "OK"
fun ref() = Result::class.memberProperties.single() as KProperty1<Result, String>
}
fun box(): String {
val p = Result().ref()
try {
p.get(Result())
return "Fail: private property is accessible by default"
} catch(e: IllegalCallableAccessException) { }
p.isAccessible = true
val r = p.get(Result())
p.isAccessible = false
try {
p.get(Result())
return "Fail: setAccessible(false) had no effect"
} catch(e: IllegalCallableAccessException) { }
return r
}
|
apache-2.0
|
8227dac1c9f58dbf16368921febdf7b7
| 22 | 85 | 0.653491 | 3.892308 | false | false | false | false |
PlateStack/PlateAPI
|
src/main/kotlin/org/platestack/api/plugin/plate-plugins.kt
|
1
|
8040
|
/*
* Copyright (C) 2017 José Roberto de Araújo Júnior
*
* 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.platestack.api.plugin
import mu.KLogger
import org.platestack.api.plugin.exception.PluginLoadingException
import org.platestack.api.server.PlateStack
import org.platestack.structure.immutable.ImmutableList
import org.platestack.util.ReflectionTarget
import org.platestack.util.UniqueModification
import java.io.IOException
import java.lang.reflect.Modifier
import java.net.URL
import kotlin.reflect.KClass
import kotlin.reflect.full.cast
import kotlin.reflect.full.createInstance
import kotlin.reflect.full.isSuperclassOf
import kotlin.reflect.jvm.jvmName
/**
* A plugin loaded by PlateStack
*/
abstract class PlatePlugin @ReflectionTarget constructor(): Plugin {
override val namespace: PlateNamespace get() = PlateNamespace
val metadata = checkNotNull(PlateNamespace.loader.loadingPlugin) {
"Attempted to create a new PlatePlugin instance in a invalid state!"
}
override val version get() = metadata.version
/**
* A logger to be used exclusively by this plugin
*/
@Suppress("LeakingThis")
protected val logger = PlateStack.internal.createLogger(this)
/**
* Method called when the plugin is fully ready to load
*/
open protected fun onEnable() {}
/**
* Method called when the plugin is being disable, no more activities will be allowed after this method returns
*/
open protected fun onDisable() {}
@JvmSynthetic internal fun enable() = onEnable()
@JvmSynthetic internal fun disable() = onEnable()
}
abstract class PlateLoader(protected val logger: KLogger) {
init {
try {
PlateNamespace.loader
error("A plate plugin loader has already been installed and ${javaClass.name} can't be instantiated now.")
}
catch (ignored: UninitializedPropertyAccessException) {
// Allowed
}
}
private val loadingLock = Any()
abstract val loadingOrder: ImmutableList<String>
open protected fun setAPI(metadata: PlateMetadata) {
synchronized(loadingLock) {
try {
loadingPlugin = metadata
PlateNamespace.api = object : PlatePlugin(){}
}
finally {
loadingPlugin = null
}
logger.info { "The PlateStack API has been set to ${metadata.version} and depends on the following libraries:\n - ${metadata.libraries.joinToString("\n - ")}" }
}
}
/**
* A plugin which is being loaded right now
*/
internal var loadingPlugin: PlateMetadata? = null ; get() {
val value = field
field = null
return value
}
@Throws(ClassNotFoundException::class)
protected fun ClassLoader.loadPluginClass(metadata: PlateMetadata, className: String): KClass<out PlatePlugin> {
synchronized(loadingLock) {
val kClass: KClass<*>
try {
logger.info { "Pre-loading ${metadata.name} ${metadata.version} -- #${metadata.id} $className" }
loadingPlugin = metadata
kClass = loadClass(className).kotlin
}
catch (e: ClassNotFoundException) {
throw PluginLoadingException(cause = e)
}
finally {
loadingPlugin = null
}
if(!PlatePlugin::class.isSuperclassOf(kClass)) {
throw ClassNotFoundException("The class ${kClass.jvmName} defines a @Plate annotation but does not extends the PlatePlugin class!")
}
@Suppress("UNCHECKED_CAST")
return kClass as KClass<out PlatePlugin>
}
}
private val <T: PlatePlugin> KClass<T>.scalaModule: T? get() {
try { java.getDeclaredField("MODULE$") } catch (e: NoSuchFieldException) { return null }.let {
val access = it.modifiers
if (Modifier.isPublic(access) && Modifier.isStatic(access) && it.type.name == jvmName && isSuperclassOf(it.type.kotlin)) {
return cast(it.get(null))
}
}
return null
}
private val <T: PlatePlugin> KClass<T>.groovySingleton: T? get() {
val java = java
try{ java.getDeclaredMethod("getInstance") } catch (e: NoSuchMethodException) { return null }.let {
val access = it.modifiers
if(it.returnType == java && it.exceptionTypes.isEmpty() && Modifier.isPublic(access) && Modifier.isStatic(access)) {
return cast(it.invoke(null))
}
}
return null
}
protected fun <T: PlatePlugin> getOrCreateInstance(metadata: PlateMetadata, kClass: KClass<T>): T {
synchronized(loadingLock) {
try {
logger.info { "Loading ${metadata.name} ${metadata.version} -- #${metadata.id} $kClass" }
loadingPlugin = metadata
// Kotlin object
kClass.objectInstance?.apply { return this }
// Scala module
kClass.scalaModule?.apply { return this }
// Groovy / Java singleton by static getInstance() method
kClass.groovySingleton?.apply { return this }
// Public constructor without parameters
return kClass.createInstance()
}
finally {
loadingPlugin = null
}
}
}
protected fun enable(plugin: PlatePlugin) {
synchronized(loadingLock) {
if (plugin.metadata.id in PlateNamespace.plugins)
error("The plugin ${plugin.metadata.id} is already loaded!")
logger.info { "Enabling ${plugin.metadata.name} ${plugin.metadata.version} -- #${plugin.metadata.id}" }
try {
PlateNamespace.plugins[plugin.metadata.id] = plugin
plugin.enable()
}
catch (e: Exception) {
PlateNamespace.plugins -= plugin.metadata.id
throw PluginLoadingException(cause = e)
}
}
}
protected fun disable(plugin: PlatePlugin) {
synchronized(loadingLock) {
if (plugin.metadata.id !in PlateNamespace.plugins)
error("The plugin ${plugin.metadata.id} is not loaded!")
logger.info { "Disabling ${plugin.metadata.name} ${plugin.metadata.version} -- #${plugin.metadata.id}" }
try {
plugin.disable()
}
catch (e: Exception) {
throw PluginLoadingException(cause = e)
}
finally {
PlateNamespace.plugins -= plugin.metadata.id
}
}
}
@Throws(IOException::class)
abstract fun scan(file: URL): Map<String, PlateMetadata>
@Throws(PluginLoadingException::class)
abstract fun load(files: Set<URL>): List<PlatePlugin>
fun load(vararg files: URL) = load(files.toSet())
}
/**
* All PlateStack plugins must be loaded from here
*/
object PlateNamespace: PluginNamespace {
var loader by UniqueModification<PlateLoader>()
var api by UniqueModification<PlatePlugin>()
override val id: String get() = "plate"
/**
* All loaded plugins
*/
internal val plugins = hashMapOf<String, PlatePlugin>()
val loadedPlugins: Collection<PlatePlugin> get() = plugins.values.toList()
override fun get(pluginId: String) = plugins[pluginId]
}
|
apache-2.0
|
67cf7e55f9a3cdfd0a7851ca2eba95de
| 33.346154 | 172 | 0.61951 | 4.71102 | false | false | false | false |
Cognifide/APM
|
app/aem/core/src/main/kotlin/com/cognifide/apm/core/services/event/EventManager.kt
|
1
|
936
|
/*-
* ========================LICENSE_START=================================
* AEM Permission Management
* %%
* Copyright (C) 2013 Wunderman Thompson Technology
* %%
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
* =========================LICENSE_END==================================
*/
package com.cognifide.apm.core.services.event
interface EventManager {
fun trigger(event: ApmEvent)
}
|
apache-2.0
|
63b7b967d29cbb0b340a28b74bea9467
| 35.52 | 75 | 0.625 | 4.68 | false | false | false | false |
MarkNKamau/JustJava-Android
|
app/src/main/java/com/marknkamau/justjava/ui/addressBook/AddressAdapter.kt
|
1
|
1657
|
package com.marknkamau.justjava.ui.addressBook
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.marknjunge.core.data.model.Address
import com.marknkamau.justjava.databinding.ItemAddressBinding
class AddressAdapter(
private val deleteAddress: (address: Address) -> Unit
) : RecyclerView.Adapter<AddressAdapter.ViewHolder>() {
val items = mutableListOf<Address>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val binding = ItemAddressBinding.inflate(LayoutInflater.from(parent.context), parent, false)
return ViewHolder(binding, deleteAddress)
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
holder.bind(items[position])
}
override fun getItemCount() = items.size
fun setItems(newItems: List<Address>) {
items.clear()
items.addAll(newItems)
notifyDataSetChanged()
}
inner class ViewHolder(
private val binding: ItemAddressBinding,
private val deleteAddress: (Address) -> Unit
) : RecyclerView.ViewHolder(binding.root) {
fun bind(address: Address) {
binding.tvStreetAddress.text = address.streetAddress
binding.tvDeliveryInstructions.text = address.deliveryInstructions
binding.tvDeliveryInstructions.visibility =
if (address.deliveryInstructions == null) View.GONE else View.VISIBLE
binding.root.setOnLongClickListener {
deleteAddress(address)
true
}
}
}
}
|
apache-2.0
|
71a97016bf48b69b78c8be124af92087
| 32.816327 | 100 | 0.697646 | 4.902367 | false | false | false | false |
Commit451/GitLabAndroid
|
app/src/main/java/com/commit451/gitlab/activity/BuildActivity.kt
|
2
|
6583
|
package com.commit451.gitlab.activity
import android.Manifest
import android.annotation.SuppressLint
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.MenuItem
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.core.content.ContextCompat
import com.commit451.addendum.design.snackbar
import com.commit451.gitlab.App
import com.commit451.gitlab.R
import com.commit451.gitlab.adapter.BuildPagerAdapter
import com.commit451.gitlab.event.BuildChangedEvent
import com.commit451.gitlab.extension.getDownloadBuildUrl
import com.commit451.gitlab.extension.with
import com.commit451.gitlab.model.api.Build
import com.commit451.gitlab.model.api.Project
import com.commit451.gitlab.util.DownloadUtil
import kotlinx.android.synthetic.main.activity_build.*
import kotlinx.android.synthetic.main.progress_fullscreen.*
import timber.log.Timber
/**
* Shows the details of a build
*/
class BuildActivity : BaseActivity() {
companion object {
private const val REQUEST_PERMISSION_WRITE_STORAGE = 1337
private const val KEY_PROJECT = "key_project"
private const val KEY_BUILD = "key_merge_request"
fun newIntent(context: Context, project: Project, build: Build): Intent {
val intent = Intent(context, BuildActivity::class.java)
intent.putExtra(KEY_PROJECT, project)
intent.putExtra(KEY_BUILD, build)
return intent
}
}
private lateinit var menuItemDownload: MenuItem
private lateinit var project: Project
private lateinit var build: Build
private val onMenuItemClickListener = Toolbar.OnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_retry -> {
fullscreenProgress.visibility = View.VISIBLE
App.get().gitLab.retryBuild(project.id, build.id)
.with(this)
.subscribe({
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.build_started)
App.bus().post(BuildChangedEvent(build))
}, {
Timber.e(it)
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.unable_to_retry_build)
})
return@OnMenuItemClickListener true
}
R.id.action_erase -> {
fullscreenProgress.visibility = View.VISIBLE
App.get().gitLab.eraseBuild(project.id, build.id)
.with(this)
.subscribe({
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.build_erased)
App.bus().post(BuildChangedEvent(it))
}, {
Timber.e(it)
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.unable_to_erase_build)
})
return@OnMenuItemClickListener true
}
R.id.action_cancel -> {
fullscreenProgress.visibility = View.VISIBLE
App.get().gitLab.cancelBuild(project.id, build.id)
.with(this)
.subscribe({
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.build_canceled)
App.bus().post(BuildChangedEvent(it))
}, {
Timber.e(it)
fullscreenProgress.visibility = View.GONE
root.snackbar(R.string.unable_to_cancel_build)
})
return@OnMenuItemClickListener true
}
R.id.action_download -> {
checkDownloadBuild()
return@OnMenuItemClickListener true
}
}
false
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_build)
project = intent.getParcelableExtra(KEY_PROJECT)!!
build = intent.getParcelableExtra(KEY_BUILD)!!
toolbar.title = String.format(getString(R.string.build_number), build.id)
toolbar.setNavigationIcon(R.drawable.ic_back_24dp)
toolbar.setNavigationOnClickListener { onBackPressed() }
toolbar.subtitle = project.nameWithNamespace
toolbar.inflateMenu(R.menu.retry)
toolbar.inflateMenu(R.menu.erase)
toolbar.inflateMenu(R.menu.cancel)
toolbar.inflateMenu(R.menu.download)
toolbar.setOnMenuItemClickListener(onMenuItemClickListener)
menuItemDownload = toolbar.menu.findItem(R.id.action_download)
menuItemDownload.isVisible = build.artifactsFile != null
setupTabs()
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
when (requestCode) {
REQUEST_PERMISSION_WRITE_STORAGE -> {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
downloadBuild()
}
}
}
}
private fun setupTabs() {
val sectionsPagerAdapter = BuildPagerAdapter(
this,
supportFragmentManager,
project,
build)
viewPager.adapter = sectionsPagerAdapter
tabLayout.setupWithViewPager(viewPager)
}
@SuppressLint("NewApi")
private fun checkDownloadBuild() {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
downloadBuild()
} else {
requestPermissions(arrayOf(Manifest.permission.WRITE_EXTERNAL_STORAGE), REQUEST_PERMISSION_WRITE_STORAGE)
}
}
private fun downloadBuild() {
val account = App.get().getAccount()
val downloadUrl = build.getDownloadBuildUrl(App.get().getAccount().serverUrl!!, project)
Timber.d("Downloading build: $downloadUrl")
val artifactsFileName = build.artifactsFile?.fileName
if (artifactsFileName != null) {
DownloadUtil.download(this, account, downloadUrl, artifactsFileName)
}
}
}
|
apache-2.0
|
fd74feaf16e9af7bd5aed6a5618196a7
| 38.419162 | 135 | 0.602765 | 5.126947 | false | false | false | false |
da1z/intellij-community
|
platform/testGuiFramework/src/com/intellij/testGuiFramework/recorder/GlobalActionRecorder.kt
|
4
|
3178
|
/*
* 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.recorder
import com.intellij.ide.IdeEventQueue
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.ex.AnActionListener
import com.intellij.openapi.diagnostic.Logger
import com.intellij.testGuiFramework.recorder.ui.GuiScriptEditorPanel
import java.awt.event.KeyEvent
import java.awt.event.MouseEvent
/**
* @author Sergey Karashevich
*/
object GlobalActionRecorder {
private val LOG = Logger.getInstance("#${GlobalActionRecorder::class.qualifiedName}")
var isActive = false
private set
private val globalActionListener = object : AnActionListener {
override fun beforeActionPerformed(action: AnAction?, dataContext: DataContext?, event: AnActionEvent?) {
if (event?.place == GuiScriptEditorPanel.GUI_SCRIPT_EDITOR_PLACE) return //avoid GUI Script Editor Actions
if(action == null) return
EventDispatcher.processActionEvent(action, event)
LOG.info("IDEA is going to perform action ${action.templatePresentation.text}")
}
override fun beforeEditorTyping(c: Char, dataContext: DataContext?) {
LOG.info("IDEA typing detected: ${c}")
}
override fun afterActionPerformed(action: AnAction?, dataContext: DataContext?, event: AnActionEvent?) {
if (event?.place == GuiScriptEditorPanel.GUI_SCRIPT_EDITOR_PLACE) return //avoid GUI Script Editor Actions
if (action == null) return
LOG.info("IDEA action performed ${action.templatePresentation.text}")
}
}
private val globalAwtProcessor = IdeEventQueue.EventDispatcher { awtEvent ->
when (awtEvent) {
is MouseEvent -> EventDispatcher.processMouseEvent(awtEvent)
is KeyEvent -> EventDispatcher.processKeyBoardEvent(awtEvent)
}
false
}
fun activate() {
if (isActive) return
LOG.info("Global action recorder is active")
ActionManager.getInstance().addAnActionListener(globalActionListener)
IdeEventQueue.getInstance().addDispatcher(globalAwtProcessor, GuiRecorderManager.frame) //todo: add disposal dependency on component
isActive = true
}
fun deactivate() {
if (isActive) {
LOG.info("Global action recorder is non active")
ActionManager.getInstance().removeAnActionListener(globalActionListener)
IdeEventQueue.getInstance().removeDispatcher(globalAwtProcessor)
}
isActive = false
ContextChecker.clearContext()
}
}
|
apache-2.0
|
229829e66f84d71475619820f53a9dea
| 35.965116 | 136 | 0.754563 | 4.673529 | false | false | false | false |
realm/realm-java
|
realm-transformer/src/main/kotlin/io/realm/analytics/RealmAnalytics.kt
|
1
|
5946
|
/*
* Copyright 2021 Realm 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 io.realm.analytics
import io.realm.transformer.CONNECT_TIMEOUT
import io.realm.transformer.READ_TIMEOUT
import io.realm.transformer.Utils
import io.realm.transformer.ext.getAgpVersion
import io.realm.transformer.ext.getAppId
import io.realm.transformer.ext.getMinSdk
import io.realm.transformer.ext.getTargetSdk
import org.gradle.api.Project
import org.gradle.api.artifacts.ResolvedArtifact
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import java.util.concurrent.Executors
import java.util.concurrent.TimeUnit
// Package level logger
val logger: Logger = LoggerFactory.getLogger("realm-logger")
/**
* Asynchronously submits build information to Realm as part of running
* the Gradle build.
*
* To be clear: this does *not* run when your app is in production or on
* your end-user's devices; it will only run when you build your app from source.
*
* Why are we doing this? Because it helps us build a better product for you.
* None of the data personally identifies you, your employer or your app, but it
* *will* help us understand what Realm version you use, what host OS you use,
* etc. Having this info will help with prioritizing our time, adding new
* features and deprecating old features. Collecting an anonymized bundle &
* anonymized MAC is the only way for us to count actual usage of the other
* metrics accurately. If we don't have a way to deduplicate the info reported,
* it will be useless, as a single developer building their app on Windows ten
* times would report 10 times more than a single developer that only builds
* once from Mac OS X, making the data all but useless. No one likes sharing
* data unless it's necessary, we get it, and we've debated adding this for a
* long long time. Since Realm is a free product without an email signup, we
* feel this is a necessary step so we can collect relevant data to build a
* better product for you.
*
* Currently the following information is reported:
* - What version of Realm is being used
* - What OS you are running on
* - An anonymized MAC address and bundle ID to aggregate the other information on.
*
*/
class RealmAnalytics {
private var data: AnalyticsData? = null
/**
* Sends the analytics.
*
* @param inputs the inputs provided by the Transform API
* @param inputModelClasses a list of ctClasses describing the Realm models
*/
public fun execute() {
try {
// If there is no data, analytics was disabled, so exit early.
val analyticsData: AnalyticsData = data ?: return
val pool = Executors.newFixedThreadPool(1);
try {
pool.execute { UrlEncodedAnalytics.create().execute(analyticsData) }
pool.awaitTermination(CONNECT_TIMEOUT + READ_TIMEOUT, TimeUnit.MILLISECONDS);
} catch (e: InterruptedException) {
pool.shutdownNow()
}
} catch (e: Exception) {
// Analytics failing for any reason should not crash the build
logger.debug("Error happened when sending Realm analytics data: $e")
}
}
public fun calculateAnalyticsData(project: Project): Boolean {
if (!isAnalyticsEnabled(project)) {
return false
}
// Language specific data
// Should be safe to iterate the configurations as we are way beyond the configuration
// phase
var containsKotlin = false
outer@
for (conf in project.configurations) {
try {
for (artifact: ResolvedArtifact in conf.resolvedConfiguration.resolvedArtifacts) {
if (artifact.name.startsWith("kotlin-stdlib")) {
containsKotlin = true
break@outer
}
}
} catch (ignore: Exception) {
// Some artifacts might not be able to resolve, in this case, just ignore them.
}
}
// Android specific data
val appId: String = project.getAppId()
val targetSdk: String = project.getTargetSdk()
val minSdk: String = project.getMinSdk()
val target =
when {
project.plugins.findPlugin("com.android.application") != null -> {
"app"
}
project.plugins.findPlugin("com.android.library") != null -> {
"library"
}
else -> {
"unknown"
}
}
val gradleVersion = project.gradle.gradleVersion
val agpVersion = project.getAgpVersion()
// Realm specific data
val sync: Boolean = Utils.isSyncEnabled(project)
data = AnalyticsData(
appId = PublicAppId(appId),
usesKotlin = containsKotlin,
usesSync = sync,
targetSdk = targetSdk,
minSdk = minSdk,
target = target,
gradleVersion = gradleVersion,
agpVersion = agpVersion
)
return true
}
private fun isAnalyticsEnabled(project: Project): Boolean {
val env = System.getenv()
return !project.gradle.startParameter.isOffline
&& env["REALM_DISABLE_ANALYTICS"] == null
&& env["CI"] == null
}
}
|
apache-2.0
|
d30b68afb7670681b0f325409f57c419
| 37.367742 | 98 | 0.645308 | 4.696682 | false | false | false | false |
lordtao/android-tao-core
|
lib/src/main/java/ua/at/tsvetkov/application/AppConfig.kt
|
1
|
24745
|
/**
* ****************************************************************************
* Copyright (c) 2010 Alexandr Tsvetkov.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
*
* Contributors:
* Alexandr Tsvetkov - initial API and implementation
*
*
* Project:
* TAO Core
*
*
* License agreement:
*
*
* 1. This code is published AS IS. Author is not responsible for any damage that can be
* caused by any application that uses this code.
* 2. Author does not give a garantee, that this code is error free.
* 3. This code can be used in NON-COMMERCIAL applications AS IS without any special
* permission from author.
* 4. This code can be modified without any special permission from author IF AND ONLY IF
* this license agreement will remain unchanged.
* ****************************************************************************
*/
package ua.at.tsvetkov.application
import android.annotation.TargetApi
import android.app.Activity
import android.app.Application
import android.content.Context
import android.content.SharedPreferences
import android.content.SharedPreferences.Editor
import android.content.pm.ApplicationInfo
import android.content.pm.PackageInfo
import android.content.pm.PackageManager
import android.content.pm.PackageManager.NameNotFoundException
import android.os.Build
import android.os.StrictMode
import android.preference.PreferenceManager
import android.provider.Settings
import android.widget.Toast
import ua.at.tsvetkov.ui.Screen
import ua.at.tsvetkov.util.Log
import java.math.RoundingMode
import java.text.DecimalFormat
import java.util.*
/**
* Return the basic parameters of the application. Initialize and restoration of essential parameters for the app. Data saves and loads in
* to the Shared Preferences with name equals the app packages name. Automatically create the working directory for the application in the
* standard place. Checks is the app is new or is new version and whether it was previously installed.
*
* @author A.Tsvetkov 2010 http://tsvetkov.at.ua mailto:[email protected]
*/
const val APP_VERSION_NAME = "APP_VERSION_NAME"
const val APP_VERSION_CODE = "APP_VERSION_CODE"
const val SAVE = true
const val NOT_SAVE = false
private const val LINE_DOUBLE = "=============================================================================================="
private const val DEFAULT_SETTINGS_STRING = "| Default Shared Preferences Data"
private const val TRIAL_IS_EXPIRED = "Sorry, the trial version has expired "
private const val MAX_LENGTH = 93
class AppConfig {
companion object {
private var mPreferences: SharedPreferences? = null
private lateinit var mEditor: Editor
private var isInitialized = false
/**
* Return the app name without spaces.
*
* @return the app name without spaces.
*/
@JvmStatic
var appName: String? = null
private set
/**
* Return device Diagonal enum constant
*
* @return Diagonal
*/
@JvmStatic
var deviceDiagonal: Diagonal? = null
private set
/**
* Return device diagonal in inches
*
* @return inches
*/
@JvmStatic
var diagonalInInch: Float = 0f
private set
/**
* Whether the app is debuggable or not
*
* @return is debuggable
*/
@JvmStatic
var isDebuggable = true
private set
/**
* Whether the app is currently being debugged (e.g. over ADB)
*
* @return is being debugged
*/
@JvmStatic
var isBeingDebugged = true
private set
/**
* Return true if the app is absolutely new
*
* @return is the app is absolutely new
*/
@JvmStatic
var isFreshInstallation = false
private set
/**
* Return true if new version of the app is started
*
* @return is new version of app is started
*/
@JvmStatic
var isNewVersion = false
private set
/**
* Return is StrictMode is enabled.
*
* @return Return is StrictMode is enabled.
*/
@JvmStatic
var isStrictModeEnabled = false
private set
/**
* Return the app signature KeyHash for this application
*
* @return the app signature KeyHash
*/
@JvmStatic
var applicationSignatureKeyHash: String? = null
private set
/**
* Return the app signature fingerprint for this application
*
* @return the app signature fingerprint
*/
@JvmStatic
var signatureFingerprint: String? = null
private set
/**
* Return the app signature fingerprint for this application separated by ':'
*
* @return the app signature fingerprint
*/
@JvmStatic
var signatureFingerprintColon: String? = null
private set
/**
* Name of the app package.
*
* @return the package name
*/
@JvmStatic
var packageName: String? = null
private set
/**
* The version name of this package, as specified by the <manifest> tag's versionName attribute.
*
* @return the app version name
</manifest> */
@JvmStatic
var appVersionName: String? = null
private set
/**
* The version number of this package, as specified by the <manifest> tag's versionCode attribute.
*
* @return the app version code
</manifest> */
@JvmStatic
var appVersionCode = 0
private set
/**
* A 64-bit number (as a hex string) that is randomly generated when the user first sets up the device
* and should remain constant for the lifetime of the user's device.
* The value may change if a factory reset is performed on the device.
*
* @return the android id
*/
@JvmStatic
var androidId: String? = null
private set
/**
* Checks whether the device is a telephone
*
* @return is the device is a telephone
*/
@JvmStatic
var isPhone: Boolean = false
private set
/**
* Checks whether the device is a tablet
*
* @return is the device is a tablet
*/
@JvmStatic
var isTablet: Boolean = false
private set
/**
* Checking the initializing of this class and print error stack trace otherwise.
*
* @return true if initiated
*/
@JvmStatic
val isInitializing: Boolean
get() = if (isInitialized) {
true
} else {
throw IllegalArgumentException("AppConfig is not initiated. Call ua.at.tsvetkov.application.AppConfig.init(application) in your Application code.")
}
/**
* Init configuration.
*
* @param application the Application
* @throws NumberFormatException
*/
@JvmStatic
fun init(application: Application) {
packageName = application.applicationInfo.packageName
var appData: PackageInfo? = null
try {
appData = application.packageManager.getPackageInfo(application.packageName, PackageManager.GET_SIGNATURES)
} catch (e: NameNotFoundException) {
Log.e("Package not found", e)
}
mPreferences = PreferenceManager.getDefaultSharedPreferences(application)
mEditor = mPreferences!!.edit()
appName = application.getString(appData!!.applicationInfo.labelRes)
isFreshInstallation = mPreferences!!.getInt(APP_VERSION_CODE, -1) < 0
if (appData.versionCode > mPreferences!!.getInt(APP_VERSION_CODE, 0)) {
isNewVersion = true
}
deviceDiagonal = Screen.getDiagonal(application)
diagonalInInch = Screen.getDiagonalInInch(application).toFloat()
isPhone = Screen.isPhone(application)
isTablet = Screen.isTablet(application)
applicationSignatureKeyHash = Apps.getApplicationSignatureKeyHash(application, packageName!!)
signatureFingerprint = Apps.getSignatureFingerprint(application, packageName!!, ' ')
signatureFingerprintColon = Apps.getSignatureFingerprint(application, packageName!!, ':')
appVersionName = appData.versionName
appVersionCode = appData.versionCode
androidId = Settings.Secure.getString(application.contentResolver, Settings.Secure.ANDROID_ID)
mEditor!!.putString(APP_VERSION_NAME, appVersionName)
mEditor!!.putInt(APP_VERSION_CODE, appVersionCode)
save()
isDebuggable = 0 != application.applicationInfo.flags and ApplicationInfo.FLAG_DEBUGGABLE
isBeingDebugged = android.os.Debug.isDebuggerConnected()
if (!isDebuggable) {
android.util.Log.w("▪ $appName ▪", "➧ Log is prohibited because debug mode is disabled.")
Log.setDisabled()
}
isInitialized = true
}
/**
* Print the app data and shared mPreferences in to the LogCat
*
* @param context the app context
*/
@JvmStatic
fun printInfo(context: Context) {
if (!isDebuggable) {
return
}
var max = mPreferences!!.all.keys.maxBy { it.length }!!.length
max = if (max < 31) 31 else max
val formatPref = "| %-${max}s%s"
val df = DecimalFormat("##.##")
df.roundingMode = RoundingMode.DOWN
val realDiagonal = df.format(diagonalInInch)
var infoString = " \n$LINE_DOUBLE\n" +
"| Application name $appName".padEnd(MAX_LENGTH, ' ').plus("|\n") +
"| Android device ID $androidId".padEnd(MAX_LENGTH, ' ').plus("|\n") +
"| Application package $packageName".padEnd(MAX_LENGTH, ' ').plus("|\n") +
"| Signature Fingerprint SHA-1 $signatureFingerprintColon".padEnd(MAX_LENGTH, ' ').plus("|\n") +
"| Signature Fingerprint SHA-1 $signatureFingerprint".padEnd(MAX_LENGTH, ' ').plus("|\n") +
"| Signature Key Hash $applicationSignatureKeyHash".dropLast(1).padEnd(MAX_LENGTH, ' ').plus("|\n") +
"| Diagonal $deviceDiagonal - $realDiagonal\"".padEnd(MAX_LENGTH, ' ').plus("|\n") +
"| New app version $isNewVersion".padEnd(MAX_LENGTH, ' ').plus("|\n") +
"| Fresh installation $isFreshInstallation".padEnd(MAX_LENGTH, ' ').plus("|\n") +
"| Strict mode $isStrictModeEnabled".padEnd(MAX_LENGTH, ' ').plus("|\n") +
"$LINE_DOUBLE\n" +
"$DEFAULT_SETTINGS_STRING".padEnd(MAX_LENGTH, ' ').plus("|\n") +
"$LINE_DOUBLE\n"
val prefs = mPreferences!!.all.entries.sortedBy { it.key }
for ((key, value) in prefs) {
infoString = infoString.plus(String.format(formatPref, key, value).padEnd(MAX_LENGTH, ' ').plus("|\n"))
}
infoString = infoString.plus("$LINE_DOUBLE\n ")
android.util.Log.i("▪ $appName ▪", infoString)
}
/**
* Retrieve a boolean value from the mPreferences.
*
* @param key The name of the preference to modify.
* @param defValue Value to return if this preference does not exist.
* @return Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a boolean.
*/
@JvmStatic
fun getBoolean(key: String, defValue: Boolean): Boolean {
return mPreferences!!.getBoolean(key, defValue)
}
/**
* Retrieve a float value from the mPreferences.
*
* @param key The name of the preference to modify.
* @param defValue Value to return if this preference does not exist.
* @return Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a float.
*/
@JvmStatic
fun getFloat(key: String, defValue: Float): Float {
return mPreferences!!.getFloat(key, defValue)
}
/**
* Retrieve a float value from the mPreferences, 0 if not found
*
* @param key The name of the preference to modify.
* @return Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a float.
*/
@JvmStatic
fun getFloat(key: String): Float {
return mPreferences!!.getFloat(key, 0f)
}
/**
* Return int value
*
* @param key The name of the preference to modify.
* @param defValue Value to return if this preference does not exist.
* @return Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a int.
*/
@JvmStatic
fun getInt(key: String, defValue: Int): Int {
return mPreferences!!.getInt(key, defValue)
}
/**
* Return int value, 0 if not found
*
* @param key The name of the preference to modify.
* @return value
*/
@JvmStatic
fun getInt(key: String): Int {
return mPreferences!!.getInt(key, 0)
}
/**
* Return long value
*
* @param key The name of the preference to modify.
* @param defValue Value to return if this preference does not exist.
* @return Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a long.
*/
@JvmStatic
fun getLong(key: String, defValue: Long): Long {
return mPreferences!!.getLong(key, defValue)
}
/**
* Return long value, 0 if not found
*
* @param key The name of the preference to modify.
* @return value
*/
@JvmStatic
fun getLong(key: String): Long {
return mPreferences!!.getLong(key, 0)
}
/**
* Return value or "" if not found
*
* @param key The name of the preference to modify.
* @return value
*/
@JvmStatic
fun getString(key: String): String {
return mPreferences!!.getString(key, "")
}
/**
* Return value
*
* @param key The name of the preference to modify.
* @param defValue Value to return if this preference does not exist.
* @return Returns the preference value if it exists, or defValue. Throws ClassCastException if there is a preference with this name that is not a String.
*/
@JvmStatic
fun getString(key: String, defValue: String): String? {
return mPreferences!!.getString(key, defValue)
}
/**
* Retrieve a set of String values from the mPreferences.
*
*
*
* Note that you *must not* modify the set instance returned
* by this call. The consistency of the stored data is not guaranteed
* if you do, nor is your ability to modify the instance at all.
*
* @param key The name of the preference to retrieve.
* @param defValues Values to return if this preference does not exist.
* @return Return Returns the preference values if they exist, or defValues.
* Throws ClassCastException if there is a preference with this name
* that is not a Set.
* @throws Exception Not supported before version API 11 (HONEYCOMB)
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@Throws(Exception::class)
@JvmStatic
fun getStringSet(key: String, defValues: Set<String>): Set<String>? {
return if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mPreferences!!.getStringSet(key, defValues)
} else {
throw Exception("Not supported before version API 11 (HONEYCOMB)")
}
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*/
@JvmStatic
fun putBoolean(key: String, value: Boolean) {
mEditor!!.putBoolean(key, value)
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*/
@JvmStatic
fun putFloat(key: String, value: Float) {
mEditor!!.putFloat(key, value)
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*/
@JvmStatic
fun putInt(key: String, value: Int) {
mEditor!!.putInt(key, value)
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*/
@JvmStatic
fun putLong(key: String, value: Long) {
mEditor!!.putLong(key, value)
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*/
@JvmStatic
fun putString(key: String, value: String) {
mEditor!!.putString(key, value)
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@JvmStatic
fun putStringSet(key: String, value: Set<String>) {
mEditor!!.putStringSet(key, value)
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
* @param isNeedToSave Go write the SharedPreferences or postpone.
*/
@JvmStatic
fun putBoolean(key: String, value: Boolean, isNeedToSave: Boolean) {
mEditor!!.putBoolean(key, value)
if (isNeedToSave) {
save()
}
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
* @param isNeedToSave Go write the SharedPreferences or postpone.
*/
@JvmStatic
fun putFloat(key: String, value: Float, isNeedToSave: Boolean) {
mEditor!!.putFloat(key, value)
if (isNeedToSave) {
save()
}
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
* @param isNeedToSave Go write the SharedPreferences or postpone.
*/
@JvmStatic
fun putInt(key: String, value: Int, isNeedToSave: Boolean) {
mEditor!!.putInt(key, value)
if (isNeedToSave) {
save()
}
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
* @param isNeedToSave Go write the SharedPreferences or postpone.
*/
@JvmStatic
fun putLong(key: String, value: Long, isNeedToSave: Boolean) {
mEditor!!.putLong(key, value)
if (isNeedToSave) {
save()
}
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
* @param isNeedToSave Go write the SharedPreferences or postpone.
*/
@JvmStatic
fun putString(key: String, value: String, isNeedToSave: Boolean) {
mEditor!!.putString(key, value)
if (isNeedToSave) {
save()
}
}
/**
* Set a new for this key
*
* @param key The name of the preference to modify.
* @param value The new value for the preference.
* @param isNeedToSave Go write the SharedPreferences or postpone.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@JvmStatic
fun putStringSet(key: String, value: Set<String>, isNeedToSave: Boolean) {
mEditor!!.putStringSet(key, value)
if (isNeedToSave) {
save()
}
}
/**
* Go write the SharedPreferences.
*/
@JvmStatic
fun save() {
mEditor!!.commit()
}
/**
* Clear the SharedPreferences
*/
@JvmStatic
fun clear() {
mEditor!!.clear()
mEditor!!.commit()
Log.i(">>> Shared mPreferences was CLEARED! <<<")
}
/**
* Enable StrictMode in the app. Put call in the first called onCreate() method in Application or Activity.
*
* @param aContext the app Context
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
@JvmStatic
fun enableStrictMode(aContext: Context) {
try {
val appFlags = aContext.applicationInfo.flags
if (appFlags and ApplicationInfo.FLAG_DEBUGGABLE != 0) {
StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build())
StrictMode.setVmPolicy(StrictMode.VmPolicy.Builder().detectActivityLeaks().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build())
}
isStrictModeEnabled = true
Log.i("StrictMode is enabled.")
} catch (throwable: Throwable) {
isStrictModeEnabled = false
Log.i("StrictMode is not supported. Skipping...")
}
}
/**
* Return true if application run in debug mode
*
* @return Return true if application run in debug mode
*/
@JvmStatic
fun isDebugMode(): Boolean {
return isDebuggable
}
/**
* Check evaluate date and finish activity if expired.
*
* @param activity current activity
* @param year evaluate year
* @param month evaluate month
* @param day evaluate day
*/
@JvmStatic
fun finishIfTrialExpired(activity: Activity, year: Int, month: Int, day: Int) {
val date = Date()
val today = Date()
date.year = year - 1900
date.month = month - 1
date.date = day
if (date.before(today)) {
Toast.makeText(activity, TRIAL_IS_EXPIRED + date.toGMTString(), Toast.LENGTH_LONG).show()
Log.w(TRIAL_IS_EXPIRED + date.toGMTString())
activity.finish()
}
}
}
}
|
gpl-3.0
|
5106af3fd47607cb9a04f14e2f02aef5
| 34.901306 | 190 | 0.558116 | 4.973859 | false | false | false | false |
Applandeo/Material-Calendar-View
|
library/src/main/java/com/applandeo/materialcalendarview/EventDay.kt
|
1
|
1809
|
package com.applandeo.materialcalendarview
import android.graphics.drawable.Drawable
import androidx.annotation.ColorInt
import androidx.annotation.DrawableRes
import androidx.annotation.RestrictTo
import com.applandeo.materialcalendarview.utils.EventImage
import com.applandeo.materialcalendarview.utils.setMidnight
import java.util.*
/**
* This class represents an event of a day. An instance of this class is returned when user click
* a day cell. This class can be overridden to make calendar more functional. A list of instances of
* this class can be passed to CalendarView object using setEvents() method.
*
*
* @param calendar Calendar object which represents a date of the event
* @param drawable Drawable which will be displayed in a day cell
* @param drawableRes Drawable resource which will be displayed in a day cell
* @param labelColor Color which will be displayed as row label text color
*
* Created by Applandeo Team.
*/
data class EventDay(val calendar: Calendar) {
//An object which contains image to display in the day row
internal var imageDrawable: EventImage = EventImage.EmptyEventImage
internal var labelColor: Int = 0
@set:RestrictTo(RestrictTo.Scope.LIBRARY)
var isEnabled: Boolean = false
init {
calendar.setMidnight()
}
constructor(day: Calendar, drawable: Drawable) : this(day) {
imageDrawable = EventImage.EventImageDrawable(drawable)
}
constructor(day: Calendar, @DrawableRes drawableRes: Int) : this(day) {
imageDrawable = EventImage.EventImageResource(drawableRes)
}
constructor(day: Calendar, @DrawableRes drawableRes: Int, @ColorInt labelColor: Int) : this(day) {
imageDrawable = EventImage.EventImageResource(drawableRes)
this.labelColor = labelColor
}
}
|
apache-2.0
|
dcd674515c790e8c3d2591c6c73d1a82
| 35.2 | 102 | 0.752902 | 4.488834 | false | false | false | false |
ingokegel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/conversion/copy/PlainTextPasteImportResolver.kt
|
1
|
11011
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.conversion.copy
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.progress.ProgressManager
import com.intellij.psi.*
import com.intellij.psi.search.PsiShortNamesCache
import com.intellij.psi.util.PsiTreeUtil
import org.jetbrains.kotlin.builtins.jvm.JavaToKotlinClassMapper
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptorWithVisibility
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.matches
import org.jetbrains.kotlin.idea.base.projectStructure.moduleInfoOrNull
import org.jetbrains.kotlin.idea.base.util.runReadActionInSmartMode
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.getResolutionFacade
import org.jetbrains.kotlin.idea.caches.resolve.util.getJavaMemberDescriptor
import org.jetbrains.kotlin.idea.core.isVisible
import org.jetbrains.kotlin.idea.imports.canBeReferencedViaImport
import org.jetbrains.kotlin.idea.references.mainReference
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.psi.KtDotQualifiedExpression
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtImportDirective
import org.jetbrains.kotlin.psi.psiUtil.referenceExpression
import org.jetbrains.kotlin.utils.addToStdlib.safeAs
/**
* Tested with TextJavaToKotlinCopyPasteConversionTestGenerated
*/
class PlainTextPasteImportResolver(private val dataForConversion: DataForConversion, val targetFile: KtFile) {
private val file = dataForConversion.file
private val project = targetFile.project
private val importList = file.importList!!
// keep access to deprecated PsiElementFactory.SERVICE for bwc with <= 191
private val psiElementFactory = PsiElementFactory.getInstance(project)
private val bindingContext by lazy { targetFile.analyzeWithContent() }
private val resolutionFacade = targetFile.getResolutionFacade()
private val shortNameCache = PsiShortNamesCache.getInstance(project)
private val scope = file.resolveScope
private val failedToResolveReferenceNames = HashSet<String>()
private var ambiguityInResolution = false
private var couldNotResolve = false
val addedImports = mutableListOf<PsiImportStatementBase>()
private fun canBeImported(descriptor: DeclarationDescriptorWithVisibility?): Boolean {
return descriptor != null
&& descriptor.canBeReferencedViaImport()
&& descriptor.isVisible(targetFile, null, bindingContext, resolutionFacade)
}
private fun addImport(importStatement: PsiImportStatementBase, shouldAddToTarget: Boolean = false) {
file.importList?.let {
it.add(importStatement)
if (shouldAddToTarget)
addedImports.add(importStatement)
}
}
fun addImportsFromTargetFile() {
if (importList in dataForConversion.elementsAndTexts.toList()) return
val task = {
val addImportList = mutableListOf<PsiImportStatementBase>()
fun tryConvertKotlinImport(importDirective: KtImportDirective) {
val importPath = importDirective.importPath
val importedReference = importDirective.importedReference
if (importPath != null && !importPath.hasAlias() && importedReference is KtDotQualifiedExpression) {
val receiver = importedReference
.receiverExpression
.referenceExpression()
?.mainReference
?.resolve()
val selector = importedReference
.selectorExpression
?.referenceExpression()
?.mainReference
?.resolve()
val isPackageReceiver = receiver is PsiPackage
val isClassReceiver = receiver is PsiClass
val isClassSelector = selector is PsiClass
if (importPath.isAllUnder) {
when {
isClassReceiver ->
addImportList.add(psiElementFactory.createImportStaticStatement(receiver as PsiClass, "*"))
isPackageReceiver ->
addImportList.add(psiElementFactory.createImportStatementOnDemand((receiver as PsiPackage).qualifiedName))
}
} else {
when {
isClassSelector ->
addImportList.add(psiElementFactory.createImportStatement(selector as PsiClass))
isClassReceiver ->
addImportList.add(
psiElementFactory.createImportStaticStatement(
receiver as PsiClass,
importPath.importedName!!.asString()
)
)
}
}
}
}
runReadAction {
val importDirectives = targetFile.importDirectives
importDirectives.forEachIndexed { index, value ->
ProgressManager.getInstance().progressIndicator?.fraction = 1.0 * index / importDirectives.size
tryConvertKotlinImport(value)
}
}
ApplicationManager.getApplication().invokeAndWait {
runWriteAction { addImportList.forEach { addImport(it) } }
}
}
ProgressManager.getInstance().runProcessWithProgressSynchronously(
task, KotlinBundle.message("copy.text.adding.imports"), true, project
)
}
fun tryResolveReferences() {
val task = {
fun performWriteAction(block: () -> Unit) {
ApplicationManager.getApplication().invokeAndWait { runWriteAction { block() } }
}
fun tryResolveReference(reference: PsiQualifiedReference): Boolean {
if (runReadAction { reference.resolve() } != null) return true
val referenceName = runReadAction { reference.referenceName } ?: return false
if (referenceName in failedToResolveReferenceNames) return false
if (runReadAction { reference.qualifier } != null) return false
val classes = runReadAction {
shortNameCache.getClassesByName(referenceName, scope)
.mapNotNull { psiClass ->
val containingFile = psiClass.containingFile
if (RootKindFilter.everything.matches(containingFile)) {
psiClass to psiClass.getJavaMemberDescriptor() as? ClassDescriptor
} else null
}.filter { canBeImported(it.second) }
}
classes.find { (_, descriptor) ->
JavaToKotlinClassMapper.mapPlatformClass(descriptor!!).isNotEmpty()
}?.let { (psiClass, _) ->
performWriteAction { addImport(psiElementFactory.createImportStatement(psiClass)) }
}
if (runReadAction { reference.resolve() } != null) return true
classes.singleOrNull()?.let { (psiClass, _) ->
performWriteAction { addImport(psiElementFactory.createImportStatement(psiClass), true) }
}
when {
runReadAction { reference.resolve() } != null -> return true
classes.isNotEmpty() -> {
ambiguityInResolution = true
return false
}
}
val members = runReadAction {
(shortNameCache.getMethodsByName(referenceName, scope).asList() +
shortNameCache.getFieldsByName(referenceName, scope).asList())
.asSequence()
.map { it as PsiMember }
.filter { it.moduleInfoOrNull != null }
.map { it to it.getJavaMemberDescriptor(resolutionFacade) as? DeclarationDescriptorWithVisibility }
.filter { canBeImported(it.second) }
.toList()
}
members.singleOrNull()?.let { (psiMember, _) ->
performWriteAction {
addImport(
psiElementFactory.createImportStaticStatement(psiMember.containingClass!!, psiMember.name!!),
true
)
}
}
when {
runReadAction { reference.resolve() } != null -> return false
members.isNotEmpty() -> ambiguityInResolution = true
else -> couldNotResolve = true
}
return false
}
val smartPointerManager = SmartPointerManager.getInstance(file.project)
val elementsWithUnresolvedRef = project.runReadActionInSmartMode {
PsiTreeUtil.collectElements(file) { element ->
element.reference != null
&& element.reference is PsiQualifiedReference
&& element.reference?.resolve() == null
}.map { smartPointerManager.createSmartPsiElementPointer(it) }
}
val reversed = elementsWithUnresolvedRef.reversed()
val progressIndicator = ProgressManager.getInstance().progressIndicator
progressIndicator?.isIndeterminate = false
reversed.forEachIndexed { index, value ->
progressIndicator?.fraction = 1.0 * index / reversed.size
runReadAction { value.element?.reference?.safeAs<PsiQualifiedReference>() }?.let { reference ->
if (!tryResolveReference(reference)) {
runReadAction { reference.referenceName }?.let {
failedToResolveReferenceNames += it
}
}
}
}
}
ProgressManager.getInstance().runProcessWithProgressSynchronously(
task, KotlinBundle.message("copy.text.resolving.references"), true, project
)
}
}
|
apache-2.0
|
e6e0635434901e4c6b29d2caca9ba88f
| 45.855319 | 158 | 0.598947 | 6.383188 | false | false | false | false |
benjamin-bader/thrifty
|
thrifty-integration-tests/src/test/kotlin/com/microsoft/thrifty/integration/conformance/server/ThriftTestHandler.kt
|
1
|
6094
|
/*
* Thrifty
*
* Copyright (c) Microsoft Corporation
*
* All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the License);
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING
* WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE,
* FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing permissions and limitations under the License.
*/
package com.microsoft.thrifty.integration.conformance.server
import com.microsoft.thrifty.integration.kgen.HasUnion
import com.microsoft.thrifty.integration.kgen.Insanity
import com.microsoft.thrifty.integration.kgen.NonEmptyUnion
import com.microsoft.thrifty.integration.kgen.Numberz
import com.microsoft.thrifty.integration.kgen.server.ThriftTest
import com.microsoft.thrifty.integration.kgen.UnionWithDefault
import com.microsoft.thrifty.integration.kgen.UserId
import com.microsoft.thrifty.integration.kgen.Xception
import com.microsoft.thrifty.integration.kgen.Xception2
import com.microsoft.thrifty.integration.kgen.Xtruct
import com.microsoft.thrifty.integration.kgen.Xtruct2
import okio.ByteString
import org.apache.thrift.TException
class ThriftTestHandler : ThriftTest {
override suspend fun testVoid() {
}
override suspend fun testString(thing: String): String {
return thing
}
override suspend fun testBool(thing: Boolean): Boolean {
return thing
}
override suspend fun testByte(thing: Byte): Byte {
return thing
}
override suspend fun testI32(thing: Int): Int {
return thing
}
override suspend fun testI64(thing: Long): Long {
return thing
}
override suspend fun testDouble(thing: Double): Double {
return thing
}
override suspend fun testBinary(thing: ByteString): ByteString {
return thing
}
override suspend fun testStruct(thing: Xtruct): Xtruct {
return thing
}
override suspend fun testNest(thing: Xtruct2): Xtruct2 {
return thing
}
override suspend fun testMap(thing: Map<Int, Int>): Map<Int, Int> {
return thing
}
override suspend fun testStringMap(thing: Map<String, String>): Map<String, String> {
return thing
}
override suspend fun testSet(thing: Set<Int>): Set<Int> {
return thing
}
override suspend fun testList(thing: List<Int>): List<Int> {
return thing
}
override suspend fun testEnum(thing: Numberz): Numberz {
return thing
}
override suspend fun testTypedef(thing: UserId): UserId {
return thing
}
override suspend fun testMapMap(hello: Int): Map<Int, Map<Int, Int>> {
// {-4 => {-4 => -4, -3 => -3, -2 => -2, -1 => -1, }, 4 => {1 => 1, 2 => 2, 3 => 3, 4 => 4, }, }
// {-4 => {-4 => -4, -3 => -3, -2 => -2, -1 => -1, }, 4 => {1 => 1, 2 => 2, 3 => 3, 4 => 4, }, }
val result: MutableMap<Int, Map<Int, Int>> = LinkedHashMap()
val first: MutableMap<Int, Int> = LinkedHashMap()
val second: MutableMap<Int, Int> = LinkedHashMap()
first[-4] = -4
first[-3] = -3
first[-2] = -2
first[-1] = -1
second[1] = 1
second[2] = 2
second[3] = 3
second[4] = 4
result[-4] = first
result[4] = second
return result
}
override suspend fun testInsanity(argument: Insanity): Map<UserId, Map<Numberz, Insanity>> {
/*
* { 1 => { 2 => argument,
* 3 => argument,
* },
* 2 => { 6 => <empty Insanity struct>, },
* }
*/
/*
* { 1 => { 2 => argument,
* 3 => argument,
* },
* 2 => { 6 => <empty Insanity struct>, },
* }
*/
val result: MutableMap<Long, Map<Numberz, Insanity>> = LinkedHashMap()
val first: MutableMap<Numberz, Insanity> = LinkedHashMap()
val second: MutableMap<Numberz, Insanity> = LinkedHashMap()
first[Numberz.TWO] = argument
first[Numberz.THREE] = argument
second[Numberz.SIX] = Insanity(null, null)
result[1L] = first
result[2L] = second
return result
}
override suspend fun testMulti(
arg0: Byte,
arg1: Int,
arg2: Long,
arg3: Map<Short, String>,
arg4: Numberz,
arg5: UserId
): Xtruct {
return Xtruct("Hello2", arg0, arg1, arg2, null, null)
}
override suspend fun testException(arg: String) {
if ("TException" == arg) {
throw TException()
} else if ("Xception" == arg) {
throw Xception(1001, "Xception")
}
}
override suspend fun testMultiException(arg0: String, arg1: String): Xtruct {
if ("Xception" == arg0) {
throw Xception(1001, "This is an Xception")
} else if ("Xception2" == arg0) {
val xtruct = Xtruct(
string_thing = "This is an Xception2",
byte_thing = null,
i32_thing = null,
i64_thing = null,
double_thing = null,
bool_thing = null
)
throw Xception2(2002, xtruct)
}
return Xtruct(
string_thing = arg1,
byte_thing = null,
i32_thing = null,
i64_thing = null,
double_thing = null,
bool_thing = null
)
}
override suspend fun testOneway(secondsToSleep: Int) {
}
override suspend fun testUnionArgument(arg0: NonEmptyUnion): HasUnion {
val result = HasUnion(arg0)
return result
}
override suspend fun testUnionWithDefault(theArg: UnionWithDefault): UnionWithDefault {
return theArg
}
}
|
apache-2.0
|
9de6cc99be5199e9dab684d2d23c838d
| 27.476636 | 116 | 0.595504 | 3.983007 | false | true | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/AddCallOrUnwrapTypeFix.kt
|
1
|
3353
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.inspections.coroutines
import com.intellij.codeInsight.intention.FileModifier.SafeFieldForPreview
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.quickfix.createFromUsage.callableBuilder.getReturnTypeReference
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.bindingContextUtil.getTargetFunctionDescriptor
class AddCallOrUnwrapTypeFix(
val withBody: Boolean,
val functionName: String,
val typeName: String,
val shouldMakeSuspend: Boolean,
@SafeFieldForPreview
val simplify: (KtExpression) -> Unit
) : LocalQuickFix {
override fun getName(): String =
if (withBody) KotlinBundle.message("add.call.or.unwrap.type.fix.text", functionName)
else KotlinBundle.message("add.call.or.unwrap.type.fix.text1", typeName)
override fun getFamilyName(): String = name
private fun KtExpression.addCallAndSimplify(factory: KtPsiFactory) {
val newCallExpression = factory.createExpressionByPattern("$0.$functionName()", this)
val result = replaced(newCallExpression)
simplify(result)
}
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val function = descriptor.psiElement.getNonStrictParentOfType<KtFunction>() ?: return
val returnTypeReference = function.getReturnTypeReference()
val context = function.analyzeWithContent()
val functionDescriptor = context[BindingContext.FUNCTION, function] ?: return
if (shouldMakeSuspend) {
function.addModifier(KtTokens.SUSPEND_KEYWORD)
}
if (returnTypeReference != null) {
val returnType = functionDescriptor.returnType ?: return
val returnTypeArgument = returnType.arguments.firstOrNull()?.type ?: return
function.setType(returnTypeArgument)
}
if (!withBody) return
val factory = KtPsiFactory(project)
val bodyExpression = function.bodyExpression
bodyExpression?.forEachDescendantOfType<KtReturnExpression> {
if (it.getTargetFunctionDescriptor(context) == functionDescriptor) {
it.returnedExpression?.addCallAndSimplify(factory)
}
}
if (function is KtFunctionLiteral) {
val lastStatement = function.bodyExpression?.statements?.lastOrNull()
if (lastStatement != null && lastStatement !is KtReturnExpression) {
lastStatement.addCallAndSimplify(factory)
}
} else if (!function.hasBlockBody()) {
bodyExpression?.addCallAndSimplify(factory)
}
}
}
|
apache-2.0
|
7ad6af950ca6ec5f33bfcd7b36ac4687
| 46.239437 | 158 | 0.73725 | 5.103501 | false | false | false | false |
DanielGrech/anko
|
preview/idea-plugin/src/org/jetbrains/kotlin/android/dslpreview/RobowrapperContext.kt
|
3
|
6988
|
/*
* 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.
*/
package org.jetbrains.kotlin.android.dslpreview
import java.io.File
import kotlin.properties.Delegates
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.roots.ModuleRootManager
import java.util.ArrayList
import com.intellij.openapi.application.PathManager
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.JavaSdkType
import com.intellij.psi.PsiClass
class RobowrapperContext(description: PreviewClassDescription) {
val androidFacet = description.androidFacet
val activityClassName = description.qualifiedName
private val mainSourceProvider = androidFacet.getMainIdeaSourceProvider()
private val applicationPackage = androidFacet.getManifest()
?.getPackage()?.getXmlAttributeValue()?.getValue() ?: "app"
private val assetsDirectory = mainSourceProvider.getAssetsDirectories().firstOrNull()
private val resDirectory = mainSourceProvider.getResDirectories().firstOrNull()
private val activities by Delegates.lazy {
androidFacet.getManifest()
?.getApplication()
?.getActivities()
?: listOf()
}
private val manifest by Delegates.lazy { generateManifest() }
private fun runReadAction<T>(action: () -> T): T {
return ApplicationManager.getApplication().runReadAction<T>(action)
}
private fun generateManifest() = runReadAction {
val activityEntries = activities.map {
val clazz = it.getActivityClass()
val theme = if (clazz.getValue().isAppCompatActivity()) "android:theme=\"@style/Theme.AppCompat\"" else ""
"<activity android:name=\"${clazz.toString()}\" $theme />"
}.joinToString("\n")
val manifestFile = File.createTempFile("AndroidManifest", ".xml")
manifestFile.writeText(
"""<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="%PACKAGE%">
<uses-sdk android:targetSdkVersion="21"/>
<application>
%ACTIVITIES%
</application>
</manifest>""".replace("%PACKAGE%", applicationPackage).replace("%ACTIVITIES%", activityEntries))
manifestFile
}
// `manifest` is already initialized at this point
fun removeManifest() {
if (manifest.exists()) {
manifest.delete()
}
}
private fun ArrayList<String>.add(name: String, value: String) = add(name + escape(value))
private fun ArrayList<String>.add(name: String, value: VirtualFile) = add(name + escape(value.getPath()))
private fun ArrayList<String>.add(name: String, value: File) = add(name + escape(value.getAbsolutePath()))
public fun makeArguments(): List<String> {
val module = androidFacet.getModule()
val roots = ModuleRootManager.getInstance(module).orderEntries().classes().getRoots()
val androidSdkDirectory = androidFacet.getSdkData()?.getLocation()?.getPath()
val pluginJarPath = PathManager.getJarPathForClass(javaClass)!!
val pluginDirectory = File(pluginJarPath).getParent()
val robowrapperDirectory = File(
File(pluginJarPath).getParentFile().getParentFile(), "robowrapper/")
val robolectricMavenDependencies = RobowrapperDependencies.DEPENDENCIES.map { it.file.getAbsolutePath() }.joinToString(":")
val robowrapperDependencies = listOf(
"gson-2.3.jar",
"jeromq-0.3.4.jar")
.map { File(pluginDirectory, it).getAbsolutePath() }.joinToString(":", prefix = ":")
val robolectricDependencies = robowrapperDirectory
.listFiles { it.name.endsWith(".jar") }
?.map { it.getAbsolutePath() }?.joinToString(":", prefix = ":") ?: ""
val androidDependencies = resolveAndroidDependencies(roots, androidSdkDirectory)
val dependencyDirectory = RobowrapperDependencies.DEPENDENCIES_DIRECTORY
val sdk = ModuleRootManager.getInstance(module).getSdk()
val sdkType = sdk?.getSdkType()
val pathToJava = if (sdk != null && sdkType is JavaSdkType) {
sdkType.getVMExecutablePath(sdk)
} else "java"
val a = arrayListOf(escape(pathToJava), "-cp")
with (a) {
add(robolectricMavenDependencies + robowrapperDependencies + robolectricDependencies + androidDependencies)
add("-Djava.io.tmpdir=", File(dependencyDirectory, "tmp"))
add("-Drobolectric.offline=true")
add("-Drobolectric.dependency.dir=", dependencyDirectory)
add("-Drobo.activityClass=", activityClassName)
add("-Drobo.packageName=", applicationPackage)
add("-Dandroid.manifest=", manifest)
add("-Dandroid.resources=", resDirectory!!)
if (assetsDirectory != null) {
add("-Dandroid.assets=", assetsDirectory)
} else {
add("-Dandroid.assets=", File(resDirectory.getParent().getPath(), "assets"))
}
//TODO: check policy file loading
//add("-Djava.security.manager=default")
//add("-Djava.security.policy=", File(dependencyDirectory, "robowrapper.policy"))
add("org.jetbrains.kotlin.android.robowrapper.Robowrapper")
this
}
return a
}
private fun resolveAndroidDependencies(roots: Array<VirtualFile>, androidSdkDirectory: String?): String {
val sb = StringBuilder()
for (root in roots) {
var item = root.getPath()
if (androidSdkDirectory != null && item.startsWith(androidSdkDirectory)) {
continue
}
if (item.endsWith("!/")) {
item = item.substring(0, item.length() - 2)
}
sb.append(':').append(item.replace(":", "\":"))
}
return sb.toString()
}
private fun escape(v: String?): String {
return (v ?: "").replace("\"", "\\\"").replace(" ", "\\ ")
}
private fun PsiClass?.isAppCompatActivity(): Boolean {
if (this == null) return false
if (getQualifiedName() == "android.support.v7.app.AppCompatActivity") return true
else return getSuperClass()?.isAppCompatActivity() ?: false
}
}
|
apache-2.0
|
98bd118aeb83c693bd1dfd6bc639cc09
| 40.850299 | 131 | 0.649256 | 4.779754 | false | false | false | false |
yholkamp/jacumulus
|
src/main/java/net/nextpulse/jacumulus/requests/models/Expense.kt
|
1
|
2451
|
package net.nextpulse.jacumulus.requests.models
import net.nextpulse.jacumulus.util.typeadapters.BigDecimalAdapter
import net.nextpulse.jacumulus.util.typeadapters.DateAdapter
import net.nextpulse.jacumulus.util.typeadapters.PaymentStatusEnumAdapter
import java.math.BigDecimal
import java.util.*
import javax.xml.bind.annotation.XmlElement
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter
/**
*
* @see [https://www.siel.nl/acumulus/API/Expenses/Add_Expense/]
*/
data class Expense(
@get:XmlElement(name = "description")
var description: String? = null,
@get:XmlJavaTypeAdapter(BigDecimalAdapter::class)
@get:XmlElement(name = "amountexvat")
var amountExVat: BigDecimal? = null,
@get:XmlElement(name = "vatrate")
var vatRate: Int? = null,
@get:XmlElement(name = "vattype")
var vatType: String? = null,
@get:XmlJavaTypeAdapter(DateAdapter::class)
@get:XmlElement(name = "issuedate")
var issueDate: Date? = null,
@get:XmlElement(name = "costheading")
var costHeading: String? = null,
@get:XmlElement(name = "costcenter")
var costCenter: String? = null,
@get:XmlElement(name = "disablelimiteddeduction")
var disableLimitedDeduction: String? = null,
@get:XmlElement(name = "accountnumber")
var accountNumber: String? = null,
@get:XmlElement(name = "paymentstatus")
@get:XmlJavaTypeAdapter(PaymentStatusEnumAdapter::class)
var paymentStatus: PaymentStatus? = null,
@get:XmlJavaTypeAdapter(DateAdapter::class)
@get:XmlElement(name = "paymentdate")
var paymentDate: Date? = null,
/**
* Percentage value between 0 and 100 (including 0 and 100) to be applied to the expense. Defaults to 0 (no privatepercentage applied).
*/
@get:XmlElement(name = "privatepercentage")
var privatePercentage: Int = 0,
@get:XmlElement(name = "recurrences")
var recurrences: String? = null,
@get:XmlElement(name = "monthly")
var monthly: String? = null,
@get:XmlElement(name = "investment")
var investment: Int = 0,
@get:XmlElement(name = "writeoffinyears")
var writeOffInYears: Int? = null,
@get:XmlJavaTypeAdapter(BigDecimalAdapter::class)
@get:XmlElement(name = "scrapvalue")
var scrapValue: BigDecimal = BigDecimal.ZERO
)
|
mit
|
7277d7277484eaeec93997db11c32382
| 41.275862 | 143 | 0.667075 | 3.940514 | false | false | false | false |
Major-/Vicis
|
scene3d/src/main/kotlin/rs/emulate/scene3d/backend/opengl/OpenGLGeometryState.kt
|
1
|
5874
|
package rs.emulate.scene3d.backend.opengl
import org.lwjgl.BufferUtils
import org.lwjgl.opengl.GL11.*
import org.lwjgl.opengl.GL15.*
import org.lwjgl.opengl.GL20.*
import org.lwjgl.opengl.GL30.glBindVertexArray
import org.lwjgl.opengl.GL30.glGenVertexArrays
import org.lwjgl.system.MemoryUtil.NULL
import rs.emulate.scene3d.Camera
import rs.emulate.scene3d.Geometry
import rs.emulate.scene3d.GeometryType
import rs.emulate.scene3d.Node
import rs.emulate.scene3d.backend.opengl.bindings.OpenGLShaderModule
import rs.emulate.scene3d.backend.opengl.bindings.OpenGLShaderModuleType
import rs.emulate.scene3d.backend.opengl.bindings.OpenGLShaderProgram
import rs.emulate.scene3d.material.VertexAttribute
import kotlin.concurrent.withLock
fun GeometryType.toOpenGLType() = when (this) {
GeometryType.TRIANGLES -> GL_TRIANGLES
}
/**
* OpenGL state and container objects for a single geometry node.
*/
class OpenGLGeometryState {
/**
* A flag indicating if the OpenGL state has been fully initialized.
*/
var initialized: Boolean = false
/**
* The type of geometry this state represents.
*/
lateinit var geometryType: GeometryType
/**
* The ID of the Vertex Array Object backing
*/
var vertexArrayObjectId: Int = -1
/**
* The IDs of the Vertex Buffer Objects holding the geometry's vertex attributes.
*/
lateinit var vertexBufferObjectIds: IntArray
/**
* The ID of the Vertex Buffer Object containing the indices for rendering indexed geometry.
* May be empty.
*/
var vertexIndexBufferObjectId: Int = -1
/**
* The shader program this geometry is drawn with.
*/
lateinit var shader: OpenGLShaderProgram
/**
* Create the required OpenGL state from the given [Node].
*/
fun initialize(node: Geometry) {
val material = node.material
val vertexLayout = material.vertexLayout
val vs = OpenGLShaderModule.create(OpenGLShaderModuleType.VERT, material.vertexShader.load())
val fs = OpenGLShaderModule.create(OpenGLShaderModuleType.FRAG, material.fragmentShader.load())
val vaoBuffer = BufferUtils.createIntBuffer(1)
val vboBuffer = BufferUtils.createIntBuffer(vertexLayout.elements.size)
val indexVboBuffer = BufferUtils.createIntBuffer(1)
glGenVertexArrays(vaoBuffer)
glGenBuffers(vboBuffer)
glGenBuffers(indexVboBuffer)
geometryType = node.geometryType
shader = OpenGLShaderProgram.create(vs, fs)
vertexArrayObjectId = vaoBuffer[0]
vertexBufferObjectIds = (0 until vertexLayout.elements.size).map { vboBuffer[it] }.toIntArray()
vertexIndexBufferObjectId = indexVboBuffer[0]
update(node)
initialized = true
}
/**
* Draw the vertex arrays backing this OpenGL state with the parameters supplied by the [Node]'s [Geometry].
*/
fun draw(camera: Camera, node: Geometry) {
shader.bind(
MODEL_MATRIX_UNIFORM to node.worldMatrix,
PROJECTION_MATRIX_UNIFORM to camera.projectionMatrix,
VIEW_MATRIX_UNIFORM to camera.viewMatrix
)
glDepthFunc(GL_LEQUAL)
glEnable(GL_DEPTH_TEST)
glFrontFace(GL_CW)
glCullFace(GL_BACK)
glEnable(GL_CULL_FACE)
glBindVertexArray(vertexArrayObjectId)
if (node.indices.isEmpty()) {
glDrawArrays(geometryType.toOpenGLType(), 0, node.positions.size)
} else {
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexIndexBufferObjectId)
glDrawElements(geometryType.toOpenGLType(), node.indices.size * geometryType.components, GL_UNSIGNED_INT, 0L)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, 0)
}
glUseProgram(0)
glBindVertexArray(0)
}
/**
* Update the already initialized VAOs and VBOs with new vertex data supplied by the [Node].
*/
fun update(node: Geometry) {
node.lock.withLock {
val vertexAttributes = node.material.vertexLayout.elements
for (vertexAttribute in vertexAttributes) {
val data = node.data.buffer(vertexAttribute.type)
val key = vertexAttribute.type.key
val location = shader.attributeLocations[key]
if (data.isEmpty() && !vertexAttribute.optional) {
throw RuntimeException("Required vertex attribute $key not available in node.")
} else if (location == null && !vertexAttribute.optional) {
throw RuntimeException("Required vertex attribute $key was not found in the shader. Perhaps it was unused and optimized out?")
} else if (location == null) {
continue
}
glBindVertexArray(vertexArrayObjectId)
glBindBuffer(GL_ARRAY_BUFFER, vertexBufferObjectIds[location])
glEnableVertexAttribArray(location)
glBufferData(GL_ARRAY_BUFFER, data.buffer.asFloatBuffer(), GL_STATIC_DRAW)
glVertexAttribPointer(location, data.components, GL_FLOAT, false, 0, NULL)
glBindBuffer(GL_ARRAY_BUFFER, 0)
glBindVertexArray(0)
}
if (node.indices.isNotEmpty()) {
val data = node.data.buffer(VertexAttribute.Index)
glBindVertexArray(vertexArrayObjectId)
glBindBuffer(GL_ELEMENT_ARRAY_BUFFER, vertexIndexBufferObjectId)
glBufferData(GL_ELEMENT_ARRAY_BUFFER, data.buffer, GL_DYNAMIC_DRAW)
}
node.dirty = false
glBindVertexArray(0)
}
}
companion object {
const val MODEL_MATRIX_UNIFORM = "model"
const val PROJECTION_MATRIX_UNIFORM = "projection"
const val VIEW_MATRIX_UNIFORM = "view"
}
}
|
isc
|
a5b3b75b341b0e9bcd81d59510409e60
| 34.6 | 147 | 0.662411 | 4.614297 | false | false | false | false |
efficios/jabberwocky
|
jabberwocky-lttng/src/main/kotlin/com/efficios/jabberwocky/lttng/kernel/analysis/os/handlers/KernelEventHandlerUtils.kt
|
2
|
5446
|
/*
* Copyright (C) 2018 EfficiOS Inc., Alexandre Montplaisir <[email protected]>
* Copyright (C) 2015 Ericsson
*
* All rights reserved. This program and the accompanying materials are
* made available under the terms of the Eclipse Public License v1.0 which
* accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*/
package com.efficios.jabberwocky.lttng.kernel.analysis.os.handlers
import ca.polymtl.dorsal.libdelorean.IStateSystemWriter
import ca.polymtl.dorsal.libdelorean.statevalue.IntegerStateValue
import ca.polymtl.dorsal.libdelorean.statevalue.StateValue
import com.efficios.jabberwocky.lttng.kernel.analysis.os.Attributes
import com.efficios.jabberwocky.lttng.kernel.analysis.os.StateValues
/**
* Kernel Event Handler Utils is a collection of static methods to be used in
* subclasses of IKernelEventHandler.
*/
/**
* Gets the CPU quark of the given CPU.
*/
fun IStateSystemWriter.getCPUNode(cpuNumber: Int): Int =
getQuarkRelativeAndAdd(getNodeCPUs(), cpuNumber.toString())
/**
* Get the node quark of the thread currently running on the given CPU.
* 'null' is returned if we do not currently know which thread is running on this cpu.
*/
fun IStateSystemWriter.getCurrentThreadNode(cpuNumber: Int): Int? {
/*
* Shortcut for the "current thread" attribute node. It requires
* querying the current CPU's current thread.
*/
val quark = getQuarkRelativeAndAdd(getCPUNode(cpuNumber), Attributes.CURRENT_THREAD)
val value = queryOngoingState(quark)
val thread = (value as? IntegerStateValue)?.value ?: return null
return getQuarkRelativeAndAdd(getNodeThreads(), Attributes.buildThreadAttributeName(thread, cpuNumber))
}
/**
* When we want to set a process back to a "running" state, first check its
* current System_call attribute. If there is a system call active, we put
* the process back in the syscall state. If not, we put it back in user
* mode state.
*/
fun IStateSystemWriter.setProcessToRunning(timestamp: Long, currentThreadNode: Int) {
val quark = getQuarkRelativeAndAdd(currentThreadNode, Attributes.SYSTEM_CALL)
val sv = if (queryOngoingState(quark).isNull) {
/* We were in user mode before the interruption */
StateValues.PROCESS_STATUS_RUN_USERMODE_VALUE
} else {
/* We were previously in kernel mode */
StateValues.PROCESS_STATUS_RUN_SYSCALL_VALUE
}
modifyAttribute(timestamp, sv, currentThreadNode)
}
/**
* Get the "IRQs" node for the given CPU.
*/
fun IStateSystemWriter.getNodeIRQs(cpuNumber: Int): Int =
getQuarkAbsoluteAndAdd(Attributes.CPUS, Integer.toString(cpuNumber), Attributes.IRQS)
/**
* Get the "CPUs" node.
*/
fun IStateSystemWriter.getNodeCPUs(): Int =
getQuarkAbsoluteAndAdd(Attributes.CPUS)
/**
* Get the Soft IRQs node for the given CPU.
*/
fun IStateSystemWriter.getNodeSoftIRQs(cpuNumber: Int): Int =
getQuarkAbsoluteAndAdd(Attributes.CPUS, Integer.toString(cpuNumber), Attributes.SOFT_IRQS)
/**
* Get the "Threads" node.
*/
fun IStateSystemWriter.getNodeThreads(): Int =
getQuarkAbsoluteAndAdd(Attributes.THREADS)
/**
* Reset the CPU's status when it's coming out of an interruption.
*/
fun IStateSystemWriter.cpuExitInterrupt(timestamp: Long, cpuNumber: Int) {
val cpuNode = getCPUNode(cpuNumber)
val value = getCpuStatus(cpuNode)
modifyAttribute(timestamp, value, cpuNode)
}
/**
* Get the ongoing Status state of a CPU.
*
* This will look through the states of the
*
* <ul>
* <li>IRQ</li>
* <li>Soft IRQ</li>
* <li>Process</li>
* </ul>
*
* under the CPU, giving priority to states higher in the list. If a state
* is a null value, we continue looking down the list.
*
* @param cpuQuark
* The *quark* of the CPU we are looking for. Careful, this is
* NOT the CPU number (or attribute name)!
* @return The state value that represents the status of the given CPU
*/
private fun IStateSystemWriter.getCpuStatus(cpuQuark: Int): StateValue {
/* Check if there is a IRQ running */
getQuarkRelativeAndAdd(cpuQuark, Attributes.IRQS)
.let { getSubAttributes(it, false) }
.map { queryOngoingState(it) }
.forEach {
if (!it.isNull) {
return it
}
}
/* Check if there is a soft IRQ running */
getQuarkRelativeAndAdd(cpuQuark, Attributes.SOFT_IRQS)
.let { getSubAttributes(it, false) }
.map { queryOngoingState(it) }
.forEach {
if (!it.isNull) {
return it
}
}
/*
* Check if there is a thread running. If not, report IDLE. If there is,
* report the running state of the thread (usermode or system call).
*/
val currentThreadState = getQuarkRelativeAndAdd(cpuQuark, Attributes.CURRENT_THREAD)
.let { queryOngoingState(it) } as? IntegerStateValue ?: return StateValue.nullValue()
val tid = currentThreadState.value
if (tid == 0) {
return StateValues.CPU_STATUS_IDLE_VALUE
}
val threadSystemCallQuark = getQuarkAbsoluteAndAdd(Attributes.THREADS, tid.toString(), Attributes.SYSTEM_CALL)
return if (queryOngoingState(threadSystemCallQuark).isNull) {
StateValues.CPU_STATUS_RUN_USERMODE_VALUE
} else {
StateValues.CPU_STATUS_RUN_SYSCALL_VALUE
}
}
|
epl-1.0
|
594b15e9deea03f7927d081f089ab3bd
| 34.363636 | 114 | 0.696107 | 3.819074 | false | false | false | false |
spinnaker/orca
|
orca-core/src/main/java/com/netflix/spinnaker/orca/DynamicTaskImplementationResolver.kt
|
2
|
3500
|
package com.netflix.spinnaker.orca
import com.netflix.spinnaker.kork.dynamicconfig.DynamicConfigService
import com.netflix.spinnaker.orca.api.pipeline.Task
import com.netflix.spinnaker.orca.api.pipeline.graph.TaskNode.DefinedTask
import com.netflix.spinnaker.orca.api.pipeline.graph.TaskNode.TaskDefinition
import com.netflix.spinnaker.orca.api.pipeline.models.StageExecution
import com.netflix.spinnaker.orca.clouddriver.utils.CloudProviderAware
import com.netflix.spinnaker.orca.config.TaskOverrideConfigurationProperties
import com.netflix.spinnaker.orca.config.TaskOverrideConfigurationProperties.TaskOverrideDefinition
import org.slf4j.LoggerFactory
/**
* This resolver will modify the task definition if the original definition
* matches the criteria for task replacement and the configuration for such a replacement is enabled.
*/
class DynamicTaskImplementationResolver(
val dynamicConfigService: DynamicConfigService,
val taskOverrideConfigurationProperties: TaskOverrideConfigurationProperties
) : TaskImplementationResolver, CloudProviderAware {
private val log = LoggerFactory.getLogger(javaClass)
override fun resolve(stage: StageExecution, taskNode: DefinedTask): DefinedTask {
val taskOverrideDefinition = taskOverrideConfigurationProperties
.overrideDefinitions
.firstOrNull {
it.stageName.equals(stage.type, true) &&
it.originalTaskImplementingClassName.equals(taskNode.implementingClassName, true)
} ?: return taskNode
if (isOverrideEnabled(getConfigAttributeName(stage, taskOverrideDefinition))) {
val clazz: Class<*> = Class.forName(taskOverrideDefinition.newTaskImplementingClassName)
if (Task::class.java.isAssignableFrom(clazz)) {
val newTask: DefinedTask = TaskDefinition(
taskNode.name, // task name remains the same.
clazz as Class<Task>
)
log.info(
"Task '{}' is overridden with new task impl class '{}'",
taskNode.name,
taskOverrideDefinition.newTaskImplementingClassName
)
return newTask
}
log.warn(
"Task '{}' is overridden but the new task impl class '{}' is not of type task",
taskNode.name,
taskOverrideDefinition.newTaskImplementingClassName
)
}
log.info("No task override set {}", taskNode.name)
return taskNode
}
private fun getConfigAttributeName(
stage: StageExecution,
taskOverrideDefinition: TaskOverrideDefinition
): String {
val configAttributeParts: MutableList<String> = mutableListOf()
taskOverrideDefinition.overrideCriteriaAttributes?.forEach {
when (it) {
APPLICATION_ATTR_NAME -> configAttributeParts.add(stage.execution.application)
CLOUDPROVIDER_ATTR_NAME ->
configAttributeParts.add(getCloudProvider(stage) ?: CloudProviderAware.DEFAULT_CLOUD_PROVIDER)
else -> {
if (stage.context[it] != null) {
configAttributeParts.add(stage.context[it].toString())
}
}
}
}
configAttributeParts.add(stage.type.toLowerCase())
return configAttributeParts.joinToString(".", ATTRIBUTE_PREFIX)
}
private fun isOverrideEnabled(configAttrName: String): Boolean {
return dynamicConfigService.isEnabled(configAttrName, false)
}
private companion object {
const val ATTRIBUTE_PREFIX = "task-override."
const val APPLICATION_ATTR_NAME = "application"
const val CLOUDPROVIDER_ATTR_NAME = "cloudprovider"
}
}
|
apache-2.0
|
60f3cd0d8b11064690d0c76a28c84530
| 38.772727 | 104 | 0.74 | 4.710633 | false | true | false | false |
GunoH/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/ReplaceCollectionCountWithSizeInspection.kt
|
2
|
2490
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package org.jetbrains.kotlin.idea.inspections
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.builtins.KotlinBuiltIns
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyze
import org.jetbrains.kotlin.idea.inspections.collections.isCalling
import org.jetbrains.kotlin.name.FqName
import org.jetbrains.kotlin.psi.KtCallExpression
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.callExpressionVisitor
import org.jetbrains.kotlin.resolve.lazy.BodyResolveMode
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.intentions.receiverType
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
class ReplaceCollectionCountWithSizeInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return callExpressionVisitor(fun(callExpression: KtCallExpression) {
if (callExpression.calleeExpression?.text != "count" || callExpression.valueArguments.isNotEmpty()) return
val context = callExpression.analyze(BodyResolveMode.PARTIAL)
if (!callExpression.isCalling(FqName("kotlin.collections.count"))) return
val receiverType = callExpression.getResolvedCall(context)?.resultingDescriptor?.receiverType()?: return
if (KotlinBuiltIns.isIterableOrNullableIterable(receiverType)) return
holder.registerProblem(
callExpression,
KotlinBundle.message("could.be.replaced.with.size"),
ReplaceCollectionCountWithSizeQuickFix()
)
})
}
}
class ReplaceCollectionCountWithSizeQuickFix : LocalQuickFix {
override fun getName() = KotlinBundle.message("replace.collection.count.with.size.quick.fix.text")
override fun getFamilyName() = name
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val element = descriptor.psiElement as KtCallExpression
element.replace(KtPsiFactory(element).createExpression("size"))
}
}
|
apache-2.0
|
85cc555ef76f4ca2e723acc2c594834b
| 48.8 | 120 | 0.781526 | 5.102459 | false | false | false | false |
shogo4405/HaishinKit.java
|
haishinkit/src/main/java/com/haishinkit/media/MediaProjectionSource.kt
|
1
|
3447
|
package com.haishinkit.media
import android.content.Context
import android.hardware.display.DisplayManager
import android.hardware.display.VirtualDisplay
import android.media.projection.MediaProjection
import android.util.DisplayMetrics
import android.util.Log
import android.util.Size
import android.view.Surface
import com.haishinkit.BuildConfig
import com.haishinkit.codec.util.ScheduledFpsController
import com.haishinkit.graphics.PixelTransform
import com.haishinkit.net.NetStream
import java.util.concurrent.atomic.AtomicBoolean
/**
* A video source that captures a display by the MediaProjection API.
*/
class MediaProjectionSource(
private val context: Context,
private var mediaProjection: MediaProjection,
private val metrics: DisplayMetrics,
override val fpsControllerClass: Class<*>? = ScheduledFpsController::class.java,
override var utilizable: Boolean = false
) :
VideoSource, PixelTransform.Listener {
var scale = 0.5F
var rotatesWithContent = true
override var stream: NetStream? = null
set(value) {
field = value
stream?.videoCodec?.fpsControllerClass = fpsControllerClass
}
override val isRunning = AtomicBoolean(false)
override var resolution = Size(1, 1)
set(value) {
field = value
stream?.videoSetting?.width = value.width
stream?.videoSetting?.height = value.height
}
private var virtualDisplay: VirtualDisplay? = null
override fun setUp() {
if (utilizable) return
resolution =
Size((metrics.widthPixels * scale).toInt(), (metrics.heightPixels * scale).toInt())
stream?.videoCodec?.setAssetManager(context.assets)
stream?.videoCodec?.setListener(this)
super.setUp()
}
override fun tearDown() {
if (!utilizable) return
mediaProjection.stop()
super.tearDown()
}
override fun startRunning() {
if (isRunning.get()) return
if (BuildConfig.DEBUG) {
Log.d(TAG, "startRunning()")
}
isRunning.set(true)
}
override fun stopRunning() {
if (!isRunning.get()) return
if (BuildConfig.DEBUG) {
Log.d(TAG, "stopRunning()")
}
virtualDisplay?.release()
isRunning.set(false)
}
override fun onPixelTransformImageAvailable(pixelTransform: PixelTransform) {
}
override fun onPixelTransformSurfaceChanged(pixelTransform: PixelTransform, surface: Surface?) {
pixelTransform.createInputSurface(resolution.width, resolution.height, 0x1)
}
override fun onPixelTransformInputSurfaceCreated(
pixelTransform: PixelTransform,
surface: Surface
) {
var flags = DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR
if (rotatesWithContent) {
flags += VIRTUAL_DISPLAY_FLAG_ROTATES_WITH_CONTENT
}
virtualDisplay = mediaProjection.createVirtualDisplay(
DEFAULT_DISPLAY_NAME,
resolution.width,
resolution.height,
metrics.densityDpi,
flags,
surface,
null,
null
)
}
companion object {
const val DEFAULT_DISPLAY_NAME = "MediaProjectionSourceDisplay"
private const val VIRTUAL_DISPLAY_FLAG_ROTATES_WITH_CONTENT = 128
private val TAG = MediaProjectionSource::class.java.simpleName
}
}
|
bsd-3-clause
|
af9dcf5b7cc8feb22d18e6f00c401fa9
| 30.916667 | 100 | 0.668697 | 4.683424 | false | false | false | false |
GunoH/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/actions/ShowMessageHistoryAction.kt
|
4
|
6677
|
// 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.openapi.vcs.actions
import com.intellij.icons.AllIcons
import com.intellij.ide.TextCopyProvider
import com.intellij.openapi.actionSystem.ActionUpdateThread
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.PlatformDataKeys.COPY_PROVIDER
import com.intellij.openapi.application.ApplicationManager.getApplication
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.actions.ContentChooser.RETURN_SYMBOL
import com.intellij.openapi.editor.colors.EditorFontType
import com.intellij.openapi.fileEditor.impl.text.TextEditorProvider
import com.intellij.openapi.project.DumbAwareAction
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.popup.JBPopup
import com.intellij.openapi.ui.popup.JBPopupFactory
import com.intellij.openapi.ui.popup.JBPopupListener
import com.intellij.openapi.ui.popup.LightweightWindowEvent
import com.intellij.openapi.util.text.StringUtil.convertLineSeparators
import com.intellij.openapi.util.text.StringUtil.first
import com.intellij.openapi.vcs.CheckinProjectPanel
import com.intellij.openapi.vcs.VcsConfiguration
import com.intellij.openapi.vcs.VcsDataKeys
import com.intellij.openapi.vcs.ui.CommitMessage
import com.intellij.ui.ColoredListCellRenderer
import com.intellij.ui.awt.RelativePoint
import com.intellij.ui.speedSearch.SpeedSearchUtil.applySpeedSearchHighlighting
import com.intellij.util.ObjectUtils.sentinel
import com.intellij.util.containers.nullize
import com.intellij.util.ui.JBUI.scale
import com.intellij.vcs.commit.NonModalCommitPanel
import com.intellij.vcs.commit.message.CommitMessageInspectionProfile.getSubjectRightMargin
import org.jetbrains.annotations.Nls
import java.awt.Point
import javax.swing.JList
import javax.swing.ListSelectionModel.SINGLE_SELECTION
/**
* Action showing the history of recently used commit messages. Source code of this class is provided
* as a sample of using the [CheckinProjectPanel] API. Actions to be shown in the commit dialog
* should be added to the `Vcs.MessageActionGroup` action group.
*/
class ShowMessageHistoryAction : DumbAwareAction() {
init {
isEnabledInModalContext = true
}
override fun update(e: AnActionEvent) {
val project = e.project
val commitMessage = getCommitMessage(e)
if (e.place == NonModalCommitPanel.COMMIT_TOOLBAR_PLACE) {
e.presentation.icon = AllIcons.Vcs.HistoryInline
e.presentation.hoveredIcon = AllIcons.Vcs.HistoryInlineHovered
}
e.presentation.isVisible = project != null && commitMessage != null
e.presentation.isEnabled = e.presentation.isVisible && !VcsConfiguration.getInstance(project!!).recentMessages.isEmpty()
}
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.BGT
}
override fun actionPerformed(e: AnActionEvent) {
val project = e.project!!
val commitMessage = getCommitMessage(e)!!
createPopup(project, commitMessage, VcsConfiguration.getInstance(project).recentMessages.reversed())
.showInBestPositionFor(e.dataContext)
}
private fun createPopup(project: Project, commitMessage: CommitMessage, messages: List<String>): JBPopup {
var chosenMessage: String? = null
var selectedMessage: String? = null
val rightMargin = getSubjectRightMargin(project)
val previewCommandGroup = sentinel("Preview Commit Message")
return JBPopupFactory.getInstance().createPopupChooserBuilder(messages)
.setFont(commitMessage.editorField.editor?.colorsScheme?.getFont(EditorFontType.PLAIN))
.setVisibleRowCount(7)
.setSelectionMode(SINGLE_SELECTION)
.setItemSelectedCallback {
selectedMessage = it
it?.let { preview(project, commitMessage, it, previewCommandGroup) }
}
.setItemChosenCallback { chosenMessage = it }
.setRenderer(object : ColoredListCellRenderer<String>() {
override fun customizeCellRenderer(list: JList<out String>, value: @Nls String, index: Int, selected: Boolean, hasFocus: Boolean) {
append(first(convertLineSeparators(value, RETURN_SYMBOL), rightMargin, false))
applySpeedSearchHighlighting(list, this, true, selected)
}
})
.addListener(object : JBPopupListener {
override fun beforeShown(event: LightweightWindowEvent) {
val popup = event.asPopup()
val relativePoint = RelativePoint(commitMessage.editorField, Point(0, -scale(3)))
val screenPoint = Point(relativePoint.screenPoint).apply { translate(0, -popup.size.height) }
popup.setLocation(screenPoint)
}
override fun onClosed(event: LightweightWindowEvent) {
// IDEA-195094 Regression: New CTRL-E in "commit changes" breaks keyboard shortcuts
commitMessage.editorField.requestFocusInWindow()
// Use invokeLater() as onClosed() is called before callback from setItemChosenCallback
getApplication().invokeLater { chosenMessage ?: cancelPreview(project, commitMessage) }
}
})
.setNamerForFiltering { it }
.setAutoPackHeightOnFiltering(false)
.createPopup()
.apply {
setDataProvider { dataId ->
when (dataId) {
// default list action does not work as "CopyAction" is invoked first, but with other copy provider
COPY_PROVIDER.name -> object : TextCopyProvider() {
override fun getActionUpdateThread(): ActionUpdateThread = ActionUpdateThread.EDT
override fun getTextLinesToCopy() = listOfNotNull(selectedMessage).nullize()
}
else -> null
}
}
}
}
private fun preview(project: Project,
commitMessage: CommitMessage,
message: String,
groupId: Any) =
CommandProcessor.getInstance().executeCommand(project, {
commitMessage.setCommitMessage(message)
commitMessage.editorField.selectAll()
}, "", groupId, commitMessage.editorField.document)
private fun cancelPreview(project: Project, commitMessage: CommitMessage) {
val manager = UndoManager.getInstance(project)
val fileEditor = commitMessage.editorField.editor?.let { TextEditorProvider.getInstance().getTextEditor(it) }
if (manager.isUndoAvailable(fileEditor)) manager.undo(fileEditor)
}
private fun getCommitMessage(e: AnActionEvent) = e.getData(VcsDataKeys.COMMIT_MESSAGE_CONTROL) as? CommitMessage
}
|
apache-2.0
|
fa8ab1b9524f2ab10c1e92aaa97c217d
| 44.421769 | 140 | 0.751385 | 4.852471 | false | false | false | false |
jk1/intellij-community
|
plugins/gradle/java/src/service/resolve/GradleExtensionsContributor.kt
|
4
|
15684
|
// 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.service.resolve
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator
import com.intellij.openapi.roots.ProjectFileIndex
import com.intellij.openapi.util.Ref
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PatternCondition
import com.intellij.patterns.PsiJavaPatterns.psiElement
import com.intellij.psi.CommonClassNames.*
import com.intellij.psi.JavaPsiFacade
import com.intellij.psi.PsiElement
import com.intellij.psi.ResolveState
import com.intellij.psi.scope.ElementClassHint
import com.intellij.psi.scope.NameHint
import com.intellij.psi.scope.PsiScopeProcessor
import com.intellij.util.ProcessingContext
import groovy.lang.Closure
import org.jetbrains.plugins.gradle.service.resolve.GradleCommonClassNames.*
import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings
import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings.GradleProp
import org.jetbrains.plugins.gradle.settings.GradleExtensionsSettings.GradleTask
import org.jetbrains.plugins.groovy.dsl.holders.NonCodeMembersHolder.DOCUMENTATION
import org.jetbrains.plugins.groovy.lang.parser.GroovyElementTypes.COMPOSITE_LSHIFT_SIGN
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.*
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.path.GrMethodCallExpression
import org.jetbrains.plugins.groovy.lang.psi.impl.GroovyPsiManager
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.path.GrMethodCallExpressionImpl
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightMethodBuilder
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrLightVariable
import org.jetbrains.plugins.groovy.lang.psi.patterns.GroovyClosurePattern
import org.jetbrains.plugins.groovy.lang.psi.patterns.GroovyPatterns.groovyBinaryExpression
import org.jetbrains.plugins.groovy.lang.psi.patterns.groovyClosure
import org.jetbrains.plugins.groovy.lang.psi.patterns.psiMethod
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_LANG_CLOSURE
import org.jetbrains.plugins.groovy.lang.resolve.ResolveUtil
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_KEY
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DELEGATES_TO_STRATEGY_KEY
import org.jetbrains.plugins.groovy.lang.resolve.delegatesTo.DelegatesToInfo
/**
* @author Vladislav.Soroka
* @since 11/16/2016
*/
class GradleExtensionsContributor : GradleMethodContextContributor {
override fun getDelegatesToInfo(closure: GrClosableBlock): DelegatesToInfo? {
val extensionsData = getExtensionsFor(closure) ?: return null
for (extension in extensionsData.extensions) {
val extensionClosure = groovyClosure().inMethod(psiMethod(GRADLE_API_PROJECT, extension.name))
if (extensionClosure.accepts(closure)) {
return DelegatesToInfo(TypesUtil.createType(extension.rootTypeFqn, closure), Closure.DELEGATE_FIRST)
}
val objectTypeFqn = extension.namedObjectTypeFqn?.let { if (it.isNotBlank()) it else null } ?: continue
val objectType = TypesUtil.createType(objectTypeFqn, closure)
val objectClosure = groovyClosure().withAncestor(2, extensionClosure)
if (objectClosure.accepts(closure)) {
return DelegatesToInfo(objectType, Closure.DELEGATE_FIRST)
}
val objectReference = object : ElementPattern<PsiElement> {
override fun getCondition() = null
override fun accepts(o: Any?) = false
override fun accepts(o: Any?, context: ProcessingContext): Boolean {
return o is GrExpression && o.type?.isAssignableFrom(objectType) ?: false
}
}
if (psiElement().withParent(
psiElement().withFirstChild(objectReference)).accepts(closure)) {
return DelegatesToInfo(objectType, Closure.DELEGATE_FIRST)
}
}
return null
}
override fun process(methodCallInfo: MutableList<String>,
processor: PsiScopeProcessor,
state: ResolveState,
place: PsiElement): Boolean {
val extensionsData = getExtensionsFor(place) ?: return true
val classHint = processor.getHint(ElementClassHint.KEY)
val shouldProcessMethods = ResolveUtil.shouldProcessMethods(classHint)
val shouldProcessProperties = ResolveUtil.shouldProcessProperties(classHint)
val groovyPsiManager = GroovyPsiManager.getInstance(place.project)
val resolveScope = place.resolveScope
val projectClass = JavaPsiFacade.getInstance(place.project).findClass(GRADLE_API_PROJECT, resolveScope) ?: return true
val name = processor.getHint(NameHint.KEY)?.getName(state)
if (psiElement().inside(closureInLeftShiftMethod).accepts(place)) {
if (!GradleResolverUtil.processDeclarations(processor, state, place, GRADLE_API_DEFAULT_TASK)) {
return false
}
}
if (place.text == "task" && place is GrReferenceExpression && place.parent is GrApplicationStatement) {
if (GradleResolverUtil.isLShiftElement(place.parent?.children?.getOrNull(1)?.firstChild)) {
val taskContainerClass = JavaPsiFacade.getInstance(place.project).findClass(GRADLE_API_TASK_CONTAINER, resolveScope) ?: return true
val returnClass = groovyPsiManager.createTypeByFQClassName(GRADLE_API_TASK, resolveScope) ?: return true
val methodBuilder = GrLightMethodBuilder(place.manager, "create").apply {
containingClass = taskContainerClass
returnType = returnClass
}
methodBuilder.addParameter("task", GRADLE_API_TASK, true)
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(methodBuilder, state)) return false
}
}
for (extension in extensionsData.extensions) {
if (!processExtension(processor, state, place, extension)) return false
if (name == extension.name) break
}
if (place.getUserData(RESOLVED_CODE).let { it == null || !it }) {
if (psiElement().withAncestor(2, groovyClosure().with(object : PatternCondition<GrClosableBlock?>("withDelegatesToInfo") {
override fun accepts(t: GrClosableBlock, context: ProcessingContext?): Boolean {
return getDelegatesToInfo(t) != null
}
})).accepts(place)) {
return true
}
var isTaskDeclaration = false
val parent = place.parent
val superParent = parent?.parent
if (superParent is GrCommandArgumentList && superParent.parent?.firstChild?.text == "task") {
isTaskDeclaration = true
}
for (gradleTask in extensionsData.tasks) {
if (shouldProcessMethods && name == gradleTask.name) {
val returnClass = groovyPsiManager.createTypeByFQClassName(
if (isTaskDeclaration) JAVA_LANG_STRING else gradleTask.typeFqn, resolveScope) ?: continue
val methodBuilder = GrLightMethodBuilder(place.manager, gradleTask.name).apply {
containingClass = projectClass
returnType = returnClass
if (parent is GrMethodCallExpressionImpl && parent.argumentList.namedArguments.isNotEmpty()) {
addParameter("args", JAVA_UTIL_MAP, true)
}
val closureParam = addAndGetParameter("configuration", GROOVY_LANG_CLOSURE, true)
closureParam.putUserData(DELEGATES_TO_KEY, gradleTask.typeFqn)
closureParam.putUserData(DELEGATES_TO_STRATEGY_KEY, Closure.OWNER_FIRST)
}
if (!processor.execute(methodBuilder, state)) return false
break
}
val taskClosure = groovyClosure().inMethod(psiMethod(GRADLE_API_PROJECT, gradleTask.name))
val psiElement = psiElement()
if (psiElement.inside(taskClosure).accepts(place)) {
if (shouldProcessMethods && !GradleResolverUtil.processDeclarations(processor, state, place, gradleTask.typeFqn)) {
place.putUserData(RESOLVED_CODE, null)
return false
}
else {
place.putUserData(RESOLVED_CODE, null)
}
}
}
if (name != null && place is GrReferenceExpression && !place.isQualified) {
if (!shouldProcessMethods && shouldProcessProperties) {
for (gradleTask in extensionsData.tasks) {
if (name == gradleTask.name) {
val docRef = Ref.create<String>()
val variable = object : GrLightVariable(place.manager, name, gradleTask.typeFqn, place) {
override fun getNavigationElement(): PsiElement {
val navigationElement = super.getNavigationElement()
navigationElement.putUserData(DOCUMENTATION, docRef.get())
return navigationElement
}
}
val doc = getDocumentation(gradleTask, variable)
docRef.set(doc)
place.putUserData(DOCUMENTATION, doc)
if (!processor.execute(variable, state)) return false
break
}
}
}
val propExecutionResult = extensionsData.findProperty(name)?.let {
if (!shouldProcessMethods && shouldProcessProperties) {
val docRef = Ref.create<String>()
val variable = object : GrLightVariable(place.manager, name, it.typeFqn, place) {
override fun getNavigationElement(): PsiElement {
val navigationElement = super.getNavigationElement()
navigationElement.putUserData(DOCUMENTATION, docRef.get())
return navigationElement
}
}
val doc = getDocumentation(it, variable)
docRef.set(doc)
place.putUserData(DOCUMENTATION, doc)
return processor.execute(variable, state)
}
else if (shouldProcessMethods && it.typeFqn == GROOVY_LANG_CLOSURE) {
val returnClass = groovyPsiManager.createTypeByFQClassName(GROOVY_LANG_CLOSURE, resolveScope) ?: return true
val methodBuilder = GrLightMethodBuilder(place.manager, name).apply {
returnType = returnClass
addParameter("args", JAVA_LANG_OBJECT, true)
}
return processor.execute(methodBuilder, state)
}
true
}
if (propExecutionResult != null && propExecutionResult) return false
}
}
return true
}
companion object {
val closureInLeftShiftMethod: GroovyClosurePattern = groovyClosure().withTreeParent(
groovyBinaryExpression().with(object : PatternCondition<GrBinaryExpression?>("leftShiftCondition") {
override fun accepts(t: GrBinaryExpression, context: ProcessingContext?): Boolean {
return t.operationTokenType == COMPOSITE_LSHIFT_SIGN
}
}))
fun getExtensionsFor(psiElement: PsiElement): GradleExtensionsSettings.GradleExtensionsData? {
val project = psiElement.project
val virtualFile = psiElement.containingFile?.originalFile?.virtualFile ?: return null
val module = ProjectFileIndex.SERVICE.getInstance(project).getModuleForFile(virtualFile)
return GradleExtensionsSettings.getInstance(project).getExtensionsFor(module) ?: return null
}
fun getDocumentation(gradleProp: GradleExtensionsSettings.TypeAware,
lightVariable: GrLightVariable): String? {
if (gradleProp is GradleProp) {
return getDocumentation(gradleProp, lightVariable)
}
else if (gradleProp is GradleTask) {
return getDocumentation(gradleProp, lightVariable)
}
else {
return null
}
}
fun getDocumentation(gradleProp: GradleProp,
lightVariable: GrLightVariable): String {
val buffer = StringBuilder()
buffer.append("<PRE>")
JavaDocInfoGenerator.generateType(buffer, lightVariable.type, lightVariable, true)
buffer.append(" " + gradleProp.name)
val hasInitializer = !gradleProp.value.isNullOrBlank()
if (hasInitializer) {
buffer.append(" = ")
val longString = gradleProp.value!!.toString().length > 100
if (longString) {
buffer.append("<blockquote>")
}
buffer.append(gradleProp.value)
if (longString) {
buffer.append("</blockquote>")
}
}
buffer.append("</PRE>")
if (hasInitializer) {
buffer.append("<br><b>Initial value has been got during last import</b>")
}
return buffer.toString()
}
fun getDocumentation(gradleTask: GradleTask,
lightVariable: GrLightVariable): String {
val buffer = StringBuilder()
buffer.append("<PRE>")
JavaDocInfoGenerator.generateType(buffer, lightVariable.type, lightVariable, true)
buffer.append(" " + gradleTask.name)
buffer.append("</PRE>")
if (!gradleTask.description.isNullOrBlank()) {
buffer.append(gradleTask.description)
}
return buffer.toString()
}
}
}
fun processExtension(processor: PsiScopeProcessor,
state: ResolveState,
place: PsiElement,
extension: GradleExtensionsSettings.GradleExtension): Boolean {
val classHint = processor.getHint(ElementClassHint.KEY)
val shouldProcessMethods = ResolveUtil.shouldProcessMethods(classHint)
val groovyPsiManager = GroovyPsiManager.getInstance(place.project)
val resolveScope = place.resolveScope
val projectClass = JavaPsiFacade.getInstance(place.project).findClass(GRADLE_API_PROJECT, resolveScope) ?: return true
val name = processor.getHint(NameHint.KEY)?.getName(state)
if (name == extension.name) {
val returnClass = groovyPsiManager.createTypeByFQClassName(extension.rootTypeFqn, resolveScope) ?: return true
val methodName = if (shouldProcessMethods) extension.name else "get" + extension.name.capitalize()
val methodBuilder = GrLightMethodBuilder(place.manager, methodName).apply {
containingClass = projectClass
returnType = returnClass
}
if (shouldProcessMethods) {
methodBuilder.addParameter("configuration", GROOVY_LANG_CLOSURE, true)
}
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(methodBuilder, state)) return false
}
val extensionClosure = groovyClosure().inMethod(psiMethod(GRADLE_API_PROJECT, extension.name))
val placeText = place.text
val psiElement = psiElement()
if (psiElement.inside(extensionClosure).accepts(place)) {
if (shouldProcessMethods && !GradleResolverUtil.processDeclarations(processor, state, place, extension.rootTypeFqn)) {
return false
}
val objectTypeFqn = extension.namedObjectTypeFqn?.let { if (it.isNotBlank()) it else null } ?: return true
if (place.parent is GrMethodCallExpression) {
val methodBuilder = GradleResolverUtil.createMethodWithClosure(placeText, objectTypeFqn, null, place)
if (methodBuilder != null) {
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(methodBuilder, state)) return false
}
}
if (place.parent is GrReferenceExpression || psiElement.withTreeParent(extensionClosure).accepts(place)) {
val variable = GrLightVariable(place.manager, placeText, objectTypeFqn, place)
place.putUserData(RESOLVED_CODE, true)
if (!processor.execute(variable, state)) return false
}
}
return true
}
|
apache-2.0
|
d6ee9eca37f112045827341ed15ecaab
| 45.958084 | 140 | 0.704157 | 4.928975 | false | false | false | false |
AsamK/TextSecure
|
app/src/main/java/org/thoughtcrime/securesms/mediasend/v2/text/TextStoryPostLinkEntryFragment.kt
|
1
|
2946
|
package org.thoughtcrime.securesms.mediasend.v2.text
import android.content.DialogInterface
import android.os.Bundle
import android.view.View
import android.widget.EditText
import androidx.constraintlayout.widget.Group
import androidx.core.widget.addTextChangedListener
import androidx.fragment.app.viewModels
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.components.KeyboardEntryDialogFragment
import org.thoughtcrime.securesms.linkpreview.LinkPreviewRepository
import org.thoughtcrime.securesms.linkpreview.LinkPreviewViewModel
import org.thoughtcrime.securesms.stories.StoryLinkPreviewView
import org.thoughtcrime.securesms.util.ViewUtil
import org.thoughtcrime.securesms.util.visible
class TextStoryPostLinkEntryFragment : KeyboardEntryDialogFragment(
contentLayoutId = R.layout.stories_text_post_link_entry_fragment
) {
private lateinit var input: EditText
private val linkPreviewViewModel: LinkPreviewViewModel by viewModels(
factoryProducer = { LinkPreviewViewModel.Factory(LinkPreviewRepository()) }
)
private val viewModel: TextStoryPostCreationViewModel by viewModels(
ownerProducer = {
requireActivity()
}
)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
input = view.findViewById(R.id.input)
val linkPreview: StoryLinkPreviewView = view.findViewById(R.id.link_preview)
val confirmButton: View = view.findViewById(R.id.confirm_button)
val shareALinkGroup: Group = view.findViewById(R.id.share_a_link_group)
input.addTextChangedListener(
afterTextChanged = {
val scheme = "https://"
val (uriString, selectionStart, selectionEnd) = if (it!!.startsWith(scheme)) {
Triple(it, input.selectionStart, input.selectionEnd)
} else {
Triple("$scheme$it", input.selectionStart + scheme.length, input.selectionEnd + scheme.length)
}
linkPreviewViewModel.onTextChanged(requireContext(), uriString.toString(), selectionStart, selectionEnd)
}
)
confirmButton.setOnClickListener {
val linkPreviewState = linkPreviewViewModel.linkPreviewState.value
if (linkPreviewState != null) {
val url = linkPreviewState.linkPreview.map { it.url }.orElseGet { linkPreviewState.activeUrlForError }
viewModel.setLinkPreview(url)
}
dismissAllowingStateLoss()
}
linkPreviewViewModel.linkPreviewState.observe(viewLifecycleOwner) { state ->
linkPreview.bind(state)
shareALinkGroup.visible = !state.isLoading && !state.linkPreview.isPresent && (state.error == null && state.activeUrlForError == null)
confirmButton.isEnabled = state.linkPreview.isPresent || state.activeUrlForError != null
}
}
override fun onResume() {
super.onResume()
ViewUtil.focusAndShowKeyboard(input)
}
override fun onDismiss(dialog: DialogInterface) {
linkPreviewViewModel.onSend()
super.onDismiss(dialog)
}
}
|
gpl-3.0
|
7afdc5f94c1f902904c818e3bbb035eb
| 35.825 | 140 | 0.759335 | 4.7136 | false | false | false | false |
andrewoma/dexx
|
kollection/src/test/kotlin/com/github/andrewoma/dexx/kollection/AbstractImmutableSetTest.kt
|
1
|
3883
|
/*
* Copyright (c) 2015 Andrew O'Malley
*
* 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.andrewoma.dexx.kollection
import org.assertj.core.api.Assertions.assertThat
import org.junit.Test
abstract class AbstractImmutableSetTest {
abstract fun <E : Comparable<E>> set(vararg elements: E): ImmutableSet<E>
@Test fun `should support immutable semantics`() {
val set1 = set(1, 2, 3)
val set2 = set1 + 4
val set3 = set1 - 1
assertThat(set1).isEqualTo(set(1, 2, 3))
assertThat(set2).isEqualTo(set(1, 2, 3, 4))
assertThat(set3).isEqualTo(set(2, 3))
}
@Test fun `should support equals and hashCode`() {
assertThat(set<Int>()).isEqualTo(set<Int>())
assertThat(set(1)).isEqualTo(set(1))
assertThat(set(1, 2, 3)).isEqualTo(set(1, 2, 3))
assertThat(set(1, 2, 3)).isNotEqualTo(set(2, 3, 4))
assertThat(set<Int>().hashCode()).isEqualTo(set<Int>().hashCode())
assertThat(set(1).hashCode()).isEqualTo(set(1).hashCode())
assertThat(set(1, 2, 3).hashCode()).isEqualTo(set(1, 2, 3).hashCode())
assertThat(set(1, 2, 3).hashCode()).isNotEqualTo(set(2, 3, 4).hashCode())
}
@Test fun `should equal kotlin sets`() {
assertThat(set(1, 2, 3)).isEqualTo(hashSetOf(1, 2, 3))
assertThat(hashSetOf(1, 2, 3)).isEqualTo(set(1, 2, 3))
}
@Test fun `should convert to and from kotlin collections`() {
assertThat(arrayListOf(1, 2, 3).toImmutableSet()).isEqualTo(set(1, 2, 3))
assertThat(set(1, 2, 3).toSet()).isEqualTo(setOf(1, 2, 3))
}
@Test fun `should support bulk operations`() {
assertThat(set(1, 2, 3) + set(4, 5)).isEqualTo(set(1, 2, 3, 4, 5))
assertThat(set(1, 2, 3) - set(1, 2)).isEqualTo(set(3))
}
@Test fun `should support contains`() {
assertThat(set(1, 2, 3).contains(1)).isTrue()
assertThat(set(1, 2, 3).contains(4)).isFalse()
assertThat(set(1, 2, 3).containsAll(setOf(1, 2, 3))).isTrue()
assertThat(set(1, 2, 3).containsAll(setOf(1, 2))).isTrue()
assertThat(set(1, 2, 3).containsAll(setOf(1, 2, 3, 4))).isFalse()
}
@Test fun `should support size`() {
assertThat(set<Int>().size).isEqualTo(0)
assertThat(set<Int>().isEmpty()).isTrue()
assertThat(set(1).size).isEqualTo(1)
assertThat(set(1).isEmpty()).isFalse()
assertThat(set(1, 2, 3).size).isEqualTo(3)
assertThat(set(1, 2, 3).isEmpty()).isFalse()
}
@Test fun `should iterate elements`() {
assertThat(set(1, 2, 3).iterator().asSequence().toSet()).isEqualTo(setOf(1, 2, 3))
}
@Test fun `should support variance`() {
val set: ImmutableSet<Int> = set(1, 2, 3)
val setAny: ImmutableSet<Any> = set
assertThat(setAny).isEqualTo(set)
}
}
|
mit
|
fcde7a1a31f78f4552d8feab085c8f14
| 38.622449 | 90 | 0.645377 | 3.701621 | false | true | false | false |
dbrant/apps-android-wikipedia
|
app/src/main/java/org/wikipedia/util/ThrowableUtil.kt
|
1
|
3219
|
package org.wikipedia.util
import android.content.Context
import org.json.JSONException
import org.wikipedia.R
import org.wikipedia.createaccount.CreateAccountException
import org.wikipedia.dataclient.mwapi.MwException
import org.wikipedia.dataclient.okhttp.HttpStatusException
import org.wikipedia.login.LoginClient.LoginFailedException
import java.lang.Exception
import java.net.SocketException
import java.net.SocketTimeoutException
import java.net.UnknownHostException
import java.util.concurrent.TimeoutException
import javax.net.ssl.SSLException
object ThrowableUtil {
// TODO: replace with Apache Commons Lang ExceptionUtils.
@JvmStatic
fun getInnermostThrowable(e: Throwable): Throwable {
var t = e
while (t.cause != null) {
t = t.cause!!
}
return t
}
// TODO: replace with Apache Commons Lang ExceptionUtils.
private fun throwableContainsException(e: Throwable, exClass: Class<*>): Boolean {
var t: Throwable? = e
while (t != null) {
if (exClass.isInstance(t)) {
return true
}
t = t.cause
}
return false
}
@JvmStatic
fun getAppError(context: Context, e: Throwable): AppError {
val inner = getInnermostThrowable(e)
// look at what kind of exception it is...
return if (isNetworkError(e)) {
AppError(context.getString(R.string.error_network_error),
context.getString(R.string.format_error_server_message,
inner.localizedMessage))
} else if (e is HttpStatusException) {
AppError(e.message!!, e.code().toString())
} else if (inner is LoginFailedException || inner is CreateAccountException ||
inner is MwException) {
AppError(inner.localizedMessage!!, "")
} else if (throwableContainsException(e, JSONException::class.java)) {
AppError(context.getString(R.string.error_response_malformed),
inner.localizedMessage)
} else {
// everything else has fallen through, so just treat it as an "unknown" error
AppError(context.getString(R.string.error_unknown),
inner.localizedMessage)
}
}
@JvmStatic
fun isOffline(caught: Throwable?): Boolean {
return caught is UnknownHostException || caught is SocketException
}
@JvmStatic
fun isTimeout(caught: Throwable?): Boolean {
return caught is SocketTimeoutException
}
@JvmStatic
fun is404(caught: Throwable): Boolean {
return caught is HttpStatusException && caught.code() == 404
}
@JvmStatic
fun isEmptyException(caught: Throwable): Boolean {
return caught is EmptyException
}
@JvmStatic
fun isNetworkError(e: Throwable): Boolean {
return throwableContainsException(e, UnknownHostException::class.java) ||
throwableContainsException(e, TimeoutException::class.java) ||
throwableContainsException(e, SSLException::class.java)
}
class EmptyException : Exception()
class AppError(val error: String, val detail: String?)
}
|
apache-2.0
|
eb3fca134ad185501493247c718b0399
| 33.98913 | 89 | 0.656415 | 4.840602 | false | false | false | false |
dahlstrom-g/intellij-community
|
plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/idea/refactoring/inline/FindReferenceInEditorTest.kt
|
6
|
3412
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.inline
import org.jetbrains.kotlin.idea.references.KtSimpleNameReference
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.psi.KtFile
class FindReferenceInEditorTest : KotlinLightCodeInsightFixtureTestCase() {
fun `test function, caret at start`() = doTest(
"""
fun test() {}
fun println(any: Any) {}
fun usage() {
println(<caret>test())
}
""".trimIndent()
)
fun `test function, caret at end`() = doTest(
"""
fun test() {}
fun println(any: Any) {}
fun usage() {
println(test<caret>())
}
""".trimIndent()
)
fun `test function, caret at middle`() = doTest(
"""
fun test() {}
fun println(any: Any) {}
fun usage() {
println(te<caret>st())
}
""".trimIndent()
)
fun `test short function, caret at start`() = doTest(
"""
fun t() {}
fun println(any: Any) {}
fun usage() {
println(<caret>t())
}
""".trimIndent()
)
fun `test short function, caret at end`() = doTest(
"""
fun t() {}
fun println(any: Any) {}
fun usage() {
println(t<caret>())
}
""".trimIndent()
)
fun `test println function`() = doTest(
"""
fun println(any: Any) {}
fun test() {}
fun usage() {
println<caret>(test())
}
""".trimIndent()
)
fun `test property, caret at start`() = doTest(
"""
val name = "name"
fun println(any: Any) {}
fun usage() {
println(<caret>name)
}
""".trimIndent()
)
fun `test property, caret at end`() = doTest(
"""
val name = "name"
fun println(any: Any) {}
fun usage() {
println(name<caret>)
}
""".trimIndent()
)
fun `test property, caret at middle`() = doTest(
"""
val name = "name"
fun println(any: Any) {}
fun usage() {
println(na<caret>me)
}
""".trimIndent()
)
fun `test short property, caret at start`() = doTest(
"""
val v = "name"
fun println(any: Any) {}
fun usage() {
println(<caret>v)
}
""".trimIndent()
)
fun `test short property, caret at end`() = doTest(
"""
val v = "name"
fun println(any: Any) {}
fun usage() {
println(v<caret>)
}
""".trimIndent()
)
private fun doTest(text: String) {
val file = myFixture.configureByText("dummy.kt", text) as KtFile
val reference = myFixture.editor.findSimpleNameReference()
assertInstanceOf(reference, KtSimpleNameReference::class.java)
assertEquals(file.declarations.first(), reference?.resolve())
}
}
|
apache-2.0
|
a89b4c8643fde585464f9be6f1bfb127
| 26.304 | 158 | 0.475381 | 4.74548 | false | true | false | false |
ripdajacker/todoapp-rest-example
|
src/main/kotlin/dk/mehmedbasic/examples/todoapp/TodoEntityCrudController.kt
|
1
|
2294
|
package dk.mehmedbasic.examples.todoapp
import com.j256.ormlite.dao.Dao
import org.codehaus.jackson.map.ObjectMapper
import org.eclipse.jetty.http.HttpStatus
import spark.Request
import spark.Response
import spark.Spark.*
class TodoEntityCrudController {
private val mapper = ObjectMapper()
private val dao: Dao<TodoEntity, Long> = Database.todoDao
init {
path("todos") {
get(":id", this::getById, mapper::writeValueAsString)
get("", this::getAll, mapper::writeValueAsString)
put("", this::create, mapper::writeValueAsString)
post("", this::update, mapper::writeValueAsString)
}
}
fun getById(request: Request, response: Response): Any {
val identifierString = request.params(":id")
if (identifierString == null) {
response.status(HttpStatus.NOT_ACCEPTABLE_406)
return hashMapOf("status" to 406, "message" to "No ID specified.")
}
val result = dao.queryForId(identifierString.trim().toLong())
if (result != null) {
return result
}
return hashMapOf("status" to 404, "message" to "The entity with the specified ID does not exist.")
}
fun getAll(request: Request, response: Response): Any {
return dao.queryForAll()
}
fun update(request: Request, response: Response): Any {
val updatedEntity = mapper.readValue(request.body(), TodoEntity::class.java)
if (dao.queryForId(updatedEntity.id) != null) {
dao.update(updatedEntity)
return hashMapOf("status" to 200, "message" to "Updated entity ${updatedEntity.id}")
}
return hashMapOf("status" to 404, "message" to "The entity with the specified ID does not exist.")
}
fun create(request: Request, response: Response): Any {
val updatedEntity = mapper.readValue(request.body(), TodoEntity::class.java)
updatedEntity.id = null
updatedEntity.creationTs = System.currentTimeMillis()
val status = dao.createOrUpdate(updatedEntity)
if (status.isCreated) {
return hashMapOf("status" to 200, "message" to "Successfully added entity.")
}
return hashMapOf("status" to 501, "message" to "Something went wrong.")
}
}
|
mit
|
8a75a6b665b358647814aab09417642f
| 35.412698 | 106 | 0.645597 | 4.437137 | false | false | false | false |
awsdocs/aws-doc-sdk-examples
|
kotlin/usecases/creating_workflows_stepfunctions/src/main/kotlin/example2/SendMessage.kt
|
1
|
926
|
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package example2
import aws.sdk.kotlin.services.sns.SnsClient
import aws.sdk.kotlin.services.sns.model.PublishRequest
import aws.sdk.kotlin.services.sns.model.SnsException
import kotlin.system.exitProcess
class SendMessage {
suspend fun send(phone: String ) {
val snsClient = SnsClient{ region = "us-east-1" }
try {
val request = PublishRequest {
message = "Hello, please check the database for new ticket assigned to you"
phoneNumber = phone
}
val result = snsClient.publish(request)
println("${result.messageId} message sent.")
} catch (e: SnsException) {
println(e.message)
snsClient.close()
exitProcess(0)
}
}
}
|
apache-2.0
|
180f1c01eed62b60ad06514e613d2dba
| 25.235294 | 91 | 0.603672 | 4.228311 | false | false | false | false |
DreierF/MyTargets
|
shared/src/main/java/de/dreier/mytargets/shared/models/db/Bow.kt
|
1
|
3238
|
/*
* 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.shared.models.db
import androidx.room.ColumnInfo
import androidx.room.Entity
import androidx.room.PrimaryKey
import android.os.Parcelable
import de.dreier.mytargets.shared.models.EBowType
import de.dreier.mytargets.shared.models.IIdSettable
import de.dreier.mytargets.shared.models.Thumbnail
import kotlinx.android.parcel.Parcelize
@Parcelize
@Entity
data class Bow(
@PrimaryKey(autoGenerate = true)
override var id: Long = 0,
var name: String = "",
var type: EBowType? = EBowType.RECURVE_BOW,
var brand: String? = "",
var size: String? = "",
var braceHeight: String? = "",
var tiller: String? = "",
var limbs: String? = "",
var sight: String? = "",
var drawWeight: String? = "",
var stabilizer: String? = "",
var clicker: String? = "",
var button: String? = "",
var string: String? = "",
var nockingPoint: String? = "",
var letoffWeight: String? = "",
var arrowRest: String? = "",
var restHorizontalPosition: String? = "",
var restVerticalPosition: String? = "",
var restStiffness: String? = "",
var camSetting: String? = "",
var scopeMagnification: String? = "",
var description: String? = "",
@ColumnInfo(typeAffinity = ColumnInfo.BLOB)
var thumbnail: Thumbnail? = null
) : IIdSettable, Parcelable {
fun areAllPropertiesSet(): Boolean {
return !size.isNullOrEmpty() &&
!drawWeight.isNullOrEmpty() &&
(!type!!.showLetoffWeight() || !letoffWeight.isNullOrEmpty()) &&
(!type!!.showArrowRest() || !arrowRest.isNullOrEmpty()) &&
(!type!!.showArrowRest() || !restVerticalPosition.isNullOrEmpty()) &&
(!type!!.showArrowRest() || !restHorizontalPosition.isNullOrEmpty()) &&
(!type!!.showArrowRest() || !restStiffness.isNullOrEmpty()) &&
(!type!!.showCamSetting() || !camSetting.isNullOrEmpty()) &&
(!type!!.showTiller() || !tiller.isNullOrEmpty()) &&
(!type!!.showBraceHeight() || !braceHeight.isNullOrEmpty()) &&
(!type!!.showLimbs() || !limbs.isNullOrEmpty()) &&
(!type!!.showSight() || !sight.isNullOrEmpty()) &&
(!type!!.showScopeMagnification() || !scopeMagnification.isNullOrEmpty()) &&
(!type!!.showStabilizer() || !stabilizer.isNullOrEmpty()) &&
(!type!!.showClicker() || !clicker.isNullOrEmpty()) &&
(!type!!.showNockingPoint() || !nockingPoint.isNullOrEmpty()) &&
!string.isNullOrEmpty() &&
(!type!!.showButton() || !button.isNullOrEmpty()) &&
!description.isNullOrEmpty()
}
}
|
gpl-2.0
|
cd7e8ff2f3c624c8c8e04a2ce22f6d6d
| 39.475 | 92 | 0.62168 | 4.23822 | false | false | false | false |
airbnb/epoxy
|
epoxy-processor/src/main/java/com/airbnb/epoxy/processor/Timer.kt
|
1
|
1632
|
package com.airbnb.epoxy.processor
import androidx.room.compiler.processing.XMessager
import javax.tools.Diagnostic
import kotlin.math.pow
import kotlin.math.roundToInt
class Timer(val name: String) {
private val timingSteps = mutableListOf<TimingStep>()
private var startNanos: Long? = null
private var lastTimingNanos: Long? = null
fun start() {
timingSteps.clear()
startNanos = System.nanoTime()
lastTimingNanos = startNanos
}
fun markStepCompleted(stepDescription: String) {
val nowNanos = System.nanoTime()
val lastNanos = lastTimingNanos ?: error("Timer was not started")
lastTimingNanos = nowNanos
timingSteps.add(TimingStep(nowNanos - lastNanos, stepDescription))
}
fun finishAndPrint(messager: XMessager) {
val start = startNanos ?: error("Timer was not started")
val message = buildString {
appendLine("$name finished in ${formatNanos(System.nanoTime() - start)}")
timingSteps.forEach { step ->
appendLine(" - ${step.description} (${formatNanos(step.durationNanos)})")
}
}
messager.printMessage(Diagnostic.Kind.WARNING, message)
}
private class TimingStep(val durationNanos: Long, val description: String)
private fun formatNanos(nanos: Long): String {
val diffMs = nanos.div(1_000_000.0).roundTo(3)
return "$diffMs ms"
}
private fun Double.roundTo(numFractionDigits: Int): Double {
val factor = 10.0.pow(numFractionDigits.toDouble())
return (this * factor).roundToInt() / factor
}
}
|
apache-2.0
|
bf47f9f51965989aa6890170b9234d10
| 31.64 | 89 | 0.662377 | 4.410811 | false | false | false | false |
google-developer-training/basic-android-kotlin-compose-training-reply-app
|
app/src/main/java/com/example/reply/ui/theme/Type.kt
|
2
|
2821
|
/*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.reply.ui.theme
import androidx.compose.material3.Typography
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.sp
// Material 3 typography
val replyTypography = Typography(
headlineLarge = TextStyle(
fontWeight = FontWeight.SemiBold,
fontSize = 32.sp,
lineHeight = 40.sp,
letterSpacing = 0.sp
),
headlineMedium = TextStyle(
fontWeight = FontWeight.SemiBold,
fontSize = 28.sp,
lineHeight = 36.sp,
letterSpacing = 0.sp
),
headlineSmall = TextStyle(
fontWeight = FontWeight.SemiBold,
fontSize = 24.sp,
lineHeight = 32.sp,
letterSpacing = 0.sp
),
titleLarge = TextStyle(
fontWeight = FontWeight.SemiBold,
fontSize = 22.sp,
lineHeight = 28.sp,
letterSpacing = 0.sp
),
titleMedium = TextStyle(
fontWeight = FontWeight.SemiBold,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.15.sp
),
titleSmall = TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.1.sp
),
bodyLarge = TextStyle(
fontWeight = FontWeight.Normal,
fontSize = 16.sp,
lineHeight = 24.sp,
letterSpacing = 0.15.sp
),
bodyMedium = TextStyle(
fontWeight = FontWeight.Medium,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.25.sp
),
bodySmall = TextStyle(
fontWeight = FontWeight.Bold,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = 0.4.sp
),
labelLarge = TextStyle(
fontWeight = FontWeight.SemiBold,
fontSize = 14.sp,
lineHeight = 20.sp,
letterSpacing = 0.1.sp
),
labelMedium = TextStyle(
fontWeight = FontWeight.SemiBold,
fontSize = 12.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
),
labelSmall = TextStyle(
fontWeight = FontWeight.SemiBold,
fontSize = 11.sp,
lineHeight = 16.sp,
letterSpacing = 0.5.sp
)
)
|
apache-2.0
|
11bb802287b66a8828bf254fbe4555ab
| 27.785714 | 75 | 0.622474 | 4.267776 | false | false | false | false |
MewX/Emoticons-with-You
|
Android/app/src/main/java/org/mewx/emo/view/MainActivity.kt
|
1
|
3119
|
package org.mewx.emo.view
import android.os.Bundle
import android.support.design.widget.FloatingActionButton
import android.support.design.widget.Snackbar
import android.view.View
import android.support.design.widget.NavigationView
import android.support.v4.view.GravityCompat
import android.support.v4.widget.DrawerLayout
import android.support.v7.app.ActionBarDrawerToggle
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.Menu
import android.view.MenuItem
import org.mewx.emo.R
class MainActivity : AppCompatActivity(), NavigationView.OnNavigationItemSelectedListener {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val toolbar = findViewById(R.id.toolbar) as Toolbar
setSupportActionBar(toolbar)
val fab = findViewById(R.id.fab) as FloatingActionButton
fab.setOnClickListener { view ->
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
.setAction("Action", null).show()
}
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
val toggle = ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close)
drawer.setDrawerListener(toggle)
toggle.syncState()
val navigationView = findViewById(R.id.nav_view) as NavigationView
navigationView.setNavigationItemSelectedListener(this)
}
override fun onBackPressed() {
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START)
} else {
super.onBackPressed()
}
}
override fun onCreateOptionsMenu(menu: Menu): Boolean {
// Inflate the menu; this adds items to the action bar if it is present.
menuInflater.inflate(R.menu.menu_main, menu)
return true
}
override fun onOptionsItemSelected(item: MenuItem): Boolean {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
val id = item.itemId
if (id == R.id.action_settings) {
return true
}
return super.onOptionsItemSelected(item)
}
override fun onNavigationItemSelected(item: MenuItem): Boolean {
// Handle navigation view item clicks here.
val id = item.itemId
if (id == R.id.nav_camera) {
// Handle the camera action
} else if (id == R.id.nav_gallery) {
} else if (id == R.id.nav_slideshow) {
} else if (id == R.id.nav_manage) {
} else if (id == R.id.nav_share) {
} else if (id == R.id.nav_send) {
}
val drawer = findViewById(R.id.drawer_layout) as DrawerLayout
drawer.closeDrawer(GravityCompat.START)
return true
}
}
|
apache-2.0
|
ee7dcd7b1eae696b0262f4ea6ff07000
| 32.902174 | 105 | 0.672331 | 4.507225 | false | false | false | false |
DemonWav/MinecraftDevIntelliJ
|
src/main/kotlin/com/demonwav/mcdev/platform/mixin/util/MixinMemberReference.kt
|
1
|
2871
|
/*
* Minecraft Dev for IntelliJ
*
* https://minecraftdev.org
*
* Copyright (c) 2020 minecraft-dev
*
* MIT License
*/
package com.demonwav.mcdev.platform.mixin.util
import com.demonwav.mcdev.util.MemberReference
object MixinMemberReference {
fun toString(reference: MemberReference): String {
val builder = StringBuilder()
if (reference.owner != null) {
builder.append('L').append(reference.owner.replace('.', '/')).append(';')
}
builder.append(reference.name)
reference.descriptor?.let { descriptor ->
if (!descriptor.startsWith('(')) {
// Field descriptor
builder.append(':')
}
builder.append(descriptor)
}
return builder.toString()
}
/**
* Parses a [MemberReference] based on the specifications of Mixin's
* MemberInfo.
*/
fun parse(reference: String?): MemberReference? {
reference ?: return null
val owner: String?
var pos = reference.lastIndexOf('.')
if (pos != -1) {
// Everything before the dot is the qualifier/owner
owner = reference.substring(0, pos).replace('/', '.')
} else {
pos = reference.indexOf(';')
if (pos != -1 && reference.startsWith('L')) {
val internalOwner = reference.substring(1, pos)
if (internalOwner.contains('.')) {
// Invalid: Qualifier should only contain slashes
return null
}
owner = internalOwner.replace('/', '.')
} else {
// No owner/qualifier specified
pos = -1
owner = null
}
}
val descriptor: String?
val name: String
val matchAll: Boolean
// Find descriptor separator
val methodDescPos = reference.indexOf('(', pos + 1)
if (methodDescPos != -1) {
// Method descriptor
descriptor = reference.substring(methodDescPos)
name = reference.substring(pos + 1, methodDescPos)
matchAll = false
} else {
val fieldDescPos = reference.indexOf(':', pos + 1)
if (fieldDescPos != -1) {
descriptor = reference.substring(fieldDescPos + 1)
name = reference.substring(pos + 1, fieldDescPos)
matchAll = false
} else {
descriptor = null
matchAll = reference.endsWith('*')
name = if (matchAll) {
reference.substring(pos + 1, reference.lastIndex)
} else {
reference.substring(pos + 1)
}
}
}
return MemberReference(name, descriptor, owner, matchAll)
}
}
|
mit
|
a65a7b345487d75e0f31824ad4724277
| 28.90625 | 85 | 0.518635 | 5.099467 | false | false | false | false |
apache/isis
|
incubator/clients/kroviz/src/main/kotlin/org/apache/causeway/client/kroviz/ui/panel/EventBubbleChart.kt
|
2
|
9933
|
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.apache.causeway.client.kroviz.ui.panel
import io.kvision.chart.*
import io.kvision.chart.js.LegendItem
import io.kvision.core.Color
import io.kvision.core.CssSize
import io.kvision.core.UNIT
import io.kvision.panel.SimplePanel
import io.kvision.utils.obj
import org.apache.causeway.client.kroviz.core.event.LogEntry
import org.apache.causeway.client.kroviz.ui.core.SessionManager
import org.apache.causeway.client.kroviz.ui.dialog.EventLogDetail
import org.apache.causeway.client.kroviz.utils.StringUtils
import kotlin.math.pow
@OptIn(ExperimentalJsExport::class)
@JsExport
fun openLogEntry(i: Int) {
val logEntry = SessionManager.getEventStore().log[i]
EventLogDetail(logEntry).open()
}
class EventBubbleChart : SimplePanel() {
private val model = SessionManager.getEventStore()
private val logStart = model.getLogStartMilliSeconds()
private var chart: Chart
init {
width = CssSize(90, UNIT.vw)
chart = chart(
configuration = buildConfiguration()
)
}
private fun buildConfiguration(): Configuration {
fun buildToolTipList(): List<String> {
val labelList = mutableListOf<String>()
model.log.forEachIndexed { i, it ->
val l = it.buildToolTip(i)
labelList.add(l)
}
return labelList
}
val dataSetsList = listOf(buildDataSets())
return Configuration(
type = ChartType.BUBBLE,
dataSets = dataSetsList,
labels = buildToolTipList(),
options = buildChartOptions(),
)
}
private fun buildChartOptions(): ChartOptions {
fun buildLegend(): LegendOptions {
fun buildLegendLabelList(): Array<LegendItem> {
val legendLabelList = mutableListOf<LegendItem>()
label2color.forEach {
val li = obj {
text = it.key
fillStyle = it.value
}
legendLabelList.add(li as LegendItem)
}
val error = obj {
text = "error"
fillStyle = TRANSPARENT
strokeStyle = ERROR_COLOR
}
legendLabelList.add(error as LegendItem)
val running = obj {
text = "running"
fillStyle = TRANSPARENT
strokeStyle = RUNNING_COLOR
}
legendLabelList.add(running as LegendItem)
val size = obj {
text = "bubble size ^= response bytes"
fillStyle = TRANSPARENT
strokeStyle = TRANSPARENT
}
legendLabelList.add(size as LegendItem)
return legendLabelList.toTypedArray()
}
return LegendOptions(
display = true,
position = Position.RIGHT,
labels = LegendLabelOptions(generateLabels = {
buildLegendLabelList()
}),
title = LegendTitleOptions(text = "Parallel Requests", display = true),
)
}
return ChartOptions(
maintainAspectRatio = true,
plugins = PluginsOptions(
title = TitleOptions(
text = listOf("Request Duration over Time by Request Parallelism and Response Bytes"),
display = true
),
tooltip = TooltipOptions(
callbacks = TooltipCallback(
footer = tooltipCallbackFooterJsFunction()
)
),
legend = buildLegend(),
),
onClick = onClickJsFunction(),
showLine = true,
scales = mapOf(
"x" to ChartScales(
title = ScaleTitleOptions(
text = "Time since Connect(ms)", display = true
)
),
"y" to ChartScales(
title = ScaleTitleOptions(text = "duration in ms (log)", display = true),
type = ScalesType.LOGARITHMIC
)
)
)
}
private fun buildDataSets(): DataSets {
fun buildBgColorList(): List<Color> {
val bgColorList = mutableListOf<Color>()
model.log.forEach {
val c = it.determineBubbleColor()
bgColorList.add(c)
}
return bgColorList
}
fun buildBorderColorList(): List<Color> {
val borderColorList = mutableListOf<Color>()
model.log.forEach {
when {
it.isError() -> borderColorList.add(ERROR_COLOR)
it.isRunning() -> borderColorList.add(RUNNING_COLOR)
else -> borderColorList.add(TRANSPARENT)
}
}
return borderColorList
}
/**
* The term DataSets is severely miss leading:
* 1. a plural form is used (where actually a singular would be more appropriate) -> "a DataSets"
* 2. datasets are used inside datasets, data inside data
*/
fun buildDataSetsList(): List<DataSets> {
val dataSetsList = mutableListOf<DataSets>()
model.log.forEach {
val d = it.buildData()
dataSetsList.add(d)
}
return dataSetsList
}
return DataSets(
backgroundColor = buildBgColorList(),
borderColor = buildBorderColorList(),
data = buildDataSetsList(),
)
}
private fun LogEntry.buildToolTip(index: Int): String {
val size = StringUtils.format(this.responseLength)
val ms = StringUtils.format(this.duration)
val title = StringUtils.shortTitle(this.title)
return title +
"\nseq.no.: $index" +
"\nparallel runs: ${this.runningAtStart}" +
"\nrsp.len.: $size" +
"\nduration: $ms" +
"\ntype: ${this.type}"
}
private fun LogEntry.calculateBubbleSize(): Int {
val i = responseLength
return i.toDouble().pow(1 / 4.toDouble()).toInt()
}
private fun LogEntry.determineBubbleColor(): Color {
val i = runningAtStart
return when {
(i >= 0) && (i <= 4) -> LIGHT_BLUE
(i > 4) && (i <= 8) -> DARK_BLUE
(i > 8) && (i <= 16) -> GREEN
(i > 16) && (i <= 32) -> YELLOW
(i > 32) && (i <= 64) -> RED
(i > 64) && (i <= 128) -> RED_VIOLET
else -> VIOLET
}
}
private fun LogEntry.buildData(): dynamic {
var time = createdAt.getTime()
if (updatedAt != null) {
time = updatedAt!!.getTime()
}
val relativeTimeMs = time - logStart
val bubbleSize = calculateBubbleSize()
val data = obj {
x = relativeTimeMs
y = duration
r = bubbleSize
}
return data
}
companion object {
val TRANSPARENT = Color.rgba(0xFF, 0xFF, 0xFF, 0x00)
val ERROR_COLOR = Color.rgba(0xFF, 0x00, 0x00, 0xFF)
val RUNNING_COLOR = Color.rgba(0xFF, 0xFF, 0x00, 0xFF)
val LIGHT_BLUE = Color.rgba(0x4B, 0xAC, 0xC6, 0x80)
val DARK_BLUE = Color.rgba(0x4F, 0x81, 0xBD, 0x80)
val GREEN = Color.rgba(0x9B, 0xBB, 0x59, 0x80)
val YELLOW = Color.rgba(0xF7, 0x96, 0x46, 0x80)
val RED = Color.rgba(0xC0, 0x50, 0x4D, 0x80)
val RED_VIOLET = Color.rgba(0xA0, 0x5A, 0x78, 0x80)
val VIOLET = Color.rgba(0x80, 0x64, 0xA2, 0x80)
val label2color = mapOf(
"0 .. 4" to LIGHT_BLUE,
"5 .. 8" to DARK_BLUE,
"9 .. 16" to GREEN,
"17 .. 32" to YELLOW,
"33 .. 64" to RED,
"65 .. 128" to RED_VIOLET,
">= 129" to VIOLET
)
fun onClickJsFunction(): dynamic {
return js(
"""function(e) {
var element = e.chart.getElementsAtEventForMode(e, 'nearest', {intersect: true}, true);
if (element.length > 0) {
var i = element[0].index;
kroviz.org.apache.causeway.client.kroviz.ui.panel.openLogEntry(i);
}
}"""
)
}
fun tooltipCallbackFooterJsFunction(): dynamic {
return js(
"""function(context) {
var ctx = context[0];
var chart = ctx.chart;
var ccc = chart.config._config;
var data = ccc.data;
var i = ctx.dataIndex;
return data.labels[i];
}"""
)
}
}
}
|
apache-2.0
|
919494887e44b577f22052472aba7e7c
| 34.475 | 111 | 0.524011 | 4.5711 | false | false | false | false |
JetBrains/intellij-community
|
plugins/gradle/src/org/jetbrains/plugins/gradle/util/GradleImportingUtil.kt
|
1
|
5792
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
@file:JvmName("GradleImportingUtil")
package org.jetbrains.plugins.gradle.util
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskId
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskNotificationListenerAdapter
import com.intellij.openapi.externalSystem.model.task.ExternalSystemTaskType
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemProcessingManager
import com.intellij.openapi.externalSystem.service.internal.ExternalSystemResolveProjectTask
import com.intellij.openapi.externalSystem.service.notification.ExternalSystemProgressNotificationManager
import com.intellij.openapi.externalSystem.service.project.manage.ProjectDataImportListener
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.IntellijInternalApi
import com.intellij.openapi.util.io.FileUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.all
import java.nio.file.Path
import kotlin.io.path.absolutePathString
private fun isResolveTask(id: ExternalSystemTaskId): Boolean {
if (id.type == ExternalSystemTaskType.RESOLVE_PROJECT) {
val task = ApplicationManager.getApplication()
.getService(ExternalSystemProcessingManager::class.java)
.findTask(id)
if (task is ExternalSystemResolveProjectTask) {
return !task.isPreviewMode
}
}
return false
}
@IntellijInternalApi
fun whenResolveTaskStarted(action: () -> Unit, parentDisposable: Disposable) {
ExternalSystemProgressNotificationManager.getInstance()
.addNotificationListener(object : ExternalSystemTaskNotificationListenerAdapter() {
override fun onStart(id: ExternalSystemTaskId, workingDir: String?) {
if (isResolveTask(id)) {
action()
}
}
}, parentDisposable)
}
@IntellijInternalApi
fun getProjectDataLoadPromise(parentDisposable: Disposable): Promise<Project> {
return getResolveTaskFinishPromise(parentDisposable)
.thenAsync { project -> getProjectDataLoadPromise(project, null) }
}
@TestOnly
fun getProjectDataLoadPromise(): Promise<Project> {
return getExternalSystemTaskFinishPromise(::isResolveTask)
.thenAsync { project -> getProjectDataLoadPromise(project, null) }
}
/**
* @param expectedProjects specific linked gradle projects paths to wait for
*/
@TestOnly
fun getProjectDataLoadPromise(expectedProjects: List<Path>): Promise<Project> {
require(expectedProjects.isNotEmpty())
return getExternalSystemTaskFinishPromise(::isResolveTask).thenAsync { project ->
expectedProjects.map {
val linkedProjectPath: String = FileUtil.toCanonicalPath(it.absolutePathString())
getProjectDataLoadPromise(project, linkedProjectPath)
}.all(project, false)
}
}
@TestOnly
fun getExecutionTaskFinishPromise(): Promise<Project> {
return getExternalSystemTaskFinishPromise { it.type == ExternalSystemTaskType.EXECUTE_TASK }
}
private fun getResolveTaskFinishPromise(parentDisposable: Disposable): Promise<Project> {
return getExternalSystemTaskFinishPromise(parentDisposable, ::isResolveTask)
}
private fun getExternalSystemTaskFinishPromise(
parentDisposable: Disposable,
isRelevantTask: (ExternalSystemTaskId) -> Boolean
): Promise<Project> {
val disposable = Disposer.newDisposable(parentDisposable, "")
return getExternalSystemTaskFinishPromiseImpl(disposable, isRelevantTask)
}
private fun getExternalSystemTaskFinishPromise(
isRelevantTask: (ExternalSystemTaskId) -> Boolean
): Promise<Project> {
val disposable = Disposer.newDisposable("")
return getExternalSystemTaskFinishPromiseImpl(disposable, isRelevantTask)
}
private fun getExternalSystemTaskFinishPromiseImpl(
disposable: Disposable,
isRelevantTask: (ExternalSystemTaskId) -> Boolean
): Promise<Project> {
val promise = AsyncPromise<Project>()
ExternalSystemProgressNotificationManager.getInstance()
.addNotificationListener(object : ExternalSystemTaskNotificationListenerAdapter() {
override fun onSuccess(id: ExternalSystemTaskId) {
if (isRelevantTask(id)) {
Disposer.dispose(disposable)
promise.setResult(id.findProject()!!)
}
}
override fun onFailure(id: ExternalSystemTaskId, e: Exception) {
if (isRelevantTask(id)) {
Disposer.dispose(disposable)
promise.setError(e)
}
}
override fun onCancel(id: ExternalSystemTaskId) {
if (isRelevantTask(id)) {
Disposer.dispose(disposable)
promise.cancel()
}
}
}, disposable)
return promise
}
private fun getProjectDataLoadPromise(project: Project, expectedProjectPath: String? = null): Promise<Project> {
val promise = AsyncPromise<Project>()
val parentDisposable = Disposer.newDisposable()
val connection = project.messageBus.connect(parentDisposable)
connection.subscribe(ProjectDataImportListener.TOPIC, object : ProjectDataImportListener {
override fun onFinalTasksFinished(projectPath: String?) {
if (expectedProjectPath == null || expectedProjectPath == projectPath) {
Disposer.dispose(parentDisposable)
promise.setResult(project)
}
}
override fun onImportFailed(projectPath: String?, t: Throwable) {
if (expectedProjectPath == null || expectedProjectPath == projectPath) {
Disposer.dispose(parentDisposable)
promise.setError("Import failed for $projectPath")
}
}
})
return promise
}
|
apache-2.0
|
bc18a49b38308305edf1008a3dd59dfe
| 36.862745 | 120 | 0.773308 | 4.971674 | false | false | false | false |
StepicOrg/stepik-android
|
app/src/main/java/org/stepic/droid/web/storage/model/StorageRecordWrapped.kt
|
2
|
642
|
package org.stepic.droid.web.storage.model
import com.google.gson.Gson
import com.google.gson.JsonElement
import com.google.gson.annotations.SerializedName
import org.stepic.droid.util.toObject
class StorageRecordWrapped(
val id: Long? = null,
val user: Long? = null,
val kind: String,
val data: JsonElement,
@SerializedName("create_date") val createDate: String? = null,
@SerializedName("update_date") val updateDate: String? = null
) {
inline fun <reified T> unwrap(gson: Gson = Gson()) = StorageRecord<T>(
id, user, kind, data.toObject(gson), createDate, updateDate
)
}
|
apache-2.0
|
822ad8f26f587d56439e23cfcb3301f5
| 32.842105 | 74 | 0.682243 | 3.844311 | false | false | false | false |
raybritton/json-query
|
lib/src/main/kotlin/com/raybritton/jsonquery/tools/Where.kt
|
1
|
3004
|
package com.raybritton.jsonquery.tools
import com.raybritton.jsonquery.RuntimeException
import com.raybritton.jsonquery.models.*
/**
* Given a json structure
* Removes parts that do not match query
*/
internal fun Any.where(where: Where, caseSensitive: Boolean, offset: Int?): Any {
return when (this) {
is JsonObject -> this.where(where, caseSensitive, offset)
is JsonArray -> this.where(where, caseSensitive, offset)
else -> throw RuntimeException("Tried to run where on ${this.javaClass}")
}
}
private fun JsonObject.where(where: Where, caseSensitive: Boolean, offset: Int?): JsonObject {
when (where.projection) {
is WhereProjection.Element -> throw RuntimeException("ELEMENT can not be used with an object", RuntimeException.ExtraInfo.ELEMENT_WHERE_OBJECT)
is WhereProjection.Field -> {
if (!where.operator.op(this.navigateToTargetOrProjection(where.projection.value), where.value, caseSensitive)) {
clear()
}
}
is WhereProjection.Math -> {
val field = (where.projection.field as ElementFieldProjection.Field).value
val result = (this.navigateToTargetOrProjection(field) as? JsonArray)?.math(where.projection.expr, ElementFieldProjection.Element, false)
val matches = if (result != null) {
where.operator.op(result, where.value, caseSensitive)
} else {
false
}
if (!matches) {
clear()
}
}
}
return this
}
private fun JsonArray.where(where: Where, caseSensitive: Boolean, offset: Int?): JsonArray {
when (where.projection) {
is WhereProjection.Element -> {
return filterUntilSize(offset) { where.operator.op(it, where.value, caseSensitive) }.toJsonArray()
}
is WhereProjection.Field -> {
return filterUntilSize(offset) { where.operator.op(it.navigateToTargetOrProjection(where.projection.value), where.value, caseSensitive) }.toJsonArray()
}
is WhereProjection.Math -> {
return filterUntilSize(offset) { element ->
val field = (where.projection.field as ElementFieldProjection.Field).value
val result = (element.navigateToTargetOrProjection(field) as? JsonArray)?.math(where.projection.expr, ElementFieldProjection.Element, false)
if (result != null) {
where.operator.op(result, where.value, caseSensitive)
} else {
false
}
}.toJsonArray()
}
}
}
private fun JsonArray.filterUntilSize(size: Int?, predicate: (Any?) -> Boolean): JsonArray {
val output = JsonArray()
val iterator = iterator()
while (iterator.hasNext() && (size == null || (output.size < size))) {
val element = iterator.next()
if (predicate(element)) {
output.add(element)
}
}
return output
}
|
apache-2.0
|
06f02f2859478c2ae9a32f2b119470a5
| 39.608108 | 163 | 0.624168 | 4.56535 | false | false | false | false |
spacecowboy/Feeder
|
app/src/main/java/com/nononsenseapps/feeder/db/room/FeedDao.kt
|
1
|
5763
|
package com.nononsenseapps.feeder.db.room
import android.database.Cursor
import androidx.room.Dao
import androidx.room.Delete
import androidx.room.Insert
import androidx.room.OnConflictStrategy
import androidx.room.Query
import androidx.room.Update
import com.nononsenseapps.feeder.db.COL_CUSTOM_TITLE
import com.nononsenseapps.feeder.db.COL_ID
import com.nononsenseapps.feeder.db.COL_TAG
import com.nononsenseapps.feeder.db.COL_TITLE
import com.nononsenseapps.feeder.model.FeedUnreadCount
import java.net.URL
import kotlinx.coroutines.flow.Flow
import org.threeten.bp.Instant
@Dao
interface FeedDao {
@Insert(onConflict = OnConflictStrategy.REPLACE)
suspend fun insertFeed(feed: Feed): Long
@Update
suspend fun updateFeed(feed: Feed): Int
@Delete
suspend fun deleteFeed(feed: Feed): Int
@Query("DELETE FROM feeds WHERE id IS :feedId")
suspend fun deleteFeedWithId(feedId: Long): Int
@Query(
"""
DELETE FROM feeds WHERE id IN (:ids)
"""
)
suspend fun deleteFeeds(ids: List<Long>): Int
@Query("SELECT * FROM feeds WHERE id IS :feedId")
fun loadFeedFlow(feedId: Long): Flow<Feed?>
@Query("SELECT DISTINCT tag FROM feeds ORDER BY tag COLLATE NOCASE")
suspend fun loadTags(): List<String>
@Query("SELECT DISTINCT tag FROM feeds ORDER BY tag COLLATE NOCASE")
fun loadAllTags(): Flow<List<String>>
@Query("SELECT * FROM feeds WHERE id IS :feedId")
suspend fun loadFeed(feedId: Long): Feed?
@Query(
"""
SELECT * FROM feeds
WHERE id is :feedId
AND last_sync < :staleTime
"""
)
suspend fun loadFeedIfStale(feedId: Long, staleTime: Long): Feed?
@Query("SELECT * FROM feeds WHERE tag IS :tag")
suspend fun loadFeeds(tag: String): List<Feed>
@Query("SELECT * FROM feeds WHERE tag IS :tag AND last_sync < :staleTime")
suspend fun loadFeedsIfStale(tag: String, staleTime: Long): List<Feed>
@Query("SELECT notify FROM feeds WHERE tag IS :tag")
fun loadLiveFeedsNotify(tag: String): Flow<List<Boolean>>
@Query("SELECT notify FROM feeds WHERE id IS :feedId")
fun loadLiveFeedsNotify(feedId: Long): Flow<List<Boolean>>
@Query("SELECT notify FROM feeds")
fun loadLiveFeedsNotify(): Flow<List<Boolean>>
@Query("SELECT * FROM feeds")
suspend fun loadFeeds(): List<Feed>
@Query(
"""
SELECT $COL_ID as id, $COL_TITLE as title
FROM feeds
ORDER BY $COL_TITLE
"""
)
fun loadFeedsForContentProvider(): Cursor
@Query("SELECT * FROM feeds WHERE last_sync < :staleTime")
suspend fun loadFeedsIfStale(staleTime: Long): List<Feed>
@Query("SELECT * FROM feeds WHERE url IS :url")
suspend fun loadFeedWithUrl(url: URL): Feed?
@Query("SELECT id FROM feeds WHERE notify IS 1")
suspend fun loadFeedIdsToNotify(): List<Long>
@Query(
"""
SELECT id, title, url, tag, custom_title, notify, currently_syncing, image_url, unread_count
FROM feeds
LEFT JOIN (SELECT COUNT(1) AS unread_count, feed_id
FROM feed_items
WHERE unread IS 1
GROUP BY feed_id
)
ON feeds.id = feed_id
"""
)
fun loadFlowOfFeedsWithUnreadCounts(): Flow<List<FeedUnreadCount>>
@Query("UPDATE feeds SET notify = :notify WHERE id IS :id")
suspend fun setNotify(id: Long, notify: Boolean)
@Query("UPDATE feeds SET notify = :notify WHERE tag IS :tag")
suspend fun setNotify(tag: String, notify: Boolean)
@Query("UPDATE feeds SET notify = :notify")
suspend fun setAllNotify(notify: Boolean)
@Query("SELECT $COL_ID, $COL_TITLE, $COL_CUSTOM_TITLE FROM feeds WHERE id IS :feedId")
suspend fun getFeedTitle(feedId: Long): FeedTitle?
@Query("SELECT $COL_ID, $COL_TITLE, $COL_CUSTOM_TITLE FROM feeds WHERE id IS :feedId")
fun getFeedTitlesWithId(feedId: Long): Flow<List<FeedTitle>>
@Query(
"""
SELECT $COL_ID, $COL_TITLE, $COL_CUSTOM_TITLE
FROM feeds
WHERE $COL_TAG IS :feedTag
ORDER BY $COL_TITLE COLLATE NOCASE
"""
)
fun getFeedTitlesWithTag(feedTag: String): Flow<List<FeedTitle>>
@Query("SELECT $COL_ID, $COL_TITLE, $COL_CUSTOM_TITLE FROM feeds ORDER BY $COL_TITLE COLLATE NOCASE")
fun getAllFeedTitles(): Flow<List<FeedTitle>>
@Query(
"""
SELECT MAX(last_sync)
FROM feeds
WHERE currently_syncing
"""
)
fun getCurrentlySyncingLatestTimestamp(): Flow<Instant?>
@Query(
"""
UPDATE feeds
SET currently_syncing = :syncing
WHERE id IS :feedId
"""
)
suspend fun setCurrentlySyncingOn(feedId: Long, syncing: Boolean)
@Query(
"""
UPDATE feeds
SET currently_syncing = :syncing, last_sync = :lastSync
WHERE id IS :feedId
"""
)
suspend fun setCurrentlySyncingOn(feedId: Long, syncing: Boolean, lastSync: Instant)
@Query(
"""
SELECT *
FROM feeds
ORDER BY url
"""
)
suspend fun getFeedsOrderedByUrl(): List<Feed>
@Query(
"""
SELECT *
FROM feeds
ORDER BY url
"""
)
fun getFlowOfFeedsOrderedByUrl(): Flow<List<Feed>>
@Query(
"""
DELETE FROM feeds
WHERE url is :url
"""
)
suspend fun deleteFeedWithUrl(url: URL): Int
}
/**
* Inserts or updates feed depending on if ID is valid. Returns ID.
*/
suspend fun FeedDao.upsertFeed(feed: Feed): Long = when (feed.id > ID_UNSET) {
true -> {
updateFeed(feed)
feed.id
}
false -> {
insertFeed(feed)
}
}
|
gpl-3.0
|
b484d40793d1abc04c6452e6a94e2104
| 27.112195 | 105 | 0.632657 | 4.047051 | false | false | false | false |
allotria/intellij-community
|
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/indices/EntityStorageInternalIndex.kt
|
3
|
2632
|
// Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl.indices
import com.intellij.openapi.diagnostic.thisLogger
import com.intellij.workspaceModel.storage.impl.EntityId
import com.intellij.workspaceModel.storage.impl.containers.BidirectionalSetMap
import com.intellij.workspaceModel.storage.impl.containers.copy
import org.jetbrains.annotations.TestOnly
open class EntityStorageInternalIndex<T> private constructor(
internal open val index: BidirectionalSetMap<EntityId, T>,
protected val oneToOneAssociation: Boolean
) {
constructor(oneToOneAssociation: Boolean) : this(BidirectionalSetMap<EntityId, T>(), oneToOneAssociation)
internal fun getIdsByEntry(entry: T): List<EntityId>? = index.getKeysByValue(entry)?.toList()
internal fun getEntryById(id: EntityId): T? = index[id]
internal fun entries(): Collection<T> {
return index.values
}
class MutableEntityStorageInternalIndex<T> private constructor(
// Do not write to [index] directly! Create a method in this index and call [startWrite] before write.
override var index: BidirectionalSetMap<EntityId, T>,
oneToOneAssociation: Boolean
) : EntityStorageInternalIndex<T>(index, oneToOneAssociation) {
private var freezed = true
internal fun index(id: EntityId, entry: T? = null) {
startWrite()
if (entry == null) {
index.remove(id)
return
}
index[id] = entry
if (oneToOneAssociation) {
if (index.getKeysByValue(entry)?.size ?: 0 > 1) {
thisLogger().error("One to one association is violated. Id: $id, Entity: $entry. This id is already associated with ${index.getKeysByValue(entry)}")
}
}
}
@TestOnly
internal fun clear() {
startWrite()
index.clear()
}
@TestOnly
internal fun copyFrom(another: EntityStorageInternalIndex<T>) {
startWrite()
this.index.putAll(another.index)
}
private fun startWrite() {
if (!freezed) return
freezed = false
index = index.copy()
}
fun toImmutable(): EntityStorageInternalIndex<T> {
freezed = true
return EntityStorageInternalIndex(this.index, this.oneToOneAssociation)
}
companion object {
fun <T> from(other: EntityStorageInternalIndex<T>): MutableEntityStorageInternalIndex<T> {
if (other is MutableEntityStorageInternalIndex<T>) other.freezed = true
return MutableEntityStorageInternalIndex(other.index, other.oneToOneAssociation)
}
}
}
}
|
apache-2.0
|
356cce474785ed4fa88c24c640a068f2
| 33.181818 | 158 | 0.711246 | 4.51458 | false | false | false | false |
grover-ws-1/http4k
|
http4k-server-netty/src/main/kotlin/org/http4k/server/Netty.kt
|
1
|
4203
|
package org.http4k.server
import io.netty.bootstrap.ServerBootstrap
import io.netty.buffer.ByteBufInputStream
import io.netty.buffer.Unpooled.wrappedBuffer
import io.netty.channel.ChannelFuture
import io.netty.channel.ChannelHandlerContext
import io.netty.channel.ChannelInitializer
import io.netty.channel.ChannelOption
import io.netty.channel.SimpleChannelInboundHandler
import io.netty.channel.nio.NioEventLoopGroup
import io.netty.channel.socket.SocketChannel
import io.netty.channel.socket.nio.NioServerSocketChannel
import io.netty.handler.codec.DecoderResult.SUCCESS
import io.netty.handler.codec.http.DefaultFullHttpResponse
import io.netty.handler.codec.http.FullHttpRequest
import io.netty.handler.codec.http.HttpObjectAggregator
import io.netty.handler.codec.http.HttpResponseStatus
import io.netty.handler.codec.http.HttpServerCodec
import io.netty.handler.codec.http.HttpVersion.HTTP_1_1
import org.http4k.core.Body
import org.http4k.core.HttpHandler
import org.http4k.core.Method.valueOf
import org.http4k.core.Request
import org.http4k.core.Response
import org.http4k.core.Uri
import org.http4k.core.then
import org.http4k.filter.ServerFilters
import java.io.ByteArrayOutputStream
import java.io.InputStream
import java.nio.ByteBuffer
/**
* Exposed to allow for insertion into a customised Netty server instance
*/
class Http4kChannelHandler(handler: HttpHandler) : SimpleChannelInboundHandler<FullHttpRequest>() {
private val safeHandler = ServerFilters.CatchAll().then(handler)
override fun channelRead0(ctx: ChannelHandlerContext, request: FullHttpRequest): Unit {
try {
if (request.decoderResult() == SUCCESS) {
ctx.writeAndFlush(safeHandler(request.asRequest()).asNettyResponse())
}
} finally {
ctx.close()
}
}
private fun Response.asNettyResponse(): DefaultFullHttpResponse {
val responseBody = wrappedBuffer(body.payload)
val res = DefaultFullHttpResponse(HTTP_1_1, HttpResponseStatus(status.code, status.description), responseBody)
headers.forEach { (key, value) -> res.headers().set(key, value) }
return res
}
private fun InputStream.readAll(estimatedSize: Int = DEFAULT_BUFFER_SIZE): ByteArray {
val buffer = ByteArrayOutputStream(Math.max(estimatedSize, this.available()))
copyTo(buffer)
return buffer.toByteArray()
}
private fun FullHttpRequest.asRequest(): Request =
headers().fold(Request(valueOf(method().name()), Uri.Companion.of(uri()))) {
memo, next ->
memo.header(next.key, next.value)
}.body(Body(ByteBuffer.wrap(ByteBufInputStream(content()).readAll())))
}
data class Netty(val port: Int = 8000) : ServerConfig {
override fun toServer(handler: HttpHandler): Http4kServer {
return object : Http4kServer {
private val masterGroup = NioEventLoopGroup()
private val workerGroup = NioEventLoopGroup()
private var closeFuture: ChannelFuture? = null
override fun start(): Http4kServer {
val bootstrap = ServerBootstrap()
bootstrap.group(masterGroup, workerGroup)
.channel(NioServerSocketChannel::class.java)
.childHandler(object : ChannelInitializer<SocketChannel>() {
public override fun initChannel(ch: SocketChannel) {
ch.pipeline().addLast("codec", HttpServerCodec())
ch.pipeline().addLast("aggregator", HttpObjectAggregator(Int.MAX_VALUE))
ch.pipeline().addLast("handler", Http4kChannelHandler(handler))
}
})
.option(ChannelOption.SO_BACKLOG, 128)
.childOption(ChannelOption.SO_KEEPALIVE, true)
closeFuture = bootstrap.bind(port).sync().channel().closeFuture()
return this
}
override fun stop() {
closeFuture?.cancel(false)
workerGroup.shutdownGracefully()
masterGroup.shutdownGracefully()
}
}
}
}
|
apache-2.0
|
642142ccc8d3615b0f8de64e4a946a87
| 39.413462 | 118 | 0.681418 | 4.659645 | false | false | false | false |
leafclick/intellij-community
|
plugins/stats-collector/src/com/intellij/stats/completion/LookupSelectionTracker.kt
|
1
|
1178
|
// 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.stats.completion
import com.intellij.codeInsight.lookup.LookupEvent
import com.intellij.codeInsight.lookup.LookupListener
import com.intellij.stats.personalization.session.ElementSessionFactorsStorage
import com.intellij.stats.storage.factors.LookupStorage
class LookupSelectionTracker(private val storage: LookupStorage) : LookupListener {
private var currentElementStorage: ElementSessionFactorsStorage? = null
override fun lookupShown(event: LookupEvent) = selectionChanged(event)
override fun currentItemChanged(event: LookupEvent) = selectionChanged(event)
private fun selectionChanged(event: LookupEvent) {
val lookupElement = event.item
if (lookupElement != null) {
val elementStorage = storage.getItemStorage(lookupElement.idString()).sessionFactors
if (elementStorage == currentElementStorage) return
elementStorage.selectionTracker.itemSelected()
currentElementStorage?.selectionTracker?.itemUnselected()
currentElementStorage = elementStorage
}
}
}
|
apache-2.0
|
59d59f8d34dae6244ea394befad03396
| 44.346154 | 140 | 0.801358 | 4.847737 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/coroutines/tryFinallyWithHandleResult.kt
|
2
|
2405
|
// WITH_RUNTIME
// WITH_COROUTINES
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
var globalResult = ""
var wasCalled = false
class Controller {
val postponedActions = mutableListOf<() -> Unit>()
suspend fun suspendWithValue(v: String): String = suspendCoroutineOrReturn { x ->
postponedActions.add {
x.resume(v)
}
COROUTINE_SUSPENDED
}
suspend fun suspendWithException(e: Exception): String = suspendCoroutineOrReturn { x ->
postponedActions.add {
x.resumeWithException(e)
}
COROUTINE_SUSPENDED
}
fun run(c: suspend Controller.() -> String) {
c.startCoroutine(this, handleResultContinuation {
globalResult = it
})
while (postponedActions.isNotEmpty()) {
postponedActions[0]()
postponedActions.removeAt(0)
}
}
}
fun builder(expectException: Boolean = false, c: suspend Controller.() -> String) {
val controller = Controller()
globalResult = "#"
wasCalled = false
if (!expectException) {
controller.run(c)
}
else {
try {
controller.run(c)
globalResult = "fail: exception was not thrown"
} catch (e: Exception) {
globalResult = e.message!!
}
}
if (!wasCalled) {
throw RuntimeException("fail wasCalled")
}
if (globalResult != "OK") {
throw RuntimeException("fail $globalResult")
}
}
fun commonThrow() {
throw RuntimeException("OK")
}
fun box(): String {
builder {
try {
suspendWithValue("OK")
} finally {
if (suspendWithValue("G") != "G") throw RuntimeException("fail 1")
wasCalled = true
}
}
builder(expectException = true) {
try {
suspendWithException(RuntimeException("OK"))
} finally {
if (suspendWithValue("G") != "G") throw RuntimeException("fail 2")
wasCalled = true
}
}
builder(expectException = true) {
try {
suspendWithValue("OK")
commonThrow()
suspendWithValue("OK")
} finally {
if (suspendWithValue("G") != "G") throw RuntimeException("fail 3")
wasCalled = true
}
}
return globalResult
}
|
apache-2.0
|
f2b4ce6d424e687ea9298e49e3a85695
| 23.05 | 92 | 0.567568 | 4.74359 | false | false | false | false |
JuliusKunze/kotlin-native
|
backend.native/tests/external/codegen/box/ranges/contains/inOptimizableFloatRange.kt
|
2
|
1236
|
// TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS
// WITH_RUNTIME
fun check(x: Float, left: Float, right: Float): Boolean {
val result = x in left..right
val manual = x >= left && x <= right
val range = left..right
assert(result == manual) { "Failed: optimized === manual for $range" }
assert(result == checkUnoptimized(x, range)) { "Failed: optimized === unoptimized for $range" }
return result
}
fun checkUnoptimized(x: Float, range: ClosedRange<Float>): Boolean {
return x in range
}
fun box(): String {
assert(check(1.0f, 0.0f, 2.0f))
assert(!check(1.0f, -1.0f, 0.0f))
assert(check(Float.MIN_VALUE, 0.0f, 1.0f))
assert(check(Float.MAX_VALUE, Float.MAX_VALUE - Float.MIN_VALUE, Float.MAX_VALUE))
assert(!check(Float.NaN, Float.NaN, Float.NaN))
assert(!check(0.0f, Float.NaN, Float.NaN))
assert(check(-0.0f, -0.0f, +0.0f))
assert(check(-0.0f, -0.0f, -0.0f))
assert(check(-0.0f, +0.0f, +0.0f))
assert(check(+0.0f, -0.0f, -0.0f))
assert(check(+0.0f, +0.0f, +0.0f))
assert(check(+0.0f, -0.0f, +0.0f))
var value = 0.0f
assert(++value in 1.0f..1.0f)
assert(++value !in 1.0f..1.0f)
return "OK"
}
|
apache-2.0
|
e71bddc60d3fbe131954157bdb44a535
| 30.692308 | 99 | 0.615696 | 2.675325 | false | false | false | false |
smmribeiro/intellij-community
|
platform/vcs-impl/src/com/intellij/openapi/vcs/changes/committed/RepositoryLocationCommittedChangesPanel.kt
|
12
|
3768
|
// 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.openapi.vcs.changes.committed
import com.intellij.openapi.actionSystem.DefaultActionGroup
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.application.runInEdt
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task.Backgroundable
import com.intellij.openapi.project.Project
import com.intellij.openapi.ui.Messages.showErrorDialog
import com.intellij.openapi.vcs.CommittedChangesProvider
import com.intellij.openapi.vcs.RepositoryLocation
import com.intellij.openapi.vcs.VcsBundle
import com.intellij.openapi.vcs.VcsDataKeys.REMOTE_HISTORY_CHANGED_LISTENER
import com.intellij.openapi.vcs.VcsDataKeys.REMOTE_HISTORY_LOCATION
import com.intellij.openapi.vcs.VcsException
import com.intellij.openapi.vcs.versionBrowser.ChangeBrowserSettings
import com.intellij.openapi.vcs.versionBrowser.CommittedChangeList
import com.intellij.util.AsynchConsumer
import com.intellij.util.BufferedListConsumer
import com.intellij.util.Consumer
private val LOG = logger<RepositoryLocationCommittedChangesPanel<*>>()
internal class RepositoryLocationCommittedChangesPanel<S : ChangeBrowserSettings>(
project: Project,
val provider: CommittedChangesProvider<*, S>,
val repositoryLocation: RepositoryLocation,
extraActions: DefaultActionGroup
) : CommittedChangesPanel(project) {
@Volatile
private var isDisposed = false
var maxCount: Int = 0
var settings: S = provider.createDefaultSettings()
var isLoading: Boolean = false
private set
init {
setup(extraActions, provider.createActions(browser, repositoryLocation))
}
override fun refreshChanges() = LoadCommittedChangesTask().queue()
override fun getData(dataId: String): Any? =
when {
REMOTE_HISTORY_CHANGED_LISTENER.`is`(dataId) -> Consumer<String> { refreshChanges() }
REMOTE_HISTORY_LOCATION.`is`(dataId) -> repositoryLocation
else -> super.getData(dataId)
}
override fun dispose() {
isDisposed = true
}
private inner class LoadCommittedChangesTask : Backgroundable(project, VcsBundle.message("changes.title.loading.changes"), true) {
private var error: VcsException? = null
init {
browser.reset()
isLoading = true
browser.setLoading(true)
}
override fun run(indicator: ProgressIndicator) =
try {
val appender = { changeLists: List<CommittedChangeList> ->
runInEdt(ModalityState.stateForComponent(browser)) {
if (project.isDisposed) return@runInEdt
browser.append(changeLists)
}
}
val bufferedAppender = BufferedListConsumer(30, appender, -1)
provider.loadCommittedChanges(settings, repositoryLocation, maxCount, object : AsynchConsumer<CommittedChangeList> {
override fun consume(changeList: CommittedChangeList) {
if (isDisposed) indicator.cancel()
ProgressManager.checkCanceled()
bufferedAppender.consumeOne(changeList)
}
override fun finished() = bufferedAppender.flush()
})
}
catch (e: VcsException) {
LOG.info(e)
error = e
}
override fun onSuccess() {
error?.let {
showErrorDialog(myProject, VcsBundle.message("changes.error.refreshing.view", it.messages.joinToString("\n")),
VcsBundle.message("changes.committed.changes"))
}
}
override fun onFinished() {
isLoading = false
browser.setLoading(false)
}
}
}
|
apache-2.0
|
a2426227c127222ebe73988acda46b48
| 33.577982 | 140 | 0.735403 | 4.669145 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/kotlin/performance-tests/test/org/jetbrains/kotlin/idea/testFramework/ProjectBuilder.kt
|
1
|
16724
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.testFramework
import com.intellij.ide.highlighter.ModuleFileType
import com.intellij.jarRepository.JarRepositoryManager
import com.intellij.jarRepository.RepositoryLibraryType.REPOSITORY_LIBRARY_KIND
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleTypeId
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.JavaSdk
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.impl.JavaAwareProjectJdkTableImpl
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.impl.libraries.LibraryEx
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.testFramework.PlatformTestUtil
import com.intellij.testFramework.PsiTestUtil
import com.intellij.util.io.*
import org.jetbrains.idea.maven.utils.library.RepositoryLibraryProperties
import org.jetbrains.kotlin.idea.artifacts.KotlinArtifacts
import org.jetbrains.kotlin.idea.perf.util.ProfileTools.Companion.initDefaultProfile
import org.jetbrains.kotlin.idea.test.ConfigLibraryUtil
import org.jetbrains.kotlin.idea.test.addRoot
import org.jetbrains.kotlin.idea.util.application.runWriteAction
import org.jetbrains.kotlin.test.KotlinRoot
import org.jetbrains.kotlin.utils.addToStdlib.cast
import java.io.File
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
abstract class AbstractSource {
protected val body = StringBuilder()
protected open fun newLineAfterCodeBlock(): Boolean = true
protected open fun intendLevel(): Int = 0
private fun intendPrefix() = " ".repeat(2 * intendLevel())
fun body(code: Any) {
this.body.append(code.toString().prependIndent(intendPrefix()))
if (newLineAfterCodeBlock()) this.body.append('\n')
}
override fun toString(): String = body.toString()
}
abstract class AbstractClassSource(val name: String) : AbstractSource() {
override fun intendLevel(): Int = 1
fun function(name: String, funSource: FunSource.() -> Unit) {
super.body(FunSource(name).apply(funSource))
}
}
class CompanionObjectSource : AbstractClassSource("") {
override fun toString(): String = "companion object {\n$body}"
}
enum class Visibility {
PUBLIC,
PRIVATE,
INTERNAL
}
data class Parameter(
val name: String,
val type: String,
val mutable: Boolean = false,
val visibility: Visibility = Visibility.PUBLIC,
val defaultValueExpression: String? = null,
) {
override fun toString(): String {
val visibilityString = if (visibility == Visibility.PUBLIC) "" else visibility.name.lowercase() + " "
val valueExpression = defaultValueExpression?.let { " = $it" } ?: ""
return "$visibilityString${if (mutable) "var" else "val"} $name: $type$valueExpression"
}
}
class ClassSource(name: String, private val topLevel: Boolean = true) : AbstractClassSource(name) {
private var dataClass: Boolean = false
private var openClass: Boolean = false
private val ctorParameters = mutableListOf<Parameter>()
private var superClass: String? = null
private val interfaces = mutableListOf<String>()
fun superClass(superClass: String) {
check(this.superClass == null) { "super class is already specified for $name: ${this.superClass}" }
this.superClass = superClass
}
fun interfaces(iface: String) {
interfaces.add(iface)
}
fun openClass() {
openClass(true)
}
private fun openClass(openClass: Boolean) {
this.openClass = openClass
}
fun dataClass() {
dataClass(true)
}
private fun dataClass(dataClass: Boolean) {
this.dataClass = dataClass
}
fun ctorParameter(parameter: Parameter) {
ctorParameters.add(parameter)
}
fun companionObject(companionObjectSource: CompanionObjectSource.() -> Unit) {
check(topLevel) { "companion object is allowed only in top-level classes, wrong class: $name" }
val source = CompanionObjectSource().apply(companionObjectSource)
super.body(source)
}
private fun classModifier(): String {
val open = if (!openClass) "" else "open "
val data = if (!dataClass) "" else "data "
return open + data
}
private fun superAndInterfaces(): String {
val superStr = if (superClass != null) {
": $superClass()"
} else ""
return if (interfaces.isEmpty()) superStr
else {
val interfacesStr = interfaces.joinToString()
if (superStr.isEmpty()) ": $interfacesStr" else "$superStr, $interfacesStr"
}
}
private fun constructorParameters(): String = if (ctorParameters.isEmpty()) {
""
} else {
"(" + ctorParameters.joinToString(", ") + ")"
}
override fun toString(): String = "${classModifier()}class $name ${constructorParameters()} ${superAndInterfaces()} {\n$body}"
}
class FunSource(val name: String) : AbstractSource() {
private val params = mutableMapOf<String, String>()
private var openFunction: Boolean = false
private var returnType: String? = null
override fun intendLevel(): Int = 1
fun openFunction() {
this.openFunction = true
}
fun param(name: String, type: String) {
this.params[name] = type
}
fun returnType(returnType: String) {
this.returnType = returnType
}
private fun modifiers(): String {
val s = if (openFunction) "open" else ""
return if (s.isEmpty()) s else "$s "
}
private fun retType(): String {
returnType ?: return ""
return ": $returnType "
}
override fun toString(): String =
"${modifiers()}fun $name(${params.map { it.key + ": " + it.value }.joinToString()}) ${retType()}{\n$body}"
}
class ModuleDescription(val moduleName: String) {
private val modules = mutableListOf<ModuleDescription>()
private val libraries = mutableListOf<LibraryDescription>()
private val kotlinFiles = mutableListOf<Pair<String, KotlinFileSource>>()
private lateinit var modulePath: Path
private var src: String = "src"
private var jdk: Sdk? = null
fun module(moduleName: String, moduleDescription: ModuleDescription.() -> Unit) {
val description = ModuleDescription(moduleName).apply(moduleDescription)
modules.add(description)
}
fun jdk(jdk: Sdk) {
this.jdk = jdk
}
fun src(path: String) {
src = path
}
internal fun setUpJdk(jdk: Sdk) {
if (this.jdk != null) return
this.jdk = jdk
modules.forEach {
it.setUpJdk(jdk)
}
}
fun library(name: String, mavenArtefact: String) {
libraries.add(MavenLibraryDescription(name, mavenArtefact))
}
fun kotlinStandardLibrary() {
libraries.add(SpecialLibraryDescription("Kotlin Runtime", SpecialLibraryDescription.SpecialLibrary.KOTLIN_STDLIB))
}
fun kotlinFile(name: String, kotlinFileSource: KotlinFileSource.() -> Unit) {
val source = KotlinFileSource().apply(kotlinFileSource)
kotlinFiles.add(Pair(name, source))
}
internal fun generateFiles(path: Path) {
modulePath = path
path.createDirectories()
for (module in modules) {
val srcDir = path.resolve(module.moduleName)
module.generateFiles(srcDir)
}
val srcDir = path.resolve(src)
srcDir.createDirectories()
kotlinFiles.forEach { (name, source) ->
val packageDir = source.pkg?.let { pkg ->
val pkgPath = srcDir.resolve(pkg.replace('.', '/'))
pkgPath.createDirectories()
pkgPath
} ?: srcDir
packageDir.resolve("$name.kt").toFile().writeText(source.toString())
}
}
fun createModule(project: Project) {
val moduleVirtualFile = LocalFileSystem.getInstance().refreshAndFindFileByNioFile(modulePath) ?: error("unable to find ${modulePath}")
runWriteAction {
val moduleManager = ModuleManager.getInstance(project)
val module = with(moduleManager.modifiableModel) {
val imlPath = modulePath.resolve("$moduleName${ModuleFileType.DOT_DEFAULT_EXTENSION}")
val module = newModule(imlPath, ModuleTypeId.JAVA_MODULE)
PsiTestUtil.addSourceRoot(module, moduleVirtualFile.findFileByRelativePath(src) ?: error("no '$src' in $this"))
commit()
module
}
ConfigLibraryUtil.configureSdk(module, jdk ?: error("jdk is not specified for $this"))
for (library in libraries) {
library.addToModule(project, module)
}
}
}
override fun toString(): String = "module '${moduleName}'"
}
abstract class LibraryDescription(val name: String, val scope: DependencyScope = DependencyScope.COMPILE) {
abstract fun addToModule(project: Project, module: Module)
}
class MavenLibraryDescription(name: String, val mavenArtefact: String, scope: DependencyScope = DependencyScope.COMPILE): LibraryDescription(name, scope) {
override fun addToModule(project: Project, module: Module) {
val (libraryGroupId, libraryArtifactId, version) = mavenArtefact.split(":").also {
assert(it.size == 3) { "mavenArtefact is expected to be 'groupId:artifactId:version', actual is '$mavenArtefact'" }
}
val libraryProperties = RepositoryLibraryProperties(libraryGroupId, libraryArtifactId, version, true, emptyList())
val orderRoots = JarRepositoryManager.loadDependenciesModal(project, libraryProperties, false, false, null, null)
ConfigLibraryUtil.addLibrary(module, name, kind = REPOSITORY_LIBRARY_KIND) {
val modifiableLibrary = cast<LibraryEx.ModifiableModelEx>()
val realLibraryProperties = modifiableLibrary.properties.cast<RepositoryLibraryProperties>()
realLibraryProperties.mavenId = libraryProperties.mavenId
modifiableLibrary.properties = realLibraryProperties
for (orderRoot in orderRoots) {
addRoot(orderRoot.file, orderRoot.type)
}
}
}
override fun toString(): String {
return "Maven library '$mavenArtefact'"
}
}
class SpecialLibraryDescription(name: String, private val library: SpecialLibrary, scope: DependencyScope = DependencyScope.COMPILE): LibraryDescription(name, scope) {
override fun addToModule(project: Project, module: Module) {
when(library) {
SpecialLibrary.KOTLIN_STDLIB ->
ConfigLibraryUtil.addLibrary(module, name) {
addRoot(KotlinArtifacts.instance.kotlinStdlib, OrderRootType.CLASSES)
}
}
}
enum class SpecialLibrary {
KOTLIN_STDLIB
}
}
class KotlinFileSource : AbstractSource() {
internal var pkg: String? = null
fun pkg(pkg: String) {
check(this.pkg == null) { "package directive is already specified: ${this.pkg}" }
this.pkg = pkg
super.body("package $pkg\n")
}
fun import(fqName: String) {
super.body("import $fqName\n")
}
fun importStar(pkgName: String) {
super.body("import $pkgName.*\n")
}
fun topClass(name: String, clsSource: ClassSource.() -> Unit) {
super.body(ClassSource(name).apply(clsSource))
}
fun topFunction(name: String, funSource: FunSource.() -> Unit) {
super.body(FunSource(name).apply(funSource))
}
}
class ProjectBuilder {
internal lateinit var name: String
internal var initDefaultProfile: Boolean = true
private var buildGradleKts: String? = null
private val modules = mutableListOf<ModuleDescription>()
fun module(moduleName: String = ProjectOpenAction.SIMPLE_JAVA_MODULE.name, moduleDescription: ModuleDescription.() -> Unit) {
val description = ModuleDescription(moduleName).apply(moduleDescription)
modules.add(description)
}
fun name(name: String) {
this.name = name
}
fun initDefaultProfile() {
this.initDefaultProfile = true
}
fun initDefaultProfile(initDefaultProfile: Boolean) {
this.initDefaultProfile = initDefaultProfile
}
fun buildGradleKtsTemplate(buildGradle: File) {
val target = if (buildGradle.exists()) buildGradle else KotlinRoot.DIR.resolve(buildGradle)
this.buildGradleKts = target.absolutePath
}
private fun setUpJdk(jdk: Sdk) {
modules.forEach {
it.setUpJdk(jdk)
}
}
private fun generateFiles(): Path {
val projectPath = Files.createTempDirectory(name)!!
Runtime.getRuntime().addShutdownHook(Thread {
projectPath.delete(true)
})
val buildGradleKtsPath = buildGradleKts?.let { Paths.get(it) }
buildGradleKtsPath?.let { buildGradlePath ->
when {
buildGradlePath.isFile() -> buildGradlePath.copy(projectPath)
buildGradlePath.isDirectory() -> {
val buildGradleFile = listOf("build.gradle.kts", "build.gradle").map { buildGradlePath.resolve(it) }
.firstOrNull { it.exists() }
?: error("neither build.gradle.kts nor build.gradle found at $buildGradlePath")
buildGradleFile.copy(projectPath.resolve(buildGradleFile.fileName))
}
else -> error("illegal type of build gradle path: $buildGradlePath")
}
}
if (buildGradleKtsPath != null) {
val module = modules.singleOrNull() ?: error("Gradle model supports only a single module")
module.generateFiles(projectPath.resolve("src/main/java"))
} else {
when(modules.size) {
1 -> {
modules[0].generateFiles(projectPath)
}
else -> {
for (module in modules) {
val moduleDir = projectPath.resolve(module.moduleName)
module.generateFiles(moduleDir)
}
}
}
}
return projectPath
}
private fun createModules(project: Project) {
if (buildGradleKts != null) return
for (module in modules) {
module.createModule(project)
}
}
fun openProjectOperation(): OpenProjectOperation {
val builder = this
val jdkTableImpl = JavaAwareProjectJdkTableImpl.getInstanceEx()
val homePath = if (jdkTableImpl.internalJdk.homeDirectory!!.name == "jre") {
jdkTableImpl.internalJdk.homeDirectory!!.parent.path
} else {
jdkTableImpl.internalJdk.homePath!!
}
val javaSdk = JavaSdk.getInstance()
val jdk18 = javaSdk.createJdk("1.8", homePath)
setUpJdk(jdk18)
val projectPath = generateFiles()
val openAction =
when {
buildGradleKts != null -> ProjectOpenAction.GRADLE_PROJECT
modules.size == 1 -> ProjectOpenAction.SIMPLE_JAVA_MODULE
modules.size > 1 -> ProjectOpenAction.EXISTING_IDEA_PROJECT
else -> error("at least one module has to be specified")
}
val openProject = OpenProject(
projectPath = projectPath.toRealPath().toString(),
projectName = name,
jdk = jdk18,
projectOpenAction = openAction
)
return object : OpenProjectOperation {
override fun openProject() = ProjectOpenAction.openProject(openProject)
override fun postOpenProject(project: Project) {
createModules(project)
openAction.postOpenProject(project = project, openProject = openProject)
if (builder.initDefaultProfile) {
project.initDefaultProfile()
}
PlatformTestUtil.saveProject(project, true)
}
}
}
}
interface OpenProjectOperation {
fun openProject(): Project
fun postOpenProject(project: Project)
}
fun openProject(initializer: ProjectBuilder.() -> Unit): Project {
val projectBuilder = ProjectBuilder().apply(initializer)
val openProject = projectBuilder.openProjectOperation()
return openProject.openProject().also {
openProject.postOpenProject(it)
}
}
|
apache-2.0
|
9674c0712681d321a823dfa5ff929bb4
| 33.342916 | 167 | 0.648948 | 4.751136 | false | false | false | false |
smmribeiro/intellij-community
|
plugins/git4idea/src/git4idea/GitBranchesUsageCollector.kt
|
1
|
1959
|
// 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.
// 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 git4idea
import com.intellij.internal.statistic.IdeActivityDefinition
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.BooleanEventField
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventId
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
class GitBranchesUsageCollector : CounterUsagesCollector() {
override fun getGroup(): EventLogGroup = GROUP
companion object {
private const val VERSION = 1
private val GROUP: EventLogGroup = EventLogGroup("git.branches", VERSION)
private val POPUP_CLICKED: EventId = GROUP.registerEvent("popup_widget_clicked")
@JvmField
val IS_BRANCH_PROTECTED: BooleanEventField = EventFields.Boolean("is_protected")
@JvmField
val IS_NEW_BRANCH: BooleanEventField = EventFields.Boolean("is_new")
@JvmField
val FINISHED_SUCCESSFULLY: BooleanEventField = EventFields.Boolean("successfully")
@JvmField
val CHECKOUT_ACTIVITY: IdeActivityDefinition = GROUP.registerIdeActivity(
"checkout",
startEventAdditionalFields = arrayOf(IS_BRANCH_PROTECTED, IS_NEW_BRANCH),
finishEventAdditionalFields = arrayOf(FINISHED_SUCCESSFULLY)
)
@JvmField
val CHECKOUT_OPERATION = GROUP.registerIdeActivity("checkout_operation", parentActivity = CHECKOUT_ACTIVITY)
@JvmField
val VFS_REFRESH = GROUP.registerIdeActivity("vfs_refresh", parentActivity = CHECKOUT_ACTIVITY)
@JvmStatic
fun branchWidgetClicked() {
POPUP_CLICKED.log()
}
}
}
|
apache-2.0
|
e3e20d1779525fab1c78ad5f403bd752
| 39.833333 | 158 | 0.773864 | 4.789731 | false | false | false | false |
smmribeiro/intellij-community
|
platform/credential-store/src/kdbx/KdbxHeader.kt
|
12
|
12084
|
/*
* Copyright 2015 Jo Rabin
*
* 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.credentialStore.kdbx
import com.google.common.io.LittleEndianDataInputStream
import com.google.common.io.LittleEndianDataOutputStream
import com.intellij.credentialStore.generateBytes
import com.intellij.util.ArrayUtilRt
import com.intellij.util.io.DigestUtil
import org.bouncycastle.crypto.engines.AESEngine
import org.bouncycastle.crypto.io.CipherInputStream
import org.bouncycastle.crypto.io.CipherOutputStream
import org.bouncycastle.crypto.modes.CBCBlockCipher
import org.bouncycastle.crypto.paddings.PaddedBufferedBlockCipher
import org.bouncycastle.crypto.params.KeyParameter
import org.bouncycastle.crypto.params.ParametersWithIV
import java.io.InputStream
import java.io.OutputStream
import java.nio.ByteBuffer
import java.security.DigestInputStream
import java.security.DigestOutputStream
import java.security.SecureRandom
import java.util.*
import java.util.zip.GZIPOutputStream
/**
* This class represents the header portion of a KeePass KDBX file or stream. The header is received in
* plain text and describes the encryption and compression of the remainder of the file.
* It is a factory for encryption and decryption streams and contains a hash of its own serialization.
* While KDBX streams are Little-Endian, data is passed to and from this class in standard Java byte order.
* @author jo
* This UUID denotes that AES Cipher is in use. No other values are known.
*/
private val AES_CIPHER = UUID.fromString("31C1F2E6-BF71-4350-BE58-05216AFC5AFF")
private const val FILE_VERSION_CRITICAL_MASK = 0xFFFF0000.toInt()
private const val SIG1 = 0x9AA2D903.toInt()
private const val SIG2 = 0xB54BFB67.toInt()
private const val FILE_VERSION_32 = 0x00030001
internal fun createProtectedStreamKey(random: SecureRandom) = random.generateBytes(32)
private object HeaderType {
const val END: Byte = 0
const val COMMENT: Byte = 1
const val CIPHER_ID: Byte = 2
const val COMPRESSION_FLAGS: Byte = 3
const val MASTER_SEED: Byte = 4
const val TRANSFORM_SEED: Byte = 5
const val TRANSFORM_ROUNDS: Byte = 6
const val ENCRYPTION_IV: Byte = 7
const val PROTECTED_STREAM_KEY: Byte = 8
const val STREAM_START_BYTES: Byte = 9
const val INNER_RANDOM_STREAM_ID: Byte = 10
}
private fun readSignature(input: LittleEndianDataInputStream): Boolean {
return input.readInt() == SIG1 && input.readInt() == SIG2
}
private fun verifyFileVersion(input: LittleEndianDataInputStream): Boolean {
return input.readInt() and FILE_VERSION_CRITICAL_MASK <= FILE_VERSION_32 and FILE_VERSION_CRITICAL_MASK
}
internal class KdbxHeader() {
constructor(inputStream: InputStream) : this() {
readKdbxHeader(inputStream)
}
constructor(random: SecureRandom) : this() {
masterSeed = random.generateBytes(32)
transformSeed = random.generateBytes(32)
encryptionIv = random.generateBytes(16)
protectedStreamKey = createProtectedStreamKey(random)
}
/**
* The ordinal 0 represents uncompressed and 1 GZip compressed
*/
enum class CompressionFlags {
NONE, GZIP
}
/**
* The ordinals represent various types of encryption that may be applied to fields within the unencrypted data
*/
enum class ProtectedStreamAlgorithm {
NONE, ARC_FOUR, SALSA_20
}
// the cipher in use
private var cipherUuid = AES_CIPHER
/* whether the data is compressed */
var compressionFlags = CompressionFlags.GZIP
private set
private var masterSeed: ByteArray = ArrayUtilRt.EMPTY_BYTE_ARRAY
private var transformSeed: ByteArray = ArrayUtilRt.EMPTY_BYTE_ARRAY
private var transformRounds: Long = 6000
private var encryptionIv: ByteArray = ArrayUtilRt.EMPTY_BYTE_ARRAY
var protectedStreamKey: ByteArray = ArrayUtilRt.EMPTY_BYTE_ARRAY
private set
private var protectedStreamAlgorithm = ProtectedStreamAlgorithm.SALSA_20
/* these bytes appear in cipher text immediately following the header */
var streamStartBytes = ByteArray(32)
private set
/* not transmitted as part of the header, used in the XML payload, so calculated
* on transmission or receipt */
var headerHash: ByteArray? = null
/**
* Create a decrypted input stream using supplied digest and this header
* apply decryption to the passed encrypted input stream
*/
fun createDecryptedStream(digest: ByteArray, inputStream: InputStream): InputStream {
val finalKeyDigest = getFinalKeyDigest(digest, masterSeed, transformSeed, transformRounds)
return getDecryptedInputStream(inputStream, finalKeyDigest, encryptionIv)
}
/**
* Create an unencrypted output stream using the supplied digest and this header
* and use the supplied output stream to write encrypted data.
*/
fun createEncryptedStream(digest: ByteArray, outputStream: OutputStream): OutputStream {
val finalKeyDigest = getFinalKeyDigest(digest, masterSeed, transformSeed, transformRounds)
var out = getEncryptedOutputStream(outputStream, finalKeyDigest, encryptionIv)
out.write(streamStartBytes)
out = HashedBlockOutputStream(out)
return when (compressionFlags) {
CompressionFlags.GZIP -> GZIPOutputStream(out, HashedBlockOutputStream.BLOCK_SIZE)
else -> out
}
}
private fun setCipherUuid(uuid: ByteArray) {
val b = ByteBuffer.wrap(uuid)
val incoming = UUID(b.long, b.getLong(8))
if (incoming != AES_CIPHER) {
throw IllegalStateException("Unknown Cipher UUID $incoming")
}
cipherUuid = incoming
}
/**
* Populate a KdbxHeader from the input stream supplied
*/
private fun readKdbxHeader(inputStream: InputStream) {
val digest = DigestUtil.sha256()
// we do not close this stream, otherwise we lose our place in the underlying stream
val digestInputStream = DigestInputStream(inputStream, digest)
// we do not close this stream, otherwise we lose our place in the underlying stream
val input = LittleEndianDataInputStream(digestInputStream)
if (!readSignature(input)) {
throw KdbxException("Bad signature")
}
if (!verifyFileVersion(input)) {
throw IllegalStateException("File version did not match")
}
while (true) {
val headerType = input.readByte()
if (headerType == HeaderType.END) {
break
}
when (headerType) {
HeaderType.COMMENT -> readHeaderData(input)
HeaderType.CIPHER_ID -> setCipherUuid(readHeaderData(input))
HeaderType.COMPRESSION_FLAGS -> {
compressionFlags = CompressionFlags.values()[readIntHeaderData(input)]
}
HeaderType.MASTER_SEED -> masterSeed = readHeaderData(input)
HeaderType.TRANSFORM_SEED -> transformSeed = readHeaderData(input)
HeaderType.TRANSFORM_ROUNDS -> transformRounds = readLongHeaderData(input)
HeaderType.ENCRYPTION_IV -> encryptionIv = readHeaderData(input)
HeaderType.PROTECTED_STREAM_KEY -> protectedStreamKey = readHeaderData(input)
HeaderType.STREAM_START_BYTES -> streamStartBytes = readHeaderData(input)
HeaderType.INNER_RANDOM_STREAM_ID -> {
protectedStreamAlgorithm = ProtectedStreamAlgorithm.values()[readIntHeaderData(input)]
}
else -> throw IllegalStateException("Unknown File Header")
}
}
// consume length etc. following END flag
readHeaderData(input)
headerHash = digest.digest()
}
/**
* Write a KdbxHeader to the output stream supplied. The header is updated with the
* message digest of the written stream.
*/
fun writeKdbxHeader(outputStream: OutputStream) {
val messageDigest = DigestUtil.sha256()
val digestOutputStream = DigestOutputStream(outputStream, messageDigest)
val output = LittleEndianDataOutputStream(digestOutputStream)
// write the magic number
output.writeInt(SIG1)
output.writeInt(SIG2)
// write a file version
output.writeInt(FILE_VERSION_32)
output.writeByte(HeaderType.CIPHER_ID.toInt())
output.writeShort(16)
val b = ByteArray(16)
val bb = ByteBuffer.wrap(b)
bb.putLong(cipherUuid.mostSignificantBits)
bb.putLong(8, cipherUuid.leastSignificantBits)
output.write(b)
output.writeByte(HeaderType.COMPRESSION_FLAGS.toInt())
output.writeShort(4)
output.writeInt(compressionFlags.ordinal)
output.writeByte(HeaderType.MASTER_SEED.toInt())
output.writeShort(masterSeed.size)
output.write(masterSeed)
output.writeByte(HeaderType.TRANSFORM_SEED.toInt())
output.writeShort(transformSeed.size)
output.write(transformSeed)
output.writeByte(HeaderType.TRANSFORM_ROUNDS.toInt())
output.writeShort(8)
output.writeLong(transformRounds)
output.writeByte(HeaderType.ENCRYPTION_IV.toInt())
output.writeShort(encryptionIv.size)
output.write(encryptionIv)
output.writeByte(HeaderType.PROTECTED_STREAM_KEY.toInt())
output.writeShort(protectedStreamKey.size)
output.write(protectedStreamKey)
output.writeByte(HeaderType.STREAM_START_BYTES.toInt())
output.writeShort(streamStartBytes.size)
output.write(streamStartBytes)
output.writeByte(HeaderType.INNER_RANDOM_STREAM_ID.toInt())
output.writeShort(4)
output.writeInt(protectedStreamAlgorithm.ordinal)
output.writeByte(HeaderType.END.toInt())
output.writeShort(0)
headerHash = digestOutputStream.messageDigest.digest()
}
}
private fun getFinalKeyDigest(key: ByteArray, masterSeed: ByteArray, transformSeed: ByteArray, transformRounds: Long): ByteArray {
val engine = AESEngine()
engine.init(true, KeyParameter(transformSeed))
// copy input key
val transformedKey = ByteArray(key.size)
System.arraycopy(key, 0, transformedKey, 0, transformedKey.size)
// transform rounds times
for (rounds in 0 until transformRounds) {
engine.processBlock(transformedKey, 0, transformedKey, 0)
engine.processBlock(transformedKey, 16, transformedKey, 16)
}
val md = DigestUtil.sha256()
val transformedKeyDigest = md.digest(transformedKey)
md.update(masterSeed)
return md.digest(transformedKeyDigest)
}
/**
* Create a decrypted input stream from an encrypted one
*/
private fun getDecryptedInputStream(encryptedInputStream: InputStream, keyData: ByteArray, ivData: ByteArray): InputStream {
val keyAndIV = ParametersWithIV(KeyParameter(keyData), ivData)
val cipher = PaddedBufferedBlockCipher(CBCBlockCipher(AESEngine()))
cipher.init(false, keyAndIV)
return CipherInputStream(encryptedInputStream, cipher)
}
/**
* Create an encrypted output stream from an unencrypted output stream
*/
private fun getEncryptedOutputStream(decryptedOutputStream: OutputStream, keyData: ByteArray, ivData: ByteArray): OutputStream {
val cipher = PaddedBufferedBlockCipher(CBCBlockCipher(AESEngine()))
cipher.init(true, ParametersWithIV(KeyParameter(keyData), ivData))
return CipherOutputStream(decryptedOutputStream, cipher)
}
private fun readIntHeaderData(input: LittleEndianDataInputStream): Int {
val fieldLength = input.readShort()
if (fieldLength.toInt() != 4) {
throw IllegalStateException("Int required but length was $fieldLength")
}
return input.readInt()
}
private fun readLongHeaderData(input: LittleEndianDataInputStream): Long {
val fieldLength = input.readShort()
if (fieldLength.toInt() != 8) {
throw IllegalStateException("Long required but length was $fieldLength")
}
return input.readLong()
}
private fun readHeaderData(input: LittleEndianDataInputStream): ByteArray {
val value = ByteArray(input.readShort().toInt())
input.readFully(value)
return value
}
|
apache-2.0
|
7e688c71aef7318e6d1e02970f049f8a
| 35.400602 | 130 | 0.752234 | 4.282069 | false | false | false | false |
mdaniel/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/quickfix/MoveTypeAliasToTopLevelFix.kt
|
1
|
1575
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import org.jetbrains.kotlin.diagnostics.Diagnostic
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeinsight.api.classic.quickfixes.KotlinQuickFixAction
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtTypeAlias
import org.jetbrains.kotlin.psi.psiUtil.parents
class MoveTypeAliasToTopLevelFix(element: KtTypeAlias) : KotlinQuickFixAction<KtTypeAlias>(element) {
override fun getText() = KotlinBundle.message("fix.move.typealias.to.top.level")
override fun getFamilyName() = text
override fun invoke(project: Project, editor: Editor?, file: KtFile) {
val typeAlias = element ?: return
val parents = typeAlias.parents.toList().reversed()
val containingFile = parents.firstOrNull() as? KtFile ?: return
val target = parents.getOrNull(1) ?: return
containingFile.addAfter(typeAlias, target)
containingFile.addAfter(KtPsiFactory(typeAlias).createNewLine(2), target)
typeAlias.delete()
}
companion object : KotlinSingleIntentionActionFactory() {
override fun createAction(diagnostic: Diagnostic) = (diagnostic.psiElement as? KtTypeAlias)?.let { MoveTypeAliasToTopLevelFix(it) }
}
}
|
apache-2.0
|
fff4473b2b0257f32a96f24741513ef1
| 46.727273 | 158 | 0.768254 | 4.525862 | false | false | false | false |
mdaniel/intellij-community
|
python/src/com/jetbrains/python/sdk/PyTargetsRemoteSourcesRefresher.kt
|
1
|
7925
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.sdk
import com.google.gson.Gson
import com.google.gson.annotations.SerializedName
import com.intellij.execution.ExecutionException
import com.intellij.execution.target.TargetEnvironment
import com.intellij.execution.target.TargetEnvironment.TargetPath
import com.intellij.execution.target.TargetEnvironmentRequest
import com.intellij.execution.target.TargetProgressIndicatorAdapter
import com.intellij.execution.target.value.getRelativeTargetPath
import com.intellij.execution.target.value.getTargetDownloadPath
import com.intellij.execution.target.value.getTargetUploadPath
import com.intellij.openapi.Disposable
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.modules
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.remote.RemoteSdkProperties
import com.intellij.util.PathMappingSettings
import com.intellij.util.PathUtil
import com.intellij.util.io.ZipUtil
import com.intellij.util.io.deleteWithParentsIfEmpty
import com.jetbrains.python.PythonHelper
import com.jetbrains.python.run.*
import com.jetbrains.python.run.target.HelpersAwareTargetEnvironmentRequest
import com.jetbrains.python.target.PyTargetAwareAdditionalData
import java.nio.file.Files
import java.nio.file.attribute.FileTime
import java.time.Instant
import kotlin.io.path.deleteExisting
import kotlin.io.path.div
private const val STATE_FILE = ".state.json"
class PyTargetsRemoteSourcesRefresher(val sdk: Sdk, private val project: Project) {
private val pyRequest: HelpersAwareTargetEnvironmentRequest =
checkNotNull(PythonInterpreterTargetEnvironmentFactory.findPythonTargetInterpreter(sdk, project))
private val targetEnvRequest: TargetEnvironmentRequest
get() = pyRequest.targetEnvironmentRequest
init {
assert(sdk !is Disposable || !Disposer.isDisposed(sdk))
}
@Throws(ExecutionException::class)
fun run(indicator: ProgressIndicator) {
val localRemoteSourcesRoot = Files.createDirectories(sdk.remoteSourcesLocalPath)
val localUploadDir = Files.createTempDirectory("remote_sync")
val uploadVolume = TargetEnvironment.UploadRoot(localRootPath = localUploadDir, targetRootPath = TargetPath.Temporary())
targetEnvRequest.uploadVolumes += uploadVolume
val downloadVolume = TargetEnvironment.DownloadRoot(localRootPath = localRemoteSourcesRoot, targetRootPath = TargetPath.Temporary())
targetEnvRequest.downloadVolumes += downloadVolume
pyRequest.targetEnvironmentRequest.ensureProjectSdkAndModuleDirsAreOnTarget(project, sdk)
val execution = prepareHelperScriptExecution(helperPackage = PythonHelper.REMOTE_SYNC, helpersAwareTargetRequest = pyRequest)
val stateFilePath = localRemoteSourcesRoot / STATE_FILE
val stateFilePrevTimestamp: FileTime
if (Files.exists(stateFilePath)) {
stateFilePrevTimestamp = Files.getLastModifiedTime(stateFilePath)
Files.copy(stateFilePath, localUploadDir / STATE_FILE)
execution.addParameter("--state-file")
execution.addParameter(uploadVolume.getTargetUploadPath().getRelativeTargetPath(STATE_FILE))
}
else {
stateFilePrevTimestamp = FileTime.from(Instant.MIN)
}
execution.addParameter(downloadVolume.getTargetDownloadPath())
val targetWithVfs = sdk.targetEnvConfiguration?.let { PythonInterpreterTargetEnvironmentFactory.getTargetWithMappedLocalVfs(it) }
if (targetWithVfs != null) {
// If sdk is target that supports local VFS, there is no reason to copy editable packages to remote_sources
// since their paths should be available locally (to be edited)
// Such packages are in user content roots, so we report them to remote_sync script
val moduleRoots = project.modules.flatMap { it.rootManager.contentRoots.asList() }.mapNotNull {
targetWithVfs.getTargetPathFromVfs(it)
}
if (moduleRoots.isNotEmpty()) {
execution.addParameter("--project-roots")
for (root in moduleRoots) {
execution.addParameter(root)
}
}
}
val targetIndicator = TargetProgressIndicatorAdapter(indicator)
val environment = targetEnvRequest.prepareEnvironment(targetIndicator)
try {
// XXX Make it automatic
environment.uploadVolumes.values.forEach { it.upload(".", targetIndicator) }
val cmd = execution.buildTargetedCommandLine(environment, sdk, emptyList())
cmd.execute(environment, indicator)
// XXX Make it automatic
environment.downloadVolumes.values.forEach { it.download(".", indicator) }
}
finally {
environment.shutdown()
}
if (!Files.exists(stateFilePath)) {
throw IllegalStateException("$stateFilePath is missing")
}
if (Files.getLastModifiedTime(stateFilePath) <= stateFilePrevTimestamp) {
throw IllegalStateException("$stateFilePath has not been updated")
}
val stateFile: StateFile
Files.newBufferedReader(stateFilePath).use {
stateFile = Gson().fromJson(it, StateFile::class.java)
}
val pathMappings = PathMappingSettings()
// Preserve mappings for paths added by user and explicitly excluded by user
// We may lose these mappings otherwise
(sdk.sdkAdditionalData as? PyTargetAwareAdditionalData)?.let { pyData ->
(pyData.pathsAddedByUser + pyData.pathsRemovedByUser).forEach { (localPath, remotePath) ->
pathMappings.add(PathMappingSettings.PathMapping(localPath.toString(), remotePath))
}
}
for (root in stateFile.roots) {
val remoteRootPath = root.path
val localRootName = remoteRootPath.hashCode().toString()
val localRoot = Files.createDirectories(localRemoteSourcesRoot / localRootName)
pathMappings.addMappingCheckUnique(localRoot.toString(), remoteRootPath)
val rootZip = localRemoteSourcesRoot / root.zipName
ZipUtil.extract(rootZip, localRoot, null, true)
for (invalidEntryRelPath in root.invalidEntries) {
val localInvalidEntry = localRoot / PathUtil.toSystemDependentName(invalidEntryRelPath)
LOG.debug("Removing the mapped file $invalidEntryRelPath from $remoteRootPath")
localInvalidEntry.deleteWithParentsIfEmpty(localRemoteSourcesRoot)
}
rootZip.deleteExisting()
}
if (targetWithVfs != null) {
// If target has local VFS, we map locally available roots to VFS instead of copying them to remote_sources
// See how ``updateSdkPaths`` is used
for (remoteRoot in stateFile.skippedRoots) {
val localPath = targetWithVfs.getVfsFromTargetPath(remoteRoot)?.path ?: continue
pathMappings.add(PathMappingSettings.PathMapping(localPath, remoteRoot))
}
}
(sdk.sdkAdditionalData as? RemoteSdkProperties)?.setPathMappings(pathMappings)
val fs = LocalFileSystem.getInstance()
// "remote_sources" folder may now contain new packages
// since we copied them there not via VFS, we must refresh it, so Intellij knows about them
pathMappings.pathMappings.mapNotNull { fs.findFileByPath(it.localRoot) }.forEach { it.refresh(false, true) }
}
private class StateFile {
var roots: List<RootInfo> = emptyList()
@SerializedName("skipped_roots")
var skippedRoots: List<String> = emptyList()
}
private class RootInfo {
var path: String = ""
@SerializedName("zip_name")
var zipName: String = ""
@SerializedName("invalid_entries")
var invalidEntries: List<String> = emptyList()
override fun toString(): String = path
}
companion object {
val LOG = logger<PyTargetsRemoteSourcesRefresher>()
}
}
|
apache-2.0
|
5a3ecbe1059cf8b243f8928d86b6a469
| 42.070652 | 140 | 0.764038 | 4.826431 | false | false | false | false |
anthonycr/Lightning-Browser
|
app/src/main/java/acr/browser/lightning/browser/webrtc/WebRtcPermissionsModel.kt
|
1
|
2243
|
package acr.browser.lightning.browser.webrtc
import acr.browser.lightning.extensions.requiredPermissions
import android.webkit.PermissionRequest
import javax.inject.Inject
import javax.inject.Singleton
/**
* The model that manages permission requests originating from a web page.
*/
@Singleton
class WebRtcPermissionsModel @Inject constructor() {
private val resourceGrantMap = mutableMapOf<String, HashSet<String>>()
/**
* Request a permission from the user to use certain device resources. Will call either
* [PermissionRequest.grant] or [PermissionRequest.deny] based on the response received from the
* user.
*
* @param permissionRequest the request being made.
* @param view the view that will delegate requesting permissions or resources from the user.
*/
fun requestPermission(permissionRequest: PermissionRequest, view: WebRtcPermissionsView) {
val host = permissionRequest.origin.host ?: ""
val requiredResources = permissionRequest.resources
val requiredPermissions = permissionRequest.requiredPermissions()
if (resourceGrantMap[host]?.containsAll(requiredResources.asList()) == true) {
view.requestPermissions(requiredPermissions) { permissionsGranted ->
if (permissionsGranted) {
permissionRequest.grant(requiredResources)
} else {
permissionRequest.deny()
}
}
} else {
view.requestResources(host, requiredResources) { resourceGranted ->
if (resourceGranted) {
view.requestPermissions(requiredPermissions) { permissionsGranted ->
if (permissionsGranted) {
resourceGrantMap[host]?.addAll(requiredResources)
?: resourceGrantMap.put(host, requiredResources.toHashSet())
permissionRequest.grant(requiredResources)
} else {
permissionRequest.deny()
}
}
} else {
permissionRequest.deny()
}
}
}
}
}
|
mpl-2.0
|
1f0010cbe04b017cdbe1256af0e1ebbb
| 39.053571 | 100 | 0.612127 | 5.766067 | false | false | false | false |
3sidedcube/react-native-navigation
|
lib/android/app/src/main/java/com/reactnativenavigation/options/FontOptions.kt
|
1
|
2159
|
package com.reactnativenavigation.options
import android.graphics.Typeface
import com.reactnativenavigation.options.params.NullText
import com.reactnativenavigation.options.params.Text
import com.reactnativenavigation.options.parsers.TypefaceLoader
class FontOptions {
private var isDirty = false
var fontFamily: Text = NullText()
set(value) {
field = value
isDirty = true
}
var fontStyle: Text = NullText()
set(value) {
field = value
isDirty = true
}
var fontWeight: Text = NullText()
set(value) {
field = value
isDirty = true
}
private var _typeface: Typeface? = null
@JvmOverloads fun getTypeface(typefaceLoader: TypefaceLoader, defaultTypeface: Typeface? = null): Typeface? {
if (isDirty) {
_typeface = typefaceLoader.getTypeFace(fontFamily.get(""), fontStyle.get(""), fontWeight.get(""))
isDirty = false
}
return _typeface
?: defaultTypeface?.let { typefaceLoader.getTypeFace(fontFamily.get(""), fontStyle.get(""), fontWeight.get(""), it) }
}
fun mergeWith(other: FontOptions) {
if (other.fontFamily.hasValue()) fontFamily = other.fontFamily
if (other.fontStyle.hasValue()) fontStyle = other.fontStyle
if (other.fontWeight.hasValue()) fontWeight = other.fontWeight
}
fun mergeWithDefault(defaultOptions: FontOptions) {
if (!fontFamily.hasValue()) fontFamily = defaultOptions.fontFamily
if (!fontStyle.hasValue()) fontStyle = defaultOptions.fontStyle
if (!fontWeight.hasValue()) fontWeight = defaultOptions.fontWeight
}
fun hasValue() = fontFamily.hasValue() || fontStyle.hasValue() || fontWeight.hasValue()
@JvmOverloads fun get(defaultValue: FontOptions? = null): FontOptions? {
return if (hasValue()) this else defaultValue
}
override fun equals(other: Any?) = (other as? FontOptions)?.let {
fontFamily.equals(other.fontFamily) &&
fontStyle.equals(other.fontStyle) &&
fontWeight.equals(other.fontWeight)
} ?: false
}
|
mit
|
a7c89e020dc3adece1048f7c28f1fe67
| 35.610169 | 133 | 0.651227 | 4.873589 | false | false | false | false |
siosio/intellij-community
|
platform/platform-impl/src/com/intellij/ide/util/TipsUsageManager.kt
|
1
|
7029
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.util
import com.intellij.featureStatistics.FeatureDescriptor
import com.intellij.featureStatistics.FeaturesRegistryListener
import com.intellij.featureStatistics.ProductivityFeaturesRegistry
import com.intellij.ide.TipsOfTheDayUsagesCollector
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.logger
import com.intellij.util.text.DateFormatUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.EventQueue
import kotlin.random.Random
@ApiStatus.Internal
@State(name = "ShownTips", storages = [Storage(value = "shownTips.xml", roamingType = RoamingType.DISABLED)])
internal class TipsUsageManager : PersistentStateComponent<TipsUsageManager.State> {
companion object {
@JvmStatic
fun getInstance(): TipsUsageManager = service()
}
private val shownTips: MutableMap<String, Long> = mutableMapOf()
private val utilityHolder = TipsUtilityHolder.readFromResourcesAndCreate()
init {
ApplicationManager.getApplication().messageBus.connect().subscribe(FeaturesRegistryListener.TOPIC, TipsUsageListener())
}
override fun getState(): State = State(shownTips)
override fun loadState(state: State) {
shownTips.putAll(state.shownTips)
}
fun sortByUtility(tips: List<TipAndTrickBean>, experimentType: TipsUtilityExperiment): RecommendationDescription {
val usedTips = mutableSetOf<TipAndTrickBean>()
val unusedTips = mutableSetOf<TipAndTrickBean>()
ProductivityFeaturesRegistry.getInstance()?.let { featuresRegistry ->
for (featureId in featuresRegistry.featureIds) {
val feature = featuresRegistry.getFeatureDescriptor(featureId)
val tip = TipUIUtil.getTip(feature) ?: continue
if (!tips.contains(tip)) continue
if (System.currentTimeMillis() - feature.lastTimeUsed < DateFormatUtil.MONTH) {
usedTips.add(tip)
unusedTips.remove(tip) // some tips correspond to multiple features
} else if (!usedTips.contains(tip)) {
unusedTips.add(tip)
}
}
}
val otherTips = tips.toSet() - (usedTips + unusedTips)
val resultTips = when (experimentType) {
TipsUtilityExperiment.BY_TIP_UTILITY -> {
val sortedByUtility = utilityHolder.sampleTips(unusedTips + usedTips)
sortedByUtility + otherTips.shuffled()
}
TipsUtilityExperiment.BY_TIP_UTILITY_IGNORE_USED -> {
val sortedByUtility = utilityHolder.sampleTips(unusedTips)
sortedByUtility + otherTips.shuffled() + usedTips.shuffled()
}
}
return RecommendationDescription(experimentType.toString(), resultTips, utilityHolder.getMetadataVersion())
}
fun fireTipShown(tip: TipAndTrickBean) {
shownTips[tip.fileName] = System.currentTimeMillis()
}
fun filterShownTips(tips: List<TipAndTrickBean>): List<TipAndTrickBean> {
val resultTips = tips.toMutableList()
for (tipFile in shownTips.keys.shuffled()) {
resultTips.find { it.fileName == tipFile }?.let { tip ->
resultTips.remove(tip)
resultTips.add(tip)
}
}
if (wereTipsShownToday()) {
shownTips.maxByOrNull { it.value }?.let {
resultTips.find { tip -> tip.fileName == it.key }?.let { tip ->
resultTips.remove(tip)
resultTips.add(0, tip)
}
}
}
return resultTips
}
fun wereTipsShownToday(): Boolean = System.currentTimeMillis() - (shownTips.maxOfOrNull { it.value } ?: 0) < DateFormatUtil.DAY
data class State(var shownTips: Map<String, Long> = emptyMap())
private class TipsUtilityHolder private constructor(private val tips2utility: Map<String, Double>) {
companion object {
private val LOG = logger<TipsUtilityHolder>()
private const val TIPS_UTILITY_FILE = "tips_utility.csv"
fun create(tipsUtility: Map<String, Double>): TipsUtilityHolder = TipsUtilityHolder(tipsUtility)
fun readFromResourcesAndCreate(): TipsUtilityHolder = create(readTipsUtility())
private fun readTipsUtility() : Map<String, Double> {
assert(!EventQueue.isDispatchThread() || ApplicationManager.getApplication().isUnitTestMode)
val classLoader = TipsUtilityHolder::class.java.classLoader
val lines = classLoader.getResourceAsStream(TIPS_UTILITY_FILE)?.use { it.bufferedReader().readLines() }
if (lines == null) {
LOG.error("Can't read resource file with tips utilities: $TIPS_UTILITY_FILE")
return emptyMap()
}
return lines.associate {
val values = it.split(",")
Pair(values[0], values[1].toDoubleOrNull() ?: 0.0)
}
}
}
fun getMetadataVersion(): String = "0.1"
fun sampleTips(tips: Iterable<TipAndTrickBean>): List<TipAndTrickBean> {
val (knownTips, unknownTips) = tips.map { Pair(it, getTipUtility(it)) }.partition { it.second >= 0 }
val result = mutableListOf<TipAndTrickBean>()
result.sampleByUtility(knownTips)
result.sampleUnknown(unknownTips)
return result
}
private fun MutableList<TipAndTrickBean>.sampleByUtility(knownTips: List<Pair<TipAndTrickBean, Double>>) {
val sortedTips = knownTips.sortedByDescending { it.second }.toMutableSet()
var totalUtility = sortedTips.sumByDouble { it.second }
for (i in 0 until sortedTips.size) {
var cumulativeUtility = 0.0
if (totalUtility <= 0.0) {
this.addAll(sortedTips.map { it.first }.shuffled())
break
}
val prob = Random.nextDouble(totalUtility)
for (tip2utility in sortedTips) {
val tipUtility = tip2utility.second
cumulativeUtility += tipUtility
if (prob <= cumulativeUtility) {
this.add(tip2utility.first)
totalUtility -= tipUtility
sortedTips.remove(tip2utility)
break
}
}
}
}
private fun MutableList<TipAndTrickBean>.sampleUnknown(unknownTips: List<Pair<TipAndTrickBean, Double>>) {
val unknownProb = unknownTips.size.toDouble() / (this.size + unknownTips.size)
var currentIndex = 0
for (unknownTip in unknownTips.shuffled()) {
while (currentIndex < this.size && Random.nextDouble() > unknownProb) {
currentIndex++
}
this.add(currentIndex, unknownTip.first)
currentIndex++
}
}
private fun getTipUtility(tip: TipAndTrickBean): Double {
return tips2utility.getOrDefault(tip.fileName, -1.0)
}
}
private inner class TipsUsageListener : FeaturesRegistryListener {
override fun featureUsed(feature: FeatureDescriptor) {
TipUIUtil.getTip(feature)?.let { tip ->
shownTips[tip.fileName]?.let { timestamp ->
TipsOfTheDayUsagesCollector.triggerTipUsed(tip.fileName, System.currentTimeMillis() - timestamp)
}
}
}
}
}
|
apache-2.0
|
ed27bbb18c5230823824be4b0be29db8
| 38.717514 | 140 | 0.692417 | 4.4347 | false | false | false | false |
siosio/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/intentions/ChopParameterListIntention.kt
|
2
|
5636
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.intentions
import com.intellij.application.options.CodeStyle
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.codeStyle.CommonCodeStyleSettings
import org.jetbrains.kotlin.idea.KotlinBundle
import org.jetbrains.kotlin.idea.formatter.kotlinCommonSettings
import org.jetbrains.kotlin.idea.util.reformatted
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.allChildren
import org.jetbrains.kotlin.psi.psiUtil.createSmartPointer
import org.jetbrains.kotlin.psi.psiUtil.siblings
import org.jetbrains.kotlin.psi.psiUtil.startOffset
abstract class AbstractChopListIntention<TList : KtElement, TElement : KtElement>(
listClass: Class<TList>,
private val elementClass: Class<TElement>,
textGetter: () -> String
) : SelfTargetingIntention<TList>(listClass, textGetter) {
override fun allowCaretInsideElement(element: PsiElement) =
element !is KtValueArgument && super.allowCaretInsideElement(element)
open fun leftParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean = false
open fun rightParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean = false
override fun isApplicableTo(element: TList, caretOffset: Int): Boolean {
val elements = element.elements()
if (elements.size <= 1) return false
if (!isApplicableCaretOffset(caretOffset, element)) return false
if (elements.dropLast(1).all { hasLineBreakAfter(it) }) return false
return true
}
override fun applyTo(element: TList, editor: Editor?) {
val project = element.project
val document = editor?.document ?: return
val pointer = element.createSmartPointer()
val commonCodeStyleSettings = CodeStyle.getSettings(project).kotlinCommonSettings
val leftParOnNewLine = leftParOnNewLine(commonCodeStyleSettings)
val rightParOnNewLine = rightParOnNewLine(commonCodeStyleSettings)
val elements = element.elements()
if (rightParOnNewLine && !hasLineBreakAfter(elements.last())) {
element.allChildren.lastOrNull { it.node.elementType == KtTokens.RPAR }?.startOffset?.let { document.insertString(it, "\n") }
}
val maxIndex = elements.size - 1
for ((index, e) in elements.asReversed().withIndex()) {
if (index == maxIndex && !leftParOnNewLine) break
if (!hasLineBreakBefore(e)) {
document.insertString(e.startOffset, "\n")
}
}
val documentManager = PsiDocumentManager.getInstance(project)
documentManager.commitDocument(document)
pointer.element?.reformatted()
}
protected fun hasLineBreakAfter(element: TElement): Boolean = nextBreak(element) != null
protected fun nextBreak(element: TElement): PsiWhiteSpace? = element.siblings(withItself = false)
.takeWhile { !elementClass.isInstance(it) }
.firstOrNull { it is PsiWhiteSpace && it.textContains('\n') } as? PsiWhiteSpace
protected fun hasLineBreakBefore(element: TElement): Boolean = prevBreak(element) != null
protected fun prevBreak(element: TElement): PsiWhiteSpace? = element.siblings(withItself = false, forward = false)
.takeWhile { !elementClass.isInstance(it) }
.firstOrNull { it is PsiWhiteSpace && it.textContains('\n') } as? PsiWhiteSpace
protected fun TList.elements(): List<TElement> = allChildren.filter { elementClass.isInstance(it) }
.map {
@Suppress("UNCHECKED_CAST")
it as TElement
}
.toList()
protected fun isApplicableCaretOffset(caretOffset: Int, element: TList): Boolean {
val elementBeforeCaret = element.containingFile.findElementAt(caretOffset - 1) ?: return true
if (elementBeforeCaret.node.elementType != KtTokens.RPAR) return true
return elementBeforeCaret.parent == element
}
}
class ChopParameterListIntention : AbstractChopListIntention<KtParameterList, KtParameter>(
KtParameterList::class.java,
KtParameter::class.java,
KotlinBundle.lazyMessage("put.parameters.on.separate.lines")
) {
override fun isApplicableTo(element: KtParameterList, caretOffset: Int): Boolean {
if (element.parent is KtFunctionLiteral) return false
return super.isApplicableTo(element, caretOffset)
}
override fun leftParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean {
return commonCodeStyleSettings.METHOD_PARAMETERS_LPAREN_ON_NEXT_LINE
}
override fun rightParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean {
return commonCodeStyleSettings.METHOD_PARAMETERS_RPAREN_ON_NEXT_LINE
}
}
class ChopArgumentListIntention : AbstractChopListIntention<KtValueArgumentList, KtValueArgument>(
KtValueArgumentList::class.java,
KtValueArgument::class.java,
KotlinBundle.lazyMessage("put.arguments.on.separate.lines")
) {
override fun leftParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean {
return commonCodeStyleSettings.CALL_PARAMETERS_LPAREN_ON_NEXT_LINE
}
override fun rightParOnNewLine(commonCodeStyleSettings: CommonCodeStyleSettings): Boolean {
return commonCodeStyleSettings.CALL_PARAMETERS_RPAREN_ON_NEXT_LINE
}
}
|
apache-2.0
|
9b3bb576270edf1e562c2256260cb247
| 44.088 | 158 | 0.739177 | 4.917976 | false | false | false | false |
JetBrains/kotlin-native
|
build-tools/src/main/kotlin/org/jetbrains/kotlin/RegressionsReporter.kt
|
1
|
7218
|
/*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin
import groovy.lang.Closure
import org.gradle.api.Action
import org.gradle.api.DefaultTask
import org.gradle.api.Project
import org.gradle.api.Task
import org.gradle.api.tasks.Input
import org.gradle.api.tasks.TaskAction
import com.ullink.slack.simpleslackapi.impl.SlackSessionFactory
import org.jetbrains.report.json.*
import java.io.FileInputStream
import java.io.IOException
import java.io.File
import java.util.concurrent.TimeUnit
import java.net.HttpURLConnection
import java.net.URL
import java.util.Base64
import java.util.Properties
/**
* Task to produce regressions report and send it to slack. Requires a report with current benchmarks result
* and path to analyzer tool
*
* @property currentBenchmarksReportFile path to file with becnhmarks result
* @property analyzer path to analyzer tool
* @property htmlReport name of result html report
* @property defaultBranch name of default branch
* @property summaryFile name of file with short summary
* @property bundleBuild property to show if current build is full or not
*/
open class RegressionsReporter : DefaultTask() {
val slackUsers = mapOf(
"olonho" to "nikolay.igotti",
"nikolay.igotti" to "nikolay.igotti",
"ilya.matveev" to "ilya.matveev",
"ilmat192" to "ilya.matveev",
"vasily.v.levchenko" to "minamoto",
"vasily.levchenko" to "minamoto",
"alexander.gorshenev" to "alexander.gorshenev",
"igor.chevdar" to "igor.chevdar",
"pavel.punegov" to "Pavel Punegov",
"dmitriy.dolovov" to "dmitriy.dolovov",
"svyatoslav.scherbina" to "svyatoslav.scherbina",
"sbogolepov" to "sergey.bogolepov",
"Alexey.Zubakov" to "Alexey.Zubakov",
"kirill.shmakov" to "kirill.shmakov",
"elena.lepilkina" to "elena.lepilkina")
@Input
lateinit var currentBenchmarksReportFile: String
@Input
lateinit var analyzer: String
@Input
lateinit var htmlReport: String
@Input
lateinit var defaultBranch: String
@Input
lateinit var summaryFile: String
@Input
var bundleBuild: Boolean = false
private fun tabUrl(buildId: String, buildTypeId: String, tab: String) =
"$teamCityUrl/viewLog.html?buildId=$buildId&buildTypeId=$buildTypeId&tab=$tab"
private fun testReportUrl(buildId: String, buildTypeId: String) =
tabUrl(buildId, buildTypeId, "testsInfo")
private fun previousBuildLocator(buildTypeId: String, branchName: String) =
"buildType:id:$buildTypeId,branch:name:$branchName,status:SUCCESS,state:finished,count:1"
private fun changesListUrl(buildLocator: String) =
"$teamCityUrl/app/rest/changes/?locator=build:$buildLocator"
private fun getCommits(buildLocator: String, user: String, password: String): CommitsList {
val changes = try {
sendGetRequest(changesListUrl(buildLocator), user, password)
} catch (t: Throwable) {
error("Try to get commits! TeamCity is unreachable!")
}
return CommitsList(JsonTreeParser.parse(changes))
}
@TaskAction
fun run() {
// Get TeamCity properties.
val teamcityConfig = System.getenv("TEAMCITY_BUILD_PROPERTIES_FILE") ?:
error("Can't load teamcity config!")
val buildProperties = Properties().apply { load(FileInputStream(teamcityConfig)) }
val buildId = buildProperties.getProperty("teamcity.build.id")
val buildTypeId = buildProperties.getProperty("teamcity.buildType.id")
val buildNumber = buildProperties.getProperty("build.number")
val user = buildProperties.getProperty("teamcity.auth.userId")
val password = buildProperties.getProperty("teamcity.auth.password")
// Get branch.
val currentBuild = getBuild("id:$buildId", user, password)
val branch = getBuildProperty(currentBuild,"branchName")
val testReportUrl = testReportUrl(buildId, buildTypeId)
// Get previous build on branch.
getBuild(previousBuildLocator(buildTypeId,branch), user, password)
// Get changes description.
val changesList = getCommits("id:$buildId", user, password)
val changesInfo = "*Changes* in branch *$branch:*\n" + buildString {
changesList.commits.forEach {
append(" - Change ${it.revision} by ${it.developer} (details: ${it.webUrlWithDescription})\n")
}
}
// File name on Artifactory is the same as current.
val artifactoryFileName = currentBenchmarksReportFile.substringAfterLast("/")
// Get compare to build.
val compareToBuild = getBuild(previousBuildLocator(buildTypeId, defaultBranch), user, password)
val compareToBuildLink = getBuildProperty(compareToBuild,"webUrl")
val compareToBuildNumber = getBuildProperty(compareToBuild,"number")
val target = System.getProperty("os.name").replace("\\s".toRegex(), "")
// Generate comparison report.
val output = arrayOf(analyzer, "-r", "html", currentBenchmarksReportFile, "artifactory:$compareToBuildNumber:$target:$artifactoryFileName", "-o", htmlReport)
.runCommand()
if (output.contains("Uncaught exception")) {
error("Error during comparasion of $currentBenchmarksReportFile and " +
"artifactory:$compareToBuildNumber:$target:$artifactoryFileName with $analyzer! " +
"Please check files existance and their correctness.")
}
arrayOf("$analyzer", "-r", "statistics", "$currentBenchmarksReportFile", "artifactory:$compareToBuildNumber:$target:$artifactoryFileName", "-o", "$summaryFile")
.runCommand()
val reportLink = "https://kotlin-native-perf-summary.labs.jb.gg/?target=$target&build=$buildNumber"
val detailedReportLink = "https://kotlin-native-performance.labs.jb.gg/?" +
"report=artifactory:$buildNumber:$target:$artifactoryFileName&" +
"compareTo=artifactory:$compareToBuildNumber:$target:$artifactoryFileName"
val title = "\n*Performance report for target $target (build $buildNumber)* - $reportLink\n" +
"*Detailed info - * $detailedReportLink"
val header = "$title\n$changesInfo\n\nCompare to build $compareToBuildNumber: $compareToBuildLink\n\n"
val footer = "*Benchmarks statistics:* $testReportUrl"
val message = "$header\n$footer\n"
// Send to channel or user directly.
val session = SlackSessionFactory.createWebSocketSlackSession(buildProperties.getProperty("konan-reporter-token"))
session.connect()
if (branch == defaultBranch) {
if (bundleBuild) {
val channel = session.findChannelByName(buildProperties.getProperty("konan-channel-name"))
session.sendMessage(channel, message)
}
}
session.disconnect()
}
}
|
apache-2.0
|
4cb2af9cafa31e57ff415eaa2d2777aa
| 40.965116 | 168 | 0.677196 | 4.265957 | false | false | false | false |
jwren/intellij-community
|
plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/pullUp/pullUpUtils.kt
|
3
|
7764
|
// Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.refactoring.pullUp
import com.intellij.psi.PsiClass
import com.intellij.psi.PsiMethod
import org.jetbrains.kotlin.asJava.toLightClass
import org.jetbrains.kotlin.descriptors.CallableMemberDescriptor
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.idea.codeInsight.shorten.addToShorteningWaitSet
import org.jetbrains.kotlin.idea.core.replaced
import org.jetbrains.kotlin.idea.core.setType
import org.jetbrains.kotlin.idea.refactoring.isAbstract
import org.jetbrains.kotlin.idea.refactoring.memberInfo.KotlinMemberInfo
import org.jetbrains.kotlin.idea.refactoring.memberInfo.lightElementForMemberInfo
import org.jetbrains.kotlin.idea.util.IdeDescriptorRenderers
import org.jetbrains.kotlin.idea.util.anonymousObjectSuperTypeOrNull
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.DescriptorUtils
import org.jetbrains.kotlin.resolve.descriptorUtil.builtIns
import org.jetbrains.kotlin.types.TypeSubstitutor
import org.jetbrains.kotlin.types.Variance
import org.jetbrains.kotlin.types.isError
import org.jetbrains.kotlin.types.typeUtil.isUnit
fun KtProperty.mustBeAbstractInInterface() =
hasInitializer() || hasDelegate() || (!hasInitializer() && !hasDelegate() && accessors.isEmpty())
fun KtNamedDeclaration.isAbstractInInterface(originalClass: KtClassOrObject) =
originalClass is KtClass && originalClass.isInterface() && isAbstract()
fun KtNamedDeclaration.canMoveMemberToJavaClass(targetClass: PsiClass): Boolean {
return when (this) {
is KtProperty, is KtParameter -> {
if (targetClass.isInterface) return false
if (hasModifier(KtTokens.OPEN_KEYWORD) || hasModifier(KtTokens.ABSTRACT_KEYWORD)) return false
if (this is KtProperty && (accessors.isNotEmpty() || delegateExpression != null)) return false
true
}
is KtNamedFunction -> valueParameters.all { it.defaultValue == null }
else -> false
}
}
fun addMemberToTarget(targetMember: KtNamedDeclaration, targetClass: KtClassOrObject): KtNamedDeclaration {
if (targetClass is KtClass && targetClass.isInterface()) {
targetMember.removeModifier(KtTokens.FINAL_KEYWORD)
}
if (targetMember is KtParameter) {
val parameterList = (targetClass as KtClass).createPrimaryConstructorIfAbsent().valueParameterList!!
val anchor = parameterList.parameters.firstOrNull { it.isVarArg || it.hasDefaultValue() }
return parameterList.addParameterBefore(targetMember, anchor)
}
val anchor = targetClass.declarations.asSequence().filterIsInstance(targetMember::class.java).lastOrNull()
return when {
anchor == null && targetMember is KtProperty -> targetClass.addDeclarationBefore(targetMember, null)
else -> targetClass.addDeclarationAfter(targetMember, anchor)
}
}
private fun KtParameter.needToBeAbstract(targetClass: KtClassOrObject): Boolean {
return hasModifier(KtTokens.ABSTRACT_KEYWORD) || targetClass is KtClass && targetClass.isInterface()
}
private fun KtParameter.toProperty(): KtProperty =
KtPsiFactory(this)
.createProperty(text)
.also {
val originalTypeRef = typeReference
val generatedTypeRef = it.typeReference
if (originalTypeRef != null && generatedTypeRef != null) {
// Preserve copyable user data of original type reference
generatedTypeRef.replace(originalTypeRef)
}
}
fun doAddCallableMember(
memberCopy: KtCallableDeclaration,
clashingSuper: KtCallableDeclaration?,
targetClass: KtClassOrObject
): KtCallableDeclaration {
val memberToAdd = if (memberCopy is KtParameter && memberCopy.needToBeAbstract(targetClass)) memberCopy.toProperty() else memberCopy
if (clashingSuper != null && clashingSuper.hasModifier(KtTokens.ABSTRACT_KEYWORD)) {
return clashingSuper.replaced(if (memberToAdd is KtParameter && clashingSuper is KtProperty) memberToAdd.toProperty() else memberToAdd)
}
return addMemberToTarget(memberToAdd, targetClass) as KtCallableDeclaration
}
// TODO: Formatting rules don't apply here for some reason
fun KtNamedDeclaration.addAnnotationWithSpace(annotationEntry: KtAnnotationEntry): KtAnnotationEntry {
val result = addAnnotationEntry(annotationEntry)
addAfter(KtPsiFactory(this).createWhiteSpace(), modifierList)
return result
}
fun KtClass.makeAbstract() {
if (!isInterface()) {
addModifier(KtTokens.ABSTRACT_KEYWORD)
}
}
fun KtClassOrObject.getSuperTypeEntryByDescriptor(
descriptor: ClassDescriptor,
context: BindingContext
): KtSuperTypeListEntry? {
return superTypeListEntries.firstOrNull {
val referencedType = context[BindingContext.TYPE, it.typeReference]
referencedType?.constructor?.declarationDescriptor == descriptor
}
}
fun makeAbstract(
member: KtCallableDeclaration,
originalMemberDescriptor: CallableMemberDescriptor,
substitutor: TypeSubstitutor,
targetClass: KtClass
) {
if (!targetClass.isInterface()) {
member.addModifier(KtTokens.ABSTRACT_KEYWORD)
}
val builtIns = originalMemberDescriptor.builtIns
if (member.typeReference == null) {
var type = originalMemberDescriptor.returnType
if (type == null || type.isError) {
type = builtIns.nullableAnyType
} else {
type = substitutor.substitute(type.anonymousObjectSuperTypeOrNull() ?: type, Variance.INVARIANT)
?: builtIns.nullableAnyType
}
if (member is KtProperty || !type.isUnit()) {
member.setType(type, false)
}
}
val deleteFrom = when (member) {
is KtProperty -> {
member.equalsToken ?: member.delegate ?: member.accessors.firstOrNull()
}
is KtNamedFunction -> {
member.equalsToken ?: member.bodyExpression
}
else -> null
}
if (deleteFrom != null) {
member.deleteChildRange(deleteFrom, member.lastChild)
}
}
fun addSuperTypeEntry(
delegator: KtSuperTypeListEntry,
targetClass: KtClassOrObject,
targetClassDescriptor: ClassDescriptor,
context: BindingContext,
substitutor: TypeSubstitutor
) {
val referencedType = context[BindingContext.TYPE, delegator.typeReference]!!
val referencedClass = referencedType.constructor.declarationDescriptor as? ClassDescriptor ?: return
if (targetClassDescriptor == referencedClass || DescriptorUtils.isDirectSubclass(targetClassDescriptor, referencedClass)) return
val typeInTargetClass = substitutor.substitute(referencedType, Variance.INVARIANT)
if (!(typeInTargetClass != null && !typeInTargetClass.isError)) return
val renderedType = IdeDescriptorRenderers.SOURCE_CODE.renderType(typeInTargetClass)
val newSpecifier = KtPsiFactory(targetClass).createSuperTypeEntry(renderedType)
targetClass.addSuperTypeListEntry(newSpecifier).addToShorteningWaitSet()
}
fun getInterfaceContainmentVerifier(getMemberInfos: () -> List<KotlinMemberInfo>): (KtNamedDeclaration) -> Boolean = result@{ member ->
val psiMethodToCheck = lightElementForMemberInfo(member) as? PsiMethod ?: return@result false
getMemberInfos().any {
if (!it.isSuperClass || it.overrides != false) return@any false
val psiSuperInterface = (it.member as? KtClass)?.toLightClass()
psiSuperInterface?.findMethodBySignature(psiMethodToCheck, true) != null
}
}
|
apache-2.0
|
f8000ef89ff430d1a362cc9c6d54272b
| 40.303191 | 158 | 0.743174 | 5.274457 | false | false | false | false |
JetBrains/intellij-community
|
plugins/kotlin/base/analysis-api/analysis-api-utils/src/org/jetbrains/kotlin/idea/base/analysis/api/utils/resolveUtils.kt
|
1
|
5641
|
// Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.parameterInfo
import org.jetbrains.kotlin.analysis.api.KtAnalysisSession
import org.jetbrains.kotlin.analysis.api.calls.KtCallCandidateInfo
import org.jetbrains.kotlin.analysis.api.calls.KtFunctionCall
import org.jetbrains.kotlin.analysis.api.calls.singleFunctionCallOrNull
import org.jetbrains.kotlin.analysis.api.signatures.KtFunctionLikeSignature
import org.jetbrains.kotlin.analysis.api.symbols.KtCallableSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtFileSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtFunctionLikeSymbol
import org.jetbrains.kotlin.analysis.api.symbols.KtSymbol
import org.jetbrains.kotlin.analysis.api.symbols.markers.KtSymbolWithVisibility
import org.jetbrains.kotlin.analysis.api.types.KtTypeNullability
import org.jetbrains.kotlin.builtins.StandardNames
import org.jetbrains.kotlin.name.Name
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.getQualifiedExpressionForSelector
import org.jetbrains.kotlin.resolve.ArrayFqNames
// Analogous to Call.resolveCandidates() in plugins/kotlin/core/src/org/jetbrains/kotlin/idea/core/Utils.kt
fun KtAnalysisSession.collectCallCandidates(callElement: KtElement): List<KtCallCandidateInfo> {
val (candidates, explicitReceiver) = when (callElement) {
is KtCallElement -> {
val explicitReceiver = callElement.getQualifiedExpressionForSelector()?.receiverExpression
callElement.collectCallCandidates() to explicitReceiver
}
is KtArrayAccessExpression -> callElement.collectCallCandidates() to callElement.arrayExpression
else -> return emptyList()
}
if (candidates.isEmpty()) return emptyList()
val fileSymbol = callElement.containingKtFile.getFileSymbol()
return candidates.filter { filterCandidate(it, callElement, fileSymbol, explicitReceiver) }
}
private fun KtAnalysisSession.filterCandidate(
candidateInfo: KtCallCandidateInfo,
callElement: KtElement,
fileSymbol: KtFileSymbol,
explicitReceiver: KtExpression?
): Boolean {
val candidateCall = candidateInfo.candidate
if (candidateCall !is KtFunctionCall<*>) return false
val signature = candidateCall.partiallyAppliedSymbol.signature
return filterCandidateByReceiverTypeAndVisibility(signature, callElement, fileSymbol, explicitReceiver)
}
fun KtAnalysisSession.filterCandidateByReceiverTypeAndVisibility(
signature: KtFunctionLikeSignature<KtFunctionLikeSymbol>,
callElement: KtElement,
fileSymbol: KtFileSymbol,
explicitReceiver: KtExpression?
): Boolean {
val candidateSymbol: KtSymbol = signature.symbol
if (callElement is KtConstructorDelegationCall) {
// Exclude caller from candidates for `this(...)` delegated constructor calls.
// The parent of KtDelegatedConstructorCall should be the KtConstructor. We don't need to get the symbol for the constructor
// to determine if it's a self-call; we can just compare the candidate's PSI.
val candidatePsi = candidateSymbol.psi
if (candidatePsi != null && candidatePsi == callElement.parent) {
return false
}
}
if (candidateSymbol is KtCallableSymbol) {
// We want only the candidates that match the receiver type. E.g., if you have code like this:
// ```
// fun String.foo() {}
// fun Int.foo() {}
// fun call(i: Int?) {
// <expr>i?.foo()</expr>
// }
// ```
// The available candidates are `String.foo()` and `Int.foo()`. When checking the receiver types for safe calls, we want to compare
// the non-nullable receiver type against the candidate receiver type. E.g., that `Int` (and not the type of `i` which is `Int?`)
// is subtype of `Int` (the candidate receiver type).
val receiverTypes = if (explicitReceiver != null) {
val isSafeCall = explicitReceiver.parent is KtSafeQualifiedExpression
val explicitReceiverType = explicitReceiver.getKtType() ?: error("Receiver should have a KtType")
val adjustedType = if (isSafeCall) {
explicitReceiverType.withNullability(KtTypeNullability.NON_NULLABLE)
} else {
explicitReceiverType
}
listOf(adjustedType)
} else {
val scopeContext = callElement.containingKtFile.getScopeContextForPosition(callElement)
scopeContext.implicitReceivers.map { it.type }
}
val candidateReceiverType = signature.receiverType
if (candidateReceiverType != null && receiverTypes.none { it.isSubTypeOf(candidateReceiverType) }) return false
}
// Filter out candidates not visible from call site
if (candidateSymbol is KtSymbolWithVisibility && !isVisible(candidateSymbol, fileSymbol, explicitReceiver, callElement)) return false
return true
}
private val ARRAY_OF_FUNCTION_NAMES: Set<Name> = setOf(ArrayFqNames.ARRAY_OF_FUNCTION) +
ArrayFqNames.PRIMITIVE_TYPE_TO_ARRAY.values +
ArrayFqNames.EMPTY_ARRAY
fun KtAnalysisSession.isArrayOfCall(callElement: KtCallElement): Boolean {
val resolvedCall = callElement.resolveCall().singleFunctionCallOrNull() ?: return false
val callableId = resolvedCall.partiallyAppliedSymbol.signature.callableIdIfNonLocal ?: return false
return callableId.packageName == StandardNames.BUILT_INS_PACKAGE_FQ_NAME && callableId.callableName in ARRAY_OF_FUNCTION_NAMES
}
|
apache-2.0
|
8d8d2b360e9789fbf4751f89778091b6
| 48.06087 | 158 | 0.741535 | 5.005324 | false | false | false | false |
SimpleMobileTools/Simple-Commons
|
commons/src/main/kotlin/com/simplemobiletools/commons/extensions/Context-storage-sdk30.kt
|
1
|
9878
|
package com.simplemobiletools.commons.extensions
import android.content.Context
import android.net.Uri
import android.os.Environment
import android.provider.DocumentsContract
import android.provider.MediaStore
import androidx.documentfile.provider.DocumentFile
import com.simplemobiletools.commons.helpers.EXTERNAL_STORAGE_PROVIDER_AUTHORITY
import com.simplemobiletools.commons.helpers.isRPlus
import com.simplemobiletools.commons.helpers.isSPlus
import com.simplemobiletools.commons.models.FileDirItem
import java.io.File
private const val DOWNLOAD_DIR = "Download"
private const val ANDROID_DIR = "Android"
private val DIRS_INACCESSIBLE_WITH_SAF_SDK_30 = listOf(DOWNLOAD_DIR, ANDROID_DIR)
fun Context.hasProperStoredFirstParentUri(path: String): Boolean {
val firstParentUri = createFirstParentTreeUri(path)
return contentResolver.persistedUriPermissions.any { it.uri.toString() == firstParentUri.toString() }
}
fun Context.isAccessibleWithSAFSdk30(path: String): Boolean {
if (path.startsWith(recycleBinPath) || isExternalStorageManager()) {
return false
}
val level = getFirstParentLevel(path)
val firstParentDir = path.getFirstParentDirName(this, level)
val firstParentPath = path.getFirstParentPath(this, level)
val isValidName = firstParentDir != null
val isDirectory = File(firstParentPath).isDirectory
val isAnAccessibleDirectory = DIRS_INACCESSIBLE_WITH_SAF_SDK_30.all { !firstParentDir.equals(it, true) }
return isRPlus() && isValidName && isDirectory && isAnAccessibleDirectory
}
fun Context.getFirstParentLevel(path: String): Int {
return when {
isRPlus() && (isInAndroidDir(path) || isInSubFolderInDownloadDir(path)) -> 1
else -> 0
}
}
fun Context.isRestrictedWithSAFSdk30(path: String): Boolean {
if (path.startsWith(recycleBinPath) || isExternalStorageManager()) {
return false
}
val level = getFirstParentLevel(path)
val firstParentDir = path.getFirstParentDirName(this, level)
val firstParentPath = path.getFirstParentPath(this, level)
val isInvalidName = firstParentDir == null
val isDirectory = File(firstParentPath).isDirectory
val isARestrictedDirectory = DIRS_INACCESSIBLE_WITH_SAF_SDK_30.any { firstParentDir.equals(it, true) }
return isRPlus() && (isInvalidName || (isDirectory && isARestrictedDirectory))
}
fun Context.isInDownloadDir(path: String): Boolean {
if (path.startsWith(recycleBinPath)) {
return false
}
val firstParentDir = path.getFirstParentDirName(this, 0)
return firstParentDir.equals(DOWNLOAD_DIR, true)
}
fun Context.isInSubFolderInDownloadDir(path: String): Boolean {
if (path.startsWith(recycleBinPath)) {
return false
}
val firstParentDir = path.getFirstParentDirName(this, 1)
return if (firstParentDir == null) {
false
} else {
val startsWithDownloadDir = firstParentDir.startsWith(DOWNLOAD_DIR, true)
val hasAtLeast1PathSegment = firstParentDir.split("/").filter { it.isNotEmpty() }.size > 1
val firstParentPath = path.getFirstParentPath(this, 1)
startsWithDownloadDir && hasAtLeast1PathSegment && File(firstParentPath).isDirectory
}
}
fun Context.isInAndroidDir(path: String): Boolean {
if (path.startsWith(recycleBinPath)) {
return false
}
val firstParentDir = path.getFirstParentDirName(this, 0)
return firstParentDir.equals(ANDROID_DIR, true)
}
fun isExternalStorageManager(): Boolean {
return isRPlus() && Environment.isExternalStorageManager()
}
// is the app a Media Management App on Android 12+?
fun Context.canManageMedia(): Boolean {
return isSPlus() && MediaStore.canManageMedia(this)
}
fun Context.createFirstParentTreeUriUsingRootTree(fullPath: String): Uri {
val storageId = getSAFStorageId(fullPath)
val level = getFirstParentLevel(fullPath)
val rootParentDirName = fullPath.getFirstParentDirName(this, level)
val treeUri = DocumentsContract.buildTreeDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, "$storageId:")
val documentId = "${storageId}:$rootParentDirName"
return DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
}
fun Context.createFirstParentTreeUri(fullPath: String): Uri {
val storageId = getSAFStorageId(fullPath)
val level = getFirstParentLevel(fullPath)
val rootParentDirName = fullPath.getFirstParentDirName(this, level)
val firstParentId = "$storageId:$rootParentDirName"
return DocumentsContract.buildTreeDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, firstParentId)
}
fun Context.createDocumentUriUsingFirstParentTreeUri(fullPath: String): Uri {
val storageId = getSAFStorageId(fullPath)
val relativePath = when {
fullPath.startsWith(internalStoragePath) -> fullPath.substring(internalStoragePath.length).trim('/')
else -> fullPath.substringAfter(storageId).trim('/')
}
val treeUri = createFirstParentTreeUri(fullPath)
val documentId = "${storageId}:$relativePath"
return DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
}
fun Context.getSAFDocumentId(path: String): String {
val basePath = path.getBasePath(this)
val relativePath = path.substring(basePath.length).trim('/')
val storageId = getSAFStorageId(path)
return "$storageId:$relativePath"
}
fun Context.createSAFDirectorySdk30(path: String): Boolean {
return try {
val treeUri = createFirstParentTreeUri(path)
val parentPath = path.getParentPath()
if (!getDoesFilePathExistSdk30(parentPath)) {
createSAFDirectorySdk30(parentPath)
}
val documentId = getSAFDocumentId(parentPath)
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
DocumentsContract.createDocument(contentResolver, parentUri, DocumentsContract.Document.MIME_TYPE_DIR, path.getFilenameFromPath()) != null
} catch (e: IllegalStateException) {
showErrorToast(e)
false
}
}
fun Context.createSAFFileSdk30(path: String): Boolean {
return try {
val treeUri = createFirstParentTreeUri(path)
val parentPath = path.getParentPath()
if (!getDoesFilePathExistSdk30(parentPath)) {
createSAFDirectorySdk30(parentPath)
}
val documentId = getSAFDocumentId(parentPath)
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
DocumentsContract.createDocument(contentResolver, parentUri, path.getMimeType(), path.getFilenameFromPath()) != null
} catch (e: IllegalStateException) {
showErrorToast(e)
false
}
}
fun Context.getDoesFilePathExistSdk30(path: String): Boolean {
return when {
isAccessibleWithSAFSdk30(path) -> getFastDocumentSdk30(path)?.exists() ?: false
else -> File(path).exists()
}
}
fun Context.getSomeDocumentSdk30(path: String): DocumentFile? = getFastDocumentSdk30(path) ?: getDocumentSdk30(path)
fun Context.getFastDocumentSdk30(path: String): DocumentFile? {
val uri = createDocumentUriUsingFirstParentTreeUri(path)
return DocumentFile.fromSingleUri(this, uri)
}
fun Context.getDocumentSdk30(path: String): DocumentFile? {
val level = getFirstParentLevel(path)
val firstParentPath = path.getFirstParentPath(this, level)
var relativePath = path.substring(firstParentPath.length)
if (relativePath.startsWith(File.separator)) {
relativePath = relativePath.substring(1)
}
return try {
val treeUri = createFirstParentTreeUri(path)
var document = DocumentFile.fromTreeUri(applicationContext, treeUri)
val parts = relativePath.split("/").filter { it.isNotEmpty() }
for (part in parts) {
document = document?.findFile(part)
}
document
} catch (ignored: Exception) {
null
}
}
fun Context.deleteDocumentWithSAFSdk30(fileDirItem: FileDirItem, allowDeleteFolder: Boolean, callback: ((wasSuccess: Boolean) -> Unit)?) {
try {
var fileDeleted = false
if (fileDirItem.isDirectory.not() || allowDeleteFolder) {
val fileUri = createDocumentUriUsingFirstParentTreeUri(fileDirItem.path)
fileDeleted = DocumentsContract.deleteDocument(contentResolver, fileUri)
}
if (fileDeleted) {
deleteFromMediaStore(fileDirItem.path)
callback?.invoke(true)
}
} catch (e: Exception) {
callback?.invoke(false)
showErrorToast(e)
}
}
fun Context.renameDocumentSdk30(oldPath: String, newPath: String): Boolean {
return try {
val treeUri = createFirstParentTreeUri(oldPath)
val documentId = getSAFDocumentId(oldPath)
val parentUri = DocumentsContract.buildDocumentUriUsingTree(treeUri, documentId)
DocumentsContract.renameDocument(contentResolver, parentUri, newPath.getFilenameFromPath()) != null
} catch (e: IllegalStateException) {
showErrorToast(e)
false
}
}
fun Context.hasProperStoredDocumentUriSdk30(path: String): Boolean {
val documentUri = buildDocumentUriSdk30(path)
return contentResolver.persistedUriPermissions.any { it.uri.toString() == documentUri.toString() }
}
fun Context.buildDocumentUriSdk30(fullPath: String): Uri {
val storageId = getSAFStorageId(fullPath)
val relativePath = when {
fullPath.startsWith(internalStoragePath) -> fullPath.substring(internalStoragePath.length).trim('/')
else -> fullPath.substringAfter(storageId).trim('/')
}
val documentId = "${storageId}:$relativePath"
return DocumentsContract.buildDocumentUri(EXTERNAL_STORAGE_PROVIDER_AUTHORITY, documentId)
}
fun Context.getPicturesDirectoryPath(fullPath: String): String {
val basePath = fullPath.getBasePath(this)
return File(basePath, Environment.DIRECTORY_PICTURES).absolutePath
}
|
gpl-3.0
|
ef256aef5ab27558b606030c50bab103
| 37.585938 | 146 | 0.732031 | 4.447546 | false | false | false | false |
djkovrik/YapTalker
|
data/src/main/java/com/sedsoftware/yaptalker/data/repository/YapChosenTopicRepository.kt
|
1
|
6991
|
package com.sedsoftware.yaptalker.data.repository
import com.sedsoftware.yaptalker.data.exception.RequestErrorException
import com.sedsoftware.yaptalker.data.mapper.EditedPostMapper
import com.sedsoftware.yaptalker.data.mapper.QuotedPostMapper
import com.sedsoftware.yaptalker.data.mapper.ServerResponseMapper
import com.sedsoftware.yaptalker.data.mapper.TopicPageMapper
import com.sedsoftware.yaptalker.data.network.site.YapLoader
import com.sedsoftware.yaptalker.data.system.SchedulersProvider
import com.sedsoftware.yaptalker.domain.entity.BaseEntity
import com.sedsoftware.yaptalker.domain.entity.base.EditedPost
import com.sedsoftware.yaptalker.domain.entity.base.QuotedPost
import com.sedsoftware.yaptalker.domain.entity.base.ServerResponse
import com.sedsoftware.yaptalker.domain.repository.ChosenTopicRepository
import io.reactivex.Completable
import io.reactivex.Single
import okhttp3.MediaType
import okhttp3.MultipartBody
import okhttp3.RequestBody
import java.io.File
import javax.inject.Inject
class YapChosenTopicRepository @Inject constructor(
private val dataLoader: YapLoader,
private val dataMapper: TopicPageMapper,
private val quoteMapper: QuotedPostMapper,
private val editedPostMapper: EditedPostMapper,
private val responseMapper: ServerResponseMapper,
private val schedulers: SchedulersProvider
) : ChosenTopicRepository {
companion object {
private const val KARMA_ACT = "ST"
private const val KARMA_CODE = "vote_post"
private const val KARMA_TYPE_TOPIC = 1
private const val KARMA_TYPE_POST = 0
private const val POST_ACT = "Post"
private const val POST_CODE = "03"
private const val POST_MAX_FILE_SIZE = 512000
private const val POST_EDIT_CODE = "09"
private const val FILE_PART_NAME = "FILE_UPLOAD"
private const val UPLOADED_FILE_TYPE = "image/jpeg"
private const val MESSAGE_SENDING_ERROR_MARKER = "Возникли следующие трудности"
}
override fun getChosenTopic(
forumId: Int,
topicId: Int,
startPostNumber: Int
): Single<List<BaseEntity>> =
dataLoader
.loadTopicPage(forumId, topicId, startPostNumber)
.map(dataMapper)
.subscribeOn(schedulers.io())
override fun requestPostTextAsQuote(
forumId: Int,
topicId: Int,
targetPostId: Int
): Single<QuotedPost> =
dataLoader
.loadTargetPostQuotedText(forumId, topicId, targetPostId)
.map(quoteMapper)
.subscribeOn(schedulers.io())
override fun requestPostTextForEditing(
forumId: Int,
topicId: Int,
postId: Int,
startingPost: Int
): Single<EditedPost> =
dataLoader
.loadTargetPostEditedText(forumId, topicId, postId, startingPost)
.map(editedPostMapper)
.subscribeOn(schedulers.io())
override fun requestKarmaChange(
isTopic: Boolean,
targetPostId: Int,
targetTopicId: Int,
diff: Int
): Single<ServerResponse> =
dataLoader
.changeKarma(
act = KARMA_ACT,
code = KARMA_CODE,
rank = diff,
postId = targetPostId,
topicId = targetTopicId,
type = if (isTopic) KARMA_TYPE_TOPIC else KARMA_TYPE_POST
)
.map(responseMapper)
.subscribeOn(schedulers.io())
override fun requestPostKarmaChange(
targetPostId: Int,
targetTopicId: Int,
diff: Int
): Single<ServerResponse> =
dataLoader
.changeKarma(
act = KARMA_ACT,
code = KARMA_CODE,
rank = diff,
postId = targetPostId,
topicId = targetTopicId,
type = KARMA_TYPE_POST
)
.map(responseMapper)
.subscribeOn(schedulers.io())
override fun requestTopicKarmaChange(
targetPostId: Int,
targetTopicId: Int,
diff: Int
): Single<ServerResponse> =
dataLoader
.changeKarma(
act = KARMA_ACT,
code = KARMA_CODE,
rank = diff,
postId = targetPostId,
topicId = targetTopicId,
type = KARMA_TYPE_TOPIC
)
.map(responseMapper)
.subscribeOn(schedulers.io())
override fun requestMessageSending(
targetForumId: Int,
targetTopicId: Int,
page: Int,
authKey: String,
message: String,
filePath: String
): Completable =
dataLoader
.postMessage(
act = POST_ACT,
code = POST_CODE,
forum = targetForumId,
topic = targetTopicId,
st = page,
enableemo = "yes",
enablesig = "yes",
authKey = authKey,
postContent = message,
enabletag = 0,
maxFileSize = POST_MAX_FILE_SIZE,
uploadedFile = createMultiPartForFile(FILE_PART_NAME, filePath)
)
.map(responseMapper)
.flatMapCompletable { checkMessageSending(it) }
.subscribeOn(schedulers.io())
override fun requestEditedMessageSending(
targetForumId: Int,
targetTopicId: Int,
targetPostId: Int,
page: Int,
authKey: String,
message: String,
file: String
): Completable =
dataLoader
.postEditedMessage(
st = page,
act = POST_ACT,
s = "",
forum = targetForumId,
enableemo = "yes",
enablesig = "yes",
authKey = authKey,
maxFileSize = POST_MAX_FILE_SIZE,
code = POST_EDIT_CODE,
topic = targetTopicId,
post = targetPostId,
postContent = message,
enabletag = 0,
fileupload = file
)
.map(responseMapper)
.flatMapCompletable { checkMessageSending(it) }
.subscribeOn(schedulers.io())
private fun createMultiPartForFile(partName: String, path: String): MultipartBody.Part? =
if (path.isNotEmpty()) {
val file = File(path)
val requestFile = RequestBody.create(MediaType.parse(UPLOADED_FILE_TYPE), file)
MultipartBody.Part.createFormData(partName, file.name, requestFile)
} else {
null
}
private fun checkMessageSending(response: ServerResponse): Completable =
if (response.text.contains(MESSAGE_SENDING_ERROR_MARKER)) {
Completable.error(RequestErrorException("Message sending request failed."))
} else {
Completable.complete()
}
}
|
apache-2.0
|
4be21371841b8a03f6d072d181dd145d
| 32.97561 | 93 | 0.600287 | 4.709263 | false | false | false | false |
androidx/androidx
|
compose/ui/ui/src/androidAndroidTest/kotlin/androidx/compose/ui/input/nestedscroll/NestedScrollModifierTest.kt
|
3
|
45312
|
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.ui.input.nestedscroll
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.requiredSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.BasicText
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.background
import androidx.compose.ui.draw.clipToBounds
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.platform.AbstractComposeView
import androidx.compose.ui.test.junit4.createComposeRule
import androidx.compose.ui.unit.Velocity
import androidx.compose.ui.unit.dp
import androidx.test.espresso.Espresso.onView
import androidx.test.espresso.action.CoordinatesProvider
import androidx.test.espresso.action.GeneralLocation
import androidx.test.espresso.action.GeneralSwipeAction
import androidx.test.espresso.action.Press
import androidx.test.espresso.action.Swipe
import androidx.test.ext.junit.runners.AndroidJUnit4
import androidx.test.filters.FlakyTest
import androidx.test.filters.MediumTest
import com.google.common.truth.Truth.assertThat
import com.google.common.truth.Truth.assertWithMessage
import kotlin.math.abs
import kotlin.math.sign
import kotlinx.coroutines.isActive
import kotlinx.coroutines.runBlocking
import org.hamcrest.CoreMatchers.allOf
import org.hamcrest.CoreMatchers.instanceOf
import org.junit.Rule
import org.junit.Test
import org.junit.runner.RunWith
@RunWith(AndroidJUnit4::class)
@MediumTest
class NestedScrollModifierTest {
@get:Rule
val rule = createComposeRule()
private val preScrollOffset = Offset(120f, 120f)
private val scrollOffset = Offset(125f, 125f)
private val scrollLeftOffset = Offset(32f, 32f)
private val preFling = Velocity(120f, 120f)
private val postFlingConsumed = Velocity(151f, 63f)
private val postFlingLeft = Velocity(11f, 13f)
@Test
fun nestedScroll_twoNodes_orderTest(): Unit = runBlocking {
var counter = 0
val childConnection = object : NestedScrollConnection {}
val parentConnection = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(counter).isEqualTo(1)
counter++
return Offset.Zero
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(counter).isEqualTo(3)
counter++
return Offset.Zero
}
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(counter).isEqualTo(5)
counter++
return Velocity.Zero
}
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(counter).isEqualTo(7)
counter++
return available
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.requiredSize(100.dp).nestedScroll(parentConnection)) {
Box(
Modifier.requiredSize(100.dp).nestedScroll(childConnection, childDispatcher)
)
}
}
assertThat(counter).isEqualTo(0)
counter++
childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
assertThat(counter).isEqualTo(2)
counter++
childDispatcher
.dispatchPostScroll(scrollOffset, scrollLeftOffset, NestedScrollSource.Drag)
assertThat(counter).isEqualTo(4)
counter++
childDispatcher.dispatchPreFling(preFling)
assertThat(counter).isEqualTo(6)
counter++
childDispatcher.dispatchPostFling(postFlingConsumed, postFlingLeft)
assertThat(counter).isEqualTo(8)
counter++
}
@Test
fun nestedScroll_NNodes_orderTest_preScroll() {
var counter = 0
val childConnection = object : NestedScrollConnection {}
val parentConnection = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(counter).isEqualTo(2)
counter++
return Offset.Zero
}
}
val grandParentConnection = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(counter).isEqualTo(1)
counter++
return Offset.Zero
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.requiredSize(100.dp).nestedScroll(grandParentConnection)) {
Box(Modifier.requiredSize(100.dp).nestedScroll(parentConnection)) {
Box(
Modifier.requiredSize(100.dp).nestedScroll(childConnection, childDispatcher)
)
}
}
}
rule.runOnIdle {
assertThat(counter).isEqualTo(0)
counter++
childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
assertThat(counter).isEqualTo(3)
counter++
}
}
@Test
fun nestedScroll_NNodes_orderTest_scroll() {
var counter = 0
val childConnection = object : NestedScrollConnection {}
val parentConnection = object : NestedScrollConnection {
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(counter).isEqualTo(1)
counter++
return Offset.Zero
}
}
val grandParentConnection = object : NestedScrollConnection {
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(counter).isEqualTo(2)
counter++
return Offset.Zero
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.requiredSize(100.dp).nestedScroll(grandParentConnection)) {
Box(Modifier.requiredSize(100.dp).nestedScroll(parentConnection)) {
Box(
Modifier.requiredSize(100.dp).nestedScroll(childConnection, childDispatcher)
)
}
}
}
rule.runOnIdle {
assertThat(counter).isEqualTo(0)
counter++
childDispatcher
.dispatchPostScroll(scrollOffset, scrollLeftOffset, NestedScrollSource.Drag)
assertThat(counter).isEqualTo(3)
counter++
}
}
@Test
fun nestedScroll_NNodes_orderTest_preFling(): Unit = runBlocking {
var counter = 0
val childConnection = object : NestedScrollConnection {}
val parentConnection = object : NestedScrollConnection {
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(counter).isEqualTo(2)
counter++
return Velocity.Zero
}
}
val grandParentConnection = object : NestedScrollConnection {
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(counter).isEqualTo(1)
counter++
return Velocity.Zero
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.requiredSize(100.dp).nestedScroll(grandParentConnection)) {
Box(Modifier.requiredSize(100.dp).nestedScroll(parentConnection)) {
Box(
Modifier.requiredSize(100.dp).nestedScroll(childConnection, childDispatcher)
)
}
}
}
assertThat(counter).isEqualTo(0)
counter++
childDispatcher.dispatchPreFling(preFling)
assertThat(counter).isEqualTo(3)
counter++
}
@Test
fun nestedScroll_NNodes_orderTest_fling(): Unit = runBlocking {
var counter = 0
val childConnection = object : NestedScrollConnection {}
val parentConnection = object : NestedScrollConnection {
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(counter).isEqualTo(1)
counter++
return Velocity.Zero
}
}
val grandParentConnection = object : NestedScrollConnection {
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(counter).isEqualTo(2)
counter++
return Velocity.Zero
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.requiredSize(100.dp).nestedScroll(grandParentConnection)) {
Box(Modifier.requiredSize(100.dp).nestedScroll(parentConnection)) {
Box(
Modifier.requiredSize(100.dp).nestedScroll(childConnection, childDispatcher)
)
}
}
}
assertThat(counter).isEqualTo(0)
counter++
childDispatcher.dispatchPostFling(postFlingConsumed, postFlingLeft)
assertThat(counter).isEqualTo(3)
counter++
}
@Test
fun nestedScroll_twoNodes_hierarchyDispatch(): Unit = runBlocking {
val preScrollReturn = Offset(60f, 30f)
val preFlingReturn = Velocity(154f, 56f)
var currentsource = NestedScrollSource.Drag
val childConnection = object : NestedScrollConnection {}
val parentConnection = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(available).isEqualTo(preScrollOffset)
assertThat(source).isEqualTo(currentsource)
return preScrollReturn
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(consumed).isEqualTo(scrollOffset)
assertThat(available).isEqualTo(scrollLeftOffset)
assertThat(source).isEqualTo(currentsource)
return Offset.Zero
}
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(available).isEqualTo(preFling)
return preFlingReturn
}
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(consumed).isEqualTo(postFlingConsumed)
assertThat(available).isEqualTo(postFlingLeft)
return Velocity.Zero
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.requiredSize(100.dp).nestedScroll(parentConnection)) {
Box(
Modifier.requiredSize(100.dp).nestedScroll(childConnection, childDispatcher)
)
}
}
val preRes1 = childDispatcher.dispatchPreScroll(preScrollOffset, currentsource)
assertThat(preRes1).isEqualTo(preScrollReturn)
childDispatcher.dispatchPostScroll(scrollOffset, scrollLeftOffset, currentsource)
// flip to fling to test again below
currentsource = NestedScrollSource.Fling
val preRes2 = childDispatcher.dispatchPreScroll(preScrollOffset, currentsource)
assertThat(preRes2).isEqualTo(preScrollReturn)
childDispatcher.dispatchPostScroll(scrollOffset, scrollLeftOffset, currentsource)
val preFlingRes = childDispatcher.dispatchPreFling(preFling)
assertThat(preFlingRes).isEqualTo(preFlingReturn)
childDispatcher.dispatchPostFling(postFlingConsumed, postFlingLeft)
}
@Test
fun nestedScroll_deltaCalculation_preScroll() {
val dispatchedPreScroll = Offset(10f, 10f)
val grandParentConsumesPreScroll = Offset(2f, 2f)
val parentConsumedPreScroll = Offset(1f, 1f)
val childConnection = object : NestedScrollConnection {}
val grandParentConnection = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(available).isEqualTo(dispatchedPreScroll)
return grandParentConsumesPreScroll
}
}
val parentConnection = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(available)
.isEqualTo(dispatchedPreScroll - grandParentConsumesPreScroll)
return parentConsumedPreScroll
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.requiredSize(100.dp).nestedScroll(grandParentConnection)) {
Box(Modifier.requiredSize(100.dp).nestedScroll(parentConnection)) {
Box(
Modifier.requiredSize(100.dp).nestedScroll(childConnection, childDispatcher)
)
}
}
}
rule.runOnIdle {
val preRes =
childDispatcher.dispatchPreScroll(dispatchedPreScroll, NestedScrollSource.Drag)
assertThat(preRes).isEqualTo(grandParentConsumesPreScroll + parentConsumedPreScroll)
}
}
@Test
fun nestedScroll_deltaCalculation_scroll() {
val dispatchedConsumedScroll = Offset(4f, 4f)
val dispatchedScroll = Offset(10f, 10f)
val grandParentConsumedScroll = Offset(2f, 2f)
val parentConsumedScroll = Offset(1f, 1f)
val childConnection = object : NestedScrollConnection {}
val grandParentConnection = object : NestedScrollConnection {
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(consumed).isEqualTo(parentConsumedScroll + dispatchedConsumedScroll)
assertThat(available).isEqualTo(dispatchedScroll - parentConsumedScroll)
return grandParentConsumedScroll
}
}
val parentConnection = object : NestedScrollConnection {
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(consumed).isEqualTo(dispatchedConsumedScroll)
assertThat(available).isEqualTo(dispatchedScroll)
return parentConsumedScroll
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.requiredSize(100.dp).nestedScroll(grandParentConnection)) {
Box(Modifier.requiredSize(100.dp).nestedScroll(parentConnection)) {
Box(
Modifier.requiredSize(100.dp).nestedScroll(childConnection, childDispatcher)
)
}
}
}
rule.runOnIdle {
childDispatcher.dispatchPostScroll(
dispatchedConsumedScroll,
dispatchedScroll,
NestedScrollSource.Drag
)
}
}
@Test
fun nestedScroll_deltaCalculation_preFling() = runBlocking {
val dispatchedVelocity = Velocity(10f, 10f)
val grandParentConsumesPreFling = Velocity(2f, 2f)
val parentConsumedPreFling = Velocity(1f, 1f)
val childConnection = object : NestedScrollConnection {}
val grandParentConnection = object : NestedScrollConnection {
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(available).isEqualTo(dispatchedVelocity)
return grandParentConsumesPreFling
}
}
val parentConnection = object : NestedScrollConnection {
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(available)
.isEqualTo(dispatchedVelocity - grandParentConsumesPreFling)
return parentConsumedPreFling
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.requiredSize(100.dp).nestedScroll(grandParentConnection)) {
Box(Modifier.requiredSize(100.dp).nestedScroll(parentConnection)) {
Box(
Modifier.requiredSize(100.dp).nestedScroll(childConnection, childDispatcher)
)
}
}
}
val preRes = childDispatcher.dispatchPreFling(dispatchedVelocity)
assertThat(preRes).isEqualTo(grandParentConsumesPreFling + parentConsumedPreFling)
}
@Test
fun nestedScroll_deltaCalculation_fling(): Unit = runBlocking {
val dispatchedConsumedVelocity = Velocity(4f, 4f)
val dispatchedLeftVelocity = Velocity(10f, 10f)
val grandParentConsumedPostFling = Velocity(2f, 2f)
val parentConsumedPostFling = Velocity(1f, 1f)
val childConnection = object : NestedScrollConnection {}
val grandParentConnection = object : NestedScrollConnection {
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(consumed)
.isEqualTo(parentConsumedPostFling + dispatchedConsumedVelocity)
assertThat(available)
.isEqualTo(dispatchedLeftVelocity - parentConsumedPostFling)
return grandParentConsumedPostFling
}
}
val parentConnection = object : NestedScrollConnection {
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(consumed).isEqualTo(dispatchedConsumedVelocity)
assertThat(available).isEqualTo(dispatchedLeftVelocity)
return parentConsumedPostFling
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.requiredSize(100.dp).nestedScroll(grandParentConnection)) {
Box(Modifier.requiredSize(100.dp).nestedScroll(parentConnection)) {
Box(
Modifier.requiredSize(100.dp).nestedScroll(childConnection, childDispatcher)
)
}
}
}
childDispatcher.dispatchPostFling(dispatchedConsumedVelocity, dispatchedLeftVelocity)
}
@Test
fun nestedScroll_twoNodes_flatDispatch(): Unit = runBlocking {
val preScrollReturn = Offset(60f, 30f)
val preFlingReturn = Velocity(154f, 56f)
var currentsource = NestedScrollSource.Drag
val childConnection = object : NestedScrollConnection {}
val parentConnection = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(available).isEqualTo(preScrollOffset)
assertThat(source).isEqualTo(currentsource)
return preScrollReturn
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(consumed).isEqualTo(scrollOffset)
assertThat(available).isEqualTo(scrollLeftOffset)
assertThat(source).isEqualTo(currentsource)
return Offset.Zero
}
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(available).isEqualTo(preFling)
return preFlingReturn
}
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(consumed).isEqualTo(postFlingConsumed)
assertThat(available).isEqualTo(postFlingLeft)
return Velocity.Zero
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(
Modifier
.requiredSize(100.dp)
.nestedScroll(parentConnection) // parent
.nestedScroll(childConnection, childDispatcher) // child
)
}
val preRes1 = childDispatcher.dispatchPreScroll(preScrollOffset, currentsource)
assertThat(preRes1).isEqualTo(preScrollReturn)
childDispatcher.dispatchPostScroll(scrollOffset, scrollLeftOffset, currentsource)
// flip to fling to test again below
currentsource = NestedScrollSource.Fling
val preRes2 = childDispatcher.dispatchPreScroll(preScrollOffset, currentsource)
assertThat(preRes2).isEqualTo(preScrollReturn)
childDispatcher.dispatchPostScroll(scrollOffset, scrollLeftOffset, currentsource)
val preFlingRes = childDispatcher.dispatchPreFling(preFling)
assertThat(preFlingRes).isEqualTo(preFlingReturn)
childDispatcher.dispatchPostFling(postFlingConsumed, postFlingLeft)
}
@Test
fun nestedScroll_shouldNotCalledSelfConnection(): Unit = runBlocking {
val childConnection = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertWithMessage("self connection shouldn't be called").fail()
return Offset.Zero
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertWithMessage("self connection shouldn't be called").fail()
return Offset.Zero
}
override suspend fun onPreFling(available: Velocity): Velocity {
assertWithMessage("self connection shouldn't be called").fail()
return Velocity.Zero
}
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertWithMessage("self connection shouldn't be called").fail()
return Velocity.Zero
}
}
val parentConnection = object : NestedScrollConnection {}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
Box(Modifier.nestedScroll(parentConnection)) {
Box(Modifier.nestedScroll(childConnection, childDispatcher))
}
}
childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
childDispatcher
.dispatchPostScroll(scrollOffset, scrollLeftOffset, NestedScrollSource.Fling)
childDispatcher.dispatchPreFling(preFling)
childDispatcher.dispatchPostFling(postFlingConsumed, postFlingLeft)
}
@Test
fun nestedScroll_hierarchyDispatch_rootParentRemoval() {
testRootParentAdditionRemoval { root, child ->
Box(Modifier.requiredSize(100.dp).then(root)) {
Box(child)
}
}
}
@Test
fun nestedScroll_flatDispatch_rootParentRemoval() {
testRootParentAdditionRemoval { root, child ->
Box(Modifier.then(root).then(child))
}
}
@Test
fun nestedScroll_flatDispatch_longChain_rootParentRemoval() {
testRootParentAdditionRemoval { root, child ->
// insert a few random modifiers so it's more realistic example of wrapper re-usage
Box(
Modifier.requiredSize(100.dp)
.then(root)
.padding(5.dp)
.requiredSize(50.dp)
.then(child)
)
}
}
@Test
fun nestedScroll_hierarchyDispatch_middleParentRemoval() {
testMiddleParentAdditionRemoval { rootMod, middleMod, childMod ->
// random boxes to emulate nesting
Box(Modifier.requiredSize(100.dp).then(rootMod)) {
Box {
Box(Modifier.requiredSize(100.dp).then(middleMod)) {
Box {
Box(childMod)
}
}
}
}
}
}
@Test
fun nestedScroll_flatDispatch_middleParentRemoval() {
testMiddleParentAdditionRemoval { rootMod, middleMod, childMod ->
Box(
Modifier
.then(rootMod)
.then(middleMod)
.then(childMod)
)
}
}
@Test
fun nestedScroll_flatDispatch_longChain_middleParentRemoval() {
testMiddleParentAdditionRemoval { rootMod, middleMod, childMod ->
// insert a few random modifiers so it's more realistic example of wrapper re-usage
Box(
Modifier
.requiredSize(100.dp)
.then(rootMod)
.requiredSize(90.dp)
.clipToBounds()
.then(middleMod)
.padding(5.dp)
.then(childMod)
)
}
}
@Test
fun nestedScroll_flatDispatch_runtimeSwapChange_orderTest() = runBlocking {
val preScrollReturn = Offset(60f, 30f)
val preFlingReturn = Velocity(154f, 56f)
var counter = 0
val isConnection1Parent = mutableStateOf(true)
val childConnection = object : NestedScrollConnection {}
val connection1 = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 1 else 2)
counter++
return preScrollReturn
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 2 else 1)
counter++
return Offset.Zero
}
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 1 else 2)
counter++
return preFlingReturn
}
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 2 else 1)
counter++
return Velocity.Zero
}
}
val connection2 = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 2 else 1)
counter++
return preScrollReturn
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 1 else 2)
counter++
return Offset.Zero
}
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 2 else 1)
counter++
return preFlingReturn
}
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 1 else 2)
counter++
return Velocity.Zero
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
val nestedScrollParents = if (isConnection1Parent.value) {
Modifier.nestedScroll(connection1).nestedScroll(connection2)
} else {
Modifier.nestedScroll(connection2).nestedScroll(connection1)
}
Box(
Modifier
.requiredSize(100.dp)
.then(nestedScrollParents)
.nestedScroll(childConnection, childDispatcher)
)
}
repeat(2) {
counter = 1
childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
assertThat(counter).isEqualTo(3)
counter = 1
childDispatcher.dispatchPostScroll(
scrollOffset,
scrollLeftOffset,
NestedScrollSource.Drag
)
assertThat(counter).isEqualTo(3)
counter = 1
childDispatcher.dispatchPreFling(preFling)
assertThat(counter).isEqualTo(3)
counter = 1
childDispatcher.dispatchPostFling(postFlingConsumed, postFlingLeft)
assertThat(counter).isEqualTo(3)
counter = 1
isConnection1Parent.value = !isConnection1Parent.value
rule.waitForIdle()
}
}
@Test
fun nestedScroll_rootParentRemoval_childHasProperDispatchScope() {
val emitParent = mutableStateOf(true)
val parentConnection = object : NestedScrollConnection {}
val childConnection = object : NestedScrollConnection {}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
val parent =
if (emitParent.value) {
Modifier.nestedScroll(parentConnection)
} else {
Modifier
}
Box(parent) {
Box(Modifier.nestedScroll(childConnection, childDispatcher))
}
}
rule.runOnIdle {
assertThat(childDispatcher.coroutineScope.isActive).isTrue()
emitParent.value = false
}
rule.runOnIdle {
// still not null as we took origin
assertThat(childDispatcher.coroutineScope.isActive).isTrue()
}
}
@Test
fun nestedScroll_hierarchyDispatch_runtimeSwapChange_orderTest() = runBlocking {
val preScrollReturn = Offset(60f, 30f)
val preFlingReturn = Velocity(154f, 56f)
var counter = 0
val isConnection1Parent = mutableStateOf(true)
val childConnection = object : NestedScrollConnection {}
val connection1 = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 1 else 2)
counter++
return preScrollReturn
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 2 else 1)
counter++
return Offset.Zero
}
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 1 else 2)
counter++
return preFlingReturn
}
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 2 else 1)
counter++
return Velocity.Zero
}
}
val connection2 = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 2 else 1)
counter++
return preScrollReturn
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 1 else 2)
counter++
return Offset.Zero
}
override suspend fun onPreFling(available: Velocity): Velocity {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 2 else 1)
counter++
return preFlingReturn
}
override suspend fun onPostFling(
consumed: Velocity,
available: Velocity
): Velocity {
assertThat(counter).isEqualTo(if (isConnection1Parent.value) 1 else 2)
counter++
return Velocity.Zero
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
val outerBoxConnection = if (isConnection1Parent.value) connection1 else connection2
val innerBoxConnection = if (isConnection1Parent.value) connection2 else connection1
Box(Modifier.requiredSize(100.dp).nestedScroll(outerBoxConnection)) {
Box(Modifier.requiredSize(100.dp).nestedScroll(innerBoxConnection)) {
Box(Modifier.nestedScroll(childConnection, childDispatcher))
}
}
}
repeat(2) {
counter = 1
childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
assertThat(counter).isEqualTo(3)
counter = 1
childDispatcher.dispatchPostScroll(
scrollOffset,
scrollLeftOffset,
NestedScrollSource.Drag
)
assertThat(counter).isEqualTo(3)
counter = 1
childDispatcher.dispatchPreFling(preFling)
assertThat(counter).isEqualTo(3)
counter = 1
childDispatcher.dispatchPostFling(postFlingConsumed, postFlingLeft)
assertThat(counter).isEqualTo(3)
counter = 1
isConnection1Parent.value = !isConnection1Parent.value
rule.waitForIdle()
}
}
@FlakyTest(bugId = 259725902)
@Test
fun nestedScroll_movingTarget_velocityShouldRespectSign() {
var lastVelocity = Velocity.Zero
val MaxOffsetBound = 900f
val ConsumedEverything = 0.0f
rule.setContent {
var offset by remember {
mutableStateOf(MaxOffsetBound)
}
val nestedScrollConnection = remember {
object : NestedScrollConnection {
fun consumedDelta(scrollDelta: Float): Float {
if (offset == 0f && scrollDelta < 0f) return ConsumedEverything
if (offset == MaxOffsetBound && scrollDelta > 0f) return ConsumedEverything
val previousOffset = offset
offset = (scrollDelta + offset).coerceIn(0f, MaxOffsetBound)
return offset - previousOffset
}
override fun onPreScroll(
available: Offset,
source: NestedScrollSource
): Offset {
return if (available.y < 0) {
val consumed = consumedDelta(available.y)
Offset(x = 0f, y = consumed)
} else Offset.Zero
}
override fun onPostScroll(
consumed: Offset,
available: Offset,
source: NestedScrollSource
): Offset {
return if (abs(available.y) > 0f &&
available.y > 0f
) {
Offset(0f, consumedDelta(available.y))
} else
super.onPostScroll(consumed, available, source)
}
override suspend fun onPreFling(available: Velocity): Velocity {
lastVelocity = available
return super.onPreFling(available)
}
}
}
Column(modifier = Modifier.fillMaxSize()) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(80.dp)
)
LazyColumn(
modifier = Modifier
.graphicsLayer {
translationY = offset
}
.nestedScroll(connection = nestedScrollConnection)
.fillMaxWidth()
.weight(1f)
) {
items(100) {
Box(
modifier = Modifier
.fillMaxWidth()
.height(60.dp)
.background(Color.Gray)
) {
BasicText(text = it.toString())
}
Spacer(modifier = Modifier.height(8.dp))
}
}
}
}
composeViewSwipeUp()
rule.runOnIdle {
// swipe ups provide negative signed velocities
assertThat(sign(lastVelocity.y)).isEqualTo(-1)
}
composeViewSwipeDown()
rule.runOnIdle {
// swipe downs provide positive signed velocities
assertThat(sign(lastVelocity.y)).isEqualTo(1)
}
composeViewSwipeDown()
rule.runOnIdle {
// swipe downs provide positive signed velocities
assertThat(sign(lastVelocity.y)).isEqualTo(1)
}
}
// helper functions
private fun composeViewSwipeUp() {
onView(allOf(instanceOf(AbstractComposeView::class.java)))
.perform(
espressoSwipe(
GeneralLocation.BOTTOM_CENTER,
GeneralLocation.CENTER
)
)
}
private fun composeViewSwipeDown() {
onView(allOf(instanceOf(AbstractComposeView::class.java)))
.perform(
espressoSwipe(
GeneralLocation.CENTER,
GeneralLocation.BOTTOM_CENTER
)
)
}
private fun espressoSwipe(
start: CoordinatesProvider,
end: CoordinatesProvider
): GeneralSwipeAction {
return GeneralSwipeAction(
Swipe.FAST, start, end,
Press.FINGER
)
}
private fun testMiddleParentAdditionRemoval(
content: @Composable (root: Modifier, middle: Modifier, child: Modifier) -> Unit
) {
val rootParentPreConsumed = Offset(60f, 30f)
val parentToRemovePreConsumed = Offset(21f, 44f)
val emitNewParent = mutableStateOf(true)
val childConnection = object : NestedScrollConnection {}
val rootParent = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
return rootParentPreConsumed
}
}
val parentToRemove = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
if (!emitNewParent.value) {
assertWithMessage("Shouldn't be called when not emitted").fail()
}
return parentToRemovePreConsumed
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
val maybeNestedScroll =
if (emitNewParent.value) Modifier.nestedScroll(parentToRemove) else Modifier
content.invoke(
Modifier.nestedScroll(rootParent),
maybeNestedScroll,
Modifier.nestedScroll(childConnection, childDispatcher)
)
}
rule.runOnIdle {
val res =
childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
assertThat(res).isEqualTo(rootParentPreConsumed + parentToRemovePreConsumed)
emitNewParent.value = false
}
rule.runOnIdle {
val res =
childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
assertThat(res).isEqualTo(rootParentPreConsumed)
emitNewParent.value = true
}
rule.runOnIdle {
val res =
childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
assertThat(res).isEqualTo(rootParentPreConsumed + parentToRemovePreConsumed)
}
}
private fun testRootParentAdditionRemoval(
content: @Composable (root: Modifier, child: Modifier) -> Unit
) {
val preScrollReturn = Offset(60f, 30f)
val emitParentNestedScroll = mutableStateOf(true)
val childConnection = object : NestedScrollConnection {}
val parent = object : NestedScrollConnection {
override fun onPreScroll(available: Offset, source: NestedScrollSource): Offset {
return preScrollReturn
}
}
val childDispatcher = NestedScrollDispatcher()
rule.setContent {
val maybeNestedScroll =
if (emitParentNestedScroll.value) Modifier.nestedScroll(parent) else Modifier
content.invoke(
maybeNestedScroll,
Modifier.nestedScroll(childConnection, childDispatcher)
)
}
rule.runOnIdle {
val res = childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
assertThat(res).isEqualTo(preScrollReturn)
emitParentNestedScroll.value = false
}
rule.runOnIdle {
val res = childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
assertThat(res).isEqualTo(Offset.Zero)
emitParentNestedScroll.value = true
}
rule.runOnIdle {
val res = childDispatcher.dispatchPreScroll(preScrollOffset, NestedScrollSource.Drag)
assertThat(res).isEqualTo(preScrollReturn)
}
}
}
|
apache-2.0
|
b53d8d841969bb875753ed9813f4736e
| 36.356142 | 100 | 0.585871 | 5.759756 | false | false | false | false |
androidx/androidx
|
camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/compat/Camera2CameraMetadata.kt
|
3
|
8498
|
/*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.camera.camera2.pipe.compat
import android.hardware.camera2.CameraCharacteristics
import android.hardware.camera2.CaptureRequest
import android.hardware.camera2.CaptureResult
import android.os.Build
import android.util.ArrayMap
import androidx.annotation.GuardedBy
import androidx.annotation.RequiresApi
import androidx.camera.camera2.pipe.CameraId
import androidx.camera.camera2.pipe.CameraMetadata
import androidx.camera.camera2.pipe.Metadata
import androidx.camera.camera2.pipe.core.Debug
import kotlin.reflect.KClass
/**
* This implementation provides access to [CameraCharacteristics] and lazy caching of properties
* that are either expensive to create and access, or that only exist on newer versions of the
* OS. This allows all fields to be accessed and return reasonable values on all OS versions.
*/
@RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
internal class Camera2CameraMetadata constructor(
override val camera: CameraId,
override val isRedacted: Boolean,
private val characteristics: CameraCharacteristics,
private val metadataProvider: CameraMetadataProvider,
private val metadata: Map<Metadata.Key<*>, Any?>,
private val cacheBlocklist: Set<CameraCharacteristics.Key<*>>,
) : CameraMetadata {
@GuardedBy("values")
private val values = ArrayMap<CameraCharacteristics.Key<*>, Any?>()
@Suppress("UNCHECKED_CAST")
override fun <T> get(key: Metadata.Key<T>): T? = metadata[key] as T?
@Suppress("UNCHECKED_CAST")
override fun <T> getOrDefault(key: Metadata.Key<T>, default: T): T =
metadata[key] as T? ?: default
override fun <T> get(key: CameraCharacteristics.Key<T>): T? {
if (cacheBlocklist.contains(key)) {
return characteristics.get(key)
}
// Cache the return value of calls to characteristics as the implementation performs a
// blocking jni binder call which can be expensive when invoked frequently (see b/144028609
// for more details).
// Implementation notes:
// 1. Null return values may eventually turn non-null on subsequent queries (due to
// permissions). Null return values are not cached and are always re-queried.
//
// 2. Non-null return values will never turn null, and will not change once returned. If
// permissions are revoked, this should result in the app process being restarted.
//
// 3. Duplicate non-null values are expected to be identical (even if the object instance
// is different), and so it does not matter which value is cached if two calls from
// different threads try to read the value simultaneously.
@Suppress("UNCHECKED_CAST")
var result = synchronized(values) { values[key] } as T?
if (result == null) {
result = characteristics.get(key)
if (result != null) {
synchronized(values) {
values[key] = result
}
}
}
return result
}
override fun <T> getOrDefault(key: CameraCharacteristics.Key<T>, default: T): T =
get(key) ?: default
@Suppress("UNCHECKED_CAST")
override fun <T : Any> unwrapAs(type: KClass<T>): T? = when (type) {
CameraCharacteristics::class -> characteristics as T
else -> null
}
override val keys: Set<CameraCharacteristics.Key<*>> get() = _keys.value
override val requestKeys: Set<CaptureRequest.Key<*>> get() = _requestKeys.value
override val resultKeys: Set<CaptureResult.Key<*>> get() = _resultKeys.value
override val sessionKeys: Set<CaptureRequest.Key<*>> get() = _sessionKeys.value
override val physicalCameraIds: Set<CameraId> get() = _physicalCameraIds.value
override val physicalRequestKeys: Set<CaptureRequest.Key<*>>
get() = _physicalRequestKeys.value
override suspend fun getPhysicalMetadata(cameraId: CameraId): CameraMetadata {
check(physicalCameraIds.contains(cameraId)) {
"$cameraId is not a valid physical camera on $this"
}
return metadataProvider.getMetadata(cameraId)
}
override fun awaitPhysicalMetadata(cameraId: CameraId): CameraMetadata {
check(physicalCameraIds.contains(cameraId)) {
"$cameraId is not a valid physical camera on $this"
}
return metadataProvider.awaitMetadata(cameraId)
}
private val _keys: Lazy<Set<CameraCharacteristics.Key<*>>> =
lazy(LazyThreadSafetyMode.PUBLICATION) {
try {
Debug.trace("Camera-${camera.value}#keys") {
@Suppress("UselessCallOnNotNull")
characteristics.keys.orEmpty().toSet()
}
} catch (ignored: AssertionError) {
emptySet()
}
}
private val _requestKeys: Lazy<Set<CaptureRequest.Key<*>>> =
lazy(LazyThreadSafetyMode.PUBLICATION) {
try {
Debug.trace("Camera-${camera.value}#availableCaptureRequestKeys") {
@Suppress("UselessCallOnNotNull")
characteristics.availableCaptureRequestKeys.orEmpty().toSet()
}
} catch (ignored: AssertionError) {
emptySet()
}
}
private val _resultKeys: Lazy<Set<CaptureResult.Key<*>>> =
lazy(LazyThreadSafetyMode.PUBLICATION) {
try {
Debug.trace("Camera-${camera.value}#availableCaptureResultKeys") {
@Suppress("UselessCallOnNotNull")
characteristics.availableCaptureResultKeys.orEmpty().toSet()
}
} catch (ignored: AssertionError) {
emptySet()
}
}
private val _physicalCameraIds: Lazy<Set<CameraId>> =
lazy(LazyThreadSafetyMode.PUBLICATION) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
emptySet()
} else {
try {
Debug.trace("Camera-${camera.value}#physicalCameraIds") {
@Suppress("UselessCallOnNotNull")
Api28Compat.getPhysicalCameraIds(characteristics)
.orEmpty()
.map { CameraId(it) }
.toSet()
}
} catch (ignored: AssertionError) {
emptySet()
} catch (ignored: NullPointerException) {
emptySet()
}
}
}
private val _physicalRequestKeys: Lazy<Set<CaptureRequest.Key<*>>> =
lazy(LazyThreadSafetyMode.PUBLICATION) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
emptySet()
} else {
try {
Debug.trace("Camera-${camera.value}#availablePhysicalCameraRequestKeys") {
Api28Compat.getAvailablePhysicalCameraRequestKeys(characteristics)
.orEmpty()
.toSet()
}
} catch (ignored: AssertionError) {
emptySet()
}
}
}
private val _sessionKeys: Lazy<Set<CaptureRequest.Key<*>>> =
lazy(LazyThreadSafetyMode.PUBLICATION) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.P) {
emptySet()
} else {
try {
Debug.trace("Camera-${camera.value}#availableSessionKeys") {
Api28Compat.getAvailableSessionKeys(characteristics).orEmpty().toSet()
}
} catch (ignored: AssertionError) {
emptySet()
}
}
}
}
|
apache-2.0
|
561402e383036670bfc7ebf93fb2095d
| 40.05314 | 99 | 0.610379 | 4.972499 | false | false | false | false |
nrizzio/Signal-Android
|
app/src/main/java/org/thoughtcrime/securesms/badges/models/LargeBadge.kt
|
1
|
2651
|
package org.thoughtcrime.securesms.badges.models
import android.view.View
import android.widget.TextView
import org.thoughtcrime.securesms.R
import org.thoughtcrime.securesms.badges.BadgeImageView
import org.thoughtcrime.securesms.util.adapter.mapping.LayoutFactory
import org.thoughtcrime.securesms.util.adapter.mapping.MappingAdapter
import org.thoughtcrime.securesms.util.adapter.mapping.MappingModel
import org.thoughtcrime.securesms.util.adapter.mapping.MappingViewHolder
data class LargeBadge(
val badge: Badge
) {
class Model(val largeBadge: LargeBadge, val shortName: String, val maxLines: Int) : MappingModel<Model> {
override fun areItemsTheSame(newItem: Model): Boolean {
return newItem.largeBadge.badge.id == largeBadge.badge.id
}
override fun areContentsTheSame(newItem: Model): Boolean {
return newItem.largeBadge == largeBadge && newItem.shortName == shortName && newItem.maxLines == maxLines
}
}
class EmptyModel : MappingModel<EmptyModel> {
override fun areItemsTheSame(newItem: EmptyModel): Boolean = true
override fun areContentsTheSame(newItem: EmptyModel): Boolean = true
}
class EmptyViewHolder(itemView: View) : MappingViewHolder<EmptyModel>(itemView) {
override fun bind(model: EmptyModel) {
}
}
class ViewHolder(itemView: View) : MappingViewHolder<Model>(itemView) {
private val badge: BadgeImageView = itemView.findViewById(R.id.badge)
private val name: TextView = itemView.findViewById(R.id.name)
private val description: TextView = itemView.findViewById(R.id.description)
override fun bind(model: Model) {
badge.setBadge(model.largeBadge.badge)
name.text = context.getString(R.string.ViewBadgeBottomSheetDialogFragment__s_supports_signal, model.shortName)
description.text = if (model.largeBadge.badge.isSubscription()) {
context.getString(R.string.ViewBadgeBottomSheetDialogFragment__s_supports_signal_with_a_monthly, model.shortName)
} else {
context.getString(R.string.ViewBadgeBottomSheetDialogFragment__s_supports_signal_with_a_donation, model.shortName)
}
description.setLines(model.maxLines)
description.maxLines = model.maxLines
description.minLines = model.maxLines
}
}
companion object {
fun register(mappingAdapter: MappingAdapter) {
mappingAdapter.registerFactory(Model::class.java, LayoutFactory({ ViewHolder(it) }, R.layout.view_badge_bottom_sheet_dialog_fragment_page))
mappingAdapter.registerFactory(EmptyModel::class.java, LayoutFactory({ EmptyViewHolder(it) }, R.layout.view_badge_bottom_sheet_dialog_fragment_page))
}
}
}
|
gpl-3.0
|
fd6acb5f093ecc564ff8dfa7221ec127
| 40.421875 | 155 | 0.760468 | 4.296596 | false | false | false | false |
GunoH/intellij-community
|
platform/lang-impl/src/com/intellij/lang/documentation/ide/ui/DocumentationUI.kt
|
7
|
8595
|
// 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.lang.documentation.ide.ui
import com.intellij.codeInsight.CodeInsightBundle
import com.intellij.codeInsight.documentation.DocumentationHintEditorPane
import com.intellij.codeInsight.documentation.DocumentationLinkHandler
import com.intellij.codeInsight.documentation.DocumentationManager.SELECTED_QUICK_DOC_TEXT
import com.intellij.codeInsight.documentation.DocumentationManager.decorate
import com.intellij.codeInsight.documentation.DocumentationScrollPane
import com.intellij.ide.DataManager
import com.intellij.lang.documentation.DocumentationImageResolver
import com.intellij.lang.documentation.ide.actions.DOCUMENTATION_BROWSER
import com.intellij.lang.documentation.ide.actions.PRIMARY_GROUP_ID
import com.intellij.lang.documentation.ide.actions.registerBackForwardActions
import com.intellij.lang.documentation.ide.impl.DocumentationBrowser
import com.intellij.lang.documentation.ide.impl.DocumentationPage
import com.intellij.lang.documentation.ide.impl.DocumentationPageContent
import com.intellij.navigation.TargetPresentation
import com.intellij.openapi.Disposable
import com.intellij.openapi.actionSystem.DataProvider
import com.intellij.openapi.application.EDT
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.text.HtmlChunk
import com.intellij.ui.FontSizeModel
import com.intellij.ui.PopupHandler
import com.intellij.util.flow.collectLatestUndispatched
import com.intellij.util.ui.EDT
import com.intellij.util.ui.UIUtil
import com.intellij.util.ui.accessibility.ScreenReader
import kotlinx.coroutines.*
import kotlinx.coroutines.channels.BufferOverflow
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.asSharedFlow
import kotlinx.coroutines.flow.collect
import org.jetbrains.annotations.Nls
import java.awt.Color
import java.awt.Rectangle
import javax.swing.Icon
import javax.swing.JScrollPane
internal class DocumentationUI(
project: Project,
val browser: DocumentationBrowser,
) : DataProvider, Disposable {
val scrollPane: JScrollPane
val editorPane: DocumentationHintEditorPane
val fontSize: FontSizeModel = DocumentationFontSizeModel()
private val icons = mutableMapOf<String, Icon>()
private var imageResolver: DocumentationImageResolver? = null
private val linkHandler: DocumentationLinkHandler
private val cs = CoroutineScope(Dispatchers.EDT)
private val myContentUpdates = MutableSharedFlow<Unit>(replay = 1, onBufferOverflow = BufferOverflow.DROP_OLDEST)
val contentUpdates: SharedFlow<Unit> = myContentUpdates.asSharedFlow()
init {
scrollPane = DocumentationScrollPane()
editorPane = DocumentationHintEditorPane(project, DocumentationScrollPane.keyboardActions(scrollPane), {
imageResolver?.resolveImage(it)
}, { icons[it] })
scrollPane.setViewportView(editorPane)
scrollPane.addMouseWheelListener(FontSizeMouseWheelListener(fontSize))
linkHandler = DocumentationLinkHandler.createAndRegister(editorPane, this, ::linkActivated)
browser.ui = this
Disposer.register(this, browser)
for (action in linkHandler.createLinkActions()) {
action.registerCustomShortcutSet(editorPane, this)
}
registerBackForwardActions(editorPane)
val contextMenu = PopupHandler.installPopupMenu(
editorPane,
PRIMARY_GROUP_ID,
"documentation.pane.content.menu"
)
Disposer.register(this) { editorPane.removeMouseListener(contextMenu) }
DataManager.registerDataProvider(editorPane, this)
fetchingMessage()
cs.launch(CoroutineName("DocumentationUI content update"), start = CoroutineStart.UNDISPATCHED) {
browser.pageFlow.collectLatestUndispatched { page ->
handlePage(page)
}
}
cs.launch(CoroutineName("DocumentationUI font size update"), start = CoroutineStart.UNDISPATCHED) {
fontSize.updates.collect {
editorPane.applyFontProps(it)
}
}
}
override fun dispose() {
cs.cancel("DocumentationUI disposal")
clearImages()
}
override fun getData(dataId: String): Any? {
return when {
DOCUMENTATION_BROWSER.`is`(dataId) -> browser
SELECTED_QUICK_DOC_TEXT.`is`(dataId) -> editorPane.selectedText?.replace(160.toChar(), ' ') // IDEA-86633
else -> null
}
}
fun setBackground(color: Color): Disposable {
val editorBG = editorPane.background
editorPane.background = color
return Disposable {
editorPane.background = editorBG
}
}
private fun clearImages() {
icons.clear()
imageResolver = null
}
private suspend fun handlePage(page: DocumentationPage) {
val presentation = page.request.presentation
page.contentFlow.collectLatestUndispatched {
handleContent(presentation, it)
}
}
private suspend fun handleContent(presentation: TargetPresentation, pageContent: DocumentationPageContent?) {
when (pageContent) {
null -> {
// to avoid flickering: don't show ""Fetching..." message right away, give a chance for documentation to load
delay(DEFAULT_UI_RESPONSE_TIMEOUT) // this call will be immediately cancelled once a new emission happens
clearImages()
fetchingMessage()
applyUIState(UIState.Reset)
}
DocumentationPageContent.Empty -> {
clearImages()
noDocumentationMessage()
applyUIState(UIState.Reset)
}
is DocumentationPageContent.Content -> {
clearImages()
handleContent(presentation, pageContent)
}
}
}
private suspend fun handleContent(presentation: TargetPresentation, pageContent: DocumentationPageContent.Content) {
val content = pageContent.content
imageResolver = content.imageResolver
val locationChunk = getDefaultLocationChunk(presentation)
val linkChunk = linkChunk(presentation.presentableText, pageContent.links)
val decorated = decorate(content.html, locationChunk, linkChunk)
if (!updateContent(decorated)) {
return
}
val uiState = pageContent.uiState
if (uiState != null) {
yield()
applyUIState(uiState)
}
}
private fun getDefaultLocationChunk(presentation: TargetPresentation): HtmlChunk? {
return presentation.locationText?.let { locationText ->
presentation.locationIcon?.let { locationIcon ->
val iconKey = registerIcon(locationIcon)
HtmlChunk.fragment(
HtmlChunk.tag("icon").attr("src", iconKey),
HtmlChunk.nbsp(),
HtmlChunk.text(locationText)
)
} ?: HtmlChunk.text(locationText)
}
}
private fun registerIcon(icon: Icon): String {
val key = icons.size.toString()
icons[key] = icon
return key
}
private fun fetchingMessage() {
updateContent(message(CodeInsightBundle.message("javadoc.fetching.progress")))
}
private fun noDocumentationMessage() {
updateContent(message(CodeInsightBundle.message("no.documentation.found")))
}
private fun message(message: @Nls String): @Nls String {
return HtmlChunk.div()
.setClass("content-only")
.addText(message)
.wrapWith("body")
.wrapWith("html")
.toString()
}
private fun updateContent(text: @Nls String): Boolean {
EDT.assertIsEdt()
if (editorPane.text == text) {
return false
}
editorPane.text = text
check(myContentUpdates.tryEmit(Unit))
return true
}
private fun applyUIState(uiState: UIState) {
when (uiState) {
UIState.Reset -> {
editorPane.scrollRectToVisible(Rectangle(0, 0))
if (ScreenReader.isActive()) {
editorPane.caretPosition = 0
}
}
is UIState.ScrollToAnchor -> {
UIUtil.scrollToReference(editorPane, uiState.anchor)
}
is UIState.RestoreFromSnapshot -> {
uiState.snapshot.invoke()
}
}
}
private fun linkActivated(href: String) {
if (href.startsWith("#")) {
UIUtil.scrollToReference(editorPane, href.removePrefix("#"))
}
else {
browser.navigateByLink(href)
}
}
fun uiSnapshot(): UISnapshot {
EDT.assertIsEdt()
val viewRect = scrollPane.viewport.viewRect
val highlightedLink = linkHandler.highlightedLink
return {
EDT.assertIsEdt()
linkHandler.highlightLink(highlightedLink)
editorPane.scrollRectToVisible(viewRect)
if (ScreenReader.isActive()) {
editorPane.caretPosition = 0
}
}
}
}
|
apache-2.0
|
a31e9e34289e9e8fb2605df407c29c69
| 32.838583 | 120 | 0.735428 | 4.663592 | false | false | false | false |
dpisarenko/econsim-tr01
|
src/main/java/cc/altruix/econsimtr01/ch0201/TransitionReadinessColFunction.kt
|
1
|
2160
|
/*
* Copyright 2012-2016 Dmitri Pisarenko
*
* WWW: http://altruix.cc
* E-Mail: [email protected]
* Skype: dp118m (voice calls must be scheduled in advance)
*
* Physical address:
*
* 4-i Rostovskii pereulok 2/1/20
* 119121 Moscow
* Russian Federation
*
* This file is part of econsim-tr01.
*
* econsim-tr01 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.
*
* econsim-tr01 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 econsim-tr01. If not, see <http://www.gnu.org/licenses/>.
*
*/
package cc.altruix.econsimtr01.ch0201
import alice.tuprolog.Prolog
/**
* Created by pisarenko on 20.04.2016.
*/
class TransitionReadinessColFunction : ITimeSeriesFieldFillerFunction {
companion object {
val moneyInSavingsAccountExtractor = MoneyInSavingsAccountColFunction()
val peopleInListExtractor = SubscribersCohortColFunction(1)
val softwareCompletionExtractor = PercentageResourceLevelColFunction("stacy", "r14", 480.0)
}
override fun invoke(prolog: Prolog, time: Long): String
{
if (enoughMoney(prolog, time) &&
enoughPeopleInList(prolog, time) &&
softwareComplete(prolog, time)) {
return "yes"
}
return "no"
}
internal fun softwareComplete(prolog: Prolog, time: Long): Boolean =
softwareCompletionExtractor.invoke(prolog, time).toDouble() >= 100.0
internal fun enoughPeopleInList(prolog: Prolog, time: Long): Boolean =
peopleInListExtractor.invoke(prolog, time).toDouble() >= 1000.0
internal fun enoughMoney(prolog: Prolog, time: Long): Boolean =
moneyInSavingsAccountExtractor.invoke(prolog, time).toDouble() >= 3000.0
}
|
gpl-3.0
|
057d749347af47740456cb835a07be40
| 33.854839 | 99 | 0.699074 | 4.114286 | false | false | false | false |
vovagrechka/fucking-everything
|
aplight/src/main/java/aplight/aplight-1.kt
|
1
|
3618
|
package aplight
import alraune.*
import org.antlr.v4.runtime.RuleContext
import vgrechka.*
import java.util.*
import kotlin.math.max
class KoClass(
val name: String,
val fqn: String,
val props: MutableList<KoProp> = mutableListOf(),
val anns: MutableList<KoAnnotation> = mutableListOf())
class KoProp(
val name: String,
val typeGuess: String,
val annotations: MutableList<KoAnnotation>)
class KoAnnotation(
val type: String)
fun parseKoPropsInto(props: MutableList<KoProp>, classBody: KotlinParser.ClassBodyContext?) {
for (memberDecl in classBody?.members()?.memberDeclaration() ?: listOf()) {
val propertyDeclaration = memberDecl.propertyDeclaration()
if (propertyDeclaration != null) {
val variableDeclarationEntry = propertyDeclaration.variableDeclarationEntry()
val propName = variableDeclarationEntry.SimpleName().text
val typeGuess = guessType(propertyDeclaration, variableDeclarationEntry)
val annotations = mutableListOf<KoAnnotation>()
propertyDeclaration.modifiers()?.modifier()?.forEach {mod->
mod.modifierKeyword()?.annotations()?.annotation()?.forEach {ann->
annotations += KoAnnotation(type = nodesToFqn(ann.unescapedAnnotation().identifier()))
}
}
props += KoProp(name = propName, typeGuess = typeGuess, annotations = annotations)
}
}
}
fun parseKoProps(classBody: KotlinParser.ClassBodyContext?): MutableList<KoProp> {
val list = mutableListOf<KoProp>()
parseKoPropsInto(list, classBody)
return list
}
fun guessType(propertyDeclaration: KotlinParser.PropertyDeclarationContext, variableDeclarationEntry: KotlinParser.VariableDeclarationEntryContext): String {
val type = variableDeclarationEntry.type()
if (type != null) {
val userType = type.typeDescriptor().userType()
if (userType != null) {
return nodesToFqn(userType.simpleUserType())
}
}
if (propertyDeclaration.by() != null) {
val expression = propertyDeclaration.expression()
val postfixUnaryExpression = expression
?.disjunction()?.firstOrNull()
?.conjunction()?.firstOrNull()
?.equalityComparison()?.firstOrNull()
?.comparison()?.firstOrNull()
?.namedInfix()?.firstOrNull()
?.elvisExpression()?.firstOrNull()
?.infixFunctionCall()?.firstOrNull()
?.rangeExpression()?.firstOrNull()
?.additiveExpression()?.firstOrNull()
?.multiplicativeExpression()?.firstOrNull()
?.typeRHS()?.firstOrNull()
?.prefixUnaryExpression()?.firstOrNull()
?.postfixUnaryExpression()
if (postfixUnaryExpression != null) {
val identifier = postfixUnaryExpression.atomicExpression()?.identifier()
if (identifier?.text in setOf("notNull", "notNullOnce", "maybeNull", "maybeNullOnce")) {
val typeArgs = postfixUnaryExpression.callSuffix().typeArguments().type()
check(typeArgs.size == 1)
val simpleUserTypes = typeArgs.first().typeDescriptor().userType().simpleUserType()
check(simpleUserTypes.size > 0)
var typeName = nodesToFqn(simpleUserTypes)
if (identifier!!.text.contains("maybeNull"))
typeName += "?"
return typeName
}
}
}
return "boobs"
}
fun nodesToFqn(xs: List<RuleContext>) = xs.joinToString(".") {it.text}
|
apache-2.0
|
e0e499368cce554f394bd7666d9ee113
| 33.457143 | 157 | 0.638751 | 5.117397 | false | false | false | false |
GunoH/intellij-community
|
platform/workspaceModel/storage/src/com/intellij/workspaceModel/storage/impl/indices/SymbolicIdInternalIndex.kt
|
2
|
2131
|
// Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.workspaceModel.storage.impl.indices
import com.google.common.collect.HashBiMap
import com.intellij.workspaceModel.storage.SymbolicEntityId
import com.intellij.workspaceModel.storage.impl.EntityId
import org.jetbrains.annotations.TestOnly
open class SymbolicIdInternalIndex private constructor(
internal open val index: HashBiMap<EntityId, SymbolicEntityId<*>>
) {
constructor() : this(HashBiMap.create<EntityId, SymbolicEntityId<*>>())
internal fun getIdsByEntry(symbolicId: SymbolicEntityId<*>): EntityId? = index.inverse()[symbolicId]
internal fun getEntryById(id: EntityId): SymbolicEntityId<*>? = index[id]
internal fun entries(): Collection<SymbolicEntityId<*>> {
return index.values
}
class MutableSymbolicIdInternalIndex private constructor(
// Do not write to [index] directly! Create a method in this index and call [startWrite] before write.
override var index: HashBiMap<EntityId, SymbolicEntityId<*>>
) : SymbolicIdInternalIndex(index) {
private var freezed = true
internal fun index(id: EntityId, symbolicId: SymbolicEntityId<*>? = null) {
startWrite()
if (symbolicId == null) {
index.remove(id)
return
}
index[id] = symbolicId
}
@TestOnly
internal fun clear() {
startWrite()
index.clear()
}
@TestOnly
internal fun copyFrom(another: SymbolicIdInternalIndex) {
startWrite()
this.index.putAll(another.index)
}
private fun startWrite() {
if (!freezed) return
freezed = false
index = HashBiMap.create(index)
}
fun toImmutable(): SymbolicIdInternalIndex {
freezed = true
return SymbolicIdInternalIndex(this.index)
}
companion object {
fun from(other: SymbolicIdInternalIndex): MutableSymbolicIdInternalIndex {
if (other is MutableSymbolicIdInternalIndex) other.freezed = true
return MutableSymbolicIdInternalIndex(other.index)
}
}
}
}
|
apache-2.0
|
fded6f212067a4ebbf4cf435de7a917c
| 29.884058 | 140 | 0.709995 | 4.843182 | false | false | false | false |
smmribeiro/intellij-community
|
python/python-psi-impl/src/com/jetbrains/python/psi/types/PyLiteralType.kt
|
7
|
7609
|
// 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.jetbrains.python.psi.types
import com.intellij.openapi.util.Ref
import com.jetbrains.python.PyNames
import com.jetbrains.python.PyTokenTypes
import com.jetbrains.python.codeInsight.dataflow.scope.ScopeUtil
import com.jetbrains.python.codeInsight.typing.PyTypingTypeProvider
import com.jetbrains.python.psi.*
import com.jetbrains.python.psi.impl.PyEvaluator
import com.jetbrains.python.psi.impl.PyPsiUtils
import com.jetbrains.python.psi.resolve.PyResolveContext
/**
* Represents literal type introduced in PEP 586.
*/
class PyLiteralType private constructor(cls: PyClass, val expression: PyExpression) : PyClassTypeImpl(cls, false) {
override fun getName(): String = "Literal[${expression.text}]"
override fun toString(): String = "PyLiteralType: ${expression.text}"
override fun equals(other: Any?): Boolean {
return this === other || javaClass == other?.javaClass && match(this, other as PyLiteralType)
}
override fun hashCode(): Int = 31 * pyClass.hashCode()
companion object {
/**
* Tries to construct literal type for index passed to `typing.Literal[...]`
*/
fun fromLiteralParameter(expression: PyExpression, context: TypeEvalContext): PyType? =
when (expression) {
is PyTupleExpression -> {
val elements = expression.elements
val classes = elements.mapNotNull { toLiteralType(it, context, true) }
if (elements.size == classes.size) PyUnionType.union(classes) else null
}
else -> toLiteralType(expression, context, true)
}
/**
* Tries to construct literal type or collection of literal types for a value that could be downcasted to `typing.Literal[...] type
* or its collection.
*/
fun fromLiteralValue(expression: PyExpression, context: TypeEvalContext): PyType? {
val value =
when (expression) {
is PyKeywordArgument -> expression.valueExpression
is PyParenthesizedExpression -> PyPsiUtils.flattenParens(expression)
else -> expression
} ?: return null
return when (value) {
is PySequenceExpression -> {
val classes = if (value is PyDictLiteralExpression) {
val keyTypes = value.elements.map { fromLiteralValue(it.key, context) }
val valueTypes = value.elements.map { type -> type.value?.let { fromLiteralValue(it, context) } }
listOf(PyUnionType.union(keyTypes), PyUnionType.union(valueTypes))
}
else value.elements.map { fromLiteralValue(it, context) }
if (value is PyTupleExpression) {
PyTupleType.create(value, classes)
}
else {
val name = when (value) {
is PyListLiteralExpression -> "list"
is PySetLiteralExpression -> "set"
is PyDictLiteralExpression -> "dict"
else -> null
}
name?.let { PyCollectionTypeImpl.createTypeByQName(value, name, false, classes) }
}
}
else -> toLiteralType(value, context, false) ?: context.getType(value)
}
}
/**
* [actual] matches [expected] if it has the same type and its expression evaluates to the same value
*/
fun match(expected: PyLiteralType, actual: PyLiteralType): Boolean {
return expected.pyClass == actual.pyClass &&
PyEvaluator.evaluateNoResolve(expected.expression, Any::class.java) ==
PyEvaluator.evaluateNoResolve(actual.expression, Any::class.java)
}
/**
* If [expected] type is `typing.Literal[...]`,
* then tries to infer `typing.Literal[...]` for [expression],
* otherwise returns type inferred by [context].
*/
fun promoteToLiteral(expression: PyExpression,
expected: PyType?,
context: TypeEvalContext,
substitutions: PyTypeChecker.GenericSubstitutions?): PyType? {
if (expected is PyTypedDictType) {
return null
}
val substitution = substitutions?.let { PyTypeChecker.substitute(expected, it, context) }
?: if (expected is PyGenericType) expected.bound else expected
if (containsLiteral(substitution)) {
return fromLiteralValue(expression, context)
}
return null
}
private fun containsLiteral(type: PyType?): Boolean {
return type is PyLiteralType ||
type is PyUnionType && type.members.any { containsLiteral(it) } ||
type is PyCollectionType && type.elementTypes.any { containsLiteral(it) }
}
private fun toLiteralType(expression: PyExpression, context: TypeEvalContext, index: Boolean): PyType? {
if (expression is PyNoneLiteralExpression && !expression.isEllipsis ||
expression is PyReferenceExpression &&
expression.name == PyNames.NONE &&
LanguageLevel.forElement(expression).isPython2) return PyNoneType.INSTANCE
if (index && (expression is PyReferenceExpression || expression is PySubscriptionExpression)) {
val subLiteralType = Ref.deref(PyTypingTypeProvider.getType(expression, context))
if (PyTypeUtil.toStream(subLiteralType).all { it is PyLiteralType }) return subLiteralType
}
if (expression is PyReferenceExpression && expression.isQualified) {
PyUtil
.multiResolveTopPriority(expression, PyResolveContext.defaultContext(context))
.asSequence()
.filterIsInstance<PyTargetExpression>()
.mapNotNull { ScopeUtil.getScopeOwner(it) as? PyClass }
.firstOrNull { owner -> owner.getAncestorTypes(context).any { it?.classQName == "enum.Enum" } }
?.let {
val type = context.getType(it)
return if (type is PyInstantiableType<*>) type.toInstance() else type
}
}
return classOfAcceptableLiteral(expression, context, index)?.let { PyLiteralType(it, expression) }
}
private fun classOfAcceptableLiteral(expression: PyExpression, context: TypeEvalContext, index: Boolean): PyClass? {
return when {
expression is PyNumericLiteralExpression -> if (expression.isIntegerLiteral) getPyClass(expression, context) else null
expression is PyStringLiteralExpression ->
if (isAcceptableStringLiteral(expression, index)) getPyClass(expression, context) else null
expression is PyLiteralExpression -> getPyClass(expression, context)
expression is PyPrefixExpression && expression.operator == PyTokenTypes.MINUS -> {
val operand = expression.operand
if (operand is PyNumericLiteralExpression && operand.isIntegerLiteral) getPyClass(operand, context) else null
}
expression is PyReferenceExpression &&
expression.name.let { it == PyNames.TRUE || it == PyNames.FALSE } &&
LanguageLevel.forElement(expression).isPython2 -> getPyClass(expression, context)
else -> null
}
}
private fun getPyClass(expression: PyExpression, context: TypeEvalContext) = (context.getType(expression) as? PyClassType)?.pyClass
private fun isAcceptableStringLiteral(expression: PyStringLiteralExpression, index: Boolean): Boolean {
val singleElement = expression.stringElements.singleOrNull() ?: return false
return if (!index && singleElement is PyFormattedStringElement) singleElement.fragments.isEmpty()
else singleElement is PyPlainStringElement
}
}
}
|
apache-2.0
|
395c124f11b0cbaef98d637a85d63891
| 42.982659 | 140 | 0.67315 | 4.912201 | false | false | false | false |
smmribeiro/intellij-community
|
java/java-impl/src/com/intellij/codeInsight/completion/CompletionMemory.kt
|
29
|
3007
|
/*
* 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.codeInsight.completion
import com.intellij.openapi.editor.Document
import com.intellij.openapi.editor.RangeMarker
import com.intellij.openapi.util.Key
import com.intellij.openapi.util.Segment
import com.intellij.openapi.util.TextRange
import com.intellij.psi.*
import java.util.*
/**
* @author peter
*/
object CompletionMemory {
private val LAST_CHOSEN_METHODS = Key.create<LinkedList<RangeMarker>>("COMPLETED_METHODS")
private val CHOSEN_METHODS = Key.create<SmartPsiElementPointer<PsiMethod>>("CHOSEN_METHODS")
@JvmStatic
fun registerChosenMethod(method: PsiMethod, call: PsiCall) {
val nameRange = getAnchorRange(call) ?: return
val document = call.containingFile.viewProvider.document ?: return
addToMemory(document, createChosenMethodMarker(document, CompletionUtil.getOriginalOrSelf(method), nameRange))
}
private fun getAnchorRange(call: PsiCall) = when (call) {
is PsiMethodCallExpression -> call.methodExpression.referenceNameElement?.textRange
is PsiNewExpression -> call.classOrAnonymousClassReference?.referenceNameElement?.textRange
else -> null
}
private fun addToMemory(document: Document, marker: RangeMarker) {
val completedMethods = LinkedList<RangeMarker>()
document.getUserData(LAST_CHOSEN_METHODS)?.let { completedMethods.addAll(it.filter { it.isValid && !haveSameRange(it, marker) }) }
while (completedMethods.size > 10) {
completedMethods.removeAt(0)
}
document.putUserData(LAST_CHOSEN_METHODS, completedMethods)
completedMethods.add(marker)
}
private fun createChosenMethodMarker(document: Document, method: PsiMethod, nameRange: TextRange): RangeMarker {
val marker = document.createRangeMarker(nameRange.startOffset, nameRange.endOffset)
marker.putUserData(CHOSEN_METHODS, SmartPointerManager.getInstance(method.project).createSmartPsiElementPointer(method))
return marker
}
@JvmStatic
fun getChosenMethod(call: PsiCall): PsiMethod? {
val range = getAnchorRange(call) ?: return null
val completedMethods = call.containingFile.viewProvider.document?.getUserData(LAST_CHOSEN_METHODS)
val marker = completedMethods?.let { it.find { m -> haveSameRange(m, range) } }
return marker?.getUserData(CHOSEN_METHODS)?.element
}
private fun haveSameRange(s1: Segment, s2: Segment) = s1.startOffset == s2.startOffset && s1.endOffset == s2.endOffset
}
|
apache-2.0
|
03bc42cacd234200a69317359b58090f
| 40.777778 | 134 | 0.763219 | 4.357971 | false | false | false | false |
android/sunflower
|
app/src/main/java/com/google/samples/apps/sunflower/data/GardenPlantingRepository.kt
|
1
|
1658
|
/*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.sunflower.data
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class GardenPlantingRepository @Inject constructor(
private val gardenPlantingDao: GardenPlantingDao
) {
suspend fun createGardenPlanting(plantId: String) {
val gardenPlanting = GardenPlanting(plantId)
gardenPlantingDao.insertGardenPlanting(gardenPlanting)
}
suspend fun removeGardenPlanting(gardenPlanting: GardenPlanting) {
gardenPlantingDao.deleteGardenPlanting(gardenPlanting)
}
fun isPlanted(plantId: String) =
gardenPlantingDao.isPlanted(plantId)
fun getPlantedGardens() = gardenPlantingDao.getPlantedGardens()
companion object {
// For Singleton instantiation
@Volatile private var instance: GardenPlantingRepository? = null
fun getInstance(gardenPlantingDao: GardenPlantingDao) =
instance ?: synchronized(this) {
instance ?: GardenPlantingRepository(gardenPlantingDao).also { instance = it }
}
}
}
|
apache-2.0
|
0798a7d2166c1a574423dd51dc5b5805
| 31.509804 | 94 | 0.729192 | 4.530055 | false | false | false | false |
myunusov/maxur-mserv
|
maxur-mserv-core/src/test/kotlin/org/maxur/mserv/frame/rest/ServiceResourceIT.kt
|
1
|
1473
|
package org.maxur.mserv.frame.rest
import org.assertj.core.api.Assertions.assertThat
import org.glassfish.hk2.utilities.binding.AbstractBinder
import org.junit.Test
import org.junit.runner.RunWith
import org.maxur.mserv.frame.MicroService
import org.mockito.Mock
import org.mockito.Mockito.`when`
import org.mockito.junit.MockitoJUnitRunner
import java.io.IOException
import kotlin.reflect.KClass
@RunWith(MockitoJUnitRunner::class)
class ServiceResourceIT : AbstractResourceAT() {
@Mock
private lateinit var service: MicroService
override fun resourceClass(): KClass<out Any> = ServiceResource::class
override fun configurator(): Function1<AbstractBinder, Unit> = { binder: AbstractBinder ->
binder.bind(service).to(MicroService::class.java)
}
@Test
@Throws(IOException::class)
fun testServiceResourceSelf() {
`when`(service.version).thenReturn("0.1")
`when`(service.name).thenReturn("test")
val baseTarget = target("/service")
val json = baseTarget.request()
.accept("application/hal+json")
.get(String::class.java)
val node = mapper.readTree(json)
assertThat(node.findPath("name").asText())
.isEqualTo("test: 0.1")
assertThat(node.findPath("self").findPath("href").asText())
.isEqualTo("service")
assertThat(node.findPath("command").findPath("href").asText())
.isEqualTo("service/command")
}
}
|
apache-2.0
|
43494076a346030115c02ca9a5e22c2a
| 31.733333 | 94 | 0.692464 | 4.172805 | false | true | false | false |
ThiagoGarciaAlves/intellij-community
|
uast/uast-java/src/org/jetbrains/uast/java/declarations/JavaUFile.kt
|
4
|
1733
|
/*
* 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 org.jetbrains.uast.java
import com.intellij.psi.PsiComment
import com.intellij.psi.PsiJavaFile
import com.intellij.psi.PsiRecursiveElementWalkingVisitor
import org.jetbrains.uast.*
import java.util.*
class JavaUFile(override val psi: PsiJavaFile, override val languagePlugin: UastLanguagePlugin) : UFile, JvmDeclarationUElement {
override val packageName: String
get() = psi.packageName
override val imports by lz {
psi.importList?.allImportStatements?.map { JavaUImportStatement(it, this) } ?: listOf()
}
override val annotations: List<UAnnotation>
get() = psi.packageStatement?.annotationList?.annotations?.map { JavaUAnnotation(it, this) } ?: emptyList()
override val classes by lz { psi.classes.map { JavaUClass.create(it, this) } }
override val allCommentsInFile by lz {
val comments = ArrayList<UComment>(0)
psi.accept(object : PsiRecursiveElementWalkingVisitor() {
override fun visitComment(comment: PsiComment) {
comments += UComment(comment, this@JavaUFile)
}
})
comments
}
override fun equals(other: Any?) = (other as? JavaUFile)?.psi == psi
}
|
apache-2.0
|
9704689b61a15b366b5742a3d060717f
| 35.125 | 129 | 0.738027 | 4.300248 | false | false | false | false |
xaethos/tracker-notifier
|
app/src/main/java/net/xaethos/trackernotifier/adapters/ResourceAdapter.kt
|
1
|
1115
|
package net.xaethos.trackernotifier.adapters
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.ViewGroup
import net.xaethos.trackernotifier.models.Resource
import java.util.*
class ResourceAdapter<R : Resource, VH : ResourceViewHolder<R>>(
val itemViewType: Int = 0,
val viewHolderFactory: (LayoutInflater, Int, ViewGroup) -> VH) : RecyclerView.Adapter<VH>() {
private val items = ArrayList<R>()
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int) =
viewHolderFactory(LayoutInflater.from(parent.context), viewType, parent);
override fun onBindViewHolder(holder: VH, position: Int) = holder.bind(get(position))
override fun getItemId(position: Int) = get(position).id
override fun getItemViewType(position: Int) = itemViewType
override fun getItemCount() = items.size
operator fun get(position: Int) = items[position]
fun setResources(resources: Collection<R>?) {
items.clear()
if (resources != null) items.addAll(resources)
notifyDataSetChanged()
}
}
|
mit
|
5278bf9337ae146673d79ff50b32b451
| 31.794118 | 101 | 0.72287 | 4.477912 | false | false | false | false |
square/sqldelight
|
sqldelight-idea-plugin/src/test/kotlin/com/squareup/sqldelight/intellij/rename/SqliteElementTests.kt
|
1
|
5327
|
package com.squareup.sqldelight.intellij.rename
import com.squareup.sqldelight.core.lang.SqlDelightFileType
import com.squareup.sqldelight.intellij.SqlDelightFixtureTestCase
class SqliteElementTests : SqlDelightFixtureTestCase() {
fun testTableRename() {
myFixture.configureByText(
SqlDelightFileType,
"""
|CREATE TABLE <caret>test(
| value TEXT
|);
|
|CREATE TABLE otherTest(
| value TEXT REFERENCES test(value)
|);
|
|CREATE INDEX myIndex ON test(value);
|
|CREATE VIEW myView AS
|SELECT *
|FROM test;
|
|someInsert:
|INSERT INTO test
|VALUES (?);
|
|someSelect:
|SELECT *
|FROM test;
""".trimMargin()
)
myFixture.renameElementAtCaret("newTest")
myFixture.checkResult(
"""
|CREATE TABLE newTest(
| value TEXT
|);
|
|CREATE TABLE otherTest(
| value TEXT REFERENCES newTest(value)
|);
|
|CREATE INDEX myIndex ON newTest(value);
|
|CREATE VIEW myView AS
|SELECT *
|FROM newTest;
|
|someInsert:
|INSERT INTO newTest
|VALUES (?);
|
|someSelect:
|SELECT *
|FROM newTest;
""".trimMargin()
)
}
fun testColumnRename() {
myFixture.configureByText(
SqlDelightFileType,
"""
|CREATE TABLE test(
| <caret>value TEXT
|);
|
|CREATE TABLE otherTest(
| value TEXT REFERENCES test(value)
|);
|
|CREATE INDEX myIndex ON test(value);
|
|CREATE VIEW myView AS
|SELECT value
|FROM test;
|
|someInsert:
|INSERT INTO test (value)
|VALUES (?);
|
|someSelect:
|SELECT value
|FROM test;
""".trimMargin()
)
myFixture.renameElementAtCaret("newValue")
myFixture.checkResult(
"""
|CREATE TABLE test(
| newValue TEXT
|);
|
|CREATE TABLE otherTest(
| value TEXT REFERENCES test(newValue)
|);
|
|CREATE INDEX myIndex ON test(newValue);
|
|CREATE VIEW myView AS
|SELECT newValue
|FROM test;
|
|someInsert:
|INSERT INTO test (newValue)
|VALUES (?);
|
|someSelect:
|SELECT newValue
|FROM test;
""".trimMargin()
)
}
fun testViewRename() {
myFixture.configureByText(
SqlDelightFileType,
"""
|CREATE VIEW myView AS
|SELECT 1;
|
|someSelect:
|SELECT *
|FROM <caret>myView;
""".trimMargin()
)
myFixture.renameElementAtCaret("newView")
myFixture.checkResult(
"""
|CREATE VIEW newView AS
|SELECT 1;
|
|someSelect:
|SELECT *
|FROM newView;
""".trimMargin()
)
}
fun testColumnAliasRename() {
myFixture.configureByText(
SqlDelightFileType,
"""
|CREATE VIEW myView AS
|SELECT 1 AS columnAlias;
|
|someSelect:
|SELECT <caret>columnAlias
|FROM myView;
""".trimMargin()
)
myFixture.renameElementAtCaret("newAlias")
myFixture.checkResult(
"""
|CREATE VIEW myView AS
|SELECT 1 AS newAlias;
|
|someSelect:
|SELECT newAlias
|FROM myView;
""".trimMargin()
)
}
fun testTableAliasRename() {
myFixture.configureByText(
SqlDelightFileType,
"""
|CREATE VIEW myView AS
|SELECT 1 AS columnAlias;
|
|someSelect:
|SELECT tableAlias.columnAlias
|FROM myView tableAlias
|WHERE <caret>tableAlias.columnAlias = 1;
""".trimMargin()
)
myFixture.renameElementAtCaret("newAlias")
myFixture.checkResult(
"""
|CREATE VIEW myView AS
|SELECT 1 AS columnAlias;
|
|someSelect:
|SELECT newAlias.columnAlias
|FROM myView newAlias
|WHERE newAlias.columnAlias = 1;
""".trimMargin()
)
}
fun testCteTableRename() {
myFixture.configureByText(
SqlDelightFileType,
"""
|CREATE VIEW myView AS
|SELECT 1 AS columnAlias;
|
|someSelect:
|WITH tableAlias AS (
| SELECT * FROM myView
|)
|SELECT tableAlias.columnAlias
|FROM tableAlias
|WHERE <caret>tableAlias.columnAlias = 1;
""".trimMargin()
)
myFixture.renameElementAtCaret("newAlias")
myFixture.checkResult(
"""
|CREATE VIEW myView AS
|SELECT 1 AS columnAlias;
|
|someSelect:
|WITH newAlias AS (
| SELECT * FROM myView
|)
|SELECT newAlias.columnAlias
|FROM newAlias
|WHERE newAlias.columnAlias = 1;
""".trimMargin()
)
}
fun testCteColumnRename() {
myFixture.configureByText(
SqlDelightFileType,
"""
|someSelect:
|WITH test (columnAlias) AS (
| SELECT 1
|)
|SELECT test.columnAlias
|FROM test
|WHERE test.<caret>columnAlias = 1;
""".trimMargin()
)
myFixture.renameElementAtCaret("newAlias")
myFixture.checkResult(
"""
|someSelect:
|WITH test (newAlias) AS (
| SELECT 1
|)
|SELECT test.newAlias
|FROM test
|WHERE test.newAlias = 1;
""".trimMargin()
)
}
}
|
apache-2.0
|
ac5e68157191ebfc84600eed4fefd79d
| 19.488462 | 65 | 0.557162 | 4.384362 | false | true | false | false |
ibinti/intellij-community
|
platform/platform-impl/src/com/intellij/openapi/keymap/impl/MacOSDefaultKeymap.kt
|
9
|
3249
|
/*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.openapi.keymap.impl
import com.intellij.configurationStore.SchemeDataHolder
import com.intellij.openapi.actionSystem.KeyboardShortcut
import com.intellij.openapi.actionSystem.MouseShortcut
import com.intellij.openapi.actionSystem.Shortcut
import org.intellij.lang.annotations.JdkConstants
import java.awt.event.InputEvent
import javax.swing.KeyStroke
class MacOSDefaultKeymap(dataHolder: SchemeDataHolder<KeymapImpl>, defaultKeymapManager: DefaultKeymap) : DefaultKeymapImpl(dataHolder, defaultKeymapManager) {
companion object {
@JvmStatic
fun convertShortcutFromParent(shortcut: Shortcut): Shortcut {
if (shortcut is MouseShortcut) {
return _convertMouseShortcut(shortcut)
}
if (shortcut is KeyboardShortcut) {
return KeyboardShortcut(_convertKeyStroke(shortcut.firstKeyStroke), shortcut.secondKeyStroke?.let(::_convertKeyStroke))
}
return shortcut
}
}
override fun convertKeyStroke(keyStroke: KeyStroke) = _convertKeyStroke(keyStroke)
override fun convertMouseShortcut(shortcut: MouseShortcut) = _convertMouseShortcut(shortcut)
override fun convertShortcut(shortcut: Shortcut) = convertShortcutFromParent(shortcut)
}
private fun _convertKeyStroke(parentKeyStroke: KeyStroke): KeyStroke = KeyStroke.getKeyStroke(parentKeyStroke.keyCode, mapModifiers(parentKeyStroke.modifiers), parentKeyStroke.isOnKeyRelease)
private fun _convertMouseShortcut(shortcut: MouseShortcut) = MouseShortcut(shortcut.button, mapModifiers(shortcut.modifiers), shortcut.clickCount)
@JdkConstants.InputEventMask
private fun mapModifiers(@JdkConstants.InputEventMask inModifiers: Int): Int {
var modifiers = inModifiers
var meta = false
if (modifiers and InputEvent.META_MASK != 0) {
modifiers = modifiers and InputEvent.META_MASK.inv()
meta = true
}
var metaDown = false
if (modifiers and InputEvent.META_DOWN_MASK != 0) {
modifiers = modifiers and InputEvent.META_DOWN_MASK.inv()
metaDown = true
}
var control = false
if (modifiers and InputEvent.CTRL_MASK != 0) {
modifiers = modifiers and InputEvent.CTRL_MASK.inv()
control = true
}
var controlDown = false
if (modifiers and InputEvent.CTRL_DOWN_MASK != 0) {
modifiers = modifiers and InputEvent.CTRL_DOWN_MASK.inv()
controlDown = true
}
if (meta) {
modifiers = modifiers or InputEvent.CTRL_MASK
}
if (metaDown) {
modifiers = modifiers or InputEvent.CTRL_DOWN_MASK
}
if (control) {
modifiers = modifiers or InputEvent.META_MASK
}
if (controlDown) {
modifiers = modifiers or InputEvent.META_DOWN_MASK
}
return modifiers
}
|
apache-2.0
|
8038bcf363b7959b5b0494a4d6f05391
| 32.84375 | 191 | 0.756848 | 4.506241 | false | false | false | false |
proxer/ProxerLibAndroid
|
library/src/main/kotlin/me/proxer/library/entity/user/UserInfo.kt
|
2
|
1620
|
package me.proxer.library.entity.user
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
import me.proxer.library.entity.ProxerIdItem
import me.proxer.library.entity.ProxerImageItem
import java.util.Date
/**
* Entity holding all basic info of a user.
*
* @property username The username.
* @property isTeamMember If the user is a team member.
* @property isDonator If the user is currently a donator.
* @property status The current status message.
* @property lastStatusChange The time of the last status change.
* @property uploadPoints The upload points.
* @property forumPoints The forum points.
* @property animePoints The anime points.
* @property mangaPoints The manga points.
* @property infoPoints The info points.
* @property miscPoints The miscellaneous points.
*
* @author Ruben Gees
*/
@JsonClass(generateAdapter = true)
data class UserInfo(
@Json(name = "uid") override val id: String,
@Json(name = "username") val username: String,
@Json(name = "avatar") override val image: String,
@Json(name = "isTeam") val isTeamMember: Boolean,
@Json(name = "isDonator") val isDonator: Boolean,
@Json(name = "status") val status: String,
@Json(name = "status_time") val lastStatusChange: Date,
@Json(name = "points_uploads") val uploadPoints: Int,
@Json(name = "points_forum") val forumPoints: Int,
@Json(name = "points_anime") val animePoints: Int,
@Json(name = "points_manga") val mangaPoints: Int,
@Json(name = "points_info") val infoPoints: Int,
@Json(name = "points_misc") val miscPoints: Int
) : ProxerIdItem, ProxerImageItem
|
gpl-3.0
|
7990d872fe4d1ec9ce3dee2a794778cb
| 38.512195 | 65 | 0.72284 | 3.648649 | false | false | false | false |
fluidsonic/jetpack-kotlin
|
Sources/StringAttributeMap.kt
|
1
|
9123
|
package com.github.fluidsonic.jetpack
import java.util.HashMap
@Suppress("unused")
public interface StringAttribute<Value : Any>
public interface StringAttributeMap {
val attributes: Set<StringAttribute<*>>
fun containsAttribute(attribute: StringAttribute<*>) =
attributes.contains(attribute)
val entries: Set<Map.Entry<StringAttribute<*>, Any>>
fun isEmpty() =
attributes.isEmpty()
operator fun iterator(): Iterator<StringAttribute<*>> =
attributes.iterator()
val size: Int
get() = attributes.size
fun toImmutable(): StringAttributeMap =
when (size) {
0 -> EmptyStringAttributeMap
1 -> entries.first().let { SingleElementStringAttributeMap(attribute = it.key, value = it.value) }
else -> StringAttributeHashMap(entries.associateTo(HashMap(size)) { it.key to it.value })
}
fun toImmutableMap(): Map<StringAttribute<*>, Any> =
toMap().toHashMap()
fun toMap(): Map<StringAttribute<*>, Any>
fun toMutable(): MutableStringAttributeMap =
MutableStringAttributeHashMap(entries.associateTo(HashMap(size)) { it.key to it.value })
fun toMutableMap(): MutableMap<StringAttribute<*>, Any> =
toMap().toHashMap()
fun valueForAttribute(attribute: StringAttribute<*>): Any?
}
public interface MutableStringAttributeMap : StringAttributeMap {
fun clear()
override operator fun iterator(): MutableIterator<StringAttribute<*>>
fun put(attribute: StringAttribute<*>, value: Any): Any?
fun putAll(attributes: StringAttributeMap) {
for ((attribute, value) in attributes.entries) {
put(attribute, value)
}
}
fun removeAttribute(attribute: StringAttribute<*>): Any?
}
private object EmptyStringAttributeMap : StringAttributeMap {
public override val attributes: Set<StringAttribute<*>>
get() = emptySet()
public override fun containsAttribute(attribute: StringAttribute<*>) =
false
public override val entries: Set<Map.Entry<StringAttribute<*>, Any>>
get() = emptySet()
public override fun isEmpty() =
true
public override fun iterator() =
attributes.iterator()
public override val size: Int
get() = 0
public override fun toImmutable() =
this
public override fun toImmutableMap() =
emptyMap<StringAttribute<*>, Any>()
public override fun toMap() =
emptyMap<StringAttribute<*>, Any>()
public override fun toMutable() =
MutableStringAttributeHashMap()
public override fun toMutableMap() =
mutableMapOf<StringAttribute<*>, Any>()
public override fun toString() =
"{}"
public override fun valueForAttribute(attribute: StringAttribute<*>) =
null
}
private class SingleElementStringAttributeMap(
attribute: StringAttribute<*>, value: Any
) : StringAttributeMap {
private val map = mapOf(attribute to value)
public override val attributes: Set<StringAttribute<*>>
get() = map.keys
public override fun containsAttribute(attribute: StringAttribute<*>) =
map.containsKey(attribute)
public override val entries: Set<Map.Entry<StringAttribute<*>, Any>>
get() = map.entries
public override fun isEmpty() =
map.isEmpty()
public override val size: Int
get() = 1
public override fun toImmutable() =
this
public override fun toImmutableMap() =
map
public override fun toMap() =
map
public override fun toMutable(): MutableStringAttributeMap =
MutableStringAttributeHashMap(map.toHashMap())
public override fun toString() =
map.toString()
public override fun valueForAttribute(attribute: StringAttribute<*>) =
map[attribute]
}
private class StringAttributeHashMap(
internal val map: HashMap<StringAttribute<*>, Any>
) : StringAttributeMap {
public override val attributes: Set<StringAttribute<*>>
get() = map.keys
public override fun containsAttribute(attribute: StringAttribute<*>) =
map.containsKey(attribute)
public override val entries: Set<Map.Entry<StringAttribute<*>, Any>>
get() = map.entries
public override fun isEmpty() =
map.isEmpty()
public override val size: Int
get() = map.size
public override fun toImmutable() =
this
public override fun toImmutableMap() =
map
public override fun toMap() =
map
public override fun toMutable(): MutableStringAttributeMap =
MutableStringAttributeHashMap(map.toHashMap())
public override fun toString() =
map.toString()
public override fun valueForAttribute(attribute: StringAttribute<*>) =
map[attribute]
}
private class MutableStringAttributeHashMap(
internal val map: HashMap<StringAttribute<*>, Any> = hashMapOf()
) : MutableStringAttributeMap {
public override val attributes: Set<StringAttribute<*>>
get() = map.keys
public override fun clear() {
map.clear()
}
public override fun containsAttribute(attribute: StringAttribute<*>) =
map.containsKey(attribute)
override val entries: Set<Map.Entry<StringAttribute<*>, Any>>
get() = map.entries
public override fun isEmpty() =
map.isEmpty()
public override fun iterator() =
map.keys.iterator()
public override val size: Int
get() = map.size
public override fun put(attribute: StringAttribute<*>, value: Any) =
map.put(attribute, value)
public override fun putAll(attributes: StringAttributeMap) {
when (attributes) {
is StringAttributeHashMap -> map.putAll(attributes.map)
is MutableStringAttributeHashMap -> map.putAll(attributes.map)
else -> super.putAll(attributes)
}
}
public override fun removeAttribute(attribute: StringAttribute<*>) =
map.remove(attribute)
public override fun toImmutable(): StringAttributeMap =
StringAttributeHashMap(map.toHashMap())
public override fun toMap(): Map<StringAttribute<*>, Any> =
map
public override fun toMutable(): MutableStringAttributeMap =
MutableStringAttributeHashMap(map.toHashMap())
public override fun toString() =
map.toString()
public override fun valueForAttribute(attribute: StringAttribute<*>) =
map[attribute]
}
public fun emptyStringAttributes(): StringAttributeMap =
EmptyStringAttributeMap
public fun mutableStringAttributesOf(): MutableStringAttributeMap =
MutableStringAttributeHashMap()
public fun mutableStringAttributesOf(pair: Pair<StringAttribute<*>, Any>): MutableStringAttributeMap =
MutableStringAttributeHashMap(hashMapOf(pair))
public fun mutableStringAttributesOf(vararg pairs: Pair<StringAttribute<*>, Any>): MutableStringAttributeMap =
MutableStringAttributeHashMap(hashMapOf(*pairs))
public fun stringAttributesOf() =
emptyStringAttributes()
public fun stringAttributesOf(pair: Pair<StringAttribute<*>, Any>): StringAttributeMap =
SingleElementStringAttributeMap(attribute = pair.first, value = pair.second)
public fun stringAttributesOf(vararg pairs: Pair<StringAttribute<*>, Any>) =
pairs.toAttributes()
public inline operator fun <Attribute, reified Value> StringAttributeMap.get(attribute: Attribute): Value?
where Attribute : StringAttribute<out Value>, Value : Any =
valueForAttribute(attribute as StringAttribute<*>) as? Value
public fun StringAttributeMap.isNotEmpty() =
!isEmpty()
public fun MutableStringAttributeMap.put(pair: Pair<StringAttribute<*>, Any>) =
put(pair.first, pair.second)
public fun MutableStringAttributeMap.putAll(pairs: Array<Pair<StringAttribute<*>, Any>>) {
for (pair in pairs) {
put(pair)
}
}
public fun MutableStringAttributeMap.putAll(pairs: Iterable<Pair<StringAttribute<*>, Any>>) {
for (pair in pairs) {
put(pair)
}
}
public fun MutableStringAttributeMap.putAll(pairs: Sequence<Pair<StringAttribute<*>, Any>>) {
for (pair in pairs) {
put(pair)
}
}
public fun MutableStringAttributeMap.removeAttributes(attributes: Array<StringAttribute<*>>) {
for (attribute in attributes) {
removeAttribute(attribute)
}
}
public fun MutableStringAttributeMap.removeAttributes(attributes: Iterable<StringAttribute<*>>) {
for (attribute in attributes) {
removeAttribute(attribute)
}
}
public fun MutableStringAttributeMap.removeAttributes(attributes: Sequence<StringAttribute<*>>) {
for (attribute in attributes) {
removeAttribute(attribute)
}
}
public inline operator fun <Attribute, reified Value> MutableStringAttributeMap.set(attribute: Attribute, value: Value): Value?
where Attribute : StringAttribute<out Value>, Value : Any =
put(attribute = attribute, value = value) as? Value
public fun Array<out Pair<StringAttribute<*>, Any>>.toAttributes(): StringAttributeMap =
when (size) {
0 -> emptyStringAttributes()
1 -> stringAttributesOf(this[0])
else -> StringAttributeHashMap(hashMapOf(*this))
}
public fun Iterable<Pair<StringAttribute<*>, Any>>.toAttributes(): StringAttributeMap {
if (this is Collection) {
when (size) {
0 -> return emptyStringAttributes()
1 -> return stringAttributesOf(if (this is List) this[0] else iterator().next())
}
}
return StringAttributeHashMap(toMap(hashMapOf()))
}
public fun Sequence<Pair<StringAttribute<*>, Any>>.toAttributes(): StringAttributeMap =
StringAttributeHashMap(toMap(hashMapOf()))
public infix fun <Attribute, Value> Attribute.with(value: Value)
where Attribute : StringAttribute<Value>, Value : Any
= this to value
|
mit
|
ea0f677ed18a40d7d41da6b7b87a62f9
| 21.305623 | 127 | 0.740327 | 4.182944 | false | false | false | false |
Stargamers/FastHub
|
app/src/main/java/com/fastaccess/ui/modules/editor/comment/CommentEditorFragment.kt
|
4
|
6924
|
package com.fastaccess.ui.modules.editor.comment
import android.annotation.SuppressLint
import android.app.Activity
import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.support.transition.TransitionManager
import android.support.v4.app.FragmentManager
import android.view.View
import android.view.ViewGroup
import android.widget.EditText
import butterknife.BindView
import butterknife.OnClick
import com.fastaccess.R
import com.fastaccess.helper.BundleConstant
import com.fastaccess.helper.Bundler
import com.fastaccess.helper.InputHelper
import com.fastaccess.helper.ViewHelper
import com.fastaccess.provider.emoji.Emoji
import com.fastaccess.ui.base.BaseFragment
import com.fastaccess.ui.base.mvp.BaseMvp
import com.fastaccess.ui.base.mvp.presenter.BasePresenter
import com.fastaccess.ui.modules.editor.EditorActivity
import com.fastaccess.ui.modules.editor.emoji.EmojiMvp
import com.fastaccess.ui.modules.editor.popup.EditorLinkImageMvp
import com.fastaccess.ui.widgets.markdown.MarkDownLayout
import com.fastaccess.ui.widgets.markdown.MarkdownEditText
import net.yslibrary.android.keyboardvisibilityevent.KeyboardVisibilityEvent
import net.yslibrary.android.keyboardvisibilityevent.Unregistrar
/**
* Created by kosh on 21/08/2017.
*/
class CommentEditorFragment : BaseFragment<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>(), MarkDownLayout.MarkdownListener,
EmojiMvp.EmojiCallback, EditorLinkImageMvp.EditorLinkCallback {
@BindView(R.id.commentBox) lateinit var commentBox: View
@BindView(R.id.markdDownLayout) lateinit var markdDownLayout: MarkDownLayout
@BindView(R.id.commentText) lateinit var commentText: MarkdownEditText
@BindView(R.id.markdownBtnHolder) lateinit var markdownBtnHolder: View
@BindView(R.id.sendComment) lateinit var sendComment: View
@BindView(R.id.toggleButtons) lateinit var toggleButtons: View
private var commentListener: CommentListener? = null
private var keyboardListener: Unregistrar? = null
@OnClick(R.id.sendComment) internal fun onComment() {
if (!InputHelper.isEmpty(getEditText())) {
commentListener?.onSendActionClicked(InputHelper.toString(getEditText()), arguments?.getBundle(BundleConstant.ITEM))
ViewHelper.hideKeyboard(getEditText())
arguments = null
}
}
@OnClick(R.id.fullScreenComment) internal fun onExpandScreen() {
val intent = Intent(context, EditorActivity::class.java)
intent.putExtras(Bundler.start()
.put(BundleConstant.EXTRA_TYPE, BundleConstant.ExtraType.FOR_RESULT_EXTRA)
.put(BundleConstant.EXTRA, getEditText().text.toString())
.putStringArrayList("participants", commentListener?.getNamesToTag())
.end())
startActivityForResult(intent, BundleConstant.REQUEST_CODE)
}
@OnClick(R.id.toggleButtons) internal fun onToggleButtons(v: View) {
TransitionManager.beginDelayedTransition((view as ViewGroup?)!!)
v.isActivated = !v.isActivated
markdownBtnHolder.visibility = if (markdownBtnHolder.visibility == View.VISIBLE) View.GONE else View.VISIBLE
}
override fun onAttach(context: Context?) {
super.onAttach(context)
if (parentFragment is CommentListener) {
commentListener = parentFragment as CommentListener
} else if (context is CommentListener) {
commentListener = context
}
}
override fun onDetach() {
commentListener = null
super.onDetach()
}
override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter()
override fun fragmentLayout(): Int = R.layout.comment_box_layout
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
arguments?.let {
val hideSendButton = it.getBoolean(BundleConstant.YES_NO_EXTRA)
if (hideSendButton) {
sendComment.visibility = View.GONE
}
}
markdDownLayout.markdownListener = this
if (savedInstanceState == null) {
arguments?.getBundle(BundleConstant.ITEM)?.getString(BundleConstant.EXTRA)?.let { commentText.setText(it) }
}
}
override fun onStart() {
super.onStart()
keyboardListener = KeyboardVisibilityEvent.registerEventListener(activity, {
TransitionManager.beginDelayedTransition((view as ViewGroup?)!!)
toggleButtons.isActivated = it
markdownBtnHolder.visibility = if (!it) View.GONE else View.VISIBLE
})
}
override fun onStop() {
keyboardListener?.unregister()
super.onStop()
}
override fun getEditText(): EditText = commentText
override fun fragmentManager(): FragmentManager = childFragmentManager
override fun getSavedText(): CharSequence? = commentText.savedText
override fun onEmojiAdded(emoji: Emoji?) = markdDownLayout.onEmojiAdded(emoji)
@SuppressLint("SetTextI18n")
fun onCreateComment(text: String, bundle: Bundle?) {
arguments = Bundler.start().put(BundleConstant.ITEM, bundle).end()
commentText.setText("${if (commentText.text.isNullOrBlank()) "" else "${commentText.text} "}$text")
getEditText().setSelection(getEditText().text.length)
commentText.requestFocus()
ViewHelper.showKeyboard(commentText)
}
fun onAddUserName(username: String) {
getEditText().setText(if (getEditText().text.isNullOrBlank()) {
"@$username"
} else {
"${getEditText().text} @$username"
})
getEditText().setSelection(getEditText().text.length)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
if (resultCode == Activity.RESULT_OK) {
if (requestCode == BundleConstant.REQUEST_CODE) {
val text = data?.extras?.getCharSequence(BundleConstant.EXTRA)
getEditText().setText(text)
getEditText().setSelection(getEditText().text.length)
}
}
}
override fun onAppendLink(title: String?, link: String?, isLink: Boolean) {
markdDownLayout.onAppendLink(title, link, isLink)
}
interface CommentListener {
fun onCreateComment(text: String, bundle: Bundle?) {}
fun onSendActionClicked(text: String, bundle: Bundle?)
fun onTagUser(username: String)
fun onClearEditText()
fun getNamesToTag(): ArrayList<String>?
}
companion object {
fun newInstance(bundle: Bundle?): CommentEditorFragment {
val fragment = CommentEditorFragment()
bundle?.let {
fragment.arguments = Bundler.start().put(BundleConstant.ITEM, bundle).end()
}
return fragment
}
}
}
|
gpl-3.0
|
bdb41cacd6852706fb8929d107160bbd
| 38.798851 | 128 | 0.700318 | 4.755495 | false | false | false | false |
AsynkronIT/protoactor-kotlin
|
proto-actor/src/main/kotlin/actor/proto/Props.kt
|
1
|
2219
|
package actor.proto
import actor.proto.mailbox.Dispatcher
import actor.proto.mailbox.Mailbox
import actor.proto.mailbox.newUnboundedMailbox
typealias Receive = suspend (Context) -> Unit
typealias Send = suspend (SenderContext, PID, MessageEnvelope) -> Unit
typealias ReceiveMiddleware = (Receive) -> Receive
typealias SenderMiddleware = (Send) -> Send
data class Props(
val spawner: (name: String, props: Props, parent: PID?) -> PID = ::defaultSpawner,
val producer: (() -> Actor)? = null,
val mailboxProducer: () -> Mailbox = { newUnboundedMailbox() },
val supervisorStrategy: SupervisorStrategy = Supervision.defaultStrategy,
val dispatcher: Dispatcher = actor.proto.mailbox.Dispatchers.DEFAULT_DISPATCHER,
val receiveMiddleware: List<ReceiveMiddleware> = listOf(),
val senderMiddleware: List<SenderMiddleware> = listOf()
) {
fun withChildSupervisorStrategy(supervisorStrategy: SupervisorStrategy): Props = copy(supervisorStrategy = supervisorStrategy)
fun withMailbox(mailboxProducer: () -> Mailbox): Props = copy(mailboxProducer = mailboxProducer)
fun withDispatcher(dispatcher: Dispatcher): Props = copy(dispatcher = dispatcher)
}
internal fun Props.spawn(name: String, parent: PID?): PID = spawner(name, this, parent)
fun Props.withProducer(producer: () -> Actor): Props = copy(producer = producer)
fun Props.withSpawner(spawner: (String, Props, PID?) -> PID): Props = copy(spawner = spawner)
fun Props.withSenderMiddleware(vararg middleware: SenderMiddleware): Props = copy(senderMiddleware = middleware.toList())
fun Props.withReceiveMiddleware(vararg middleware: ReceiveMiddleware): Props = copy(receiveMiddleware = middleware.toList())
fun defaultSpawner(name: String, props: Props, parent: PID?): PID {
val mailbox = props.mailboxProducer()
val dispatcher = props.dispatcher
val process = LocalProcess(mailbox)
val self = ProcessRegistry.put(name, process)
val ctx = ActorContext(props.producer!!, self, props.supervisorStrategy, props.receiveMiddleware, props.senderMiddleware, parent)
mailbox.registerHandlers(ctx, dispatcher)
mailbox.postSystemMessage(Started)
mailbox.start()
return self
}
|
apache-2.0
|
e02c45247673c10413a0fda731cd303d
| 46.212766 | 133 | 0.746282 | 4.29207 | false | false | false | false |
RichoDemus/kotlin-test
|
src/main/kotlin/demo/functional_refactoring/FunctionalStuff.kt
|
1
|
1011
|
package demo.functional_refactoring
internal class FunctionalStuff {
private val countries = listOf("Sweden", "Norway", "Finland")
private val cities = mapOf(
Pair("Sweden", listOf("Stockholm", "Västerås")),
Pair("Norway", listOf("Oslo")),
Pair("Finland", listOf("Helsinki")))
private val people = mapOf(
Pair("Stockholm", listOf("Erik", "Lotta", "Lisa")),
Pair("Västerås", listOf("Sven", "Nina")),
Pair("Oslo", listOf("Yngwe")),
Pair("Helsinki", listOf("Kim")))
fun getAllCountries() = countries
fun getCitiesByCountry(country: String) = cities.getOrElse(country, {listOf()})
fun getInhabitantsByCity(city: String) = people.getOrElse(city, {listOf()})
fun getAllPeople() = getAllCountries()
.flatMap { getCitiesByCountry(it) }
.flatMap { getInhabitantsByCity(it) }
}
internal fun main(args : Array<String>) = FunctionalStuff().getAllPeople().forEach { println(it) }
|
apache-2.0
|
c59afff24f2364af5cf4d2516c1d7f44
| 40.958333 | 98 | 0.623635 | 3.933594 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/LorittaDiscordStuff.kt
|
1
|
6751
|
/* package net.perfectdreams.loritta.cinnamon.discord
import dev.kord.common.annotation.KordUnsafe
import dev.kord.common.entity.Snowflake
import dev.kord.core.entity.User
import dev.kord.rest.ratelimit.ParallelRequestRateLimiter
import dev.kord.rest.request.KtorRequestException
import dev.kord.rest.request.KtorRequestHandler
import dev.kord.rest.service.RestClient
import kotlinx.datetime.Clock
import kotlinx.serialization.SerializationException
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.decodeFromJsonElement
import kotlinx.serialization.json.encodeToJsonElement
import kotlinx.serialization.json.jsonObject
import net.perfectdreams.loritta.cinnamon.discord.utils.BetterSTRecoveringKtorRequestHandler
import net.perfectdreams.loritta.cinnamon.discord.utils.ComponentDataUtils
import net.perfectdreams.loritta.cinnamon.discord.utils.StoredGenericInteractionData
import net.perfectdreams.loritta.cinnamon.discord.utils.config.LorittaDiscordConfig
import net.perfectdreams.loritta.cinnamon.pudding.Pudding
import net.perfectdreams.loritta.cinnamon.pudding.data.CachedUserInfo
import net.perfectdreams.loritta.cinnamon.pudding.data.UserId
import kotlin.time.Duration
import kotlin.time.Duration.Companion.minutes
abstract class LorittaDiscordStuff(
val discordConfig: LorittaDiscordConfig,
val pudding: Pudding
) {
@OptIn(KordUnsafe::class)
val rest = RestClient(
BetterSTRecoveringKtorRequestHandler(
KtorRequestHandler(
discordConfig.token,
// By default, Kord uses ExclusionRequestRateLimiter, and that suspends all coroutines if a request is ratelimited
// So we need to use the ParallelRequestRateLimiter
requestRateLimiter = ParallelRequestRateLimiter()
)
)
)
suspend fun getCachedUserInfo(userId: Snowflake) = getCachedUserInfo(UserId(userId.value))
suspend fun getCachedUserInfo(userId: UserId): CachedUserInfo? {
// First, try getting the cached user info from the database
val cachedUserInfoFromDatabase = pudding.users.getCachedUserInfoById(userId)
if (cachedUserInfoFromDatabase != null)
return cachedUserInfoFromDatabase
// If not present, get it from Discord!
val restUser = try {
rest.user.getUser(Snowflake(userId.value))
} catch (e: KtorRequestException) {
null
}
if (restUser != null) {
// If the REST user really exists, then let's update it in our database and then return the cached user info
pudding.users.insertOrUpdateCachedUserInfo(
UserId(restUser.id.value),
restUser.username,
restUser.discriminator,
restUser.avatar
)
return CachedUserInfo(
UserId(restUser.id.value),
restUser.username,
restUser.discriminator,
restUser.avatar
)
}
return null
}
suspend fun insertOrUpdateCachedUserInfo(user: User) {
pudding.users.insertOrUpdateCachedUserInfo(
UserId(user.id.value),
user.username,
user.discriminator,
user.data.avatar
)
}
suspend inline fun <reified T> encodeDataForComponentOnDatabase(data: T, ttl: Duration = 15.minutes): ComponentOnDatabaseStoreResult<T> {
// Can't fit on a button... Let's store it on the database!
val now = Clock.System.now()
val interactionDataId = pudding.interactionsData.insertInteractionData(
Json.encodeToJsonElement<T>(
data
).jsonObject,
now,
now + ttl
)
val storedGenericInteractionData = StoredGenericInteractionData(ComponentDataUtils.KTX_SERIALIZATION_SIMILAR_PROTOBUF_STRUCTURE_ISSUES_WORKAROUND_DUMMY, interactionDataId)
return ComponentOnDatabaseStoreResult(
interactionDataId,
storedGenericInteractionData,
ComponentDataUtils.encode(storedGenericInteractionData)
)
}
suspend inline fun <reified T> decodeDataFromComponentOnDatabase(data: String): ComponentOnDatabaseQueryResult<T> {
val genericInteractionData = ComponentDataUtils.decode<StoredGenericInteractionData>(data)
val dataFromDatabase = pudding.interactionsData.getInteractionData(genericInteractionData.interactionDataId)
?.jsonObject ?: return ComponentOnDatabaseQueryResult(genericInteractionData, null)
return ComponentOnDatabaseQueryResult(genericInteractionData, Json.decodeFromJsonElement<T>(dataFromDatabase))
}
/**
* Encodes the [data] to fit on a button. If it doesn't fit in a button, a [StoredGenericInteractionData] will be encoded instead and the data will be stored on the database.
*/
suspend inline fun <reified T> encodeDataForComponentOrStoreInDatabase(data: T, ttl: Duration = 15.minutes): String {
val encoded = ComponentDataUtils.encode(data)
// Let's suppose that all components always have 5 characters at the start
// (Technically it is true: Discord InteraKTions uses ":" as the separator, and we only use 4 chars for ComponentExecutorIds)
val padStart = 5 // "0000:"
if (100 - padStart >= encoded.length) {
// Can fit on a button! So let's just return what we currently have
return encoded
} else {
// Can't fit on a button... Let's store it on the database!
return encodeDataForComponentOnDatabase(data, ttl).serializedData
}
}
/**
* Decodes the [data] based on the source data:
* * If [data] is a [StoredGenericInteractionData], the data will be retrieved from the database and deserialized using [T]
* * If else, the data will be deserialized using [T]
*
* This should be used in conjuction with [encodeDataForComponentOrStoreInDatabase]
*/
suspend inline fun <reified T> decodeDataFromComponentOrFromDatabase(data: String): T? {
return try {
val result = decodeDataFromComponentOnDatabase<T>(data)
result.data
} catch (e: SerializationException) {
// If the deserialization failed, then let's try deserializing as T
ComponentDataUtils.decode<T>(data)
}
}
data class ComponentOnDatabaseStoreResult<T>(
val interactionDataId: Long,
val data: StoredGenericInteractionData,
val serializedData: String
)
data class ComponentOnDatabaseQueryResult<T>(
val genericInteractionData: StoredGenericInteractionData,
val data: T?
)
} */
|
agpl-3.0
|
62e585be4c06af69d75d1fdc2789dab5
| 40.679012 | 179 | 0.69723 | 4.899129 | false | false | false | false |
LorittaBot/Loritta
|
discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/morenitta/utils/OutdatedCommandUtils.kt
|
1
|
2674
|
package net.perfectdreams.loritta.morenitta.utils
import net.perfectdreams.loritta.morenitta.LorittaBot
import net.perfectdreams.loritta.morenitta.commands.CommandContext
import net.dv8tion.jda.api.EmbedBuilder
import net.perfectdreams.loritta.common.locale.BaseLocale
import net.perfectdreams.loritta.morenitta.platform.discord.legacy.commands.DiscordCommandContext
import java.time.Instant
import java.time.ZoneOffset
import java.time.ZonedDateTime
import java.time.temporal.ChronoUnit
/**
* Utilites to ask users to use Loritta's slash commands instead of using old commands
*/
object OutdatedCommandUtils {
private val ZONE_UTC = ZoneOffset.UTC
private val MESSAGE_INTENT_DEADLINE = ZonedDateTime.of(2022, 8, 31, 0, 0, 0, 0, ZONE_UTC)
private val OUTDATED_COMMAND_WARNING_DEADLINE = MESSAGE_INTENT_DEADLINE.minusDays(7L)
suspend fun sendOutdatedCommandMessage(
context: CommandContext,
locale: BaseLocale,
slashCommandName: String,
alwaysSendOutdatedCommandWarning: Boolean = false
) {
if (alwaysSendOutdatedCommandWarning || shouldSendOutdatedCommandWarning())
context.sendMessageEmbeds(buildEmbed(locale, slashCommandName))
}
suspend fun sendOutdatedCommandMessage(
context: net.perfectdreams.loritta.morenitta.api.commands.CommandContext,
locale: BaseLocale,
slashCommandName: String,
alwaysSendOutdatedCommandWarning: Boolean = false
) {
context as DiscordCommandContext
if (alwaysSendOutdatedCommandWarning || shouldSendOutdatedCommandWarning())
context.sendMessageEmbeds(buildEmbed(locale, slashCommandName))
}
/**
* This checks if the outdated command warning should be sent or not, based on the amount of days between now and the deadline date
*/
private fun shouldSendOutdatedCommandWarning(): Boolean {
val now = Instant.now()
val dayDiff = now.until(OUTDATED_COMMAND_WARNING_DEADLINE, ChronoUnit.DAYS)
return LorittaBot.RANDOM.nextLong(0, dayDiff.coerceAtLeast(1L)) == 0L
}
private fun buildEmbed(locale: BaseLocale, slashCommandName: String) = EmbedBuilder()
.setTitle("${locale["commands.outdatedCommand.title"]} <:lori_zap:956404868417990776>")
.setDescription(
locale.getList(
"commands.outdatedCommand.description",
slashCommandName,
"https://discord.gg/lori",
"<:lori_yay:1014022521739280454>",
"<:lori_lurk:1012854272817381487>",
).joinToString("\n")
)
.setColor(Constants.ROBLOX_RED) // heh
.build()
}
|
agpl-3.0
|
2be92a3f76d948ed21f1c88019da319b
| 40.796875 | 135 | 0.711668 | 4.555366 | false | false | false | false |
cbeyls/fosdem-companion-android
|
app/src/main/java/be/digitalia/fosdem/utils/FragmentExt.kt
|
1
|
1528
|
package be.digitalia.fosdem.utils
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentFactory
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.LifecycleOwner
/**
* A Lazy implementation which can only be called when a fragment has a view
* and will automatically clear the value when the view hierarchy gets destroyed.
*/
fun <T : Any> Fragment.viewLifecycleLazy(initializer: () -> T): Lazy<T> = ViewLifecycleLazy(this, initializer)
private class ViewLifecycleLazy<T : Any>(private val fragment: Fragment, private val initializer: () -> T) : Lazy<T>, LifecycleEventObserver {
private var cached: T? = null
override val value: T
get() {
return cached ?: run {
val newValue = initializer()
cached = newValue
fragment.viewLifecycleOwner.lifecycle.addObserver(this)
newValue
}
}
override fun isInitialized() = cached != null
override fun toString() = cached.toString()
override fun onStateChanged(source: LifecycleOwner, event: Lifecycle.Event) {
if (event == Lifecycle.Event.ON_DESTROY) {
cached = null
}
}
}
fun FragmentFactory.instantiate(fragmentClass: Class<out Fragment>): Fragment {
return instantiate(fragmentClass.classLoader!!, fragmentClass.name)
}
inline fun <reified T : Fragment> FragmentFactory.instantiate(): Fragment {
return instantiate(T::class.java)
}
|
apache-2.0
|
d61de6b08cc6b1b373a285905c055daa
| 32.977778 | 142 | 0.695026 | 4.805031 | false | false | false | false |
CCI-MIT/Mailhandler
|
src/main/java/org/xcolab/mailhandler/service/SpamFilterService.kt
|
1
|
3116
|
package org.xcolab.mailhandler.service
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.boot.context.properties.EnableConfigurationProperties
import org.springframework.stereotype.Service
import org.xcolab.mailhandler.config.SpamSettings
import org.xcolab.mailhandler.pojo.ParsedEmail
import org.xcolab.mailhandler.pojo.SpamReport
@Service
@EnableConfigurationProperties(SpamSettings::class)
class SpamFilterService
@Autowired constructor(spamSettings: SpamSettings) {
val filterThreshold = spamSettings.filter.threshold
val warningThreshold = spamSettings.warning.threshold
val isFilterEnabled = spamSettings.filter.isEnabled
val isShowReportOnWarning = spamSettings.warning.isShowReport
val isShowScoreOnWarning = spamSettings.warning.isShowScore
val isWarningEnabled = spamSettings.warning.isEnabled
val filterPhrases: List<String> = spamSettings.filter.phrases
fun shouldFilterMessage(parsedEmail: ParsedEmail, spamReport: SpamReport): Boolean {
return (isFilterEnabled && spamReport.score > filterThreshold)
|| filterPhrases.any { parsedEmail.html.contains(it) }
|| filterPhrases.any { parsedEmail.text.contains(it) }
|| filterPhrases.any { parsedEmail.subject.contains(it) }
}
fun formatEmailWithSpamReport(parsedEmail: ParsedEmail, spamReport: SpamReport): ParsedEmail {
return parsedEmail.copy(
subject = formatSubjectWithSpamReport(parsedEmail.subject, spamReport),
html = formatBodyWithSpamReport(parsedEmail.html, true, spamReport),
text = formatBodyWithSpamReport(parsedEmail.text, false, spamReport)
)
}
private fun formatSubjectWithSpamReport(subject: String, spamReport: SpamReport): String {
if (shouldShowSpamWarning(spamReport)) {
return getWarning(spamReport) + subject;
}
return subject
}
private fun shouldShowSpamReport(spamReport: SpamReport): Boolean {
return isShowReportOnWarning && shouldShowSpamWarning(spamReport)
}
private fun getWarning(spamReport: SpamReport): String {
val s = "[Potential Spam] "
if (isShowScoreOnWarning) {
return s + "[SpamScore: ${spamReport.score}] "
}
return s
}
private fun formatBodyWithSpamReport(body: String, asHtml: Boolean,
spamReport: SpamReport): String {
if (shouldShowSpamReport(spamReport)) {
return body + formatSpamReport(spamReport, asHtml)
}
return body
}
private fun shouldShowSpamWarning(spamReport: SpamReport): Boolean {
return isWarningEnabled && spamReport.score > warningThreshold
}
private fun formatSpamReport(spamReport: SpamReport, asHtml: Boolean): String {
val sb = StringBuilder()
if (asHtml) {
sb.append("<br/><br/>=======<br/><br/>")
} else {
sb.append("\n\n=======\n\n")
}
sb.append(spamReport)
return sb.toString()
}
}
|
mit
|
18b4083f51b96d507cef0c926b4b9f76
| 38.443038 | 98 | 0.688703 | 4.464183 | false | false | false | false |
simonorono/SRSM
|
src/main/kotlin/srsm/data/FotoDB.kt
|
1
|
2144
|
/*
* Copyright 2016 Sociedad Religiosa Servidores de María
*
* 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 srsm.data
import srsm.G
import srsm.model.Servidor
import java.sql.Connection
object FotoDB {
private fun conn(): Connection {
return G.db.dataSource.connection
}
private fun hasFoto(id: Int): Boolean {
conn().use { c ->
c.prepareStatement("SELECT 1 FROM foto WHERE servidorId = ?;").use { s ->
s.setInt(1, id)
s.executeQuery().use { rs ->
return rs.next()
}
}
}
}
private fun getFoto(id: Int): ByteArray {
conn().use { c ->
c.prepareStatement("SELECT foto FROM foto WHERE servidorId = ?;").use { s ->
s.setInt(1, id)
s.executeQuery().use { rs ->
if (rs.next()) {
return rs.getBytes(1)
}
}
}
}
return ByteArray(0)
}
fun getFoto(s: Servidor) = getFoto(s.id ?: 0)
private fun setFoto(id: Int, bytes: ByteArray) {
conn().use { c ->
if (hasFoto(id)) {
c.prepareStatement("UPDATE foto SET foto = ? WHERE servidorId = ?;")
} else {
c.prepareStatement("INSERT INTO foto (foto, servidorId) VALUES (?, ?);")
}.use { s ->
s.setBytes(1, bytes)
s.setInt(2, id)
s.executeUpdate()
}
}
}
fun setFoto(s: Servidor, foto: ByteArray) = setFoto(s.id ?: 0, foto)
}
|
apache-2.0
|
0c7896a1988898662cd1acfe82043d6a
| 29.183099 | 88 | 0.545497 | 4.043396 | false | false | false | false |
android/app-bundle-samples
|
InstantApps/install-api/app/src/main/java/com/google/android/instantapps/samples/install/InstallApiActivity.kt
|
1
|
2489
|
/*
* Copyright (C) 2019 Google Inc. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.instantapps.samples.install
import android.content.Intent
import android.net.Uri
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity
import com.google.android.gms.instantapps.InstantApps
/**
* An Activity that shows usage of the Install API, [documented here](https://developer.android.com/topic/instant-apps/reference.html#showinstallprompt).
*
* This sample does not have an installed app counterpart from the Play Store.
* To see how this sample works, follow the instructions in the accompanying README.md
*/
class InstallApiActivity : AppCompatActivity() {
/**
* Intent to launch after the app has been installed.
*/
private val postInstallIntent = Intent(
Intent.ACTION_VIEW,
Uri.parse("https://install-api.instantappsample.com/")
).addCategory(Intent.CATEGORY_BROWSABLE).putExtras(Bundle().apply {
putString("The key to", "sending data via intent")
})
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_install)
val isInstantApp = InstantApps.getPackageManagerCompat(this).isInstantApp
findViewById<Button>(R.id.start_installation).apply {
isEnabled = isInstantApp
// Show the installation prompt only for an instant app.
if (isInstantApp) {
setOnClickListener {
InstantApps.showInstallPrompt(
this@InstallApiActivity,
postInstallIntent,
REQUEST_CODE,
REFERRER
)
}
}
}
}
companion object {
private val REFERRER = "InstallApiActivity"
private val REQUEST_CODE = 7
}
}
|
apache-2.0
|
63216f395218b36bd0d9dfb473c31242
| 36.712121 | 153 | 0.673363 | 4.652336 | false | false | false | false |
Shynixn/PetBlocks
|
petblocks-bukkit-plugin/petblocks-bukkit-nms-117R1/src/main/java/com/github/shynixn/petblocks/bukkit/logic/business/nms/v1_17_R1/NMSPetVillager.kt
|
1
|
4878
|
package com.github.shynixn.petblocks.bukkit.logic.business.nms.v1_17_R1
import com.github.shynixn.petblocks.api.PetBlocksApi
import com.github.shynixn.petblocks.api.business.proxy.PathfinderProxy
import com.github.shynixn.petblocks.api.business.service.ConcurrencyService
import com.github.shynixn.petblocks.api.persistence.entity.AIMovement
import net.minecraft.core.BlockPosition
import net.minecraft.world.entity.Entity
import net.minecraft.world.entity.EntityTypes
import net.minecraft.world.entity.ai.attributes.GenericAttributes
import net.minecraft.world.entity.ai.goal.PathfinderGoal
import net.minecraft.world.entity.ai.goal.PathfinderGoalSelector
import net.minecraft.world.entity.animal.EntityPig
import net.minecraft.world.level.block.state.IBlockData
import org.bukkit.Bukkit
import org.bukkit.Location
import org.bukkit.craftbukkit.v1_17_R1.CraftServer
import org.bukkit.craftbukkit.v1_17_R1.CraftWorld
import org.bukkit.event.entity.CreatureSpawnEvent
/**
* NMS implementation of the Villager pet backend.
*/
class NMSPetVillager(petDesign: NMSPetArmorstand, location: Location) :
EntityPig(EntityTypes.an, (location.world as CraftWorld).handle) {
private var petDesign: NMSPetArmorstand? = null
// Pathfinders need to be self cached for Paper.
private var initialClear = true
private var pathfinderCounter = 0
private var cachedPathfinders = HashSet<PathfinderGoal>()
// BukkitEntity has to be self cached since 1.14.
private var entityBukkit: Any? = null
init {
this.petDesign = petDesign
this.isSilent = true
clearAIGoals()
this.getAttributeInstance(GenericAttributes.d)!!.value = 0.30000001192092896 * 0.75
this.O = 1.0F
val mcWorld = (location.world as CraftWorld).handle
this.setPosition(location.x, location.y - 200, location.z)
mcWorld.addEntity(this, CreatureSpawnEvent.SpawnReason.CUSTOM)
val targetLocation = location.clone()
PetBlocksApi.resolve(ConcurrencyService::class.java).runTaskSync(20L) {
// Only fix location if it is not already fixed.
if (this.bukkitEntity.location.distance(targetLocation) > 20) {
this.setPosition(targetLocation.x, targetLocation.y + 1.0, targetLocation.z)
}
}
}
/**
* Applies pathfinders to the entity.
*/
fun applyPathfinders(pathfinders: List<Any>) {
clearAIGoals()
pathfinderCounter = 0
val proxies = HashMap<PathfinderProxy, CombinedPathfinder.Cache>()
val hyperPathfinder = CombinedPathfinder(proxies)
for (pathfinder in pathfinders) {
if (pathfinder is PathfinderProxy) {
val wrappedPathfinder = Pathfinder(pathfinder)
this.cachedPathfinders.add(wrappedPathfinder)
proxies[pathfinder] = CombinedPathfinder.Cache()
val aiBase = pathfinder.aiBase
if (aiBase is AIMovement) {
this.getAttributeInstance(GenericAttributes.d)!!.value =
0.30000001192092896 * aiBase.movementSpeed
this.O = aiBase.climbingHeight.toFloat()
}
} else {
// goalSelector
this.bP.a(pathfinderCounter++, pathfinder as PathfinderGoal)
this.cachedPathfinders.add(pathfinder)
}
}
this.bP.a(pathfinderCounter++, hyperPathfinder)
this.cachedPathfinders.add(hyperPathfinder)
}
/**
* Gets called on move to play sounds.
*/
override fun b(blockposition: BlockPosition, iblockdata: IBlockData) {
if (petDesign == null) {
return
}
if (!this.isInWater) {
petDesign!!.proxy.playMovementEffects()
}
}
/**
* Disable health.
*/
override fun setHealth(f: Float) {
}
/**
* Gets the bukkit entity.
*/
override fun getBukkitEntity(): CraftPet {
if (this.entityBukkit == null) {
entityBukkit = CraftPet(Bukkit.getServer() as CraftServer, this)
val field = Entity::class.java.getDeclaredField("bukkitEntity")
field.isAccessible = true
field.set(this, entityBukkit)
}
return this.entityBukkit as CraftPet
}
/**
* Clears all entity aiGoals.
*/
private fun clearAIGoals() {
if (initialClear) {
val dField = PathfinderGoalSelector::class.java.getDeclaredField("d")
dField.isAccessible = true
(dField.get(this.bP) as MutableSet<*>).clear()
(dField.get(this.bQ) as MutableSet<*>).clear()
initialClear = false
}
for (pathfinder in cachedPathfinders) {
this.bP.a(pathfinder)
}
this.cachedPathfinders.clear()
}
}
|
apache-2.0
|
bf78cb013b35e1fb338d7c2fd9a0748e
| 33.111888 | 92 | 0.654367 | 4.430518 | false | false | false | false |
danybony/word-clock
|
AndroidThings/things/src/main/java/net/bonysoft/wordclock/matrix/EnglishGenerator.kt
|
1
|
4218
|
package net.bonysoft.wordclock.matrix
import org.joda.time.LocalTime
class EnglishGenerator : MatrixGenerator {
companion object {
const val LED_SIZE = 144
private val ITS = intArrayOf(1, 2, 3)
private val ONE = intArrayOf(62, 63, 64)
private val TWO = intArrayOf(65, 66, 67)
private val THREE = intArrayOf(91, 92, 93, 94, 95)
private val FOUR = intArrayOf(72, 73, 74, 75)
private val FIVE = intArrayOf(76, 77, 78, 79)
private val SIX = intArrayOf(80, 81, 82)
private val SEVEN = intArrayOf(97, 98, 99, 100, 101)
private val EIGHT = intArrayOf(102, 103, 104, 105, 106)
private val NINE = intArrayOf(122, 123, 124, 125)
private val TEN = intArrayOf(115, 116, 117)
private val ELEVEN = intArrayOf(85, 86, 87, 88, 89, 90)
private val TWELVE = intArrayOf(109, 110, 111, 112, 113, 114)
private val MIN_FIVE = intArrayOf(43, 44, 45, 46)
private val MIN_TEN = intArrayOf(18, 19, 20)
private val MIN_QUARTER = intArrayOf(26, 27, 28, 29, 30, 31, 32)
private val MIN_TWENTY = intArrayOf(37, 38, 39, 40, 41, 42)
private val MIN_HALF = intArrayOf(14, 15, 16, 17)
private val TO = intArrayOf(49, 50)
private val PAST = intArrayOf(51, 52, 53, 54)
private val O_CLOCK = intArrayOf(137, 138, 139, 140, 141, 142)
private val ERROR = intArrayOf(14, 15, 20, 21, 25, 26, 27, 28, 31, 32, 33, 34, 38, 39, 44, 45, 88, 89, 90, 91, 99, 100, 101, 102, 103, 104, 110, 111, 116, 117, 121, 122, 129, 130)
}
override fun createMatrix(time: LocalTime): BooleanArray {
return BooleanArray(LED_SIZE, { false })
.addPrefix()
.addHour(time)
.addSeparator(time)
.addMinutes(time)
}
override fun createErrorMatrix(): BooleanArray {
return BooleanArray(LED_SIZE, { ERROR.contains(it) })
}
private fun BooleanArray.addPrefix(): BooleanArray {
return kotlin.BooleanArray(LED_SIZE) {
ITS.contains(it)
}
}
private fun BooleanArray.addHour(time: LocalTime): BooleanArray {
val displayedHour = if (time.minuteOfHour < 35) (time.hourOfDay % 12) else (time.hourOfDay + 1) % 12
return kotlin.BooleanArray(LED_SIZE) {
this[it] || when (displayedHour) {
0 -> TWELVE.contains(it)
1 -> ONE.contains(it)
2 -> TWO.contains(it)
3 -> THREE.contains(it)
4 -> FOUR.contains(it)
5 -> FIVE.contains(it)
6 -> SIX.contains(it)
7 -> SEVEN.contains(it)
8 -> EIGHT.contains(it)
9 -> NINE.contains(it)
10 -> TEN.contains(it)
11 -> ELEVEN.contains(it)
else -> false
}
}
}
private fun BooleanArray.addSeparator(time: LocalTime): BooleanArray {
val minutes = time.minuteOfHour
return kotlin.BooleanArray(LED_SIZE) {
this[it] || when {
minutes < 5 -> false
minutes < 35 -> PAST.contains(it)
else -> TO.contains(it)
}
}
}
private fun BooleanArray.addMinutes(time: LocalTime): BooleanArray {
val minutes = time.minuteOfHour
return kotlin.BooleanArray(LED_SIZE) {
this[it] || when {
minutes < 5 -> O_CLOCK.contains(it)
minutes < 10 -> MIN_FIVE.contains(it)
minutes < 15 -> MIN_TEN.contains(it)
minutes < 20 -> MIN_QUARTER.contains(it)
minutes < 25 -> MIN_TWENTY.contains(it)
minutes < 30 -> MIN_TWENTY.contains(it) || MIN_FIVE.contains(it)
minutes < 35 -> MIN_HALF.contains(it)
minutes < 40 -> MIN_TWENTY.contains(it) || MIN_FIVE.contains(it)
minutes < 45 -> MIN_TWENTY.contains(it)
minutes < 50 -> MIN_QUARTER.contains(it)
minutes < 55 -> MIN_TEN.contains(it)
minutes < 60 -> MIN_FIVE.contains(it)
else -> false
}
}
}
}
|
apache-2.0
|
71a8de37bf2daee0e7646757dc59afad
| 38.420561 | 187 | 0.544571 | 3.960563 | false | false | false | false |
wireapp/wire-android
|
storage/src/main/kotlin/com/waz/zclient/storage/db/users/migration/UserDatabase133To134Migration.kt
|
1
|
570
|
@file:Suppress("MagicNumber")
package com.waz.zclient.storage.db.users.migration
import androidx.room.migration.Migration
import androidx.sqlite.db.SupportSQLiteDatabase
import com.waz.zclient.storage.db.MigrationUtils
val USER_DATABASE_MIGRATION_133_TO_134 = object : Migration(133, 134) {
override fun migrate(database: SupportSQLiteDatabase) {
MigrationUtils.addColumn(
database = database,
tableName = "Conversations",
columnName = "domain",
columnType = MigrationUtils.ColumnType.TEXT
)
}
}
|
gpl-3.0
|
c6c71ba5a4bfe32581fb5ca01115f66e
| 32.529412 | 71 | 0.705263 | 4.453125 | false | false | false | false |
Deletescape-Media/Lawnchair
|
lawnchair/src/app/lawnchair/ui/AlertBottomSheetContent.kt
|
1
|
1921
|
package app.lawnchair.ui
import androidx.compose.foundation.layout.*
import androidx.compose.material.ContentAlpha
import androidx.compose.material.LocalContentAlpha
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.ProvideTextStyle
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import app.lawnchair.util.navigationBarsOrDisplayCutoutPadding
@Composable
fun AlertBottomSheetContent(
buttons: @Composable RowScope.() -> Unit,
modifier: Modifier = Modifier,
title: (@Composable () -> Unit)? = null,
text: @Composable (() -> Unit)? = null,
content: @Composable (() -> Unit)? = null
) {
val contentPadding = Modifier.padding(start = 16.dp, top = 16.dp, end = 16.dp)
Column(
modifier = modifier
.navigationBarsOrDisplayCutoutPadding()
.fillMaxWidth()
) {
if (title != null) {
Box(modifier = contentPadding) {
CompositionLocalProvider(LocalContentAlpha provides ContentAlpha.high) {
val textStyle = MaterialTheme.typography.titleLarge
ProvideTextStyle(textStyle, title)
}
}
}
if (text != null) {
Box(modifier = contentPadding) {
val textStyle = MaterialTheme.typography.bodyMedium
ProvideTextStyle(textStyle, text)
}
}
if (content != null) {
Box(modifier = Modifier.padding(top = if (title != null || text != null) 16.dp else 0.dp)) {
content()
}
}
Row(
horizontalArrangement = Arrangement.End,
modifier = Modifier
.padding(16.dp)
.fillMaxWidth()
) {
buttons()
}
}
}
|
gpl-3.0
|
002db806915b35a5c71f314dd99cc709
| 32.701754 | 104 | 0.61114 | 4.951031 | false | false | false | false |
jdinkla/groovy-java-ray-tracer
|
src/main/kotlin/net/dinkla/raytracer/math/Polynomials.kt
|
1
|
11592
|
package net.dinkla.raytracer.math
/**
* Created by IntelliJ IDEA.
* User: jorndinkla
* Date: 05.05.2010
* Time: 21:20:07
* To change this template use File | Settings | File Templates.
*/
object Polynomials {
// fun solveQuadric(c: FloatArray, s: FloatArray): Int {
// assert(c.size == 3)
// assert(s.size == 2)
//
// /* normal form: x^2 + px + q = 0 */
// val p = c[1] / (2 * c[2])
// val q = c[0] / c[2]
// val D = p * p - q
//
// if (MathUtils.isZero(D)) {
// s[0] = -p
// return 1
// } else if (D > 0) {
// val sqrtD = Math.sqrt(D.toDouble()).toFloat()
// s[0] = sqrtD - p
// s[1] = -sqrtD - p
// return 2
// } else {
// return 0
// }
// }
//
// fun solveQuartic(c: FloatArray, s: FloatArray): Int {
// assert(c.size == 5)
// assert(s.size == 4)
//
// val coeffs4 = FloatArray(4)
// val coeffs3 = FloatArray(3)
// val z: Float
// var u: Float
// var v: Float
// val sub: Float
// val A: Float
// val B: Float
// val C: Float
// val D: Float
// val sq_A: Float
// val p: Float
// val q: Float
// val r: Float
// var i: Int
// var num: Int
//
// /* normal form: x^4 + Ax^3 + Bx^2 + Cx + D = 0 */
// A = c[3] / c[4]
// B = c[2] / c[4]
// C = c[1] / c[4]
// D = c[0] / c[4]
//
// /* substitute x = y - A/4 to eliminate cubic term:
// x^4 + px^2 + qx + r = 0 */
// sq_A = A * A
// p = -3.0 / 8 * sq_A + B
// q = 1.0 / 8 * sq_A * A - 1.0 / 2 * A * B + C
// r = -3.0 / 256 * sq_A * sq_A + 1.0 / 16 * sq_A * B - 1.0 / 4 * A * C + D
//
// if (MathUtils.isZero(r)) {
// /* no absolute term: y(y^3 + py + q) = 0 */
// coeffs4[0] = q
// coeffs4[1] = p
// coeffs4[2] = 0f
// coeffs4[3] = 1f
// val ss0 = floatArrayOf(s[0], s[1], s[2])
// num = solveCubic(coeffs4, ss0)
// s[0] = ss0[0]
// s[1] = ss0[1]
// s[2] = ss0[2]
// s[num++] = 0f
// } else {
// /* solve the resolvent cubic ... */
// coeffs4[0] = 1.0 / 2 * r * p - 1.0 / 8 * q * q
// coeffs4[1] = -r
// coeffs4[2] = -1.0 / 2 * p
// coeffs4[3] = 1f
//
// val ss1 = floatArrayOf(s[0], s[1], s[2])
// solveCubic(coeffs4, ss1)
// s[0] = ss1[0]
// s[1] = ss1[1]
// s[2] = ss1[2]
//
// /* ... and take the one real solution ... */
// z = s[0]
//
// /* ... to build two quadric equations */
// u = z * z - r
// v = 2 * z - p
//
// if (MathUtils.isZero(u)) {
// u = 0f
// } else if (u > 0) {
// u = Math.sqrt(u.toDouble()).toFloat()
// } else {
// return 0
// }
// if (MathUtils.isZero(v)) {
// v = 0f
// } else if (v > 0) {
// v = Math.sqrt(v.toDouble()).toFloat()
// } else {
// return 0
// }
// coeffs3[0] = z - u
// coeffs3[1] = if (q < 0) -v else v
// coeffs3[2] = 1f
//
// val ss2 = floatArrayOf(s[0], s[1])
// num = solveQuadric(coeffs3, ss2)
// s[0] = ss2[0]
// s[1] = ss2[1]
//
// coeffs3[0] = z + u
// coeffs3[1] = if (q < 0) v else -v
// coeffs3[2] = 1f
//
// val ss3 = floatArrayOf(s[0 + num], s[1 + num])
// num += Polynomials.solveQuadric(coeffs3, ss3)
// s[0] = ss3[0]
// s[1] = ss3[1]
//
// }
//
// /* resubstitute */
// sub = 1.0 / 4 * A
//
// i = 0
// while (i < num) {
// s[i] -= sub
// ++i
// }
// return num
// }
//
// fun solveCubic(c: FloatArray, s: FloatArray): Int {
// assert(c.size == 4)
// assert(s.size == 3)
//
// var i: Int
// val num: Int
// val sub: Float
// val A: Float
// val B: Float
// val C: Float
// val sq_A: Float
// val p: Float
// val q: Float
// val cb_p: Float
// val D: Float
//
// /* normal form: x^3 + Ax^2 + Bx + C = 0 */
// A = c[2] / c[3]
// B = c[1] / c[3]
// C = c[0] / c[3]
//
// /* substitute x = y - A/3 to eliminate quadric term: x^3 +px + q = 0 */
// sq_A = A * A
// p = 1.0 / 3 * (-1.0 / 3 * sq_A + B)
// q = 1.0 / 2 * (2.0 / 27 * A * sq_A - 1.0 / 3 * A * B + C)
//
// /* use Cardano's formula */
// cb_p = p * p * p
// D = q * q + cb_p
//
// if (MathUtils.isZero(D)) {
// if (MathUtils.isZero(q)) { /* one triple solution */
// s[0] = 0f
// num = 1
// } else { /* one single and one double solution */
// val u = Math.cbrt((-q).toDouble()).toFloat()
// s[0] = 2 * u
// s[1] = -u
// num = 2
// }
// } else if (D < 0) { /* Casus irreducibilis: three real solutions */
// val phi = 1.0 / 3 * Math.acos((-q / Math.sqrt((-cb_p).toDouble()).toFloat()).toDouble()).toFloat()
// val t = 2 * Math.sqrt((-p).toDouble()).toFloat()
//
// s[0] = t * Math.cos(phi.toDouble()).toFloat()
// s[1] = -t * Math.cos(phi + Math.PI / 3).toFloat()
// s[2] = -t * Math.cos(phi - Math.PI / 3).toFloat()
//
// num = 3
// } else { /* one real solution */
// val sqrt_D = Math.sqrt(D.toDouble()).toFloat()
// val u = Math.cbrt((sqrt_D - q).toDouble()).toFloat()
// val v = -Math.cbrt((sqrt_D + q).toDouble()).toFloat()
// s[0] = u + v
// num = 1
// }
//
// /* resubstitute */
// sub = 1.0 / 3 * A
// i = 0
// while (i < num) {
// s[i] -= sub
// ++i
// }
// return num
// }
fun solveQuadric(c: DoubleArray, s: DoubleArray): Int {
assert(c.size == 3)
assert(s.size == 2)
/* normal form: x^2 + px + q = 0 */
val p = c[1] / (2 * c[2])
val q = c[0] / c[2]
val D = p * p - q
if (MathUtils.isZero(D)) {
s[0] = -p
return 1
} else if (D > 0) {
val sqrtD = Math.sqrt(D)
s[0] = sqrtD - p
s[1] = -sqrtD - p
return 2
} else {
return 0
}
}
fun solveQuartic(c: DoubleArray, s: DoubleArray): Int {
assert(c.size == 5)
assert(s.size == 4)
val coeffs4 = DoubleArray(4)
val coeffs3 = DoubleArray(3)
val z: Double
var u: Double
var v: Double
val sub: Double
val A: Double = c[3] / c[4]
val B: Double = c[2] / c[4]
val C: Double = c[1] / c[4]
val D: Double = c[0] / c[4]
val sq_A: Double
val p: Double
val q: Double
val r: Double
var i = 0
var num: Int
/* normal form: x^4 + Ax^3 + Bx^2 + Cx + D = 0 */
/* substitute x = y - A/4 to eliminate cubic term:
x^4 + px^2 + qx + r = 0 */
sq_A = A * A
p = -3.0 / 8 * sq_A + B
q = (1.0 / 8) * sq_A * A - (1.0 / 2) * A * B + C
r = (-3.0 / 256) * sq_A * sq_A + (1.0 / 16) * sq_A * B - (1.0 / 4) * A * C + D
if (MathUtils.isZero(r)) {
/* no absolute term: y(y^3 + py + q) = 0 */
coeffs4[0] = q
coeffs4[1] = p
coeffs4[2] = 0.0
coeffs4[3] = 1.0
val ss = doubleArrayOf(s[0], s[1], s[2])
num = solveCubic(coeffs4, ss)
s[0] = ss[0]
s[1] = ss[1]
s[2] = ss[2]
s[num++] = 0.0
} else {
/* solve the resolvent cubic ... */
coeffs4[0] = (1.0 / 2) * r * p - (1.0 / 8) * q * q
coeffs4[1] = -r
coeffs4[2] = -1.0 / 2 * p
coeffs4[3] = 1.0
val ss = doubleArrayOf(s[0], s[1], s[2])
solveCubic(coeffs4, ss)
s[0] = ss[0]
s[1] = ss[1]
s[2] = ss[2]
/* ... and take the one real solution ... */
z = s[0]
/* ... to build two quadric equations */
u = z * z - r
v = 2 * z - p
u = when {
MathUtils.isZero(u) -> 0.0
u > 0 -> Math.sqrt(u)
else -> 0.0
}
v = when {
MathUtils.isZero(v) -> 0.0
v > 0 -> Math.sqrt(v)
else -> 0.0
}
coeffs3[0] = z - u
coeffs3[1] = if (q < 0) -v else v
coeffs3[2] = 1.0
val ss2 = doubleArrayOf(s[0], s[1])
num = solveQuadric(coeffs3, ss2)
s[0] = ss2[0]
s[1] = ss2[1]
coeffs3[0] = z + u
coeffs3[1] = if (q < 0) v else -v
coeffs3[2] = 1.0
// TODO: Was heißt s+ num
// double[] ss3 = { s[0 + num], s[1 + num] };
val ss3 = doubleArrayOf(s[0 + num], s[1 + num])
num += Polynomials.solveQuadric(coeffs3, ss3)
s[0] = ss3[0]
s[1] = ss3[1]
}
/* resubstitute */
sub = 1.0 / 4 * A
while (i < num) {
s[i] -= sub
++i
}
return num
}
fun solveCubic(c: DoubleArray, s: DoubleArray): Int {
assert(c.size == 4)
assert(s.size == 3)
var i = 0
val num: Int
val sub: Double
val A: Double = c[2] / c[3]
val B: Double = c[1] / c[3]
val C: Double = c[0] / c[3]
val sq_A: Double
val p: Double
val q: Double
val cb_p: Double
val D: Double
/* normal form: x^3 + Ax^2 + Bx + C = 0 */
/* substitute x = y - A/3 to eliminate quadric term: x^3 +px + q = 0 */
sq_A = A * A
p = 1.0 / 3 * (-1.0 / 3 * sq_A + B)
q = 1.0 / 2 * ((2.0 / 27).toDouble() * A * sq_A - (1.0 / 3).toDouble() * A * B + C)
/* use Cardano's formula */
cb_p = p * p * p
D = q * q + cb_p
if (MathUtils.isZero(D)) {
if (MathUtils.isZero(q)) { /* one triple solution */
s[0] = 0.0
num = 1
} else { /* one single and one double solution */
val u = Math.cbrt(-q)
s[0] = 2 * u
s[1] = -u
num = 2
}
} else if (D < 0) { /* Casus irreducibilis: three real solutions */
val phi = 1.0 / 3 * Math.acos(-q / Math.sqrt(-cb_p))
val t = 2 * Math.sqrt(-p)
s[0] = t * Math.cos(phi)
s[1] = -t * Math.cos(phi + Math.PI / 3)
s[2] = -t * Math.cos(phi - Math.PI / 3)
num = 3
} else { /* one real solution */
val sqrt_D = Math.sqrt(D)
val u = Math.cbrt(sqrt_D - q)
val v = -Math.cbrt(sqrt_D + q)
s[0] = u + v
num = 1
}
/* resubstitute */
sub = 1.0 / 3 * A
while (i < num) {
s[i] -= sub
++i
}
return num
}
}
|
apache-2.0
|
89ee8ee62e5a1b16de49af582b5b2c72
| 27.905237 | 112 | 0.369683 | 2.900651 | false | false | false | false |
tinypass/piano-sdk-for-android
|
id/id/src/main/java/io/piano/android/id/models/BaseResponse.kt
|
1
|
661
|
package io.piano.android.id.models
import com.squareup.moshi.Json
import com.squareup.moshi.JsonClass
@JsonClass(generateAdapter = true)
open class BaseResponse(
val code: Int,
val message: String?,
@Json(name = "validation_errors") val validationErrors: Map<String, String>?
) {
val hasError: Boolean = code != 0
val error: String = validationErrors?.let {
it[KEY_MESSAGE] ?: it.values.joinToString(separator = "; ")
} ?: message.takeUnless { it.isNullOrEmpty() } ?: ERROR_TEMPLATE + code
companion object {
internal const val KEY_MESSAGE = "message"
internal const val ERROR_TEMPLATE = "Error "
}
}
|
apache-2.0
|
7a14286c57f8d6d8c5f01bdd46c7d7cb
| 29.045455 | 80 | 0.676248 | 4.030488 | false | false | false | false |
mrkirby153/KirBot
|
src/main/kotlin/me/mrkirby153/KirBot/command/executors/music/CommandQueue.kt
|
1
|
4951
|
package me.mrkirby153.KirBot.command.executors.music
import me.mrkirby153.KirBot.command.annotations.CommandDescription
import me.mrkirby153.KirBot.command.CommandCategory
import me.mrkirby153.KirBot.command.annotations.Command
import me.mrkirby153.KirBot.command.args.CommandContext
import me.mrkirby153.KirBot.module.ModuleManager
import me.mrkirby153.KirBot.modules.music.MusicManager
import me.mrkirby153.KirBot.modules.music.MusicModule
import me.mrkirby153.KirBot.utils.Context
import me.mrkirby153.KirBot.utils.embed.link
import me.mrkirby153.KirBot.utils.escapeMarkdown
import me.mrkirby153.KirBot.utils.settings.GuildSettings
import net.dv8tion.jda.api.Permission
import java.util.Random
import javax.inject.Inject
import kotlin.math.roundToInt
class CommandQueue @Inject constructor(private val musicModule: MusicModule) {
@Command(name = "queue", arguments = ["[option:string]"], aliases = ["np", "nowplaying"],
permissions = [Permission.MESSAGE_EMBED_LINKS], category = CommandCategory.MUSIC)
@CommandDescription("Shows the current queue")
fun execute(context: Context, cmdContext: CommandContext) {
if (!GuildSettings.musicEnabled.get(context.guild))
return
val manager = musicModule.getManager(context.guild)
if (cmdContext.has("option")) {
when (cmdContext.get<String>("option")!!.toLowerCase()) {
"clear" -> {
manager.queue.clear()
context.send().success("Queue cleared!").queue()
}
"shuffle" -> {
val queue = manager.queue.toMutableList()
val random = Random()
manager.queue.clear()
while (queue.isNotEmpty()) {
val element: MusicManager.QueuedSong = queue[random.nextInt(queue.size)]
manager.queue.add(element)
queue.remove(element)
}
context.send().success("Queue shuffled!").queue()
}
}
return
}
if (manager.nowPlaying == null && manager.queue.isEmpty()) {
context.send().embed("Now Playing") {
description { +"Nothing is playing right now" }
timestamp {
now()
}
}.rest().queue()
return
}
context.send().embed {
val nowPlaying = manager.nowPlaying ?: return@embed
if (nowPlaying.info.uri.contains("youtu")) {
thumbnail = "https://i.ytimg.com/vi/${nowPlaying.info.identifier}/default.jpg"
}
description {
+("**Music Queue :musical_note:**" link manager.nowPlaying!!.info.uri)
+"\n\n__Now Playing__"
+"\n\n"
if (manager.playing)
+":loud_sound: "
else
+":speaker: "
val position = "${MusicManager.parseMS(nowPlaying.position)}/${MusicManager.parseMS(
nowPlaying.info.length)}"
+nowPlaying.info.title.escapeMarkdown() link nowPlaying.info.uri
+"\n\n :rewind: ${buildProgressBar(12, nowPlaying.position, nowPlaying.duration)} :fast_forward: ($position)"
+"\n\n:arrow_down_small: __Up Next__ :arrow_down_small:"
+"\n\n"
if (manager.queue.size == 0)
+"Nothing"
else
manager.queue.forEachIndexed { index, (track) ->
if (length < 1500)
appendln(
" " + (index + 1) + ". " + (track.info.title link track.info.uri) + " (${MusicManager.parseMS(
track.duration)})")
}
}
timestamp {
now()
}
footer {
text {
var duration = 0L
manager.queue.forEach {
duration += it.track.duration
}
duration += nowPlaying.duration
append("\n\n${MusicManager.parseMS(
duration)} | ${manager.queue.size + 1} songs")
}
}
}.rest().queue()
}
private fun buildProgressBar(steps: Int, current: Long, max: Long, bar: String = "▬",
dot: String = "\uD83D\uDD18"): String {
val percent = current.toDouble() / max
val pos = Math.min(Math.max((steps * percent).roundToInt(), 1), steps)
return buildString {
for (i in 1 until (steps+1)) {
if (i == pos)
append(dot)
else
append(bar)
}
}
}
}
|
mit
|
6e55d8bbdae696436d0510f8d7c5b6da
| 40.949153 | 130 | 0.518893 | 4.814202 | false | false | false | false |
fnberta/PopularMovies
|
app/src/main/java/ch/berta/fabio/popularmovies/features/details/component/Main.kt
|
1
|
2361
|
/*
* Copyright (c) 2017 Fabio Berta
*
* 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 ch.berta.fabio.popularmovies.features.details.component
import ch.berta.fabio.popularmovies.NavigationTarget
import ch.berta.fabio.popularmovies.data.MovieStorage
import ch.berta.fabio.popularmovies.features.details.vdos.rows.DetailsVideoRowViewData
import ch.berta.fabio.popularmovies.features.details.view.DetailsArgs
import ch.berta.fabio.popularmovies.log
import com.jakewharton.rxrelay2.PublishRelay
import io.reactivex.Observable
data class DetailsSources(
val uiEvents: DetailsUiEvents,
val movieStorage: MovieStorage
)
data class DetailsUiEvents(
val snackbarShown: PublishRelay<Unit> = PublishRelay.create(),
val updateSwipes: PublishRelay<Unit> = PublishRelay.create(),
val favClicks: PublishRelay<Unit> = PublishRelay.create(),
val videoClicks: PublishRelay<DetailsVideoRowViewData> = PublishRelay.create()
)
sealed class DetailsAction {
object SnackbarShown : DetailsAction()
object UpdateSwipe : DetailsAction()
object FavClick : DetailsAction()
data class VideoClick(val videoViewModel: DetailsVideoRowViewData) : DetailsAction()
}
sealed class DetailsSink {
data class State(val state: DetailsState) : DetailsSink()
data class Navigation(val target: NavigationTarget) : DetailsSink()
}
fun main(sources: DetailsSources, detailsArgs: DetailsArgs): Observable<DetailsSink> = intention(sources)
.log("action")
.publish {
val state = model(it, sources.movieStorage, detailsArgs)
.map { DetailsSink.State(it) }
val navigationTargets = navigationTargets(it, detailsArgs)
.map { DetailsSink.Navigation(it) }
Observable.merge(state, navigationTargets)
}
.share()
|
apache-2.0
|
28bb72063a8f759d10540eb835d3d814
| 37.704918 | 105 | 0.734858 | 4.340074 | false | false | false | false |
italoag/qksms
|
presentation/src/main/java/com/moez/QKSMS/feature/settings/SettingsController.kt
|
3
|
11724
|
/*
* Copyright (C) 2017 Moez Bhatti <[email protected]>
*
* This file is part of QKSMS.
*
* QKSMS 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.
*
* QKSMS 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 QKSMS. If not, see <http://www.gnu.org/licenses/>.
*/
package com.moez.QKSMS.feature.settings
import android.animation.ObjectAnimator
import android.app.TimePickerDialog
import android.content.Context
import android.os.Build
import android.text.format.DateFormat
import android.view.View
import androidx.appcompat.app.AlertDialog
import androidx.core.view.isVisible
import com.bluelinelabs.conductor.RouterTransaction
import com.google.android.material.snackbar.Snackbar
import com.jakewharton.rxbinding2.view.clicks
import com.jakewharton.rxbinding2.view.longClicks
import com.moez.QKSMS.BuildConfig
import com.moez.QKSMS.R
import com.moez.QKSMS.common.MenuItem
import com.moez.QKSMS.common.QkChangeHandler
import com.moez.QKSMS.common.QkDialog
import com.moez.QKSMS.common.base.QkController
import com.moez.QKSMS.common.util.Colors
import com.moez.QKSMS.common.util.extensions.animateLayoutChanges
import com.moez.QKSMS.common.util.extensions.setBackgroundTint
import com.moez.QKSMS.common.util.extensions.setVisible
import com.moez.QKSMS.common.widget.PreferenceView
import com.moez.QKSMS.common.widget.QkSwitch
import com.moez.QKSMS.common.widget.TextInputDialog
import com.moez.QKSMS.feature.settings.about.AboutController
import com.moez.QKSMS.feature.settings.autodelete.AutoDeleteDialog
import com.moez.QKSMS.feature.settings.swipe.SwipeActionsController
import com.moez.QKSMS.feature.themepicker.ThemePickerController
import com.moez.QKSMS.injection.appComponent
import com.moez.QKSMS.repository.SyncRepository
import com.moez.QKSMS.util.Preferences
import com.uber.autodispose.android.lifecycle.scope
import com.uber.autodispose.autoDisposable
import io.reactivex.Observable
import io.reactivex.subjects.PublishSubject
import io.reactivex.subjects.Subject
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import kotlinx.android.synthetic.main.settings_controller.*
import kotlinx.android.synthetic.main.settings_controller.view.*
import kotlinx.android.synthetic.main.settings_switch_widget.view.*
import kotlinx.android.synthetic.main.settings_theme_widget.*
import javax.inject.Inject
import kotlin.coroutines.resume
class SettingsController : QkController<SettingsView, SettingsState, SettingsPresenter>(), SettingsView {
@Inject lateinit var context: Context
@Inject lateinit var colors: Colors
@Inject lateinit var nightModeDialog: QkDialog
@Inject lateinit var textSizeDialog: QkDialog
@Inject lateinit var sendDelayDialog: QkDialog
@Inject lateinit var mmsSizeDialog: QkDialog
@Inject override lateinit var presenter: SettingsPresenter
private val signatureDialog: TextInputDialog by lazy {
TextInputDialog(activity!!, context.getString(R.string.settings_signature_title), signatureSubject::onNext)
}
private val autoDeleteDialog: AutoDeleteDialog by lazy {
AutoDeleteDialog(activity!!, autoDeleteSubject::onNext)
}
private val viewQksmsPlusSubject: Subject<Unit> = PublishSubject.create()
private val startTimeSelectedSubject: Subject<Pair<Int, Int>> = PublishSubject.create()
private val endTimeSelectedSubject: Subject<Pair<Int, Int>> = PublishSubject.create()
private val signatureSubject: Subject<String> = PublishSubject.create()
private val autoDeleteSubject: Subject<Int> = PublishSubject.create()
private val progressAnimator by lazy { ObjectAnimator.ofInt(syncingProgress, "progress", 0, 0) }
init {
appComponent.inject(this)
retainViewMode = RetainViewMode.RETAIN_DETACH
layoutRes = R.layout.settings_controller
colors.themeObservable()
.autoDisposable(scope())
.subscribe { activity?.recreate() }
}
override fun onViewCreated() {
preferences.postDelayed({ preferences?.animateLayoutChanges = true }, 100)
when (Build.VERSION.SDK_INT >= 29) {
true -> nightModeDialog.adapter.setData(R.array.night_modes)
false -> nightModeDialog.adapter.data = context.resources.getStringArray(R.array.night_modes)
.mapIndexed { index, title -> MenuItem(title, index) }
.drop(1)
}
textSizeDialog.adapter.setData(R.array.text_sizes)
sendDelayDialog.adapter.setData(R.array.delayed_sending_labels)
mmsSizeDialog.adapter.setData(R.array.mms_sizes, R.array.mms_sizes_ids)
about.summary = context.getString(R.string.settings_version, BuildConfig.VERSION_NAME)
}
override fun onAttach(view: View) {
super.onAttach(view)
presenter.bindIntents(this)
setTitle(R.string.title_settings)
showBackButton(true)
}
override fun preferenceClicks(): Observable<PreferenceView> = (0 until preferences.childCount)
.map { index -> preferences.getChildAt(index) }
.mapNotNull { view -> view as? PreferenceView }
.map { preference -> preference.clicks().map { preference } }
.let { preferences -> Observable.merge(preferences) }
override fun aboutLongClicks(): Observable<*> = about.longClicks()
override fun viewQksmsPlusClicks(): Observable<*> = viewQksmsPlusSubject
override fun nightModeSelected(): Observable<Int> = nightModeDialog.adapter.menuItemClicks
override fun nightStartSelected(): Observable<Pair<Int, Int>> = startTimeSelectedSubject
override fun nightEndSelected(): Observable<Pair<Int, Int>> = endTimeSelectedSubject
override fun textSizeSelected(): Observable<Int> = textSizeDialog.adapter.menuItemClicks
override fun sendDelaySelected(): Observable<Int> = sendDelayDialog.adapter.menuItemClicks
override fun signatureChanged(): Observable<String> = signatureSubject
override fun autoDeleteChanged(): Observable<Int> = autoDeleteSubject
override fun mmsSizeSelected(): Observable<Int> = mmsSizeDialog.adapter.menuItemClicks
override fun render(state: SettingsState) {
themePreview.setBackgroundTint(state.theme)
night.summary = state.nightModeSummary
nightModeDialog.adapter.selectedItem = state.nightModeId
nightStart.setVisible(state.nightModeId == Preferences.NIGHT_MODE_AUTO)
nightStart.summary = state.nightStart
nightEnd.setVisible(state.nightModeId == Preferences.NIGHT_MODE_AUTO)
nightEnd.summary = state.nightEnd
black.setVisible(state.nightModeId != Preferences.NIGHT_MODE_OFF)
black.checkbox.isChecked = state.black
autoEmoji.checkbox.isChecked = state.autoEmojiEnabled
delayed.summary = state.sendDelaySummary
sendDelayDialog.adapter.selectedItem = state.sendDelayId
delivery.checkbox.isChecked = state.deliveryEnabled
signature.summary = state.signature.takeIf { it.isNotBlank() }
?: context.getString(R.string.settings_signature_summary)
textSize.summary = state.textSizeSummary
textSizeDialog.adapter.selectedItem = state.textSizeId
autoColor.checkbox.isChecked = state.autoColor
systemFont.checkbox.isChecked = state.systemFontEnabled
unicode.checkbox.isChecked = state.stripUnicodeEnabled
mobileOnly.checkbox.isChecked = state.mobileOnly
autoDelete.summary = when (state.autoDelete) {
0 -> context.getString(R.string.settings_auto_delete_never)
else -> context.resources.getQuantityString(
R.plurals.settings_auto_delete_summary, state.autoDelete, state.autoDelete)
}
longAsMms.checkbox.isChecked = state.longAsMms
mmsSize.summary = state.maxMmsSizeSummary
mmsSizeDialog.adapter.selectedItem = state.maxMmsSizeId
when (state.syncProgress) {
is SyncRepository.SyncProgress.Idle -> syncingProgress.isVisible = false
is SyncRepository.SyncProgress.Running -> {
syncingProgress.isVisible = true
syncingProgress.max = state.syncProgress.max
progressAnimator.apply { setIntValues(syncingProgress.progress, state.syncProgress.progress) }.start()
syncingProgress.isIndeterminate = state.syncProgress.indeterminate
}
}
}
override fun showQksmsPlusSnackbar() {
view?.run {
Snackbar.make(contentView, R.string.toast_qksms_plus, Snackbar.LENGTH_LONG).run {
setAction(R.string.button_more) { viewQksmsPlusSubject.onNext(Unit) }
setActionTextColor(colors.theme().theme)
show()
}
}
}
// TODO change this to a PopupWindow
override fun showNightModeDialog() = nightModeDialog.show(activity!!)
override fun showStartTimePicker(hour: Int, minute: Int) {
TimePickerDialog(activity, { _, newHour, newMinute ->
startTimeSelectedSubject.onNext(Pair(newHour, newMinute))
}, hour, minute, DateFormat.is24HourFormat(activity)).show()
}
override fun showEndTimePicker(hour: Int, minute: Int) {
TimePickerDialog(activity, { _, newHour, newMinute ->
endTimeSelectedSubject.onNext(Pair(newHour, newMinute))
}, hour, minute, DateFormat.is24HourFormat(activity)).show()
}
override fun showTextSizePicker() = textSizeDialog.show(activity!!)
override fun showDelayDurationDialog() = sendDelayDialog.show(activity!!)
override fun showSignatureDialog(signature: String) = signatureDialog.setText(signature).show()
override fun showAutoDeleteDialog(days: Int) = autoDeleteDialog.setExpiry(days).show()
override suspend fun showAutoDeleteWarningDialog(messages: Int): Boolean = withContext(Dispatchers.Main) {
suspendCancellableCoroutine<Boolean> { cont ->
AlertDialog.Builder(activity!!)
.setTitle(R.string.settings_auto_delete_warning)
.setMessage(context.resources.getString(R.string.settings_auto_delete_warning_message, messages))
.setOnCancelListener { cont.resume(false) }
.setNegativeButton(R.string.button_cancel) { _, _ -> cont.resume(false) }
.setPositiveButton(R.string.button_yes) { _, _ -> cont.resume(true) }
.show()
}
}
override fun showMmsSizePicker() = mmsSizeDialog.show(activity!!)
override fun showSwipeActions() {
router.pushController(RouterTransaction.with(SwipeActionsController())
.pushChangeHandler(QkChangeHandler())
.popChangeHandler(QkChangeHandler()))
}
override fun showThemePicker() {
router.pushController(RouterTransaction.with(ThemePickerController())
.pushChangeHandler(QkChangeHandler())
.popChangeHandler(QkChangeHandler()))
}
override fun showAbout() {
router.pushController(RouterTransaction.with(AboutController())
.pushChangeHandler(QkChangeHandler())
.popChangeHandler(QkChangeHandler()))
}
}
|
gpl-3.0
|
daabaca515522a8db708025b62829329
| 41.948718 | 118 | 0.722791 | 4.545948 | false | false | false | false |
sangcomz/FishBun
|
FishBunDemo/src/main/java/com/sangcomz/fishbundemo/SubFragment.kt
|
1
|
3397
|
package com.sangcomz.fishbundemo
import android.app.Activity
import android.content.Intent
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.recyclerview.widget.LinearLayoutManager
import com.sangcomz.fishbun.FishBun
import com.sangcomz.fishbun.adapter.image.impl.CoilAdapter
import com.sangcomz.fishbundemo.databinding.FragmentSubBinding
/**
* A simple [Fragment] subclass.
*/
class SubFragment : Fragment() {
var path = ArrayList<Uri>()
private lateinit var imageAdapter: ImageAdapter
private var _binding: FragmentSubBinding? = null
private val binding get() = _binding!!
private val startForResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
if (it.resultCode == AppCompatActivity.RESULT_OK) {
path = it.data?.getParcelableArrayListExtra(FishBun.INTENT_PATH) ?: arrayListOf()
imageAdapter.changePath(path)
}
}
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View {
_binding = FragmentSubBinding.inflate(inflater, container, false)
return binding.root
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
with(binding.recyclerview) {
layoutManager = LinearLayoutManager(context, LinearLayoutManager.HORIZONTAL, false)
imageAdapter = ImageAdapter(requireActivity(), ImageController(binding.imgMain), path)
adapter = imageAdapter
}
binding.btnAddImages.setOnClickListener {
FishBun.with(this@SubFragment)
.setImageAdapter(CoilAdapter())
.setMaxCount(10)
.setActionBarColor(Color.parseColor("#3F51B5"), Color.parseColor("#303F9F"))
.setSelectedImages(path)
.hasCameraInPickerPage(true)
.startAlbumWithOnActivityResult(IMAGE_PICKER_REQUEST_CODE)
}
binding.btnAddImagesUseCallback.setOnClickListener {
FishBun.with(this@SubFragment)
.setImageAdapter(CoilAdapter())
.setMaxCount(10)
.setActionBarColor(Color.parseColor("#3F51B5"), Color.parseColor("#303F9F"))
.setSelectedImages(path)
.hasCameraInPickerPage(true)
.startAlbumWithActivityResultCallback(startForResult)
}
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
when (requestCode) {
IMAGE_PICKER_REQUEST_CODE -> if (resultCode == Activity.RESULT_OK) {
path = data?.getParcelableArrayListExtra(FishBun.INTENT_PATH) ?: arrayListOf()
imageAdapter.changePath(path)
}
}
}
override fun onDestroyView() {
super.onDestroyView()
_binding = null
}
companion object {
const val IMAGE_PICKER_REQUEST_CODE = 1
fun newInstance() = SubFragment()
}
}
|
apache-2.0
|
96d6008f80e09f960c9caa268578818e
| 35.148936 | 110 | 0.678834 | 4.951895 | false | false | false | false |
RyotaMurohoshi/KotLinq
|
src/main/kotlin/com/muhron/kotlinq/groupJoin.kt
|
1
|
6901
|
package com.muhron.kotlinq
// for Sequence
fun <TOuter, TInner, TKey, TResult> Sequence<TOuter>.groupJoin(
inner: Sequence<TInner>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (TOuter, Sequence<TInner>) -> TResult): Sequence<TResult> =
groupJoin(this, inner, outerKeySelector, innerKeySelector, resultSelector)
fun <TOuter, TInner, TKey, TResult> Sequence<TOuter>.groupJoin(
inner: Iterable<TInner>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (TOuter, Sequence<TInner>) -> TResult): Sequence<TResult> =
groupJoin(this, inner.asSequence(), outerKeySelector, innerKeySelector, resultSelector)
fun <TOuter, TInner, TKey, TResult> Sequence<TOuter>.groupJoin(
inner: Array<TInner>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (TOuter, Sequence<TInner>) -> TResult): Sequence<TResult> =
groupJoin(this, inner.asSequence(), outerKeySelector, innerKeySelector, resultSelector)
fun <TOuter, TOuterK, TOuterV, TKey, TResult> Sequence<TOuter>.groupJoin(
inner: Map<TOuterK, TOuterV>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (Map.Entry<TOuterK, TOuterV>) -> TKey,
resultSelector: (TOuter, Sequence<Map.Entry<TOuterK, TOuterV>>) -> TResult): Sequence<TResult> =
groupJoin(this, inner.asSequence(), outerKeySelector, innerKeySelector, resultSelector)
// for Iterable
fun <TOuter, TInner, TKey, TResult> Iterable<TOuter>.groupJoin(
inner: Sequence<TInner>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (TOuter, Sequence<TInner>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
fun <TOuter, TInner, TKey, TResult> Iterable<TOuter>.groupJoin(
inner: Iterable<TInner>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (TOuter, Sequence<TInner>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
fun <TOuter, TInner, TKey, TResult> Iterable<TOuter>.groupJoin(
inner: Array<TInner>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (TOuter, Sequence<TInner>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
fun <TOuter, TOuterK, TOuterV, TKey, TResult> Iterable<TOuter>.groupJoin(
inner: Map<TOuterK, TOuterV>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (Map.Entry<TOuterK, TOuterV>) -> TKey,
resultSelector: (TOuter, Sequence<Map.Entry<TOuterK, TOuterV>>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
// for Array
fun <TOuter, TInner, TKey, TResult> Array<TOuter>.groupJoin(
inner: Sequence<TInner>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (TOuter, Sequence<TInner>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
fun <TOuter, TInner, TKey, TResult> Array<TOuter>.groupJoin(
inner: Iterable<TInner>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (TOuter, Sequence<TInner>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
fun <TOuter, TInner, TKey, TResult> Array<TOuter>.groupJoin(
inner: Array<TInner>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (TOuter, Sequence<TInner>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
fun <TOuter, TOuterK, TOuterV, TKey, TResult> Array<TOuter>.groupJoin(
inner: Map<TOuterK, TOuterV>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (Map.Entry<TOuterK, TOuterV>) -> TKey,
resultSelector: (TOuter, Sequence<Map.Entry<TOuterK, TOuterV>>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
// for Map
fun <TOuterK, TOuterV, TInner, TKey, TResult> Map<TOuterK, TOuterV>.groupJoin(
inner: Sequence<TInner>,
outerKeySelector: (Map.Entry<TOuterK, TOuterV>) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (Map.Entry<TOuterK, TOuterV>, Sequence<TInner>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
fun <TOuterK, TOuterV, TInner, TKey, TResult> Map<TOuterK, TOuterV>.groupJoin(
inner: Iterable<TInner>,
outerKeySelector: (Map.Entry<TOuterK, TOuterV>) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (Map.Entry<TOuterK, TOuterV>, Sequence<TInner>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
fun <TOuterK, TOuterV, TInner, TKey, TResult> Map<TOuterK, TOuterV>.groupJoin(
inner: Array<TInner>,
outerKeySelector: (Map.Entry<TOuterK, TOuterV>) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (Map.Entry<TOuterK, TOuterV>, Sequence<TInner>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
fun <TOuterK, TOuterV, TInnerK, TInnerV, TKey, TResult> Map<TOuterK, TOuterV>.groupJoin(
inner: Map<TInnerK, TInnerV>,
outerKeySelector: (Map.Entry<TOuterK, TOuterV>) -> TKey,
innerKeySelector: (Map.Entry<TInnerK, TInnerV>) -> TKey,
resultSelector: (Map.Entry<TOuterK, TOuterV>, Sequence<Map.Entry<TInnerK, TInnerV>>) -> TResult): Sequence<TResult> =
asSequence().groupJoin(inner, outerKeySelector, innerKeySelector, resultSelector)
@JvmName("groupJoins")
fun <TOuter, TInner, TKey, TResult> groupJoin(
outer: Sequence<TOuter>,
inner: Sequence<TInner>,
outerKeySelector: (TOuter) -> TKey,
innerKeySelector: (TInner) -> TKey,
resultSelector: (TOuter, Sequence<TInner>) -> TResult): Sequence<TResult> {
return Sequence {
val innerLookup = inner.toLookup(innerKeySelector)
outer.map { outerElement ->
val key = outerKeySelector(outerElement)
val innerElements = innerLookup[key]
resultSelector(outerElement, innerElements)
}.iterator()
}
}
|
mit
|
5f52b5fcb51b35ebe9875b9de0acedfc
| 49.742647 | 125 | 0.682075 | 3.620672 | false | false | false | false |
TangHao1987/intellij-community
|
platform/configuration-store-impl/src/XmlElementStorage.kt
|
2
|
10975
|
/*
* Copyright 2000-2015 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.configurationStore
import com.intellij.openapi.components.RoamingType
import com.intellij.openapi.components.StateStorage
import com.intellij.openapi.components.TrackingPathMacroSubstitutor
import com.intellij.openapi.components.impl.stores.*
import com.intellij.openapi.util.JDOMUtil
import com.intellij.util.ArrayUtil
import com.intellij.util.containers.ContainerUtil
import com.intellij.util.containers.SmartHashSet
import gnu.trove.THashMap
import org.jdom.Attribute
import org.jdom.Element
import org.jdom.JDOMException
import java.io.IOException
import java.util.Arrays
abstract class XmlElementStorage protected constructor(protected val fileSpec: String,
protected val rootElementName: String,
protected val pathMacroSubstitutor: TrackingPathMacroSubstitutor?,
roamingType: RoamingType?,
provider: StreamProvider?) : StateStorageBase<StateMap>() {
protected val roamingType: RoamingType = roamingType ?: RoamingType.PER_USER
private val provider: StreamProvider? = if (provider == null || roamingType == RoamingType.DISABLED || !provider.isApplicable(fileSpec, this.roamingType)) null else provider
protected abstract fun loadLocalData(): Element?
override fun getStateAndArchive(storageData: StateMap, component: Any, componentName: String) = storageData.getStateAndArchive(componentName)
override fun loadData(): StateMap {
val states = StateMap()
val element: Element?
// we don't use local data if has stream provider
if (provider != null && provider.enabled) {
try {
element = loadDataFromProvider()
if (element != null) {
states.loadState(element)
}
}
catch (e: Exception) {
LOG.error(e)
element = null
}
}
else {
element = loadLocalData()
}
if (element != null) {
states.loadState(element)
}
return states
}
throws(IOException::class, JDOMException::class)
private fun loadDataFromProvider() = JDOMUtil.load(provider!!.loadContent(fileSpec, roamingType))
private fun StateMap.loadState(element: Element) {
beforeElementLoaded(element)
StateMap.load(this, element, pathMacroSubstitutor, true)
}
fun setDefaultState(element: Element) {
element.setName(rootElementName)
val states = StateMap()
states.loadState(element)
storageDataRef.set(states)
}
override fun startExternalization() = if (checkIsSavingDisabled()) null else createSaveSession(getStorageData())
protected abstract fun createSaveSession(states: StateMap): StateStorage.ExternalizationSession
override fun analyzeExternalChangesAndUpdateIfNeed(componentNames: MutableSet<String>) {
val oldData = storageDataRef.get()
val newData = getStorageData(true)
if (oldData == null) {
if (LOG.isDebugEnabled()) {
LOG.debug("analyzeExternalChangesAndUpdateIfNeed: old data null, load new for ${toString()}")
}
componentNames.addAll(newData.keys())
}
else {
val changedComponentNames = oldData.getChangedComponentNames(newData)
if (LOG.isDebugEnabled()) {
LOG.debug("analyzeExternalChangesAndUpdateIfNeed: changedComponentNames $changedComponentNames for ${toString()}")
}
if (!ContainerUtil.isEmpty(changedComponentNames)) {
componentNames.addAll(changedComponentNames)
}
}
}
private fun setStorageData(oldStorageData: StateMap, newStorageData: StateMap?) {
if (oldStorageData !== newStorageData && storageDataRef.getAndSet(newStorageData) !== oldStorageData) {
LOG.warn("Old storage data is not equal to current, new storage data was set anyway")
}
}
abstract class XmlElementStorageSaveSession<T : XmlElementStorage>(private val originalStates: StateMap, protected val storage: T) : SaveSessionBase() {
private var copiedStates: StateMap? = null
private val newLiveStates = THashMap<String, Element>()
override fun createSaveSession() = if (storage.checkIsSavingDisabled() || copiedStates == null) null else this
override fun setSerializedState(component: Any, componentName: String, element: Element?) {
if (copiedStates == null) {
copiedStates = setStateAndCloneIfNeed(componentName, element, originalStates, newLiveStates)
}
else {
copiedStates!!.setState(componentName, element, newLiveStates)
}
}
override fun save() {
var states = copiedStates!!
var element = save(states, newLiveStates, storage.rootElementName)
if (element == null || JDOMUtil.isEmpty(element)) {
element = null
}
else {
storage.beforeElementSaved(element)
}
val provider = storage.provider
if (provider != null && provider.enabled) {
if (element == null) {
provider.delete(storage.fileSpec, storage.roamingType)
}
else {
// we should use standard line-separator (\n) - stream provider can share file content on any OS
val content = StorageUtil.writeToBytes(element, "\n")
provider.saveContent(storage.fileSpec, content.getInternalBuffer(), content.size(), storage.roamingType)
}
}
else {
saveLocally(element)
}
storage.setStorageData(originalStates, states)
}
throws(IOException::class)
protected abstract fun saveLocally(element: Element?)
}
protected open fun beforeElementLoaded(element: Element) {
}
protected open fun beforeElementSaved(element: Element) {
if (pathMacroSubstitutor != null) {
try {
pathMacroSubstitutor.collapsePaths(element)
}
finally {
pathMacroSubstitutor.reset()
}
}
}
public fun updatedFromStreamProvider(changedComponentNames: MutableSet<String>, deleted: Boolean) {
if (roamingType == RoamingType.DISABLED) {
// storage roaming was changed to DISABLED, but settings repository has old state
return
}
try {
val newElement = if (deleted) null else loadDataFromProvider()
val states = storageDataRef.get()
if (newElement == null) {
// if data was loaded, mark as changed all loaded components
if (states != null) {
changedComponentNames.addAll(states.keys())
setStorageData(states, null)
}
}
else if (states != null) {
val newStorageData = StateMap()
newStorageData.loadState(newElement)
changedComponentNames.addAll(states.getChangedComponentNames(newStorageData))
setStorageData(states, newStorageData)
}
}
catch (e: Throwable) {
LOG.error(e)
}
}
}
private fun save(states: StateMap, newLiveStates: Map<String, Element>, rootElementName: String): Element? {
if (states.isEmpty()) {
return null
}
val rootElement = Element(rootElementName)
val componentNames = ArrayUtil.toStringArray(states.keys())
Arrays.sort(componentNames)
for (componentName in componentNames) {
assert(componentName != null)
val element = states.getElement(componentName, newLiveStates)
// name attribute should be first
val elementAttributes = element.getAttributes()
if (elementAttributes.isEmpty()) {
element.setAttribute(StateMap.NAME, componentName)
}
else {
var nameAttribute: Attribute? = element.getAttribute(StateMap.NAME)
if (nameAttribute == null) {
nameAttribute = Attribute(StateMap.NAME, componentName)
elementAttributes.add(0, nameAttribute)
}
else {
nameAttribute.setValue(componentName)
if (elementAttributes.get(0) != nameAttribute) {
elementAttributes.remove(nameAttribute)
elementAttributes.add(0, nameAttribute)
}
}
}
rootElement.addContent(element)
}
return rootElement
}
fun setStateAndCloneIfNeed(componentName: String, newState: Element?, oldStates: StateMap, newLiveStates: MutableMap<String, Element>): StateMap? {
val oldState = oldStates.get(componentName)
if (newState == null || JDOMUtil.isEmpty(newState)) {
if (oldState == null) {
return null
}
val newStates = StateMap(oldStates)
newStates.remove(componentName)
return newStates
}
prepareElement(newState)
newLiveStates.put(componentName, newState)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return null
}
}
else if (oldState != null) {
newBytes = StateMap.getNewByteIfDiffers(componentName, newState, oldState as ByteArray)
if (newBytes == null) {
return null
}
}
val newStates = StateMap(oldStates)
newStates.put(componentName, newBytes ?: newState)
return newStates
}
fun prepareElement(state: Element) {
if (state.getParent() != null) {
LOG.warn("State element must not have parent ${JDOMUtil.writeElement(state)}")
state.detach()
}
state.setName(StateMap.COMPONENT)
}
fun StateMap.setState(componentName: String, newState: Element?, newLiveStates: MutableMap<String, Element>): Any? {
if (newState == null || JDOMUtil.isEmpty(newState)) {
return remove(componentName)
}
prepareElement(newState)
newLiveStates.put(componentName, newState)
val oldState = get(componentName)
var newBytes: ByteArray? = null
if (oldState is Element) {
if (JDOMUtil.areElementsEqual(oldState as Element?, newState)) {
return null
}
}
else if (oldState != null) {
newBytes = StateMap.getNewByteIfDiffers(componentName, newState, oldState as ByteArray)
if (newBytes == null) {
return null
}
}
put(componentName, if (newBytes == null) newState else newBytes)
return newState
}
// newStorageData - myStates contains only live (unarchived) states
private fun StateMap.getChangedComponentNames(newStates: StateMap): Set<String> {
val bothStates = SmartHashSet(keys())
bothStates.retainAll(newStates.keys())
val diffs = SmartHashSet<String>()
diffs.addAll(newStates.keys())
diffs.addAll(keys())
diffs.removeAll(bothStates)
for (componentName in bothStates) {
compare(componentName, newStates, diffs)
}
return diffs
}
|
apache-2.0
|
78796c0a8b927ab24cd7ca785d37aa7e
| 32.668712 | 175 | 0.690478 | 4.826297 | false | false | false | false |
googlearchive/android-RecyclerView
|
kotlinApp/app/src/main/java/com/example/android/recyclerview/RecyclerViewFragment.kt
|
3
|
5215
|
/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.example.android.recyclerview
import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.RadioButton
/**
* Demonstrates the use of [RecyclerView] with a [LinearLayoutManager] and a
* [GridLayoutManager].
*/
class RecyclerViewFragment : Fragment() {
private lateinit var currentLayoutManagerType: LayoutManagerType
private lateinit var recyclerView: RecyclerView
private lateinit var layoutManager: RecyclerView.LayoutManager
private lateinit var dataset: Array<String>
enum class LayoutManagerType { GRID_LAYOUT_MANAGER, LINEAR_LAYOUT_MANAGER }
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
// Initialize dataset, this data would usually come from a local content provider or
// remote server.
initDataset()
}
override fun onCreateView(inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?): View? {
val rootView = inflater.inflate(R.layout.recycler_view_frag,
container, false).apply { tag = TAG}
recyclerView = rootView.findViewById(R.id.recyclerView)
// LinearLayoutManager is used here, this will layout the elements in a similar fashion
// to the way ListView would layout elements. The RecyclerView.LayoutManager defines how
// elements are laid out.
layoutManager = LinearLayoutManager(activity)
currentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER
if (savedInstanceState != null) {
// Restore saved layout manager type.
currentLayoutManagerType = savedInstanceState
.getSerializable(KEY_LAYOUT_MANAGER) as LayoutManagerType
}
setRecyclerViewLayoutManager(currentLayoutManagerType)
// Set CustomAdapter as the adapter for RecyclerView.
recyclerView.adapter = CustomAdapter(dataset)
rootView.findViewById<RadioButton>(R.id.linear_layout_rb).setOnClickListener{
setRecyclerViewLayoutManager(LayoutManagerType.LINEAR_LAYOUT_MANAGER)
}
rootView.findViewById<RadioButton>(R.id.grid_layout_rb).setOnClickListener{
setRecyclerViewLayoutManager(LayoutManagerType.GRID_LAYOUT_MANAGER)
}
return rootView
}
/**
* Set RecyclerView's LayoutManager to the one given.
*
* @param layoutManagerType Type of layout manager to switch to.
*/
private fun setRecyclerViewLayoutManager(layoutManagerType: LayoutManagerType) {
var scrollPosition = 0
// If a layout manager has already been set, get current scroll position.
if (recyclerView.layoutManager != null) {
scrollPosition = (recyclerView.layoutManager as LinearLayoutManager)
.findFirstCompletelyVisibleItemPosition()
}
when (layoutManagerType) {
RecyclerViewFragment.LayoutManagerType.GRID_LAYOUT_MANAGER -> {
layoutManager = GridLayoutManager(activity, SPAN_COUNT)
currentLayoutManagerType = LayoutManagerType.GRID_LAYOUT_MANAGER
}
RecyclerViewFragment.LayoutManagerType.LINEAR_LAYOUT_MANAGER -> {
layoutManager = LinearLayoutManager(activity)
currentLayoutManagerType = LayoutManagerType.LINEAR_LAYOUT_MANAGER
}
}
with(recyclerView) {
layoutManager = [email protected]
scrollToPosition(scrollPosition)
}
}
override fun onSaveInstanceState(savedInstanceState: Bundle) {
// Save currently selected layout manager.
savedInstanceState.putSerializable(KEY_LAYOUT_MANAGER, currentLayoutManagerType)
super.onSaveInstanceState(savedInstanceState)
}
/**
* Generates Strings for RecyclerView's adapter. This data would usually come
* from a local content provider or remote server.
*/
private fun initDataset() {
dataset = Array(DATASET_COUNT, {i -> "This is element # $i"})
}
companion object {
private val TAG = "RecyclerViewFragment"
private val KEY_LAYOUT_MANAGER = "layoutManager"
private val SPAN_COUNT = 2
private val DATASET_COUNT = 60
}
}
|
apache-2.0
|
eefcd5dd0b266be5dbd93fefa3651e9f
| 36.517986 | 96 | 0.697411 | 5.316004 | false | false | false | false |
alashow/music-android
|
modules/ui-artist/src/main/java/tm/alashow/datmusic/ui/artist/ArtistDetailViewModel.kt
|
1
|
1436
|
/*
* Copyright (C) 2021, Alashov Berkeli
* All rights reserved.
*/
package tm.alashow.datmusic.ui.artist
import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import javax.inject.Inject
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.launch
import tm.alashow.base.util.extensions.stateInDefault
import tm.alashow.datmusic.data.interactors.GetArtistDetails
import tm.alashow.datmusic.data.observers.ObserveArtist
import tm.alashow.datmusic.data.observers.ObserveArtistDetails
import tm.alashow.datmusic.data.repos.artist.DatmusicArtistParams
import tm.alashow.navigation.ARTIST_ID_KEY
@HiltViewModel
class ArtistDetailViewModel @Inject constructor(
private val handle: SavedStateHandle,
private val artist: ObserveArtist,
private val artistDetails: ObserveArtistDetails
) : ViewModel() {
private val artistParams = DatmusicArtistParams(handle.get<String>(ARTIST_ID_KEY)!!)
val state = combine(artist.flow, artistDetails.flow, ::ArtistDetailViewState)
.stateInDefault(viewModelScope, ArtistDetailViewState.Empty)
init {
load()
}
private fun load(forceRefresh: Boolean = false) = viewModelScope.launch {
artist(artistParams)
artistDetails(GetArtistDetails.Params(artistParams, forceRefresh))
}
fun refresh() = load(true)
}
|
apache-2.0
|
ceca8f6ae2270fbf2c0a69302636c136
| 32.395349 | 88 | 0.787604 | 4.351515 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.