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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/rename/KotlinMemberInplaceRenameHandler.kt | 4 | 3839 | // 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.refactoring.rename
import com.intellij.lang.Language
import com.intellij.openapi.editor.Editor
import com.intellij.psi.*
import com.intellij.refactoring.RefactoringActionHandler
import com.intellij.refactoring.rename.inplace.MemberInplaceRenameHandler
import com.intellij.refactoring.rename.inplace.MemberInplaceRenamer
import com.intellij.refactoring.rename.inplace.VariableInplaceRenamer
import org.jetbrains.kotlin.idea.base.psi.unquoteKotlinIdentifier
import org.jetbrains.kotlin.psi.KtNamedDeclaration
import org.jetbrains.kotlin.psi.KtObjectDeclaration
import org.jetbrains.kotlin.psi.KtPrimaryConstructor
class KotlinMemberInplaceRenameHandler : MemberInplaceRenameHandler() {
private class RenamerImpl(
elementToRename: PsiNamedElement,
substitutedElement: PsiElement?,
editor: Editor,
currentName: String,
oldName: String
) : MemberInplaceRenamer(elementToRename, substitutedElement, editor, currentName, oldName) {
override fun isIdentifier(newName: String?, language: Language?): Boolean {
if (newName == "" && (variable as? KtObjectDeclaration)?.isCompanion() == true) return true
return super.isIdentifier(newName, language)
}
override fun acceptReference(reference: PsiReference): Boolean {
val refElement = reference.element
val textRange = reference.rangeInElement
val referenceText = refElement.text.substring(textRange.startOffset, textRange.endOffset).unquoteKotlinIdentifier()
return referenceText == myElementToRename.name
}
override fun startsOnTheSameElement(handler: RefactoringActionHandler?, element: PsiElement?): Boolean {
return variable == element && (handler is MemberInplaceRenameHandler || handler is KotlinRenameDispatcherHandler)
}
override fun createInplaceRenamerToRestart(variable: PsiNamedElement, editor: Editor, initialName: String): VariableInplaceRenamer {
return RenamerImpl(variable, substituted, editor, initialName, myOldName)
}
}
private fun PsiElement.substitute(): PsiElement {
if (this is KtPrimaryConstructor) return getContainingClassOrObject()
return this
}
override fun createMemberRenamer(element: PsiElement, elementToRename: PsiNameIdentifierOwner, editor: Editor): MemberInplaceRenamer {
val currentElementToRename = elementToRename.substitute() as PsiNameIdentifierOwner
val nameIdentifier = currentElementToRename.nameIdentifier
// Move caret if constructor range doesn't intersect with the one of the containing class
val offset = editor.caretModel.offset
val editorPsiFile = PsiDocumentManager.getInstance(element.project).getPsiFile(editor.document)
if (nameIdentifier != null && editorPsiFile == elementToRename.containingFile && elementToRename is KtPrimaryConstructor && offset !in nameIdentifier.textRange && offset in elementToRename.textRange) {
editor.caretModel.moveToOffset(nameIdentifier.textOffset)
}
val currentName = nameIdentifier?.text ?: ""
return RenamerImpl(currentElementToRename, element, editor, currentName, currentName)
}
override fun isAvailable(element: PsiElement?, editor: Editor, file: PsiFile): Boolean {
if (!editor.settings.isVariableInplaceRenameEnabled) return false
val currentElement = element?.substitute() as? KtNamedDeclaration ?: return false
return currentElement.nameIdentifier != null && !KotlinVariableInplaceRenameHandler.isInplaceRenameAvailable(currentElement)
}
}
| apache-2.0 | 5087d9b674d114522f17bd8edd9e6f30 | 53.070423 | 209 | 0.753321 | 5.629032 | false | false | false | false |
GunoH/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/projectActions/MoveProjectToGroupActionGroup.kt | 3 | 1651 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license.
package com.intellij.openapi.wm.impl.welcomeScreen.projectActions
import com.intellij.ide.RecentProjectsManager
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.project.DumbAware
import com.intellij.openapi.util.text.NaturalComparator
import com.intellij.openapi.wm.impl.welcomeScreen.projectActions.RecentProjectsWelcomeScreenActionBase.Companion.getSelectedItem
import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.CloneableProjectItem
import com.intellij.openapi.wm.impl.welcomeScreen.recentProjects.RecentProjectItem
/**
* @author Konstantin Bulenkov
*/
class MoveProjectToGroupActionGroup : DefaultActionGroup(), DumbAware {
override fun getActionUpdateThread(): ActionUpdateThread {
return ActionUpdateThread.EDT
}
override fun getChildren(e: AnActionEvent?): Array<AnAction> {
if (e == null) return AnAction.EMPTY_ARRAY
val item = getSelectedItem(e)
if (item is RecentProjectItem || item is CloneableProjectItem) {
val result = mutableListOf<AnAction>()
val groups = RecentProjectsManager.getInstance().groups.sortedWith(compareBy(NaturalComparator.INSTANCE) { it.name })
for (group in groups) {
if (group.isTutorials) {
continue
}
result.add(MoveProjectToGroupAction(group))
}
if (groups.isNotEmpty()) {
result.add(Separator.getInstance())
result.add(RemoveSelectedProjectsFromGroupsAction())
}
return result.toTypedArray()
}
return AnAction.EMPTY_ARRAY
}
} | apache-2.0 | ca4611beb0fcfada756d1469e7f4aa9d | 38.333333 | 128 | 0.757723 | 4.62465 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/refactoring/inline/KotlinInlineActionHandler.kt | 4 | 2749 | // 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.refactoring.inline
import com.intellij.lang.Language
import com.intellij.lang.findUsages.DescriptiveNameUtil
import com.intellij.lang.refactoring.InlineActionHandler
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsContexts
import com.intellij.psi.PsiElement
import com.intellij.refactoring.util.CommonRefactoringUtil
import org.jetbrains.kotlin.asJava.unwrapped
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.KotlinLanguage
import org.jetbrains.kotlin.psi.KtElement
abstract class KotlinInlineActionHandler : InlineActionHandler() {
override fun isEnabledForLanguage(language: Language) = language == KotlinLanguage.INSTANCE
final override fun canInlineElement(element: PsiElement): Boolean {
val kotlinElement = unwrapKotlinElement(element) ?: return false
return canInlineKotlinElement(kotlinElement)
}
final override fun inlineElement(project: Project, editor: Editor?, element: PsiElement) {
val kotlinElement = unwrapKotlinElement(element) ?: error("Kotlin element not found")
KotlinInlineRefactoringFUSCollector.log(elementFrom = kotlinElement, languageTo = KotlinLanguage.INSTANCE, isCrossLanguage = false)
inlineKotlinElement(project, editor, kotlinElement)
}
override fun getActionName(element: PsiElement?): String = refactoringName
abstract fun canInlineKotlinElement(element: KtElement): Boolean
abstract fun inlineKotlinElement(project: Project, editor: Editor?, element: KtElement)
abstract val refactoringName: @NlsContexts.DialogTitle String
open val helpId: String? = null
fun showErrorHint(project: Project, editor: Editor?, @NlsContexts.DialogMessage message: String) {
CommonRefactoringUtil.showErrorHint(project, editor, message, refactoringName, helpId)
}
fun checkSources(project: Project, editor: Editor?, declaration: KtElement): Boolean = !declaration.containingKtFile.isCompiled.also {
if (it) {
val declarationName = DescriptiveNameUtil.getDescriptiveName(declaration)
showErrorHint(
project,
editor,
KotlinBundle.message("error.hint.text.cannot.inline.0.from.a.decompiled.file", declarationName)
)
}
}
}
private fun unwrapKotlinElement(element: PsiElement): KtElement? {
val ktElement = element.unwrapped as? KtElement
return ktElement?.navigationElement as? KtElement ?: ktElement
}
| apache-2.0 | f2703be6357608495d8dcc2a586a6b49 | 46.396552 | 158 | 0.76355 | 4.865487 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/core/src/org/intellij/plugins/markdown/lang/psi/impl/MarkdownLinkDefinition.kt | 5 | 1924 | package org.intellij.plugins.markdown.lang.psi.impl
import com.intellij.extapi.psi.ASTWrapperPsiElement
import com.intellij.lang.ASTNode
import com.intellij.navigation.ItemPresentation
import com.intellij.psi.PsiElement
import com.intellij.psi.util.parentOfType
import org.intellij.plugins.markdown.lang.MarkdownElementTypes
import org.intellij.plugins.markdown.lang.psi.MarkdownPsiElement
import org.intellij.plugins.markdown.lang.psi.util.childrenOfType
import org.intellij.plugins.markdown.structureView.MarkdownBasePresentation
class MarkdownLinkDefinition(node: ASTNode): ASTWrapperPsiElement(node), MarkdownPsiElement {
val linkLabel: MarkdownLinkLabel
get() = findChildByType(MarkdownElementTypes.LINK_LABEL) ?: error("Failed to find link label. Seems link parsing has failed.")
val linkDestination: MarkdownLinkDestination
get() = findChildByType(MarkdownElementTypes.LINK_DESTINATION) ?: error("Failed to find link destination. Seems link parsing has failed.")
val linkTitle: PsiElement?
get() = findChildByType(MarkdownElementTypes.LINK_TITLE)
internal val isCommentWrapper
get() = childrenOfType(MarkdownElementTypes.LINK_COMMENT).any()
override fun getPresentation(): ItemPresentation {
return LinkDefinitionPresentation()
}
private inner class LinkDefinitionPresentation: MarkdownBasePresentation() {
override fun getPresentableText(): String? {
return when {
!isValid -> null
else -> "Def: ${linkLabel.text} → ${linkDestination.text}"
}
}
override fun getLocationString(): String? {
return when {
!isValid -> null
else -> linkTitle?.text
}
}
}
companion object {
internal fun isUnderCommentWrapper(element: PsiElement): Boolean {
val linkDefinition = element.parentOfType<MarkdownLinkDefinition>(withSelf = true)
return linkDefinition?.isCommentWrapper == true
}
}
}
| apache-2.0 | 5e635fd83d32f6d89dc7c8d1dcb63e54 | 35.961538 | 142 | 0.759625 | 4.890585 | false | false | false | false |
GunoH/intellij-community | platform/statistics/src/com/intellij/internal/statistic/eventLog/events/scheme/EventsSchemeBuilder.kt | 4 | 8980 | // 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.internal.statistic.eventLog.events.scheme
import com.intellij.internal.statistic.eventLog.events.*
import com.intellij.internal.statistic.service.fus.collectors.ApplicationUsagesCollector
import com.intellij.internal.statistic.service.fus.collectors.FUCounterUsageLogger
import com.intellij.internal.statistic.service.fus.collectors.FeatureUsagesCollector
import com.intellij.internal.statistic.service.fus.collectors.ProjectUsagesCollector
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.extensions.PluginDescriptor
import java.util.regex.Pattern
object EventsSchemeBuilder {
val pluginInfoFields = setOf(
FieldDescriptor("plugin", setOf("{util#plugin}")),
FieldDescriptor("plugin_type", setOf("{util#plugin_type}")),
FieldDescriptor("plugin_version", setOf("{util#plugin_version}"))
)
private val classValidationRuleNames = setOf("class_name", "dialog_class", "quick_fix_class_name",
"run_config_factory", "tip_info", "run_config_factory",
"run_config_id", "facets_type", "registry_key")
private val classValidationRules = classValidationRuleNames.map { "{util#$it}" }
private fun fieldSchema(field: EventField<*>, fieldName: String, eventName: String, groupId: String): Set<FieldDescriptor> {
if (field.name.contains(".")) {
throw IllegalStateException("Field name should not contains dots, because dots are used to express hierarchy. " +
"Group=$groupId, event=$eventName, field=${field.name}")
}
return when (field) {
EventFields.PluginInfo,
EventFields.PluginInfoFromInstance, // todo extract marker trait for delegates
EventFields.PluginInfoByDescriptor,
-> pluginInfoFields
is ObjectEventField -> buildObjectEvenScheme(fieldName, field.fields, eventName, groupId)
is ObjectListEventField -> buildObjectEvenScheme(fieldName, field.fields, eventName, groupId)
is ListEventField<*> -> {
if (field is StringListEventField.ValidatedByInlineRegexp) {
validateRegexp(field.regexp)
}
buildFieldDescriptors(fieldName, field.validationRule, FieldDataType.ARRAY)
}
is PrimitiveEventField -> {
if (field is StringEventField.ValidatedByInlineRegexp) {
validateRegexp(field.regexp)
}
if (field is RegexpIntEventField) {
validateRegexp(field.regexp)
}
buildFieldDescriptors(fieldName, field.validationRule, FieldDataType.PRIMITIVE)
}
}
}
private fun buildFieldDescriptors(fieldName: String, validationRules: List<String>, fieldDataType: FieldDataType): Set<FieldDescriptor> {
val fields = mutableSetOf(FieldDescriptor(fieldName, validationRules.toSet(), fieldDataType))
if (validationRules.any { it in classValidationRules }) {
fields.addAll(pluginInfoFields)
}
return fields
}
private fun validateRegexp(regexp: String) {
if (regexp == ".*") {
throw IllegalStateException("Regexp should be more strict to prevent accidentally reporting sensitive data.")
}
Pattern.compile(regexp)
}
private fun buildObjectEvenScheme(fieldName: String, fields: Array<out EventField<*>>,
eventName: String, groupId: String): Set<FieldDescriptor> {
val fieldsDescriptors = mutableSetOf<FieldDescriptor>()
for (eventField in fields) {
fieldsDescriptors.addAll(fieldSchema(eventField, fieldName + "." + eventField.name, eventName, groupId))
}
return fieldsDescriptors
}
/**
* @param recorder id of the recorder, only groups from that recorder will be used to build scheme.
* If null, groups from all recorders will be used.
* @param pluginId id of the plugin, only groups registered in that plugin will be used to build scheme.
* If null, all registered groups will be used.
* @param brokenPluginIds list of plugin ids, groups registered in this plugins will **not** be used to build scheme.
* If null, all registered groups will be used.
* Only applicable when `pluginId == null`
*/
@JvmStatic
@JvmOverloads
fun buildEventsScheme(recorder: String?, pluginId: String? = null, brokenPluginIds: Set<String> = emptySet()): List<GroupDescriptor> {
val result = mutableListOf<GroupDescriptor>()
val counterCollectors = ArrayList<FeatureUsageCollectorInfo>()
FUCounterUsageLogger.EP_NAME.processWithPluginDescriptor { counterUsageCollectorEP, descriptor: PluginDescriptor ->
if (counterUsageCollectorEP.implementationClass != null) {
val collectorPlugin = descriptor.pluginId.idString
if ((pluginId == null && !brokenPluginIds.contains(collectorPlugin)) || pluginId == collectorPlugin) {
val collector = ApplicationManager.getApplication().instantiateClass<FeatureUsagesCollector>(
counterUsageCollectorEP.implementationClass, descriptor)
counterCollectors.add(FeatureUsageCollectorInfo(collector, collectorPlugin))
}
}
}
result.addAll(collectGroupsFromExtensions("counter", counterCollectors, recorder))
val stateCollectors = ArrayList<FeatureUsageCollectorInfo>()
ApplicationUsagesCollector.EP_NAME.processWithPluginDescriptor { collector, descriptor ->
val collectorPlugin = descriptor.pluginId.idString
if ((pluginId == null && !brokenPluginIds.contains(collectorPlugin)) || pluginId == collectorPlugin) {
stateCollectors.add(FeatureUsageCollectorInfo(collector, collectorPlugin))
}
}
ProjectUsagesCollector.EP_NAME.processWithPluginDescriptor { collector, descriptor ->
val collectorPlugin = descriptor.pluginId.idString
if ((pluginId == null && !brokenPluginIds.contains(collectorPlugin)) || pluginId == collectorPlugin) {
stateCollectors.add(FeatureUsageCollectorInfo(collector, collectorPlugin))
}
}
result.addAll(collectGroupsFromExtensions("state", stateCollectors, recorder))
result.sortBy(GroupDescriptor::id)
return result
}
fun collectGroupsFromExtensions(groupType: String,
collectors: Collection<FeatureUsageCollectorInfo>,
recorder: String?): MutableCollection<GroupDescriptor> {
val result = HashMap<String, GroupDescriptor>()
for ((collector, plugin) in collectors) {
val collectorClass = if (collector.javaClass.enclosingClass != null) collector.javaClass.enclosingClass else collector.javaClass
validateGroupId(collector)
val group = collector.group ?: continue
if (recorder != null && group.recorder != recorder) continue
val existingGroup = result[group.id]
if (existingGroup != null && group.version != existingGroup.version) {
throw IllegalStateException("If group is reused in multiple collectors classes (e.g Project and Application collector), " +
"it should have the same version (group=${group.id})")
}
val existingScheme = existingGroup?.schema ?: HashSet()
val eventsDescriptors = existingScheme + group.events.groupBy { it.eventId }
.map { (eventName, events) -> EventDescriptor(eventName, buildFields(events, eventName, group.id)) }
.toSet()
result[group.id] = GroupDescriptor(group.id, groupType, group.version, eventsDescriptors, collectorClass.name, group.recorder, plugin)
}
return result.values
}
private fun validateGroupId(collector: FeatureUsagesCollector) {
try {
// get group id to check that either group or group id is overridden
@Suppress("DEPRECATION")
collector.groupId
}
catch (e: IllegalStateException) {
throw IllegalStateException(e.message + " in " + collector.javaClass.name)
}
}
private fun buildFields(events: List<BaseEventId>, eventName: String, groupId: String): Set<FieldDescriptor> {
return events.flatMap { it.getFields() }
.flatMap { field -> fieldSchema(field, field.name, eventName, groupId) }
.groupBy { it.path }
.map { (name, values) ->
val type = defineDataType(values, name, eventName, groupId)
FieldDescriptor(name, values.flatMap { it.value }.toSet(), type)
}
.toSet()
}
private fun defineDataType(values: List<FieldDescriptor>, name: String, eventName: String, groupId: String): FieldDataType {
val dataType = values.first().dataType
return if (values.any { it.dataType != dataType })
throw IllegalStateException("Field couldn't have multiple types (group=$groupId, event=$eventName, field=$name)")
else {
dataType
}
}
data class FeatureUsageCollectorInfo(val collector: FeatureUsagesCollector,
val pluginId: String)
}
| apache-2.0 | aec45bfcaa8d72bf3dae5beb119f057d | 48.340659 | 140 | 0.704232 | 4.942212 | false | false | false | false |
jk1/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/resolve/BaseGroovyResolveResult.kt | 2 | 1463 | // 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.groovy.lang.resolve
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiMember
import com.intellij.psi.PsiModifierListOwner
import com.intellij.psi.PsiSubstitutor
import org.jetbrains.plugins.groovy.lang.psi.api.toplevel.imports.GrImportStatement
import org.jetbrains.plugins.groovy.lang.psi.util.GrStaticChecker
import org.jetbrains.plugins.groovy.lang.psi.util.PsiUtil
open class BaseGroovyResolveResult<out T : PsiElement>(
element: T,
private val place: PsiElement?,
private val resolveContext: PsiElement? = null,
private val substitutor: PsiSubstitutor = PsiSubstitutor.EMPTY
) : ElementResolveResult<T>(element) {
private val accessible by lazy(LazyThreadSafetyMode.PUBLICATION) {
element !is PsiMember || place == null || PsiUtil.isAccessible(place, element)
}
override fun isAccessible(): Boolean = accessible
private val staticsOk by lazy(LazyThreadSafetyMode.PUBLICATION) {
resolveContext is GrImportStatement ||
element !is PsiModifierListOwner ||
place == null ||
GrStaticChecker.isStaticsOK(element, place, resolveContext, false)
}
override fun isStaticsOK(): Boolean = staticsOk
override fun getCurrentFileResolveContext(): PsiElement? = resolveContext
override fun getSubstitutor(): PsiSubstitutor = substitutor
}
| apache-2.0 | 151efa91da3cc0325ddfd8940aee24a3 | 38.540541 | 140 | 0.787423 | 4.571875 | false | false | false | false |
RoyaAoki/Megumin | mobile/src/main/java/com/sqrtf/megumin/SearchActivity.kt | 1 | 4987 | package com.sqrtf.megumin
import android.content.Context
import android.content.Intent
import android.os.Bundle
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.view.inputmethod.EditorInfo.IME_ACTION_SEARCH
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import com.bumptech.glide.Glide
import com.bumptech.glide.load.engine.DiskCacheStrategy
import com.sqrtf.common.StringUtil
import com.sqrtf.common.activity.BaseActivity
import com.sqrtf.common.api.ApiClient
import com.sqrtf.common.api.ApiHelper
import com.sqrtf.common.model.Bangumi
import io.reactivex.functions.Consumer
class SearchActivity : BaseThemeActivity() {
companion object {
fun intent(context: Context): Intent {
val intent = Intent(context, SearchActivity::class.java)
return intent
}
private val TASK_ID_LOAD = 0x01
}
private val recyclerView by lazy { findViewById<RecyclerView>(R.id.recycler_view) }
private val edit by lazy { findViewById<EditText>(R.id.edit) }
private val bangumiList = arrayListOf<Bangumi>()
private val adapter = HomeAdapter()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_search)
findViewById<View>(R.id.back).setOnClickListener { super.onBackPressed() }
val mLayoutManager = LinearLayoutManager(this)
recyclerView.layoutManager = mLayoutManager
recyclerView.adapter = adapter
edit.setOnEditorActionListener { v, actionId, event ->
if (actionId == IME_ACTION_SEARCH && edit.text.isNotEmpty()) {
hideKeyboard()
search(edit.text.toString())
}
true
}
}
private fun search(s: String) {
ApiClient.getInstance().getSearchBangumi(1, 300, "air_date", "desc", s)
.withLifecycle()
.onlyRunOneInstance(SearchActivity.TASK_ID_LOAD, true)
.subscribe(Consumer {
display(it.getData())
}, toastErrors())
}
private fun display(data: List<Bangumi>) {
if (data.isEmpty()) {
showToast(getString(R.string.empty))
} else {
bangumiList.clear()
bangumiList.addAll(data)
adapter.notifyDataSetChanged()
}
}
private fun hideKeyboard() {
if (currentFocus == null) return
val inputManager = getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
inputManager.hideSoftInputFromWindow(this.currentFocus?.windowToken, InputMethodManager.HIDE_NOT_ALWAYS)
edit.clearFocus()
}
private class WideCardHolder(view: View) : RecyclerView.ViewHolder(view) {
val image = view.findViewById<ImageView>(R.id.imageView)
val title = view.findViewById<TextView>(R.id.title)
// val subtitle = view.findViewById<TextView>(R.id.subtitle)
val info = view.findViewById<TextView>(R.id.info)
val state = view.findViewById<TextView>(R.id.state)
val info2 = view.findViewById<TextView>(R.id.info2)
}
private inner class HomeAdapter : RecyclerView.Adapter<WideCardHolder>() {
override fun onCreateViewHolder(p0: ViewGroup, p1: Int): WideCardHolder = WideCardHolder(LayoutInflater.from(this@SearchActivity).inflate(R.layout.include_bangumi_wide, p0, false))
override fun onBindViewHolder(viewHolder: WideCardHolder, p1: Int) {
val bangumi = bangumiList[p1]
viewHolder.title.text = bangumi.name_cn
// viewHolder.subtitle.text = bangumi.name
viewHolder.info.text = viewHolder.info.resources.getString(R.string.update_info)
?.format(bangumi.eps, bangumi.air_weekday.let { StringUtil.dayOfWeek(it) }, bangumi.air_date)
if (bangumi.favorite_status > 0) {
val array = resources.getStringArray(R.array.array_favorite)
if (array.size > bangumi.favorite_status) {
viewHolder.state.text = array[bangumi.favorite_status]
}
} else {
viewHolder.state.text = ""
}
viewHolder.info2.text = bangumi.summary.replace("\n", "")
Glide.with(this@SearchActivity)
.load(bangumi.cover_image.fixedUrl())
.diskCacheStrategy(DiskCacheStrategy.SOURCE)
.into(viewHolder.image)
viewHolder.itemView.setOnClickListener {
[email protected](bangumi.let { it1 -> DetailActivity.intent(this@SearchActivity, it1) })
}
}
override fun getItemCount(): Int = bangumiList.size
}
}
| mit | 601a2b99b187dd1820ae3b279e98d883 | 37.960938 | 188 | 0.66152 | 4.472646 | false | false | false | false |
voxelcarrot/Warren | src/main/kotlin/engineer/carrot/warren/warren/IrcSocket.kt | 2 | 3375 | package engineer.carrot.warren.warren
import engineer.carrot.warren.kale.IKale
import engineer.carrot.warren.kale.irc.message.IIrcMessageSerialiser
import engineer.carrot.warren.warren.ssl.WrappedSSLSocketFactory
import okio.BufferedSink
import okio.BufferedSource
import okio.Okio
import java.io.IOException
import java.io.InterruptedIOException
import java.net.Socket
import java.util.concurrent.TimeUnit
interface ILineSource {
fun nextLine(): String?
}
class IrcSocket(val server: String, val port: Int, val useTLS: Boolean, val kale: IKale, val serialiser: IIrcMessageSerialiser, val fingerprints: Set<String>?) : IMessageSink, ILineSource {
private val LOGGER = loggerFor<IrcSocket>()
lateinit var socket: Socket
lateinit var source: BufferedSource
lateinit var sink: BufferedSink
private fun createTLSSocket(): Socket? {
val socketFactory = WrappedSSLSocketFactory(fingerprints)
try {
val socket = socketFactory.createSocket(server, port)
socket.startHandshake()
return socket
} catch (exception: Exception) {
LOGGER.error("failed to connect using: $server:$port $exception")
}
return null
}
private fun createPlaintextSocket(): Socket? {
try {
return Socket(server, port)
} catch (exception: Exception) {
LOGGER.error("failed to connect using $server:$port $exception")
}
return null
}
override fun setUp(): Boolean {
val rawSocket = if (useTLS) {
createTLSSocket()
} else {
LOGGER.warn("making a plaintext socket for connection to $server:$port - use TLS on port 6697 if the server supports it")
createPlaintextSocket()
}
if (rawSocket == null) {
LOGGER.error("failed to set up socket, bailing")
return false
}
socket = rawSocket
sink = Okio.buffer(Okio.sink(socket.outputStream))
source = Okio.buffer(Okio.source(socket.inputStream))
source.timeout().timeout(5, TimeUnit.SECONDS)
return true
}
override fun tearDown() {
socket.close()
}
override fun nextLine(): String? {
val line = try {
source.readUtf8LineStrict()
} catch (exception: IOException) {
LOGGER.warn("exception waiting for line: $exception")
return null
} catch (exception: InterruptedIOException) {
LOGGER.warn("process wait interrupted, bailing out")
tearDown()
return null
}
LOGGER.trace(">> $line")
return line
}
override fun write(message: Any) {
val ircMessage = kale.serialise(message)
if (ircMessage == null) {
LOGGER.error("failed to serialise to irc message: $message")
return
}
val line = serialiser.serialise(ircMessage)
if (line == null) {
LOGGER.error("failed to serialise to line: $ircMessage")
return
}
LOGGER.trace("<< $line")
sink.writeString(line + "\r\n", Charsets.UTF_8)
sink.flush()
}
override fun writeRaw(line: String) {
LOGGER.trace("<< RAW: $line")
sink.writeString(line + "\r\n", Charsets.UTF_8)
sink.flush()
}
} | isc | c94c48a57db2061db2e8b17aaf33dff5 | 26.447154 | 189 | 0.617778 | 4.585598 | false | false | false | false |
ayatk/biblio | infrastructure/database/src/main/java/com/ayatk/biblio/infrastructure/database/DatabaseModule.kt | 1 | 1641 | /*
* Copyright (c) 2016-2018 ayatk.
*
* 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.ayatk.biblio.infrastructure.database
import android.app.Application
import androidx.room.Room
import com.ayatk.biblio.infrastructure.database.dao.BookmarkDao
import com.ayatk.biblio.infrastructure.database.dao.EpisodeDao
import com.ayatk.biblio.infrastructure.database.dao.IndexDao
import com.ayatk.biblio.infrastructure.database.dao.NovelDao
import dagger.Module
import dagger.Provides
import javax.inject.Singleton
@Module
class DatabaseModule {
@Singleton
@Provides
fun provideDb(app: Application): AppDatabase =
Room.databaseBuilder(app, AppDatabase::class.java, "biblio.db")
.fallbackToDestructiveMigration()
.build()
@Singleton
@Provides
fun provideBookmarkDao(db: AppDatabase): BookmarkDao = db.bookmarkDao()
@Singleton
@Provides
fun provideEpisodeDao(db: AppDatabase): EpisodeDao = db.episodeDao()
@Singleton
@Provides
fun provideIndexDao(db: AppDatabase): IndexDao = db.indexDao()
@Singleton
@Provides
fun provideNovelDao(db: AppDatabase): NovelDao = db.novelDao()
}
| apache-2.0 | 629d673b19a785093a8d0bdd185e0d67 | 29.388889 | 75 | 0.764778 | 4.07196 | false | false | false | false |
jovr/imgui | core/src/main/kotlin/imgui/demo/ShowDemoWindowMisc.kt | 2 | 10965 | package imgui.demo
import glm_.i
import imgui.*
import imgui.ImGui.bullet
import imgui.ImGui.bulletText
import imgui.ImGui.button
import imgui.ImGui.captureKeyboardFromApp
import imgui.ImGui.foregroundDrawList
import imgui.ImGui.getMouseDragDelta
import imgui.ImGui.inputText
import imgui.ImGui.io
import imgui.ImGui.isItemActive
import imgui.ImGui.isItemHovered
import imgui.ImGui.isKeyPressed
import imgui.ImGui.isKeyReleased
import imgui.ImGui.isMouseClicked
import imgui.ImGui.isMouseDoubleClicked
import imgui.ImGui.isMouseDragging
import imgui.ImGui.isMousePosValid
import imgui.ImGui.isMouseReleased
import imgui.ImGui.mouseCursor
import imgui.ImGui.popAllowKeyboardFocus
import imgui.ImGui.pushAllowKeyboardFocus
import imgui.ImGui.sameLine
import imgui.ImGui.selectable
import imgui.ImGui.setKeyboardFocusHere
import imgui.ImGui.sliderFloat3
import imgui.ImGui.text
import imgui.ImGui.textWrapped
import imgui.api.demoDebugInformations.Companion.helpMarker
import imgui.classes.TextFilter
import imgui.dsl.collapsingHeader
import imgui.dsl.treeNode
object ShowDemoWindowMisc {
operator fun invoke() {
Filtering()
collapsingHeader("Inputs, Navigation & Focus") {
// Display ImGuiIO output flags
text("WantCaptureMouse: ${io.wantCaptureMouse}")
text("WantCaptureKeyboard: ${io.wantCaptureKeyboard}")
text("WantTextInput: ${io.wantTextInput}")
text("WantMoveMouse: ${io.wantSetMousePos}")
text("NavActive: ${io.navActive}, NavVisible: ${io.navVisible}")
treeNode("Keyboard, Mouse & Navigation State") {
if (isMousePosValid()) text("Mouse pos: (%g, %g)", io.mousePos.x, io.mousePos.y)
else text("Mouse pos: <INVALID>")
text("Mouse delta: (%g, %g)", io.mouseDelta.x, io.mouseDelta.y)
text("Mouse down:")
for (i in 0 until io.mouseDown.size)
if (io.mouseDownDuration[i] >= 0f) {
sameLine()
text("b$i (%.02f secs)", io.mouseDownDuration[i])
}
text("Mouse clicked:")
for (i in io.mouseDown.indices)
if (isMouseClicked(MouseButton of i)) {
sameLine()
text("b$i")
}
text("Mouse dblclick:")
for (i in io.mouseDown.indices)
if (isMouseDoubleClicked(MouseButton of i)) {
sameLine()
text("b$i")
}
text("Mouse released:")
for (i in io.mouseDown.indices)
if (isMouseReleased(MouseButton of i)) {
sameLine()
text("b$i")
}
text("Mouse wheel: %.1f", io.mouseWheel)
text("Keys down:")
for (i in io.keysDown.indices)
if (io.keysDownDuration[i] >= 0f) {
sameLine()
text("$i (0x%X) (%.02f secs)", i, io.keysDownDuration[i])
}
text("Keys pressed:")
for (i in io.keysDown.indices)
if (isKeyPressed(i)) {
sameLine()
text("$i (0x%X)", i)
}
text("Keys release:")
for (i in io.keysDown.indices)
if (isKeyReleased(i)) {
sameLine()
text("$i (0x%X)", i)
}
val ctrl = if (io.keyCtrl) "CTRL " else ""
val shift = if (io.keyShift) "SHIFT " else ""
val alt = if (io.keyAlt) "ALT " else ""
val super_ = if (io.keySuper) "SUPER " else ""
text("Keys mods: $ctrl$shift$alt$super_")
text("Chars queue:")
io.inputQueueCharacters.forEach { c ->
// UTF-8 will represent some characters using multiple bytes, so we join them here
// example: 'ç' becomes "0xC3, 0xA7"
val bytes = c.toString().toByteArray().joinToString { "0x%X".format(it) }
sameLine(); text("\'%c\' (%s)", if (c > ' ' && c.i <= 255) c else '?', bytes)
}
text("NavInputs down:")
io.navInputs.filter { it > 0f }.forEachIndexed { i, it -> sameLine(); text("[$i] %.2f", it) }
text("NavInputs pressed:")
io.navInputsDownDuration.filter { it == 0f }.forEachIndexed { i, _ -> sameLine(); text("[$i]") }
text("NavInputs duration:")
io.navInputsDownDuration.filter { it >= 0f }.forEachIndexed { i, it -> sameLine(); text("[$i] %.2f", it) }
button("Hovering me sets the\nkeyboard capture flag")
if (isItemHovered()) captureKeyboardFromApp(true)
sameLine()
button("Holding me clears the\nthe keyboard capture flag")
if (isItemActive) captureKeyboardFromApp(false)
}
Tabbing()
`Focus from code`()
treeNode("Dragging") {
textWrapped("You can use getMouseDragDelta(0) to query for the dragged amount on any widget.")
for(button in MouseButton.values())
if (button != MouseButton.None) {
text("IsMouseDragging(${button.i}):")
text(" w/ default threshold: ${isMouseDragging(button).i},")
text(" w/ zero threshold: ${isMouseDragging(button, 0f).i},")
text(" w/ large threshold: ${isMouseDragging(button, 20f)},")
}
button("Drag Me")
if (isItemActive)
foregroundDrawList.addLine(io.mouseClickedPos[0], io.mousePos, Col.Button.u32, 4f) // Draw a line between the button and the mouse cursor
// Drag operations gets "unlocked" when the mouse has moved past a certain threshold
// (the default threshold is stored in io.MouseDragThreshold). You can request a lower or higher
// threshold using the second parameter of IsMouseDragging() and GetMouseDragDelta().
val valueRaw = getMouseDragDelta(MouseButton.Left, 0f)
val valueWithLockThreshold = getMouseDragDelta(MouseButton.Left)
val mouseDelta = io.mouseDelta
text("GetMouseDragDelta(0):")
text(" w/ default threshold: (%.1f, %.1f)", valueWithLockThreshold.x, valueWithLockThreshold.y)
text(" w/ zero threshold: (%.1f, %.1f)", valueRaw.x, valueRaw.y)
text("io.MouseDelta: (%.1f, %.1f)", mouseDelta.x, mouseDelta.y)
}
treeNode("Mouse cursors") {
val current = mouseCursor
text("Current mouse cursor = ${current.i}: $current")
text("Hover to see mouse cursors:")
sameLine(); helpMarker(
"Your application can render a different mouse cursor based on what ImGui::GetMouseCursor() returns. " +
"If software cursor rendering (io.MouseDrawCursor) is set ImGui will draw the right cursor for you, " +
"otherwise your backend needs to handle it.")
for (i in 0 until MouseCursor.COUNT) {
bullet(); selectable("Mouse cursor $i: ${MouseCursor.of(i)}", false)
if (isItemHovered())
mouseCursor = MouseCursor.of(i)
}
}
}
}
object Filtering {
val filter = TextFilter()
operator fun invoke() {
collapsingHeader("Filtering") {
// Helper class to easy setup a text filter.
// You may want to implement a more feature-full filtering scheme in your own application.
text("Filter usage:\n" +
" \"\" display all lines\n" +
" \"xxx\" display lines containing \"xxx\"\n" +
" \"xxx,yyy\" display lines containing \"xxx\" or \"yyy\"\n" +
" \"-xxx\" hide lines containing \"xxx\"")
filter.draw()
val lines = arrayListOf("aaa1.c", "bbb1.c", "ccc1.c", "aaa2.cpp", "bbb2.cpp", "ccc2.cpp", "abc.h", "hello, world")
lines.stream().filter { filter.passFilter(it) }.forEach { bulletText(it) }
}
}
}
object Tabbing {
var buf = "hello".toByteArray(32)
operator fun invoke() {
treeNode("Tabbing") {
text("Use TAB/SHIFT+TAB to cycle through keyboard editable fields.")
inputText("1", buf)
inputText("2", buf)
inputText("3", buf)
pushAllowKeyboardFocus(false)
inputText("4 (tab skip)", buf)
//SameLine(); ShowHelperMarker("Use PushAllowKeyboardFocus(bool) to disable tabbing through certain widgets.");
popAllowKeyboardFocus()
inputText("5", buf)
}
}
}
object `Focus from code` {
var buf = "click on a button to set focus".toByteArray(128)
val f3 = FloatArray(3)
operator fun invoke() {
treeNode("Focus from code") {
val focus1 = button("Focus on 1"); sameLine()
val focus2 = button("Focus on 2"); sameLine()
val focus3 = button("Focus on 3")
var hasFocus = 0
if (focus1) setKeyboardFocusHere()
inputText("1", buf)
if (isItemActive) hasFocus = 1
if (focus2) setKeyboardFocusHere()
inputText("2", buf)
if (isItemActive) hasFocus = 2
pushAllowKeyboardFocus(false)
if (focus3) setKeyboardFocusHere()
inputText("3 (tab skip)", buf)
if (isItemActive) hasFocus = 3
popAllowKeyboardFocus()
text("Item with focus: ${if (hasFocus != 0) "$hasFocus" else "<none>"}")
// Use >= 0 parameter to SetKeyboardFocusHere() to focus an upcoming item
var focusAhead = -1
if (button("Focus on X")) focusAhead = 0; sameLine()
if (button("Focus on Y")) focusAhead = 1; sameLine()
if (button("Focus on Z")) focusAhead = 2
if (focusAhead != -1) setKeyboardFocusHere(focusAhead)
sliderFloat3("Float3", f3, 0f, 1f)
textWrapped("NB: Cursor & selection are preserved when refocusing last used item in code.")
}
}
}
} | mit | 90ee734590ad300492ae510f3ec9e25e | 43.755102 | 157 | 0.526541 | 4.677474 | false | false | false | false |
bozaro/git-lfs-java | gitlfs-common/src/main/kotlin/ru/bozaro/gitlfs/common/data/LockConflictRes.kt | 1 | 496 | package ru.bozaro.gitlfs.common.data
import com.fasterxml.jackson.annotation.JsonCreator
import com.fasterxml.jackson.annotation.JsonProperty
class LockConflictRes @JsonCreator constructor(
@field:JsonProperty(value = "message", required = true)
@param:JsonProperty(value = "message", required = true)
val message: String,
@field:JsonProperty(value = "lock", required = true)
@param:JsonProperty(value = "lock", required = true)
val lock: Lock
)
| lgpl-3.0 | d7bf2f35f3b08c652b998bda4654229f | 37.153846 | 63 | 0.707661 | 4.239316 | false | false | false | false |
google/android-fhir | engine/src/main/java/com/google/android/fhir/db/impl/dao/LocalChangeDao.kt | 1 | 5952 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.fhir.db.impl.dao
import androidx.room.Dao
import androidx.room.Insert
import androidx.room.Query
import androidx.room.Transaction
import ca.uhn.fhir.parser.IParser
import com.google.android.fhir.db.impl.entities.LocalChangeEntity
import com.google.android.fhir.db.impl.entities.LocalChangeEntity.Type
import com.google.android.fhir.db.impl.entities.ResourceEntity
import com.google.android.fhir.logicalId
import com.google.android.fhir.toTimeZoneString
import com.google.android.fhir.versionId
import java.util.Date
import org.hl7.fhir.r4.model.Resource
import org.hl7.fhir.r4.model.ResourceType
import timber.log.Timber
/**
* Dao for local changes made to a resource. One row in LocalChangeEntity corresponds to one change
* e.g. an INSERT or UPDATE. The UPDATES (diffs) are stored as RFC 6902 JSON patches. When a
* resource needs to be synced, all corresponding LocalChanges are 'squashed' to create a a single
* LocalChangeEntity to sync with the server.
*/
@Dao
internal abstract class LocalChangeDao {
lateinit var iParser: IParser
@Insert abstract suspend fun addLocalChange(localChangeEntity: LocalChangeEntity)
@Transaction
open suspend fun addInsertAll(resources: List<Resource>) {
resources.forEach { resource -> addInsert(resource) }
}
suspend fun addInsert(resource: Resource) {
val resourceId = resource.logicalId
val resourceType = resource.resourceType
val timestamp = Date().toTimeZoneString()
val resourceString = iParser.encodeResourceToString(resource)
addLocalChange(
LocalChangeEntity(
id = 0,
resourceType = resourceType.name,
resourceId = resourceId,
timestamp = timestamp,
type = Type.INSERT,
payload = resourceString,
versionId = resource.versionId
)
)
}
suspend fun addUpdate(oldEntity: ResourceEntity, resource: Resource) {
val resourceId = resource.logicalId
val resourceType = resource.resourceType
val timestamp = Date().toTimeZoneString()
if (!localChangeIsEmpty(resourceId, resourceType) &&
lastChangeType(resourceId, resourceType)!!.equals(Type.DELETE)
) {
throw InvalidLocalChangeException(
"Unexpected DELETE when updating $resourceType/$resourceId. UPDATE failed."
)
}
val jsonDiff =
LocalChangeUtils.diff(
iParser,
iParser.parseResource(oldEntity.serializedResource) as Resource,
resource
)
if (jsonDiff.length() == 0) {
Timber.i(
"New resource ${resource.resourceType}/${resource.id} is same as old resource. " +
"Not inserting UPDATE LocalChange."
)
return
}
addLocalChange(
LocalChangeEntity(
id = 0,
resourceType = resourceType.name,
resourceId = resourceId,
timestamp = timestamp,
type = Type.UPDATE,
payload = jsonDiff.toString(),
versionId = oldEntity.versionId
)
)
}
suspend fun addDelete(resourceId: String, resourceType: ResourceType, remoteVersionId: String?) {
val timestamp = Date().toTimeZoneString()
addLocalChange(
LocalChangeEntity(
id = 0,
resourceType = resourceType.name,
resourceId = resourceId,
timestamp = timestamp,
type = Type.DELETE,
payload = "",
versionId = remoteVersionId
)
)
}
@Query(
"""
SELECT type
FROM LocalChangeEntity
WHERE resourceId = :resourceId
AND resourceType = :resourceType
ORDER BY id ASC
LIMIT 1
"""
)
abstract suspend fun lastChangeType(resourceId: String, resourceType: ResourceType): Type?
@Query(
"""
SELECT COUNT(type)
FROM LocalChangeEntity
WHERE resourceId = :resourceId
AND resourceType = :resourceType
LIMIT 1
"""
)
abstract suspend fun countLastChange(resourceId: String, resourceType: ResourceType): Int
private suspend fun localChangeIsEmpty(resourceId: String, resourceType: ResourceType): Boolean =
countLastChange(resourceId, resourceType) == 0
@Query(
"""
SELECT *
FROM LocalChangeEntity
ORDER BY LocalChangeEntity.id ASC"""
)
abstract suspend fun getAllLocalChanges(): List<LocalChangeEntity>
@Query(
"""
DELETE FROM LocalChangeEntity
WHERE LocalChangeEntity.id = (:id)
"""
)
abstract suspend fun discardLocalChanges(id: Long)
@Transaction
open suspend fun discardLocalChanges(token: LocalChangeToken) {
token.ids.forEach { discardLocalChanges(it) }
}
@Query(
"""
DELETE FROM LocalChangeEntity
WHERE resourceId = (:resourceId)
AND resourceType = :resourceType
"""
)
abstract suspend fun discardLocalChanges(resourceId: String, resourceType: ResourceType)
suspend fun discardLocalChanges(resources: List<Resource>) {
resources.forEach { discardLocalChanges(it.logicalId, it.resourceType) }
}
@Query(
"""
SELECT *
FROM LocalChangeEntity
WHERE resourceId = :resourceId AND resourceType = :resourceType
"""
)
abstract suspend fun getLocalChanges(
resourceType: ResourceType,
resourceId: String
): List<LocalChangeEntity>
class InvalidLocalChangeException(message: String?) : Exception(message)
}
| apache-2.0 | 2184bcba9e16c89b66cd4c75ca40f8ba | 29.060606 | 99 | 0.692708 | 4.690307 | false | false | false | false |
iSoron/uhabits | uhabits-core-legacy/src/main/js/org/isoron/platform/io/JsFiles.kt | 1 | 5644 | /*
* Copyright (C) 2016-2019 Álinson Santos Xavier <[email protected]>
*
* This file is part of Loop Habit Tracker.
*
* Loop Habit Tracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by the
* Free Software Foundation, either version 3 of the License, or (at your
* option) any later version.
*
* Loop Habit Tracker is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
* more details.
*
* You should have received a copy of the GNU General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.isoron.platform.io
import kotlinx.coroutines.*
import org.isoron.platform.gui.*
import org.isoron.platform.gui.Image
import org.w3c.dom.*
import org.w3c.xhr.*
import kotlin.browser.*
import kotlin.js.*
class JsFileStorage {
private val TAG = "JsFileStorage"
private val log = StandardLog()
private val indexedDB = eval("indexedDB")
private var db: dynamic = null
private val DB_NAME = "Main"
private val OS_NAME = "Files"
suspend fun init() {
log.info(TAG, "Initializing")
Promise<Int> { resolve, reject ->
val req = indexedDB.open(DB_NAME, 2)
req.onerror = { reject(Exception("could not open IndexedDB")) }
req.onupgradeneeded = {
log.info(TAG, "Creating document store")
req.result.createObjectStore(OS_NAME)
}
req.onsuccess = {
log.info(TAG, "Ready")
db = req.result
resolve(0)
}
}.await()
}
suspend fun delete(path: String) {
Promise<Int> { resolve, reject ->
val transaction = db.transaction(OS_NAME, "readwrite")
val os = transaction.objectStore(OS_NAME)
val req = os.delete(path)
req.onerror = { reject(Exception("could not delete $path")) }
req.onsuccess = { resolve(0) }
}.await()
}
suspend fun put(path: String, content: String) {
Promise<Int> { resolve, reject ->
val transaction = db.transaction(OS_NAME, "readwrite")
val os = transaction.objectStore(OS_NAME)
val req = os.put(content, path)
req.onerror = { reject(Exception("could not put $path")) }
req.onsuccess = { resolve(0) }
}.await()
}
suspend fun get(path: String): String {
return Promise<String> { resolve, reject ->
val transaction = db.transaction(OS_NAME, "readonly")
val os = transaction.objectStore(OS_NAME)
val req = os.get(path)
req.onerror = { reject(Exception("could not get $path")) }
req.onsuccess = { resolve(req.result) }
}.await()
}
suspend fun exists(path: String): Boolean {
return Promise<Boolean> { resolve, reject ->
val transaction = db.transaction(OS_NAME, "readonly")
val os = transaction.objectStore(OS_NAME)
val req = os.count(path)
req.onerror = { reject(Exception("could not count $path")) }
req.onsuccess = { resolve(req.result > 0) }
}.await()
}
}
class JsFileOpener(val fileStorage: JsFileStorage) : FileOpener {
override fun openUserFile(path: String): UserFile {
return JsUserFile(fileStorage, path)
}
override fun openResourceFile(path: String): ResourceFile {
return JsResourceFile(path)
}
}
class JsUserFile(val fs: JsFileStorage,
val filename: String) : UserFile {
override suspend fun lines(): List<String> {
return fs.get(filename).lines()
}
override suspend fun delete() {
fs.delete(filename)
}
override suspend fun exists(): Boolean {
return fs.exists(filename)
}
}
class JsResourceFile(val filename: String) : ResourceFile {
override suspend fun exists(): Boolean {
return Promise<Boolean> { resolve, reject ->
val xhr = XMLHttpRequest()
xhr.open("GET", "/assets/$filename", true)
xhr.onload = { resolve(xhr.status.toInt() != 404) }
xhr.onerror = { reject(Exception()) }
xhr.send()
}.await()
}
override suspend fun lines(): List<String> {
return Promise<List<String>> { resolve, reject ->
val xhr = XMLHttpRequest()
xhr.open("GET", "/assets/$filename", true)
xhr.onload = { resolve(xhr.responseText.lines()) }
xhr.onerror = { reject(Exception()) }
xhr.send()
}.await()
}
override suspend fun copyTo(dest: UserFile) {
val fs = (dest as JsUserFile).fs
fs.put(dest.filename, lines().joinToString("\n"))
}
override suspend fun toImage(): Image {
return Promise<Image> { resolve, reject ->
val img = org.w3c.dom.Image()
img.onload = {
val canvas = JsCanvas(document.createElement("canvas") as HTMLCanvasElement, 1.0)
canvas.element.width = img.naturalWidth
canvas.element.height = img.naturalHeight
canvas.setColor(Color(0xffffff))
canvas.fillRect(0.0, 0.0, canvas.getWidth(), canvas.getHeight())
canvas.ctx.drawImage(img, 0.0, 0.0)
resolve(canvas.toImage())
}
img.src = "/assets/$filename"
}.await()
}
}
| gpl-3.0 | b46bddda383d8d719ca4b20742dcdb85 | 33.2 | 97 | 0.593656 | 4.140132 | false | false | false | false |
CodeNinjaResearch/tailCallFibonacci | src/main/java/main.kt | 1 | 1772 |
import api.Fibonacci
import org.jfree.chart.JFreeChart
import src.Recursive
import src.TailRec
import src.util.PlotK
import java.awt.EventQueue
import kotlin.concurrent.thread
/**
* Created by vicboma on 31/10/15.
*/
fun main(args: Array<String>) {
val rangeSequence = 50
val namePlot = "Fibonacci"
val plot = PlotK(namePlot,rangeSequence)
val listOfFibo = listFibonacci()
execute(listOfFibo, rangeSequence,plot)
}
private fun <T>execute(fibonacci: T, sequence: Long): Long where T: Fibonacci = fibonacci.method(sequence)
private fun listFibonacci() = listOf(Recursive(), TailRec())
private fun execute<T>(listFibo: List<T>, rangeSequence: Int, plot : PlotK) where T: Fibonacci {
for(fibo in listFibo) {
thread{
for (sequence in 0..rangeSequence) {
val execute = calcule(fibo, sequence)
draw(execute, fibo, plot, sequence)
}
}
}
}
private fun <T> calcule(fibo: T, sequence: Int): Long where T : Fibonacci {
val timeInit = System.nanoTime()
val execute = execute(fibo, sequence.toLong())
val timeEnd = System.nanoTime() - timeInit
println("${fibo.javaClass.canonicalName} ${execute}")
return execute
}
private fun <T> draw(execute: Long, fibo: T, plot: PlotK, sequence: Int) where T : Fibonacci {
EventQueue.invokeAndWait {
addValueDataSet(fibo, plot, sequence, execute)
drawPlot(plot.chart, sequence)
}
}
private fun addValueDataSet<T>(fibo: T, plot: PlotK, sequence: Int, value: Long) where T : api.Fibonacci {
plot.dataset.addValue(value, fibo.javaClass.canonicalName, sequence)
}
private fun drawPlot(plot : JFreeChart, sequence: Int) {
plot.setTitle("Fibonacci T($sequence)")
}
| mit | f834465f446a9a2cfc4d787bae88d36b | 20.349398 | 107 | 0.671558 | 3.601626 | false | false | false | false |
dahlstrom-g/intellij-community | java/java-impl/src/com/intellij/codeInsight/intention/impl/IntentionActionGroup.kt | 8 | 2607 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.codeInsight.intention.impl
import com.intellij.codeInsight.intention.IntentionAction
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.jetbrains.annotations.Nls
/**
* This action represents a group of similar actions with ability to choose one.
* - if all actions in group are unavailable, then this action becomes unavailable too;
* - if one action in group is available, then this action uses its text and invokes it without [choosing][chooseAction];
* - otherwise [getGroupText] and [chooseAction] are used.
*
* @param T type of actions
*/
abstract class IntentionActionGroup<T : IntentionAction>(private val actions: List<T>) : BaseIntentionAction() {
final override fun getElementToMakeWritable(currentFile: PsiFile): PsiElement? = null
final override fun startInWriteAction(): Boolean = false
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean {
if (editor == null || file == null) return false
val availableActions = actions.filter { it.isAvailable(project, editor, file) }
if (availableActions.isEmpty()) return false
text = availableActions.singleOrNull()?.text ?: getGroupText(availableActions)
return true
}
/**
* @param actions list of available actions with 2 elements minimum
* @return text of this action
*/
@Nls(capitalization = Nls.Capitalization.Sentence)
protected abstract fun getGroupText(actions: List<T>): String
final override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
if (editor == null || file == null) return
val availableActions = actions.filter { it.isAvailable(project, editor, file) }
if (availableActions.isEmpty()) return
fun invokeAction(action: IntentionAction) {
ShowIntentionActionsHandler.chooseActionAndInvoke(file, editor, action, action.text)
}
val singleAction = availableActions.singleOrNull()
if (singleAction != null) {
invokeAction(singleAction)
}
else {
chooseAction(project, editor, file, actions, ::invokeAction)
}
}
/**
* @param actions list of available actions with 2 elements minimum
* @param invokeAction consumer which invokes the selected action
*/
protected abstract fun chooseAction(project: Project, editor: Editor, file: PsiFile, actions: List<T>, invokeAction: (T) -> Unit)
}
| apache-2.0 | 47585e9588be5024301b9d0a2df51e8a | 38.5 | 140 | 0.739547 | 4.464041 | false | false | false | false |
dahlstrom-g/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/kdoc/KotlinExternalDocs.kt | 5 | 17167 | // 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.kdoc
import com.intellij.codeInsight.documentation.AbstractExternalFilter
import com.intellij.codeInsight.javadoc.JavaDocInfoGenerator
import com.intellij.ide.BrowserUtil
import com.intellij.lang.java.JavaDocumentationProvider
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.util.io.FileUtil
import com.intellij.openapi.vfs.VfsUtilCore
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.*
import com.intellij.psi.util.PsiUtil
import com.intellij.util.Urls
import com.intellij.util.castSafelyTo
import org.intellij.lang.annotations.Language
import org.jetbrains.annotations.Nls
import org.jetbrains.annotations.VisibleForTesting
import org.jetbrains.builtInWebServer.BuiltInServerOptions
import org.jetbrains.builtInWebServer.WebServerPathToFileManager
import org.jetbrains.kotlin.asJava.LightClassUtil
import org.jetbrains.kotlin.asJava.classes.KtLightClass
import org.jetbrains.kotlin.asJava.elements.KtLightDeclaration
import org.jetbrains.kotlin.asJava.elements.KtLightField
import org.jetbrains.kotlin.asJava.elements.KtLightMember
import org.jetbrains.kotlin.asJava.elements.KtLightMethod
import org.jetbrains.kotlin.idea.KotlinDocumentationProvider
import org.jetbrains.kotlin.idea.util.application.runReadAction
import org.jetbrains.kotlin.psi.*
import org.jetbrains.uast.*
import org.jsoup.Jsoup
import org.jsoup.nodes.Element
import java.io.ByteArrayInputStream
import java.io.Reader
import java.nio.charset.StandardCharsets
import java.util.regex.Pattern
/**
* A set of utilities for generating external docs urls for given Kotlin elements,
* which then can be fetched by the [KotlinDocExtractorFromJavaDoc].
*/
object KotlinExternalDocUrlsProvider {
/**
* Generates list of possible urls to JavaDocs.html for the given Kotlin [element].
*
* Note that different `javadoc` versions may generate docs' html pages with different anchors id format,
* e.g. placing anchor for method as `<a id='method(Arg1Type,Arg2Type)'/>` or `<a id='method-Arg1Type-Arg2Type-'/>`.
*
* So, for example, for the method `Pizza#contains(ingredient: Pizza.Ingredient)` possible urls may be
* ```kotlin
* listOf(
* "http://localhost:63343/kotlin-use-javadoc-library/test-library-1.0-SNAPSHOT-javadoc.jar/some/pack/Pizza.html#contains(Pizza.Ingredient)",
*
* "http://localhost:63343/kotlin-use-javadoc-library/test-library-1.0-SNAPSHOT-javadoc.jar/some/pack/Pizza.html#contains-Pizza.Ingredient-"
* )
* ```
* where paths lead to our [org.jetbrains.builtInWebServer].
* Note anchors `contains(Pizza.Ingredient)` and `contains-Pizza.Ingredient-`
* by which the [fetcher][KotlinDocExtractorFromJavaDoc]
* is supposed to understand which part of the docs is requested.
*/
fun getExternalJavaDocUrl(element: PsiElement?): List<String>? {
val urls: List<String>? = when (element) {
is KtEnumEntry -> findUrlsForEnumEntry(element)
is KtClass -> findUrlsForClass(element)
is KtFunction -> findUrlsForLightElement(element, LightClassUtil.getLightClassMethod(element))
is KtProperty -> findUrlsForLightProperty(element, LightClassUtil.getLightClassPropertyMethods(element))
is KtParameter -> findUrlsForLightProperty(element, LightClassUtil.getLightClassPropertyMethods(element))
// in case when quick doc is requested for Kotlin library element from Java code
is KtLightClass -> findUrlsForClass(element)
is KtLightMember<*> -> findUrlsForLightElement(findUrlsForClass(element.containingClass), element)
else -> null // core API requires null instead of empty list do designate that we do not provide any urls
}
return urls?.map { FileUtil.toSystemIndependentName(it) }
}
private fun findUrlsForClass(aClass: KtClass?): List<String> {
val classFqName = aClass?.fqName?.asString() ?: return emptyList()
return findUrlsForClass(classFqName, aClass.containingKtFile)
}
private fun findUrlsForClass(aClass: PsiClass?): List<String> {
val classFqName = aClass?.qualifiedName ?: return emptyList()
val pkgFqName = PsiUtil.getPackageName(aClass) ?: return emptyList()
val virtualFile = aClass.containingFile?.originalFile?.virtualFile ?: return emptyList()
return findUrlsForClass(pkgFqName, classFqName, aClass.project, virtualFile)
}
private fun findUrlsForEnumEntry(enumEntry: KtEnumEntry?): List<String> {
val classFqName = enumEntry
?.parent
?.toUElement()
?.getParentOfType(UClass::class.java)
?.javaPsi
?.qualifiedName
?: return emptyList()
return findUrlsForClass(classFqName, enumEntry.containingKtFile)
.mapNotNull { classUrl -> enumEntry.name?.let { "$classUrl#$it" } }
}
private fun findUrlsForContainingClassOf(ktElement: KtDeclaration): List<String> {
val containingClass = getContainingLightClassForKtDeclaration(ktElement) ?: return emptyList()
val classFqName = containingClass.qualifiedName ?: return emptyList()
return findUrlsForClass(classFqName, ktElement.containingKtFile)
}
private fun findUrlsForClass(classFqName: String, containingKtFile: KtFile): List<String> {
val virtualFile = containingKtFile.originalFile.virtualFile ?: return emptyList()
val pkgName = containingKtFile.packageFqName.asString()
return findUrlsForClass(pkgName, classFqName, containingKtFile.project, virtualFile)
}
private fun findUrlsForClass(
pkgFqName: String,
classFqName: String,
project: Project,
virtualFile: VirtualFile
): List<String> {
val relPath = when {
pkgFqName.isEmpty() -> "[root]/$classFqName"
else -> pkgFqName.replace('.', '/') + '/' + classFqName.substring(pkgFqName.length + 1)
}
val urls = JavaDocumentationProvider.findUrlForVirtualFile(
project, virtualFile, relPath + JavaDocumentationProvider.HTML_EXTENSION)
return urls ?: emptyList()
}
private fun findUrlsForLightProperty(
ktElement: KtDeclaration,
lightProperty: LightClassUtil.PropertyAccessorsPsiMethods
): List<String> {
val classUrls = findUrlsForContainingClassOf(ktElement)
return listOf(
findUrlsForLightElement(classUrls, lightProperty.backingField),
findUrlsForLightElement(classUrls, lightProperty.setter),
findUrlsForLightElement(classUrls, lightProperty.getter)
)
.flatten()
}
private fun findUrlsForLightElement(ktElement: KtDeclaration, lightElement: PsiElement?): List<String> {
return findUrlsForLightElement(findUrlsForContainingClassOf(ktElement), lightElement)
}
private fun findUrlsForLightElement(classUrls: List<String>, lightElement: PsiElement?): List<String> {
if (lightElement == null) {
return emptyList()
}
val elementSignatures = getLightElementSignatures(lightElement)
return classUrls.flatMap { classUrl -> elementSignatures.map { signature -> "$classUrl#$signature" } }
}
private fun getLightElementSignatures(element: PsiElement): List<String> {
return when (element) {
is PsiField -> listOf(element.name)
is PsiMethod -> {
listOf(element.name + "(", element.name + "-")
// JavaDocumentationProvider.getHtmlMethodSignatures(element, LanguageLevel.HIGHEST).toList()
// Unfortunately, currently Dokka generates anchors for function in a different format than Java's `javadoc`,
// e.g. functions params have simple non-qualified names.
// We haven't yet decided whether we want to change Dokka's result format to coincide or
// to implement anchors generation for Dokka's variant here, so by now we are just looking for all overloads
// and show them all.
}
else -> emptyList()
}
}
private fun getContainingLightClassForKtDeclaration(declaration: KtDeclaration): PsiClass? {
return when {
declaration is KtFunction && declaration.isLocal -> null
else -> declaration.toUElementOfType<UMethod>()?.uastParent?.javaPsi?.castSafelyTo<PsiClass>()
}
}
}
/**
* Fetches and extracts docs for the given element from urls to the JavaDoc.html
* which were generated by the [KotlinExternalDocUrlsProvider].
*/
class KotlinDocExtractorFromJavaDoc(private val project: Project) : AbstractExternalFilter() {
private var myCurrentProcessingElement: PsiElement? = null
/**
* Converts a relative link into
* `com.intellij.codeInsight.documentation.DocumentationManagerProtocol.PSI_ELEMENT_PROTOCOL PSI_ELEMENT_PROTOCOL`
* -type link if possible, so that by pressing on links in quick doc we could open docs right inside the same quick doc hint.
*/
private val myReferenceConverters = arrayOf<RefConvertor>(
object : RefConvertor(HREF_REGEXP) {
override fun convertReference(root: String, href: String): String {
if (BrowserUtil.isAbsoluteURL(href)) {
return href
}
val reference = myCurrentProcessingElement?.let { JavaDocInfoGenerator.createReferenceForRelativeLink(href, it) }
return when {
reference != null -> reference
href.startsWith("#") -> root + href
else -> {
val nakedRoot = ourHtmlFileSuffix.matcher(root).replaceAll("/")
doAnnihilate(nakedRoot + href)
}
}
}
}
)
override fun getRefConverters(): Array<RefConvertor> {
return myReferenceConverters
}
@Throws(Exception::class)
@Nls
override fun getExternalDocInfoForElement(elementDocUrl: String, element: PsiElement): String? {
myCurrentProcessingElement = element
val externalDoc = tryGetDocFromBuiltInServer(elementDocUrl)
?: super.getExternalDocInfoForElement(elementDocUrl, element)
myCurrentProcessingElement = null
return externalDoc?.let { buildResultDocPage(elementDocUrl, generateSignature(element), it) }
}
@VisibleForTesting
fun getExternalDocInfoForElement(elementDocUrl: String, javaDocPageHtml: String): String {
val content = javaDocPageHtml.toByteArray()
val contentStream = ByteArrayInputStream(content)
val contentReader = MyReader(contentStream, StandardCharsets.UTF_8.name())
val parsedDocs = buildString { contentReader.use { reader -> doBuildFromStream(elementDocUrl, reader, this) } }
return correctDocText(elementDocUrl, parsedDocs)
}
@Nls
private fun buildResultDocPage(elementDocUrl: String, elementSignature: String?, elementDoc: String): String {
@NlsSafe
@Language("HTML")
val result = """
<html>
<head>
${VfsUtilCore.convertToURL(elementDocUrl)?.let { "<base href=\"$it\">" } ?: ""}
<style type="text/css">
ul.inheritance {
margin: 0;
padding: 0;
}
ul.inheritance li {
display: inline;
list-style-type: none;
}
ul.inheritance li ul.inheritance {
margin-left: 15px;
padding-left: 15px;
padding-top: 1px;
}
.definition {
padding: 0 0 5px 0;
margin: 0 0 5px 0;
border-bottom: thin solid #c8cac0;
}
</style>
</head>
<body>
${elementSignature ?: ""}
${elementDoc}
</body>
</html>
""".trimIndent()
return result
}
private fun generateSignature(element: PsiElement): String? {
return runReadAction { KotlinDocumentationProvider().generateDoc(element, null) }
?.let { Jsoup.parse(it) }
?.getElementsByClass("definition")
?.first()
?.outerHtml()
}
@NlsSafe
private fun tryGetDocFromBuiltInServer(elementDocUrl: String): String? {
val projectPath = "/" + project.name + "/"
val urlToBuiltInServer = "http://localhost:${BuiltInServerOptions.getInstance().effectiveBuiltInServerPort}$projectPath"
if (!elementDocUrl.startsWith(urlToBuiltInServer)) return null
val url = Urls.parseFromIdea(elementDocUrl) ?: return null
val file = WebServerPathToFileManager.getInstance(project).findVirtualFile(url.path.substring(projectPath.length)) ?: return null
val content = file.inputStream.use { it.readAllBytes() }
val contentStream = ByteArrayInputStream(content)
val contentReader = MyReader(contentStream, StandardCharsets.UTF_8.name())
val parsedDocs = buildString { contentReader.use { reader -> doBuildFromStream(elementDocUrl, reader, this) } }
return correctDocText(elementDocUrl, parsedDocs)
}
override fun doBuildFromStream(url: String, input: Reader, data: StringBuilder) {
if (input !is MyReader) return
val root = Jsoup.parse(input.inputStream, input.encoding, url)
val anchor = url.substringAfterLast("#", "")
if (anchor.isBlank()) {
data.append(root.findClassDescriptionFromRoot() ?: "")
} else {
val anchors = root.findAnchors(anchor)
val elementDescription = when {
anchors.size == 1 -> {
anchors.single().let {
it.findClassMemberElementDescriptionFromAnchor()
?: it.findEnumEntryDescriptionFromAnchor()
}
}
else -> {
val overloads = anchors.mapNotNull { it.findClassMemberElementDescriptionFromAnchor(doIncludeSignature = true) }
@Language("HTML")
val result = """
<h3 style="margin-bottom: 0; font-weight: bold;">Found ${overloads.size} overloads:</h3>
<ol>
${overloads.joinToString(separator = "\n\n") { "<li style='margin: 0 0 8px 0;'>$it</li>" }}
</ol>
""".trimIndent()
result
}
}
data.append(elementDescription ?: "")
}
}
companion object {
private val HREF_REGEXP = Pattern.compile("<A.*?HREF=\"([^>\"]*)\"", Pattern.CASE_INSENSITIVE or Pattern.DOTALL)
}
}
/* ------------------------------------------------------------------------------------------- */
//region Utilities for extracting docs from the javadoc.html by element anchors
private fun Element.findAnchors(anchorName: String): List<Element> {
return select("a[name^=$anchorName], a[id^=$anchorName], a[href\$=$anchorName]")
}
private fun Element.findClassDescriptionFromRoot(): String? {
return getElementsByClass("description").first()?.findElementDescriptionFromUlBlockList()
}
private fun Element.findClassMemberElementDescriptionFromAnchor(doIncludeSignature: Boolean = false): String? {
return nextElementSibling()?.findElementDescriptionFromUlBlockList(doIncludeSignature)
}
private fun Element.findElementDescriptionFromUlBlockList(doIncludeSignature: Boolean = false): String? {
val infoHolder = selectFirst("li.blockList") ?: return null
val description = infoHolder.getElementsByClass("block").first() ?: return null
val signature = description.previousElementSibling()?.takeIf { it.tag().normalName() == "pre" }
val tagsDictionary = description.nextElementSibling()?.takeIf { it.tag().normalName() == "dl" }
return buildString {
if (doIncludeSignature && signature != null) {
append(signature.outerHtml())
}
append(description.outerHtml())
if (tagsDictionary != null) {
append(tagsDictionary.outerHtml())
}
}
}
private fun Element.findEnumEntryDescriptionFromAnchor(): String? {
val description = parents().firstOrNull { it.tag().normalName() == "th" }?.nextElementSibling()?.children() ?: return null
return """
<div>
${description.outerHtml()}
</div>
""".trimIndent()
}
//endregion
/* ------------------------------------------------------------------------------------------- */ | apache-2.0 | 6c2f6d081f656f38f2aeb8997cea4b51 | 43.247423 | 158 | 0.647987 | 4.965866 | false | false | false | false |
phylame/jem | scj/src/main/kotlin/jem/sci/plugin/ScriptRunner.kt | 1 | 4658 | /*
* Copyright 2015-2017 Peng Wan <[email protected]>
*
* This file is part of Jem.
*
* 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 jem.sci.plugin
import jclp.log.Log
import jem.Book
import jem.epm.EpmManager
import jem.epm.ParserParam
import jem.sci.SCI
import jem.sci.SCISettings
import jem.sci.SCJPlugin
import mala.App
import mala.App.tr
import mala.Plugin
import mala.cli.*
import org.apache.commons.cli.Option
import java.io.File
import java.nio.file.Path
import javax.script.ScriptEngine
import javax.script.ScriptEngineManager
import javax.script.ScriptException
class ScriptRunner : SCJAddon(), SCJPlugin {
override val name = "Script Runner"
override val description = tr("addon.runner.desc")
override fun init() {
newOption("R", "run-script")
.hasArg()
.argName(tr("opt.R.arg"))
.action(object : ListFetcher("R"), Command {
override fun execute(delegate: CDelegate): Int {
val paths = SCI["R"] as? List<*> ?: return -1
var code = 0
paths.map {
when (it) {
is File -> it
is Path -> it.toFile()
else -> File(it.toString())
}
}.forEach {
code = if (!it.exists()) {
App.error(tr("err.misc.noFile", it))
-1
} else {
minOf(code, runScript(it) {})
}
}
return code
}
})
Option.builder()
.hasArg()
.longOpt("engine-name")
.argName(tr("opt.engine.arg"))
.desc(tr("opt.engineName.desc"))
.action(StringFetcher("engine-name"))
Option.builder()
.hasArg()
.argName(tr("opt.R.arg"))
.longOpt("book-filter")
.desc(tr("opt.bookFilter.desc"))
.action(StringFetcher("book-filter"))
}
override fun onBookOpened(book: Book, param: ParserParam?) {
val file = File(SCI["book-filter"]?.toString() ?: return)
if (!file.exists()) {
App.error(tr("err.misc.noFile", file))
return
}
runScript(file) {
put("book", book)
}
}
private inline fun runScript(file: File, action: ScriptEngine.() -> Unit): Int {
val engine = getScriptEngine(file) ?: return -1
Log.t(javaClass.simpleName) { "engine ${engine.factory.engineName} is detected" }
action(engine)
try {
file.reader().use(engine::eval)
} catch (e: ScriptException) {
App.error(tr("err.scriptRunner.badScript"), e)
return -1
}
return 0
}
private fun getScriptEngine(file: File): ScriptEngine? {
val engineManager = ScriptEngineManager()
val name = SCI["engine-name"]?.toString()
val engine: ScriptEngine?
if (name != null) {
engine = engineManager.getEngineByName(name)
if (engine == null) {
App.error(tr("err.scriptRunner.noName", name))
return null
}
} else {
engine = engineManager.getEngineByExtension(file.extension)
if (engine == null) {
App.error(tr("err.scriptRunner.noExtension", file.extension))
return null
}
}
engine.put("app", App)
engine.put("sci", SCI)
engine.put("log", Log)
engine.put("epm", EpmManager)
engine.put("settings", SCISettings)
engine.put(ScriptEngine.FILENAME, file.path)
App.plugins.with<ScriptPlugin> {
initEngine(engine)
}
return engine
}
}
interface ScriptPlugin : Plugin {
fun initEngine(engine: ScriptEngine)
}
| apache-2.0 | ef664d2708fd1ddc5ed299b20bce3ff0 | 31.802817 | 89 | 0.531129 | 4.406812 | false | false | false | false |
tateisu/SubwayTooter | app/src/main/java/jp/juggler/subwaytooter/column/UserRelationLoader.kt | 1 | 6885 | package jp.juggler.subwaytooter.column
import jp.juggler.subwaytooter.api.TootApiClient
import jp.juggler.subwaytooter.api.TootParser
import jp.juggler.subwaytooter.api.entity.*
import jp.juggler.subwaytooter.table.AcctSet
import jp.juggler.subwaytooter.table.TagSet
import jp.juggler.subwaytooter.table.UserRelation
import jp.juggler.util.LogCategory
import jp.juggler.util.toJsonArray
import jp.juggler.util.toPostRequestBuilder
import java.util.HashSet
class UserRelationLoader(val column: Column) {
companion object {
private val log = LogCategory("UserRelationLoader")
}
val whoSet = HashSet<EntityId>()
val acctSet = HashSet<String>()
private val tagSet = HashSet<String>()
fun add(whoRef: TootAccountRef?) {
add(whoRef?.get())
}
fun add(who: TootAccount?) {
who ?: return
whoSet.add(who.id)
val fullAcct = column.accessInfo.getFullAcct(who)
acctSet.add("@${fullAcct.ascii}")
acctSet.add("@${fullAcct.pretty}")
//
add(who.movedRef)
}
fun add(s: TootStatus?) {
if (s == null) return
add(s.accountRef)
add(s.reblog)
s.tags?.forEach { tagSet.add(it.name) }
}
fun add(n: TootNotification?) {
if (n == null) return
add(n.accountRef)
add(n.status)
}
suspend fun update(client: TootApiClient, parser: TootParser) {
var n: Int
var size: Int
if (column.isMisskey) {
// parser内部にアカウントIDとRelationのマップが生成されるので、それをデータベースに記録する
run {
val now = System.currentTimeMillis()
val whoList =
parser.misskeyUserRelationMap.entries.toMutableList()
var start = 0
val end = whoList.size
while (start < end) {
var step = end - start
if (step > Column.RELATIONSHIP_LOAD_STEP) step = Column.RELATIONSHIP_LOAD_STEP
UserRelation.saveListMisskey(now, column.accessInfo.db_id, whoList, start, step)
start += step
}
log.d("updateRelation: update $end relations.")
}
// 2018/11/1 Misskeyにもリレーション取得APIができた
// アカウントIDの集合からRelationshipを取得してデータベースに記録する
size = whoSet.size
if (size > 0) {
val whoList = ArrayList<EntityId>(size)
whoList.addAll(whoSet)
val now = System.currentTimeMillis()
n = 0
while (n < whoList.size) {
val userIdList = ArrayList<EntityId>(Column.RELATIONSHIP_LOAD_STEP)
for (i in 0 until Column.RELATIONSHIP_LOAD_STEP) {
if (n >= size) break
if (!parser.misskeyUserRelationMap.containsKey(whoList[n])) {
userIdList.add(whoList[n])
}
++n
}
if (userIdList.isEmpty()) continue
val result = client.request(
"/api/users/relation",
column.accessInfo.putMisskeyApiToken().apply {
put(
"userId",
userIdList.map { it.toString() }.toJsonArray()
)
}.toPostRequestBuilder()
)
if (result == null || result.response?.code in 400 until 500) break
val list = parseList(::TootRelationShip, parser, result.jsonArray)
if (list.size == userIdList.size) {
for (i in 0 until list.size) {
list[i].id = userIdList[i]
}
UserRelation.saveListMisskeyRelationApi(now, column.accessInfo.db_id, list)
}
}
log.d("updateRelation: update $n relations.")
}
} else {
// アカウントIDの集合からRelationshipを取得してデータベースに記録する
size = whoSet.size
if (size > 0) {
val whoList = ArrayList<EntityId>(size)
whoList.addAll(whoSet)
val now = System.currentTimeMillis()
n = 0
while (n < whoList.size) {
val sb = StringBuilder()
sb.append("/api/v1/accounts/relationships")
for (i in 0 until Column.RELATIONSHIP_LOAD_STEP) {
if (n >= size) break
sb.append(if (i == 0) '?' else '&')
sb.append("id[]=")
sb.append(whoList[n++].toString())
}
val result = client.request(sb.toString()) ?: break // cancelled.
val list = parseList(::TootRelationShip, parser, result.jsonArray)
if (list.size > 0) UserRelation.saveListMastodon(
now,
column.accessInfo.db_id,
list
)
}
log.d("updateRelation: update $n relations.")
}
}
// 出現したacctをデータベースに記録する
size = acctSet.size
if (size > 0) {
val acctList = ArrayList<String?>(size)
acctList.addAll(acctSet)
val now = System.currentTimeMillis()
n = 0
while (n < acctList.size) {
var length = size - n
if (length > Column.ACCT_DB_STEP) length = Column.ACCT_DB_STEP
AcctSet.saveList(now, acctList, n, length)
n += length
}
log.d("updateRelation: update $n acct.")
}
// 出現したタグをデータベースに記録する
size = tagSet.size
if (size > 0) {
val tagList = ArrayList<String?>(size)
tagList.addAll(tagSet)
val now = System.currentTimeMillis()
n = 0
while (n < tagList.size) {
var length = size - n
if (length > Column.ACCT_DB_STEP) length = Column.ACCT_DB_STEP
TagSet.saveList(now, tagList, n, length)
n += length
}
log.d("updateRelation: update $n tag.")
}
}
}
| apache-2.0 | 2825a16c21513df51a8301829c74aa18 | 33.940217 | 100 | 0.481476 | 4.643961 | false | false | false | false |
paplorinc/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/lang/psi/patterns/GroovyClosurePattern.kt | 6 | 2098 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.plugins.groovy.lang.psi.patterns
import com.intellij.patterns.ElementPattern
import com.intellij.patterns.PatternCondition
import com.intellij.psi.PsiMethod
import com.intellij.util.ProcessingContext
import org.jetbrains.plugins.groovy.lang.psi.api.statements.arguments.GrArgumentList
import org.jetbrains.plugins.groovy.lang.psi.api.statements.blocks.GrClosableBlock
import org.jetbrains.plugins.groovy.lang.psi.api.statements.expressions.GrCall
class GroovyClosurePattern : GroovyExpressionPattern<GrClosableBlock, GroovyClosurePattern>(GrClosableBlock::class.java) {
fun inMethod(methodPattern: ElementPattern<out PsiMethod>): GroovyClosurePattern = with(object : PatternCondition<GrClosableBlock>("closureInMethod") {
override fun accepts(closure: GrClosableBlock, context: ProcessingContext?): Boolean {
val parent = closure.parent
val call = when (parent) {
is GrCall -> {
if (closure !in parent.closureArguments) return false
parent
}
is GrArgumentList -> {
val grandParent = parent.parent as? GrCall ?: return false
if (grandParent.closureArguments.isNotEmpty()) return false
if (grandParent.expressionArguments.lastOrNull() != closure) return false
grandParent
}
else -> return false
}
context?.put(closureCallKey, call)
val method = call.resolveMethod() ?: return false
return methodPattern.accepts(method)
}
})
} | apache-2.0 | 70f33625476726f31cb0fb5cf60ca54e | 40.98 | 153 | 0.737846 | 4.662222 | false | false | false | false |
paplorinc/intellij-community | platform/credential-store/src/credentialStore.kt | 3 | 2392 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.credentialStore
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.io.toByteArray
import java.nio.CharBuffer
import java.security.SecureRandom
import java.util.*
internal val LOG = logger<CredentialStore>()
fun joinData(user: String?, password: OneTimeString?): ByteArray? {
if (user == null && password == null) {
return null
}
val builder = StringBuilder(user.orEmpty())
StringUtil.escapeChar(builder, '\\')
StringUtil.escapeChar(builder, '@')
if (password != null) {
builder.append('@')
password.appendTo(builder)
}
val buffer = Charsets.UTF_8.encode(CharBuffer.wrap(builder))
// clear password
builder.setLength(0)
return buffer.toByteArray()
}
fun splitData(data: String?): Credentials? {
if (data.isNullOrEmpty()) {
return null
}
val list = parseString(data!!, '@')
return Credentials(list.getOrNull(0), list.getOrNull(1))
}
private const val ESCAPING_CHAR = '\\'
private fun parseString(data: String, @Suppress("SameParameterValue") delimiter: Char): List<String> {
val part = StringBuilder()
val result = ArrayList<String>(2)
var i = 0
var c: Char?
do {
c = data.getOrNull(i++)
if (c != null && c != delimiter) {
if (c == ESCAPING_CHAR) {
c = data.getOrNull(i++)
}
if (c != null) {
part.append(c)
continue
}
}
result.add(part.toString())
part.setLength(0)
if (i < data.length) {
result.add(data.substring(i))
break
}
}
while (c != null)
return result
}
// check isEmpty before
@JvmOverloads
fun Credentials.serialize(storePassword: Boolean = true) = joinData(userName, if (storePassword) password else null)!!
internal val ACCESS_TO_KEY_CHAIN_DENIED = Credentials(null, null as OneTimeString?)
fun createSecureRandom(): SecureRandom {
// do not use SecureRandom.getInstanceStrong()
// https://tersesystems.com/blog/2015/12/17/the-right-way-to-use-securerandom/
// it leads to blocking without any advantages
return SecureRandom()
}
@Synchronized
internal fun SecureRandom.generateBytes(size: Int): ByteArray {
val result = ByteArray(size)
nextBytes(result)
return result
} | apache-2.0 | 1f58b91db33dc55c3667e4e36fc8dcc6 | 25.01087 | 140 | 0.690635 | 3.772871 | false | false | false | false |
georocket/georocket | src/main/kotlin/io/georocket/ogcapifeatures/LandingPageEndpoint.kt | 1 | 2819 | package io.georocket.ogcapifeatures
import io.georocket.http.Endpoint
import io.georocket.ogcapifeatures.views.Views
import io.georocket.ogcapifeatures.views.json.JsonViews
import io.georocket.ogcapifeatures.views.xml.XmlViews
import io.georocket.util.PathUtils
import io.vertx.core.Vertx
import io.vertx.ext.web.Router
import io.vertx.ext.web.RoutingContext
import kotlinx.coroutines.CoroutineScope
import kotlin.coroutines.CoroutineContext
/**
* Main entry point for the OGC API Features
* @author Michel Kraemer
*/
class LandingPageEndpoint(
override val coroutineContext: CoroutineContext, private val vertx: Vertx
) : Endpoint, CoroutineScope {
private val ae = ApiEndpoint(vertx)
private val cfe = ConformanceEndpoint(vertx)
private val cle = CollectionsEndpoint(coroutineContext, vertx)
override suspend fun createRouter(): Router {
val router = Router.router(vertx)
router.get("/").produces(Views.ContentTypes.JSON).handler { ctx -> onInfo(ctx, JsonViews) }
router.get("/").produces(Views.ContentTypes.XML).handler { ctx -> onInfo(ctx, XmlViews) }
router.get("/").handler { context ->
respondWithHttp406NotAcceptable(context.response(), listOf(Views.ContentTypes.JSON, Views.ContentTypes.XML))
}
router.mountSubRouter("/api", ae.createRouter())
router.mountSubRouter("/conformance", cfe.createRouter())
router.mountSubRouter("/collections", cle.createRouter())
return router
}
override suspend fun close() {
ae.close()
cfe.close()
cle.close()
}
private fun onInfo(context: RoutingContext, views: Views) {
val basePath = context.request().path()
val links = Endpoint.getLinksToSelf(context) + listOf(
Views.Link(
href = PathUtils.join(basePath, "conformance"),
rel = "conformance",
type = Views.ContentTypes.JSON,
title = "Conformance classes implemented by this server as JSON"
),
Views.Link(
href = PathUtils.join(basePath, "conformance"),
rel = "conformance",
type = Views.ContentTypes.XML,
title = "Conformance classes implemented by this server as XML"
),
Views.Link(
href = PathUtils.join(basePath, "collections"),
rel = "data",
type = Views.ContentTypes.JSON,
title = "Metadata about feature collections as JSON"
),
Views.Link(
href = PathUtils.join(basePath, "collections"),
rel = "data",
type = Views.ContentTypes.XML,
title = "Metadata about feature collections as XML"
),
Views.Link(
href = PathUtils.join(basePath, "api"),
rel = "service-desc",
type = "application/vnd.oai.openapi+json;version=3.0",
title = "API definition"
),
)
views.landingPage(context.response(), links)
}
}
| apache-2.0 | 4c78835398360733612b4a1a592b183d | 32.963855 | 114 | 0.684285 | 4.091437 | false | false | false | false |
paplorinc/intellij-community | plugins/git4idea/src/git4idea/repo/GitRepoInfo.kt | 4 | 1559 | // 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 git4idea.repo
import com.intellij.dvcs.repo.Repository
import com.intellij.vcs.log.Hash
import git4idea.GitLocalBranch
import git4idea.GitReference
import git4idea.GitRemoteBranch
import gnu.trove.THashMap
data class GitRepoInfo(val currentBranch: GitLocalBranch?,
val currentRevision: String?,
val state: Repository.State,
val remotes: Collection<GitRemote>,
val localBranchesWithHashes: Map<GitLocalBranch, Hash>,
val remoteBranchesWithHashes: Map<GitRemoteBranch, Hash>,
val branchTrackInfos: Collection<GitBranchTrackInfo>,
val submodules: Collection<GitSubmoduleInfo>,
val hooksInfo: GitHooksInfo,
val isShallow: Boolean) {
val branchTrackInfosMap = THashMap<String, GitBranchTrackInfo>(GitReference.BRANCH_NAME_HASHING_STRATEGY).apply {
branchTrackInfos.associateByTo(this) { it.localBranch.name }
}
val remoteBranches: Collection<GitRemoteBranch>
@Deprecated("")
get() = remoteBranchesWithHashes.keys
override fun toString() = "GitRepoInfo{current=$currentBranch, remotes=$remotes, localBranches=$localBranchesWithHashes, " +
"remoteBranches=$remoteBranchesWithHashes, trackInfos=$branchTrackInfos, submodules=$submodules, hooks=$hooksInfo}"
}
| apache-2.0 | 3da8180d312463cc46c99ee437f52ab4 | 49.290323 | 143 | 0.68762 | 5.145215 | false | false | false | false |
paplorinc/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/conflict/TreeConflictDescription.kt | 3 | 2163 | // 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.idea.svn.conflict
import org.jetbrains.idea.svn.SvnUtil.createUrl
import org.jetbrains.idea.svn.SvnUtil.resolvePath
import org.jetbrains.idea.svn.api.BaseNodeDescription
import org.jetbrains.idea.svn.api.NodeKind
import java.io.File
import javax.xml.bind.annotation.*
class TreeConflictDescription private constructor(builder: Builder, base: File) : BaseNodeDescription(builder.kind) {
val path = resolvePath(base, builder.path)
val conflictAction = builder.action
val conflictReason = builder.reason
val operation = builder.operation
val sourceLeftVersion = builder.sourceLeftVersion
val sourceRightVersion = builder.sourceRightVersion
fun toPresentableString() = "local $conflictReason, incoming $conflictAction upon $operation"
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "tree-conflict")
@XmlRootElement(name = "tree-conflict")
class Builder {
@XmlAttribute(name = "victim")
var path = ""
@XmlAttribute
var kind = NodeKind.UNKNOWN
@XmlAttribute
var operation = ConflictOperation.NONE
@XmlAttribute
var action = ConflictAction.ADD
@XmlAttribute
var reason = ConflictReason.ADDED
@XmlElement(name = "version")
private val versions = mutableListOf<ConflictVersionWithSide>()
val sourceLeftVersion get() = versions.find { it.side == "source-left" }?.build()
val sourceRightVersion get() = versions.find { it.side == "source-right" }?.build()
fun build(base: File) = TreeConflictDescription(this, base)
}
}
@XmlAccessorType(XmlAccessType.NONE)
@XmlType(name = "version")
@XmlRootElement(name = "version")
private class ConflictVersionWithSide {
@XmlAttribute
var side = ""
@XmlAttribute
var kind = NodeKind.UNKNOWN
@XmlAttribute(name = "path-in-repos")
var path = ""
@XmlAttribute(name = "repos-url")
var repositoryRoot = ""
@XmlAttribute(name = "revision")
var revisionNumber = -1L
fun build() = ConflictVersion(createUrl(repositoryRoot), path, revisionNumber, kind)
} | apache-2.0 | 40f799cf4e2bbbf2591e7150b57ef0d0 | 29.914286 | 140 | 0.742487 | 3.998152 | false | false | false | false |
indianpoptart/RadioControl | RadioControl/app/src/main/java/com/nikhilparanjape/radiocontrol/utilities/NetworkUtility.kt | 1 | 1030 | package com.nikhilparanjape.radiocontrol.utilities
import android.content.Context
import android.util.Log
import java.net.InetAddress
import kotlin.system.measureTimeMillis
/**
* Created by Nikhil on 01/19/2021.
*
* A custom Networking Utility class for RadioControl
*
* This "offloads" the networking tasks to this class allowing for easy returns for UI elements
*
* @author Nikhil Paranjape
*
*
*/
class NetworkUtility {
companion object{
fun reachable(context: Context): Boolean {
val preferences = androidx.preference.PreferenceManager.getDefaultSharedPreferences(context)
val ip = preferences.getString("prefPingIp", "1.0.0.1")
val address = InetAddress.getByName(ip)
var reachable = false
val timeDifference = measureTimeMillis {
reachable = address.isReachable(1000)
}
Log.d("RadioControl-Networking", "Reachable?: $reachable, Time: $timeDifference")
return reachable
}
}
} | gpl-3.0 | fc7a065b269130d6bcd3c79ef9a53f33 | 28.457143 | 104 | 0.67767 | 4.746544 | false | false | false | false |
google/iosched | shared/src/test/java/com/google/samples/apps/iosched/shared/domain/sessions/ObserveConferenceDataUseCaseTest.kt | 1 | 1632 | /*
* Copyright 2018 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.samples.apps.iosched.shared.domain.sessions
import com.google.samples.apps.iosched.shared.model.TestDataRepository
import com.google.samples.apps.iosched.test.data.MainCoroutineRule
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.test.runTest
import org.hamcrest.MatcherAssert.assertThat
import org.hamcrest.Matchers.notNullValue
import org.hamcrest.core.Is.`is`
import org.junit.Rule
import org.junit.Test
/**
* Unit tests for [ObserveConferenceDataUseCase].
*/
class ObserveConferenceDataUseCaseTest {
// Overrides Dispatchers.Main used in Coroutines
@get:Rule
var coroutineRule = MainCoroutineRule()
@Test
fun remoteConfDataRefreshed_valueIsUpdated() = runTest {
val repo = TestDataRepository
val subject = ObserveConferenceDataUseCase(repo, coroutineRule.testDispatcher)
repo.refreshCacheWithRemoteConferenceData()
// Start the listeners
val result = subject(Unit).first()
assertThat(result, `is`(notNullValue()))
}
}
| apache-2.0 | 2625a93a1c4ec4d4c9fabeb5cbf49936 | 32.306122 | 86 | 0.754289 | 4.422764 | false | true | false | false |
raybritton/json-query | lib/src/main/kotlin/com/raybritton/jsonquery/models/Query.kt | 1 | 5188 | package com.raybritton.jsonquery.models
import com.raybritton.jsonquery.SyntaxException
import com.raybritton.jsonquery.ext.wrap
import com.raybritton.jsonquery.parsing.tokens.Keyword
import com.raybritton.jsonquery.parsing.tokens.Operator
import com.raybritton.jsonquery.parsing.tokens.Token
import com.raybritton.jsonquery.parsing.tokens.isKeyword
import com.raybritton.jsonquery.printers.QueryPrinter
internal data class Query(
val originalString: String,
val method: Method,
val target: Target,
val flags: Flags,
val where: Where?,
val search: SearchQuery? = null,
val select: SelectQuery? = null,
val describe: DescribeQuery? = null
) {
enum class Method {
SELECT, DESCRIBE, SEARCH
}
data class Flags(
val isCaseSensitive: Boolean = false,
val isDistinct: Boolean = false,
val isWithValues: Boolean = false,
val isWithKeys: Boolean = false,
val isByElement: Boolean = false,
val isAsJson: Boolean = false,
val isPrettyPrinted: Boolean = false,
val isOnlyPrintKeys: Boolean = false,
val isOnlyPrintValues: Boolean = false,
val isOrderByDesc: Boolean = false
)
override fun toString() = QueryPrinter.print(this)
}
internal data class SearchQuery(val targetRange: TargetRange, val operator: Operator, val value: Value<*>) {
enum class TargetRange {
ANY, KEY, VALUE
}
}
internal data class SelectQuery(val projection: SelectProjection?, val limit: Int?, val offset: Int?, val orderBy: ElementFieldProjection?)
internal data class DescribeQuery(val projection: String?, val limit: Int?, val offset: Int?)
internal data class Where(val projection: WhereProjection, val operator: Operator, val value: Value<*>)
internal sealed class Value<T>(val value: T) {
class ValueNumber(value: Double) : Value<Double>(value)
class ValueString(value: String) : Value<String>(value)
class ValueBoolean(value: Boolean) : Value<Boolean>(value)
class ValueQuery(value: Query) : Value<Query>(value)
class ValueType(value: Keyword) : Value<Keyword>(value)
override fun toString(): String {
return when (this) {
is ValueType -> value.name
is ValueString -> value.wrap()
is ValueBoolean -> if (value) Keyword.TRUE.name else Keyword.FALSE.name
else -> value.toString()
}
}
companion object {
fun build(any: Token<*>?): Value<*>? {
return when {
any is Token.STRING -> {
if (any.value.isEmpty()) {
throw SyntaxException("String value is empty at ${any.charIdx}", SyntaxException.ExtraInfo.VALUE_INVALID)
}
Value.ValueString(any.value)
}
any is Token.NUMBER -> {
if (any.value.isNaN() || any.value.isInfinite()) {
throw SyntaxException("Number value is invalid at ${any.charIdx}", SyntaxException.ExtraInfo.VALUE_INVALID)
}
Value.ValueNumber(any.value)
}
any.isKeyword(Keyword.TRUE, Keyword.FALSE) -> Value.ValueBoolean(any?.value == Keyword.TRUE)
any.isKeyword(Keyword.ARRAY, Keyword.OBJECT, Keyword.BOOLEAN, Keyword.STRING, Keyword.NUMBER, Keyword.NULL) -> Value.ValueType((any as Token.KEYWORD).value)
else -> null
}
}
}
}
internal sealed class Target {
class TargetField(val value: String) : Target()
class TargetQuery(val query: Query) : Target()
}
internal sealed class ElementFieldProjection {
class Field(val value: String) : ElementFieldProjection()
object Element : ElementFieldProjection()
override fun toString(): String {
return when (this) {
is Element -> Keyword.ELEMENT.name
is Field -> this.value.wrap()
}
}
companion object {
fun build(any: Token<*>?): ElementFieldProjection? {
return when {
any is Token.STRING -> Field(any.value)
any.isKeyword(Keyword.ELEMENT) -> Element
else -> null
}
}
}
}
internal sealed class WhereProjection {
class Field(val value: String) : WhereProjection()
object Element : WhereProjection()
class Math(val expr: Keyword, val field: ElementFieldProjection) : WhereProjection()
companion object {
fun build(any: Token<*>?): WhereProjection? {
return when {
any is Token.STRING -> WhereProjection.Field(any.value)
any.isKeyword(Keyword.ELEMENT) -> WhereProjection.Element
else -> null
}
}
}
}
internal sealed class SelectProjection {
object All : SelectProjection()
class SingleField(val field: String, val newName: String?) : SelectProjection()
class MultipleFields(val fields: List<Pair<String, String?>>) : SelectProjection()
class Math(val expr: Keyword, val field: ElementFieldProjection) : SelectProjection()
} | apache-2.0 | a4e51c2bf13e260188d9f044c8a69c76 | 35.801418 | 172 | 0.626638 | 4.661276 | false | false | false | false |
allotria/intellij-community | platform/editor-ui-api/src/com/intellij/ide/ui/experimental/toolbar/ExperimentalToolbarSettings.kt | 1 | 6035 | // 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.ide.ui.experimental.toolbar
import com.intellij.ide.ui.ToolbarSettings
import com.intellij.ide.ui.UISettings
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.components.*
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.util.registry.RegistryValue
import com.intellij.openapi.util.registry.RegistryValueListener
@State(name = "ToolbarSettingsService", storages = [(Storage(StoragePathMacros.NON_ROAMABLE_FILE))])
class ExperimentalToolbarSettings private constructor() : ToolbarSettings,
PersistentStateComponent<ExperimentalToolbarStateWrapper> {
val logger = Logger.getInstance(ExperimentalToolbarSettings::class.java)
val newToolbarEnabled: Boolean
get() = Registry.`is`("ide.new.navbar", false)
private var toolbarState = ExperimentalToolbarStateWrapper()
private val disposable = Disposer.newDisposable()
inner class ToolbarRegistryListener : RegistryValueListener {
override fun afterValueChanged(value: RegistryValue) {
val v = value.asBoolean()
toolbarState.state =
getToolbarStateByVisibilityFlags(v, if(v) false else isToolbarVisible(), v,
if(v) false else isNavBarVisible())
logger.info("Registry value new.navbar was changed to $v, toolbar state is " + toolbarState.state)
updateSettingsState()
UISettings.instance.fireUISettingsChanged()
}
}
init {
if (!newToolbarEnabled) {
toolbarState.state = getToolbarStateByVisibilityFlags(false, UISettings.instance.state.showMainToolbar, false,
UISettings.instance.state.showNavigationBar)
}
Disposer.register(ApplicationManager.getApplication(), disposable)
Registry.get("ide.new.navbar").addListener(ToolbarRegistryListener(), disposable)
}
override fun getState(): ExperimentalToolbarStateWrapper {
return toolbarState
}
override fun loadState(state: ExperimentalToolbarStateWrapper) {
if (!newToolbarEnabled) {
val oldState = UISettings.instance.state
toolbarState.state =
getToolbarStateByVisibilityFlags(false, oldState.showMainToolbar, false,
oldState.showNavigationBar)
logger.info("Loading old state, main toolbar: ${oldState.showMainToolbar} navBar ${oldState.showNavigationBar}")
}
else {
toolbarState = state
updateSettingsState()
}
}
fun getToolbarStateByVisibilityFlags(newToolbarEnabled: Boolean, oldToolbarVisible: Boolean,
newToolbarVisible: Boolean, navBarVisible: Boolean): ExperimentalToolbarStateEnum {
if (oldToolbarVisible && newToolbarVisible) {
logger.error("Illegal double toolbar visible state")
throw IllegalStateException()
}
if (newToolbarEnabled && newToolbarVisible) {
if (navBarVisible) {
return ExperimentalToolbarStateEnum.NEW_TOOLBAR_WITH_NAVBAR
}
else {
return ExperimentalToolbarStateEnum.NEW_TOOLBAR_WITHOUT_NAVBAR
}
}
else if (oldToolbarVisible) {
if (navBarVisible) {
return ExperimentalToolbarStateEnum.OLD_TOOLBAR_WITH_NAVBAR_SEPARATE
}
else {
return ExperimentalToolbarStateEnum.OLD_TOOLBAR_WITHOUT_NAVBAR
}
}
else {
if (navBarVisible) {
return ExperimentalToolbarStateEnum.OLD_NAVBAR
}
else {
return ExperimentalToolbarStateEnum.NO_TOOLBAR_NO_NAVBAR
}
}
}
override fun isNavBarVisible(): Boolean {
return toolbarState.state.navBarVisible
}
override fun setNavBarVisible(value: Boolean) {
toolbarState.state = getToolbarStateByVisibilityFlags(newToolbarEnabled, toolbarState.state.oldToolbarVisible,
toolbarState.state.newToolbarVisible,
value)
updateSettingsState()
UISettings.instance.fireUISettingsChanged()
}
private fun updateSettingsState() {
UISettings.instance.state.showNavigationBar = toolbarState.state.navBarVisible
UISettings.instance.state.showMainToolbar = toolbarState.state.oldToolbarVisible
logger.info("showNavigationBar: ${UISettings.instance.state.showNavigationBar} showMainToolbar: ${UISettings.instance.state.showMainToolbar}")
}
override fun isToolbarVisible(): Boolean {
return toolbarState.state.oldToolbarVisible
}
override fun setToolbarVisible(value: Boolean) {
if (value) {
toolbarState.state = getToolbarStateByVisibilityFlags(newToolbarEnabled, value, false, toolbarState.state.navBarVisible)
}
else {
toolbarState.state = getToolbarStateByVisibilityFlags(newToolbarEnabled, value, toolbarState.state.newToolbarVisible,
toolbarState.state.navBarVisible)
}
updateSettingsState()
UISettings.instance.fireUISettingsChanged()
}
override fun getShowToolbarInNavigationBar(): Boolean {
return toolbarState.state == ExperimentalToolbarStateEnum.OLD_NAVBAR
}
var showNewToolbar: Boolean
get() = toolbarState.state.newToolbarVisible
set(value) {
if (value) {
toolbarState.state = getToolbarStateByVisibilityFlags(newToolbarEnabled, false, value, toolbarState.state.navBarVisible)
}
else {
toolbarState.state = getToolbarStateByVisibilityFlags(newToolbarEnabled, toolbarState.state.oldToolbarVisible, value,
toolbarState.state.navBarVisible)
}
updateSettingsState()
UISettings.instance.fireUISettingsChanged()
}
}
| apache-2.0 | 4bd5babdfb48a79996116fa16bedeb56 | 38.703947 | 146 | 0.697597 | 5.175815 | false | false | false | false |
DmytroTroynikov/aemtools | aem-intellij-core/src/main/kotlin/com/aemtools/completion/htl/provider/HtlElDataSlyCallVariableCompletionProvider.kt | 1 | 2015 | package com.aemtools.completion.htl.provider
import com.aemtools.codeinsight.htl.model.DeclarationAttributeType
import com.aemtools.codeinsight.htl.model.HtlUseVariableDeclaration
import com.aemtools.codeinsight.htl.model.HtlVariableDeclaration
import com.aemtools.codeinsight.htl.model.UseType
import com.aemtools.completion.htl.common.FileVariablesResolver
import com.aemtools.lang.htl.icons.HtlIcons
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionProvider
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.util.ProcessingContext
/**
* @author Dmytro Troynikov
*/
object HtlElDataSlyCallVariableCompletionProvider : CompletionProvider<CompletionParameters>() {
override fun addCompletions(
parameters: CompletionParameters,
context: ProcessingContext,
result: CompletionResultSet) {
val position = parameters.position
val fileVariables = FileVariablesResolver.declarationsForPosition(position, parameters)
val fileTemplates = fileVariables.filter { it.attributeType == DeclarationAttributeType.DATA_SLY_TEMPLATE }
.map(HtlVariableDeclaration::toLookupElement)
val useVariables = fileVariables.map { it as? HtlUseVariableDeclaration }
.filterNotNull()
.filter { it.slyUseType == UseType.HTL }
val useTemplates = useVariables
.map { it to it.template() }
.filter { (_, value) -> value.isNotEmpty() }
.flatMap { (key, value) ->
value.map {
LookupElementBuilder
.create("${key.variableName}.${it.name}")
.withIcon(HtlIcons.HTL_FILE_ICON)
.withTypeText("HTL Template")
.withPresentableText(it.name)
.withTailText("(${key.xmlAttribute.value})", true)
}
}
result.addAllElements(useTemplates + fileTemplates)
result.stopHere()
}
}
| gpl-3.0 | 037e03ff81bf18b6e5c5951e29f1fb4a | 38.509804 | 111 | 0.732506 | 4.832134 | false | false | false | false |
allotria/intellij-community | platform/vcs-tests/testSrc/com/intellij/openapi/vcs/BaseLineStatusTrackerManagerTest.kt | 1 | 4277 | // 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
import com.intellij.diff.comparison.iterables.DiffIterableUtil
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.command.CommandProcessor
import com.intellij.openapi.command.impl.UndoManagerImpl
import com.intellij.openapi.command.undo.UndoManager
import com.intellij.openapi.editor.Document
import com.intellij.openapi.vcs.changes.shelf.ShelveChangesManager
import com.intellij.openapi.vcs.ex.*
import com.intellij.openapi.vcs.impl.LineStatusTrackerManager
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.testFramework.RunAll
import com.intellij.util.ThrowableRunnable
import com.intellij.util.ui.UIUtil
abstract class BaseLineStatusTrackerManagerTest : BaseChangeListsTest() {
protected lateinit var shelveManager: ShelveChangesManager
protected lateinit var lstm: LineStatusTrackerManager
protected lateinit var undoManager: UndoManagerImpl
override fun setUp() {
super.setUp()
DiffIterableUtil.setVerifyEnabled(true)
lstm = LineStatusTrackerManager.getInstanceImpl(getProject())
undoManager = UndoManager.getInstance(getProject()) as UndoManagerImpl
shelveManager = ShelveChangesManager.getInstance(getProject())
}
override fun tearDown() {
RunAll(
ThrowableRunnable { clm.waitUntilRefreshed() },
ThrowableRunnable { UIUtil.dispatchAllInvocationEvents() },
ThrowableRunnable { lstm.resetExcludedFromCommitMarkers() },
ThrowableRunnable { lstm.releaseAllTrackers() },
ThrowableRunnable { DiffIterableUtil.setVerifyEnabled(false) },
ThrowableRunnable { super.tearDown() }
).run()
}
override fun resetSettings() {
super.resetSettings()
VcsApplicationSettings.getInstance().ENABLE_PARTIAL_CHANGELISTS = true
VcsApplicationSettings.getInstance().SHOW_LST_GUTTER_MARKERS = true
VcsApplicationSettings.getInstance().SHOW_WHITESPACES_IN_LST = true
arePartialChangelistsSupported = true
}
protected fun releaseUnneededTrackers() {
runWriteAction { } // LineStatusTrackerManager.MyApplicationListener.afterWriteActionFinished
}
protected val VirtualFile.tracker: LineStatusTracker<*>? get() = lstm.getLineStatusTracker(this)
protected fun VirtualFile.withOpenedEditor(task: () -> Unit) {
lstm.requestTrackerFor(document, this)
try {
task()
}
finally {
lstm.releaseTrackerFor(document, this)
}
}
protected open fun runCommand(groupId: String? = null, task: () -> Unit) {
CommandProcessor.getInstance().executeCommand(getProject(), {
ApplicationManager.getApplication().runWriteAction(task)
}, "", groupId)
}
protected fun undo(document: Document) {
val editor = createMockFileEditor(document)
undoManager.undo(editor)
}
protected fun redo(document: Document) {
val editor = createMockFileEditor(document)
undoManager.redo(editor)
}
protected fun PartialLocalLineStatusTracker.assertAffectedChangeLists(vararg expectedNames: String) {
assertSameElements(this.getAffectedChangeListsIds().asListIdsToNames(), *expectedNames)
}
protected fun Range.assertChangeList(listName: String) {
val localRange = this as LocalRange
assertEquals(listName, localRange.changelistId.asListIdToName())
}
protected fun VirtualFile.assertNullTracker() {
val tracker = this.tracker
if (tracker != null) {
var message = "$tracker" +
": operational - ${tracker.isOperational()}" +
", valid - ${tracker.isValid()}, " +
", file - ${tracker.virtualFile}"
if (tracker is PartialLocalLineStatusTracker) {
message += ", hasPartialChanges - ${tracker.hasPartialChangesToCommit()}" +
", lists - ${tracker.getAffectedChangeListsIds().asListIdsToNames()}"
}
assertNull(message, tracker)
}
}
protected fun PartialLocalLineStatusTracker.assertExcludedState(expected: ExclusionState, listName: String) {
assertEquals(expected, getExcludedFromCommitState(listName.asListNameToId()))
}
}
| apache-2.0 | 9146814bd0d5949ff068d75fe065eb51 | 36.849558 | 140 | 0.748422 | 5.122156 | false | false | false | false |
DeflatedPickle/Quiver | launcher/src/main/kotlin/com/deflatedpickle/quiver/launcher/LauncherPlugin.kt | 1 | 1510 | /* Copyright (c) 2020-2021 DeflatedPickle under the MIT license */
package com.deflatedpickle.quiver.launcher
import com.deflatedpickle.haruhi.api.constants.MenuCategory
import com.deflatedpickle.haruhi.api.plugin.Plugin
import com.deflatedpickle.haruhi.api.plugin.PluginType
import com.deflatedpickle.haruhi.event.EventProgramFinishSetup
import com.deflatedpickle.haruhi.util.RegistryUtil
import com.deflatedpickle.monocons.MonoIcon
import com.deflatedpickle.quiver.backend.util.ActionUtil
import com.deflatedpickle.quiver.launcher.window.Toolbar
import com.deflatedpickle.undulation.extensions.add
import javax.swing.JMenu
@Plugin(
value = "$[name]",
author = "$[author]",
version = "$[version]",
description = """
<br>
A basic launcher
""",
type = PluginType.LAUNCHER
)
@Suppress("unused")
object LauncherPlugin {
init {
EventProgramFinishSetup.addListener {
val menuBar = RegistryUtil.get(MenuCategory.MENU.name)
(menuBar?.get(MenuCategory.FILE.name) as JMenu).apply {
add("New Pack", MonoIcon.FOLDER_NEW) { ActionUtil.newPack() }
add("Open Pack", MonoIcon.FOLDER_OPEN) { ActionUtil.openPack() }
addSeparator()
}
Toolbar.apply {
add(icon = MonoIcon.FOLDER_NEW, tooltip = "New Pack") { ActionUtil.newPack() }
add(icon = MonoIcon.FOLDER_OPEN, tooltip = "Open Pack") { ActionUtil.openPack() }
}
}
}
}
| mit | 4f26af19ee5b04b8b62715ab92e68397 | 34.116279 | 97 | 0.674172 | 4.171271 | false | false | false | false |
leafclick/intellij-community | python/src/com/jetbrains/python/codeInsight/mlcompletion/PyMlCompletionHelpers.kt | 1 | 1428 | // 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.codeInsight.mlcompletion
import com.google.common.reflect.TypeToken
import com.google.gson.Gson
import com.intellij.openapi.diagnostic.Logger
import java.io.InputStreamReader
import java.nio.charset.StandardCharsets
object PyMlCompletionHelpers {
private val LOG = Logger.getInstance("#com.jetbrains.python.codeInsight.completion.mlcompletion")
// imports and builtins popularity was calculated on github by number of search results for each present builtins or import
val importPopularity = initMapFromJsonResource("/mlcompletion/importPopularityWeights.json")
val builtinsPopularity = initMapFromJsonResource("/mlcompletion/builtinsPopularityWeights.json")
private val keyword2id = initMapFromJsonResource("/mlcompletion/keywordsNumeration.json")
fun getKeywordId(kw: String): Int? = keyword2id[kw]
private fun initMapFromJsonResource(resourcePath: String): Map<String, Int> {
try {
val resource = PyMlCompletionHelpers::class.java.getResource(resourcePath)
InputStreamReader(resource.openStream(), StandardCharsets.UTF_8).use {
return Gson().fromJson(it, object: TypeToken<HashMap<String, Int>>() {}.type)
}
}
catch (ex: Throwable) {
LOG.error(ex.message)
return emptyMap()
}
}
} | apache-2.0 | 8dfdf29c6ae7c1a85408eb59ce3694cc | 42.30303 | 140 | 0.771709 | 4.434783 | false | false | false | false |
intellij-purescript/intellij-purescript | src/main/kotlin/org/purescript/parser/ParserContext.kt | 1 | 915 | @file:Suppress("unused")
package org.purescript.parser
import com.intellij.lang.PsiBuilder
import com.intellij.psi.tree.IElementType
class ParserContext(private val builder: PsiBuilder) {
var isInAttempt = false
private var inOptional = 0
fun eof() = builder.eof()
fun advance() = builder.advanceLexer()
fun enterOptional() = inOptional++
fun exitOptional() = inOptional--
fun isInOptional() = inOptional > 0
fun text() = builder.tokenText ?: ""
fun peek() = builder.tokenType ?: EOF
fun eat(type: IElementType): Boolean {
if (builder.tokenType === type) {
advance()
return true
}
return false
}
fun start(): PsiBuilder.Marker = builder.mark()
val position: Int
get() = builder.currentOffset
fun getText(start: Int, end: Int) =
builder.originalText.subSequence(start, end).toString()
}
| bsd-3-clause | a856c948449e320083ad3233990b3dc6 | 24.416667 | 63 | 0.642623 | 4.275701 | false | false | false | false |
googlecodelabs/android-performance | benchmarking/app/src/main/java/com/example/macrobenchmark_codelab/ui/components/Snackbar.kt | 1 | 1942 | /*
* 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.macrobenchmark_codelab.ui.components
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Snackbar
import androidx.compose.material.SnackbarData
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.example.macrobenchmark_codelab.ui.theme.JetsnackTheme
/**
* An alternative to [androidx.compose.material.Snackbar] utilizing
* [com.example.macrobenchmark_codelab.ui.theme.JetsnackColors]
*/
@Composable
fun JetsnackSnackbar(
snackbarData: SnackbarData,
modifier: Modifier = Modifier,
actionOnNewLine: Boolean = false,
shape: Shape = MaterialTheme.shapes.small,
backgroundColor: Color = JetsnackTheme.colors.uiBackground,
contentColor: Color = JetsnackTheme.colors.textSecondary,
actionColor: Color = JetsnackTheme.colors.brand,
elevation: Dp = 6.dp
) {
Snackbar(
snackbarData = snackbarData,
modifier = modifier,
actionOnNewLine = actionOnNewLine,
shape = shape,
backgroundColor = backgroundColor,
contentColor = contentColor,
actionColor = actionColor,
elevation = elevation
)
}
| apache-2.0 | 6f499b0606dd45b3b234a61ac300d638 | 34.309091 | 75 | 0.753862 | 4.403628 | false | false | false | false |
chromeos/video-composition-sample | VideoCompositionSample/src/main/java/dev/chromeos/videocompositionsample/presentation/ui/mapper/TrackModelMapper.kt | 1 | 2178 | /*
* Copyright (c) 2021 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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 dev.chromeos.videocompositionsample.presentation.ui.mapper
import dev.chromeos.videocompositionsample.presentation.ui.model.TrackModel
import dev.chromeos.videocompositionsample.domain.entity.Clip
import dev.chromeos.videocompositionsample.domain.entity.Effect
import dev.chromeos.videocompositionsample.domain.entity.Track
import dev.chromeos.videocompositionsample.presentation.R
import java.util.*
class TrackModelMapper {
fun map(entity: Track): TrackModel {
val nameResId = when (entity.clip) {
Clip.Video_3840x2160_30fps -> R.string.settings__clip1
Clip.Video_1080x1920_30fps -> R.string.settings__clip2
Clip.Video_3840x2160_60fps -> R.string.settings__clip3
Clip.Video_1920x1080_120fps -> R.string.settings__clip4
}
return TrackModel(
uuid = UUID.randomUUID().toString(),
clipId = entity.clip.clipId,
nameResId = nameResId,
effectId = entity.effect.effectId
)
}
fun mapToModel(entityList: List<Track>): List<TrackModel> {
return entityList.map { map(it) }
}
private fun map(model: TrackModel): Track {
val clip = Clip.fromClipId(model.clipId) ?: throw IllegalArgumentException("Not implemented")
val effect = Effect.fromEffectId(model.effectId) ?: throw IllegalArgumentException("Not implemented")
return Track(clip = clip, effect = effect)
}
fun mapFromModel(modelList: List<TrackModel>): List<Track> {
return modelList.map { map(it) }
}
} | apache-2.0 | 10a974342fa99e4799f79da4821f21bd | 37.910714 | 109 | 0.698347 | 4.164436 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/jvm-debugger/util/src/org/jetbrains/kotlin/idea/debugger/InlineUtils.kt | 1 | 13346 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.debugger
import com.intellij.debugger.jdi.LocalVariableProxyImpl
import com.intellij.debugger.jdi.StackFrameProxyImpl
import com.sun.jdi.LocalVariable
import org.jetbrains.kotlin.codegen.AsmUtil
import org.jetbrains.kotlin.codegen.inline.INLINE_FUN_VAR_SUFFIX
import org.jetbrains.kotlin.codegen.inline.isFakeLocalVariableForInline
import org.jetbrains.kotlin.idea.debugger.DebuggerUtils.getBorders
import org.jetbrains.kotlin.load.java.JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT
import org.jetbrains.kotlin.load.java.JvmAbi.LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION
val INLINED_THIS_REGEX = run {
val escapedName = Regex.escape(AsmUtil.INLINE_DECLARATION_SITE_THIS)
val escapedSuffix = Regex.escape(INLINE_FUN_VAR_SUFFIX)
Regex("^$escapedName(?:$escapedSuffix)*$")
}
/**
* An inline function aware view of a JVM stack frame.
*
* Due to inline functions in Kotlin, a single JVM stack frame maps
* to multiple Kotlin stack frames. The Kotlin compiler emits metadata
* in the form of local variables in order to allow the debugger to
* invert this mapping.
*
* This class encapsulates the mapping from visible variables in a
* JVM stack frame to a list of Kotlin stack frames and strips away
* the additional metadata that is only used for disambiguating inline
* stack frames.
*/
class InlineStackFrameVariableHolder private constructor(
// Visible variables sorted by start offset.
private val sortedVariables: List<LocalVariableProxyImpl>,
// Map from variable index to frame id. Every frame corresponds to a call to
// a Kotlin (inline) function.
private val variableFrameIds: IntArray,
private val currentFrameId: Int,
) {
// Returns all variables which are visible in the scope of the current (inline) function.
// This function hides scope introduction variables and strips inline metadata suffixes.
val visibleVariables: List<LocalVariableProxyImpl>
get() = sortedVariables.mapIndexedNotNull { index, variable ->
if (variableFrameIds[index] == currentFrameId) {
variable
} else {
null
}
}
val parentFrame: InlineStackFrameVariableHolder?
get() {
val scopeVariableIndex = sortedVariables.indexOfLast {
isFakeLocalVariableForInline(it.name())
}
if (scopeVariableIndex < 0) {
return null
}
val parentSortedVariables = sortedVariables.subList(0, scopeVariableIndex)
val parentVariableFrameIds = variableFrameIds.sliceArray(0 until scopeVariableIndex)
val parentFrameId = parentSortedVariables.indexOfLast {
isFakeLocalVariableForInline(it.name())
}.takeIf { it >= 0 }?.let { variableFrameIds[it] } ?: 0
return InlineStackFrameVariableHolder(parentSortedVariables, parentVariableFrameIds, parentFrameId)
}
companion object {
// Constructs an inline stack frame from a list of currently visible variables
// in introduction order.
//
// In order to construct the inline stack frame we need to associate each variable
// with a call to an inline function (frameId) and determine (the frameId of) the
// currently active inline function. Consider the following code.
//
// fun f() {
// val x = 0
// g {
// h(2)
// }
// }
//
// inline fun g(block: () -> Unit) {
// var y = 1
// block()
// }
//
// inline fun h(a: Int) {
// var z = 3
// /* breakpoint */ ...
// }
//
// When stopped at the breakpoint in `h`, we have the following visible variables.
//
// | Variable | Depth | Scope | Frame Id |
// |-------------------|-------|-------|----------|
// | x | 0 | f | 0 |
// | $i$f$g | 1 | g | 1 |
// | y$iv | 1 | g | 1 |
// | $i$a$-g-Class$f$1 | 0 | f$1 | 0 |
// | a$iv | 1 | h | 2 |
// | $i$f$h | 1 | h | 2 |
// | z$iv | 1 | h | 2 |
//
// There are two kinds of variables. Scope introduction variables are prefixed with
// $i$f or $i$a and represent calls to inline functions or calls to function arguments
// of inline functions respectively. All remaining variables represent source code
// variables along with an inline depth represented by the number of `$iv` suffixes.
//
// This function works by iterating over the variables in introduction order with
// a list of currently active stack frames. New frames are introduced or removed
// when encountering a scope introduction variable. Each variable encountered
// is either associated to one of the currently active stack frames or to the next
// inline function call (since the arguments of inline functions appear before the
// corresponding scope introduction variable).
private fun fromSortedVisibleVariables(sortedVariables: List<LocalVariableProxyImpl>): InlineStackFrameVariableHolder {
// Map from variables to frame ids
val variableFrameIds = IntArray(sortedVariables.size)
// Stack of currently active frames
var activeFrames = mutableListOf(0)
// Indices of variables representing arguments to the next function call
val pendingVariables = mutableListOf<Int>()
// Next unused frame id
var nextFrameId = 1
for ((currentIndex, variable) in sortedVariables.withIndex()) {
val name = variable.name()
val depth = getInlineDepth(name)
when {
// When we encounter a call to an inline function, we start a new frame
// using the next free frameId and assign this frame to both the scope
// introduction variable as well as all pending variables.
name.startsWith(LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION) -> {
val frameId = nextFrameId++
activeFrames.add(frameId)
for (pending in pendingVariables) {
variableFrameIds[pending] = frameId
}
pendingVariables.clear()
variableFrameIds[currentIndex] = frameId
}
// When we encounter a call to an inline function argument, we are
// moving up the call stack up to the depth of the function argument.
// This is why there should not be any pending variables at this
// point, since arguments to an inline function argument would be
// associated with a previous active frame.
//
// If we do encounter pending variables, then they belong to an
// inline call whose scope introduction variable was shadowed by
// a later call to the same function and can be hidden.
name.startsWith(LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT) -> {
for (pending in pendingVariables) {
variableFrameIds[pending] = -1
}
pendingVariables.clear()
if (depth + 1 < activeFrames.size) {
activeFrames = activeFrames.subList(0, depth + 1)
}
variableFrameIds[currentIndex] = activeFrames.last()
}
// Process variables in the current frame or a previous frame (for
// arguments to an inline function argument).
depth < activeFrames.size -> {
variableFrameIds[currentIndex] = activeFrames[depth]
}
// Process arguments to the next inline function call.
else -> {
if (depth == activeFrames.size) {
pendingVariables += currentIndex
} else {
// This can only happen if we skipped a scope introduction
// variable due to shadowing by a later call to the same
// function. In particular, the current index is not in
// scope and can be hidden.
variableFrameIds[currentIndex] = -1
}
}
}
}
return InlineStackFrameVariableHolder(sortedVariables, variableFrameIds, activeFrames.last())
}
fun fromStackFrame(frame: StackFrameProxyImpl): InlineStackFrameVariableHolder {
val allVariables = if (frame.virtualMachine.virtualMachine.isDexDebug()) {
frame.location().method().safeVariables()
} else null
// On the JVM the variable start offsets correspond to the introduction order,
// so we can proceed directly.
if (allVariables == null) {
val sortedVariables = frame.visibleVariables().sortedBy { it.variable }
return fromSortedVisibleVariables(sortedVariables)
}
// On dex, there are no separate slots for local variables. Instead, local variables
// are kept in registers and are subject to spilling. When a variable is spilled,
// its start offset is reset. In order to sort variables by introduction order,
// we need to identify spilled variables.
//
// The heuristic we use for this is to look for pairs of variables with the same
// name and type for which one begins exactly one instruction after the other ends.
//
// Unfortunately, this needs access to the private [scopeStart] and [scopeEnd] fields
// in [LocationImpl], but this is the only way to obtain the information we need.
val startOffsets = mutableMapOf<Long, MutableList<LocalVariable>>()
val replacements = mutableMapOf<LocalVariable, LocalVariable>()
for (variable in allVariables) {
val startOffset = variable.getBorders()?.start ?: continue
startOffsets.computeIfAbsent(startOffset.codeIndex()) { mutableListOf() } += variable
}
for (variable in allVariables) {
val endOffset = variable.getBorders()?.endInclusive ?: continue
val otherVariables = startOffsets[endOffset.codeIndex() + 1] ?: continue
for (other in otherVariables) {
if (variable.name() == other.name() && variable.type() == other.type()) {
replacements[other] = variable
}
}
}
// Replace each visible variable by its first visible alias when sorting.
val sortedVariables = frame.visibleVariables().sortedBy { proxy ->
var variable = proxy.variable
while (true) { variable = replacements[variable] ?: break }
variable
}
return fromSortedVisibleVariables(sortedVariables)
}
}
}
// Compute the current inline depth given a list of visible variables.
// All usages of this function should probably use [InlineStackFrame] instead,
// since the inline depth does not suffice to determine which variables
// are visible and this function will not work on a dex VM.
fun getInlineDepth(variables: List<LocalVariableProxyImpl>): Int {
val rawInlineFunDepth = variables.count { it.name().startsWith(LOCAL_VARIABLE_NAME_PREFIX_INLINE_FUNCTION) }
for (variable in variables.sortedByDescending { it.variable }) {
val name = variable.name()
val depth = getInlineDepth(name)
if (depth > 0) {
return depth
} else if (name.startsWith(LOCAL_VARIABLE_NAME_PREFIX_INLINE_ARGUMENT)) {
return 0
}
}
return rawInlineFunDepth
}
fun getInlineDepth(variableName: String): Int {
var endIndex = variableName.length
var depth = 0
val suffixLen = INLINE_FUN_VAR_SUFFIX.length
while (endIndex >= suffixLen) {
if (variableName.substring(endIndex - suffixLen, endIndex) != INLINE_FUN_VAR_SUFFIX) {
break
}
depth++
endIndex -= suffixLen
}
return depth
}
fun dropInlineSuffix(name: String): String {
val depth = getInlineDepth(name)
if (depth == 0) {
return name
}
return name.dropLast(depth * INLINE_FUN_VAR_SUFFIX.length)
} | apache-2.0 | 0e2739ef52bbbf5262adb9d7df8c241f | 46.667857 | 158 | 0.586917 | 5.260544 | false | false | false | false |
smmribeiro/intellij-community | platform/projectModel-impl/src/com/intellij/workspaceModel/ide/impl/legacyBridge/module/roots/ModifiableContentEntryBridge.kt | 3 | 10852 | package com.intellij.workspaceModel.ide.impl.legacyBridge.module.roots
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.roots.ContentEntry
import com.intellij.openapi.roots.ExcludeFolder
import com.intellij.openapi.roots.ModuleRootModel
import com.intellij.openapi.roots.SourceFolder
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.util.CachedValueProvider
import com.intellij.util.CachedValueImpl
import com.intellij.workspaceModel.ide.getInstance
import com.intellij.workspaceModel.ide.impl.toVirtualFileUrl
import com.intellij.workspaceModel.ide.isEqualOrParentOf
import com.intellij.workspaceModel.storage.WorkspaceEntityStorageDiffBuilder
import com.intellij.workspaceModel.storage.bridgeEntities.ModifiableContentRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.addSourceRootEntity
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaResourceRoot
import com.intellij.workspaceModel.storage.bridgeEntities.asJavaSourceRoot
import com.intellij.workspaceModel.storage.url.VirtualFileUrl
import com.intellij.workspaceModel.storage.url.VirtualFileUrlManager
import org.jetbrains.jps.model.JpsElement
import org.jetbrains.jps.model.java.JavaResourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootProperties
import org.jetbrains.jps.model.java.JavaSourceRootType
import org.jetbrains.jps.model.module.JpsModuleSourceRootType
import org.jetbrains.jps.model.serialization.module.JpsModuleSourceRootPropertiesSerializer
internal class ModifiableContentEntryBridge(
private val diff: WorkspaceEntityStorageDiffBuilder,
private val modifiableRootModel: ModifiableRootModelBridgeImpl,
val contentEntryUrl: VirtualFileUrl
) : ContentEntry {
companion object {
private val LOG = logger<ModifiableContentEntryBridge>()
}
private val virtualFileManager = VirtualFileUrlManager.getInstance(modifiableRootModel.project)
private val currentContentEntry = CachedValueImpl {
val contentEntry = modifiableRootModel.currentModel.contentEntries.firstOrNull { it.url == contentEntryUrl.url } as? ContentEntryBridge
?: error("Unable to find content entry in parent modifiable root model by url: $contentEntryUrl")
CachedValueProvider.Result.createSingleDependency(contentEntry, modifiableRootModel)
}
private fun <P : JpsElement> addSourceFolder(sourceFolderUrl: VirtualFileUrl, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder {
if (!contentEntryUrl.isEqualOrParentOf(sourceFolderUrl)) {
error("Source folder $sourceFolderUrl must be under content entry $contentEntryUrl")
}
val duplicate = findDuplicate(sourceFolderUrl, type, properties)
if (duplicate != null) {
LOG.debug("Source folder for '$sourceFolderUrl' and type '$type' already exist")
return duplicate
}
@Suppress("UNCHECKED_CAST")
val serializer: JpsModuleSourceRootPropertiesSerializer<P> = SourceRootPropertiesHelper.findSerializer(type)
?: error("Module source root type $type is not registered as JpsModelSerializerExtension")
val contentRootEntity = currentContentEntry.value.entity
val entitySource = contentRootEntity.entitySource
val sourceRootEntity = diff.addSourceRootEntity(
contentRoot = contentRootEntity,
url = sourceFolderUrl,
rootType = serializer.typeId,
source = entitySource
)
SourceRootPropertiesHelper.addPropertiesEntity(diff, sourceRootEntity, properties, serializer)
return currentContentEntry.value.sourceFolders.firstOrNull {
it.url == sourceFolderUrl.url && it.rootType == type
} ?: error("Source folder for '$sourceFolderUrl' and type '$type' was not found after adding")
}
private fun <P : JpsElement?> findDuplicate(sourceFolderUrl: VirtualFileUrl, type: JpsModuleSourceRootType<P>,
properties: P): SourceFolder? {
val propertiesFilter: (SourceFolder) -> Boolean = when (properties) {
is JavaSourceRootProperties -> label@{ sourceFolder: SourceFolder ->
val javaSourceRoot = (sourceFolder as SourceFolderBridge).sourceRootEntity.asJavaSourceRoot()
return@label javaSourceRoot != null && javaSourceRoot.generated == properties.isForGeneratedSources
&& javaSourceRoot.packagePrefix == properties.packagePrefix
}
is JavaResourceRootProperties -> label@{ sourceFolder: SourceFolder ->
val javaResourceRoot = (sourceFolder as SourceFolderBridge).sourceRootEntity.asJavaResourceRoot()
return@label javaResourceRoot != null && javaResourceRoot.generated == properties.isForGeneratedSources
&& javaResourceRoot.relativeOutputPath == properties.relativeOutputPath
}
else -> { _ -> true }
}
return sourceFolders.filter { it.url == sourceFolderUrl.url && it.rootType == type }.find { propertiesFilter.invoke(it) }
}
override fun removeSourceFolder(sourceFolder: SourceFolder) {
val legacyBridgeSourceFolder = sourceFolder as SourceFolderBridge
val sourceRootEntity = currentContentEntry.value.sourceRootEntities.firstOrNull { it == legacyBridgeSourceFolder.sourceRootEntity }
if (sourceRootEntity == null) {
LOG.error("SourceFolder ${sourceFolder.url} is not present under content entry $contentEntryUrl")
return
}
modifiableRootModel.removeCachedJpsRootProperties(sourceRootEntity.url)
diff.removeEntity(sourceRootEntity)
}
override fun clearSourceFolders() {
currentContentEntry.value.sourceRootEntities.forEach { sourceRoot -> diff.removeEntity(sourceRoot) }
}
private fun addExcludeFolder(excludeUrl: VirtualFileUrl): ExcludeFolder {
if (!contentEntryUrl.isEqualOrParentOf(excludeUrl)) {
error("Exclude folder $excludeUrl must be under content entry $contentEntryUrl")
}
if (excludeUrl !in currentContentEntry.value.entity.excludedUrls) {
updateContentEntry {
excludedUrls = excludedUrls + excludeUrl
}
}
return currentContentEntry.value.excludeFolders.firstOrNull {
it.url == excludeUrl.url
} ?: error("Exclude folder $excludeUrl must be present after adding it to content entry $contentEntryUrl")
}
override fun addExcludeFolder(file: VirtualFile): ExcludeFolder = addExcludeFolder(file.toVirtualFileUrl(virtualFileManager))
override fun addExcludeFolder(url: String): ExcludeFolder = addExcludeFolder(virtualFileManager.fromUrl(url))
override fun removeExcludeFolder(excludeFolder: ExcludeFolder) {
val virtualFileUrl = (excludeFolder as ExcludeFolderBridge).excludeFolderUrl
updateContentEntry {
if (!excludedUrls.contains(virtualFileUrl)) {
error("Exclude folder ${excludeFolder.url} is not under content entry $contentEntryUrl")
}
excludedUrls = excludedUrls.filter { url -> url != virtualFileUrl }
}
}
private fun updateContentEntry(updater: ModifiableContentRootEntity.() -> Unit) {
diff.modifyEntity(ModifiableContentRootEntity::class.java, currentContentEntry.value.entity, updater)
}
override fun removeExcludeFolder(url: String): Boolean {
val virtualFileUrl = virtualFileManager.fromUrl(url)
val excludedUrls = currentContentEntry.value.entity.excludedUrls
if (!excludedUrls.contains(virtualFileUrl)) return false
updateContentEntry {
this.excludedUrls = excludedUrls.filter { excludedUrl -> excludedUrl != virtualFileUrl }
}
return true
}
override fun clearExcludeFolders() {
updateContentEntry {
excludedUrls = emptyList()
}
}
override fun addExcludePattern(pattern: String) {
updateContentEntry {
excludedPatterns = if (excludedPatterns.contains(pattern)) excludedPatterns else (excludedPatterns + pattern)
}
}
override fun removeExcludePattern(pattern: String) {
updateContentEntry {
excludedPatterns = emptyList()
}
}
override fun setExcludePatterns(patterns: MutableList<String>) {
updateContentEntry {
excludedPatterns = patterns.toList()
}
}
override fun equals(other: Any?): Boolean {
return (other as? ContentEntry)?.url == url
}
override fun hashCode(): Int {
return url.hashCode()
}
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean) = addSourceFolder(file, isTestSource, "")
override fun addSourceFolder(file: VirtualFile, isTestSource: Boolean, packagePrefix: String): SourceFolder =
addSourceFolder(file, if (isTestSource) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE,
JavaSourceRootProperties(packagePrefix, false))
override fun <P : JpsElement> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>): SourceFolder =
addSourceFolder(file, type, type.createDefaultProperties())
override fun addSourceFolder(url: String, isTestSource: Boolean): SourceFolder =
addSourceFolder(url, if (isTestSource) JavaSourceRootType.TEST_SOURCE else JavaSourceRootType.SOURCE)
override fun <P : JpsElement> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>): SourceFolder =
addSourceFolder(url, type, type.createDefaultProperties())
override fun <P : JpsElement> addSourceFolder(file: VirtualFile, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder =
addSourceFolder(file.toVirtualFileUrl(virtualFileManager), type, properties)
override fun <P : JpsElement> addSourceFolder(url: String, type: JpsModuleSourceRootType<P>, properties: P): SourceFolder =
addSourceFolder(virtualFileManager.fromUrl(url), type, properties)
override fun getFile(): VirtualFile? = currentContentEntry.value.file
override fun getUrl(): String = contentEntryUrl.url
override fun getSourceFolders(): Array<SourceFolder> = currentContentEntry.value.sourceFolders
override fun getSourceFolders(rootType: JpsModuleSourceRootType<*>): List<SourceFolder> =
currentContentEntry.value.getSourceFolders(rootType)
override fun getSourceFolders(rootTypes: MutableSet<out JpsModuleSourceRootType<*>>): List<SourceFolder> =
currentContentEntry.value.getSourceFolders(rootTypes)
override fun getSourceFolderFiles(): Array<VirtualFile> = currentContentEntry.value.sourceFolderFiles
override fun getExcludeFolders(): Array<ExcludeFolder> = currentContentEntry.value.excludeFolders
override fun getExcludeFolderUrls(): MutableList<String> = currentContentEntry.value.excludeFolderUrls
override fun getExcludeFolderFiles(): Array<VirtualFile> = currentContentEntry.value.excludeFolderFiles
override fun getExcludePatterns(): List<String> = currentContentEntry.value.excludePatterns
override fun getRootModel(): ModuleRootModel = modifiableRootModel
override fun isSynthetic(): Boolean = currentContentEntry.value.isSynthetic
}
| apache-2.0 | a6fa4ea7d0d92e2512a58fdcc6265632 | 46.806167 | 155 | 0.770088 | 5.599587 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/models/ShippingRule.kt | 1 | 1440 | package com.kickstarter.models
import android.os.Parcelable
import kotlinx.parcelize.Parcelize
@Parcelize
class ShippingRule private constructor(
private val id: Long?,
private val cost: Double,
private val location: Location?
) : Parcelable {
fun id() = this.id
fun cost() = this.cost
fun location() = this.location
@Parcelize
data class Builder(
private var id: Long? = -1L,
private var cost: Double = 0.0,
private var location: Location? = Location.builder().build()
) : Parcelable {
fun id(id: Long?) = apply { this.id = id }
fun cost(cost: Double) = apply { this.cost = cost }
fun location(location: Location?) = apply { this.location = location }
fun build() = ShippingRule(
id = id,
cost = cost,
location = location
)
}
override fun toString(): String {
return location()?.displayableName() ?: ""
}
override fun equals(obj: Any?): Boolean {
var equals = super.equals(obj)
if (obj is ShippingRule) {
equals = id() == obj.id() &&
cost() == obj.cost() &&
location() == obj.location()
}
return equals
}
fun toBuilder() = Builder(
id = id,
cost = cost,
location = location
)
companion object {
@JvmStatic
fun builder() = Builder()
}
}
| apache-2.0 | b51a129dc4d64fe9a21f977285e947ea | 24.714286 | 78 | 0.552778 | 4.363636 | false | false | false | false |
vanniktech/lint-rules | lint-rules-android-lint/src/main/java/com/vanniktech/lintrules/android/ErroneousLayoutAttributeDetector.kt | 1 | 3226 | @file:Suppress("UnstableApiUsage") // We know that Lint APIs aren't final.
package com.vanniktech.lintrules.android
import com.android.SdkConstants
import com.android.SdkConstants.CONSTRAINT_LAYOUT
import com.android.SdkConstants.FRAME_LAYOUT
import com.android.SdkConstants.IMAGE_VIEW
import com.android.tools.lint.detector.api.Category
import com.android.tools.lint.detector.api.Implementation
import com.android.tools.lint.detector.api.Issue
import com.android.tools.lint.detector.api.LayoutDetector
import com.android.tools.lint.detector.api.Scope.Companion.RESOURCE_FILE_SCOPE
import com.android.tools.lint.detector.api.Severity.WARNING
import com.android.tools.lint.detector.api.XmlContext
import com.android.utils.forEach
import org.w3c.dom.Element
val ISSUE_ERRONEOUS_LAYOUT_ATTRIBUTE = Issue.create(
id = "ErroneousLayoutAttribute",
briefDescription = "Layout attribute that's not applicable to a particular view.",
explanation = "Flags if a layout attribute is not applicable to a particular view.",
category = Category.CORRECTNESS,
priority = PRIORITY,
severity = WARNING,
implementation = Implementation(ErroneousLayoutAttributeDetector::class.java, RESOURCE_FILE_SCOPE),
)
val ERRONEOUS_LAYOUT_ATTRIBUTES = mapOf(
CONSTRAINT_LAYOUT.newName() to listOf(
SdkConstants.ATTR_ORIENTATION,
SdkConstants.ATTR_GRAVITY,
SdkConstants.ATTR_SCALE_TYPE,
),
IMAGE_VIEW to listOf(
"maxLines",
),
FRAME_LAYOUT to listOf(
SdkConstants.ATTR_ORIENTATION,
SdkConstants.ATTR_GRAVITY,
),
)
class ErroneousLayoutAttributeDetector : LayoutDetector() {
override fun getApplicableElements() = ALL
override fun visitElement(
context: XmlContext,
element: Element,
) {
val layoutName = element.layoutName()
val erroneousAttributes = ERRONEOUS_LAYOUT_ATTRIBUTES[layoutName].orEmpty()
element.attributes.forEach { attribute ->
val tag = attribute.layoutAttribute()
if (tag?.startsWith("layout_constraint") == true) {
val parentLayout = (element.parentNode as Element).layoutName()
if (!CONSTRAINT_LAYOUT.isEquals(parentLayout) && !parentLayout.contains("ConstraintLayout")) {
context.report(
issue = ISSUE_ERRONEOUS_LAYOUT_ATTRIBUTE,
scope = attribute,
location = context.getLocation(attribute),
message = "$tag is not allowed since we have a $parentLayout parent",
quickfixData = fix()
.unset(attribute.namespaceURI, attribute.localName)
.name("Delete erroneous $tag attribute")
.autoFix()
.build(),
)
}
}
erroneousAttributes.forEach { erroneousAttribute ->
if (erroneousAttribute == tag) {
context.report(
issue = ISSUE_ERRONEOUS_LAYOUT_ATTRIBUTE,
scope = attribute,
location = context.getLocation(attribute),
message = "Attribute is erroneous on $layoutName",
quickfixData = fix()
.unset(attribute.namespaceURI, attribute.localName)
.name("Delete erroneous $tag attribute")
.autoFix()
.build(),
)
}
}
}
}
}
| apache-2.0 | 1025f73980b36288b4397080c84fafad | 34.450549 | 102 | 0.690639 | 4.413133 | false | false | false | false |
fabmax/kool | kool-core/src/commonMain/kotlin/de/fabmax/kool/util/BufferViews.kt | 1 | 850 | package de.fabmax.kool.util
import de.fabmax.kool.math.MutableVec2f
import de.fabmax.kool.math.MutableVec3f
import de.fabmax.kool.math.MutableVec4f
class Vec2fView(private val buf: Float32Buffer, var offset: Int) : MutableVec2f() {
override operator fun get(i: Int): Float = buf[offset + i]
override operator fun set(i: Int, v: Float) {
buf[offset + i] = v
}
}
class Vec3fView(private val buf: Float32Buffer, var offset: Int) : MutableVec3f() {
override operator fun get(i: Int): Float = buf[offset + i]
override operator fun set(i: Int, v: Float) {
buf[offset + i] = v
}
}
class Vec4fView(private val buf: Float32Buffer, var offset: Int) : MutableVec4f() {
override operator fun get(i: Int): Float = buf[offset + i]
override operator fun set(i: Int, v: Float) {
buf[offset + i] = v
}
} | apache-2.0 | 0eb1e67373afbdabbceb50fe149141fd | 31.730769 | 83 | 0.669412 | 3.183521 | false | false | false | false |
fabmax/kool | kool-demo/src/commonMain/kotlin/de/fabmax/kool/demo/SimplificationDemo.kt | 1 | 8397 | package de.fabmax.kool.demo
import de.fabmax.kool.AssetManager
import de.fabmax.kool.KoolContext
import de.fabmax.kool.demo.menu.DemoMenu
import de.fabmax.kool.math.Vec3f
import de.fabmax.kool.modules.gltf.GltfFile
import de.fabmax.kool.modules.gltf.loadGltfModel
import de.fabmax.kool.modules.ksl.blocks.ColorSpaceConversion
import de.fabmax.kool.modules.mesh.HalfEdgeMesh
import de.fabmax.kool.modules.mesh.ListEdgeHandler
import de.fabmax.kool.modules.mesh.simplification.simplify
import de.fabmax.kool.modules.mesh.simplification.terminateOnFaceCountRel
import de.fabmax.kool.modules.ui2.*
import de.fabmax.kool.pipeline.Attribute
import de.fabmax.kool.pipeline.shading.Albedo
import de.fabmax.kool.pipeline.shading.pbrShader
import de.fabmax.kool.scene.*
import de.fabmax.kool.scene.geometry.IndexedVertexList
import de.fabmax.kool.scene.geometry.MeshBuilder
import de.fabmax.kool.toString
import de.fabmax.kool.util.*
import kotlin.math.cos
import kotlin.math.sqrt
class SimplificationDemo : DemoScene("Simplification") {
private val models = mutableListOf<DemoModel>()
private val activeModel: MutableStateValue<DemoModel>
private var heMesh: HalfEdgeMesh
private val dispModel = Mesh(IndexedVertexList(Attribute.POSITIONS, Attribute.NORMALS))
private val modelWireframe = BetterLineMesh().apply {
shader = BetterLineMesh.LineShader {
color { vertexColor() }
colorSpaceConversion = ColorSpaceConversion.AS_IS
depthFactor = 0.9999f
}
}
private val simplifcationRatio = mutableStateOf(1f)
private val isAutoSimplify = mutableStateOf(true)
private val isAutoRotate = mutableStateOf(true)
private val isSolidVisible = mutableStateOf(true).onChange { dispModel.isVisible = it }
private val isWireframeVisible = mutableStateOf(true).onChange { modelWireframe.isVisible = it }
private val simplifiedNumFaces = mutableStateOf(0)
private val simplifiedNumVerts = mutableStateOf(0)
private val simplificationTime = mutableStateOf(0.0)
private class DemoModel(val name: String, val geometry: IndexedVertexList) {
override fun toString() = name
}
init {
dispModel.shader = pbrShader {
albedoSource = Albedo.STATIC_ALBEDO
albedo = Color.WHITE
roughness = 0.15f
}
val cosModel = DemoModel("Cosine grid", makeCosGrid())
activeModel = mutableStateOf(cosModel)
heMesh = HalfEdgeMesh(activeModel.value.geometry)
models += cosModel
}
override suspend fun AssetManager.loadResources(ctx: KoolContext) {
loadModel("Bunny", "${DemoLoader.modelPath}/bunny.gltf.gz", 1f, Vec3f(0f, -3f, 0f))
loadModel("Cow", "${DemoLoader.modelPath}/cow.gltf.gz", 1f, Vec3f.ZERO)
loadModel("Teapot", "${DemoLoader.modelPath}/teapot.gltf.gz", 1f, Vec3f(0f, -1.5f, 0f))
runSimplification(1f)
}
override fun Scene.setupMainScene(ctx: KoolContext) {
defaultCamTransform()
lighting.lights.apply {
clear()
add(Light().setDirectional(Vec3f(-1f, -1f, 1f)).setColor(MdColor.RED.mix(Color.WHITE, 0.25f).toLinear(), 2f))
add(Light().setDirectional(Vec3f(1f, -1f, -1f)).setColor(MdColor.CYAN.mix(Color.WHITE, 0.25f).toLinear(), 2f))
}
+group {
+dispModel
+modelWireframe
onUpdate += {
if (isAutoRotate.value) {
rotate(Time.deltaT * 3f, Vec3f.Y_AXIS)
}
}
}
}
private fun runSimplification(ratio: Float) {
val pt = PerfTimer()
dispModel.geometry.batchUpdate {
dispModel.geometry.clear()
dispModel.geometry.addGeometry(activeModel.value.geometry)
heMesh = HalfEdgeMesh(dispModel.geometry, ListEdgeHandler())
if (ratio < 0.999f) {
heMesh.simplify(terminateOnFaceCountRel(ratio.toDouble()))
}
modelWireframe.geometry.batchUpdate {
modelWireframe.clear()
heMesh.generateWireframe(modelWireframe, MdColor.LIME, 1.5f)
}
val time = pt.takeSecs()
simplificationTime.set(time)
simplifiedNumVerts.set(heMesh.vertCount)
simplifiedNumFaces.set(heMesh.faceCount)
if (time > 0.5) {
isAutoSimplify.set(false)
}
}
}
private suspend fun AssetManager.loadModel(name: String, path: String, scale: Float, offset: Vec3f) {
val modelCfg = GltfFile.ModelGenerateConfig(generateNormals = true, applyMaterials = false)
loadGltfModel(path, modelCfg)?.let { model ->
val mesh = model.meshes.values.first()
val geometry = mesh.geometry
for (i in 0 until geometry.numVertices) {
geometry.vertexIt.index = i
geometry.vertexIt.position.scale(scale).add(offset)
}
logD { "loaded: $name, bounds: ${geometry.bounds}" }
models += DemoModel(name, geometry)
}
}
private fun makeCosGrid(): IndexedVertexList {
val builder = MeshBuilder(IndexedVertexList(Attribute.POSITIONS, Attribute.NORMALS))
builder.color = MdColor.RED
builder.grid {
sizeX = 10f
sizeY = 10f
stepsX = 30
stepsY = 30
heightFun = { x, y ->
val fx = (x.toFloat() / stepsX - 0.5f) * 10f
val fy = (y.toFloat() / stepsY - 0.5f) * 10f
cos(sqrt(fx*fx + fy*fy)) * 2
}
}
return builder.geometry
}
override fun createMenu(menu: DemoMenu, ctx: KoolContext) = menuSurface {
MenuRow {
Text("Model") { labelStyle() }
ComboBox {
modifier
.width(Grow.Std)
.margin(start = sizes.largeGap)
.items(models)
.selectedIndex(models.indexOf(activeModel.use()))
.onItemSelected {
activeModel.set(models[it])
runSimplification(if (isAutoSimplify.value) simplifcationRatio.value else 1f)
}
}
}
MenuRow {
Text("Ratio") { labelStyle() }
MenuSlider(simplifcationRatio.use(), 0.01f, 1f, { "${(it * 100).toInt()} %" }) {
simplifcationRatio.set(it)
if (isAutoSimplify.value) {
runSimplification(simplifcationRatio.value)
}
}
}
Button("Simplify Mesh") {
modifier
.alignX(AlignmentX.Center)
.width(Grow.Std)
.margin(horizontal = 16.dp, vertical = 24.dp)
.onClick {
runSimplification(simplifcationRatio.value)
}
}
Text("Options") { sectionTitleStyle() }
MenuRow { LabeledSwitch("Auto simplify mesh", isAutoSimplify) }
MenuRow { LabeledSwitch("Draw solid", isSolidVisible) }
MenuRow { LabeledSwitch("Draw wireframe", isWireframeVisible) }
MenuRow { LabeledSwitch("Auto rotate view", isAutoRotate) }
Text("Statistics") { sectionTitleStyle() }
MenuRow {
Text("Faces") { labelStyle(Grow.Std) }
Text("${simplifiedNumFaces.use()} /") {
labelStyle()
modifier.textAlignX(AlignmentX.End)
}
Text("${activeModel.value.geometry.numPrimitives}") {
labelStyle()
modifier
.width(64.dp)
.textAlignX(AlignmentX.End)
}
}
MenuRow {
Text("Vertices") { labelStyle(Grow.Std) }
Text("${simplifiedNumVerts.use()} /") {
labelStyle()
modifier.textAlignX(AlignmentX.End)
}
Text("${activeModel.value.geometry.numVertices}") {
labelStyle()
modifier
.width(64.dp)
.textAlignX(AlignmentX.End)
}
}
MenuRow {
Text("Time") { labelStyle(Grow.Std) }
Text("${simplificationTime.use().toString(2)} s") { labelStyle() }
}
}
} | apache-2.0 | 2f88e0e16d6d7babc679c2be1457abb2 | 36.159292 | 122 | 0.590449 | 4.234493 | false | false | false | false |
jwren/intellij-community | platform/vcs-impl/src/com/intellij/openapi/vcs/changes/ShowEditorDiffPreviewActionProvider.kt | 3 | 1309 | // Copyright 2000-2021 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.openapi.vcs.changes
import com.intellij.idea.ActionsBundle.message
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.AnActionExtensionProvider
import com.intellij.openapi.vcs.changes.EditorTabDiffPreviewManager.Companion.EDITOR_TAB_DIFF_PREVIEW
open class ShowEditorDiffPreviewActionProvider : AnActionExtensionProvider {
override fun isActive(e: AnActionEvent): Boolean {
val project = e.project
return project != null &&
getDiffPreview(e) != null &&
EditorTabDiffPreviewManager.getInstance(project).isEditorDiffPreviewAvailable()
}
override fun update(e: AnActionEvent) {
getDiffPreview(e)?.run {
e.presentation.description += " " + message("action.Diff.ShowDiffPreview.description")
updateAvailability(e)
}
}
override fun actionPerformed(e: AnActionEvent) {
val diffPreview = getDiffPreview(e)!!
val previewManager = EditorTabDiffPreviewManager.getInstance(e.project!!)
previewManager.showDiffPreview(diffPreview)
}
open fun getDiffPreview(e: AnActionEvent) = e.getData(EDITOR_TAB_DIFF_PREVIEW)
}
| apache-2.0 | d7c3718fd0f9aa626dad29fe8a760056 | 38.666667 | 158 | 0.767762 | 4.482877 | false | false | false | false |
JetBrains/kotlin-native | backend.native/tests/runtime/collections/array_list1.kt | 4 | 10836 | /*
* Copyright 2010-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license
* that can be found in the LICENSE file.
*/
package runtime.collections.array_list1
import kotlin.test.*
fun assertTrue(cond: Boolean) {
if (!cond)
println("FAIL")
}
fun assertFalse(cond: Boolean) {
if (cond)
println("FAIL")
}
fun assertEquals(value1: Any?, value2: Any?) {
if (value1 != value2)
throw Error("FAIL " + value1 + " " + value2)
}
fun assertEquals(value1: Int, value2: Int) {
if (value1 != value2)
throw Error("FAIL " + value1 + " " + value2)
}
fun testBasic() {
val a = ArrayList<String>()
assertTrue(a.isEmpty())
assertEquals(0, a.size)
assertTrue(a.add("1"))
assertTrue(a.add("2"))
assertTrue(a.add("3"))
assertFalse(a.isEmpty())
assertEquals(3, a.size)
assertEquals("1", a[0])
assertEquals("2", a[1])
assertEquals("3", a[2])
a[0] = "11"
assertEquals("11", a[0])
assertEquals("11", a.removeAt(0))
assertEquals(2, a.size)
assertEquals("2", a[0])
assertEquals("3", a[1])
a.add(1, "22")
assertEquals(3, a.size)
assertEquals("2", a[0])
assertEquals("22", a[1])
assertEquals("3", a[2])
a.clear()
assertTrue(a.isEmpty())
assertEquals(0, a.size)
}
fun testIterator() {
val a = ArrayList(listOf("1", "2", "3"))
val it = a.iterator()
assertTrue(it.hasNext())
assertEquals("1", it.next())
assertTrue(it.hasNext())
assertEquals("2", it.next())
assertTrue(it.hasNext())
assertEquals("3", it.next())
assertFalse(it.hasNext())
}
fun testContainsAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
assertFalse(a.containsAll(listOf("6", "7", "8")))
assertFalse(a.containsAll(listOf("5", "6", "7")))
assertFalse(a.containsAll(listOf("4", "5", "6")))
assertTrue(a.containsAll(listOf("3", "4", "5")))
assertTrue(a.containsAll(listOf("2", "3", "4")))
}
fun testRemove() {
val a = ArrayList(listOf("1", "2", "3"))
assertTrue(a.remove("2"))
assertEquals(2, a.size)
assertEquals("1", a[0])
assertEquals("3", a[1])
assertFalse(a.remove("2"))
assertEquals(2, a.size)
assertEquals("1", a[0])
assertEquals("3", a[1])
}
fun testRemoveAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "1"))
assertFalse(a.removeAll(listOf("6", "7", "8")))
assertEquals(listOf("1", "2", "3", "4", "5", "1"), a)
assertTrue(a.removeAll(listOf("5", "3", "1")))
assertEquals(listOf("2", "4"), a)
}
fun testRetainAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
assertFalse(a.retainAll(listOf("1", "2", "3", "4", "5")))
assertEquals(listOf("1", "2", "3", "4", "5"), a)
assertTrue(a.retainAll(listOf("5", "3", "1")))
assertEquals(listOf("1", "3", "5"), a)
}
fun testEquals() {
val a = ArrayList(listOf("1", "2", "3"))
assertTrue(a == listOf("1", "2", "3"))
assertFalse(a == listOf("2", "3", "1")) // order matters
assertFalse(a == listOf("1", "2", "4"))
assertFalse(a == listOf("1", "2"))
}
fun testHashCode() {
val a = ArrayList(listOf("1", "2", "3"))
assertTrue(a.hashCode() == listOf("1", "2", "3").hashCode())
}
fun testToString() {
val a = ArrayList(listOf("1", "2", "3"))
assertTrue(a.toString() == listOf("1", "2", "3").toString())
}
fun testSubList() {
val a0 = ArrayList(listOf("0", "1", "2", "3", "4"))
val a = a0.subList(1, 4)
assertEquals(3, a.size)
assertEquals("1", a[0])
assertEquals("2", a[1])
assertEquals("3", a[2])
assertTrue(a == listOf("1", "2", "3"))
assertTrue(a.hashCode() == listOf("1", "2", "3").hashCode())
assertTrue(a.toString() == listOf("1", "2", "3").toString())
}
fun testResize() {
val a = ArrayList<String>()
val n = 10000
for (i in 1..n)
assertTrue(a.add(i.toString()))
assertEquals(n, a.size)
for (i in 1..n)
assertEquals(i.toString(), a[i - 1])
a.trimToSize()
assertEquals(n, a.size)
for (i in 1..n)
assertEquals(i.toString(), a[i - 1])
}
fun testSubListContains() {
val a = ArrayList(listOf("1", "2", "3", "4"))
val s = a.subList(1, 3)
assertTrue(a.contains("1"))
assertFalse(s.contains("1"))
assertTrue(a.contains("2"))
assertTrue(s.contains("2"))
assertTrue(a.contains("3"))
assertTrue(s.contains("3"))
assertTrue(a.contains("4"))
assertFalse(s.contains("4"))
}
fun testSubListIndexOf() {
val a = ArrayList(listOf("1", "2", "3", "4", "1"))
val s = a.subList(1, 3)
assertEquals(0, a.indexOf("1"))
assertEquals(-1, s.indexOf("1"))
assertEquals(1, a.indexOf("2"))
assertEquals(0, s.indexOf("2"))
assertEquals(2, a.indexOf("3"))
assertEquals(1, s.indexOf("3"))
assertEquals(3, a.indexOf("4"))
assertEquals(-1, s.indexOf("4"))
}
fun testSubListLastIndexOf() {
val a = ArrayList(listOf("1", "2", "3", "4", "1"))
val s = a.subList(1, 3)
assertEquals(4, a.lastIndexOf("1"))
assertEquals(-1, s.lastIndexOf("1"))
assertEquals(1, a.lastIndexOf("2"))
assertEquals(0, s.lastIndexOf("2"))
assertEquals(2, a.lastIndexOf("3"))
assertEquals(1, s.lastIndexOf("3"))
assertEquals(3, a.lastIndexOf("4"))
assertEquals(-1, s.lastIndexOf("4"))
}
fun testSubListClear() {
val a = ArrayList(listOf("1", "2", "3", "4"))
val s = a.subList(1, 3)
assertEquals(listOf("2", "3"), s)
s.clear()
assertEquals(listOf<String>(), s)
assertEquals(listOf("1", "4"), a)
}
fun testSubListSubListClear() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6"))
val s = a.subList(1, 5)
val q = s.subList(1, 3)
assertEquals(listOf("2", "3", "4", "5"), s)
assertEquals(listOf("3", "4"), q)
q.clear()
assertEquals(listOf<String>(), q)
assertEquals(listOf("2", "5"), s)
assertEquals(listOf("1", "2", "5", "6"), a)
}
fun testSubListAdd() {
val a = ArrayList(listOf("1", "2", "3", "4"))
val s = a.subList(1, 3)
assertEquals(listOf("2", "3"), s)
assertTrue(s.add("5"))
assertEquals(listOf("2", "3", "5"), s)
assertEquals(listOf("1", "2", "3", "5", "4"), a)
}
fun testSubListSubListAdd() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6"))
val s = a.subList(1, 5)
val q = s.subList(1, 3)
assertEquals(listOf("2", "3", "4", "5"), s)
assertEquals(listOf("3", "4"), q)
assertTrue(q.add("7"))
assertEquals(listOf("3", "4", "7"), q)
assertEquals(listOf("2", "3", "4", "7", "5"), s)
assertEquals(listOf("1", "2", "3", "4", "7", "5", "6"), a)
}
fun testSubListAddAll() {
val a = ArrayList(listOf("1", "2", "3", "4"))
val s = a.subList(1, 3)
assertEquals(listOf("2", "3"), s)
assertTrue(s.addAll(listOf("5", "6")))
assertEquals(listOf("2", "3", "5", "6"), s)
assertEquals(listOf("1", "2", "3", "5", "6", "4"), a)
}
fun testSubListSubListAddAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6"))
val s = a.subList(1, 5)
val q = s.subList(1, 3)
assertEquals(listOf("2", "3", "4", "5"), s)
assertEquals(listOf("3", "4"), q)
assertTrue(q.addAll(listOf("7", "8")))
assertEquals(listOf("3", "4", "7", "8"), q)
assertEquals(listOf("2", "3", "4", "7", "8", "5"), s)
assertEquals(listOf("1", "2", "3", "4", "7", "8", "5", "6"), a)
}
fun testSubListRemoveAt() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
val s = a.subList(1, 4)
assertEquals(listOf("2", "3", "4"), s)
assertEquals("3", s.removeAt(1))
assertEquals(listOf("2", "4"), s)
assertEquals(listOf("1", "2", "4", "5"), a)
}
fun testSubListSubListRemoveAt() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6", "7"))
val s = a.subList(1, 6)
val q = s.subList(1, 4)
assertEquals(listOf("2", "3", "4", "5", "6"), s)
assertEquals(listOf("3", "4", "5"), q)
assertEquals("4", q.removeAt(1))
assertEquals(listOf("3", "5"), q)
assertEquals(listOf("2", "3", "5", "6"), s)
assertEquals(listOf("1", "2", "3", "5", "6", "7"), a)
}
fun testSubListRemoveAll() {
val a = ArrayList(listOf("1", "2", "3", "3", "4", "5"))
val s = a.subList(1, 5)
assertEquals(listOf("2", "3", "3", "4"), s)
assertTrue(s.removeAll(listOf("3", "5")))
assertEquals(listOf("2", "4"), s)
assertEquals(listOf("1", "2", "4", "5"), a)
}
fun testSubListSubListRemoveAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6", "7"))
val s = a.subList(1, 6)
val q = s.subList(1, 4)
assertEquals(listOf("2", "3", "4", "5", "6"), s)
assertEquals(listOf("3", "4", "5"), q)
assertTrue(q.removeAll(listOf("4", "6")))
assertEquals(listOf("3", "5"), q)
assertEquals(listOf("2", "3", "5", "6"), s)
assertEquals(listOf("1", "2", "3", "5", "6", "7"), a)
}
fun testSubListRetainAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
val s = a.subList(1, 4)
assertEquals(listOf("2", "3", "4"), s)
assertTrue(s.retainAll(listOf("5", "3")))
assertEquals(listOf("3"), s)
assertEquals(listOf("1", "3", "5"), a)
}
fun testSubListSubListRetainAll() {
val a = ArrayList(listOf("1", "2", "3", "4", "5", "6", "7"))
val s = a.subList(1, 6)
val q = s.subList(1, 4)
assertEquals(listOf("2", "3", "4", "5", "6"), s)
assertEquals(listOf("3", "4", "5"), q)
assertTrue(q.retainAll(listOf("5", "3")))
assertEquals(listOf("3", "5"), q)
assertEquals(listOf("2", "3", "5", "6"), s)
assertEquals(listOf("1", "2", "3", "5", "6", "7"), a)
}
fun testIteratorRemove() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
val it = a.iterator()
while (it.hasNext())
if (it.next()[0].toInt() % 2 == 0)
it.remove()
assertEquals(listOf("1", "3", "5"), a)
}
fun testIteratorAdd() {
val a = ArrayList(listOf("1", "2", "3", "4", "5"))
val it = a.listIterator()
while (it.hasNext()) {
val next = it.next()
if (next[0].toInt() % 2 == 0)
it.add("-" + next)
}
assertEquals(listOf("1", "2", "-2", "3", "4", "-4", "5"), a)
}
@Test fun runTest() {
testBasic()
testIterator()
testRemove()
testRemoveAll()
testRetainAll()
testEquals()
testHashCode()
testToString()
testSubList()
testResize()
testSubListContains()
testSubListIndexOf()
testSubListLastIndexOf()
testSubListClear()
testSubListSubListClear()
testSubListAdd()
testSubListSubListAdd()
testSubListAddAll()
testSubListSubListAddAll()
testSubListRemoveAt()
testSubListSubListRemoveAt()
testSubListRemoveAll()
testSubListSubListRemoveAll()
testSubListSubListRemoveAll()
testSubListRetainAll()
testSubListSubListRetainAll()
testIteratorRemove()
testIteratorAdd()
println("OK")
} | apache-2.0 | ad5f504406796082ae3a96903257d0cf | 27.148052 | 101 | 0.550941 | 2.98348 | false | true | false | false |
androidx/androidx | viewpager2/integration-tests/testapp/src/main/java/androidx/viewpager2/integration/testapp/NestedScrollableHost.kt | 4 | 4517 | /*
* Copyright 2019 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.viewpager2.integration.testapp
import android.content.Context
import android.util.AttributeSet
import android.view.MotionEvent
import android.view.View
import android.view.ViewConfiguration
import android.widget.FrameLayout
import androidx.viewpager2.widget.ViewPager2
import androidx.viewpager2.widget.ViewPager2.ORIENTATION_HORIZONTAL
import kotlin.math.absoluteValue
import kotlin.math.sign
/**
* Layout to wrap a scrollable component inside a ViewPager2. Provided as a solution to the problem
* where pages of ViewPager2 have nested scrollable elements that scroll in the same direction as
* ViewPager2. The scrollable element needs to be the immediate and only child of this host layout.
*
* This solution has limitations when using multiple levels of nested scrollable elements
* (e.g. a horizontal RecyclerView in a vertical RecyclerView in a horizontal ViewPager2).
*/
class NestedScrollableHost : FrameLayout {
constructor(context: Context) : super(context)
constructor(context: Context, attrs: AttributeSet?) : super(context, attrs)
private var touchSlop = 0
private var initialX = 0f
private var initialY = 0f
private val parentViewPager: ViewPager2?
get() {
var v: View? = parent as? View
while (v != null && v !is ViewPager2) {
v = v.parent as? View
}
return v as? ViewPager2
}
private val child: View? get() = if (childCount > 0) getChildAt(0) else null
init {
touchSlop = ViewConfiguration.get(context).scaledTouchSlop
}
private fun canChildScroll(orientation: Int, delta: Float): Boolean {
val direction = -delta.sign.toInt()
return when (orientation) {
0 -> child?.canScrollHorizontally(direction) ?: false
1 -> child?.canScrollVertically(direction) ?: false
else -> throw IllegalArgumentException()
}
}
override fun onInterceptTouchEvent(e: MotionEvent): Boolean {
handleInterceptTouchEvent(e)
return super.onInterceptTouchEvent(e)
}
private fun handleInterceptTouchEvent(e: MotionEvent) {
val orientation = parentViewPager?.orientation ?: return
// Early return if child can't scroll in same direction as parent
if (!canChildScroll(orientation, -1f) && !canChildScroll(orientation, 1f)) {
return
}
if (e.action == MotionEvent.ACTION_DOWN) {
initialX = e.x
initialY = e.y
parent.requestDisallowInterceptTouchEvent(true)
} else if (e.action == MotionEvent.ACTION_MOVE) {
val dx = e.x - initialX
val dy = e.y - initialY
val isVpHorizontal = orientation == ORIENTATION_HORIZONTAL
// assuming ViewPager2 touch-slop is 2x touch-slop of child
val scaledDx = dx.absoluteValue * if (isVpHorizontal) .5f else 1f
val scaledDy = dy.absoluteValue * if (isVpHorizontal) 1f else .5f
if (scaledDx > touchSlop || scaledDy > touchSlop) {
if (isVpHorizontal == (scaledDy > scaledDx)) {
// Gesture is perpendicular, allow all parents to intercept
parent.requestDisallowInterceptTouchEvent(false)
} else {
// Gesture is parallel, query child if movement in that direction is possible
if (canChildScroll(orientation, if (isVpHorizontal) dx else dy)) {
// Child can scroll, disallow all parents to intercept
parent.requestDisallowInterceptTouchEvent(true)
} else {
// Child cannot scroll, allow all parents to intercept
parent.requestDisallowInterceptTouchEvent(false)
}
}
}
}
}
} | apache-2.0 | 47a6c5cfea4c8d6048c086de54bd5fb5 | 39.339286 | 99 | 0.655302 | 4.872708 | false | false | false | false |
androidx/androidx | camera/camera-camera2-pipe/src/main/java/androidx/camera/camera2/pipe/compat/CaptureSessionState.kt | 3 | 17245 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
@file:RequiresApi(21) // TODO(b/200306659): Remove and replace with annotation on package-info.java
package androidx.camera.camera2.pipe.compat
import android.hardware.camera2.CameraCaptureSession
import android.view.Surface
import androidx.annotation.GuardedBy
import androidx.annotation.RequiresApi
import androidx.camera.camera2.pipe.CameraSurfaceManager
import androidx.camera.camera2.pipe.StreamId
import androidx.camera.camera2.pipe.core.Debug
import androidx.camera.camera2.pipe.core.Log
import androidx.camera.camera2.pipe.core.TimestampNs
import androidx.camera.camera2.pipe.core.Timestamps
import androidx.camera.camera2.pipe.core.Timestamps.formatMs
import androidx.camera.camera2.pipe.graph.GraphListener
import androidx.camera.camera2.pipe.graph.GraphRequestProcessor
import java.io.Closeable
import java.util.Collections.synchronizedMap
import kotlinx.atomicfu.atomic
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.launch
internal val captureSessionDebugIds = atomic(0)
/**
* This class encapsulates the state and logic required to manage the lifecycle of a single Camera2
* [CameraCaptureSession], and subsequently wrapping it into a [GraphRequestProcessor] and passing
* it to the [GraphListener].
*
* After this object is created, it waits for:
* - A valid CameraDevice via [cameraDevice]
* - A valid map of Surfaces via [configureSurfaceMap]
* Once these objects are available, it will create the [CameraCaptureSession].
*
* If at any time this object is put into a COSING or CLOSED state the session will either never be
* created, or if the session has already been created, it will be de-referenced and ignored. This
* object goes into a CLOSING or CLOSED state if disconnect or shutdown is called, or if the created
* [CameraCaptureSession] invokes onClosed or onConfigureFailed.
*
* This class is thread safe.
*/
internal class CaptureSessionState(
private val graphListener: GraphListener,
private val captureSessionFactory: CaptureSessionFactory,
private val captureSequenceProcessorFactory: Camera2CaptureSequenceProcessorFactory,
private val cameraSurfaceManager: CameraSurfaceManager,
private val scope: CoroutineScope
) : CameraCaptureSessionWrapper.StateCallback {
private val debugId = captureSessionDebugIds.incrementAndGet()
private val lock = Any()
private val finalized = atomic<Boolean>(false)
private val activeSurfaceMap = synchronizedMap(HashMap<StreamId, Surface>())
private var sessionCreatingTimestamp: TimestampNs? = null
@GuardedBy("lock")
private var _cameraDevice: CameraDeviceWrapper? = null
var cameraDevice: CameraDeviceWrapper?
get() = synchronized(lock) { _cameraDevice }
set(value) = synchronized(lock) {
if (state == State.CLOSING || state == State.CLOSED) {
return
}
_cameraDevice = value
if (value != null) {
scope.launch { tryCreateCaptureSession() }
}
}
@GuardedBy("lock")
private var cameraCaptureSession: ConfiguredCameraCaptureSession? = null
@GuardedBy("lock")
private var pendingOutputMap: Map<StreamId, OutputConfigurationWrapper>? = null
@GuardedBy("lock")
private var pendingSurfaceMap: Map<StreamId, Surface>? = null
@GuardedBy("lock")
private var state = State.PENDING
private enum class State {
PENDING,
CREATING,
CREATED,
CLOSING,
CLOSED
}
@GuardedBy("lock")
private var _surfaceMap: Map<StreamId, Surface>? = null
@GuardedBy("lock")
private val _surfaceTokenMap: MutableMap<Surface, Closeable> = mutableMapOf()
fun configureSurfaceMap(surfaces: Map<StreamId, Surface>) {
synchronized(lock) {
if (state == State.CLOSING || state == State.CLOSED) {
return@synchronized
}
updateTrackedSurfaces(_surfaceMap ?: emptyMap(), surfaces)
_surfaceMap = surfaces
val pendingOutputs = pendingOutputMap
if (pendingOutputs != null && pendingSurfaceMap == null) {
// Filter the list of current surfaces down ones that are present in the set of
// deferred outputs.
val pendingSurfaces = surfaces.filter { pendingOutputs.containsKey(it.key) }
// We can only invoke finishDeferredOutputs after we have a surface for ALL
// of the deferred outputs.
if (pendingSurfaces.size == pendingOutputs.size) {
pendingSurfaceMap = pendingSurfaces
scope.launch { finalizeOutputsIfAvailable() }
}
}
scope.launch { tryCreateCaptureSession() }
}
}
override fun onActive(session: CameraCaptureSessionWrapper) {
Log.debug { "$this Active" }
}
override fun onClosed(session: CameraCaptureSessionWrapper) {
Log.debug { "$this Closed" }
Debug.traceStart { "$this#onClosed" }
disconnect()
Debug.traceStop()
}
override fun onConfigureFailed(session: CameraCaptureSessionWrapper) {
Log.warn { "$this Configuration Failed" }
Debug.traceStart { "$this#onConfigureFailed" }
disconnect()
Debug.traceStop()
}
override fun onConfigured(session: CameraCaptureSessionWrapper) {
Log.debug { "$this Configured" }
Debug.traceStart { "$this#configure" }
configure(session)
Debug.traceStop()
}
override fun onReady(session: CameraCaptureSessionWrapper) {
Log.debug { "$this Ready" }
}
override fun onCaptureQueueEmpty(session: CameraCaptureSessionWrapper) {
Log.debug { "$this CaptureQueueEmpty" }
}
override fun onSessionFinalized() {
// Only invoke finalizeSession once regardless of the number of times it is invoked.
if (finalized.compareAndSet(expect = false, update = true)) {
Log.debug { "$this Finalizing Session" }
Debug.traceStart { "$this#onSessionFinalized" }
disconnect()
finalizeSession()
Debug.traceStop()
}
}
private fun configure(session: CameraCaptureSessionWrapper?) {
val captureSession: ConfiguredCameraCaptureSession?
var tryConfigureDeferred = false
// This block is designed to do two things:
// 1. Get or create a GraphRequestProcessor instance.
// 2. Pass the GraphRequestProcessor to the graphProcessor after the session is fully
// created and the onConfigured callback has been invoked.
synchronized(lock) {
if (state == State.CLOSING || state == State.CLOSED) {
return
}
if (cameraCaptureSession == null && session != null) {
captureSession = ConfiguredCameraCaptureSession(
session,
GraphRequestProcessor.from(
captureSequenceProcessorFactory.create(session, activeSurfaceMap)
)
)
cameraCaptureSession = captureSession
} else {
captureSession = cameraCaptureSession
}
if (state != State.CREATED || captureSession == null) {
return
}
// Finalize deferredConfigs if finalizeOutputConfigurations was previously invoked.
if (pendingOutputMap != null && pendingSurfaceMap != null) {
tryConfigureDeferred = true
}
}
if (tryConfigureDeferred) {
finalizeOutputsIfAvailable(retryAllowed = false)
}
synchronized(lock) {
captureSession?.let {
Log.info {
val duration = Timestamps.now() - sessionCreatingTimestamp!!
"Configured $this in ${duration.formatMs()}"
}
graphListener.onGraphStarted(it.processor)
}
}
}
/**
* This is used to disconnect the cached [CameraCaptureSessionWrapper] and put this object into
* a closed state. This will not cancel repeating requests or abort captures.
*/
fun disconnect() {
shutdown(false)
}
/**
* This is used to disconnect the cached [CameraCaptureSessionWrapper] and put this object into
* a closed state. This may stop the repeating request and abort captures.
*/
private fun shutdown(abortAndStopRepeating: Boolean) {
var configuredCaptureSession: ConfiguredCameraCaptureSession? = null
synchronized(lock) {
if (state == State.CLOSING || state == State.CLOSED) {
return@synchronized
}
state = State.CLOSING
configuredCaptureSession = cameraCaptureSession
cameraCaptureSession = null
}
val graphProcessor = configuredCaptureSession?.processor
if (graphProcessor != null) {
Log.debug { "$this Shutdown" }
Debug.traceStart { "$this#shutdown" }
Debug.traceStart { "$graphListener#onGraphStopped" }
graphListener.onGraphStopped(graphProcessor)
Debug.traceStop()
if (abortAndStopRepeating) {
Debug.traceStart { "$this#stopRepeating" }
graphProcessor.stopRepeating()
Debug.traceStop()
Debug.traceStart { "$this#stopRepeating" }
graphProcessor.abortCaptures()
Debug.traceStop()
}
// WARNING:
// This does NOT call close on the captureSession to avoid potentially slow
// reconfiguration during mode switch and shutdown. This avoids unintentional restarts
// by clearing the internal captureSession variable, clearing all repeating requests,
// and by aborting any pending single requests.
//
// The reason we do not call close is that the android camera HAL doesn't shut down
// cleanly unless the device is also closed. See b/135125484 for example.
//
// WARNING - DO NOT CALL session.close().
Debug.traceStop()
}
var shouldFinalizeSession: Boolean
synchronized(lock) {
// If the CameraDevice is never opened, the session will never be created. For cleanup
// reasons, make sure the session is finalized after shutdown if the cameraDevice was
// never set.
shouldFinalizeSession = _cameraDevice == null
_cameraDevice = null
state = State.CLOSED
}
if (shouldFinalizeSession) {
finalizeSession()
}
}
private fun finalizeSession() {
val tokenList = synchronized(lock) {
val tokens = _surfaceTokenMap.values.toList()
_surfaceTokenMap.clear()
tokens
}
tokenList.forEach { it.close() }
}
private fun finalizeOutputsIfAvailable(retryAllowed: Boolean = true) {
val captureSession: ConfiguredCameraCaptureSession?
val pendingOutputs: Map<StreamId, OutputConfigurationWrapper>?
val pendingSurfaces: Map<StreamId, Surface>?
synchronized(lock) {
captureSession = cameraCaptureSession
pendingOutputs = pendingOutputMap
pendingSurfaces = pendingSurfaceMap
}
if (captureSession != null && pendingOutputs != null && pendingSurfaces != null) {
Debug.traceStart { "$this#finalizeOutputConfigurations" }
val finalizedStartTime = Timestamps.now()
for ((streamId, outputConfig) in pendingOutputs) {
// TODO: Consider adding support for experimental libraries on older devices.
val surface = checkNotNull(pendingSurfaces[streamId])
outputConfig.addSurface(surface)
}
// It's possible that more than one stream maps to the same output configuration since
// output configurations support multiple surfaces. If this happens, we may have more
// deferred outputs than outputConfiguration objects.
val distinctOutputs = pendingOutputs.mapTo(mutableSetOf()) { it.value }.toList()
captureSession.session.finalizeOutputConfigurations(distinctOutputs)
var tryResubmit = false
synchronized(lock) {
if (state == State.CREATED) {
activeSurfaceMap.putAll(pendingSurfaces)
Log.info {
val finalizationTime = Timestamps.now() - finalizedStartTime
"Finalized ${pendingOutputs.map { it.key }} for $this in " +
finalizationTime.formatMs()
}
tryResubmit = true
}
}
if (tryResubmit && retryAllowed) {
graphListener.onGraphModified(captureSession.processor)
}
Debug.traceStop()
}
}
private fun tryCreateCaptureSession() {
val surfaces: Map<StreamId, Surface>?
val device: CameraDeviceWrapper?
synchronized(lock) {
if (state != State.PENDING) {
return
}
surfaces = _surfaceMap
device = _cameraDevice
if (surfaces == null || device == null) {
return
}
state = State.CREATING
sessionCreatingTimestamp = Timestamps.now()
}
// Create the capture session and return a Map of StreamId -> OutputConfiguration for any
// outputs that were not initially available. These will be configured later.
Log.info {
"Creating CameraCaptureSession from ${device?.cameraId} using $this with $surfaces"
}
val deferred = Debug.trace(
"CameraDevice-${device?.cameraId?.value}#createCaptureSession"
) {
captureSessionFactory.create(device!!, surfaces!!, this)
}
synchronized(lock) {
if (state == State.CLOSING || state == State.CLOSED) {
Log.info { "Warning: $this was $state while configuration was in progress." }
return
}
check(state == State.CREATING) { "Unexpected state: $state" }
state = State.CREATED
activeSurfaceMap.putAll(surfaces!!)
if (deferred.isNotEmpty()) {
Log.info {
"Created $this with ${surfaces.keys.toList()}. " +
"Waiting to finalize ${deferred.keys.toList()}"
}
pendingOutputMap = deferred
val availableDeferredSurfaces = _surfaceMap?.filter {
deferred.containsKey(it.key)
}
if (availableDeferredSurfaces != null &&
availableDeferredSurfaces.size == deferred.size
) {
pendingSurfaceMap = availableDeferredSurfaces
}
}
}
// There are rare cases where the onConfigured call may be invoked synchronously. If this
// happens, we need to invoke configure here to make sure the session ends up in a valid
// state.
configure(session = null)
}
@GuardedBy("lock")
private fun updateTrackedSurfaces(
oldSurfaceMap: Map<StreamId, Surface>,
newSurfaceMap: Map<StreamId, Surface>
) {
val oldSurfaces = oldSurfaceMap.values.toSet()
val newSurfaces = newSurfaceMap.values.toSet()
// Close the Surfaces that were removed (unset).
val removedSurfaces = oldSurfaces - newSurfaces
for (surface in removedSurfaces) {
val surfaceToken = _surfaceTokenMap.remove(surface)?.also { it.close() }
checkNotNull(surfaceToken) { "Surface $surface doesn't have a matching surface token!" }
}
// Register new Surfaces.
val addedSurfaces = newSurfaces - oldSurfaces
for (surface in addedSurfaces) {
val surfaceToken = cameraSurfaceManager.registerSurface(surface)
_surfaceTokenMap[surface] = surfaceToken
}
}
override fun toString(): String = "CaptureSessionState-$debugId"
private data class ConfiguredCameraCaptureSession(
val session: CameraCaptureSessionWrapper,
val processor: GraphRequestProcessor
)
} | apache-2.0 | 9c8a1406e61026636c199c5030a71e87 | 36.986784 | 100 | 0.625689 | 5.21312 | false | true | false | false |
GunoH/intellij-community | platform/built-in-server/src/org/jetbrains/builtInWebServer/WebServerPathToFileManager.kt | 5 | 7679 | // 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.builtInWebServer
import com.github.benmanes.caffeine.cache.CacheLoader
import com.github.benmanes.caffeine.cache.Caffeine
import com.intellij.ProjectTopics
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.components.service
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.rootManager
import com.intellij.openapi.roots.AdditionalLibraryRootsListener
import com.intellij.openapi.roots.ModuleRootEvent
import com.intellij.openapi.roots.ModuleRootListener
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileManager
import com.intellij.openapi.vfs.newvfs.BulkFileListener
import com.intellij.openapi.vfs.newvfs.events.VFileContentChangeEvent
import com.intellij.openapi.vfs.newvfs.events.VFileEvent
import com.intellij.util.SmartList
import com.intellij.util.io.exists
import java.nio.file.Paths
import java.util.concurrent.TimeUnit
private const val cacheSize: Long = 4096 * 4
/**
* Implement [WebServerRootsProvider] to add your provider
*/
class WebServerPathToFileManager(private val project: Project) {
internal val pathToInfoCache = Caffeine.newBuilder().maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES).build<String, PathInfo>()
// time to expire should be greater than pathToFileCache
private val virtualFileToPathInfo = Caffeine.newBuilder().maximumSize(cacheSize).expireAfterAccess(11, TimeUnit.MINUTES).build<VirtualFile, PathInfo>()
internal val pathToExistShortTermCache = Caffeine.newBuilder().maximumSize(cacheSize).expireAfterAccess(5, TimeUnit.SECONDS).build<String, Boolean>()
/**
* https://youtrack.jetbrains.com/issue/WEB-25900
*
* Compute suitable roots for oldest parent (web/foo/my/file.dart -> oldest is web and we compute all suitable roots for it in advance) to avoid linear search
* (i.e. to avoid two queries for root if files web/foo and web/bar requested if root doesn't have web dir)
*/
internal val parentToSuitableRoot = Caffeine
.newBuilder()
.maximumSize(cacheSize).expireAfterAccess(10, TimeUnit.MINUTES)
.build<String, List<SuitableRoot>>(CacheLoader { path ->
val suitableRoots = SmartList<SuitableRoot>()
var moduleQualifier: String? = null
val modules = runReadAction { ModuleManager.getInstance(project).modules }
for (rootProvider in RootProvider.values()) {
for (module in modules) {
if (module.isDisposed) {
continue
}
for (root in rootProvider.getRoots(module.rootManager)) {
if (root.findChild(path) != null) {
if (moduleQualifier == null) {
moduleQualifier = getModuleNameQualifier(project, module)
}
suitableRoots.add(SuitableRoot(root, moduleQualifier))
}
}
}
}
suitableRoots
})
init {
ApplicationManager.getApplication().messageBus.connect (project).subscribe(VirtualFileManager.VFS_CHANGES, object : BulkFileListener {
override fun after(events: List<VFileEvent>) {
for (event in events) {
if (event is VFileContentChangeEvent) {
val file = event.file
for (rootsProvider in WebServerRootsProvider.EP_NAME.extensions) {
if (rootsProvider.isClearCacheOnFileContentChanged(file)) {
clearCache()
break
}
}
}
else {
clearCache()
break
}
}
}
})
project.messageBus.connect().subscribe(ProjectTopics.PROJECT_ROOTS, object : ModuleRootListener {
override fun rootsChanged(event: ModuleRootEvent) {
clearCache()
}
})
project.messageBus.connect().subscribe(AdditionalLibraryRootsListener.TOPIC,
AdditionalLibraryRootsListener { _, _, _, _ ->
clearCache()
})
}
companion object {
@JvmStatic
fun getInstance(project: Project) = project.service<WebServerPathToFileManager>()
}
private fun clearCache() {
pathToInfoCache.invalidateAll()
virtualFileToPathInfo.invalidateAll()
pathToExistShortTermCache.invalidateAll()
parentToSuitableRoot.invalidateAll()
}
@JvmOverloads
fun findVirtualFile(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): VirtualFile? {
return getPathInfo(path, cacheResult, pathQuery)?.getOrResolveVirtualFile()
}
@JvmOverloads
fun getPathInfo(path: String, cacheResult: Boolean = true, pathQuery: PathQuery = defaultPathQuery): PathInfo? {
var pathInfo = pathToInfoCache.getIfPresent(path)
if (pathInfo == null || !pathInfo.isValid) {
if (pathToExistShortTermCache.getIfPresent(path) == false) {
return null
}
pathInfo = doFindByRelativePath(path, pathQuery)
if (cacheResult) {
if (pathInfo != null && pathInfo.isValid) {
pathToInfoCache.put(path, pathInfo)
}
else {
pathToExistShortTermCache.put(path, false)
}
}
}
return pathInfo
}
fun getPath(file: VirtualFile): String? = getPathInfo(file)?.path
fun getPathInfo(child: VirtualFile): PathInfo? {
var result = virtualFileToPathInfo.getIfPresent(child)
if (result == null) {
result = WebServerRootsProvider.EP_NAME.extensionList.asSequence().map { it.getPathInfo(child, project) }.find { it != null }
if (result != null) {
virtualFileToPathInfo.put(child, result)
}
}
return result
}
internal fun doFindByRelativePath(path: String, pathQuery: PathQuery): PathInfo? {
val result = WebServerRootsProvider.EP_NAME.extensionList.asSequence().map { it.resolve(path, project, pathQuery) }.find { it != null } ?: return null
result.file?.let {
virtualFileToPathInfo.put(it, result)
}
return result
}
fun getResolver(path: String): FileResolver = if (path.isEmpty()) EMPTY_PATH_RESOLVER else RELATIVE_PATH_RESOLVER
}
interface FileResolver {
fun resolve(path: String, root: VirtualFile, moduleName: String? = null, isLibrary: Boolean = false, pathQuery: PathQuery): PathInfo?
}
private val RELATIVE_PATH_RESOLVER = object : FileResolver {
override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? {
// WEB-17691 built-in server doesn't serve files it doesn't have in the project tree
// temp:// reports isInLocalFileSystem == true, but it is not true
if (pathQuery.useVfs || root.fileSystem != LocalFileSystem.getInstance() || path == ".htaccess" || path == "config.json") {
return root.findFileByRelativePath(path)?.let { PathInfo(null, it, root, moduleName, isLibrary) }
}
val file = Paths.get(root.path, path)
return if (file.exists()) {
PathInfo(file, null, root, moduleName, isLibrary)
}
else {
null
}
}
}
private val EMPTY_PATH_RESOLVER = object : FileResolver {
override fun resolve(path: String, root: VirtualFile, moduleName: String?, isLibrary: Boolean, pathQuery: PathQuery): PathInfo? {
val file = findIndexFile(root) ?: return null
return PathInfo(null, file, root, moduleName, isLibrary)
}
}
internal val defaultPathQuery = PathQuery() | apache-2.0 | 6bceb0a98403cfef89ae4604f238bd9e | 38.792746 | 160 | 0.695794 | 4.799375 | false | false | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/actions/generate/KotlinGenerateActionBase.kt | 2 | 2314 | // 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.actions.generate
import com.intellij.codeInsight.CodeInsightActionHandler
import com.intellij.codeInsight.actions.CodeInsightAction
import com.intellij.lang.ContextAwareActionHandler
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.openapi.actionSystem.Presentation
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiFile
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindFilter
import org.jetbrains.kotlin.idea.base.projectStructure.RootKindMatcher
import org.jetbrains.kotlin.psi.KtClassOrObject
import org.jetbrains.kotlin.psi.KtFile
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
abstract class KotlinGenerateActionBase : CodeInsightAction(), CodeInsightActionHandler {
override fun update(
presentation: Presentation,
project: Project,
editor: Editor,
file: PsiFile,
dataContext: DataContext,
actionPlace: String?
) {
super.update(presentation, project, editor, file, dataContext, actionPlace)
val actionHandler = handler
if (actionHandler is ContextAwareActionHandler && presentation.isEnabled) {
presentation.isEnabled = actionHandler.isAvailableForQuickList(editor, file, dataContext)
}
}
override fun isValidForFile(project: Project, editor: Editor, file: PsiFile): Boolean {
if (file !is KtFile || file.isCompiled) return false
val targetClass = getTargetClass(editor, file) ?: return false
if (!targetClass.isValid) return false
val filter = RootKindFilter.projectSources.copy(includeScriptsOutsideSourceRoots = true)
return RootKindMatcher.matches(targetClass, filter) && isValidForClass(targetClass)
}
protected open fun getTargetClass(editor: Editor, file: PsiFile): KtClassOrObject? {
return file.findElementAt(editor.caretModel.offset)?.getNonStrictParentOfType<KtClassOrObject>()
}
protected abstract fun isValidForClass(targetClass: KtClassOrObject): Boolean
override fun startInWriteAction() = false
override fun getHandler() = this
} | apache-2.0 | 9e44897219d531f0c1ce30a146a0d898 | 42.679245 | 120 | 0.767934 | 4.955032 | false | false | false | false |
GunoH/intellij-community | plugins/svn4idea/src/org/jetbrains/idea/svn/api/ErrorCode.kt | 16 | 1377 | // 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.idea.svn.api
import org.jetbrains.idea.svn.api.ErrorCategory.*
private const val ERROR_BASE = 120000
private const val ERROR_CATEGORY_SIZE = 5000
enum class ErrorCategory(val code: Int) {
ENTRY(6),
WC(7),
FS(8),
RA(10),
RA_DAV(11),
CLIENT(15),
MISC(16),
AUTHN(19),
AUTHZ(20);
val start: Int = ERROR_BASE + code * ERROR_CATEGORY_SIZE
companion object {
@JvmStatic
fun categoryCodeOf(errorCode: Int): Int = (errorCode - ERROR_BASE) / ERROR_CATEGORY_SIZE
}
}
enum class ErrorCode(val category: ErrorCategory, val index: Int) {
ENTRY_EXISTS(ENTRY, 2),
WC_LOCKED(WC, 4),
WC_NOT_WORKING_COPY(WC, 7),
WC_NOT_FILE(WC, 8),
WC_PATH_NOT_FOUND(WC, 10),
WC_CORRUPT(WC, 16),
WC_CORRUPT_TEXT_BASE(WC, 17),
WC_UNSUPPORTED_FORMAT(WC, 21),
WC_UPGRADE_REQUIRED(WC, 36),
FS_NOT_FOUND(FS, 13),
RA_ILLEGAL_URL(RA, 0),
RA_NOT_AUTHORIZED(RA, 1),
RA_UNKNOWN_AUTH(RA, 2),
RA_DAV_PATH_NOT_FOUND(RA_DAV, 7),
CLIENT_UNRELATED_RESOURCES(CLIENT, 12),
BASE(MISC, 0),
UNVERSIONED_RESOURCE(MISC, 5),
UNSUPPORTED_FEATURE(MISC, 7),
ILLEGAL_TARGET(MISC, 9),
PROPERTY_NOT_FOUND(MISC, 17),
MERGE_INFO_PARSE_ERROR(MISC, 20);
val code: Int = category.start + index
} | apache-2.0 | 85f1a491875a7af23c673c0287029a61 | 22.758621 | 140 | 0.678286 | 2.936034 | false | false | false | false |
jwren/intellij-community | platform/lang-impl/src/com/intellij/codeInsight/hints/presentation/ScaleAwarePresentationFactory.kt | 5 | 7450 | // 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.codeInsight.hints.presentation
import com.intellij.codeInsight.hints.InlayPresentationFactory
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.editor.markup.TextAttributes
import com.intellij.ui.scale.JBUIScale
import com.intellij.ui.scale.ScaleContext
import com.intellij.ui.scale.ScaleContextAware
import com.intellij.util.IconUtil
import org.jetbrains.annotations.ApiStatus
import java.awt.AlphaComposite
import java.awt.Color
import java.awt.Graphics2D
import java.awt.Point
import java.awt.event.MouseEvent
import javax.swing.Icon
import kotlin.math.roundToInt
import kotlin.reflect.KProperty
/**
* Presentation factory, which handles presentation mode and scales Icons and Insets
*/
@ApiStatus.Experimental
class ScaleAwarePresentationFactory(
val editor: Editor,
private val delegate: PresentationFactory
) : InlayPresentationFactory by delegate {
fun lineCentered(presentation: InlayPresentation): InlayPresentation {
return LineCenteredInset(presentation, editor)
}
override fun container(presentation: InlayPresentation,
padding: InlayPresentationFactory.Padding?,
roundedCorners: InlayPresentationFactory.RoundedCorners?,
background: Color?,
backgroundAlpha: Float): InlayPresentation {
return ScaledContainerPresentation(presentation, editor, padding, roundedCorners, background, backgroundAlpha)
}
override fun icon(icon: Icon): InlayPresentation {
return MyScaledIconPresentation(icon, editor, fontShift = 0)
}
fun icon(icon: Icon, debugName: String, fontShift: Int): InlayPresentation {
return MyScaledIconPresentation(icon, editor, debugName, fontShift)
}
fun inset(base: InlayPresentation, left: Int = 0, right: Int = 0, top: Int = 0, down: Int = 0): InlayPresentation {
return ScaledInsetPresentation(
base,
left = left,
right = right,
top = top,
down = down,
editor = editor
)
}
fun seq(vararg presentations: InlayPresentation): InlayPresentation {
return delegate.seq(*presentations)
}
}
private class ScaledInsetPresentation(
private val presentation: InlayPresentation,
private val left: Int,
private val right: Int,
private val top: Int,
private val down: Int,
private val editor: Editor
) : ScaledDelegatedPresentation() {
override val delegate: InsetPresentation by valueOf<InsetPresentation, Float> { fontSize ->
InsetPresentation(
presentation,
scaleByFont(left, fontSize),
scaleByFont(right, fontSize),
scaleByFont(top, fontSize),
scaleByFont(down, fontSize)
)
}.withState {
editor.colorsScheme.editorFontSize2D
}
}
private class ScaledContainerPresentation(
private val presentation: InlayPresentation,
private val editor: Editor,
private val padding: InlayPresentationFactory.Padding? = null,
private val roundedCorners: InlayPresentationFactory.RoundedCorners? = null,
private val background: Color? = null,
private val backgroundAlpha: Float = 0.55f
) : ScaledDelegatedPresentation() {
override val delegate: ContainerInlayPresentation by valueOf<ContainerInlayPresentation, Float> { fontSize ->
ContainerInlayPresentation(
presentation,
scaleByFont(padding, fontSize),
scaleByFont(roundedCorners, fontSize),
background,
backgroundAlpha
)
}.withState {
editor.colorsScheme.editorFontSize2D
}
}
private abstract class ScaledDelegatedPresentation : BasePresentation() {
protected abstract val delegate: InlayPresentation
override val width: Int
get() = delegate.width
override val height: Int
get() = delegate.height
override fun paint(g: Graphics2D, attributes: TextAttributes) {
delegate.paint(g, attributes)
}
override fun toString(): String {
return delegate.toString()
}
override fun mouseClicked(event: MouseEvent, translated: Point) {
delegate.mouseExited()
}
override fun mouseMoved(event: MouseEvent, translated: Point) {
delegate.mouseMoved(event, translated)
}
override fun mouseExited() {
delegate.mouseExited()
}
}
private class LineCenteredInset(
private val presentation: InlayPresentation,
private val editor: Editor
) : ScaledDelegatedPresentation() {
override val delegate: InlayPresentation by valueOf<InlayPresentation, Int> { lineHeight ->
val innerHeight = presentation.height
InsetPresentation(presentation, top = (lineHeight - innerHeight) / 2)
}.withState {
editor.lineHeight
}
}
private class MyScaledIconPresentation(val icon: Icon,
val editor: Editor,
private val debugName: String = "image",
val fontShift: Int) : BasePresentation() {
override val width: Int
get() = scaledIcon.iconWidth
override val height: Int
get() = scaledIcon.iconHeight
override fun paint(g: Graphics2D, attributes: TextAttributes) {
val graphics = g.create() as Graphics2D
graphics.composite = AlphaComposite.SrcAtop.derive(1.0f)
scaledIcon.paintIcon(editor.component, graphics, 0, 0)
graphics.dispose()
}
override fun toString(): String = "<$debugName>"
private val scaledIcon by valueOf<Icon, Float> { fontSize ->
(icon as? ScaleContextAware)?.updateScaleContext(ScaleContext.create(editor.component))
IconUtil.scaleByFont(icon, editor.component, fontSize)
}.withState {
editor.colorsScheme.editorFontSize2D - fontShift
}
}
private class StateDependantValue<TData : Any, TState : Any>(
private val valueProvider: (TState) -> TData,
private val stateProvider: () -> TState
) {
private var currentState: TState? = null
private lateinit var cachedValue: TData
operator fun getValue(thisRef: Any?, property: KProperty<*>): TData {
val state = stateProvider()
if (state != currentState) {
currentState = state
cachedValue = valueProvider(state)
}
return cachedValue
}
}
private fun <TData : Any, TState : Any> valueOf(dataProvider: (TState) -> TData): StateDependantValueBuilder<TData, TState> {
return StateDependantValueBuilder(dataProvider)
}
private class StateDependantValueBuilder<TData : Any, TState : Any>(private val dataProvider: (TState) -> TData) {
fun withState(stateProvider: () -> TState): StateDependantValue<TData, TState> {
return StateDependantValue(dataProvider, stateProvider)
}
}
private fun scaleByFont(sizeFor12: Int, fontSize: Float) = (JBUIScale.getFontScale(fontSize) * sizeFor12).roundToInt()
private fun scaleByFont(paddingFor12: InlayPresentationFactory.Padding?, fontSize: Float) =
paddingFor12?.let { (left, right, top, bottom) ->
InlayPresentationFactory.Padding(
left = scaleByFont(left, fontSize),
right = scaleByFont(right, fontSize),
top = scaleByFont(top, fontSize),
bottom = scaleByFont(bottom, fontSize)
)
}
private fun scaleByFont(roundedCornersFor12: InlayPresentationFactory.RoundedCorners?, fontSize: Float) =
roundedCornersFor12?.let { (arcWidth, arcHeight) ->
InlayPresentationFactory.RoundedCorners(
arcWidth = scaleByFont(arcWidth, fontSize),
arcHeight = scaleByFont(arcHeight, fontSize)
)
} | apache-2.0 | 2d494964906e56b6759d38c13c3bf4ff | 32.868182 | 140 | 0.726577 | 4.772582 | false | false | false | false |
GunoH/intellij-community | platform/lang-impl/src/com/intellij/util/indexing/roots/SdkIndexableFilesIteratorImpl.kt | 1 | 3901 | // 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.util.indexing.roots
import com.intellij.openapi.project.Project
import com.intellij.openapi.projectRoots.Sdk
import com.intellij.openapi.projectRoots.SdkType
import com.intellij.openapi.roots.ContentIterator
import com.intellij.openapi.roots.OrderRootType
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.openapi.vfs.VirtualFileFilter
import com.intellij.util.indexing.IndexingBundle
import com.intellij.util.indexing.roots.kind.IndexableSetOrigin
import com.intellij.util.indexing.roots.origin.SdkOriginImpl
import org.jetbrains.annotations.ApiStatus
import java.util.*
@ApiStatus.Internal
class SdkIndexableFilesIteratorImpl private constructor(private val sdk: Sdk,
private val rootsToIndex: Collection<VirtualFile>) : IndexableFilesIterator {
override fun getDebugName() = "$sdkPresentableName ${sdk.name} ${rootsToIndex.joinToString { it.path }}"
private val sdkPresentableName: String
get() = (sdk.sdkType as? SdkType)?.presentableName.takeUnless { it.isNullOrEmpty() }
?: IndexingBundle.message("indexable.files.provider.indexing.sdk.unnamed")
override fun getIndexingProgressText() = IndexingBundle.message("indexable.files.provider.indexing.sdk", sdkPresentableName, sdk.name)
override fun getRootsScanningProgressText() = IndexingBundle.message("indexable.files.provider.scanning.sdk", sdkPresentableName,
sdk.name)
override fun getOrigin(): IndexableSetOrigin = SdkOriginImpl(sdk, rootsToIndex)
override fun iterateFiles(
project: Project,
fileIterator: ContentIterator,
fileFilter: VirtualFileFilter
): Boolean {
return IndexableFilesIterationMethods.iterateRoots(project, rootsToIndex, fileIterator, fileFilter)
}
override fun getRootUrls(project: Project): Set<String> {
return rootsToIndex.map { it.url }.toSet()
}
companion object {
fun createIterator(sdk: Sdk): SdkIndexableFilesIteratorImpl = SdkIndexableFilesIteratorImpl(sdk, getRootsToIndex(sdk))
fun getRootsToIndex(sdk: Sdk): Collection<VirtualFile> {
val rootProvider = sdk.rootProvider
return rootProvider.getFiles(OrderRootType.SOURCES).toList() + rootProvider.getFiles(OrderRootType.CLASSES)
}
fun createIterators(sdk: Sdk, listOfRootsToFilter: List<VirtualFile>): Collection<IndexableFilesIterator> {
val sdkRoots = getRootsToIndex(sdk).toMutableList()
val rootsToIndex = filterRootsToIterate(sdkRoots, listOfRootsToFilter)
val oldStyle: Collection<IndexableFilesIterator> = if (rootsToIndex.isEmpty()) {
emptyList()
}
else {
Collections.singletonList(SdkIndexableFilesIteratorImpl(sdk, rootsToIndex))
}
return oldStyle
}
fun filterRootsToIterate(initialRoots: MutableList<VirtualFile>,
listOfRootsToFilter: List<VirtualFile>): List<VirtualFile> {
val rootsToFilter = listOfRootsToFilter.toMutableList()
val rootsToIndex = mutableListOf<VirtualFile>()
val iteratorToFilter = rootsToFilter.iterator()
while (iteratorToFilter.hasNext()) {
val next = iteratorToFilter.next()
for (sdkRoot in initialRoots) {
if (VfsUtil.isAncestor(next, sdkRoot, false)) {
rootsToIndex.add(sdkRoot)
initialRoots.remove(sdkRoot)
iteratorToFilter.remove()
break
}
}
}
for (file in rootsToFilter) {
for (sdkRoot in initialRoots) {
if (VfsUtil.isAncestor(sdkRoot, file, false)) {
rootsToIndex.add(file)
}
}
}
return rootsToIndex
}
}
} | apache-2.0 | d99a0b94748603ad1ad5b7ee9f1664e8 | 40.073684 | 136 | 0.711356 | 4.751523 | false | false | false | false |
GunoH/intellij-community | plugins/package-search/src/com/jetbrains/packagesearch/intellij/plugin/fus/PackageSearchEventsLogger.kt | 2 | 12544 | /*******************************************************************************
* Copyright 2000-2022 JetBrains s.r.o. and contributors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* 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.jetbrains.packagesearch.intellij.plugin.fus
import com.intellij.buildsystem.model.unified.UnifiedDependencyRepository
import com.intellij.internal.statistic.eventLog.EventLogGroup
import com.intellij.internal.statistic.eventLog.events.BaseEventId
import com.intellij.internal.statistic.eventLog.events.EventFields
import com.intellij.internal.statistic.eventLog.events.EventPair
import com.intellij.internal.statistic.service.fus.collectors.CounterUsagesCollector
import com.intellij.openapi.diagnostic.RuntimeExceptionWithAttachments
import com.intellij.openapi.diagnostic.thisLogger
import com.jetbrains.packagesearch.intellij.plugin.PackageSearchBundle
import com.jetbrains.packagesearch.intellij.plugin.extensibility.CoroutineProjectModuleOperationProvider
import com.jetbrains.packagesearch.intellij.plugin.extensibility.ProjectModule
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageIdentifier
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.PackageVersion
import com.jetbrains.packagesearch.intellij.plugin.ui.toolwindow.models.TargetModules
import com.jetbrains.packagesearch.intellij.plugin.util.logDebug
import org.jetbrains.idea.reposearch.statistics.TopPackageIdValidationRule
private const val FUS_ENABLED = true
class PackageSearchEventsLogger : CounterUsagesCollector() {
override fun getGroup() = GROUP
companion object {
private const val VERSION = 11
private val GROUP = EventLogGroup(FUSGroupIds.GROUP_ID, VERSION)
// FIELDS
private val buildSystemField = EventFields.Class(FUSGroupIds.MODULE_OPERATION_PROVIDER_CLASS)
private val packageIdField = EventFields.StringValidatedByCustomRule(FUSGroupIds.PACKAGE_ID, TopPackageIdValidationRule::class.java)
private val packageVersionField = EventFields.StringValidatedByRegexp(FUSGroupIds.PACKAGE_VERSION, regexpRef = "version")
private val packageFromVersionField = EventFields.StringValidatedByRegexp(FUSGroupIds.PACKAGE_FROM_VERSION, regexpRef = "version")
private val repositoryIdField = EventFields.Enum<FUSGroupIds.IndexedRepositories>(FUSGroupIds.REPOSITORY_ID)
private val repositoryUrlField = EventFields.String(FUSGroupIds.REPOSITORY_URL, allowedValues = FUSGroupIds.indexedRepositoryUrls)
private val repositoryUsesCustomUrlField = EventFields.Boolean(FUSGroupIds.REPOSITORY_USES_CUSTOM_URL)
private val packageIsInstalledField = EventFields.Boolean(FUSGroupIds.PACKAGE_IS_INSTALLED)
private val targetModulesField = EventFields.Enum<FUSGroupIds.TargetModulesType>(FUSGroupIds.TARGET_MODULES)
private val targetModulesMixedBuildSystemsField = EventFields.Boolean(FUSGroupIds.TARGET_MODULES_MIXED_BUILD_SYSTEMS)
val preferencesGradleScopeCountField = EventFields.Int(FUSGroupIds.PREFERENCES_GRADLE_SCOPES_COUNT)
val preferencesUpdateScopesOnUsageField = EventFields.Boolean(FUSGroupIds.PREFERENCES_UPDATE_SCOPES_ON_USAGE)
val preferencesDefaultGradleScopeChangedField = EventFields.Boolean(FUSGroupIds.PREFERENCES_DEFAULT_GRADLE_SCOPE_CHANGED)
val preferencesDefaultMavenScopeChangedField = EventFields.Boolean(FUSGroupIds.PREFERENCES_DEFAULT_MAVEN_SCOPE_CHANGED)
internal val preferencesAutoAddRepositoriesField = EventFields.Boolean(FUSGroupIds.PREFERENCES_AUTO_ADD_REPOSITORIES)
private val detailsLinkLabelField = EventFields.Enum<FUSGroupIds.DetailsLinkTypes>(FUSGroupIds.DETAILS_LINK_LABEL)
private val toggleTypeField = EventFields.Enum<FUSGroupIds.ToggleTypes>(FUSGroupIds.DETAILS_VISIBLE)
private val detailsVisibleField = EventFields.Boolean(FUSGroupIds.DETAILS_VISIBLE)
private val searchQueryLengthField = EventFields.Int(FUSGroupIds.SEARCH_QUERY_LENGTH)
// EVENTS
private val packageInstalledEvent = GROUP.registerEvent(
eventId = FUSGroupIds.PACKAGE_INSTALLED,
eventField1 = packageIdField,
eventField2 = packageVersionField,
eventField3 = buildSystemField
)
private val packageRemovedEvent = GROUP.registerEvent(
eventId = FUSGroupIds.PACKAGE_REMOVED,
eventField1 = packageIdField,
eventField2 = packageVersionField,
eventField3 = buildSystemField
)
private val packageUpdatedEvent = GROUP.registerVarargEvent(
eventId = FUSGroupIds.PACKAGE_UPDATED,
packageIdField, packageFromVersionField, packageVersionField, buildSystemField
)
private val repositoryAddedEvent = GROUP.registerEvent(
eventId = FUSGroupIds.REPOSITORY_ADDED,
eventField1 = repositoryIdField,
eventField2 = repositoryUrlField
)
private val repositoryRemovedEvent = GROUP.registerEvent(
eventId = FUSGroupIds.REPOSITORY_REMOVED,
eventField1 = repositoryIdField,
eventField2 = repositoryUrlField,
eventField3 = repositoryUsesCustomUrlField
)
private val preferencesChangedEvent = GROUP.registerVarargEvent(
eventId = FUSGroupIds.PREFERENCES_CHANGED,
preferencesGradleScopeCountField,
preferencesUpdateScopesOnUsageField,
preferencesDefaultGradleScopeChangedField,
preferencesDefaultMavenScopeChangedField,
preferencesAutoAddRepositoriesField
)
private val preferencesRestoreDefaultsEvent = GROUP.registerEvent(FUSGroupIds.PREFERENCES_RESTORE_DEFAULTS)
private val packageSelectedEvent = GROUP.registerEvent(eventId = FUSGroupIds.PACKAGE_SELECTED, packageIsInstalledField)
private val targetModulesSelectedEvent = GROUP.registerEvent(
eventId = FUSGroupIds.TARGET_MODULES_SELECTED,
eventField1 = targetModulesField,
eventField2 = targetModulesMixedBuildSystemsField
)
private val detailsLinkClickEvent = GROUP.registerEvent(
eventId = FUSGroupIds.DETAILS_LINK_CLICK,
eventField1 = detailsLinkLabelField
)
private val toggleDetailsEvent = GROUP.registerEvent(
eventId = FUSGroupIds.TOGGLE,
eventField1 = toggleTypeField,
eventField2 = detailsVisibleField
)
private val searchRequestEvent = GROUP.registerEvent(
eventId = FUSGroupIds.SEARCH_REQUEST,
eventField1 = searchQueryLengthField
)
private val searchQueryClearEvent = GROUP.registerEvent(FUSGroupIds.SEARCH_QUERY_CLEAR)
private val upgradeAllEvent = GROUP.registerEvent(FUSGroupIds.UPGRADE_ALL)
fun logPackageInstalled(
packageIdentifier: PackageIdentifier,
packageVersion: PackageVersion,
targetModule: ProjectModule
) = runSafelyIfEnabled(packageInstalledEvent) {
val moduleOperationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(targetModule.moduleType)
if (moduleOperationProvider != null) {
log(packageIdentifier.rawValue, packageVersion.versionName, moduleOperationProvider::class.java)
} else {
logDebug { "Unable to log package installation for target module '${targetModule.name}': no operation provider available" }
}
}
fun logPackageRemoved(
packageIdentifier: PackageIdentifier,
packageVersion: PackageVersion,
targetModule: ProjectModule
) = runSafelyIfEnabled(packageRemovedEvent) {
val moduleOperationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(targetModule.moduleType)
if (moduleOperationProvider != null) {
log(packageIdentifier.rawValue, packageVersion.versionName, moduleOperationProvider::class.java)
} else {
logDebug { "Unable to log package removal for target module '${targetModule.name}': no operation provider available" }
}
}
fun logPackageUpdated(
packageIdentifier: PackageIdentifier,
packageFromVersion: PackageVersion,
packageVersion: PackageVersion,
targetModule: ProjectModule
) = runSafelyIfEnabled(packageUpdatedEvent) {
val moduleOperationProvider = CoroutineProjectModuleOperationProvider.forProjectModuleType(targetModule.moduleType)
if (moduleOperationProvider != null) {
log(
packageIdField.with(packageIdentifier.rawValue),
packageFromVersionField.with(packageFromVersion.versionName),
packageVersionField.with(packageVersion.versionName),
buildSystemField.with(moduleOperationProvider::class.java)
)
} else {
logDebug { "Unable to log package update for target module '${targetModule.name}': no operation provider available" }
}
}
fun logRepositoryAdded(model: UnifiedDependencyRepository) = runSafelyIfEnabled(repositoryAddedEvent) {
log(FUSGroupIds.IndexedRepositories.forId(model.id), FUSGroupIds.IndexedRepositories.validateUrl(model.url))
}
fun logRepositoryRemoved(model: UnifiedDependencyRepository) = runSafelyIfEnabled(repositoryRemovedEvent) {
val repository = FUSGroupIds.IndexedRepositories.forId(model.id)
val validatedUrl = FUSGroupIds.IndexedRepositories.validateUrl(model.url)
val usesCustomUrl = repository != FUSGroupIds.IndexedRepositories.NONE &&
repository != FUSGroupIds.IndexedRepositories.OTHER &&
validatedUrl == null
log(repository, validatedUrl, usesCustomUrl)
}
fun logPreferencesChanged(vararg preferences: EventPair<*>) = runSafelyIfEnabled(preferencesChangedEvent) {
log(*preferences)
}
fun logPreferencesRestoreDefaults() = runSafelyIfEnabled(preferencesRestoreDefaultsEvent) {
log()
}
fun logTargetModuleSelected(targetModules: TargetModules) = runSafelyIfEnabled(targetModulesSelectedEvent) {
log(FUSGroupIds.TargetModulesType.from(targetModules), targetModules.isMixedBuildSystems)
}
fun logPackageSelected(isInstalled: Boolean) = runSafelyIfEnabled(packageSelectedEvent) {
log(isInstalled)
}
fun logDetailsLinkClick(type: FUSGroupIds.DetailsLinkTypes) = runSafelyIfEnabled(detailsLinkClickEvent) {
log(type)
}
fun logToggle(type: FUSGroupIds.ToggleTypes, state: Boolean) = runSafelyIfEnabled(toggleDetailsEvent) {
log(type, state)
}
fun logSearchRequest(query: String) = runSafelyIfEnabled(searchRequestEvent) {
log(query.length)
}
fun logSearchQueryClear() = runSafelyIfEnabled(searchQueryClearEvent) {
log()
}
fun logUpgradeAll() = runSafelyIfEnabled(upgradeAllEvent) {
log()
}
private fun <T : BaseEventId> runSafelyIfEnabled(event: T, action: T.() -> Unit) {
if (FUS_ENABLED) {
try {
event.action()
} catch (e: RuntimeException) {
thisLogger().error(
PackageSearchBundle.message("packagesearch.logging.error", event.eventId),
RuntimeExceptionWithAttachments(
"Non-critical error while logging analytics event. This doesn't impact plugin functionality.",
e
)
)
}
}
}
}
}
| apache-2.0 | ec41f30fc282b79e0538d1b5feaf8dfa | 51.485356 | 140 | 0.701371 | 5.696639 | false | false | false | false |
smmribeiro/intellij-community | plugins/gradle/testSources/org/jetbrains/plugins/gradle/execution/ContainsTestUtils.kt | 13 | 1745 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.execution
data class Inverted<T>(val value: T)
operator fun <T> T.not() = Inverted(this)
/**
* assertCollection([1, 3, 5], 1, !2, 3, !4, 5) -> success
* assertCollection([1, 3, 5], 1, !2, 3) -> success
* assertCollection([1, 3, 5], 1, 2, 3, 4, 5) -> fail
* assertCollection([1, 3, 5], 1, !2, 3, 4) -> fail
* assertCollection([1, 3, 5], [1, 3], ![2, 4]) -> success
*
* @param elements must be a T, Iterable<T>, Inverted<T> or Inverted<Iterable<T>>
*/
inline fun <reified T> assertCollection(actual: Collection<T>, vararg elements: Any?) {
val (positive, negative) = partition(elements.toList())
positive.forEach { require(it is T) }
negative.forEach { require(it is T) }
val expected = positive.toMutableList()
val unexpected = actual.toMutableList()
unexpected.retainAll(negative)
expected.removeAll(actual)
if (expected.isEmpty() && unexpected.isEmpty()) return
val messageActualPart = "\nactual: $actual"
val messageExpectedPart = if (expected.isEmpty()) "" else "\nexpected but not found: $expected"
val messageUnexpectedPart = if (unexpected.isEmpty()) "" else "\nunexpected but found: $unexpected"
throw AssertionError(messageExpectedPart + messageUnexpectedPart + messageActualPart)
}
fun partition(element: Any?): Pair<List<Any?>, List<Any?>> =
when (element) {
is Inverted<*> -> partition(element.value).let { it.second to it.first }
is Iterable<*> -> element.map { partition(it) }
.let { it.flatMap { p -> p.first } to it.flatMap { p -> p.second } }
else -> listOf(element) to listOf()
} | apache-2.0 | 8a57ce3aaf0b360c4bcd8c2dee75f649 | 44.947368 | 140 | 0.673926 | 3.435039 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/core/entity/EntityReference.kt | 6 | 625 | // 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.tools.projectWizard.core.entity
import org.jetbrains.kotlin.tools.projectWizard.core.entity.settings.SettingReference
import org.jetbrains.kotlin.tools.projectWizard.core.safeAs
abstract class EntityReference {
abstract val path: String
final override fun toString() = path
final override fun equals(other: Any?) = other.safeAs<SettingReference<*, *>>()?.path == path
final override fun hashCode() = path.hashCode()
} | apache-2.0 | 0850c2c86e4e7b352c88c6dcac69a2b1 | 43.714286 | 158 | 0.7712 | 4.310345 | false | false | false | false |
smmribeiro/intellij-community | java/idea-ui/src/com/intellij/ide/projectView/actions/ExtractModuleFromPackageAction.kt | 2 | 8149 | // 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.projectView.actions
import com.intellij.CommonBundle
import com.intellij.analysis.AnalysisScope
import com.intellij.ide.JavaUiBundle
import com.intellij.ide.SaveAndSyncHandler
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.actionSystem.CommonDataKeys
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.runReadAction
import com.intellij.openapi.application.runWriteAction
import com.intellij.openapi.diagnostic.ControlFlowException
import com.intellij.openapi.diagnostic.logger
import com.intellij.openapi.module.Module
import com.intellij.openapi.module.ModuleManager
import com.intellij.openapi.module.ModuleTypeId
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.Task
import com.intellij.openapi.roots.*
import com.intellij.openapi.roots.libraries.Library
import com.intellij.openapi.ui.Messages
import com.intellij.openapi.util.NlsSafe
import com.intellij.openapi.vfs.VfsUtil
import com.intellij.packageDependencies.ForwardDependenciesBuilder
import com.intellij.psi.JavaDirectoryService
import com.intellij.psi.PsiDirectory
import com.intellij.psi.PsiManager
import com.intellij.refactoring.move.moveClassesOrPackages.MoveClassesOrPackagesUtil
import org.jetbrains.annotations.TestOnly
import org.jetbrains.concurrency.AsyncPromise
import org.jetbrains.concurrency.Promise
import java.nio.file.Path
class ExtractModuleFromPackageAction : AnAction() {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val virtualFile = e.getData(CommonDataKeys.VIRTUAL_FILE) ?: return
val module = ProjectFileIndex.getInstance(project).getModuleForFile(virtualFile) ?: return
val directory = PsiManager.getInstance(module.project).findDirectory(virtualFile) ?: return
val suggestedModuleName = "${module.name}.${directory.name}"
val parentContentRoot = ModuleRootManager.getInstance(module).contentRoots.first()
val dialog = ExtractModuleFromPackageDialog(project, suggestedModuleName, Path.of(parentContentRoot.path, directory.name, "src").toString())
if (!dialog.showAndGet()) return
analyzeDependenciesAndCreateModule(directory, module, dialog.moduleName, dialog.targetSourceRootPath)
}
override fun update(e: AnActionEvent) {
val project = e.project
val file = e.getData(CommonDataKeys.VIRTUAL_FILE)
e.presentation.isEnabledAndVisible = project != null && file != null && file.isDirectory
&& ProjectFileIndex.getInstance(project).isInSourceContent(file)
}
companion object {
private val LOG = logger<ExtractModuleFromPackageAction>()
private fun analyzeDependenciesAndCreateModule(directory: PsiDirectory,
module: Module,
moduleName: @NlsSafe String,
targetSourceRootPath: String?): Promise<Unit> {
val promise = AsyncPromise<Unit>()
val dependenciesBuilder = ForwardDependenciesBuilder(module.project, AnalysisScope(directory))
object : Task.Backgroundable(module.project,
JavaUiBundle.message("progress.title.extract.module.analyzing.dependencies", directory.name)) {
override fun run(indicator: ProgressIndicator) {
indicator.isIndeterminate = false
dependenciesBuilder.analyze()
val usedModules = LinkedHashSet<Module>()
val usedLibraries = LinkedHashSet<Library>()
runReadAction {
val fileIndex = ProjectFileIndex.getInstance(module.project)
dependenciesBuilder.directDependencies.values.asSequence().flatten().forEach { file ->
val virtualFile = file.virtualFile ?: return@forEach
val depModule = fileIndex.getModuleForFile(virtualFile)
if (depModule != null) {
usedModules.add(depModule)
return@forEach
}
val library = fileIndex.getOrderEntriesForFile(virtualFile).asSequence()
.filterIsInstance<LibraryOrderEntry>()
.filter { !it.isModuleLevel }
.mapNotNull { it.library }
.firstOrNull()
if (library != null) {
usedLibraries.add(library)
}
}
}
ApplicationManager.getApplication().invokeLater {
try {
runWriteAction {
extractModule(directory, module, moduleName, usedModules, usedLibraries, targetSourceRootPath)
}
ModuleDependenciesCleaner(module, usedModules).startInBackground(promise)
}
catch (e: Throwable) {
if (e !is ControlFlowException) {
LOG.info(e)
Messages.showErrorDialog(project, JavaUiBundle.message("dialog.message.failed.to.extract.module", e), CommonBundle.getErrorTitle())
}
promise.setError(e)
}
}
}
}.queue()
return promise
}
private fun extractModule(directory: PsiDirectory, module: Module, moduleName: @NlsSafe String,
usedModules: Set<Module>, usedLibraries: Set<Library>, targetSourceRootPath: String?) {
val packagePrefix = JavaDirectoryService.getInstance().getPackage(directory)?.qualifiedName ?: ""
val targetSourceRoot = targetSourceRootPath?.let { VfsUtil.createDirectories(it) }
val (contentRoot, imlFileDirectory) = if (targetSourceRoot != null) {
val parent = targetSourceRoot.parent
if (parent in ModuleRootManager.getInstance(module).contentRoots) targetSourceRoot to module.moduleNioFile.parent
else parent to parent.toNioPath()
}
else {
directory.virtualFile to module.moduleNioFile.parent
}
val newModule = ModuleManager.getInstance(module.project).newModule(imlFileDirectory.resolve("$moduleName.iml"),
ModuleTypeId.JAVA_MODULE)
ModuleRootModificationUtil.updateModel(newModule) { model ->
if (ModuleRootManager.getInstance(module).isSdkInherited) {
model.inheritSdk()
}
else {
model.sdk = ModuleRootManager.getInstance(module).sdk
}
val contentEntry = model.addContentEntry(contentRoot)
if (targetSourceRoot != null) {
contentEntry.addSourceFolder(targetSourceRoot, false)
}
else {
contentEntry.addSourceFolder(directory.virtualFile, false, packagePrefix)
}
val moduleDependencies = JavaProjectDependenciesAnalyzer.removeDuplicatingDependencies(usedModules)
moduleDependencies.forEach { model.addModuleOrderEntry(it) }
val exportedLibraries = HashSet<Library>()
for (moduleDependency in moduleDependencies) {
ModuleRootManager.getInstance(moduleDependency).orderEntries().exportedOnly().recursively().forEachLibrary {
exportedLibraries.add(it)
}
}
(usedLibraries - exportedLibraries).forEach { model.addLibraryEntry(it) }
}
if (targetSourceRoot != null) {
val targetDirectory = VfsUtil.createDirectoryIfMissing(targetSourceRoot, packagePrefix.replace('.', '/'))
MoveClassesOrPackagesUtil.moveDirectoryRecursively(directory, PsiManager.getInstance(module.project).findDirectory(targetDirectory.parent))
}
SaveAndSyncHandler.getInstance().scheduleProjectSave(module.project)
}
@TestOnly
fun extractModuleFromDirectory(directory: PsiDirectory, module: Module, moduleName: @NlsSafe String, targetSourceRoot: String?): Promise<Unit> {
return analyzeDependenciesAndCreateModule(directory, module, moduleName, targetSourceRoot)
}
}
}
| apache-2.0 | 5809229c11c776b7b4f2f518f38e65a4 | 48.387879 | 148 | 0.694564 | 5.400265 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/idea/tests/test/org/jetbrains/kotlin/psi/injection/StringInjectionHostTest.kt | 6 | 6477 | // 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.psi.injection
import com.intellij.openapi.util.TextRange
import org.jetbrains.kotlin.idea.test.KotlinLightCodeInsightFixtureTestCase
import org.jetbrains.kotlin.psi.KtPsiFactory
import org.jetbrains.kotlin.psi.KtStringTemplateExpression
import org.jetbrains.kotlin.utils.keysToMap
class StringInjectionHostTest : KotlinLightCodeInsightFixtureTestCase() {
fun testRegular() {
with(quoted("")) {
checkInjection("", mapOf(0 to 1))
assertOneLine()
}
with(quoted("a")) {
checkInjection("a", mapOf(0 to 1, 1 to 2))
assertOneLine()
}
with(quoted("ab")) {
checkInjection("ab", mapOf(0 to 1, 1 to 2, 2 to 3))
checkInjection("a", mapOf(0 to 1, 1 to 2), rangeInHost = TextRange(1, 2))
checkInjection("b", mapOf(0 to 2, 1 to 3), rangeInHost = TextRange(2, 3))
assertOneLine()
}
}
fun testInterpolation1(): Unit = checkAllRanges("a \$b c")
fun testInterpolation2(): Unit = checkAllRanges("a \${b} c")
fun testInterpolation3(): Unit = checkAllRanges("a\${b}c")
fun testInterpolation4(): Unit = checkAllRanges("a \${b.foo()} c")
fun testUnclosedSimpleLiteral() {
assertFalse(stringExpression("\"").isValidHost)
assertFalse(stringExpression("\"a").isValidHost)
}
fun testEscapeSequences() {
with(quoted("\\t")) {
checkInjection("\t", mapOf(0 to 1, 1 to 3))
assertNoInjection(TextRange(1, 2))
assertNoInjection(TextRange(2, 3))
assertOneLine()
}
with(quoted("a\\tb")) {
checkInjection("a\tb", mapOf(0 to 1, 1 to 2, 2 to 4, 3 to 5))
checkInjection("a", mapOf(0 to 1, 1 to 2), rangeInHost = TextRange(1, 2))
assertNoInjection(TextRange(1, 3))
checkInjection("a\t", mapOf(0 to 1, 1 to 2, 2 to 4), rangeInHost = TextRange(1, 4))
checkInjection("\t", mapOf(0 to 2, 1 to 4), rangeInHost = TextRange(2, 4))
checkInjection("\tb", mapOf(0 to 2, 1 to 4, 2 to 5), rangeInHost = TextRange(2, 5))
assertOneLine()
}
}
fun testTripleQuotes() {
with(tripleQuoted("")) {
checkInjection("", mapOf(0 to 3))
assertMultiLine()
}
with(tripleQuoted("a")) {
checkInjection("a", mapOf(0 to 3, 1 to 4))
assertMultiLine()
}
with(tripleQuoted("ab")) {
checkInjection("ab", mapOf(0 to 3, 1 to 4, 2 to 5))
checkInjection("a", mapOf(0 to 3, 1 to 4), rangeInHost = TextRange(3, 4))
checkInjection("b", mapOf(0 to 4, 1 to 5), rangeInHost = TextRange(4, 5))
assertMultiLine()
}
}
fun testEscapeSequenceInTripleQuotes() {
with(tripleQuoted("\\t")) {
checkInjection("\\t", mapOf(0 to 3, 1 to 4, 2 to 5))
checkInjection("\\", mapOf(0 to 3, 1 to 4), rangeInHost = TextRange(3, 4))
checkInjection("t", mapOf(0 to 4, 1 to 5), rangeInHost = TextRange(4, 5))
assertMultiLine()
}
}
fun testMultiLine() {
with(tripleQuoted("a\nb")) {
checkInjection("a\nb", mapOf(0 to 3, 1 to 4, 2 to 5, 3 to 6))
assertMultiLine()
}
}
fun testProvideOffsetsForDecodablePartOfUndecodableString() {
val undecodable = stringExpression(""""{\\d\}"""")
val escaper = undecodable.createLiteralTextEscaper()
val undecodableRange = undecodable.text.rangeOf("""\\d\""")
val decoded = StringBuilder()
assertFalse(escaper.decode(undecodableRange, decoded))
assertEquals("""\d""", decoded.toString())
val mapping = (0..undecodableRange.length).keysToMap { escaper.getOffsetInHost(it, undecodableRange) }
assertEquals(
mapOf(
0 to 2,
1 to 4,
2 to 5,
3 to -1,
4 to -1
),
mapping
)
}
private fun quoted(s: String): KtStringTemplateExpression {
return stringExpression("\"$s\"")
}
private fun tripleQuoted(s: String): KtStringTemplateExpression {
return stringExpression("\"\"\"$s\"\"\"")
}
private fun stringExpression(s: String): KtStringTemplateExpression {
return KtPsiFactory(project).createExpression(s) as KtStringTemplateExpression
}
private fun KtStringTemplateExpression.assertNoInjection(range: TextRange): KtStringTemplateExpression {
assertTrue(isValidHost)
assertFalse(createLiteralTextEscaper().decode(range, StringBuilder()))
return this
}
private fun KtStringTemplateExpression.assertOneLine() {
assertTrue(createLiteralTextEscaper().isOneLine)
}
private fun KtStringTemplateExpression.assertMultiLine() {
assertFalse(createLiteralTextEscaper().isOneLine)
}
private fun checkAllRanges(str: String) {
with(quoted(str)) {
checkInjection(str, (0..str.length).keysToMap { it + 1 })
assertOneLine()
}
}
private fun KtStringTemplateExpression.checkInjection(
decoded: String, targetToSourceOffsets: Map<Int, Int>, rangeInHost: TextRange? = null
) {
assertTrue(isValidHost)
for (prefix in listOf("", "prefix")) {
val escaper = createLiteralTextEscaper()
val chars = StringBuilder(prefix)
val range = rangeInHost ?: escaper.relevantTextRange
assertTrue(escaper.decode(range, chars))
assertEquals(decoded, chars.substring(prefix.length))
val extendedOffsets = HashMap(targetToSourceOffsets)
val beforeStart = targetToSourceOffsets.keys.minOrNull()!! - 1
if (beforeStart >= 0) {
extendedOffsets[beforeStart] = -1
}
extendedOffsets[targetToSourceOffsets.keys.maxOrNull()!! + 1] = -1
for ((target, source) in extendedOffsets) {
assertEquals("Wrong source offset for $target", source, escaper.getOffsetInHost(target, range))
}
}
}
}
private fun String.rangeOf(inner: String): TextRange = indexOf(inner).let { TextRange.from(it, inner.length) } | apache-2.0 | 10457adb1aac57824401eb61651e0f86 | 36.883041 | 158 | 0.600895 | 4.433265 | false | true | false | false |
80998062/Fank | presentation/src/main/java/com/sinyuk/fanfou/viewmodel/SearchViewModel.kt | 1 | 1294 | /*
*
* * Apache License
* *
* * Copyright [2017] Sinyuk
* *
* * Licensed under the Apache License, Version 2.0 (the "License");
* * you may not use this file except in compliance with the License.
* * You may obtain a copy of the License at
* *
* * http://www.apache.org/licenses/LICENSE-2.0
* *
* * Unless required by applicable law or agreed to in writing, software
* * distributed under the License is distributed on an "AS IS" BASIS,
* * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* * See the License for the specific language governing permissions and
* * limitations under the License.
*
*/
package com.sinyuk.fanfou.viewmodel
import android.arch.lifecycle.ViewModel
import com.sinyuk.fanfou.domain.repo.FanfouSearchManager
import javax.inject.Inject
/**
* Created by sinyuk on 2018/1/3.
*
*/
class SearchViewModel @Inject constructor(private val manager: FanfouSearchManager) : ViewModel() {
fun listing(query:String? = null,limit:Int? = null) = manager.savedSearches(limit = limit, query = query)
fun trends() = manager.trends()
fun save(query: String) = manager.createSearch(query)
fun delete(query: String) = manager.deleteSearch(query = query)
fun clear() = manager.clearSearches()
} | mit | 7219f956d287409e807f757c50117725 | 28.431818 | 109 | 0.703246 | 3.718391 | false | false | false | false |
AMARJITVS/NoteDirector | app/src/main/kotlin/com/amar/notesapp/models/Medium.kt | 1 | 1775 | package com.amar.NoteDirector.models
import com.simplemobiletools.commons.extensions.getMimeType
import com.simplemobiletools.commons.extensions.isGif
import com.simplemobiletools.commons.extensions.isPng
import com.simplemobiletools.commons.helpers.*
import java.io.File
import java.io.Serializable
data class Medium(var name: String, var path: String, val video: Boolean, val modified: Long, val taken: Long, val size: Long) : Serializable, Comparable<Medium> {
companion object {
private val serialVersionUID = -6553149366975455L
var sorting: Int = 0
}
fun isPng() = path.isPng()
fun isGif() = path.isGif()
fun isJpg() = path.endsWith(".jpg", true) || path.endsWith(".jpeg", true)
fun isImage() = !isGif() && !video
fun getMimeType() = File(path).getMimeType()
override fun compareTo(other: Medium): Int {
var result: Int
if (sorting and SORT_BY_NAME != 0) {
result = AlphanumComparator().compare(name.toLowerCase(), other.name.toLowerCase())
} else if (sorting and SORT_BY_SIZE != 0) {
result = if (size == other.size)
0
else if (size > other.size)
1
else
-1
} else if (sorting and SORT_BY_DATE_MODIFIED != 0) {
result = if (modified == other.modified)
0
else if (modified > other.modified)
1
else
-1
} else {
result = if (taken == other.taken)
0
else if (taken > other.taken)
1
else
-1
}
if (sorting and SORT_DESCENDING != 0) {
result *= -1
}
return result
}
}
| apache-2.0 | bad09a221c48155e7aa30deb0bf11f94 | 29.603448 | 163 | 0.562254 | 4.308252 | false | false | false | false |
MyCollab/mycollab | mycollab-esb/src/main/java/com/mycollab/module/ecm/esb/SaveContentCommand.kt | 3 | 2728 | /**
* Copyright © MyCollab
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.mycollab.module.ecm.esb
import com.google.common.eventbus.AllowConcurrentEvents
import com.google.common.eventbus.Subscribe
import com.mycollab.concurrent.DistributionLockUtil
import com.mycollab.core.utils.StringUtils
import com.mycollab.common.service.DriveInfoService
import com.mycollab.module.esb.GenericCommand
import com.mycollab.module.file.service.RawContentService
import org.slf4j.LoggerFactory
import org.springframework.stereotype.Component
import java.util.concurrent.TimeUnit
/**
* @author MyCollab Ltd
* @since 6.0.0
*/
@Component
class SaveContentCommand(private val driveInfoService: DriveInfoService,
private val rawContentService: RawContentService) : GenericCommand() {
companion object {
val LOG = LoggerFactory.getLogger(SaveContentCommand::class.java)
}
@AllowConcurrentEvents
@Subscribe
fun saveContent(event: SaveContentEvent) {
LOG.debug("Save content ${event.content} by ${event.createdUser}")
if (event.sAccountId == null) {
return
}
val lock = DistributionLockUtil.getLock("ecm-${event.sAccountId}")
var totalSize = event.content.size
if (StringUtils.isNotBlank(event.content.thumbnail)) {
totalSize += rawContentService.getSize(event.content.thumbnail!!)
}
try {
if (lock.tryLock(1, TimeUnit.HOURS)) {
val driveInfo = driveInfoService.getDriveInfo(event.sAccountId)
if (driveInfo.usedvolume == null) {
driveInfo.usedvolume = totalSize
} else {
driveInfo.usedvolume = totalSize + driveInfo.usedvolume
}
driveInfoService.saveOrUpdateDriveInfo(driveInfo)
}
} catch (e: Exception) {
LOG.error("Error while save content ${event.content}", e)
} finally {
DistributionLockUtil.removeLock("ecm-${event.sAccountId}")
lock.unlock()
}
}
} | agpl-3.0 | da224adde2bef624de6795a8ef4fa974 | 37.971429 | 95 | 0.683902 | 4.522388 | false | false | false | false |
intrigus/jtransc | jtransc-core/src/com/jtransc/ast/ast_annotation.kt | 1 | 5481 | package com.jtransc.ast
import com.jtransc.annotation.JTranscMethodBodyList
import com.jtransc.annotation.JTranscNativeName
import com.jtransc.gen.TargetName
import com.jtransc.log.log
import com.jtransc.org.objectweb.asm.Type
import java.lang.reflect.Proxy
import kotlin.reflect.KProperty1
data class AstAnnotation(
val type: AstType.REF,
val elements: Map<String, Any?>,
val runtimeVisible: Boolean
) {
private var typedObject: Any? = null
private fun getAllDescendantAnnotations(value: Any?): List<AstAnnotation> {
return when (value) {
is AstAnnotation -> getAllDescendantAnnotations(elements.values.toList())
is List<*> -> value.filterIsInstance<AstAnnotation>() + value.filterIsInstance<List<*>>().flatMap { getAllDescendantAnnotations(it) }
else -> listOf()
}
}
fun getAnnotationAnnotations(program: AstProgram): AstAnnotationList = program[type]?.annotationsList ?: AstAnnotationList(type, listOf())
fun getAllDescendantAnnotations(): List<AstAnnotation> {
val out = arrayListOf<AstAnnotation>()
out.add(this)
out.addAll(getAllDescendantAnnotations(this))
return out
}
inline fun <reified T : Any> toObject(): T? {
return this.toObject(T::class.java)
}
fun <T> toObject(clazz: Class<T>): T? {
return if (clazz.name == this.type.fqname) toAnyObject() as T else null
}
fun toAnyObject(): Any? {
if (typedObject == null) {
val classLoader = this.javaClass.classLoader
fun minicast(it: Any?, type: Class<*>): Any? {
return when (it) {
is List<*> -> {
val array = java.lang.reflect.Array.newInstance(type.componentType, it.size)
for (n in 0 until it.size) java.lang.reflect.Array.set(array, n, minicast(it[n], type.componentType))
array
}
is AstAnnotation -> {
it.toAnyObject()
}
else -> {
it
}
}
}
typedObject = Proxy.newProxyInstance(classLoader, arrayOf(classLoader.loadClass(this.type.fqname))) { proxy, method, args ->
val valueUncasted = this.elements[method.name] ?: method.defaultValue
val returnType = method.returnType
minicast(valueUncasted, returnType)
}
}
return typedObject!!
}
}
fun AstAnnotation.getRefTypesFqName(): List<FqName> {
val out = hashSetOf<FqName>()
out += this.type.getRefTypesFqName()
for (e in this.elements.values) {
when (e) {
is AstAnnotation -> {
out += e.getRefTypesFqName()
}
is Iterable<*> -> {
for (i in e) {
when (i) {
is AstAnnotation -> {
out += i.getRefTypesFqName()
}
}
}
}
is String, is Boolean, is Int, is Float, is Double, is Long, is Byte, is Short, is Char, is Void -> Unit
is Type -> {
out += FqName(e.className)
}
is AstFieldWithoutTypeRef -> {
out += e.containingClass
}
else -> {
log.info("AstAnnotation.getRefTypesFqName.Unhandled: $e")
//println("Unhandled: $e")
}
}
//println("" + e + " : " + e?.javaClass)
}
return out.toList()
}
class AstAnnotationList(val containerRef: AstRef, val list: List<AstAnnotation>) {
val byClassName by lazy { list.groupBy { it.type.fqname } }
val listRuntime by lazy { list.filter { it.runtimeVisible } }
}
inline fun <reified TItem : Any, reified TList : Any> AstAnnotationList?.getTypedList(field: KProperty1<TList, Array<TItem>>): List<TItem> {
if (this == null) return listOf()
val single = this.getTyped<TItem>()
val list = this.getTyped<TList>()
return listOf(single).filterNotNull() + (if (list != null) field.get(list).toList() else listOf())
}
inline fun <reified T : Any> AstAnnotationList?.getTyped(): T? = if (this != null) byClassName[T::class.java.name]?.firstOrNull()?.toObject<T>() else null
inline fun <reified T : Any> AstAnnotationList?.getAllTyped(): List<T> = if (this != null) byClassName[T::class.java.name]?.map { it.toObject<T>() }?.filterNotNull() ?: listOf() else listOf()
operator fun AstAnnotationList?.get(name: FqName): AstAnnotation? = if (this != null) byClassName[name.fqname]?.firstOrNull() else null
inline fun <reified T : Any> AstAnnotationList?.contains(): Boolean = if (this != null) T::class.java.name in byClassName else false
class NativeBody(val lines: List<String>, val cond: String = "") {
val value = lines.joinToString("\n")
}
fun AstAnnotationList.getBodiesForTarget(targetName: TargetName): List<NativeBody> {
val extra = when (targetName.name) {
"js" -> this.list.filter { it.type.name.simpleName == "JsMethodBody" }.map { NativeBody(listOf(it.elements["value"]?.toString() ?: "")) }
else -> listOf()
}
return this.getTypedList(JTranscMethodBodyList::value).filter { targetName.matches(it.target) }.map { NativeBody(it.value.toList(), it.cond) } + extra
}
fun AstAnnotationList.getCallSiteBodyForTarget(targetName: TargetName): String? {
return this.getTypedList(com.jtransc.annotation.JTranscCallSiteBodyList::value).filter { targetName.matches(it.target) }.map { it.value.joinToString("\n") }.firstOrNull()
}
fun AstAnnotationList.getHeadersForTarget(targetName: TargetName): List<String> {
return this.getTypedList(com.jtransc.annotation.JTranscAddHeaderList::value).filter { targetName.matches(it.target) }.flatMap { it.value.toList() }
}
fun AstAnnotationList.getNativeNameForTarget(targetName: TargetName): JTranscNativeName? {
return this.getTypedList(com.jtransc.annotation.JTranscNativeNameList::value).filter { targetName.matches(it.target) }.map { it }.firstOrNull()
}
//val AstAnnotationList.nonNativeCall get() = this.contains<JTranscNonNative>() | apache-2.0 | 0c877e8a9b64ff8a2eff099a4cc48beb | 35.546667 | 191 | 0.704798 | 3.497766 | false | false | false | false |
kerubistan/kerub | src/main/kotlin/com/github/kerubistan/kerub/planner/steps/storage/fs/create/CreateImageBasedOnTemplateFactory.kt | 2 | 3175 | package com.github.kerubistan.kerub.planner.steps.storage.fs.create
import com.github.kerubistan.kerub.model.Expectation
import com.github.kerubistan.kerub.model.FsStorageCapability
import com.github.kerubistan.kerub.model.dynamic.VirtualStorageFsAllocation
import com.github.kerubistan.kerub.model.expectations.CloneOfStorageExpectation
import com.github.kerubistan.kerub.model.expectations.StorageAvailabilityExpectation
import com.github.kerubistan.kerub.planner.OperationalState
import com.github.kerubistan.kerub.planner.issues.problems.Problem
import com.github.kerubistan.kerub.planner.steps.AbstractOperationalStepFactory
import com.github.kerubistan.kerub.utils.junix.qemu.QemuImg
import io.github.kerubistan.kroki.collections.concat
import io.github.kerubistan.kroki.size.MB
import java.math.BigInteger
import kotlin.reflect.KClass
object CreateImageBasedOnTemplateFactory : AbstractOperationalStepFactory<CreateImageBasedOnTemplate>() {
private val cloneExpectationName = CloneOfStorageExpectation::class.java.name
override fun produce(state: OperationalState): List<CreateImageBasedOnTemplate> {
return state.index.runningHosts.filter { QemuImg.available(it.stat.capabilities) }
.mapNotNull { hostData ->
hostData.stat.capabilities?.storageCapabilities
?.filterIsInstance<FsStorageCapability>()?.filter { capability ->
val storageTechnologies = state.controllerConfig.storageTechnologies
capability.mountPoint in storageTechnologies.fsPathEnabled
&& capability.fsType in storageTechnologies.fsTypeEnabled
// only if it has some tiny space
&& (hostData.dynamic?.storageStatusById?.get(capability.id)?.freeCapacity
?: BigInteger.ZERO) > 1.MB
}?.map { mount ->
state.index.virtualStorageNotAllocated
.mapNotNull { storageTobeAllocated ->
// a not yet allocated storage that have a clone expectation
// on a read-only virtual disk, that has an allocation on this host
// in the supported formats
storageTobeAllocated.index
.expectationsByClass[cloneExpectationName]?.let { expectations ->
val expectation = expectations.single() as CloneOfStorageExpectation
val templateDisk = state.vStorage[expectation.sourceStorageId]
templateDisk?.dynamic?.allocations?.filter {
it is VirtualStorageFsAllocation
&& it.hostId == hostData.id
&& it.type in formatsWithBaseImage
}?.map { templateAllocation ->
CreateImageBasedOnTemplate(
host = hostData.stat,
baseDisk = templateDisk.stat,
disk = storageTobeAllocated,
capability = mount,
format = templateAllocation.type,
baseAllocation = templateAllocation as VirtualStorageFsAllocation
)
}
}
}
}
}.concat().concat().concat()
}
override val problemHints: Set<KClass<out Problem>>
get() = setOf()
override val expectationHints: Set<KClass<out Expectation>>
get() = setOf(StorageAvailabilityExpectation::class)
} | apache-2.0 | da397e44d0fae644fa394a84a066583c | 46.402985 | 105 | 0.72126 | 4.710682 | false | false | false | false |
markusfisch/BinaryEye | app/src/main/kotlin/de/markusfisch/android/binaryeye/widget/CropImageView.kt | 1 | 847 | package de.markusfisch.android.binaryeye.widget
import android.content.Context
import android.graphics.Canvas
import android.graphics.Rect
import android.graphics.RectF
import android.util.AttributeSet
import kotlin.math.roundToInt
class CropImageView(context: Context, attr: AttributeSet) :
ConfinedScalingImageView(context, attr) {
var onScan: (() -> Unit)? = null
private val lastMappedRect = RectF()
private val onScanRunnable = Runnable { onScan?.invoke() }
fun getBoundsRect() = Rect(
bounds.left.roundToInt(),
bounds.top.roundToInt(),
bounds.right.roundToInt(),
bounds.bottom.roundToInt()
)
override fun onDraw(canvas: Canvas) {
super.onDraw(canvas)
val mr = mappedRect ?: return
if (mr != lastMappedRect) {
removeCallbacks(onScanRunnable)
postDelayed(onScanRunnable, 300)
lastMappedRect.set(mr)
}
}
}
| mit | 6e2197e83b99b6b318129079ae1ec30d | 24.666667 | 59 | 0.753247 | 3.650862 | false | false | false | false |
VoIPGRID/vialer-android | app/src/main/java/com/voipgrid/vialer/notifications/AbstractNotification.kt | 1 | 1656 | package com.voipgrid.vialer.notifications
import android.app.Notification
import android.app.NotificationChannel
import android.app.NotificationManager
import android.content.Context
import android.os.Build
import androidx.annotation.RequiresApi
import com.voipgrid.vialer.VialerApplication
abstract class AbstractNotification {
private val notificationManager : NotificationManager
get() = context.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
protected val context : Context
get() = VialerApplication.get()
protected abstract val notificationId : Int
/**
* Build and display this notification.
*
*/
fun display() {
notificationManager.notify(notificationId, build())
}
/**
* Build the notification.
*
*/
fun build(): Notification {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
provideChannelsToDelete().forEach {
notificationManager.deleteNotificationChannel(it)
}
notificationManager.createNotificationChannel(buildChannel(context))
}
return buildNotification(context)
}
/**
* Remove this notification.
*
*/
fun remove() {
notificationManager.cancel(notificationId)
}
protected abstract fun buildNotification(context: Context): Notification
@RequiresApi(value = 26)
protected abstract fun buildChannel(context: Context): NotificationChannel
/**
* Provide a list of channel ids that should be deleted.
*
*/
protected open fun provideChannelsToDelete() = listOf<String>()
} | gpl-3.0 | 7feacde2b0f36fd4a895a66e3e7a246c | 25.301587 | 93 | 0.687802 | 5.359223 | false | false | false | false |
Szewek/Minecraft-Flux | src/main/java/szewek/mcflux/special/SpecialEventReceiver.kt | 1 | 1347 | package szewek.mcflux.special
import it.unimi.dsi.fastutil.ints.IntArraySet
import net.minecraft.nbt.NBTBase
import net.minecraft.nbt.NBTTagIntArray
import net.minecraft.util.EnumFacing
import net.minecraftforge.common.capabilities.Capability
import net.minecraftforge.common.capabilities.CapabilityInject
import net.minecraftforge.common.capabilities.ICapabilityProvider
import net.minecraftforge.common.util.INBTSerializable
@Suppress("UNCHECKED_CAST")
class SpecialEventReceiver : ICapabilityProvider, INBTSerializable<NBTBase> {
private val received = IntArraySet()
override fun hasCapability(cap: Capability<*>, f: EnumFacing?): Boolean {
return cap === SELF_CAP
}
override fun <T> getCapability(cap: Capability<T>, f: EnumFacing?): T? {
return if (cap === SELF_CAP) this as T else null
}
override fun serializeNBT(): NBTBase {
SpecialEventHandler.serNBT.add()
return NBTTagIntArray(received.toIntArray())
}
override fun deserializeNBT(nbt: NBTBase) {
if (nbt is NBTTagIntArray) {
val ia = nbt.intArray
for (i in ia)
received.add(i)
}
}
fun addReceived(l: Int) {
received.add(l)
}
fun alreadyReceived(l: Int): Boolean {
return received.contains(l)
}
companion object {
@JvmField
@CapabilityInject(SpecialEventReceiver::class)
var SELF_CAP: Capability<SpecialEventReceiver>? = null
}
}
| mit | a56a34b634e108e4d7a6d0dc7360050d | 25.411765 | 77 | 0.762435 | 3.680328 | false | false | false | false |
outersky/httpproxy | src/main/java/proxy.kt | 1 | 19680 | package cn.hillwind.app.proxy
import java.io.*
import java.net.ServerSocket
import java.net.Socket
import java.util.Date
import java.util.Arrays
import java.util.zip.GZIPInputStream
private val DEFAULT_TIMEOUT = 20 * 1000
private val DEFAULT_DEBUG_LEVEL = 0
private val DEFAULT_PORT = 18888
private var debugLevel: Int = DEFAULT_DEBUG_LEVEL
private var debugOut: PrintStream = System.out
private fun log(msg:String, exception:Exception?=null){
if(debugLevel>0) {
debugOut.println("${msg}")
if(exception!=null) {
exception.printStackTrace(debugOut)
}
}
}
/* here's a main method, in case you want to run this by itself */
public fun main(args: Array<String>) {
Db.init()
var port = DEFAULT_PORT
var fwdProxyServer = ""
var fwdProxyPort = 0
var timeout = DEFAULT_TIMEOUT
if (args.size < 0) {
System.err.println("USAGE: java jProxy <port number> [<fwd proxy> <fwd port>]")
System.err.println(" <port number> the port this service listens on")
System.err.println(" <fwd proxy> optional proxy server to forward requests to")
System.err.println(" <fwd port> the port that the optional proxy server is on")
System.err.println("\nHINT: if you don't want to see all the debug information flying by,")
System.err.println("you can pipe the output to a file or to 'nul' using \">\". For example:")
System.err.println(" to send output to the file prox.txt: java jProxy 8080 > prox.txt")
System.err.println(" to make the output go away: java jProxy 8080 > nul")
return
}
if (args.size > 2) {
port = Integer.parseInt(args[0])
fwdProxyServer = args[1]
fwdProxyPort = Integer.parseInt(args[2])
}
System.err.println(" ** Starting jProxy on port " + port + ". Press CTRL-C to end. **\n")
val jp = jProxy(port, fwdProxyServer, fwdProxyPort, timeout)
jp.start()
}
public class jProxy(var port: Int, var proxyServer: String, var proxyPort: Int, var timeout: Int) : Thread() {
private var server: ServerSocket? = null
private var fwdServer: String = ""
private var fwdPort: Int = 0
/* return whether or not the socket is currently open */
public fun isRunning(): Boolean {
return server != null
}
/* closeSocket will close the open ServerSocket; use this
* to halt a running jProxy thread
*/
public fun closeSocket() {
try {
server?.close()
} catch (e: Exception) {
log("close socker error",e)
}
server = null
}
override fun run() {
try {
// create a server socket, and loop forever listening for
// client connections
server = ServerSocket(port)
log("Started jProxy on port " + port)
while (true) {
val client = server?.accept()!!
val t = ProxyThread(client, fwdServer, fwdPort,timeout)
t.start()
}
} catch (e: Exception) {
log("jProxy Thread error: " , e)
}
closeSocket()
}
}
/*
* The ProxyThread will take an HTTP request from the client
* socket and send it to either the server that the client is
* trying to contact, or another proxy server
*/
class ProxyThread(val socket: Socket, val fwdServer: String, val fwdPort: Int, val timeout:Int) : Thread() {
private val begin = System.currentTimeMillis()
override fun run() {
try {
// client streams (make sure you're using streams that use
// byte arrays, so things like GIF and JPEG files and file
// downloads will transfer properly)
val clientIn = BufferedInputStream(socket.getInputStream()!!)
val clientOut = BufferedOutputStream(socket.getOutputStream()!!)
// the socket to the remote server
var server:Socket? = null
// other variables
val host = StringBuffer("")
val request = getHTTPData(clientIn, host)
var response:ByteArray? = null
val requestLength = request.size
var responseLength = 0
var hostName = host.toString()
val pos = hostName.indexOf(":")
var hostPort = 80
// get the header info (the web browser won't disconnect after
// it's sent a request, so make sure the waitForDisconnect
// parameter is false)
// separate the host name from the host port, if necessary
// (like if it's "servername:8000")
if (pos > 0) {
hostPort = Integer.parseInt(hostName.substring(pos + 1).trim())
hostName = hostName.substring(0, pos).trim()
}
log("prepare connectting to remote host")
// either forward this request to another proxy server or
// send it straight to the Host
try {
if ((fwdServer.length() > 0) && (fwdPort > 0)) {
server = Socket(fwdServer, fwdPort)
} else {
server = Socket(hostName, hostPort)
}
} catch (e: Exception) {
// tell the client there was an error
val errMsg = "HTTP/1.0 500\nContent Type: text/plain\n\n" + "Error connecting to the server:\n" + e + "\n"
clientOut.write(errMsg.getBytes(), 0, errMsg.length())
}
if (server != null) {
server?.setSoTimeout(timeout)
val serverIn = BufferedInputStream(server?.getInputStream()!!)
val serverOut = BufferedOutputStream(server?.getOutputStream()!!)
// send the request out
serverOut.write(request, 0, requestLength)
log("request forwarded to remote host!")
serverOut.flush()
response = getHTTPData(serverIn)
responseLength = response?.size ?: 0
serverIn.close()
serverOut.close()
}
// send the response back to the client, if we haven't already
clientOut.write(response!!, 0, responseLength)
// if the user wants debug info, send them debug info; however,
// keep in mind that because we're using threads, the output won't
// necessarily be synchronous
log("\n\nRequest from " + socket.getInetAddress()?.getHostAddress() + " on Port " + socket.getLocalPort() + " to host " + hostName + ":" + hostPort + "\n (" + requestLength + " bytes sent, " + responseLength + " bytes returned, " + (System.currentTimeMillis() - begin) + " ms elapsed)")
HttpEntity.save(HttpEntity.parse(request,response) me { startTime = Date(begin) } )
// close all the client streams so we can listen again
clientOut.close()
clientIn.close()
socket.close()
} catch (e: Exception) {
log("Error in ProxyThread: ", e)
}
}
private fun getHTTPData(stream: InputStream): ByteArray {
// get the HTTP data from an InputStream, and return it as
// a byte array
// the waitForDisconnect parameter tells us what to do in case
// the HTTP header doesn't specify the Content-Length of the
// transmission
val foo = StringBuffer("")
return getHTTPData(stream, foo)
}
private fun getHTTPData(stream: InputStream, host: StringBuffer): ByteArray {
// get the HTTP data from an InputStream, and return it as
// a byte array, and also return the Host entry in the header,
// if it's specified -- note that we have to use a StringBuffer
// for the 'host' variable, because a String won't return any
// information when it's used as a parameter like that
val bs = ByteArrayOutputStream()
streamHTTPData(stream, bs, host)
return bs.toByteArray()
}
private fun streamHTTPData(stream: InputStream, out: OutputStream): Int {
val foo = StringBuffer("")
return streamHTTPData(stream, out, foo)
}
private fun streamHTTPData(stream: InputStream, out: OutputStream, host: StringBuffer): Int {
// get the HTTP data from an InputStream, and send it to
// the designated OutputStream
val header = StringBuffer("")
var data:String?
var responseCode = 0
var contentLength = 0
var byteCount = 0
var chunk = false
try {
// get the first line of the header, so we know the response code
data = readLine(stream)
if (data != null) {
header.append(data + "\r\n")
Regex("""^http\S*\s+(\S+)\s+.*""",data!!.toLowerCase()).When({it.success}){
responseCode = Integer.parseInt(it[1].trim())
}
}
// get the rest of the header info
while (true) {
data = readLine(stream)
// // the header ends at the first blank line
if(data==null || data!!.length() == 0) {
break
}
header.append(data + "\r\n")
val line = data!!.toLowerCase()
// check for the Host header
Regex("""^host:(.+)""",line).When({it.success}) {
host.setLength(0)
host.append(it[1].trim())
}
// check for the Content-Length header
Regex("""^content-length:(.+)""",line).When({it.success}){
contentLength = Integer.parseInt(it[1].trim())
}
// check for the Transfer-Encoding header
Regex("""^transfer-encoding:.*chunked.*""",line).When({it.success}){
chunk = true
}
}
// add a blank line to terminate the header info
header.append("\r\n")
// convert the header to a byte array, and write it to our stream
out.write(header.toString().getBytes(), 0, header.length())
// if the header indicated that this was not a 200 response,
// just return what we've got if there is no Content-Length,
// because we may not be getting anything else
if ((responseCode != 200) && (contentLength == 0)) {
out.flush()
return header.length()
}
// get the body, if any; we try to use the Content-Length header to
// determine how much data we're supposed to be getting, because
// sometimes the client/server won't disconnect after sending us
// information...
if (contentLength > 0) {
chunk = false
}
byteCount = if(chunk){
readChunk(stream,out)
}else{
read(stream,contentLength,out)
}
} catch (e: Exception) {
log("Error getting HTTP data: " , e)
}
//flush the OutputStream and return
try {
out.flush()
} catch (e: Exception) {
}
return header.length() + byteCount
}
private fun read(stream:InputStream, length:Int,out: OutputStream):Int{
val buf = ByteArray(4096)
var bytesIn = 0
var total = 0
while ( total < length && ( {bytesIn = stream.read(buf); bytesIn}() >= 0 ) ) {
out.write(buf, 0, bytesIn)
total += bytesIn
}
return total
}
val chunkEnd = "0\r\n\r\n".getBytes()
private fun readChunk(stream:InputStream, out: OutputStream):Int{
val buf = ByteArray(4096)
var total:Int=0
var bytesIn:Int
while ( true ) {
bytesIn = stream.read(buf);
if(bytesIn<0){
break;
}
total += bytesIn
out.write(buf, 0, bytesIn)
if(testChunkEnd(buf,bytesIn)){
break
}
}
return total
}
private fun testChunkEnd(buf : ByteArray, len:Int):Boolean{
var i = 4;
var ended = true;
if(len<5){
return false;
}
while(i>=0 && len >=5 ){
if(chunkEnd[i]!=buf[len-5+i]){
ended = false;
break;
}
i--
}
log("testChunkEnd:${ended}")
return ended
}
private fun readLine(stream: InputStream): String? {
// reads a line of text from an InputStream
val data = StringBuffer("")
var c: Int = 0
try {
// if we have nothing to read, just return null
stream.mark(1)
if (stream.read() == -1) {
return null
}else {
stream.reset()
}
while ( { c = stream.read(); c>0 && c != 10 && c != 13 }() ) {
data.append(c.toChar())
}
// deal with the case where the end-of-line terminator is \r\n
if (c == 13) {
stream.mark(1)
if (stream.read() != 10) {
stream.reset()
}
}
} catch (e: Exception) {
log("Error getting header: " , e)
}
// and return what we have
return data.toString()
}
}
public class HttpEntity {
var id:Long=0
var method:String=""
var host:String=""
var url:String=""
var contentType:String=""
var contentEncoding:String=""
var status:Int=0
var statusStr=""
var length:Long=0
var startTime:Date = EMPTY_DATE
var requestBody:ByteArray?=null
var content:ByteArray?=null
var transferEncoding:String=""
var requestHeader:String=""
var responseHeader:String=""
override fun toString(): String {
return """host:${host}
method:${method}
url:${url}
status:${status}
statusStr:${statusStr}
contentType:${contentType}
contentEncoding:${contentEncoding}
"""
}
fun realContent():ByteArray? {
if(content==null){ return null}
var cnt = content!!
if(contentEncoding.indexOf("gzip")>=0){
cnt = GZIPInputStream(cnt.inputStream).readBytes()
}
return cnt
}
fun dump(output:OutputStream){
realContent()?.inputStream?.copyTo(output)
}
class object {
private val EMPTY_DATE = Date(0)
var rdm = 1
fun save(he:HttpEntity){
Db.save(he)
}
fun parse(request:ByteArray, response:ByteArray?):HttpEntity {
val he = HttpEntity()
parseRequest(HttpHeadSlice(request),he)
if(response!=null) {
parseResponse(HttpHeadSlice(response), he)
if(he.transferEncoding.indexOf("chunked")>=0){
parseChunkContent(he)
}
}
return he
}
fun parseRequest(request: HttpHeadSlice, he:HttpEntity):HttpEntity{
val firstLine = request.nextLine() ?: ""
val sb = StringBuilder(firstLine + "\r\n")
firstRequestLine(firstLine.trim(), he)
for(line in request){
handleHeadItem(line,he)
sb.append(line).append("\r\n")
}
he.requestHeader = sb.toString()
he.requestBody = request.restBytes()
return he
}
fun parseResponse(response: HttpHeadSlice, he:HttpEntity):HttpEntity{
val firstLine = response.nextLine()?: ""
val sb = StringBuilder(firstLine + "\r\n")
firstResponseLine(firstLine.trim(), he)
for(line in response){
handleHeadItem(line,he)
sb.append(line).append("\r\n")
}
he.responseHeader = sb.toString()
he.content = response.restBytes()
return he
}
fun parseChunkContent(he:HttpEntity){
val bytes = HttpHeadSlice(he.content!!)
var result = ByteArray(0)
while(true) {
val len = Integer.parseInt(bytes.nextLine()!!, 16)
if(len==0){
break;
}
val b2 = bytes.next(len)
val old = result
result = ByteArray(result.size + len)
System.arraycopy(old,0,result,0,old.size)
System.arraycopy(b2,0,result,old.size,len)
bytes.skip(2)
}
he.content = result
he.length = he.content!!.size.toLong()
he.content!!.inputStream.copyTo(FileOutputStream("/tmp/proxy/${++rdm}.${he.contentType.replaceAll("/","_")}.${he.contentEncoding}"))
}
fun firstRequestLine(line:String, he:HttpEntity){
Regex("""(\S+)\s+(\S+)\s+(.*)""",line).When({it.success}) {
he.method = it[1]
he.url = it[2]
}
}
fun firstResponseLine(line:String, he:HttpEntity){
Regex("""HTTP\S*\s+(\d+)\s+(.*)""",line).When({it.success}) {
he.status = it[1].toInt()
if (it.size > 2) {
he.statusStr = it[2]
}
}
}
fun handleHeadItem(line:String, he:HttpEntity){
val arr = line.split(':')
arr[0] = arr[0].trim().toLowerCase()
arr[1] = arr[1].trim()
when(arr[0]){
"host" -> he.host = arr[1]
"content-type" -> he.contentType = arr[1]
"content-encoding" -> he.contentEncoding = arr[1]
"content-length" -> he.length = arr[1].toLong()
"transfer-encoding" -> he.transferEncoding = arr[1]
else -> ""
}
}
}
}
class HttpHeadSlice(val stream:ByteArray, val offset:Int=0, val length:Int=stream.size) : Iterator<String> {
private val total = stream.size
private var index = 0
override public fun next(): String {
return nextLine()!!
}
// HTTP head ends at a blank line.
override public fun hasNext(): Boolean {
val c = stream[offset + index].toInt()
return !( (c == 0) || (c == 10) || (c == 13) )
}
public fun nextLine():String?{
var i = index
var c:Int = 0
while ( i < length && offset + i < total ) {
c = stream[offset + i].toInt()
// check for an end-of-line character
if ((c == 0) || (c == 10) || (c == 13)) {
break
}
i++
}
var str = if(i>index) String(stream,index, i-index) else null
if(c==13 && offset + i + 1 < total && stream[offset + i + 1].toInt()==10){
i ++
}
index = i+1
return str
}
public fun next(size:Int):ByteArray{
val bytes = ByteArray(size)
System.arraycopy(stream,index,bytes,0,size)
index = index + size
return bytes
}
public fun skip(size:Int){
index = index + size
}
public fun rest():InputStream = ByteArrayInputStream(stream,index+2,stream.size - index - 2) // 2 -> skip the blank line
public fun restBytes():ByteArray {
val bytes = ByteArray(stream.size - index - 2) // 2 -> skip the blank line
System.arraycopy(stream,index + 2,bytes,0,bytes.size)
return bytes
}
}
| mit | 16fa979581e8a8a45951b6557c7cc2c0 | 31.909699 | 299 | 0.534197 | 4.414536 | false | false | false | false |
KotlinPorts/pooled-client | db-async-common/src/main/kotlin/com/github/mauricio/async/db/util/ChannelWrapper.kt | 2 | 3525 | /*
* Copyright 2013 Maurício Linhares
*
* Maurício Linhares 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 com.github.mauricio.async.db.util
import com.github.mauricio.async.db.exceptions.UnknownLengthException
import java.nio.charset.Charset
import io.netty.buffer.ByteBuf
import mu.KLogging
//TODO: kotlin implicitConversions?
//TODO: it was AnyVal, is it correct to make it data class?
data class ChannelWrapper(val buffer: ByteBuf) {
companion object : KLogging() {
val MySQL_NULL = 0xfb
fun bufferToWrapper(buffer: ByteBuf) = ChannelWrapper(buffer)
}
fun readFixedString(length: Int, charset: Charset): String {
val bytes = ByteArray(length)
buffer.readBytes(bytes)
return String(bytes, charset)
}
fun readCString(charset: Charset) = ByteBufferUtils.readCString(buffer, charset)
fun readUntilEOF(charset: Charset) = ByteBufferUtils.readUntilEOF(buffer, charset)
fun readLengthEncodedString(charset: Charset): String {
val length = readBinaryLength()
return readFixedString(length.toInt(), charset)
}
fun readBinaryLength(): Long {
val firstByte = buffer.readUnsignedByte().toInt()
if (firstByte <= 250) {
return firstByte.toLong()
} else {
return when (firstByte) {
MySQL_NULL -> -1L
252 -> buffer.readUnsignedShort().toLong()
253 -> readLongInt().toLong()
254 -> buffer.readLong()
else -> throw UnknownLengthException(firstByte)
}
}
}
fun readLongInt(): Int {
val first = buffer.readByte().toInt()
val second = buffer.readByte().toInt()
val third = buffer.readByte().toInt()
return (first and 0xff) or
((second and 0xff) shl 8) or
((third and 0xff) shl 16)
}
fun writeLength(length: Long) {
if (length < 251) {
buffer.writeByte(length.toInt())
} else if (length < 65536L) {
buffer.writeByte(252)
buffer.writeShort(length.toInt())
} else if (length < 16777216L) {
buffer.writeByte(253)
writeLongInt(length.toInt())
} else {
buffer.writeByte(254)
buffer.writeLong(length)
}
}
fun writeLongInt(i: Int) {
buffer.writeByte(i and 0xff)
buffer.writeByte(i shl 8)
buffer.writeByte(i shl 16)
}
fun writeLengthEncodedString(value: String, charset: Charset) {
val bytes = value.toByteArray(charset)
writeLength(bytes.size.toLong())
buffer.writeBytes(bytes)
}
fun writePacketLength(sequence: Int = 0) {
ByteBufferUtils.writePacketLength(buffer, sequence)
}
fun mysqlReadInt(): Int {
val first = buffer.readByte().toInt()
val last = buffer.readByte().toInt()
return (first and 0xff) or ((last and 0xff) shl 8)
}
}
| apache-2.0 | 3ba9f9c046f4001f102bb70c78a50184 | 30.176991 | 86 | 0.630712 | 4.306846 | false | false | false | false |
Stargamers/FastHub | app/src/main/java/com/fastaccess/ui/modules/reviews/AddReviewDialogFragment.kt | 6 | 4937 | package com.fastaccess.ui.modules.reviews
import android.content.Context
import android.graphics.Color
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.Toolbar
import android.view.View
import android.widget.TextView
import butterknife.BindView
import com.fastaccess.R
import com.fastaccess.data.dao.CommitLinesModel
import com.fastaccess.helper.BundleConstant
import com.fastaccess.helper.Bundler
import com.fastaccess.helper.InputHelper
import com.fastaccess.helper.ViewHelper
import com.fastaccess.ui.base.BaseDialogFragment
import com.fastaccess.ui.base.mvp.BaseMvp
import com.fastaccess.ui.base.mvp.presenter.BasePresenter
import com.fastaccess.ui.modules.editor.comment.CommentEditorFragment
import com.fastaccess.ui.modules.reviews.callback.ReviewCommentListener
import com.fastaccess.ui.widgets.SpannableBuilder
/**
* Created by Kosh on 24 Jun 2017, 12:32 PM
*/
class AddReviewDialogFragment : BaseDialogFragment<BaseMvp.FAView, BasePresenter<BaseMvp.FAView>>() {
@BindView(R.id.toolbar) lateinit var toolbar: Toolbar
@BindView(R.id.text) lateinit var textView: TextView
@BindView(R.id.lineNo) lateinit var lineNo: TextView
private val commentEditorFragment: CommentEditorFragment? by lazy {
childFragmentManager.findFragmentByTag("CommentEditorFragment") as CommentEditorFragment?
}
private val spacePattern = "\\s+".toRegex()
private var commentCallback: ReviewCommentListener? = null
override fun onAttach(context: Context?) {
super.onAttach(context)
commentCallback = if (parentFragment is ReviewCommentListener) {
parentFragment as ReviewCommentListener
} else {
context as ReviewCommentListener
}
}
override fun onDetach() {
commentCallback = null
super.onDetach()
}
override fun fragmentLayout(): Int = R.layout.review_comment_dialog_layout
override fun onFragmentCreated(view: View, savedInstanceState: Bundle?) {
if (savedInstanceState == null) {
val fragment = CommentEditorFragment()
fragment.arguments = Bundler.start().put(BundleConstant.YES_NO_EXTRA, true).end()
childFragmentManager.beginTransaction()
.replace(R.id.commentFragmentContainer, fragment, "CommentEditorFragment")
.commitNow()
}
val item = arguments!!.getParcelable<CommitLinesModel>(BundleConstant.ITEM)
lineNo.text = SpannableBuilder.builder()
.append(if (item.leftLineNo >= 0) String.format("%s.", item.leftLineNo) else "")
.append(if (item.rightLineNo >= 0) String.format("%s.", item.rightLineNo) else "")
lineNo.visibility = if (InputHelper.isEmpty(lineNo)) View.GONE else View.VISIBLE
val context = context ?: return
when (item.color) {
CommitLinesModel.ADDITION -> textView.setBackgroundColor(ViewHelper.getPatchAdditionColor(context))
CommitLinesModel.DELETION -> textView.setBackgroundColor(ViewHelper.getPatchDeletionColor(context))
CommitLinesModel.PATCH -> textView.setBackgroundColor(ViewHelper.getPatchRefColor(context))
else -> textView.setBackgroundColor(Color.TRANSPARENT)
}
if (item.noNewLine) {
textView.text = SpannableBuilder.builder().append(item.text.replace(spacePattern, " ")).append(" ")
.append(ContextCompat.getDrawable(context, R.drawable.ic_newline))
} else {
textView.text = item.text.replace(spacePattern, " ")
}
toolbar.setTitle(R.string.add_comment)
toolbar.setNavigationIcon(R.drawable.ic_clear)
toolbar.setNavigationOnClickListener { dismiss() }
toolbar.inflateMenu(R.menu.add_menu)
toolbar.setOnMenuItemClickListener {
if (commentEditorFragment?.getEditText()?.text.isNullOrEmpty()) {
commentEditorFragment?.getEditText()?.error = getString(R.string.required_field)
} else {
commentEditorFragment?.getEditText()?.error = null
commentCallback?.onCommentAdded(InputHelper.toString(commentEditorFragment?.getEditText()?.text),
item, arguments!!.getBundle(BundleConstant.EXTRA))
dismiss()
}
return@setOnMenuItemClickListener true
}
}
override fun providePresenter(): BasePresenter<BaseMvp.FAView> = BasePresenter()
companion object {
fun newInstance(commitLinesModel: CommitLinesModel, bundle: Bundle? = null): AddReviewDialogFragment {
val dialog = AddReviewDialogFragment()
dialog.arguments = Bundler.start()
.put(BundleConstant.ITEM, commitLinesModel)
.put(BundleConstant.EXTRA, bundle)
.end()
return dialog
}
}
} | gpl-3.0 | 3170dffa1c2dca693d0e54c6aee3f040 | 43.089286 | 113 | 0.690095 | 4.854474 | false | false | false | false |
joseph-roque/BowlingCompanion | app/src/main/java/ca/josephroque/bowlingcompanion/statistics/impl/average/Game5AverageStatistic.kt | 1 | 1013 | package ca.josephroque.bowlingcompanion.statistics.impl.average
import android.os.Parcel
import android.os.Parcelable
import ca.josephroque.bowlingcompanion.R
import ca.josephroque.bowlingcompanion.common.interfaces.parcelableCreator
/**
* Copyright (C) 2018 Joseph Roque
*
* Average score in the 5th game of a series.
*/
class Game5AverageStatistic(total: Int = 0, divisor: Int = 0) : PerGameAverageStatistic(total, divisor) {
// MARK: Overrides
override val gameNumber = 5
override val titleId = Id
override val id = Id.toLong()
// MARK: Parcelable
companion object {
/** Creator, required by [Parcelable]. */
@Suppress("unused")
@JvmField val CREATOR = parcelableCreator(::Game5AverageStatistic)
/** Unique ID for the statistic. */
const val Id = R.string.statistic_average_5
}
/**
* Construct this statistic from a [Parcel].
*/
private constructor(p: Parcel): this(total = p.readInt(), divisor = p.readInt())
}
| mit | 3922cc1a6d628042ca6e9ec74838948a | 27.138889 | 105 | 0.686081 | 4.274262 | false | false | false | false |
AlmasB/FXGL | fxgl-samples/src/main/kotlin/sandbox/subscene/PlaySubScene.kt | 1 | 831 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package sandbox.subscene
import com.almasb.fxgl.dsl.FXGL
import com.almasb.fxgl.scene.SubScene
import javafx.event.EventHandler
import javafx.scene.paint.Color
class PlaySubScene : SubScene() {
init {
var top = 30.0
val text = FXGL.getUIFactoryService().newText("Play Game Screen", Color.BLACK, 22.0)
text.translateX = LEFT
text.translateY = top
contentRoot.children.addAll(text)
top += VERTICAL_GAP
val exitButton = FXGL.getUIFactoryService().newButton("Main Menu")
exitButton.translateX = LEFT
exitButton.translateY = top
exitButton.onAction = EventHandler {
FXGL.getEventBus().fireEvent(NavigateEvent(MAIN_VIEW))
}
contentRoot.children.add(exitButton)
}
}
| mit | bf6fd17a17895f7204109a24e49d421c | 22.742857 | 86 | 0.736462 | 3.521186 | false | false | false | false |
RP-Kit/RPKit | bukkit/rpk-players-bukkit/src/main/kotlin/com/rpkit/players/bukkit/profile/RPKProfileServiceImpl.kt | 1 | 5805 | /*
* Copyright 2022 Ren Binden
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.rpkit.players.bukkit.profile
import com.rpkit.players.bukkit.RPKPlayersBukkit
import com.rpkit.players.bukkit.database.table.RPKProfileTable
import com.rpkit.players.bukkit.event.profile.RPKBukkitProfileCreateEvent
import com.rpkit.players.bukkit.event.profile.RPKBukkitProfileDeleteEvent
import com.rpkit.players.bukkit.event.profile.RPKBukkitProfileUpdateEvent
import java.util.concurrent.CompletableFuture
import java.util.concurrent.ConcurrentHashMap
class RPKProfileServiceImpl(override val plugin: RPKPlayersBukkit) : RPKProfileService {
private val profilesById = ConcurrentHashMap<Int, RPKProfile>()
private val profilesByTag = ConcurrentHashMap<String, RPKProfile>()
override fun getProfile(id: RPKProfileId): CompletableFuture<out RPKProfile?> {
return plugin.database.getTable(RPKProfileTable::class.java)[id]
}
override fun getProfile(name: RPKProfileName, discriminator: RPKProfileDiscriminator): CompletableFuture<RPKProfile?> {
return plugin.database.getTable(RPKProfileTable::class.java).get(name, discriminator)
}
override fun getPreloadedProfile(id: RPKProfileId): RPKProfile? {
return profilesById[id.value]
}
override fun getPreloadedProfile(name: RPKProfileName, discriminator: RPKProfileDiscriminator): RPKProfile? {
return profilesByTag[name + discriminator]
}
override fun loadProfile(id: RPKProfileId): CompletableFuture<out RPKProfile?> {
val preloadedProfile = getPreloadedProfile(id)
if (preloadedProfile != null) return CompletableFuture.completedFuture(preloadedProfile)
plugin.logger.info("Loading profile ${id.value}...")
val profileFuture = plugin.database.getTable(RPKProfileTable::class.java)[id]
profileFuture.thenAccept { profile ->
if (profile != null) {
profilesById[id.value] = profile
profilesByTag[profile.name + profile.discriminator] = profile
plugin.logger.info("Loaded profile ${profile.name + profile.discriminator} (${id.value})")
}
}
return profileFuture
}
override fun unloadProfile(profile: RPKProfile) {
val profileId = profile.id
if (profileId != null) {
profilesById.remove(profileId.value)
}
profilesByTag.remove(profile.name + profile.discriminator)
plugin.logger.info("Unloaded profile ${profile.name + profile.discriminator}" + if (profileId != null) " (${profileId.value})" else "")
}
override fun addProfile(profile: RPKProfile): CompletableFuture<Void> {
return CompletableFuture.runAsync {
val event = RPKBukkitProfileCreateEvent(profile, true)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return@runAsync
plugin.database.getTable(RPKProfileTable::class.java).insert(event.profile).join()
}
}
override fun updateProfile(profile: RPKProfile): CompletableFuture<Void> {
return CompletableFuture.runAsync {
val event = RPKBukkitProfileUpdateEvent(profile, true)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return@runAsync
plugin.database.getTable(RPKProfileTable::class.java).update(event.profile).join()
}
}
override fun removeProfile(profile: RPKProfile): CompletableFuture<Void> {
return CompletableFuture.runAsync {
val event = RPKBukkitProfileDeleteEvent(profile, true)
plugin.server.pluginManager.callEvent(event)
if (event.isCancelled) return@runAsync
plugin.database.getTable(RPKProfileTable::class.java).delete(event.profile).join()
}
}
override fun createProfile(name: RPKProfileName, discriminator: RPKProfileDiscriminator?, password: String?): CompletableFuture<RPKProfile> {
return CompletableFuture.supplyAsync {
val profile = RPKProfileImpl(name, discriminator ?: generateDiscriminatorFor(name).join(), password)
addProfile(profile).join()
return@supplyAsync profile
}
}
override fun createAndLoadProfile(name: RPKProfileName, discriminator: RPKProfileDiscriminator?, password: String?): CompletableFuture<RPKProfile> {
return CompletableFuture.supplyAsync {
val profile = createProfile(name, discriminator, password).join()
val profileId = profile.id
if (profileId != null) {
profilesById[profileId.value] = profile
}
profilesByTag[profile.name + profile.discriminator] = profile
plugin.logger.info("Created and loaded profile ${profile.name}#${profile.discriminator}" + if (profileId != null) " (${profileId})" else "")
return@supplyAsync profile
}
}
override fun createThinProfile(name: RPKProfileName): RPKThinProfile {
return RPKThinProfileImpl(name)
}
override fun generateDiscriminatorFor(name: RPKProfileName): CompletableFuture<RPKProfileDiscriminator> {
return plugin.database.getTable(RPKProfileTable::class.java).generateDiscriminatorFor(name)
}
} | apache-2.0 | eada11d1f14d7348305d4860ee05ddae | 44.007752 | 152 | 0.707149 | 5.008628 | false | false | false | false |
nickthecoder/tickle | tickle-core/src/main/kotlin/uk/co/nickthecoder/tickle/resources/SceneResource.kt | 1 | 6049 | /*
Tickle
Copyright (C) 2017 Nick Robinson
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package uk.co.nickthecoder.tickle.resources
import uk.co.nickthecoder.tickle.Costume
import uk.co.nickthecoder.tickle.NoDirector
import uk.co.nickthecoder.tickle.Scene
import uk.co.nickthecoder.tickle.graphics.Color
import uk.co.nickthecoder.tickle.util.Dependable
import uk.co.nickthecoder.tickle.util.JsonScene
import java.io.File
/**
* Used when loading and editing a Scene. Not used during actual game play.
*/
open class SceneResource {
var file: File? = null
var directorString: String = NoDirector::class.java.name
val directorAttributes = Resources.instance.createAttributes()
var layoutName: String = ""
set(v) {
if (field != v) {
field = v
updateLayout()
}
}
var background: Color = Color.black()
var showMouse: Boolean = true
/**
* Names of included scenes. When a scene is started (as part of a running game), the included scenes
* will be automatically merged together.
* Within the SceneEditor, the included scenes will be loaded as separate layers, which are displayed, but
* are not merged, and not editable.
*/
val includes = mutableListOf<File>()
/**
* Keyed on the name of the stage
*/
val stageResources = mutableMapOf<String, StageResource>()
/**
* Gets the Layout to create the scene, and then populates the Stages with Actors.
*/
fun createScene(): Scene {
val layout = Resources.instance.layouts.find(layoutName)!!
val scene = layout.createScene()
scene.background = background
scene.showMouse = showMouse
stageResources.forEach { name, stageResource ->
val stage = scene.stages[name]
if (stage == null) {
System.err.println("ERROR. Stage $name not found. Ignoring all actors on that stage")
} else {
stageResource.actorResources.forEach { actorResource ->
actorResource.createActor()?.let { actor ->
stage.add(actor)
}
}
}
}
return scene
}
/**
* Called when the layout has changed. Attempt to move all of the actors from like-names stages, but any
* unmatched stage names will result in actors being put in a "random" stage.
*/
private fun updateLayout() {
val oldStages = stageResources.toMap()
stageResources.clear()
val layout = Resources.instance.layouts.find(layoutName)!!
layout.layoutStages.keys.forEach { stageName ->
stageResources[stageName] = StageResource()
}
oldStages.forEach { stageName, oldStage ->
if (stageResources.containsKey(stageName)) {
stageResources[stageName]!!.actorResources.addAll(oldStage.actorResources)
} else {
if (oldStage.actorResources.isNotEmpty()) {
System.err.println("Warning. Layout ${layoutName} doesn't have a stage called '${stageName}'. Placing actors in another stage.")
stageResources.values.firstOrNull()?.actorResources?.addAll(oldStage.actorResources)
}
}
}
}
fun dependsOn(costume: Costume): Boolean {
for (sr in stageResources.values) {
if (sr.dependsOn(costume)) return true
}
return false
}
fun dependsOn(layout: Layout) = Resources.instance.findName(layout) == layoutName
}
/**
* Used in place of a SceneResource, without having to load it.
* Used within the editor, and is only in the core project, because classes such as Costume
* need this for their implementation of Deletable.
* The Deletable methods will only be called from the editor though.
*/
class SceneStub(val file: File) : Dependable {
val name: String
get() = Resources.instance.toPath(file).removeSuffix(".scene").removePrefix("scenes/")
override fun equals(other: Any?): Boolean {
if (other is SceneStub) {
return file == other.file
}
return false
}
override fun hashCode() = file.hashCode() + 1
fun load(): SceneResource = JsonScene(file).sceneResource
fun dependsOn(costume: Costume): Boolean {
try {
return load().dependsOn(costume)
} catch (e: Exception) {
println("WARNING. Couldn't load $file, when checking dependencies of $costume")
return false
}
}
fun dependsOn(layout: Layout): Boolean {
try {
return load().dependsOn(layout)
} catch (e: Exception) {
println("WARNING. Couldn't load $file, when checking dependencies of $layout")
return false
}
}
companion object {
fun allScenesStubs(): List<SceneStub> {
val result = mutableListOf<SceneStub>()
fun addFrom(dir: File) {
val files = dir.listFiles()
for (file in files) {
if (file.isDirectory) {
addFrom(file)
} else if (file.extension == "scene") {
result.add(SceneStub(file))
}
}
}
addFrom(Resources.instance.sceneDirectory)
return result
}
}
}
| gpl-3.0 | 28199acdee68a81b559d64175a36c66b | 30.670157 | 148 | 0.618119 | 4.671042 | false | false | false | false |
commons-app/apps-android-commons | app/src/main/java/fr/free/nrw/commons/upload/worker/UploadWorker.kt | 3 | 21086 | package fr.free.nrw.commons.upload.worker
import android.annotation.SuppressLint
import android.app.PendingIntent
import android.app.TaskStackBuilder
import android.content.Context
import android.content.Intent
import android.graphics.BitmapFactory
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.work.CoroutineWorker
import androidx.work.Data
import androidx.work.WorkerParameters
import com.mapbox.mapboxsdk.plugins.localization.BuildConfig
import dagger.android.ContributesAndroidInjector
import fr.free.nrw.commons.CommonsApplication
import fr.free.nrw.commons.Media
import fr.free.nrw.commons.R
import fr.free.nrw.commons.auth.SessionManager
import fr.free.nrw.commons.contributions.ChunkInfo
import fr.free.nrw.commons.contributions.Contribution
import fr.free.nrw.commons.contributions.ContributionDao
import fr.free.nrw.commons.contributions.MainActivity
import fr.free.nrw.commons.customselector.database.UploadedStatus
import fr.free.nrw.commons.customselector.database.UploadedStatusDao
import fr.free.nrw.commons.di.ApplicationlessInjection
import fr.free.nrw.commons.media.MediaClient
import fr.free.nrw.commons.theme.BaseActivity
import fr.free.nrw.commons.upload.StashUploadResult
import fr.free.nrw.commons.upload.FileUtilsWrapper
import fr.free.nrw.commons.upload.StashUploadState
import fr.free.nrw.commons.upload.UploadClient
import fr.free.nrw.commons.upload.UploadResult
import fr.free.nrw.commons.wikidata.WikidataEditService
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.MainScope
import kotlinx.coroutines.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import timber.log.Timber
import java.util.*
import java.util.regex.Pattern
import javax.inject.Inject
import kotlin.collections.ArrayList
class UploadWorker(var appContext: Context, workerParams: WorkerParameters) :
CoroutineWorker(appContext, workerParams) {
private var notificationManager: NotificationManagerCompat? = null
@Inject
lateinit var wikidataEditService: WikidataEditService
@Inject
lateinit var sessionManager: SessionManager
@Inject
lateinit var contributionDao: ContributionDao
@Inject
lateinit var uploadedStatusDao: UploadedStatusDao
@Inject
lateinit var uploadClient: UploadClient
@Inject
lateinit var mediaClient: MediaClient
@Inject
lateinit var fileUtilsWrapper: FileUtilsWrapper
private val PROCESSING_UPLOADS_NOTIFICATION_TAG = BuildConfig.APPLICATION_ID + " : upload_tag"
private val PROCESSING_UPLOADS_NOTIFICATION_ID = 101
//Attributes of the current-upload notification
private var currentNotificationID: Int = -1// lateinit is not allowed with primitives
private lateinit var currentNotificationTag: String
private var curentNotification: NotificationCompat.Builder
private val statesToProcess= ArrayList<Int>()
private val STASH_ERROR_CODES = Arrays
.asList(
"uploadstash-file-not-found",
"stashfailed",
"verification-error",
"chunk-too-small"
)
init {
ApplicationlessInjection
.getInstance(appContext)
.commonsApplicationComponent
.inject(this)
curentNotification =
getNotificationBuilder(CommonsApplication.NOTIFICATION_CHANNEL_ID_ALL)!!
statesToProcess.add(Contribution.STATE_QUEUED)
statesToProcess.add(Contribution.STATE_QUEUED_LIMITED_CONNECTION_MODE)
}
@dagger.Module
interface Module {
@ContributesAndroidInjector
fun worker(): UploadWorker
}
open inner class NotificationUpdateProgressListener(
private var notificationFinishingTitle: String?,
var contribution: Contribution?
) {
fun onProgress(transferred: Long, total: Long) {
if (transferred == total) {
// Completed!
curentNotification.setContentTitle(notificationFinishingTitle)
.setProgress(0, 100, true)
} else {
curentNotification
.setProgress(
100,
(transferred.toDouble() / total.toDouble() * 100).toInt(),
false
)
}
notificationManager?.cancel(PROCESSING_UPLOADS_NOTIFICATION_TAG, PROCESSING_UPLOADS_NOTIFICATION_ID)
notificationManager?.notify(
currentNotificationTag,
currentNotificationID,
curentNotification.build()!!
)
contribution!!.transferred = transferred
contributionDao.update(contribution).blockingAwait()
}
open fun onChunkUploaded(contribution: Contribution, chunkInfo: ChunkInfo?) {
contribution.chunkInfo = chunkInfo
contributionDao.update(contribution).blockingAwait()
}
}
private fun getNotificationBuilder(channelId: String): NotificationCompat.Builder? {
return NotificationCompat.Builder(appContext, channelId)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_launcher)
.setLargeIcon(
BitmapFactory.decodeResource(
appContext.resources,
R.drawable.ic_launcher
)
)
.setAutoCancel(true)
.setOnlyAlertOnce(true)
.setProgress(100, 0, true)
.setOngoing(true)
}
override suspend fun doWork(): Result {
var countUpload = 0
notificationManager = NotificationManagerCompat.from(appContext)
val processingUploads = getNotificationBuilder(
CommonsApplication.NOTIFICATION_CHANNEL_ID_ALL
)!!
withContext(Dispatchers.IO) {
val queuedContributions = contributionDao.getContribution(statesToProcess)
.blockingGet()
//Showing initial notification for the number of uploads being processed
Timber.e("Queued Contributions: "+ queuedContributions.size)
processingUploads.setContentTitle(appContext.getString(R.string.starting_uploads))
processingUploads.setContentText(
appContext.resources.getQuantityString(
R.plurals.starting_multiple_uploads,
queuedContributions.size,
queuedContributions.size
)
)
notificationManager?.notify(
PROCESSING_UPLOADS_NOTIFICATION_TAG,
PROCESSING_UPLOADS_NOTIFICATION_ID,
processingUploads.build()
)
/**
* To avoid race condition when multiple of these workers are working, assign this state
so that the next one does not process these contribution again
*/
queuedContributions.forEach {
it.state=Contribution.STATE_IN_PROGRESS
contributionDao.saveSynchronous(it)
}
queuedContributions.asFlow().map { contribution ->
/**
* If the limited connection mode is on, lets iterate through the queued
* contributions
* and set the state as STATE_QUEUED_LIMITED_CONNECTION_MODE ,
* otherwise proceed with the upload
*/
if (isLimitedConnectionModeEnabled()) {
if (contribution.state == Contribution.STATE_QUEUED) {
contribution.state = Contribution.STATE_QUEUED_LIMITED_CONNECTION_MODE
contributionDao.saveSynchronous(contribution)
}
} else {
contribution.transferred = 0
contribution.state = Contribution.STATE_IN_PROGRESS
contributionDao.saveSynchronous(contribution)
setProgressAsync(Data.Builder().putInt("progress", countUpload).build())
countUpload++
uploadContribution(contribution = contribution)
}
}.collect()
//Dismiss the global notification
notificationManager?.cancel(
PROCESSING_UPLOADS_NOTIFICATION_TAG,
PROCESSING_UPLOADS_NOTIFICATION_ID
)
}
//TODO make this smart, think of handling retries in the future
return Result.success()
}
/**
* Returns true is the limited connection mode is enabled
*/
private fun isLimitedConnectionModeEnabled(): Boolean {
return sessionManager.getPreference(CommonsApplication.IS_LIMITED_CONNECTION_MODE_ENABLED)
}
/**
* Upload the contribution
* @param contribution
*/
@SuppressLint("StringFormatInvalid")
private suspend fun uploadContribution(contribution: Contribution) {
if (contribution.localUri == null || contribution.localUri.path == null) {
Timber.e("""upload: ${contribution.media.filename} failed, file path is null""")
}
val media = contribution.media
val displayTitle = contribution.media.displayTitle
currentNotificationTag = contribution.localUri.toString()
currentNotificationID =
(contribution.localUri.toString() + contribution.media.filename).hashCode()
curentNotification
getNotificationBuilder(CommonsApplication.NOTIFICATION_CHANNEL_ID_ALL)!!
curentNotification.setContentTitle(
appContext.getString(
R.string.upload_progress_notification_title_start,
displayTitle
)
)
notificationManager?.notify(
currentNotificationTag,
currentNotificationID,
curentNotification.build()!!
)
val filename = media.filename
val notificationProgressUpdater = NotificationUpdateProgressListener(
appContext.getString(
R.string.upload_progress_notification_title_finishing,
displayTitle
),
contribution
)
try {
//Upload the file to stash
val stashUploadResult = uploadClient.uploadFileToStash(
appContext, filename, contribution, notificationProgressUpdater
).onErrorReturn{
return@onErrorReturn StashUploadResult(StashUploadState.FAILED,fileKey = null)
}.blockingSingle()
when (stashUploadResult.state) {
StashUploadState.SUCCESS -> {
//If the stash upload succeeds
Timber.d("Upload to stash success for fileName: $filename")
Timber.d("Ensure uniqueness of filename");
val uniqueFileName = findUniqueFileName(filename!!)
try {
//Upload the file from stash
val uploadResult = uploadClient.uploadFileFromStash(
contribution, uniqueFileName, stashUploadResult.fileKey
).onErrorReturn {
return@onErrorReturn null
}.blockingSingle()
if (null != uploadResult && uploadResult.isSuccessful()) {
Timber.d(
"Stash Upload success..proceeding to make wikidata edit"
)
wikidataEditService.addDepictionsAndCaptions(uploadResult, contribution)
.blockingSubscribe();
if(contribution.wikidataPlace==null){
Timber.d(
"WikiDataEdit not required, upload success"
)
saveCompletedContribution(contribution,uploadResult)
}else{
Timber.d(
"WikiDataEdit not required, making wikidata edit"
)
makeWikiDataEdit(uploadResult, contribution)
}
showSuccessNotification(contribution)
} else {
Timber.e("Stash Upload failed")
showFailedNotification(contribution)
contribution.state = Contribution.STATE_FAILED
contribution.chunkInfo = null
contributionDao.save(contribution).blockingAwait()
}
}catch (exception : Exception){
Timber.e(exception)
Timber.e("Upload from stash failed for contribution : $filename")
showFailedNotification(contribution)
contribution.state=Contribution.STATE_FAILED
contributionDao.saveSynchronous(contribution)
if (STASH_ERROR_CODES.contains(exception.message)) {
clearChunks(contribution)
}
}
}
StashUploadState.PAUSED -> {
showPausedNotification(contribution)
contribution.state = Contribution.STATE_PAUSED
contributionDao.saveSynchronous(contribution)
}
else -> {
Timber.e("""upload file to stash failed with status: ${stashUploadResult.state}""")
showFailedNotification(contribution)
contribution.state = Contribution.STATE_FAILED
contribution.chunkInfo = null
contributionDao.saveSynchronous(contribution)
}
}
}catch (exception: Exception){
Timber.e(exception)
Timber.e("Stash upload failed for contribution: $filename")
showFailedNotification(contribution)
contribution.state=Contribution.STATE_FAILED
clearChunks(contribution)
}
}
private fun clearChunks(contribution: Contribution) {
contribution.chunkInfo=null
contributionDao.saveSynchronous(contribution)
}
/**
* Make the WikiData Edit, if applicable
*/
private suspend fun makeWikiDataEdit(uploadResult: UploadResult, contribution: Contribution) {
val wikiDataPlace = contribution.wikidataPlace
if (wikiDataPlace != null && wikiDataPlace.imageValue == null) {
if (!contribution.hasInvalidLocation()) {
var revisionID: Long?=null
try {
revisionID = wikidataEditService.createClaim(
wikiDataPlace, uploadResult.filename,
contribution.media.captions
)
if (null != revisionID) {
showSuccessNotification(contribution)
}
}catch (exception: Exception){
Timber.e(exception)
}
withContext(Dispatchers.Main) {
wikidataEditService.handleImageClaimResult(
contribution.wikidataPlace,
revisionID
)
}
} else {
withContext(Dispatchers.Main) {
wikidataEditService.handleImageClaimResult(
contribution.wikidataPlace, null
)
}
}
}
saveCompletedContribution(contribution, uploadResult)
}
private fun saveCompletedContribution(contribution: Contribution, uploadResult: UploadResult) {
val contributionFromUpload = mediaClient.getMedia("File:" + uploadResult.filename)
.map { media: Media? -> contribution.completeWith(media!!) }
.blockingGet()
contributionFromUpload.dateModified=Date()
contributionDao.deleteAndSaveContribution(contribution, contributionFromUpload)
// Upload success, save to uploaded status.
saveIntoUploadedStatus(contribution)
}
/**
* Save to uploadedStatusDao.
*/
private fun saveIntoUploadedStatus(contribution: Contribution) {
contribution.contentUri?.let {
val imageSha1 = contribution.imageSHA1.toString()
val modifiedSha1 = fileUtilsWrapper.getSHA1(fileUtilsWrapper.getFileInputStream(contribution.localUri?.path))
MainScope().launch {
uploadedStatusDao.insertUploaded(
UploadedStatus(
imageSha1,
modifiedSha1,
imageSha1 == modifiedSha1,
true
)
);
}
}
}
private fun findUniqueFileName(fileName: String): String {
var sequenceFileName: String?
var sequenceNumber = 1
while (true) {
sequenceFileName = if (sequenceNumber == 1) {
fileName
} else {
if (fileName.indexOf('.') == -1) {
"$fileName $sequenceNumber"
} else {
val regex =
Pattern.compile("^(.*)(\\..+?)$")
val regexMatcher = regex.matcher(fileName)
regexMatcher.replaceAll("$1 $sequenceNumber$2")
}
}
if (!mediaClient.checkPageExistsUsingTitle(
String.format(
"File:%s",
sequenceFileName
)
)
.blockingGet()
) {
break
}
sequenceNumber++
}
return sequenceFileName!!
}
/**
* Notify that the current upload has succeeded
* @param contribution
*/
@SuppressLint("StringFormatInvalid")
private fun showSuccessNotification(contribution: Contribution) {
val displayTitle = contribution.media.displayTitle
contribution.state=Contribution.STATE_COMPLETED
curentNotification.setContentTitle(
appContext.getString(
R.string.upload_completed_notification_title,
displayTitle
)
)
.setContentText(appContext.getString(R.string.upload_completed_notification_text))
.setProgress(0, 0, false)
.setOngoing(false)
notificationManager?.notify(
currentNotificationTag, currentNotificationID,
curentNotification.build()
)
}
/**
* Notify that the current upload has failed
* @param contribution
*/
@SuppressLint("StringFormatInvalid")
private fun showFailedNotification(contribution: Contribution) {
val displayTitle = contribution.media.displayTitle
curentNotification.setContentIntent(getPendingIntent(MainActivity::class.java))
curentNotification.setContentTitle(
appContext.getString(
R.string.upload_failed_notification_title,
displayTitle
)
)
.setContentText(appContext.getString(R.string.upload_failed_notification_subtitle))
.setProgress(0, 0, false)
.setOngoing(false)
notificationManager?.notify(
currentNotificationTag, currentNotificationID,
curentNotification.build()
)
}
/**
* Notify that the current upload is paused
* @param contribution
*/
private fun showPausedNotification(contribution: Contribution) {
val displayTitle = contribution.media.displayTitle
curentNotification.setContentTitle(
appContext.getString(
R.string.upload_paused_notification_title,
displayTitle
)
)
.setContentText(appContext.getString(R.string.upload_paused_notification_subtitle))
.setProgress(0, 0, false)
.setOngoing(false)
notificationManager!!.notify(
currentNotificationTag, currentNotificationID,
curentNotification.build()
)
}
/**
* Method used to get Pending intent for opening different screen after clicking on notification
* @param toClass
*/
private fun getPendingIntent(toClass:Class<out BaseActivity>):PendingIntent
{
val intent = Intent(appContext,toClass)
return TaskStackBuilder.create(appContext).run {
addNextIntentWithParentStack(intent)
getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
};
}
} | apache-2.0 | f0da8572f262919f9ddb98fbee6ee4b8 | 37.550274 | 121 | 0.596272 | 5.840997 | false | false | false | false |
ujpv/intellij-rust | src/main/kotlin/org/rust/ide/inspections/RustSelfConventionInspection.kt | 1 | 2636 | package org.rust.ide.inspections
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.psi.PsiElement
import org.rust.lang.core.psi.*
import org.rust.lang.core.psi.util.parentOfType
import org.rust.lang.core.types.RustStructOrEnumTypeBase
import org.rust.lang.core.types.util.resolvedType
class RustSelfConventionInspection : RustLocalInspectionTool() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean) =
object : RustElementVisitor() {
override fun visitImplMethodMember(m: RustImplMethodMemberElement) {
val convention = SELF_CONVENTIONS.find { m.identifier.text.startsWith(it.prefix) } ?: return
if (m.selfType in convention.selfTypes) return
if (m.selfType == SelfType.SELF && m.isOwnerCopyable()) return
holder.registerProblem(m.parameters?.selfArgument ?: m.identifier, convention)
}
}
private fun RustImplMethodMemberElement.isOwnerCopyable(): Boolean {
val implBlock = parentOfType<RustImplItemElement>() ?: return false
val owner = implBlock.type?.resolvedType as? RustStructOrEnumTypeBase ?: return false
return owner.item.queryAttributes.hasMetaItem("derive", "Copy")
}
private companion object {
val SELF_CONVENTIONS = listOf(
SelfConvention("as_", listOf(SelfType.REF_SELF, SelfType.REF_MUT_SELF)),
SelfConvention("from_", listOf(SelfType.NO_SELF)),
SelfConvention("into_", listOf(SelfType.SELF)),
SelfConvention("is_", listOf(SelfType.REF_SELF, SelfType.NO_SELF)),
SelfConvention("to_", listOf(SelfType.REF_SELF))
)
}
}
enum class SelfType(val description: String) {
NO_SELF("no self"),
SELF("self by value"),
REF_SELF("self by reference"),
REF_MUT_SELF("self by mutable reference");
}
private val RustImplMethodMemberElement.selfType: SelfType get() {
val self = parameters?.selfArgument
return when {
self == null -> SelfType.NO_SELF
self.and == null -> SelfType.SELF
self.mut == null -> SelfType.REF_SELF
else -> SelfType.REF_MUT_SELF
}
}
data class SelfConvention(val prefix: String, val selfTypes: Collection<SelfType>)
private fun ProblemsHolder.registerProblem(element: PsiElement, convention: SelfConvention) {
val selfTypes = convention.selfTypes.map { it.description }.joinToString(" or ")
val description = "methods called `${convention.prefix}*` usually take $selfTypes; " +
"consider choosing a less ambiguous name"
registerProblem(element, description)
}
| mit | 9cdad148da2f2c27e00917feaadce997 | 39.553846 | 108 | 0.69044 | 4.224359 | false | false | false | false |
LorittaBot/Loritta | web/spicy-morenitta/src/main/kotlin/net/perfectdreams/spicymorenitta/routes/user.dashboard/AvailableBundlesDashboardRoute.kt | 1 | 3082 | package net.perfectdreams.spicymorenitta.routes.user.dashboard
import io.ktor.client.request.*
import io.ktor.client.statement.*
import kotlinx.browser.document
import kotlinx.browser.window
import kotlinx.html.button
import kotlinx.html.div
import kotlinx.html.dom.append
import kotlinx.html.h2
import kotlinx.html.js.onClickFunction
import kotlinx.html.style
import kotlinx.serialization.Serializable
import kotlinx.serialization.builtins.ListSerializer
import net.perfectdreams.spicymorenitta.SpicyMorenitta
import net.perfectdreams.spicymorenitta.application.ApplicationCall
import net.perfectdreams.spicymorenitta.http
import net.perfectdreams.spicymorenitta.routes.UpdateNavbarSizePostRender
import net.perfectdreams.spicymorenitta.utils.PaymentUtils
import net.perfectdreams.spicymorenitta.utils.loriUrl
import net.perfectdreams.spicymorenitta.utils.select
import org.w3c.dom.HTMLDivElement
class AvailableBundlesDashboardRoute(val m: SpicyMorenitta) : UpdateNavbarSizePostRender("/user/@me/dashboard/bundles") {
override val keepLoadingScreen: Boolean
get() = true
override fun onRender(call: ApplicationCall) {
super.onRender(call)
SpicyMorenitta.INSTANCE.launch {
val result = http.get {
url("${window.location.origin}/api/v1/economy/bundles/sonhos")
}.bodyAsText()
val list = kotlinx.serialization.json.JSON.nonstrict.decodeFromString(ListSerializer(Bundle.serializer()), result)
fixDummyNavbarHeight(call)
m.fixLeftSidebarScroll {
switchContent(call)
}
val entriesDiv = document.select<HTMLDivElement>("#bundles-content")
entriesDiv.append {
div {
style = "display: flex; flex-wrap: wrap;"
// Only show active bundles
for (entry in list.filter { it.active }) {
div {
style = "text-align: center; padding: 8px;"
h2 {
+ "${entry.sonhos} Sonhos"
}
button(classes = "button-discord button-discord-success pure-button") {
+ "Comprar! (R$ ${entry.price})"
onClickFunction = {
val o = object {
val id = entry.id.toString()
}
println(JSON.stringify(o))
PaymentUtils.requestAndRedirectToPaymentUrl(o, "${loriUrl}api/v1/economy/bundles/sonhos/${entry.id}")
}
}
}
}
}
}
m.hideLoadingScreen()
}
}
@Serializable
class Bundle(
val id: Long,
val active: Boolean,
val sonhos: Long,
val price: Double
)
} | agpl-3.0 | 8cafda061ee0455664999031e2a8b9c1 | 34.848837 | 137 | 0.57268 | 5.12812 | false | false | false | false |
darakeon/dfm | android/Lib/src/test/kotlin/com/darakeon/dfm/lib/extensions/NavigationTest.kt | 1 | 1522 | package com.darakeon.dfm.lib.extensions
import android.app.Activity
import android.content.Intent
import com.darakeon.dfm.lib.utils.mockContext
import com.darakeon.dfm.testutils.BaseTest
import com.darakeon.dfm.testutils.context.getCalledName
import com.darakeon.dfm.testutils.execute
import org.hamcrest.CoreMatchers.`is`
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert
import org.junit.Before
import org.junit.Test
import org.junit.runner.RunWith
import org.mockito.ArgumentMatchers.any
import org.mockito.Mockito.`when`
import org.mockito.Mockito.mock
import org.robolectric.RobolectricTestRunner
@RunWith(RobolectricTestRunner::class)
class NavigationTest: BaseTest() {
private lateinit var activity: Activity
private var calledIntent: Intent? = null
private val calledActivity
get() = calledIntent?.getCalledName()
@Before
fun setup() {
activity = mockContext().activity
`when`(activity.startActivity(any()))
.execute { calledIntent = it[0] as Intent }
}
@Test
fun refresh() {
val intent = mock(Intent::class.java)
`when`(activity.intent).thenReturn(intent)
activity.refresh()
assertThat(calledIntent, `is`(intent))
}
@Test
fun redirect() {
activity.redirect<Activity>()
assertThat(calledActivity, `is`("Activity"))
}
@Test
fun redirectWithChangeIntent() {
var intentModifierCalled = false
activity.redirect<Activity> {
intentModifierCalled = true
}
assertThat(calledActivity, `is`("Activity"))
Assert.assertTrue(intentModifierCalled)
}
}
| gpl-3.0 | 0adf9a8759ae4708416b38aafe6712b8 | 24.79661 | 55 | 0.774639 | 3.64988 | false | true | false | false |
wayfair/brickkit-android | BrickKit/bricks/src/main/java/com/wayfair/brickkit/brick/ViewModelBrick.kt | 1 | 5607 | package com.wayfair.brickkit.brick
import android.util.SparseArray
import android.view.View
import androidx.annotation.LayoutRes
import androidx.core.util.isNotEmpty
import androidx.databinding.DataBindingUtil
import androidx.databinding.ViewDataBinding
import com.wayfair.brickkit.padding.BrickPadding
import com.wayfair.brickkit.padding.ZeroBrickPadding
import com.wayfair.brickkit.size.BrickSize
import com.wayfair.brickkit.size.FullWidthBrickSize
import com.wayfair.brickkit.viewholder.BrickViewHolder
/**
* This class is used as a Generic Brick that can take in any XML Layout and use DataBinding to
* insert information from a [ViewModel].
*/
class ViewModelBrick private constructor(
override val layout: Int,
override val placeholderLayout: Int,
val viewModels: SparseArray<ViewModel<*>>,
spanSize: BrickSize,
padding: BrickPadding
) : BaseBrick(spanSize, padding), ViewModel.ViewModelUpdateListener {
init {
(0 until viewModels.size()).forEach { i -> viewModels.valueAt(i).addUpdateListener(this) }
}
/**
* Gets the appropriate [ViewModel] for the given binding id.
*
* @param bindId the binding id
* @return a [ViewModel] for the binding id
*/
fun getViewModel(bindId: Int): ViewModel<*>? = viewModels[bindId]
/**
* Add a view model to the Brick.
*
* @param bindingId the binding ID of the view model
* @param viewModel the view model
*/
fun addViewModel(bindingId: Int, viewModel: ViewModel<*>) {
viewModel.addUpdateListener(this)
viewModels.put(bindingId, viewModel)
onChange()
}
/**
* {@inheritDoc}
*/
override fun onBindData(holder: BrickViewHolder) {
val binding = (holder as ViewModelBrickViewHolder).viewDataBinding
(0 until viewModels.size()).forEach { i ->
binding.setVariable(viewModels.keyAt(i), viewModels.valueAt(i))
}
binding.executePendingBindings()
}
/**
* {@inheritDoc}
*/
override fun createViewHolder(itemView: View): BrickViewHolder = ViewModelBrickViewHolder(DataBindingUtil.bind(itemView)!!)
/**
* {@inheritDoc}
*/
override fun onChange() {
isHidden = !isDataReady
refreshItem()
}
/**
* {@inheritDoc}
*/
override val isDataReady: Boolean
get() {
var isDataReady = viewModels.isNotEmpty()
var i = 0
while (isDataReady && i < viewModels.size()) {
isDataReady = viewModels.valueAt(i++).isDataModelReady
}
return isDataReady
}
override fun hashCode(): Int = super.hashCode()
override fun equals(other: Any?): Boolean {
var areContentsTheSame = true
if (other is ViewModelBrick) {
(0 until viewModels.size()).forEach { i ->
(0 until other.viewModels.size()).forEach { j ->
if (viewModels.keyAt(i) == other.viewModels.keyAt(j) && viewModels.valueAt(i) != other.viewModels.valueAt(j)) {
areContentsTheSame = false
}
}
}
} else {
areContentsTheSame = false
}
return areContentsTheSame
}
/**
* A builder class for [ViewModelBrick], this makes it clearer what is required and what you are actually doing when creating
* [ViewModelBrick]s.
*/
class Builder(@LayoutRes private val layoutId: Int) {
private var placeholderLayoutId = 0
private var viewModels = SparseArray<ViewModel<*>>()
private var spanSize: BrickSize = FullWidthBrickSize()
private var padding: BrickPadding = ZeroBrickPadding()
/**
* Set the placeholder for this brick.
*
* @param placeholderLayoutId the placeholder layout id to be used
* @return the builder
*/
fun setPlaceholder(@LayoutRes placeholderLayoutId: Int): Builder {
this.placeholderLayoutId = placeholderLayoutId
return this
}
/**
* Add a [ViewModel] with a binding Id for the layout already defined.
*
* @param bindingId the binding Id of the view model
* @param viewModel the view model to be bound, extends [ViewModel]
* @return the builder
*/
fun addViewModel(bindingId: Int, viewModel: ViewModel<*>?): Builder {
if (viewModel != null) {
viewModels.put(bindingId, viewModel)
}
return this
}
/**
* Set the [BrickSize].
*
* @param spanSize the [BrickSize]
* @return the builder
*/
fun setSpanSize(spanSize: BrickSize): Builder {
this.spanSize = spanSize
return this
}
/**
* Set the [BrickPadding].
*
* @param padding the [BrickPadding]
* @return the builder
*/
fun setPadding(padding: BrickPadding): Builder {
this.padding = padding
return this
}
/**
* Assemble the [ViewModelBrick].
*
* @return the complete [ViewModelBrick]
*/
fun build(): ViewModelBrick = ViewModelBrick(layoutId, placeholderLayoutId, viewModels, spanSize, padding)
}
/**
* A special [BrickViewHolder] that can handle binding [ViewModel]s to layouts.
*/
private class ViewModelBrickViewHolder(val viewDataBinding: ViewDataBinding) : BrickViewHolder(viewDataBinding.root)
}
| apache-2.0 | 160b50c67b637bc8b95ff0f6f34faea4 | 30.324022 | 131 | 0.612805 | 5.019696 | false | false | false | false |
NuclearCoder/nuclear-bot | src/nuclearbot/client/ImplChatOut.kt | 1 | 2470 | package nuclearbot.client
import nuclearbot.util.Logger
import java.io.BufferedWriter
import java.io.IOException
import java.io.OutputStream
import java.io.OutputStreamWriter
import java.util.concurrent.ArrayBlockingQueue
/*
* Copyright (C) 2017 NuclearCoder
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Implementation of the chat output thread.<br></br>
* <br></br>
* NuclearBot (https://github.com/NuclearCoder/nuclear-bot/)<br></br>
* @author NuclearCoder (contact on the GitHub repo)
*/
class ImplChatOut(stream: OutputStream, private val name: String) : ChatOut {
private val out = BufferedWriter(OutputStreamWriter(stream))
private val queue = ArrayBlockingQueue<String>(QUEUE_SIZE, true)
private lateinit var thread: Thread
@Volatile private var running = false
init {
start(name)
}
override fun write(str: String) {
try {
queue.add(str)
} catch (e: IllegalStateException) {
Logger.error("Output queue for $name is full:")
Logger.printStackTrace(e)
}
}
override fun start(name: String) {
running = true
thread = Thread(this, name + " out").apply { start() }
}
override fun close() {
running = false
thread.interrupt()
}
override fun run() {
try {
while (running) {
try {
val message = queue.take()
out.write(message)
out.flush()
} catch (e: IOException) {
Logger.error("Exception caught in output thread:")
Logger.printStackTrace(e)
}
}
} catch (ignored: InterruptedException) {
}
}
companion object {
private const val QUEUE_SIZE = 50
}
}
| agpl-3.0 | e6cafdd2376e93697381610d800c802e | 27.72093 | 77 | 0.62996 | 4.458484 | false | false | false | false |
chRyNaN/GuitarChords | core/src/jsMain/kotlin/com/chrynan/chords/graphics/Rect.kt | 1 | 5490 | @file:Suppress("unused", "MemberVisibilityCanBePrivate")
package com.chrynan.chords.graphics
import org.w3c.dom.CanvasRenderingContext2D
import org.w3c.dom.HTMLCanvasElement
/**
* A model of a rectangle for a Javascript [HTMLCanvasElement].
*
* Note that this model considers the origin of the
* quadrant to be in the top left. So, on the x-axis, the values start at zero at the furthest left point and increase
* positively when moving to the right. And on the y-axis, the values start at zero at the highest top point and
* increase positively when moving to the bottom. So the Canvas quadrant that this [Rect] supports would look like the
* following:
*
* (0, 0) (x, 0)
* +------------------>
* |
* |
* |
* |
* (0, y) |
*
* This is important to consider because some of the properties depend on it. For instance, the [isEmpty] property will
* return true if the top is greater than or equal to the bottom).
*
* Also note that this [Rect] uses values of [Double] for the four values. This is consistent with what the
* [CanvasRenderingContext2D.rect] function expects.
*
* @property [left] The left coordinate of this [Rect].
* @property [top] The top coordinate of this [Rect].
* @property [right] The right coordinate of this [Rect].
* @property [bottom] The bottom coordinate of this [Rect].
*
* @author chRyNaN
*/
data class Rect(
var left: Double = 0.0,
var top: Double = 0.0,
var right: Double = 0.0,
var bottom: Double = 0.0
) {
/**
* Indicates whether this [Rect] is empty or not. A [Rect] is considered empty if either of it's sides have a size
* of zero or a negative number.
*
* @author chRyNaN
*/
val isEmpty: Boolean
get() = left >= right || top >= bottom
/**
* A convenience property that returns the opposite of [isEmpty].
*
* @author chRyNaN
*/
val isNotEmpty: Boolean
get() = !isEmpty
/**
* The width of this [Rect]. This is equivalent to [right] minus [left].
*
* Note that this will return a negative value if [left] is greater than [right].
*
* @author chRyNaN
*/
val width: Double
get() = right - left
/**
* The height of this [Rect]. This is equivalent to [bottom] - [top].
*
* Note that this will return a negative value if [top] is greater than [bottom].
*
* @author chRyNaN
*/
val height: Double
get() = bottom - top
/**
* The center x value of this [Rect]. This is equivalent to ([left] + [right]) * 0.5.
*
* Note that this does not verify that this [Rect] is not empty.
*
* @author chRyNaN
*/
val centerX: Double
get() = (left + right) * 0.5
/**
* The center y value of this [Rect]. This is equivalent to ([top] + [bottom]) * 0.5.
*
* Note that this does not verify that this [Rect] is not empty.
*
* @author chRyNaN
*/
val centerY: Double
get() = (top + bottom) * 0.5f
/**
* Sets this [Rect]'s values as the provided values.
*
* @author chRyNaN
*/
fun set(left: Double, top: Double, right: Double, bottom: Double) {
this.left = left
this.top = top
this.right = right
this.bottom = bottom
}
/**
* Returns a new [Rect] by offsetting this [Rect] by adding [dx] to its [left] and [right] coordinates, and
* adding [dy] to its [top] and [bottom] coordinates.
*
* @param [dx] The amount to add to this [Rect]'s [left] and [right] coordinates.
* @param [dy] The amount to add to the [Rect]'s [top] and [bottom] coordinates.
*/
fun offset(dx: Double, dy: Double): Rect =
Rect(
left = left + dx,
top = top + dy,
right = right + dx,
bottom = bottom + dy
)
/**
* Returns a new [Rect] by insetting this [Rect] by subtracting [dx] to its [left] and [right] coordinates, and
* adding [dy] to its [top] and [bottom] coordinates.
*
* @param [dx] The amount to subtract to this [Rect]'s [left] and [right] coordinates.
* @param [dy] The amount to subtract to the [Rect]'s [top] and [bottom] coordinates.
*/
@Suppress("MemberVisibilityCanBePrivate")
fun inset(dx: Double, dy: Double): Rect =
Rect(
left = left - dx,
top = top - dy,
right = right - dx,
bottom = bottom - dy
)
/**
* Retrieves a [Boolean] indicating whether the provided [x] and [y] coordinates are within this [Rect]'s bounds.
*
* @author chRyNaN
*/
fun contains(x: Float, y: Float): Boolean = isNotEmpty && x >= left && x < right && y >= top && y < bottom
/**
* Retrieves a [Boolean] indicating whether the provided [other] [Rect] is within this [Rect]'s bounds.
*
* @author chRyNaN
*/
operator fun contains(other: Rect): Boolean = isNotEmpty && left <= other.left && top <= other.top
&& right >= other.right && bottom >= other.bottom
/**
* Retrieves a new [Rect] by adding the provided [other] [Rect]'s values with this [Rect].
*
* @author chRyNaN
*/
operator fun plus(other: Rect): Rect =
Rect(
left = left + other.left,
top = top + other.top,
right = right + other.right,
bottom = bottom + other.bottom
)
} | apache-2.0 | 24ed6ddfdd03147fbfd923f912bb5f6c | 30.924419 | 119 | 0.583424 | 3.893617 | false | false | false | false |
TerrenceMiao/IPAQ | src/main/kotlin/org/paradise/ipaq/services/ExperianService.kt | 1 | 4387 | package org.paradise.ipaq.services
import com.fasterxml.jackson.databind.JsonNode
import org.paradise.ipaq.Constants
import org.paradise.ipaq.domain.ExperianAddress
import org.paradise.ipaq.domain.ExperianSearchResult
import org.paradise.ipaq.services.redis.RedisService
import org.paradise.ipaq.services.rest.RestServiceClient
import org.slf4j.LoggerFactory
import org.springframework.beans.factory.annotation.Value
import org.springframework.http.*
import org.springframework.stereotype.Service
import java.util.*
import kotlin.streams.toList
/**
* Created by terrence on 17/7/17.
*/
@Service
class ExperianService(val restServiceClient: RestServiceClient,
val redisService: RedisService,
@param:Value("\${app.experian.api.url}") val experianApiUrl: String,
@param:Value("\${app.experian.api.token}") val experianApiToken: String) {
fun search(query: String, country: String, take: Int): ResponseEntity<ExperianSearchResult> {
LOG.debug("Search address with query [{}], country [{}] and take [{}]", query, country, take)
val key = query + ", " + country
var experianSearchResult = redisService.get(key, ExperianSearchResult::class.java)
if (Objects.isNull(experianSearchResult)) {
val experianSearchResultResponseEntity = restServiceClient.exchange(
String.format(SEARCH_URL_FORMAT, experianApiUrl, query, country, Constants.MAXIMUM_TAKE),
HttpMethod.GET, HttpEntity<Any>(requestHttpHeaders), ExperianSearchResult::class.java)
if (experianSearchResultResponseEntity.hasBody() && experianSearchResultResponseEntity.body.count > 0) {
redisService.persist(key, experianSearchResultResponseEntity.body)
}
experianSearchResult = experianSearchResultResponseEntity.body
}
return ResponseEntity(takeExperianSearchResult(experianSearchResult!!, take), HttpStatus.OK)
}
fun format(country: String, id: String): ResponseEntity<ExperianAddress> {
LOG.debug("Format address for country [{}] and id [{}]", country, id)
val key = id + ", " + country
var experianAddressResult = redisService.get(key, ExperianAddress::class.java)
if (Objects.isNull(experianAddressResult)) {
val experianAddressResultResponseEntity = restServiceClient.exchange(String.format(DETAILS_URL_FORMAT, experianApiUrl, country, id),
HttpMethod.GET, HttpEntity<Any>(requestHttpHeaders), ExperianAddress::class.java)
if (experianAddressResultResponseEntity.hasBody()
&& Objects.nonNull(experianAddressResultResponseEntity.body.address)
&& Objects.nonNull(experianAddressResultResponseEntity.body.components)) {
redisService.persist(key, experianAddressResultResponseEntity.body)
}
experianAddressResult = experianAddressResultResponseEntity.body
}
return ResponseEntity(experianAddressResult!!, HttpStatus.OK)
}
fun healthCheck(): ResponseEntity<JsonNode> {
LOG.debug("Experian service health check")
return restServiceClient.exchange(String.format("%s/_admin/health", experianApiUrl), HttpMethod.GET, HttpEntity<Any>(requestHttpHeaders), JsonNode::class.java)
}
// -----------------------------------------------------------------------------------------------------------------
private fun takeExperianSearchResult(experianSearchResult: ExperianSearchResult, take: Int): ExperianSearchResult {
return if (experianSearchResult.count > take) ExperianSearchResult(take, experianSearchResult.results.stream().limit(take.toLong()).toList()) else experianSearchResult
}
private val requestHttpHeaders: HttpHeaders
get() {
val requestHeaders = HttpHeaders()
requestHeaders.accept = listOf<MediaType>(MediaType.APPLICATION_JSON)
requestHeaders.set(Constants.HTTP_HEADER_AUTH_TOKEN, experianApiToken)
return requestHeaders
}
companion object {
private val LOG = LoggerFactory.getLogger(ExperianService::class.java)
private val SEARCH_URL_FORMAT = "%s/Search?query=%s&country=%s&take=%s"
private val DETAILS_URL_FORMAT = "%s/format?country=%s&id=%s"
}
} | apache-2.0 | 2bb37dcbf66fb1fbba0d00eeeaa7f57f | 41.601942 | 175 | 0.68475 | 4.584117 | false | false | false | false |
jitsi/jitsi-videobridge | jvb/src/test/kotlin/org/jitsi/videobridge/message/BridgeChannelMessageTest.kt | 1 | 21481 | /*
* Copyright @ 2020-Present 8x8, 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 org.jitsi.videobridge.message
import com.fasterxml.jackson.core.JsonProcessingException
import com.fasterxml.jackson.databind.ObjectMapper
import com.fasterxml.jackson.databind.exc.InvalidTypeIdException
import com.fasterxml.jackson.module.kotlin.jacksonObjectMapper
import com.fasterxml.jackson.module.kotlin.readValue
import io.kotest.assertions.throwables.shouldThrow
import io.kotest.core.spec.style.ShouldSpec
import io.kotest.matchers.collections.shouldContainExactly
import io.kotest.matchers.nulls.shouldNotBeNull
import io.kotest.matchers.shouldBe
import io.kotest.matchers.string.shouldNotInclude
import io.kotest.matchers.types.shouldBeInstanceOf
import org.jitsi.nlj.VideoType
import org.jitsi.videobridge.cc.allocation.VideoConstraints
import org.jitsi.videobridge.message.BridgeChannelMessage.Companion.parse
import org.json.simple.JSONArray
import org.json.simple.JSONObject
import org.json.simple.parser.JSONParser
@Suppress("BlockingMethodInNonBlockingContext")
class BridgeChannelMessageTest : ShouldSpec() {
init {
context("serializing") {
should("encode the type as colibriClass") {
// Any message will do, this one is just simple
val message = ClientHelloMessage()
val parsed = JSONParser().parse(message.toJson())
parsed.shouldBeInstanceOf<JSONObject>()
val parsedColibriClass = parsed["colibriClass"]
parsedColibriClass.shouldBeInstanceOf<String>()
parsedColibriClass shouldBe message.type
}
}
context("parsing an invalid message") {
shouldThrow<JsonProcessingException> {
parse("{invalid json")
}
shouldThrow<JsonProcessingException> {
parse("")
}
shouldThrow<InvalidTypeIdException> {
parse("{}")
}
shouldThrow<InvalidTypeIdException> {
parse("""{"colibriClass": "invalid-colibri-class" }""")
}
context("when some of the message-specific fields are missing/invalid") {
shouldThrow<JsonProcessingException> {
// Missing dominantSpeakerEndpoint field
parse("""{"colibriClass": "DominantSpeakerEndpointChangeEvent" }""")
}
shouldThrow<JsonProcessingException> {
// dominantSpeakerEndpoint has the wrong type
parse("""{"colibriClass": "DominantSpeakerEndpointChangeEvent", "dominantSpeakerEndpoint": [5] }""")
}
}
}
context("serializing and parsing EndpointMessage") {
val endpointsMessage = EndpointMessage("to_value")
endpointsMessage.otherFields["other_field1"] = "other_value1"
endpointsMessage.put("other_field2", 97)
endpointsMessage.put("other_null", null)
val json = endpointsMessage.toJson()
// Make sure we don't mistakenly serialize the "broadcast" flag.
json shouldNotInclude "broadcast"
// Make sure we don't mistakenly serialize the "type".
json shouldNotInclude """
"type":
""".trimIndent()
val parsed = parse(json)
parsed.shouldBeInstanceOf<EndpointMessage>()
parsed.from shouldBe null
parsed.to shouldBe "to_value"
parsed.otherFields["other_field1"] shouldBe "other_value1"
parsed.otherFields["other_field2"] shouldBe 97
parsed.otherFields["other_null"] shouldBe null
parsed.otherFields.containsKey("other_null") shouldBe true
parsed.otherFields.containsKey("nonexistent") shouldBe false
endpointsMessage.from = "new"
(parse(endpointsMessage.toJson()) as EndpointMessage).from shouldBe "new"
context("parsing") {
val parsed2 = parse(ENDPOINT_MESSAGE)
parsed2 as EndpointMessage
parsed2.from shouldBe null
parsed2.to shouldBe "to_value"
parsed2.otherFields["other_field1"] shouldBe "other_value1"
parsed2.otherFields["other_field2"] shouldBe 97
parsed2.otherFields.containsKey("other_null") shouldBe true
parsed2.otherFields.containsKey("nonexistent") shouldBe false
}
}
context("serializing and parsing DominantSpeakerMessage") {
val previousSpeakers = listOf("p1", "p2")
val original = DominantSpeakerMessage("d", previousSpeakers)
val parsed = parse(original.toJson())
parsed.shouldBeInstanceOf<DominantSpeakerMessage>()
parsed.dominantSpeakerEndpoint shouldBe "d"
parsed.previousSpeakers shouldBe listOf("p1", "p2")
}
context("serializing and parsing ServerHello") {
context("without a version") {
val parsed = parse(ServerHelloMessage().toJson())
parsed.shouldBeInstanceOf<ServerHelloMessage>()
parsed.version shouldBe null
}
context("with a version") {
val message = ServerHelloMessage("v")
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<ServerHelloMessage>()
parsed.version shouldBe "v"
}
}
context("serializing and parsing ClientHello") {
val parsed = parse(ClientHelloMessage().toJson())
parsed.shouldBeInstanceOf<ClientHelloMessage>()
}
context("serializing and parsing EndpointConnectionStatusMessage") {
val parsed = parse(EndpointConnectionStatusMessage("abcdabcd", true).toJson())
parsed.shouldBeInstanceOf<EndpointConnectionStatusMessage>()
parsed.endpoint shouldBe "abcdabcd"
parsed.active shouldBe "true"
}
context("serializing and parsing ForwardedEndpointsMessage") {
val forwardedEndpoints = setOf("a", "b", "c")
val message = ForwardedEndpointsMessage(forwardedEndpoints)
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<ForwardedEndpointsMessage>()
parsed.forwardedEndpoints shouldContainExactly forwardedEndpoints
// Make sure the forwardedEndpoints field is serialized as lastNEndpoints as the client (presumably) expects
val parsedJson = JSONParser().parse(message.toJson())
parsedJson.shouldBeInstanceOf<JSONObject>()
val parsedForwardedEndpoints = parsedJson["lastNEndpoints"]
parsedForwardedEndpoints.shouldBeInstanceOf<JSONArray>()
parsedForwardedEndpoints.toList() shouldContainExactly forwardedEndpoints
}
context("serializing and parsing ForwardedSourcesMessage") {
val forwardedSources = setOf("s1", "s2", "s3")
val message = ForwardedSourcesMessage(forwardedSources)
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<ForwardedSourcesMessage>()
parsed.forwardedSources shouldContainExactly forwardedSources
}
context("serializing and parsing VideoConstraints") {
val videoConstraints: VideoConstraints = jacksonObjectMapper().readValue(VIDEO_CONSTRAINTS)
videoConstraints.maxHeight shouldBe 1080
videoConstraints.maxFrameRate shouldBe 15.0
}
context("and SenderVideoConstraintsMessage") {
val senderVideoConstraintsMessage = SenderVideoConstraintsMessage(1080)
val parsed = parse(senderVideoConstraintsMessage.toJson())
parsed.shouldBeInstanceOf<SenderVideoConstraintsMessage>()
parsed.videoConstraints.idealHeight shouldBe 1080
}
context("serializing and parsing SenderSourceConstraintsMessage") {
val senderVideoConstraintsMessage = SenderSourceConstraintsMessage("s1", 1080)
val parsed = parse(senderVideoConstraintsMessage.toJson())
parsed.shouldBeInstanceOf<SenderSourceConstraintsMessage>()
parsed.sourceName shouldBe "s1"
parsed.maxHeight shouldBe 1080
}
context("serializing and parsing AddReceiver") {
context("with source names") {
val message = AddReceiverMessage("bridge1", null, "s1", VideoConstraints(360))
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<AddReceiverMessage>()
parsed.bridgeId shouldBe "bridge1"
parsed.endpointId shouldBe null
parsed.sourceName shouldBe "s1"
parsed.videoConstraints shouldBe VideoConstraints(360)
}
context("without source names") {
val message = AddReceiverMessage("bridge1", "abcdabcd", null, VideoConstraints(360))
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<AddReceiverMessage>()
parsed.bridgeId shouldBe "bridge1"
parsed.endpointId shouldBe "abcdabcd"
parsed.sourceName shouldBe null
parsed.videoConstraints shouldBe VideoConstraints(360)
}
}
context("serializing and parsing RemoveReceiver") {
val message = RemoveReceiverMessage("bridge1", "abcdabcd")
val parsed = parse(message.toJson())
parsed.shouldBeInstanceOf<RemoveReceiverMessage>()
parsed.bridgeId shouldBe "bridge1"
parsed.endpointId shouldBe "abcdabcd"
}
context("serializing and parsing VideoType") {
val videoTypeMessage = VideoTypeMessage(VideoType.DESKTOP)
videoTypeMessage.videoType shouldBe VideoType.DESKTOP
parse(videoTypeMessage.toJson()).apply {
shouldBeInstanceOf<VideoTypeMessage>()
videoType shouldBe VideoType.DESKTOP
}
listOf("none", "NONE", "None", "nOnE").forEach {
val jsonString = """
{
"colibriClass" : "VideoTypeMessage",
"videoType" : "$it"
}
"""
parse(jsonString).apply {
shouldBeInstanceOf<VideoTypeMessage>()
videoType shouldBe VideoType.NONE
}
}
val jsonString = """
{
"colibriClass" : "VideoTypeMessage",
"videoType" : "desktop_high_fps"
}
"""
parse(jsonString).apply {
shouldBeInstanceOf<VideoTypeMessage>()
videoType shouldBe VideoType.DESKTOP_HIGH_FPS
}
}
context("serializing and parsing SourceVideoType") {
val testSourceName = "source1234"
val srcVideoTypeMessage = SourceVideoTypeMessage(VideoType.DESKTOP, testSourceName)
srcVideoTypeMessage.videoType shouldBe VideoType.DESKTOP
parse(srcVideoTypeMessage.toJson()).apply {
shouldBeInstanceOf<SourceVideoTypeMessage>()
videoType shouldBe VideoType.DESKTOP
sourceName shouldBe testSourceName
}
listOf("none", "NONE", "None", "nOnE").forEach {
val jsonString = """
{
"colibriClass" : "SourceVideoTypeMessage",
"sourceName": "$testSourceName",
"videoType" : "$it"
}
"""
parse(jsonString).apply {
shouldBeInstanceOf<SourceVideoTypeMessage>()
videoType shouldBe VideoType.NONE
sourceName shouldBe testSourceName
}
}
val jsonString = """
{
"colibriClass" : "SourceVideoTypeMessage",
"sourceName" : "source1234",
"videoType" : "desktop_high_fps"
}
"""
parse(jsonString).apply {
shouldBeInstanceOf<SourceVideoTypeMessage>()
videoType shouldBe VideoType.DESKTOP_HIGH_FPS
sourceName shouldBe testSourceName
}
}
context("serializing and parsing VideoSourceMap") {
val source1 = "source1234"
val owner1 = "endpoint1"
val ssrc1 = 12345L
val rtxSsrc1 = 45678L
val source2 = "source5678"
val owner2 = "endpoint2"
val ssrc2 = 87654L
val rtxSsrc2 = 98765L
val videoSourcesMapMessage = VideoSourcesMap(
listOf(
VideoSourceMapping(source1, owner1, ssrc1, rtxSsrc1, VideoType.CAMERA),
VideoSourceMapping(source2, owner2, ssrc2, rtxSsrc2, VideoType.DESKTOP)
)
)
parse(videoSourcesMapMessage.toJson()).apply {
shouldBeInstanceOf<VideoSourcesMap>()
mappedSources.size shouldBe 2
mappedSources shouldContainExactly
listOf(
VideoSourceMapping(source1, owner1, ssrc1, rtxSsrc1, VideoType.CAMERA),
VideoSourceMapping(source2, owner2, ssrc2, rtxSsrc2, VideoType.DESKTOP)
)
}
val jsonString = """
{"colibriClass":"VideoSourcesMap",
"mappedSources":[{"source":"source1234","owner":"endpoint1","ssrc":12345,"rtx":45678,"videoType":"CAMERA"},
{"source":"source5678","owner":"endpoint2","ssrc":87654,"rtx":98765,"videoType":"DESKTOP"}
]
}
""".trimIndent()
parse(jsonString).apply {
shouldBeInstanceOf<VideoSourcesMap>()
mappedSources.size shouldBe 2
mappedSources shouldContainExactly
listOf(
VideoSourceMapping(source1, owner1, ssrc1, rtxSsrc1, VideoType.CAMERA),
VideoSourceMapping(source2, owner2, ssrc2, rtxSsrc2, VideoType.DESKTOP)
)
}
}
context("serializing and parsing AudioSourceMap") {
val source1 = "source1234-a"
val owner1 = "endpoint1"
val ssrc1 = 23456L
val source2 = "source5678-a"
val owner2 = "endpoint2"
val ssrc2 = 98765L
val audioSourcesMapMessage = AudioSourcesMap(
listOf(
AudioSourceMapping(source1, owner1, ssrc1),
AudioSourceMapping(source2, owner2, ssrc2)
)
)
parse(audioSourcesMapMessage.toJson()).apply {
shouldBeInstanceOf<AudioSourcesMap>()
mappedSources.size shouldBe 2
mappedSources shouldContainExactly
listOf(
AudioSourceMapping(source1, owner1, ssrc1),
AudioSourceMapping(source2, owner2, ssrc2)
)
}
val jsonString = """
{"colibriClass":"AudioSourcesMap",
"mappedSources":[{"source":"source1234-a","owner":"endpoint1","ssrc":23456},
{"source":"source5678-a","owner":"endpoint2","ssrc":98765}
]
}
""".trimIndent()
parse(jsonString).apply {
shouldBeInstanceOf<AudioSourcesMap>()
mappedSources.size shouldBe 2
mappedSources shouldContainExactly
listOf(
AudioSourceMapping(source1, owner1, ssrc1),
AudioSourceMapping(source2, owner2, ssrc2)
)
}
}
context("Parsing ReceiverVideoConstraints") {
context("With all fields present") {
val parsed = parse(RECEIVER_VIDEO_CONSTRAINTS)
parsed.shouldBeInstanceOf<ReceiverVideoConstraintsMessage>()
parsed.lastN shouldBe 3
parsed.onStageEndpoints shouldBe listOf("onstage1", "onstage2")
parsed.selectedEndpoints shouldBe listOf("selected1", "selected2")
parsed.defaultConstraints shouldBe VideoConstraints(0)
val constraints = parsed.constraints
constraints.shouldNotBeNull()
constraints.size shouldBe 3
constraints["epOnStage"] shouldBe VideoConstraints(720)
constraints["epThumbnail1"] shouldBe VideoConstraints(180)
constraints["epThumbnail2"] shouldBe VideoConstraints(180, 30.0)
}
context("With fields missing") {
val parsed = parse(RECEIVER_VIDEO_CONSTRAINTS_EMPTY)
parsed.shouldBeInstanceOf<ReceiverVideoConstraintsMessage>()
parsed.lastN shouldBe null
parsed.onStageEndpoints shouldBe null
parsed.selectedEndpoints shouldBe null
parsed.defaultConstraints shouldBe null
parsed.constraints shouldBe null
}
}
xcontext("Serializing performance") {
val times = 1_000_000
val objectMapper = ObjectMapper()
fun toJsonJackson(m: DominantSpeakerMessage): String = objectMapper.writeValueAsString(m)
fun toJsonJsonSimple(m: DominantSpeakerMessage) = JSONObject().apply {
this["dominantSpeakerEndpoint"] = m.dominantSpeakerEndpoint
}.toJSONString()
fun toJsonStringConcat(m: DominantSpeakerMessage) =
"{\"colibriClass\":\"DominantSpeakerEndpointChangeEvent\",\"dominantSpeakerEndpoint\":\"" +
m.dominantSpeakerEndpoint + "\"}"
fun toJsonStringTemplate(m: DominantSpeakerMessage) =
"{\"colibriClass\":\"${DominantSpeakerMessage.TYPE}\"," +
"\"dominantSpeakerEndpoint\":\"${m.dominantSpeakerEndpoint}\"}"
fun toJsonRawStringTemplate(m: DominantSpeakerMessage) = """
{"colibriClass":"${DominantSpeakerMessage.TYPE}",
"dominantSpeakerEndpoint":"${m.dominantSpeakerEndpoint}"}
"""
fun runTest(f: (DominantSpeakerMessage) -> String): Long {
val start = System.currentTimeMillis()
for (i in 0..times) {
f(DominantSpeakerMessage(i.toString()))
}
val end = System.currentTimeMillis()
return end - start
}
System.err.println("Times=$times")
System.err.println("Jackson: ${runTest { toJsonJackson(it) }}")
System.err.println("Json-simple: ${runTest { toJsonJsonSimple(it) }}")
System.err.println("String concat: ${runTest { toJsonStringConcat(it) }}")
System.err.println("String template: ${runTest { toJsonStringTemplate(it) }}")
System.err.println("Raw string template: ${runTest { toJsonRawStringTemplate(it) }}")
System.err.println("Raw string template (trim): ${runTest { toJsonRawStringTemplate(it).trimMargin() }}")
}
}
companion object {
const val ENDPOINT_MESSAGE = """
{
"colibriClass": "EndpointMessage",
"to": "to_value",
"other_field1": "other_value1",
"other_field2": 97,
"other_null": null
}
"""
const val VIDEO_CONSTRAINTS = """
{
"maxHeight": 1080,
"maxFrameRate": 15.0
}
"""
const val RECEIVER_VIDEO_CONSTRAINTS_EMPTY = """
{
"colibriClass": "ReceiverVideoConstraints"
}
"""
const val RECEIVER_VIDEO_CONSTRAINTS = """
{
"colibriClass": "ReceiverVideoConstraints",
"lastN": 3,
"selectedEndpoints": [ "selected1", "selected2" ],
"onStageEndpoints": [ "onstage1", "onstage2" ],
"defaultConstraints": { "maxHeight": 0 },
"constraints": {
"epOnStage": { "maxHeight": 720 },
"epThumbnail1": { "maxHeight": 180 },
"epThumbnail2": { "maxHeight": 180, "maxFrameRate": 30 }
}
}
"""
}
}
| apache-2.0 | 904e2cfaaf64383a83b459fcb9a2bbb9 | 40.629845 | 124 | 0.578418 | 5.818256 | false | false | false | false |
samuelclay/NewsBlur | clients/android/NewsBlur/src/com/newsblur/activity/NbActivity.kt | 1 | 4060 | package com.newsblur.activity
import android.content.IntentFilter
import androidx.appcompat.app.AppCompatActivity
import com.newsblur.util.PrefConstants.ThemeValue
import android.os.Bundle
import com.newsblur.database.BlurDatabaseHelper
import com.newsblur.util.PrefsUtils
import com.newsblur.util.UIUtils
import com.newsblur.service.NBSyncReceiver
import com.newsblur.util.FeedUtils
import com.newsblur.util.Log
import dagger.hilt.android.AndroidEntryPoint
import javax.inject.Inject
/**
* The base class for all Activities in the NewsBlur app. Handles enforcement of
* login state and tracking of sync/update broadcasts.
*/
@AndroidEntryPoint
open class NbActivity : AppCompatActivity() {
@Inject
lateinit var dbHelper: BlurDatabaseHelper
private var uniqueLoginKey: String? = null
private var lastTheme: ThemeValue? = null
// Facilitates the db updates by the sync service on the UI
private val serviceSyncReceiver = object : NBSyncReceiver() {
override fun handleUpdateType(updateType: Int) {
runOnUiThread { handleUpdate(updateType) }
}
}
override fun onCreate(bundle: Bundle?) {
Log.offerContext(this)
Log.d(this, "onCreate")
// this is not redundant to the applyThemePreference() call in onResume. the theme needs to be set
// before onCreate() in order to work
PrefsUtils.applyThemePreference(this)
lastTheme = PrefsUtils.getSelectedTheme(this)
super.onCreate(bundle)
// in rare cases of process interruption or DB corruption, an activity can launch without valid
// login creds. redirect the user back to the loging workflow.
if (PrefsUtils.getUserId(this) == null) {
Log.e(this, "post-login activity launched without valid login.")
PrefsUtils.logout(this, dbHelper)
finish()
}
bundle?.let {
uniqueLoginKey = it.getString(UNIQUE_LOGIN_KEY)
}
if (uniqueLoginKey == null) {
uniqueLoginKey = PrefsUtils.getUniqueLoginKey(this)
}
finishIfNotLoggedIn()
}
override fun onResume() {
Log.d(this, "onResume" + UIUtils.getMemoryUsageDebug(this))
super.onResume()
finishIfNotLoggedIn()
// is is possible that another activity changed the theme while we were on the backstack
val currentSelectedTheme = PrefsUtils.getSelectedTheme(this)
if (lastTheme != currentSelectedTheme) {
lastTheme = currentSelectedTheme
PrefsUtils.applyThemePreference(this)
UIUtils.restartActivity(this)
}
registerReceiver(serviceSyncReceiver, IntentFilter().apply {
addAction(NBSyncReceiver.NB_SYNC_ACTION)
})
}
override fun onPause() {
Log.d(this.javaClass.name, "onPause")
super.onPause()
unregisterReceiver(serviceSyncReceiver)
}
private fun finishIfNotLoggedIn() {
val currentLoginKey = PrefsUtils.getUniqueLoginKey(this)
if (currentLoginKey == null || currentLoginKey != uniqueLoginKey) {
Log.d(this.javaClass.name, "This activity was for a different login. finishing it.")
finish()
}
}
override fun onSaveInstanceState(savedInstanceState: Bundle) {
Log.d(this, "onSave")
savedInstanceState.putString(UNIQUE_LOGIN_KEY, uniqueLoginKey)
super.onSaveInstanceState(savedInstanceState)
}
/**
* Pokes the sync service to perform any pending sync actions.
*/
protected fun triggerSync() {
FeedUtils.triggerSync(this)
}
/**
* Called on each NB activity after the DB has been updated by the sync service.
*
* @param updateType one or more of the UPDATE_* flags in this class to indicate the
* type of update being broadcast.
*/
protected open fun handleUpdate(updateType: Int) {
Log.w(this, "activity doesn't implement handleUpdate")
}
}
private const val UNIQUE_LOGIN_KEY = "uniqueLoginKey" | mit | e41174d763b3208a4f40d6491eeec09b | 32.561983 | 106 | 0.679064 | 4.624146 | false | false | false | false |
facebook/litho | litho-widget-kotlin/src/main/kotlin/com/facebook/litho/kotlin/widget/ExperimentalProgress.kt | 1 | 3523 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.litho.kotlin.widget
import android.content.Context
import android.graphics.Color
import android.graphics.PorterDuff
import android.graphics.drawable.Drawable
import com.facebook.litho.MeasureScope
import com.facebook.litho.MountableComponent
import com.facebook.litho.MountableComponentScope
import com.facebook.litho.MountableRenderResult
import com.facebook.litho.SimpleMountable
import com.facebook.litho.SizeSpec
import com.facebook.litho.Style
import com.facebook.litho.theming.getTheme
import com.facebook.litho.widget.ProgressView
import com.facebook.rendercore.MeasureResult
/**
* Renders an infinitely spinning progress bar.
*
* @param indeterminateDrawable Drawable to be shown to show progress.
* @param color Tint color for the drawable.
*/
class ExperimentalProgress(
private val color: Int? = null,
private val indeterminateDrawable: Drawable? = null,
private val style: Style? = null
) : MountableComponent() {
override fun MountableComponentScope.render(): MountableRenderResult {
val defaultColor = getTheme().colors.primary
return MountableRenderResult(
ProgressMountable(
color = color ?: defaultColor, indeterminateDrawable = indeterminateDrawable),
style)
}
}
private const val defaultSize: Int = 50
internal class ProgressMountable(
private val color: Int,
private val indeterminateDrawable: Drawable?
) : SimpleMountable<ProgressView>(RenderType.VIEW) {
override fun createContent(context: Context): ProgressView = ProgressView(context)
override fun MeasureScope.measure(widthSpec: Int, heightSpec: Int): MeasureResult {
return if (SizeSpec.getMode(widthSpec) == SizeSpec.UNSPECIFIED &&
SizeSpec.getMode(heightSpec) == SizeSpec.UNSPECIFIED) {
MeasureResult(defaultSize, defaultSize)
} else {
withEqualSize(widthSpec, heightSpec)
}
}
override fun mount(c: Context, content: ProgressView, layoutData: Any?) {
indeterminateDrawable?.let { content.indeterminateDrawable = indeterminateDrawable }
content.indeterminateDrawable?.let {
if (color != Color.TRANSPARENT) {
content.indeterminateDrawable.mutate().setColorFilter(color, PorterDuff.Mode.MULTIPLY)
}
}
}
override fun unmount(c: Context, content: ProgressView, layoutData: Any?) {
// restore the color first, since it acts on the indeterminateDrawable
if (color != Color.TRANSPARENT && content.indeterminateDrawable != null) {
content.indeterminateDrawable.mutate().clearColorFilter()
}
content.indeterminateDrawable = null
}
override fun shouldUpdate(
newMountable: SimpleMountable<ProgressView>,
currentLayoutData: Any?,
nextLayoutData: Any?
): Boolean {
newMountable as ProgressMountable
return newMountable.color != color ||
newMountable.indeterminateDrawable != indeterminateDrawable
}
}
| apache-2.0 | 551bc3cd580a6cedcf63da08f94fea09 | 34.585859 | 94 | 0.750781 | 4.528278 | false | false | false | false |
facebook/litho | sample/src/main/java/com/facebook/samples/litho/onboarding/model/models.kt | 1 | 5480 | /*
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.facebook.samples.litho.onboarding.model
import androidx.annotation.DrawableRes
import com.facebook.samples.litho.R
// start_example
class User(val username: String, @DrawableRes val avatarRes: Int)
class Post(
val id: String,
val user: User,
@DrawableRes val imageRes: Int,
val text: String? = null
)
// end_example
val BEN = User(username = "Ben", avatarRes = R.drawable.ic_launcher)
val LUCAS = User(username = "Lucas", avatarRes = R.drawable.ic_launcher)
val LILY = User(username = "Lily", avatarRes = R.drawable.ic_launcher)
val LYRA = User(username = "Lyra", avatarRes = R.drawable.ic_launcher)
val NEBULA = User(username = "Nebula", avatarRes = R.drawable.ic_launcher)
val TOTO_LOKI = User(username = "Toto & Loki", avatarRes = R.drawable.ic_launcher)
val NEBULAS_POST =
Post(id = "post1", user = NEBULA, imageRes = R.drawable.nebula4, text = "Meow you doin?")
val FEED =
listOf(
Post(
id = "post1",
user = BEN,
imageRes = R.drawable.ben,
text = "Did someone say tuna?"),
Post(
id = "post2", user = LILY, imageRes = R.drawable.lily, text = "Whisker-y Business"),
Post(
id = "post3",
user = LILY,
imageRes = R.drawable.lily2,
text = "I cat even right now"),
Post(
id = "post4",
user = LILY,
imageRes = R.drawable.lily3,
text = "It ain’t easy being puff-fect"),
Post(
id = "post5", user = LYRA, imageRes = R.drawable.lyra, text = "Purr-fect morning!"),
Post(
id = "post6",
user = LYRA,
imageRes = R.drawable.lyra2,
text = "Napping is the thing I love meowst"),
Post(
id = "post7",
user = LYRA,
imageRes = R.drawable.lyra3,
text = "Looking good, feline good"),
Post(
id = "post8",
user = LYRA,
imageRes = R.drawable.lyra4,
text = "It’s the purrfect time for a nap"),
Post(
id = "post9",
user = LYRA,
imageRes = R.drawable.lyra5,
text = "How claw-some is that?"),
Post(
id = "post10",
user = LUCAS,
imageRes = R.drawable.lucascat,
text = "Stay pawsitive!"),
NEBULAS_POST,
Post(
id = "post11",
user = NEBULA,
imageRes = R.drawable.nebula,
text = "I’ll have a meow-tini"),
Post(
id = "post12",
user = NEBULA,
imageRes = R.drawable.nebula2,
text = "Meow-nificent"),
Post(
id = "post13",
user = NEBULA,
imageRes = R.drawable.nebula3,
text = "Every day is a cat day for me"),
Post(
id = "post15",
user = NEBULA,
imageRes = R.drawable.nebula5,
text = "We’re purrfect for each other"),
Post(
id = "post16",
user = NEBULA,
imageRes = R.drawable.nebula6,
text = "So fur so good!"),
Post(
id = "post17",
user = NEBULA,
imageRes = R.drawable.nebula7,
text = "Catitude is everything "),
Post(
id = "post18",
user = TOTO_LOKI,
imageRes = R.drawable.toto_loki,
text = "Do you believe in furry tails"),
Post(
id = "post19",
user = TOTO_LOKI,
imageRes = R.drawable.toto_loki2,
text = "Best fur-ends"),
Post(
id = "post20",
user = TOTO_LOKI,
imageRes = R.drawable.toto_loki3,
text = "Tabby or not tabby? That is the question"),
Post(
id = "post21",
user = TOTO_LOKI,
imageRes = R.drawable.toto_loki4,
text = "Claw-less"),
Post(
id = "post22",
user = TOTO_LOKI,
imageRes = R.drawable.toto_loki5,
text = "You had me at meow"),
Post(
id = "post23",
user = TOTO_LOKI,
imageRes = R.drawable.toto_loki6,
text = "Don’t worry. Be tabby"),
)
.shuffled()
val USER_STORIES = List(10) { User("story$it", R.drawable.ic_launcher) }
| apache-2.0 | 541de0ce7ca6252178e0e8a5080e55ea | 34.751634 | 100 | 0.486106 | 3.893238 | false | false | false | false |
android/camera-samples | CameraXBasic/app/src/main/java/com/android/example/cameraxbasic/fragments/PermissionsFragment.kt | 1 | 3019 | /*
* 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
*
* 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.android.example.cameraxbasic.fragments
import android.Manifest
import android.content.Context
import android.content.pm.PackageManager
import android.os.Bundle
import android.widget.Toast
import androidx.core.content.ContextCompat
import androidx.fragment.app.Fragment
import androidx.lifecycle.lifecycleScope
import androidx.navigation.Navigation
import com.android.example.cameraxbasic.R
private const val PERMISSIONS_REQUEST_CODE = 10
private val PERMISSIONS_REQUIRED = arrayOf(Manifest.permission.CAMERA)
/**
* The sole purpose of this fragment is to request permissions and, once granted, display the
* camera fragment to the user.
*/
class PermissionsFragment : Fragment() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
if (!hasPermissions(requireContext())) {
// Request camera-related permissions
requestPermissions(PERMISSIONS_REQUIRED, PERMISSIONS_REQUEST_CODE)
} else {
// If permissions have already been granted, proceed
navigateToCamera()
}
}
override fun onRequestPermissionsResult(
requestCode: Int, permissions: Array<String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == PERMISSIONS_REQUEST_CODE) {
if (PackageManager.PERMISSION_GRANTED == grantResults.firstOrNull()) {
// Take the user to the success fragment when permission is granted
Toast.makeText(context, "Permission request granted", Toast.LENGTH_LONG).show()
navigateToCamera()
} else {
Toast.makeText(context, "Permission request denied", Toast.LENGTH_LONG).show()
}
}
}
private fun navigateToCamera() {
lifecycleScope.launchWhenStarted {
Navigation.findNavController(requireActivity(), R.id.fragment_container).navigate(
PermissionsFragmentDirections.actionPermissionsToCamera())
}
}
companion object {
/** Convenience method used to check if all permissions required by this app are granted */
fun hasPermissions(context: Context) = PERMISSIONS_REQUIRED.all {
ContextCompat.checkSelfPermission(context, it) == PackageManager.PERMISSION_GRANTED
}
}
}
| apache-2.0 | d8c5de3bbee29363cb1645164faad728 | 37.21519 | 99 | 0.706525 | 5.07395 | false | false | false | false |
google/horologist | media-ui/src/main/java/com/google/android/horologist/media/ui/components/animated/AnimatedMediaButton.kt | 1 | 3539 | /*
* Copyright 2022 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.horologist.media.ui.components.animated
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.size
import androidx.compose.runtime.Composable
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.graphicsLayer
import androidx.compose.ui.semantics.semantics
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.wear.compose.material.Button
import androidx.wear.compose.material.ButtonColors
import androidx.wear.compose.material.ButtonDefaults
import androidx.wear.compose.material.LocalContentAlpha
import com.airbnb.lottie.LottieComposition
import com.airbnb.lottie.compose.LottieAnimatable
import com.airbnb.lottie.compose.LottieAnimation
import com.airbnb.lottie.compose.LottieDynamicProperties
import com.google.android.horologist.media.ui.ExperimentalHorologistMediaUiApi
import kotlinx.coroutines.launch
import androidx.compose.ui.semantics.contentDescription as contentDescriptionProperty
/**
* A base button for media controls.
*/
@ExperimentalHorologistMediaUiApi
@Composable
public fun AnimatedMediaButton(
onClick: () -> Unit,
composition: LottieComposition?,
lottieAnimatable: LottieAnimatable,
contentDescription: String,
modifier: Modifier = Modifier,
enabled: Boolean = true,
colors: ButtonColors = ButtonDefaults.iconButtonColors(),
dynamicProperties: LottieDynamicProperties? = null,
iconSize: Dp = 30.dp,
tapTargetSize: DpSize = DpSize(48.dp, 60.dp),
iconAlign: Alignment.Horizontal = Alignment.CenterHorizontally
) {
val scope = rememberCoroutineScope()
Button(
onClick = {
scope.launch {
lottieAnimatable.animate(composition = composition)
}
onClick()
},
modifier = modifier.size(tapTargetSize),
enabled = enabled,
colors = colors
) {
LottieAnimation(
modifier = Modifier
.size(iconSize)
.run {
when (iconAlign) {
Alignment.Start -> {
offset(x = -7.5.dp)
}
Alignment.End -> {
offset(x = 7.5.dp)
}
else -> {
this
}
}
}
.align(Alignment.Center)
.graphicsLayer(alpha = LocalContentAlpha.current)
.semantics { contentDescriptionProperty = contentDescription },
composition = composition,
progress = { lottieAnimatable.progress },
dynamicProperties = dynamicProperties
)
}
}
| apache-2.0 | a117ad08a5bfd2d86044ca8612638a46 | 35.484536 | 85 | 0.670246 | 4.94965 | false | false | false | false |
Constantinuous/Angus | infrastructure/src/main/kotlin/de/constantinuous/angus/sql/impl/AntlrTSqlParser.kt | 1 | 1743 | package de.constantinuous.angus.sql.impl
import de.constantinuous.angus.parsing.sql.TSqlParser
import org.antlr.v4.runtime.ANTLRInputStream
import org.antlr.v4.runtime.CommonTokenStream
import org.antlr.v4.runtime.RuleContext
import org.antlr.v4.runtime.tree.ParseTreeWalker
import org.antlr.v4.tool.Rule
import tsqlLexer
import tsqlParser
/**
* Created by RichardG on 25.11.2016.
*/
class AntlrTSqlParser : TSqlParser {
private fun getContext(sqlCode: String): RuleContext{
// Get our lexer
val lexer = tsqlLexer(ANTLRInputStream(sqlCode))
// Get a list of matched tokens
val tokens = CommonTokenStream(lexer)
// Pass the tokens to the parser
val parser = tsqlParser(tokens)
// Specify our entry point
val drinkSentenceContext = parser.tsql_file()
return drinkSentenceContext
}
override fun printDrink(drinkSentence: String) {
val drinkSentenceContext = getContext(drinkSentence)
// Walk it and attach our listener
val walker = ParseTreeWalker()
val listener = AntlrTsqlListener()
walker.walk(listener, drinkSentenceContext)
}
override fun printTree(drinkSentence: String){
val drinkSentenceContext = getContext(drinkSentence)
explore(drinkSentenceContext, 0)
}
private fun explore(ctx: RuleContext, indentation: Int){
val ruleName = tsqlParser.ruleNames[ctx.ruleIndex]
for(i in 0..indentation){
print(" ")
}
println(ruleName)
for(i in 0..ctx.childCount){
val element = ctx.getChild(i)
if(element is RuleContext){
explore(element, indentation + 1)
}
}
}
} | mit | b8d75237e980364cf3337d4349bfa487 | 27.590164 | 60 | 0.665519 | 4.220339 | false | false | false | false |
yshrsmz/monotweety | app/src/main/java/net/yslibrary/monotweety/activity/main/MainActivity.kt | 1 | 2493 | package net.yslibrary.monotweety.activity.main
import android.content.Context
import android.content.Intent
import android.os.Bundle
import androidx.appcompat.widget.Toolbar
import com.bluelinelabs.conductor.ChangeHandlerFrameLayout
import com.bluelinelabs.conductor.Controller
import net.yslibrary.monotweety.App
import net.yslibrary.monotweety.R
import net.yslibrary.monotweety.activity.ActionBarProvider
import net.yslibrary.monotweety.activity.ActivityModule
import net.yslibrary.monotweety.base.BaseActivity
import net.yslibrary.monotweety.base.HasComponent
import net.yslibrary.monotweety.base.findById
import net.yslibrary.monotweety.event.ActivityResult
import net.yslibrary.monotweety.event.NewIntent
import net.yslibrary.monotweety.splash.SplashController
import timber.log.Timber
class MainActivity : BaseActivity(), ActionBarProvider, HasComponent<MainActivityComponent> {
companion object {
fun callingIntent(context: Context): Intent {
val intent = Intent(context, MainActivity::class.java)
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
return intent
}
}
override val container: ChangeHandlerFrameLayout
get() = findViewById<ChangeHandlerFrameLayout>(R.id.controller_container)
override val layoutResId: Int
get() = R.layout.activity_main
override val rootController: Controller
get() = SplashController()
override val component: MainActivityComponent by lazy {
DaggerMainActivityComponent.builder()
.appComponent(App.appComponent(this))
.activityModule(ActivityModule(this))
.build()
}
override fun onNewIntent(intent: Intent?) {
super.onNewIntent(intent)
Timber.i("onNewIntent - MainActivity")
intent?.let { activityBus.emit(NewIntent(it)) }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
Timber.i("onCreate - MainActivity")
val toolbar = findById<Toolbar>(R.id.toolbar)
setSupportActionBar(toolbar)
component.inject(this)
}
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
super.onActivityResult(requestCode, resultCode, data)
Timber.i("onActivityResult - MainActivity, requestCode: $requestCode, resultCode: $resultCode, data: $data, extra: ${data?.extras}")
activityBus.emit(ActivityResult(requestCode, resultCode, data))
}
}
| apache-2.0 | 63cd8e5b80b37ea29af393fe74eba417 | 36.208955 | 140 | 0.738468 | 4.859649 | false | false | false | false |
mrkirby153/KirBot | src/main/kotlin/me/mrkirby153/KirBot/modules/censor/Censor.kt | 1 | 3540 | package me.mrkirby153.KirBot.modules.censor
import me.mrkirby153.KirBot.event.Subscribe
import me.mrkirby153.KirBot.logger.LogEvent
import me.mrkirby153.KirBot.module.Module
import me.mrkirby153.KirBot.modules.censor.rules.CensorRule
import me.mrkirby153.KirBot.modules.censor.rules.DomainRule
import me.mrkirby153.KirBot.modules.censor.rules.InviteRule
import me.mrkirby153.KirBot.modules.censor.rules.TokenRule
import me.mrkirby153.KirBot.modules.censor.rules.ViolationException
import me.mrkirby153.KirBot.modules.censor.rules.WordRule
import me.mrkirby153.KirBot.modules.censor.rules.ZalgoRule
import me.mrkirby153.KirBot.utils.settings.SettingsRepository
import me.mrkirby153.KirBot.utils.getClearance
import me.mrkirby153.KirBot.utils.kirbotGuild
import me.mrkirby153.KirBot.utils.nameAndDiscrim
import me.mrkirby153.KirBot.utils.settings.GuildSettings
import me.mrkirby153.KirBot.utils.toTypedArray
import net.dv8tion.jda.api.entities.Guild
import net.dv8tion.jda.api.entities.Message
import net.dv8tion.jda.api.entities.User
import net.dv8tion.jda.api.events.message.guild.GuildMessageReceivedEvent
import net.dv8tion.jda.api.events.message.guild.GuildMessageUpdateEvent
import org.json.JSONArray
import org.json.JSONObject
class Censor : Module("censor") {
private val censorRules = mutableListOf<CensorRule>()
private val invitePattern = "(discord\\.gg|discordapp.com/invite)/([A-Za-z0-9\\-]+)"
private val inviteRegex = Regex(invitePattern)
override fun onLoad() {
censorRules.clear()
censorRules.add(ZalgoRule())
censorRules.add(TokenRule())
censorRules.add(WordRule())
censorRules.add(InviteRule())
censorRules.add(DomainRule())
}
@Subscribe
fun onGuildMessageReceived(event: GuildMessageReceivedEvent) {
if (event.author == event.jda.selfUser)
return
process(event.message)
}
@Subscribe
fun onGuildMessageUpdate(event: GuildMessageUpdateEvent) {
if (event.author == event.jda.selfUser)
return
process(event.message)
}
private fun process(message: Message) {
try {
val settings = getEffectiveSettings(message.author, message.guild)
settings.forEach { setting ->
this.censorRules.forEach { rule ->
rule.check(message, setting)
}
}
} catch (exception: ViolationException) {
message.guild.kirbotGuild.logManager.genericLog(LogEvent.MESSAGE_CENSOR,
":no_entry_sign:",
"Message (`${message.id}`) by **${message.author.nameAndDiscrim}** (`${message.author.id}`) censored in #${message.channel.name}: ${exception.msg} ```${message.contentRaw}```")
message.delete().queue()
}
}
companion object {
fun getSettings(guild: Guild): JSONObject {
return GuildSettings.censorSettings.get(guild)
}
fun getEffectiveSettings(user: User, guild: Guild): Array<JSONObject> {
val clearance = user.getClearance(guild)
val settings = getSettings(guild)
val rawRules = settings.optJSONArray("rules") ?: JSONArray()
val rules = mutableListOf<JSONObject>()
rawRules.toTypedArray(JSONObject::class.java).forEach { rule ->
if(rule.optInt("_level", -1) >= clearance) {
rules.add(rule)
}
}
return rules.toTypedArray()
}
}
} | mit | a899a69b740b034e59b05863cd113fa7 | 35.885417 | 196 | 0.680226 | 4.018161 | false | false | false | false |
Commit451/LabCoat | app/src/main/java/com/commit451/gitlab/adapter/AccountAdapter.kt | 2 | 3827 | package com.commit451.gitlab.adapter
import android.content.Context
import androidx.recyclerview.widget.RecyclerView
import android.view.ViewGroup
import android.widget.PopupMenu
import com.commit451.addendum.themeAttrColor
import com.commit451.gitlab.App
import com.commit451.gitlab.R
import com.commit451.gitlab.model.Account
import com.commit451.gitlab.viewHolder.AccountFooterViewHolder
import com.commit451.gitlab.viewHolder.AccountViewHolder
/**
* Adapter to show all the accounts
*/
class AccountAdapter(context: Context, private val listener: Listener) : RecyclerView.Adapter<RecyclerView.ViewHolder>() {
companion object {
private const val TYPE_ACCOUNT = 0
private const val TYPE_FOOTER = 1
private const val FOOTER_COUNT = 1
}
private val accounts = mutableListOf<Account>()
private val colorControlHighlight: Int = context.themeAttrColor(R.attr.colorControlHighlight)
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): RecyclerView.ViewHolder {
when (viewType) {
TYPE_ACCOUNT -> {
val holder = AccountViewHolder.inflate(parent)
holder.itemView.setOnClickListener {
val position = holder.adapterPosition
listener.onAccountClicked(getItemAtPosition(position))
}
return holder
}
TYPE_FOOTER -> {
val footerViewHolder = AccountFooterViewHolder.inflate(parent)
footerViewHolder.itemView.setOnClickListener { listener.onAddAccountClicked() }
return footerViewHolder
}
}
throw IllegalStateException("No known view holder for that type $viewType")
}
override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
when (holder) {
is AccountViewHolder -> {
val account = getItemAtPosition(position)
holder.bind(account, account == App.get().getAccount(), colorControlHighlight)
holder.itemView.setTag(R.id.list_position, position)
holder.popupMenu.setOnMenuItemClickListener(PopupMenu.OnMenuItemClickListener { item ->
when (item.itemId) {
R.id.action_sign_out -> {
val itemPosition = accounts.indexOf(account)
accounts.remove(account)
notifyItemRemoved(itemPosition)
listener.onAccountLogoutClicked(account)
return@OnMenuItemClickListener true
}
}
false
})
}
is AccountFooterViewHolder -> {
//Nah
}
else -> {
throw IllegalStateException("No known bind for this viewHolder")
}
}
}
override fun getItemCount(): Int {
return accounts.size + FOOTER_COUNT
}
override fun getItemViewType(position: Int): Int {
return if (position == accounts.size) TYPE_FOOTER else TYPE_ACCOUNT
}
fun setAccounts(accounts: Collection<Account>?) {
this.accounts.clear()
if (accounts != null) {
this.accounts.addAll(accounts)
}
notifyDataSetChanged()
}
fun addAccount(account: Account) {
if (!accounts.contains(account)) {
accounts.add(0, account)
notifyItemInserted(0)
}
}
private fun getItemAtPosition(position: Int): Account {
return accounts[position]
}
interface Listener {
fun onAccountClicked(account: Account)
fun onAddAccountClicked()
fun onAccountLogoutClicked(account: Account)
}
}
| apache-2.0 | 02774a04490ee7000c8ba45ce990ee12 | 34.435185 | 122 | 0.610661 | 5.42068 | false | false | false | false |
dya-tel/TSU-Schedule | src/main/kotlin/ru/dyatel/tsuschedule/screens/HomeScreen.kt | 1 | 4125 | package ru.dyatel.tsuschedule.screens
import android.content.Context
import android.support.v4.content.ContextCompat
import android.support.v4.graphics.drawable.DrawableCompat
import android.text.InputType
import android.view.Gravity
import android.view.View
import android.view.inputmethod.EditorInfo
import com.wealthfront.magellan.BaseScreenView
import com.wealthfront.magellan.Screen
import org.jetbrains.anko.appcompat.v7.themedTintedButton
import org.jetbrains.anko.backgroundColorResource
import org.jetbrains.anko.centerHorizontally
import org.jetbrains.anko.centerInParent
import org.jetbrains.anko.design.textInputEditText
import org.jetbrains.anko.design.themedTextInputLayout
import org.jetbrains.anko.dip
import org.jetbrains.anko.imageView
import org.jetbrains.anko.matchParent
import org.jetbrains.anko.padding
import org.jetbrains.anko.relativeLayout
import org.jetbrains.anko.singleLine
import org.jetbrains.anko.topOf
import org.jetbrains.anko.verticalLayout
import ru.dyatel.tsuschedule.BlankGroupIndexException
import ru.dyatel.tsuschedule.R
import ru.dyatel.tsuschedule.ShortGroupIndexException
import ru.dyatel.tsuschedule.events.Event
import ru.dyatel.tsuschedule.events.EventBus
import ru.dyatel.tsuschedule.layout.DIM_LARGE
import ru.dyatel.tsuschedule.layout.DIM_ULTRA_LARGE
import ru.dyatel.tsuschedule.utilities.Validator
import ru.dyatel.tsuschedule.utilities.hideKeyboard
class HomeView(context: Context) : BaseScreenView<HomeScreen>(context) {
private companion object {
val formContainerId = View.generateViewId()
}
init {
backgroundColorResource = R.color.primary_color
relativeLayout {
padding = DIM_ULTRA_LARGE
val icon = ContextCompat.getDrawable(context, R.drawable.logo)!!
val color = ContextCompat.getColor(context, R.color.text_title_color)
DrawableCompat.setTint(icon, color)
imageView(icon).lparams {
topOf(formContainerId)
centerHorizontally()
bottomMargin = DIM_LARGE
}
verticalLayout {
id = formContainerId
val input = themedTextInputLayout(R.style.HomeFormInputLayoutTheme) {
hint = context.getString(R.string.form_hint_group_index)
setErrorTextAppearance(R.style.HomeFormErrorTheme)
textInputEditText {
imeOptions = imeOptions or EditorInfo.IME_FLAG_NO_EXTRACT_UI
gravity = Gravity.CENTER
singleLine = true
inputType = InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS
}
}.lparams(width = matchParent)
themedTintedButton(R.string.button_add_group, R.style.HomeFormSubmitTheme) {
setOnClickListener {
try {
val group = Validator.validateGroup(input.editText!!.text.toString())
EventBus.broadcast(Event.ADD_GROUP, group)
} catch (e: BlankGroupIndexException) {
input.error = context.getString(R.string.form_error_blank_group)
} catch (e: ShortGroupIndexException) {
input.error = context.getString(R.string.form_error_short_group)
}
}
}.lparams(width = matchParent)
}.lparams(width = dip(300)) {
centerInParent()
}
}
}
}
class HomeScreen : Screen<HomeView>() {
override fun createView(context: Context) = HomeView(context)
override fun onShow(context: Context?) {
super.onShow(context)
EventBus.broadcast(Event.SET_TOOLBAR_SHADOW_ENABLED, false)
}
override fun onHide(context: Context?) {
activity.hideKeyboard()
EventBus.broadcast(Event.SET_TOOLBAR_SHADOW_ENABLED, true)
super.onHide(context)
}
override fun getTitle(context: Context) = context.getString(R.string.screen_home)!!
}
| mit | 17f4197a8464b3c58bcb0b09f949791b | 35.830357 | 97 | 0.664 | 4.730505 | false | false | false | false |
canou/Simple-Commons | commons/src/main/kotlin/com/simplemobiletools/commons/dialogs/ConfirmationDialog.kt | 1 | 1704 | package com.simplemobiletools.commons.dialogs
import android.content.Context
import android.support.v7.app.AlertDialog
import android.view.LayoutInflater
import com.simplemobiletools.commons.R
import com.simplemobiletools.commons.extensions.setupDialogStuff
import kotlinx.android.synthetic.main.dialog_message.view.*
/**
* A simple dialog without any view, just a messageId, a positive button and optionally a negative button
*
* @param context has to be activity context to avoid some Theme.AppCompat issues
* @param message the dialogs message, can be any String. If empty, messageId is used
* @param messageId the dialogs messageId ID. Used only if message is empty
* @param positive positive buttons text ID
* @param negative negative buttons text ID (optional)
* @param callback an anonymous function
*/
class ConfirmationDialog(val context: Context, message: String = "", messageId: Int = R.string.proceed_with_deletion, positive: Int = R.string.yes,
negative: Int = R.string.no, val callback: () -> Unit) {
var dialog: AlertDialog
init {
val view = LayoutInflater.from(context).inflate(R.layout.dialog_message, null)
view.message.text = if (message.isEmpty()) context.resources.getString(messageId) else message
val builder = AlertDialog.Builder(context)
.setPositiveButton(positive, { dialog, which -> dialogConfirmed() })
if (negative != 0)
builder.setNegativeButton(negative, null)
dialog = builder.create().apply {
context.setupDialogStuff(view, this)
}
}
private fun dialogConfirmed() {
dialog.dismiss()
callback.invoke()
}
}
| apache-2.0 | 36118b395199b557f1ed2d782ae8aa3f | 38.627907 | 147 | 0.709507 | 4.531915 | false | false | false | false |
alexpensato/spring-boot-repositories-samples | spring-data-mongodb-sample/src/main/java/net/pensato/data/mongodb/sample/domain/Student.kt | 1 | 1112 | /*
* Copyright 2017 twitter.com/PensatoAlex
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package net.pensato.data.mongodb.sample.domain
import org.springframework.data.annotation.Id
import org.springframework.data.mongodb.core.index.Indexed
import org.springframework.data.mongodb.core.mapping.DBRef
import org.springframework.data.mongodb.core.mapping.Document
@Document(collection = "student")
data class Student(
@Id var id: String? = null,
@Indexed(unique = true) var name: String = "",
var address: String = "",
@DBRef var college: College = College()
)
| apache-2.0 | e7f7aa178722dbb03ce7286cb69bbebd | 37.344828 | 75 | 0.736511 | 3.929329 | false | false | false | false |
dataloom/conductor-client | src/main/kotlin/com/openlattice/search/PersistentSearchService.kt | 1 | 5554 | package com.openlattice.search
import com.dataloom.mappers.ObjectMappers
import com.fasterxml.jackson.databind.ObjectMapper
import com.openlattice.authorization.AclKey
import com.openlattice.authorization.Principals
import com.openlattice.organizations.roles.SecurePrincipalsManager
import com.openlattice.postgres.PostgresArrays
import com.openlattice.postgres.PostgresColumn.*
import com.openlattice.postgres.PostgresTable.PERSISTENT_SEARCHES
import com.openlattice.postgres.ResultSetAdapters
import com.openlattice.postgres.streams.BasePostgresIterable
import com.openlattice.postgres.streams.PreparedStatementHolderSupplier
import com.openlattice.search.requests.PersistentSearch
import com.openlattice.search.requests.SearchConstraints
import com.zaxxer.hikari.HikariDataSource
import java.sql.Array
import java.sql.Connection
import java.sql.PreparedStatement
import java.sql.Statement
import java.time.OffsetDateTime
import java.util.*
class PersistentSearchService(private val hds: HikariDataSource, private val spm: SecurePrincipalsManager) {
private val mapper: ObjectMapper = ObjectMappers.getJsonMapper()
private fun getUserAclKey(): AclKey {
return spm.lookup(Principals.getCurrentUser())
}
private fun getUserAclKeyArray(connection: Connection): Array {
return PostgresArrays.createUuidArray(connection, getUserAclKey())
}
fun createPersistentSearch(search: PersistentSearch): UUID {
val connection = hds.connection
connection.use {
val ps: PreparedStatement = connection.prepareStatement(insertSql(connection, search))
ps.setString(1, mapper.writeValueAsString(search.searchConstraints))
ps.setString(2, mapper.writeValueAsString(search.alertMetadata))
ps.setArray(3, PostgresArrays.createTextArray(connection, search.additionalEmailAddresses))
ps.execute()
}
return search.id
}
fun loadPersistentSearchesForUser(includeExpired: Boolean): Iterable<PersistentSearch> {
return BasePostgresIterable(PreparedStatementHolderSupplier(hds, loadPersistentSearchesSql(includeExpired)) { ps ->
ps.setArray(1, getUserAclKeyArray(ps.connection))
}) {
ResultSetAdapters.persistentSearch(it)
}
}
fun updatePersistentSearchLastRead(id: UUID, lastRead: OffsetDateTime) {
val connection = hds.connection
connection.use {
val stmt: Statement = connection.createStatement()
stmt.execute(updateDateSql(connection, id, false, lastRead))
}
}
fun updatePersistentSearchAdditionalEmails(id: UUID, additionalEmails: Set<String>) {
val connection = hds.connection
connection.use {
val ps: PreparedStatement = connection.prepareStatement(updateAdditionalEmailsSql(connection, id))
ps.setArray(1, PostgresArrays.createTextArray(it, additionalEmails))
ps.execute()
}
}
fun updatePersistentSearchExpiration(id: UUID, expiration: OffsetDateTime) {
val connection = hds.connection
connection.use {
val stmt: Statement = connection.createStatement()
stmt.execute(updateDateSql(connection, id, true, expiration))
}
}
fun updatePersistentSearchConstraints(id: UUID, constraints: SearchConstraints) {
val connection = hds.connection
connection.use {
val ps: PreparedStatement = connection.prepareStatement(updateSearchConstraintsSql(connection, id))
ps.setString(1, mapper.writeValueAsString(constraints))
ps.execute()
}
}
private fun insertSql(connection: Connection, search: PersistentSearch): String {
val columns = setOf(
ID_VALUE.name,
ACL_KEY.name,
LAST_READ.name,
EXPIRATION_DATE.name,
ALERT_TYPE.name,
SEARCH_CONSTRAINTS.name,
ALERT_METADATA.name,
EMAILS.name
)
return "INSERT INTO ${PERSISTENT_SEARCHES.name} ( ${columns.joinToString()} ) " +
"VALUES ('${search.id}'::uuid, '${getUserAclKeyArray(connection)}', '${search.lastRead}', '${search.expiration}', " +
"'${search.type}', ?::jsonb, ?::jsonb, ?)"
}
private fun updateAdditionalEmailsSql(connection: Connection, id: UUID): String {
return "UPDATE ${PERSISTENT_SEARCHES.name} SET ${EMAILS.name} = ? " +
"WHERE id = '$id' AND ${ACL_KEY.name} = '${getUserAclKeyArray(connection)}'"
}
private fun updateDateSql(connection: Connection, id: UUID, isExpiration: Boolean, value: OffsetDateTime): String {
val field = if (isExpiration) EXPIRATION_DATE.name else LAST_READ.name
return "UPDATE ${PERSISTENT_SEARCHES.name} SET $field = '$value' " +
"WHERE id = '$id' AND ${ACL_KEY.name} = '${getUserAclKeyArray(connection)}'"
}
private fun updateSearchConstraintsSql(connection: Connection, id: UUID): String {
return "UPDATE ${PERSISTENT_SEARCHES.name} SET ${SEARCH_CONSTRAINTS.name} = ?::jsonb " +
"WHERE id = '$id' AND ${ACL_KEY.name} = '${getUserAclKeyArray(connection)}'"
}
private fun loadPersistentSearchesSql(includeExpired: Boolean): String {
var sql = "SELECT * FROM ${PERSISTENT_SEARCHES.name} WHERE ${ACL_KEY.name} = ?"
if (!includeExpired) {
sql += " AND ${EXPIRATION_DATE.name} > now()"
}
return sql
}
} | gpl-3.0 | d994bd3058896a6bf63f0f1be321da7c | 41.730769 | 133 | 0.683831 | 4.643813 | false | false | false | false |
wenhuiyao/CoroutinesAdapter | example/src/main/kotlin/com/wenhui/coroutines/example/MainKtActivity.kt | 1 | 2527 | package com.wenhui.coroutines.example
import android.os.Bundle
import android.support.v7.app.AppCompatActivity
import android.util.Log
import android.widget.Toast
import com.wenhui.coroutines.CoroutineContexts
import com.wenhui.coroutines.and
import com.wenhui.coroutines.from
import kotlinx.android.synthetic.main.activity_main.*
import retrofit2.Retrofit
import retrofit2.converter.moshi.MoshiConverterFactory
class MainKtActivity : AppCompatActivity() {
private val TAG = "MainActivity"
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
simpleBackgroundWorkButton.setOnClickListener {
onSimpleBackgroundWorkClick()
}
simpleMergeWorkButton.setOnClickListener {
onSimpleMergeWorkButtonClick()
}
retrofitButton.setOnClickListener {
doRetrofitWork()
}
}
private fun onSimpleBackgroundWorkClick() {
textView.text = "Start simple background work"
from {
Thread.sleep(1000)
1000
}.consume {
Thread.sleep(200)
}.onSuccess {
Log.d(TAG, "onSuccess: $it")
}.onError {
Log.d(TAG, "onError: ${it.message}")
}.start()
}
private fun onSimpleMergeWorkButtonClick() {
and({
ThreadUtils.sleep(1000)
"Merge "
}, {
ThreadUtils.sleep(2000)
1000
}).merge { str, int ->
"$str $int"
}.consume(CoroutineContexts.UI) {
Toast.makeText(this, it, Toast.LENGTH_SHORT).show()
}.onSuccess {
textView.text = it
}.onError {
Toast.makeText(this, it.message, Toast.LENGTH_SHORT).show()
}.start()
}
private fun doRetrofitWork() {
textView.text = "Start requesting google books"
val retrofit = Retrofit.Builder()
.baseUrl("https:www.googleapis.com")
.addConverterFactory(MoshiConverterFactory.create())
.build()
val retrofitService = retrofit.create(RetrofitService::class.java)
val call = retrofitService.getGoogleBook("isbn:0747532699")
from(RetrofitWork(call)).transform {
it.items[0].volumeInfo
}.onSuccess {
textView.text = it.title
}.onError {
Toast.makeText(this, "request error", Toast.LENGTH_SHORT).show()
}.start()
}
} | apache-2.0 | 862db7970f70360c839af2c2ec30de68 | 28.395349 | 76 | 0.613376 | 4.653775 | false | false | false | false |
GrandPanda/kommands | src/main/kotlin/com/darichey/discord/kommands/limiters/RoleLimiter.kt | 1 | 661 | package com.darichey.discord.kommands.limiters
import com.darichey.discord.kommands.CommandFunction
import com.darichey.discord.kommands.Limiter
import sx.blah.discord.handle.obj.IRole
/**
* A [Limiter] limiting the use of a command to certain [IRole]s.
* Will pass a command executed by a user with **ANY** of the given roles. (Not with all)
*/
class RoleLimiter(vararg roles: String, onFail: CommandFunction = {}) :
Limiter({ roles.any { role ->
author.getRolesForGuild(guild).any { it.id == role }
} }, onFail) {
constructor(vararg roles: IRole, onFail: CommandFunction = {}):
this(*roles.map(IRole::getID).toTypedArray(), onFail = onFail)
} | gpl-3.0 | 2d7637c16c9a8caca192f31b69179284 | 35.777778 | 89 | 0.727685 | 3.389744 | false | false | false | false |
msebire/intellij-community | plugins/github/src/org/jetbrains/plugins/github/pullrequest/data/service/GithubPullRequestsStateServiceImpl.kt | 1 | 10423 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.github.pullrequest.data.service
import com.intellij.openapi.Disposable
import com.intellij.openapi.application.invokeAndWaitIfNeeded
import com.intellij.openapi.progress.ProcessCanceledException
import com.intellij.openapi.progress.ProgressIndicator
import com.intellij.openapi.progress.ProgressManager
import com.intellij.openapi.progress.Task
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.text.StringUtil
import com.intellij.util.EventDispatcher
import com.intellij.util.containers.ContainerUtil
import git4idea.GitCommit
import org.jetbrains.annotations.CalledInAwt
import org.jetbrains.plugins.github.api.GithubApiRequestExecutor
import org.jetbrains.plugins.github.api.GithubApiRequests
import org.jetbrains.plugins.github.api.GithubFullPath
import org.jetbrains.plugins.github.api.GithubServerPath
import org.jetbrains.plugins.github.api.data.GithubIssueState
import org.jetbrains.plugins.github.api.data.GithubPullRequestDetailed
import org.jetbrains.plugins.github.pullrequest.action.ui.GithubMergeCommitMessageDialog
import org.jetbrains.plugins.github.pullrequest.data.GithubPullRequestsDataLoader
import org.jetbrains.plugins.github.util.GithubAsyncUtil
import org.jetbrains.plugins.github.util.GithubNotifications
import java.util.*
class GithubPullRequestsStateServiceImpl internal constructor(private val project: Project,
private val progressManager: ProgressManager,
private val dataLoader: GithubPullRequestsDataLoader,
private val requestExecutor: GithubApiRequestExecutor,
private val serverPath: GithubServerPath,
private val repoPath: GithubFullPath)
: GithubPullRequestsStateService {
private val busySet = ContainerUtil.newConcurrentSet<Long>()
private val busyChangeEventDispatcher = EventDispatcher.create(GithubPullRequestBusyStateListener::class.java)
@CalledInAwt
override fun close(pullRequest: Long) {
if (!acquire(pullRequest)) return
progressManager.run(object : Task.Backgroundable(project, "Closing Pull Request", true) {
override fun run(indicator: ProgressIndicator) {
requestExecutor.execute(indicator,
GithubApiRequests.Repos.PullRequests.update(serverPath, repoPath.user, repoPath.repository, pullRequest,
state = GithubIssueState.closed))
}
override fun onSuccess() {
GithubNotifications.showInfo(project, "Pull Request Closed", "Successfully closed pull request #${pullRequest}")
}
override fun onThrowable(error: Throwable) {
GithubNotifications.showError(project, "Failed To Close Pull Request", error)
}
override fun onFinished() {
release(pullRequest)
dataLoader.reloadDetails(pullRequest)
}
})
}
@CalledInAwt
override fun reopen(pullRequest: Long) {
if (!acquire(pullRequest)) return
progressManager.run(object : Task.Backgroundable(project, "Reopening Pull Request", true) {
override fun run(indicator: ProgressIndicator) {
requestExecutor.execute(indicator,
GithubApiRequests.Repos.PullRequests.update(serverPath, repoPath.user, repoPath.repository, pullRequest,
state = GithubIssueState.open))
}
override fun onSuccess() {
GithubNotifications.showInfo(project, "Pull Request Reopened", "Successfully reopened pull request #${pullRequest}")
}
override fun onThrowable(error: Throwable) {
GithubNotifications.showError(project, "Failed To Reopen Pull Request", error)
}
override fun onFinished() {
release(pullRequest)
dataLoader.reloadDetails(pullRequest)
}
})
}
@CalledInAwt
override fun merge(pullRequest: Long) {
if (!acquire(pullRequest)) return
progressManager.run(object : Task.Backgroundable(project, "Merging Pull Request", true) {
private lateinit var details: GithubPullRequestDetailed
override fun run(indicator: ProgressIndicator) {
indicator.text2 = "Loading details"
details = GithubAsyncUtil.awaitMutableFuture(indicator) { dataLoader.getDataProvider(pullRequest).detailsRequest }
indicator.checkCanceled()
indicator.text2 = "Acquiring commit message"
val commitMessage = invokeAndWaitIfNeeded {
val dialog = GithubMergeCommitMessageDialog(project,
"Merge Pull Request",
"Merge pull request #${pullRequest}",
details.title)
if (dialog.showAndGet()) dialog.message else null
} ?: throw ProcessCanceledException()
indicator.text2 = "Merging"
requestExecutor.execute(indicator, GithubApiRequests.Repos.PullRequests.merge(details,
commitMessage.first, commitMessage.second,
details.head.sha))
}
override fun onSuccess() {
GithubNotifications.showInfo(project, "Pull Request Merged", "Successfully merged pull request #${details.number}")
}
override fun onThrowable(error: Throwable) {
GithubNotifications.showError(project, "Failed To Merge Pull Request", error)
}
override fun onFinished() {
release(pullRequest)
dataLoader.reloadDetails(pullRequest)
}
})
}
@CalledInAwt
override fun rebaseMerge(pullRequest: Long) {
if (!acquire(pullRequest)) return
progressManager.run(object : Task.Backgroundable(project, "Merging Pull Request", true) {
lateinit var details: GithubPullRequestDetailed
override fun run(indicator: ProgressIndicator) {
indicator.text2 = "Loading details"
details = GithubAsyncUtil.awaitMutableFuture(indicator) { dataLoader.getDataProvider(pullRequest).detailsRequest }
indicator.checkCanceled()
indicator.text2 = "Merging"
requestExecutor.execute(indicator, GithubApiRequests.Repos.PullRequests.rebaseMerge(details, details.head.sha))
}
override fun onSuccess() {
GithubNotifications.showInfo(project, "Pull Request Rebased and Merged",
"Successfully rebased and merged pull request #${details.number}")
}
override fun onThrowable(error: Throwable) {
GithubNotifications.showError(project, "Failed To Rebase and Merge Pull Request", error)
}
override fun onFinished() {
release(pullRequest)
dataLoader.reloadDetails(pullRequest)
}
})
}
@CalledInAwt
override fun squashMerge(pullRequest: Long) {
if (!acquire(pullRequest)) return
progressManager.run(object : Task.Backgroundable(project, "Merging Pull Request", true) {
lateinit var details: GithubPullRequestDetailed
lateinit var commits: List<GitCommit>
override fun run(indicator: ProgressIndicator) {
indicator.text2 = "Loading details"
details = GithubAsyncUtil.awaitMutableFuture(indicator) { dataLoader.getDataProvider(pullRequest).detailsRequest }
indicator.checkCanceled()
indicator.text2 = "Loading commits"
commits = GithubAsyncUtil.awaitMutableFuture(indicator) { dataLoader.getDataProvider(pullRequest).logCommitsRequest }
indicator.checkCanceled()
indicator.text2 = "Acquiring commit message"
val body = "* " + StringUtil.join(commits, { it.subject }, "\n\n* ")
val commitMessage = invokeAndWaitIfNeeded {
val dialog = GithubMergeCommitMessageDialog(project,
"Merge Pull Request",
"Merge pull request #${pullRequest}",
body)
if (dialog.showAndGet()) dialog.message else null
} ?: throw ProcessCanceledException()
indicator.text2 = "Merging"
requestExecutor.execute(indicator, GithubApiRequests.Repos.PullRequests.merge(details,
commitMessage.first, commitMessage.second,
details.head.sha))
}
override fun onSuccess() {
GithubNotifications.showInfo(project, "Pull Request Squashed and Merged",
"Successfully squashed amd merged pull request #${details.number}")
}
override fun onThrowable(error: Throwable) {
GithubNotifications.showError(project, "Failed To Squash and Merge Pull Request", error)
}
override fun onFinished() {
release(pullRequest)
dataLoader.reloadDetails(pullRequest)
}
})
}
@CalledInAwt
private fun acquire(pullRequest: Long): Boolean {
val ok = busySet.add(pullRequest)
if (ok) busyChangeEventDispatcher.multicaster.busyStateChanged(pullRequest)
return ok
}
@CalledInAwt
private fun release(pullRequest: Long) {
val ok = busySet.remove(pullRequest)
if (ok) busyChangeEventDispatcher.multicaster.busyStateChanged(pullRequest)
}
@CalledInAwt
override fun isBusy(pullRequest: Long) = busySet.contains(pullRequest)
override fun addPullRequestBusyStateListener(disposable: Disposable, listener: (Long) -> Unit) =
busyChangeEventDispatcher.addListener(object : GithubPullRequestBusyStateListener {
override fun busyStateChanged(pullRequest: Long) {
listener(pullRequest)
}
}, disposable)
private interface GithubPullRequestBusyStateListener : EventListener {
fun busyStateChanged(pullRequest: Long)
}
} | apache-2.0 | d92e77ee33d9df6c4a57a3235686e9bc | 42.07438 | 140 | 0.652403 | 5.680109 | false | false | false | false |
google/kiosk-app-reference-implementation | app/src/main/java/com/ape/apps/sample/baypilot/ui/home/HomeViewModel.kt | 1 | 1873 | /*
* Copyright 2022 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.ape.apps.sample.baypilot.ui.home
import android.content.Context
import android.util.Log
import androidx.lifecycle.*
import com.ape.apps.sample.baypilot.data.creditplan.CreditPlanInfo
import com.ape.apps.sample.baypilot.data.sharedprefs.SharedPreferencesManager
import com.ape.apps.sample.baypilot.util.sharedpreferences.SharedPreferenceIntLiveData
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
class HomeViewModel : ViewModel() {
companion object {
private const val TAG = "BayPilotHomeViewModel"
}
private val _creditPlanInfo = MutableLiveData<CreditPlanInfo>()
val creditPlanInfo: LiveData<CreditPlanInfo>
get() = _creditPlanInfo
fun observeCreditPlanInfo(context: Context) {
Log.d(TAG, "observeCreditPlanInfo() called with: context")
val sharedPreferencesManager = SharedPreferencesManager(context)
viewModelScope.launch {
SharedPreferenceIntLiveData(
sharedPreferencesManager.sharedPreferences,
SharedPreferencesManager.KEY_CREDIT_PLAN_SAVE_ID,
0
).asFlow().collect {
Log.d(TAG, "observeCreditPlanInfo() asFlow().collect called with: creditPlanSaveId = $it")
_creditPlanInfo.value = sharedPreferencesManager.readCreditPlan()
}
}
}
} | apache-2.0 | 62503101a866d00af2e71475fa900a6c | 32.464286 | 98 | 0.755473 | 4.190157 | false | false | false | false |
NooAn/bytheway | app/src/main/java/ru/a1024bits/bytheway/ui/dialogs/ErrorStandartRegistrationDialog.kt | 1 | 2620 | package ru.a1024bits.bytheway.ui.dialogs
import android.os.Bundle
import android.support.v4.app.DialogFragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.google.firebase.auth.PhoneAuthProvider
import com.google.firebase.crash.FirebaseCrash
import kotlinx.android.synthetic.main.error_registration_dialog.*
import kotlinx.android.synthetic.main.error_registration_dialog.view.*
import ru.a1024bits.bytheway.R
import ru.a1024bits.bytheway.ui.activity.RegistrationActivity
class ErrorStandartRegistrationDialog : DialogFragment() {
var activity: RegistrationActivity? = null
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return layoutInflater.inflate(R.layout.error_registration_dialog, container, false)
}
override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
isCancelable = false
try {
view?.sendButtonCode?.setOnClickListener({
try {
activity?.mVerificationId?.let {
PhoneAuthProvider.getCredential(it, verificationsData.text.toString())?.let { credentialIt ->
activity?.signInGoogle(credentialIt, this@ErrorStandartRegistrationDialog)
}
}
} catch (e: Exception) {
e.printStackTrace()
FirebaseCrash.report(e)
}
})
view?.sendButtonPhone?.setOnClickListener({
if (verificationsData.text.toString().contains(Regex("^((380)|(7))")))
verificationsData.setText(StringBuilder("+").append(verificationsData.text.toString()))
if (activity?.validatePhoneNumber(verificationsData) == false)
return@setOnClickListener
view.verificationsData.hint = activity?.getString(R.string.sms_code)
view.sendButtonCode.visibility = View.VISIBLE
view.sendButtonPhone.visibility = View.GONE
activity?.authPhone(verificationsData)
verificationsData.setText("")
})
} catch (e: Exception) {
e.printStackTrace()
}
}
companion object {
fun newInstance(activity: RegistrationActivity): ErrorStandartRegistrationDialog {
val result = ErrorStandartRegistrationDialog()
result.activity = activity
return result
}
}
} | mit | af6401d3097b368e8086ebfb158bcaf4 | 41.274194 | 117 | 0.645802 | 5.137255 | false | false | false | false |
sksamuel/elasticsearch-river-neo4j | streamops-session/streamops-session-pulsar/src/main/kotlin/com/octaldata/session/pulsar/PulsarTopicOps.kt | 1 | 10624 | package com.octaldata.session.pulsar
import com.octaldata.core.await
import com.octaldata.domain.BrokerId
import com.octaldata.domain.DeploymentConnectionConfig
import com.octaldata.domain.structure.SchemaField
import com.octaldata.domain.topics.ExtendedTopic
import com.octaldata.domain.topics.LightTopic
import com.octaldata.domain.topics.Partition
import com.octaldata.domain.topics.PartitionId
import com.octaldata.domain.topics.TopicConfigs
import com.octaldata.domain.topics.TopicName
import com.octaldata.session.CompressionType
import com.octaldata.session.ElectionType
import com.octaldata.session.InsertRecordRequest
import com.octaldata.session.PartitionBrokerSpread
import com.octaldata.session.PartitionMessageDistribution
import com.octaldata.session.TopicOps
import com.octaldata.session.TopicPartitionOffsets
import com.sksamuel.tabby.results.success
import mu.KotlinLogging
import org.apache.pulsar.client.admin.PulsarAdmin
import org.apache.pulsar.client.api.MessageId
import org.apache.pulsar.common.policies.data.PersistentTopicInternalStats
import org.apache.pulsar.common.policies.data.TopicStats
import kotlin.time.Duration
class PulsarTopicOps(config: DeploymentConnectionConfig.Pulsar) : TopicOps {
private val logger = KotlinLogging.logger { }
private val client = PulsarAdmin.builder()
.serviceHttpUrl(config.adminServiceUrl)
.build()
override suspend fun topicNames(): Result<List<TopicName>> = runCatching {
client.tenants().tenants.flatMap { tenant ->
client.namespaces().getNamespaces(tenant).flatMap { namespace ->
client.topics().getList(namespace).map { topicName ->
TopicName(topicName)
}
}
}
}
override suspend fun count(topicName: TopicName): Result<Long> {
return Result.success(0)
}
override suspend fun offsets(
topicName: TopicName,
partitionIds: Set<PartitionId>
): Result<List<TopicPartitionOffsets>> {
return Result.success(emptyList())
}
override suspend fun truncatePartition(topicName: TopicName, partitionId: PartitionId): Result<Boolean> {
return Result.success(false)
}
override suspend fun countByPartition(topicName: TopicName): Result<Map<PartitionId, Long>> {
return Result.success(emptyMap())
}
override suspend fun partitions(topicName: TopicName): Result<List<Partition>> {
return Result.success(listOf())
}
override suspend fun compressionType(topicName: TopicName): Result<CompressionType> {
return Result.failure(Exception("Not supported for pulsar"))
}
override suspend fun topics(filter: String?): Result<List<LightTopic>> = runCatching {
client.tenants().tenants.flatMap { tenant ->
client.namespaces().getNamespaces(tenant).flatMap { namespace ->
client.topics().getList(namespace).map { topicName ->
val schema = kotlin.runCatching { client.schemas().getSchemaInfo(topicName).type.name }.getOrNull()
val subscriptions = client.topics().getSubscriptions(topicName)
LightTopic(
TopicName(topicName),
mapOf("schema" to schema, "subscriptions" to subscriptions.size.toString()),
)
}
}
}
}
override suspend fun config(topicName: TopicName): Result<TopicConfigs> = runCatching {
val internal: String = client.topics().getInternalInfo(topicName.value)
println(internal)
val stats: TopicStats = client.topics().getStats(topicName.value)
val getInternalStats: PersistentTopicInternalStats = client.topics().getInternalStats(topicName.value)
val config = mapOf(
"subscriptions" to stats.subscriptions.size.toString(),
"lastCompactionSucceedTimestamp" to stats.compaction.lastCompactionSucceedTimestamp.toString(),
"lastCompactionFailedTimestamp" to stats.compaction.lastCompactionFailedTimestamp.toString(),
"lastCompactionDurationTimeInMills" to stats.compaction.lastCompactionDurationTimeInMills.toString(),
"lastCompactionRemovedEventCount" to stats.compaction.lastCompactionRemovedEventCount.toString(),
"topicEpoch" to stats.topicEpoch.toString(),
"numberOfEntries" to getInternalStats.numberOfEntries.toString(),
"lastLedgerCreatedTimestamp" to getInternalStats.lastLedgerCreatedTimestamp.toString(),
"currentLedgerSize" to getInternalStats.currentLedgerSize.toString(),
"entriesAddedCounter" to getInternalStats.entriesAddedCounter.toString(),
"lastConfirmedEntry" to getInternalStats.lastConfirmedEntry.toString(),
"state" to getInternalStats.state.toString(),
"pendingAddEntriesCount" to getInternalStats.pendingAddEntriesCount.toString(),
"totalSize" to getInternalStats.totalSize.toString(),
"waitingCursorsCount" to getInternalStats.waitingCursorsCount.toString(),
)
TopicConfigs(topicName, config)
}
override suspend fun topic(topicName: TopicName): Result<ExtendedTopic> = runCatching {
val internal: String = client.topics().getInternalInfo(topicName.value)
val stats: TopicStats = client.topics().getStats(topicName.value)
val getInternalStats: PersistentTopicInternalStats = client.topics().getInternalStats(topicName.value)
// val getPartitionedInternalStats: PartitionedTopicInternalStats =
// client.topics().getPartitionedInternalStats(tableName.value)
val lastMessageId: MessageId = client.topics().getLastMessageId(topicName.value)
println(lastMessageId)
println(internal)
val schema = kotlin.runCatching { client.schemas().getSchemaInfo(topicName.value).type.name }.getOrNull()
ExtendedTopic(
name = topicName,
0, 0, 0, "", 0, "", 0, "",
props = mapOf(
"schema" to schema,
"subscriptions" to stats.subscriptions.size.toString(),
"lastCompactionSucceedTimestamp" to stats.compaction.lastCompactionSucceedTimestamp.toString(),
"lastCompactionFailedTimestamp" to stats.compaction.lastCompactionFailedTimestamp.toString(),
"lastCompactionDurationTimeInMills" to stats.compaction.lastCompactionDurationTimeInMills.toString(),
"lastCompactionRemovedEventCount" to stats.compaction.lastCompactionRemovedEventCount.toString(),
"topicEpoch" to stats.topicEpoch.toString(),
"lastMessageId" to lastMessageId.toString(),
"numberOfEntries" to getInternalStats.numberOfEntries.toString(),
"lastLedgerCreatedTimestamp" to getInternalStats.lastLedgerCreatedTimestamp.toString(),
"currentLedgerSize" to getInternalStats.currentLedgerSize.toString(),
"entriesAddedCounter" to getInternalStats.entriesAddedCounter.toString(),
"lastConfirmedEntry" to getInternalStats.lastConfirmedEntry.toString(),
"state" to getInternalStats.state.toString(),
"pendingAddEntriesCount" to getInternalStats.pendingAddEntriesCount.toString(),
"totalSize" to getInternalStats.totalSize.toString(),
"waitingCursorsCount" to getInternalStats.waitingCursorsCount.toString(),
),
partitions = emptyList(),
config = emptyMap()
)
}.onFailure { logger.error(it) { "Error fetching table" } }
override suspend fun create(
topicName: TopicName,
partitions: Int,
replicationFactor: Int,
retention: Long?,
compacted: Boolean
): Result<Boolean> = runCatching {
if (partitions > 1)
client.topics().createPartitionedTopicAsync(topicName.value, partitions).await()
else
client.topics().createNonPartitionedTopicAsync(topicName.value).await()
true
}
override suspend fun drop(topicName: TopicName): Result<Boolean> = runCatching {
client.topics().deleteAsync(topicName.value).await()
true
}
override suspend fun truncate(topicName: TopicName): Result<Boolean> = runCatching {
client.topics().truncateAsync(topicName.value).await()
true
}
override suspend fun triggerCompaction(topicName: TopicName): Result<Boolean> = runCatching {
client.topics().triggerCompactionAsync(topicName.value).await()
true
}
override suspend fun expireMessagesForAllSubscriptions(
topicName: TopicName,
time: Duration
): Result<Boolean> = runCatching {
client.topics().expireMessagesForAllSubscriptionsAsync(topicName.value, time.inWholeSeconds).await()
true
}
override suspend fun schema(topicName: TopicName): Result<List<SchemaField>> {
TODO("Not yet implemented")
}
override suspend fun deleteRecords(topicName: TopicName, partitions: Set<Int>, offset: Long): Result<Unit> {
return Result.success(Unit)
}
override suspend fun repartition(topicName: TopicName, count: Int): Result<Boolean> = runCatching {
client.topics().updatePartitionedTopicAsync(topicName.value, count).await()
true
}
override suspend fun setConfig(topicName: TopicName, key: String, value: String): Result<Boolean> = false.success()
override suspend fun assignPartitions(
topicName: TopicName,
assignments: Map<PartitionId, Set<BrokerId>>
): Result<Boolean> = Result.success(false)
override suspend fun insert(topicName: TopicName, req: InsertRecordRequest): Result<Boolean> {
TODO("Not yet implemented")
}
override suspend fun partitionMessageDistribution(topicName: TopicName): Result<PartitionMessageDistribution> {
return Result.success(PartitionMessageDistribution(topicName, emptyList()))
}
override suspend fun brokerPartitionDistribution(topicName: TopicName): Result<PartitionBrokerSpread> {
return Result.success(PartitionBrokerSpread(topicName, 0, 0, 0, 0, emptyList()))
}
override suspend fun replicationFactor(topicName: TopicName): Result<Int> {
return Result.success(0)
}
override suspend fun setReplicationFactor(topicName: TopicName, count: Int): Result<Boolean> {
return Result.success(false)
}
override suspend fun setCompression(topicName: TopicName, compressionType: String): Result<Boolean> {
return Result.success(false)
}
override suspend fun electLeaders(
topicName: TopicName,
electionType: ElectionType
): Result<Unit> {
return Result.success(Unit)
}
override suspend fun specifyLeader(topicName: TopicName, partitionId: PartitionId, leader: BrokerId): Result<Unit> {
return Result.success(Unit)
}
}
| apache-2.0 | e2172a00399b0628a22e1c9ca7b28cd7 | 42.363265 | 119 | 0.724774 | 4.753468 | false | false | false | false |
dleppik/EgTest | kotlin-example/src/main/java/com/vocalabs/egtest/example/kotlin/KotlinStaticExample.kt | 1 | 1091 | package com.vocalabs.egtest.example.kotlin
import com.vocalabs.egtest.annotation.Eg
import com.vocalabs.egtest.annotation.EgMatch
import com.vocalabs.egtest.annotation.EgNoMatch
object KotlinStaticExample {
@EgMatch("[email protected]")
@EgMatch("[email protected]")
@EgNoMatch("dleppik")
@EgNoMatch("dleppik@[email protected]")
@EgNoMatch("David Leppik <[email protected]>")
val SIMPLE_EMAIL_RE = """^[\w+.\-=&|/?!#$*]+@[\w.\-]+\.[\w]+$""".toRegex()
@EgMatch("[email protected]")
fun matchesEmail(s: String): Boolean = SIMPLE_EMAIL_RE.matches(s)
@Eg(given = ["listOf<String>()"], returns = "listOf<String>()")
@Eg(given = ["""listOf("Cat", "Dog", "Octopus")"""], returns = """listOf("a", "o", "Oou")""")
fun vowels(words: Collection<String>): Collection<String> {
val vowelSet = setOf('a', 'e', 'i', 'o', 'u')
return words.map { s -> s.filter { vowelSet.contains(it.toLowerCase()) } }
}
@Eg(given = ["1.0"], returns = "0.333", delta = 0.001)
fun oneThird(num: Double): Double = num / 3.0
} | apache-2.0 | 8b4264a07889d16debcaa07a8705401d | 38 | 97 | 0.627864 | 3.296073 | false | true | false | false |
deianvn/misc | cetus/src/main/kotlin/net/rizov/cetus/runner/line/NumericLiteral.kt | 1 | 360 | package net.rizov.cetus.runner.line
import net.rizov.cetus.runner.Token
abstract class NumericLiteral(private val value: String) : Token(value) {
fun getByte() = value.toByte()
fun getShort() = value.toShort()
fun getInt() = value.toInt()
fun getLong() = value.toLong()
fun getFloat() = value.toFloat()
fun getDouble() = value.toDouble()
}
| apache-2.0 | b0f54df7083678d59f5d35a1a627f9ea | 19 | 73 | 0.694444 | 3.461538 | false | false | false | false |
sabi0/intellij-community | python/src/com/jetbrains/python/testing/PyTestLegacyInterop.kt | 1 | 13847 | // Copyright 2000-2018 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.jetbrains.python.testing
import com.google.common.base.Preconditions
import com.intellij.execution.RunManager
import com.intellij.execution.actions.RunConfigurationProducer
import com.intellij.execution.configurations.RunConfiguration
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.diagnostic.Logger
import com.intellij.openapi.extensions.Extensions
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.impl.ProjectLifecycleListener
import com.intellij.openapi.startup.StartupManager
import com.intellij.openapi.util.JDOMExternalizable
import com.intellij.openapi.util.registry.Registry
import com.intellij.openapi.vfs.LocalFileSystem
import com.intellij.openapi.vfs.VirtualFile
import com.intellij.psi.PsiDocumentManager
import com.jetbrains.python.psi.PyFile
import com.jetbrains.python.psi.PyQualifiedNameOwner
import com.jetbrains.python.psi.PyUtil
import com.jetbrains.python.psi.types.TypeEvalContext
import com.jetbrains.python.run.PythonConfigurationFactoryBase
import com.jetbrains.python.run.targetBasedConfiguration.PyRunTargetVariant
import com.jetbrains.python.testing.AbstractPythonLegacyTestRunConfiguration.TestType
import com.jetbrains.python.testing.doctest.PythonDocTestConfigurationProducer
import com.jetbrains.python.testing.nosetestLegacy.PythonNoseTestRunConfiguration
import com.jetbrains.python.testing.pytestLegacy.PyTestRunConfiguration
import com.jetbrains.python.testing.unittestLegacy.PythonUnitTestRunConfiguration
import org.jdom.Element
import javax.swing.SwingUtilities
/**
* Module to support legacy configurations.
*
* When legacy configuration is ought to be dropped, just remove this module and all references to it.
* It supports switching back to old runners (see [isNewTestsModeEnabled]) and importing old configs to new one.
* [projectInitialized] shall be called for that.
*
* @author Ilya.Kazakevich
*/
/**
* @return is new mode enabled or not
*/
fun isNewTestsModeEnabled(): Boolean = Registry.`is`("python.tests.enableUniversalTests")
/**
* Should be installed as application component
*/
class PyTestLegacyInteropInitializer {
init {
disableUnneededConfigurationProducer()
// Delegate to project initialization
ApplicationManager.getApplication().messageBus.connect().subscribe(ProjectLifecycleListener.TOPIC, object : ProjectLifecycleListener {
override fun projectComponentsInitialized(project: Project) {
if (project.isDefault) return
if (project.isInitialized) {
projectInitialized(project)
return
}
StartupManager.getInstance(project).runWhenProjectIsInitialized { projectInitialized(project) }
}
})
}
}
/**
* To be called when project initialized to copy old configs to new one
*/
private fun projectInitialized(project: Project) {
assert(project.isInitialized) { "Project is not initialized yet" }
val manager = RunManager.getInstance(project)
val configurations = factories.map { manager.getConfigurationTemplate(it) } + manager.allConfigurationsList
configurations.filterIsInstance(PyAbstractTestConfiguration::class.java).forEach {
it.legacyConfigurationAdapter.copyFromLegacyIfNeeded()
}
}
/**
* It is impossible to have 2 producers for one type (class cast exception may take place), so we need to disable either old or new one
*/
private fun disableUnneededConfigurationProducer() {
val extensionPoint = Extensions.getArea(null).getExtensionPoint(RunConfigurationProducer.EP_NAME)
val newMode = isNewTestsModeEnabled()
extensionPoint.extensions.filter { it !is PythonDocTestConfigurationProducer }.forEach {
if ((it is PyTestsConfigurationProducer && !newMode) ||
(it is PythonTestLegacyConfigurationProducer<*> && newMode)) {
extensionPoint.unregisterExtension(it)
Logger.getInstance("PyTestLegacyInterop").info("Disabling " + it)
}
}
}
private fun getVirtualFileByPath(path: String): VirtualFile? {
return LocalFileSystem.getInstance().findFileByPath(path) ?: return null
}
private fun VirtualFile.asPyFile(project: Project): PyFile? {
assert(project.isInitialized, { "This function can't be used on uninitialized project" })
if (this.isDirectory) {
return null
}
var file: PyFile? = null
ApplicationManager.getApplication()
.invokeAndWait({
val document = FileDocumentManager.getInstance().getDocument(this)
if (document != null) {
file = PyUtil.`as`(PsiDocumentManager.getInstance(project).getPsiFile(document), PyFile::class.java)
}
})
return file
}
/**
* Manages legacy-to-new configuration binding
* Attach it to new configuration and mark with [com.jetbrains.reflection.DelegationProperty]
*/
class PyTestLegacyConfigurationAdapter<in T : PyAbstractTestConfiguration>(newConfig: T)
: JDOMExternalizable {
private val configManager: LegacyConfigurationManager<*, *>?
private val project = newConfig.project
/**
* Does configuration contain legacy information or was it created as new config?
* Null is unknown
*/
private var containsLegacyInformation: Boolean? = null
/**
* True if configuration [containsLegacyInformation] and this information is already copied to new config, so it should not be
* copied second time.
*
* Null means "false" and used here to prevent saving useless "false" value in .xml for new configurations.
*/
@ConfigField
var legacyInformationCopiedToNew: Boolean? = null
init {
when (newConfig) {
is PyTestConfiguration -> {
configManager = LegacyConfigurationManagerPyTest(newConfig)
}
is PyNoseTestConfiguration -> {
configManager = LegacyConfigurationManagerNose(newConfig)
}
is PyUnitTestConfiguration -> {
configManager = LegacyConfigurationManagerUnit(newConfig)
}
else -> {
configManager = null
}
}
}
override fun readExternal(element: Element) {
val configManager = configManager
if (configManager == null) {
containsLegacyInformation = false
return
}
val legacyConfig = configManager.legacyConfig
if (legacyConfig is RunConfiguration) {
(legacyConfig as RunConfiguration).readExternal(element)
}
else {
(legacyConfig as JDOMExternalizable).readExternal(element)
}
containsLegacyInformation = configManager.isLoaded()
if (project.isInitialized) {
copyFromLegacyIfNeeded()
}
}
override fun writeExternal(element: Element) {
if (containsLegacyInformation ?: return) {
val legacyConfig = configManager?.legacyConfig
if (legacyConfig is RunConfiguration) {
(legacyConfig as RunConfiguration).writeExternal(element)
}
else {
(legacyConfig as JDOMExternalizable).writeExternal(element)
}
}
}
fun copyFromLegacyIfNeeded() {
assert(project.isInitialized, { "Initialized project required" })
if (containsLegacyInformation ?: return && !(legacyInformationCopiedToNew ?: false) && SwingUtilities.isEventDispatchThread()) {
configManager?.copyFromLegacy()
legacyInformationCopiedToNew = true
}
}
}
/**
* Manages legacy-to-new configuration copying process
*/
private abstract class LegacyConfigurationManager<
LEGACY_CONF_T : AbstractPythonLegacyTestRunConfiguration<LEGACY_CONF_T>,
out NEW_CONF_T : PyAbstractTestConfiguration
>(legacyConfFactory: PythonConfigurationFactoryBase, val newConfig: NEW_CONF_T) {
@Suppress("UNCHECKED_CAST") // Factory-to-config mapping should be checked by developer: createTemplateConfiguration is not generic
val legacyConfig = legacyConfFactory.createTemplateConfiguration(newConfig.project) as LEGACY_CONF_T
/**
* Checks test type to interpret target correctly. It could be function, class or method
*/
private fun getElementFromConfig(script: PyFile): PyQualifiedNameOwner? {
if (legacyConfig.testType == TestType.TEST_FUNCTION) {
return script.findTopLevelFunction(legacyConfig.methodName)
}
val clazz = script.findTopLevelClass(legacyConfig.className) ?: return null
if (legacyConfig.testType == TestType.TEST_CLASS) {
return clazz
}
return clazz.findMethodByName(legacyConfig.methodName, true, TypeEvalContext.userInitiated(legacyConfig.project, script))
}
/**
* If one of these fields is not empty -- legacy configuration makes sence
*/
open protected fun getFieldsToCheckForEmptiness() = listOf(legacyConfig.scriptName, legacyConfig.className, legacyConfig.methodName)
/**
* @return true of legacy configuration loaded, false if configuration is pure new
*/
fun isLoaded() = getFieldsToCheckForEmptiness().find { !it.isNullOrBlank() } != null
/**
* This method should be called from AWT thread only
*
* Copies config from legacy to new configuration.
* Used by all runners but pytest which has very different settings
*/
open fun copyFromLegacy() {
Preconditions.checkState(SwingUtilities.isEventDispatchThread(), "Run on AWT thread only")
when (legacyConfig.testType) {
TestType.TEST_CLASS, TestType.TEST_FUNCTION, TestType.TEST_METHOD -> {
val virtualFile = getVirtualFileByPath(legacyConfig.scriptName) ?: return
val pyFile = virtualFile.asPyFile(legacyConfig.project) ?: return
val qualifiedName = getElementFromConfig(pyFile)?.qualifiedName ?: return
newConfig.target.targetType = PyRunTargetVariant.PYTHON
newConfig.target.target = qualifiedName
}
TestType.TEST_FOLDER -> {
newConfig.target.targetType = PyRunTargetVariant.PATH
newConfig.target.target = legacyConfig.folderName
}
TestType.TEST_SCRIPT -> {
newConfig.target.targetType = PyRunTargetVariant.PATH
newConfig.target.target = legacyConfig.scriptName
}
else -> {
Logger.getInstance(LegacyConfigurationManager::class.java).warn("Unknown type {${legacyConfig.testType}")
}
}
}
}
private class LegacyConfigurationManagerPyTest(newConfig: PyTestConfiguration) :
LegacyConfigurationManager<PyTestRunConfiguration, PyTestConfiguration>(
PythonTestConfigurationType.getInstance().LEGACY_PYTEST_FACTORY, newConfig) {
/**
* In Pytest target is provided as keywords, joined with "and".
* "function_foo", "MyClass" or "MyClass and my_method" could be used here.
*/
private val KEYWORDS_SPLIT_PATTERN = java.util.regex.Pattern.compile("\\s+and\\s+", java.util.regex.Pattern.CASE_INSENSITIVE)
override fun getFieldsToCheckForEmptiness() = super.getFieldsToCheckForEmptiness() + listOf(legacyConfig.keywords, legacyConfig.testToRun)
override fun copyFromLegacy() {
// Do not call parent since target is always provided as testToRun here
newConfig.additionalArguments = legacyConfig.params
// Default is PATH
newConfig.target.targetType = PyRunTargetVariant.PATH
val oldKeywords = legacyConfig.keywords
val virtualFile = getVirtualFileByPath(legacyConfig.testToRun) ?: return
if (virtualFile.isDirectory) {
// If target is directory, then it can't point to any symbol
newConfig.target.target = virtualFile.path
newConfig.target.targetType = PyRunTargetVariant.PATH
newConfig.keywords = oldKeywords
return
}
// If it is file -- it could be file, class, method or functions (see keywords)
val script = virtualFile.asPyFile(newConfig.project) ?: return
val keywordsList = oldKeywords.split(KEYWORDS_SPLIT_PATTERN).filter(String::isNotEmpty)
if (keywordsList.isEmpty() || keywordsList.size > 2 || keywordsList.find { it.contains(" ") } != null) {
//Give up with interpreting
newConfig.keywords = oldKeywords
newConfig.target.target = script.virtualFile.path
newConfig.target.targetType = PyRunTargetVariant.PATH
return
}
val classOrFunctionName = keywordsList[0]
val clazz = script.findTopLevelClass(classOrFunctionName)
if (keywordsList.size == 1) { // Class or function
val classOrFunction = PyUtil.`as`(clazz ?:
script.findTopLevelFunction(classOrFunctionName),
PyQualifiedNameOwner::class.java) ?: return
newConfig.target.target = classOrFunction.qualifiedName ?: return
newConfig.target.targetType = PyRunTargetVariant.PYTHON
}
if (keywordsList.size == 2) { // Class and method
clazz ?: return
val method = clazz.findMethodByName(keywordsList[1], true, TypeEvalContext.userInitiated(newConfig.project, script)) ?: return
newConfig.target.target = method.qualifiedName ?: return
newConfig.target.targetType = PyRunTargetVariant.PYTHON
}
}
}
private class LegacyConfigurationManagerUnit(newConfig: PyUnitTestConfiguration) :
LegacyConfigurationManager<PythonUnitTestRunConfiguration, PyUnitTestConfiguration>(
PythonTestConfigurationType.getInstance().LEGACY_UNITTEST_FACTORY, newConfig) {
override fun copyFromLegacy() {
super.copyFromLegacy()
newConfig.additionalArguments = legacyConfig.params
newConfig.pattern = legacyConfig.pattern
}
}
private class LegacyConfigurationManagerNose(newConfig: PyNoseTestConfiguration) :
LegacyConfigurationManager<PythonNoseTestRunConfiguration, PyNoseTestConfiguration>(
PythonTestConfigurationType.getInstance().LEGACY_NOSETEST_FACTORY, newConfig) {
override fun copyFromLegacy() {
super.copyFromLegacy()
newConfig.additionalArguments = legacyConfig.params
}
}
| apache-2.0 | fbcc2ac273aacb52eba8304aba0d2bd9 | 38.562857 | 140 | 0.744349 | 5.138033 | false | true | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.