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 |
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Thelonedevil/TLDMaths | TLDMaths/src/main/kotlin/uk/tldcode/math/tldmaths/biginteger/Operaters.kt | 1 | 657 | package uk.tldcode.math.tldmaths.biginteger
import java.math.BigInteger
operator fun BigInteger.inc(): BigInteger = this + BigInteger.ONE
operator fun BigInteger.dec(): BigInteger = this - BigInteger.ONE
operator fun BigInteger.rangeTo(other: BigInteger): BigIntegerRange = BigIntegerRange(this, other)
infix fun BigInteger.until(other: BigInteger): BigIntegerRange = this..other - BigInteger.ONE
infix fun BigInteger.downTo(other: BigInteger): BigIntegerProgression = BigIntegerProgression.fromClosedRange(this, other, BigInteger.valueOf(-1))
infix fun BigInteger.downtil(other: BigInteger): BigIntegerProgression = this downTo other + BigInteger.ONE
| apache-2.0 | e30a102f65f9d867e3c8c6d5e35f5386 | 49.538462 | 146 | 0.811263 | 4.692857 | false | false | false | false |
Fi5t/Preference | preference/src/main/kotlin/Preferences.kt | 1 | 1275 | package ru.freedomlogic.preference
import android.content.Context
import android.preference.PreferenceManager
import android.content.SharedPreferences
private val defaultInit: Any.() -> Unit = {}
public fun SharedPreferences.getString(key: String, defValue: String = ""): String = getString(key, defValue)
public fun SharedPreferences.getStringSet(key: String, defValues: Set<String> = emptySet()): Set<String> = getStringSet(key, defValues)
public fun SharedPreferences.getInt(key: String, defValue: Int = 0): Int = getInt(key, defValue)
public fun SharedPreferences.getLong(key: String, defValue: Long = 0): Long = getLong(key, defValue)
public fun SharedPreferences.getFloat(key: String, defValue: Float = 0.0f): Float = getFloat(key, defValue)
public fun SharedPreferences.getBoolean(key: String, defValue: Boolean = false): Boolean = getBoolean(key, defValue)
public fun Context.preferences(init: SharedPreferences.() -> Unit = defaultInit): SharedPreferences {
val defaultPreferences = PreferenceManager.getDefaultSharedPreferences(this)
defaultPreferences.init()
return defaultPreferences
}
public fun SharedPreferences.onChanged(listener: (SharedPreferences?, key:String?) -> Unit): Unit
= registerOnSharedPreferenceChangeListener(listener)
| apache-2.0 | e704cc1cf5ae67b39c01bae3201f0bc6 | 52.125 | 135 | 0.783529 | 4.67033 | false | false | false | false |
awsdocs/aws-doc-sdk-examples | kotlin/services/eventbridge/src/main/kotlin/com/kotlin/eventbridge/DeleteRule.kt | 1 | 1895 | // snippet-sourcedescription:[DeleteRule.kt demonstrates how to delete an Amazon EventBridge rule.]
// snippet-keyword:[AWS SDK for Kotlin]
// snippet-service:[Amazon EventBridge]
/*
Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package com.kotlin.eventbridge
// snippet-start:[eventbridge.kotlin._delete_rule.import]
import aws.sdk.kotlin.services.eventbridge.EventBridgeClient
import aws.sdk.kotlin.services.eventbridge.model.DeleteRuleRequest
import aws.sdk.kotlin.services.eventbridge.model.DisableRuleRequest
import kotlin.system.exitProcess
// snippet-end:[eventbridge.kotlin._delete_rule.import]
/**
Before running this Kotlin code example, set up your development environment,
including your credentials.
For more information, see the following documentation topic:
https://docs.aws.amazon.com/sdk-for-kotlin/latest/developer-guide/setup.html
*/
suspend fun main(args: Array<String>) {
val usage = """
Usage:
<ruleName>
Where:
ruleName - the name of the rule.
"""
if (args.size != 1) {
println(usage)
exitProcess(0)
}
val ruleName = args[0]
deleteEBRule(ruleName)
}
// snippet-start:[eventbridge.kotlin._delete_rule.main]
suspend fun deleteEBRule(ruleName: String) {
val request = DisableRuleRequest {
name = ruleName
eventBusName = "default"
}
EventBridgeClient { region = "us-west-2" }.use { eventBrClient ->
eventBrClient.disableRule(request)
val ruleRequest = DeleteRuleRequest {
name = ruleName
eventBusName = "default"
}
eventBrClient.deleteRule(ruleRequest)
println("Rule $ruleName was successfully deleted!")
}
}
// snippet-end:[eventbridge.kotlin._delete_rule.main]
| apache-2.0 | 5cb09b9637efedd97622575333214447 | 27.153846 | 99 | 0.678628 | 3.947917 | false | false | false | false |
google/intellij-community | platform/platform-impl/src/com/intellij/openapi/wm/impl/welcomeScreen/FlatWelcomeFrame.kt | 3 | 18737 | // 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
import com.intellij.icons.AllIcons
import com.intellij.ide.AppLifecycleListener
import com.intellij.ide.DataManager
import com.intellij.ide.IdeBundle
import com.intellij.ide.RecentProjectListActionProvider
import com.intellij.ide.dnd.FileCopyPasteUtil
import com.intellij.ide.impl.ProjectUtil
import com.intellij.ide.lightEdit.LightEditServiceListener
import com.intellij.ide.plugins.PluginDropHandler
import com.intellij.ide.ui.LafManagerListener
import com.intellij.idea.SplashManager
import com.intellij.notification.NotificationsManager
import com.intellij.notification.impl.NotificationsManagerImpl
import com.intellij.openapi.Disposable
import com.intellij.openapi.MnemonicHelper
import com.intellij.openapi.actionSystem.*
import com.intellij.openapi.application.ApplicationManager
import com.intellij.openapi.application.ModalityState
import com.intellij.openapi.project.Project
import com.intellij.openapi.project.ProjectManager
import com.intellij.openapi.project.ProjectManagerListener
import com.intellij.openapi.util.Disposer
import com.intellij.openapi.util.Pair
import com.intellij.openapi.util.SystemInfoRt
import com.intellij.openapi.util.WindowStateService
import com.intellij.openapi.wm.IdeFrame
import com.intellij.openapi.wm.StatusBar
import com.intellij.openapi.wm.impl.IdeFrameDecorator
import com.intellij.openapi.wm.impl.IdeGlassPaneImpl
import com.intellij.openapi.wm.impl.IdeMenuBar
import com.intellij.openapi.wm.impl.customFrameDecorations.header.CustomFrameDialogContent.Companion.getCustomContentHolder
import com.intellij.openapi.wm.impl.customFrameDecorations.header.DefaultFrameHeader
import com.intellij.openapi.wm.impl.welcomeScreen.WelcomeScreenComponentFactory.JActionLinkPanel
import com.intellij.ui.*
import com.intellij.ui.components.JBList
import com.intellij.ui.components.JBTextField
import com.intellij.ui.components.labels.ActionLink
import com.intellij.ui.components.panels.NonOpaquePanel
import com.intellij.ui.components.panels.VerticalLayout
import com.intellij.ui.components.panels.Wrapper
import com.intellij.ui.mac.touchbar.Touchbar
import com.intellij.ui.mac.touchbar.TouchbarActionCustomizations
import com.intellij.ui.scale.JBUIScale
import com.intellij.util.IconUtil
import com.intellij.util.ui.*
import com.intellij.util.ui.accessibility.AccessibleContextAccessor
import com.intellij.util.ui.update.UiNotifyConnector
import com.jetbrains.JBR
import kotlinx.coroutines.launch
import net.miginfocom.swing.MigLayout
import java.awt.*
import java.awt.dnd.*
import java.awt.event.*
import javax.swing.*
import javax.swing.event.ListDataEvent
import javax.swing.event.ListDataListener
/**
* @author Konstantin Bulenkov
*/
@Suppress("LeakingThis")
open class FlatWelcomeFrame @JvmOverloads constructor(
suggestedScreen: AbstractWelcomeScreen? = if (USE_TABBED_WELCOME_SCREEN) TabbedWelcomeScreen() else null
) : JFrame(), IdeFrame, Disposable, AccessibleContextAccessor {
val screen: AbstractWelcomeScreen
private val content: Wrapper
private var balloonLayout: WelcomeBalloonLayoutImpl?
private var isDisposed = false
private var header: DefaultFrameHeader? = null
companion object {
@JvmField
var USE_TABBED_WELCOME_SCREEN = java.lang.Boolean.parseBoolean(System.getProperty("use.tabbed.welcome.screen", "true"))
const val BOTTOM_PANEL = "BOTTOM_PANEL"
@JvmField
val DEFAULT_HEIGHT = if (USE_TABBED_WELCOME_SCREEN) 650 else 460
const val MAX_DEFAULT_WIDTH = 800
private fun saveSizeAndLocation(location: Rectangle) {
val middle = Point(location.x + location.width / 2, location.y + location.height / 2)
WindowStateService.getInstance().putLocation(WelcomeFrame.DIMENSION_KEY, middle)
WindowStateService.getInstance().putSize(WelcomeFrame.DIMENSION_KEY, location.size)
}
@JvmStatic
fun getPreferredFocusedComponent(pair: Pair<JPanel?, JBList<AnAction?>>): JComponent {
if (pair.second.model.size == 1) {
val textField = UIUtil.uiTraverser(pair.first).filter(JBTextField::class.java).first()
if (textField != null) {
return textField
}
}
return pair.second
}
}
init {
SplashManager.hideBeforeShow(this)
val rootPane = getRootPane()
balloonLayout = WelcomeBalloonLayoutImpl(rootPane, JBUI.insets(8))
screen = suggestedScreen ?: FlatWelcomeScreen(frame = this)
content = Wrapper()
contentPane = content
if (IdeFrameDecorator.isCustomDecorationActive()) {
header = DefaultFrameHeader(this)
content.setContent(getCustomContentHolder(this, screen.welcomePanel, header!!))
}
else {
if (USE_TABBED_WELCOME_SCREEN && SystemInfoRt.isMac) {
rootPane.jMenuBar = WelcomeFrameMenuBar().setFrame(this)
}
content.setContent(screen.welcomePanel)
}
val glassPane = IdeGlassPaneImpl(rootPane)
setGlassPane(glassPane)
glassPane.isVisible = false
updateComponentsAndResize()
// at this point, window insets may be unavailable, so we need to resize the window when it is shown
UiNotifyConnector.doWhenFirstShown(this, ::pack)
val app = ApplicationManager.getApplication()
val connection = app.messageBus.connect(this)
connection.subscribe(ProjectManager.TOPIC, object : ProjectManagerListener {
@Suppress("OVERRIDE_DEPRECATION")
override fun projectOpened(project: Project) {
Disposer.dispose(this@FlatWelcomeFrame)
}
})
connection.subscribe(LightEditServiceListener.TOPIC, object : LightEditServiceListener {
override fun lightEditWindowOpened(project: Project) {
Disposer.dispose(this@FlatWelcomeFrame)
}
})
connection.subscribe(AppLifecycleListener.TOPIC, object : AppLifecycleListener {
override fun appClosing() {
saveSizeAndLocation(bounds)
}
})
connection.subscribe(LafManagerListener.TOPIC, LafManagerListener {
if (balloonLayout != null) {
Disposer.dispose(balloonLayout!!)
}
balloonLayout = WelcomeBalloonLayoutImpl(rootPane, JBUI.insets(8))
updateComponentsAndResize()
repaint()
})
addComponentListener(object : ComponentAdapter() {
override fun componentResized(componentEvent: ComponentEvent) {
if (WindowStateService.getInstance().getSize(WelcomeFrame.DIMENSION_KEY) != null) {
saveSizeAndLocation(bounds)
}
}
})
setupCloseAction()
MnemonicHelper.init(this)
Disposer.register(app, this)
UIUtil.decorateWindowHeader(getRootPane())
ToolbarUtil.setTransparentTitleBar(this, getRootPane()) { runnable -> Disposer.register(this) { runnable.run() } }
app.invokeLater({ (NotificationsManager.getNotificationsManager() as NotificationsManagerImpl).dispatchEarlyNotifications() },
ModalityState.NON_MODAL)
}
protected open fun setupCloseAction() {
WelcomeFrame.setupCloseAction(this)
}
private fun updateComponentsAndResize() {
val defaultHeight = DEFAULT_HEIGHT
if (IdeFrameDecorator.isCustomDecorationActive()) {
val backgroundColor = UIManager.getColor("WelcomeScreen.background")
if (backgroundColor != null) {
header!!.background = backgroundColor
}
}
else {
if (USE_TABBED_WELCOME_SCREEN && SystemInfoRt.isMac) {
rootPane.jMenuBar = WelcomeFrameMenuBar().setFrame(this)
}
content.setContent(screen.welcomePanel)
}
if (USE_TABBED_WELCOME_SCREEN) {
val defaultSize = JBUI.size(MAX_DEFAULT_WIDTH, defaultHeight)
preferredSize = WindowStateService.getInstance().getSize(WelcomeFrame.DIMENSION_KEY) ?: defaultSize
minimumSize = defaultSize
}
else {
val width = if (RecentProjectListActionProvider.getInstance().getActions(addClearListItem = false).isEmpty()) {
666
}
else {
MAX_DEFAULT_WIDTH
}
preferredSize = JBUI.size(width, defaultHeight)
}
isResizable = USE_TABBED_WELCOME_SCREEN
val size = preferredSize
val location = WindowStateService.getInstance().getLocation(WelcomeFrame.DIMENSION_KEY)
val screenBounds = ScreenUtil.getScreenRectangle(location ?: Point(0, 0))
setBounds(
screenBounds.x + (screenBounds.width - size.width) / 2,
screenBounds.y + (screenBounds.height - size.height) / 3,
size.width,
size.height
)
UIUtil.decorateWindowHeader(getRootPane())
title = ""
title = welcomeFrameTitle
AppUIUtil.updateWindowIcon(this)
}
override fun addNotify() {
if (IdeFrameDecorator.isCustomDecorationActive()) {
JBR.getCustomWindowDecoration().setCustomDecorationEnabled(this, true)
}
super.addNotify()
}
override fun dispose() {
if (isDisposed) {
return
}
isDisposed = true
super.dispose()
balloonLayout?.let {
balloonLayout = null
Disposer.dispose(it)
}
Disposer.dispose(screen)
WelcomeFrame.resetInstance()
}
override fun getStatusBar(): StatusBar? = null
override fun getCurrentAccessibleContext() = accessibleContext
protected val welcomeFrameTitle: String
get() = WelcomeScreenComponentFactory.getApplicationTitle()
@Suppress("unused")
protected fun extendActionsGroup(panel: JPanel?) {
}
@Suppress("unused")
protected fun onFirstActionShown(action: Component) {
}
override fun getBalloonLayout(): BalloonLayout? = balloonLayout
override fun suggestChildFrameBounds(): Rectangle = bounds
override fun getProject(): Project? {
return if (ApplicationManager.getApplication().isDisposed) null else ProjectManager.getInstance().defaultProject
}
override fun setFrameTitle(title: String) {
setTitle(title)
}
override fun getComponent(): JComponent = getRootPane()
private class FlatWelcomeScreen(private val frame: FlatWelcomeFrame) : AbstractWelcomeScreen() {
private val touchbarActions = DefaultActionGroup()
private var inDnd = false
init {
background = WelcomeScreenUIManager.getMainBackground()
if (RecentProjectListActionProvider.getInstance().getActions(addClearListItem = false, useGroups = true).isNotEmpty()) {
val recentProjects = WelcomeScreenComponentFactory.createRecentProjects(this)
add(recentProjects, BorderLayout.WEST)
val projectsList = UIUtil.findComponentOfType(recentProjects, JList::class.java)
if (projectsList != null) {
projectsList.model.addListDataListener(object : ListDataListener {
override fun intervalAdded(e: ListDataEvent) {}
override fun intervalRemoved(e: ListDataEvent) {
removeIfNeeded()
}
private fun removeIfNeeded() {
if (RecentProjectListActionProvider.getInstance().getActions(addClearListItem = false, useGroups = true).isEmpty()) {
[email protected](recentProjects)
[email protected]()
[email protected]()
}
}
override fun contentsChanged(e: ListDataEvent) {
removeIfNeeded()
}
})
projectsList.addFocusListener(object : FocusListener {
override fun focusGained(e: FocusEvent) {
projectsList.repaint()
}
override fun focusLost(e: FocusEvent) {
projectsList.repaint()
}
})
}
}
add(createBody(), BorderLayout.CENTER)
dropTarget = DropTarget(this, object : DropTargetAdapter() {
override fun dragEnter(e: DropTargetDragEvent) {
setDnd(true)
}
override fun dragExit(e: DropTargetEvent) {
setDnd(false)
}
override fun drop(e: DropTargetDropEvent) {
setDnd(false)
e.acceptDrop(DnDConstants.ACTION_COPY_OR_MOVE)
val transferable = e.transferable
val list = FileCopyPasteUtil.getFiles(transferable)
if (list != null && list.size > 0) {
val pluginHandler = PluginDropHandler()
if (!pluginHandler.canHandle(transferable, null) || !pluginHandler.handleDrop(transferable, null, null)) {
ApplicationManager.getApplication().coroutineScope.launch {
ProjectUtil.openOrImportFilesAsync(list, "WelcomeFrame")
}
}
e.dropComplete(true)
return
}
e.dropComplete(false)
}
private fun setDnd(dnd: Boolean) {
inDnd = dnd
repaint()
}
})
TouchbarActionCustomizations.setShowText(touchbarActions, true)
Touchbar.setActions(this, touchbarActions)
}
override fun paint(g: Graphics) {
super.paint(g)
if (!inDnd) {
return
}
val bounds = bounds
g.color = JBUI.CurrentTheme.DragAndDrop.Area.BACKGROUND
g.fillRect(bounds.x, bounds.y, bounds.width, bounds.height)
val backgroundBorder = JBUI.CurrentTheme.DragAndDrop.BORDER_COLOR
g.color = backgroundBorder
g.drawRect(bounds.x, bounds.y, bounds.width, bounds.height)
g.drawRect(bounds.x + 1, bounds.y + 1, bounds.width - 2, bounds.height - 2)
val foreground = JBUI.CurrentTheme.DragAndDrop.Area.FOREGROUND
g.color = foreground
val labelFont = StartupUiUtil.getLabelFont()
val font = labelFont.deriveFont(labelFont.size + 5.0f)
val drop = IdeBundle.message("welcome.screen.drop.files.to.open.text")
g.font = font
val dropWidth = g.fontMetrics.stringWidth(drop)
val dropHeight = g.fontMetrics.height
g.drawString(drop, bounds.x + (bounds.width - dropWidth) / 2, (bounds.y + (bounds.height - dropHeight) * 0.45).toInt())
}
private fun createBody(): JComponent {
val panel = NonOpaquePanel(BorderLayout())
panel.add(WelcomeScreenComponentFactory.createLogo(), BorderLayout.NORTH)
touchbarActions.removeAll()
val actionPanel = createQuickStartActionPanel()
panel.add(actionPanel, BorderLayout.CENTER)
touchbarActions.addAll(actionPanel.actions)
panel.add(createSettingsAndDocsPanel(frame), BorderLayout.SOUTH)
return panel
}
private fun createSettingsAndDocsPanel(frame: JFrame): JComponent {
val panel: JPanel = NonOpaquePanel(BorderLayout())
val toolbar = NonOpaquePanel()
toolbar.layout = BoxLayout(toolbar, BoxLayout.X_AXIS)
toolbar.add(WelcomeScreenComponentFactory.createErrorsLink(this))
toolbar.add(createEventsLink())
toolbar.add(WelcomeScreenComponentFactory.createActionLink(
frame,
IdeBundle.message("action.Anonymous.text.configure"),
IdeActions.GROUP_WELCOME_SCREEN_CONFIGURE,
AllIcons.General.GearPlain,
UIUtil.findComponentOfType(frame.rootPane, JList::class.java))
)
toolbar.add(WelcomeScreenComponentFactory.createActionLink(frame, IdeBundle.message("action.GetHelp"), IdeActions.GROUP_WELCOME_SCREEN_DOC, null, null))
panel.add(toolbar, BorderLayout.EAST)
panel.border = JBUI.Borders.empty(0, 0, 8, 11)
return panel
}
private fun createEventsLink(): Component {
return WelcomeScreenComponentFactory.createEventLink(IdeBundle.message("action.Events"), frame)
}
private fun createQuickStartActionPanel(): ActionPanel {
val group = DefaultActionGroup()
val quickStart = ActionManager.getInstance().getAction(IdeActions.GROUP_WELCOME_SCREEN_QUICKSTART) as ActionGroup
WelcomeScreenActionsUtil.collectAllActions(group, quickStart)
@Suppress("SpellCheckingInspection")
val mainPanel = ActionPanel(MigLayout("ins 0, novisualpadding, gap " + JBUI.scale(5) + ", flowy", "push[pref!, center]push"))
mainPanel.isOpaque = false
val panel = object : JPanel(VerticalLayout(JBUI.scale(5))) {
private var firstAction: Component? = null
override fun add(comp: Component): Component {
val cmp = super.add(comp)
if (firstAction == null) {
firstAction = cmp
}
return cmp
}
override fun addNotify() {
super.addNotify()
if (firstAction != null) {
frame.onFirstActionShown(firstAction!!)
}
}
}
panel.isOpaque = false
frame.extendActionsGroup(mainPanel)
mainPanel.add(panel)
for (item in group.getChildren(null)) {
var action = item
val e = AnActionEvent.createFromAnAction(action, null, ActionPlaces.WELCOME_SCREEN, DataManager.getInstance().getDataContext(this))
action.update(e)
val presentation = e.presentation
if (presentation.isVisible) {
var text = presentation.text
if (text != null && text.endsWith("...")) {
text = text.substring(0, text.length - 3)
}
var icon = presentation.icon
if (icon == null || icon.iconHeight != JBUIScale.scale(16) || icon.iconWidth != JBUIScale.scale(16)) {
icon = if (icon == null) JBUIScale.scaleIcon(EmptyIcon.create(16)) else IconUtil.scale(icon, null, 16f / icon.iconWidth)
icon = IconUtil.colorize(icon, JBColor(0x6e6e6e, 0xafb1b3))
}
action = ActionGroupPanelWrapper.wrapGroups(action, this)
val link = ActionLink(text, icon, action, null, ActionPlaces.WELCOME_SCREEN)
link.isFocusable = false // don't allow focus, as the containing panel is going to be focusable
link.setPaintUnderline(false)
link.setNormalColor(WelcomeScreenUIManager.getLinkNormalColor())
val button = JActionLinkPanel(link)
button.border = JBUI.Borders.empty(8, 20)
if (action is WelcomePopupAction) {
button.add(WelcomeScreenComponentFactory.createArrow(link), BorderLayout.EAST)
TouchbarActionCustomizations.setComponent(action, link)
}
WelcomeScreenFocusManager.installFocusable(
frame,
button,
action,
KeyEvent.VK_DOWN,
KeyEvent.VK_UP,
UIUtil.findComponentOfType(frame.component, JList::class.java)
)
panel.add(button)
mainPanel.addAction(action)
}
}
return mainPanel
}
}
}
private class WelcomeFrameMenuBar : IdeMenuBar() {
override fun getMainMenuActionGroup(): ActionGroup {
val manager = ActionManager.getInstance()
return DefaultActionGroup(manager.getAction(IdeActions.GROUP_FILE), manager.getAction(IdeActions.GROUP_HELP_MENU))
}
} | apache-2.0 | 395a3bc63ff6a1cb5461f1a0510ef0c1 | 38.118998 | 158 | 0.702354 | 4.658628 | false | false | false | false |
google/intellij-community | platform/remoteDev-util/src/com/intellij/remoteDev/util/RemoteDevPathConstants.kt | 6 | 488 | package com.intellij.remoteDev.util
const val REMOTE_DEV_CACHE_LOCATION = ".cache/JetBrains/RemoteDev"
const val REMOTE_DEV_IDE_DIR = "$REMOTE_DEV_CACHE_LOCATION/dist"
const val REMOTE_DEV_CUSTOM_IDE_DIR = "$REMOTE_DEV_CACHE_LOCATION/userProvidedDist"
const val REMOTE_DEV_RECENT_PROJECTS_DIR = "$REMOTE_DEV_CACHE_LOCATION/recent"
const val REMOTE_DEV_ACTIVE_PROJECTS_DIR = "$REMOTE_DEV_CACHE_LOCATION/active"
const val REMOTE_DEV_EXPAND_SUCCEEDED_MARKER_FILE_NAME = ".expandSucceeded" | apache-2.0 | 4bcfa8fd0940ad1c33d3460cb0738ed2 | 47.9 | 83 | 0.788934 | 3.365517 | false | false | false | false |
SimpleMobileTools/Simple-Gallery | app/src/main/kotlin/com/simplemobiletools/gallery/pro/activities/PanoramaPhotoActivity.kt | 1 | 6426 | package com.simplemobiletools.gallery.pro.activities
import android.content.res.Configuration
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.graphics.Color
import android.net.Uri
import android.os.Bundle
import android.view.View
import android.view.Window
import android.view.WindowInsetsController
import android.widget.RelativeLayout
import com.google.vr.sdk.widgets.pano.VrPanoramaEventListener
import com.google.vr.sdk.widgets.pano.VrPanoramaView
import com.simplemobiletools.commons.extensions.*
import com.simplemobiletools.commons.helpers.ensureBackgroundThread
import com.simplemobiletools.commons.helpers.isRPlus
import com.simplemobiletools.gallery.pro.R
import com.simplemobiletools.gallery.pro.extensions.config
import com.simplemobiletools.gallery.pro.extensions.hideSystemUI
import com.simplemobiletools.gallery.pro.extensions.showSystemUI
import com.simplemobiletools.gallery.pro.helpers.PATH
import kotlinx.android.synthetic.main.activity_panorama_photo.*
open class PanoramaPhotoActivity : SimpleActivity() {
private val CARDBOARD_DISPLAY_MODE = 3
private var isFullscreen = false
private var isExploreEnabled = true
private var isRendering = false
public override fun onCreate(savedInstanceState: Bundle?) {
useDynamicTheme = false
requestWindowFeature(Window.FEATURE_NO_TITLE)
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_panorama_photo)
checkNotchSupport()
setupButtonMargins()
cardboard.setOnClickListener {
panorama_view.displayMode = CARDBOARD_DISPLAY_MODE
}
explore.setOnClickListener {
isExploreEnabled = !isExploreEnabled
panorama_view.setPureTouchTracking(isExploreEnabled)
explore.setImageResource(if (isExploreEnabled) R.drawable.ic_explore_vector else R.drawable.ic_explore_off_vector)
}
checkIntent()
if (isRPlus()) {
window.insetsController?.setSystemBarsAppearance(0, WindowInsetsController.APPEARANCE_LIGHT_STATUS_BARS)
}
}
override fun onResume() {
super.onResume()
panorama_view.resumeRendering()
isRendering = true
if (config.blackBackground) {
updateStatusbarColor(Color.BLACK)
}
window.statusBarColor = resources.getColor(R.color.circle_black_background)
if (config.maxBrightness) {
val attributes = window.attributes
attributes.screenBrightness = 1f
window.attributes = attributes
}
}
override fun onPause() {
super.onPause()
panorama_view.pauseRendering()
isRendering = false
}
override fun onDestroy() {
super.onDestroy()
if (isRendering) {
panorama_view.shutdown()
}
}
private fun checkIntent() {
val path = intent.getStringExtra(PATH)
if (path == null) {
toast(R.string.invalid_image_path)
finish()
return
}
intent.removeExtra(PATH)
try {
val options = VrPanoramaView.Options()
options.inputType = VrPanoramaView.Options.TYPE_MONO
ensureBackgroundThread {
val bitmap = getBitmapToLoad(path)
runOnUiThread {
panorama_view.apply {
beVisible()
loadImageFromBitmap(bitmap, options)
setFlingingEnabled(true)
setPureTouchTracking(true)
// add custom buttons so we can position them and toggle visibility as desired
setFullscreenButtonEnabled(false)
setInfoButtonEnabled(false)
setTransitionViewEnabled(false)
setStereoModeButtonEnabled(false)
setOnClickListener {
handleClick()
}
setEventListener(object : VrPanoramaEventListener() {
override fun onClick() {
handleClick()
}
})
}
}
}
} catch (e: Exception) {
showErrorToast(e)
}
window.decorView.setOnSystemUiVisibilityChangeListener { visibility ->
isFullscreen = visibility and View.SYSTEM_UI_FLAG_FULLSCREEN != 0
toggleButtonVisibility()
}
}
override fun onConfigurationChanged(newConfig: Configuration) {
super.onConfigurationChanged(newConfig)
setupButtonMargins()
}
private fun getBitmapToLoad(path: String): Bitmap? {
val options = BitmapFactory.Options()
options.inSampleSize = 1
var bitmap: Bitmap? = null
for (i in 0..10) {
try {
bitmap = if (path.startsWith("content://")) {
val inputStream = contentResolver.openInputStream(Uri.parse(path))
BitmapFactory.decodeStream(inputStream)
} else {
BitmapFactory.decodeFile(path, options)
}
break
} catch (e: OutOfMemoryError) {
options.inSampleSize *= 2
}
}
return bitmap
}
private fun setupButtonMargins() {
val navBarHeight = navigationBarHeight
(cardboard.layoutParams as RelativeLayout.LayoutParams).apply {
bottomMargin = navBarHeight
rightMargin = navigationBarWidth
}
(explore.layoutParams as RelativeLayout.LayoutParams).bottomMargin = navigationBarHeight
cardboard.onGlobalLayout {
panorama_gradient_background.layoutParams.height = navBarHeight + cardboard.height
}
}
private fun toggleButtonVisibility() {
arrayOf(cardboard, explore, panorama_gradient_background).forEach {
it.animate().alpha(if (isFullscreen) 0f else 1f)
it.isClickable = !isFullscreen
}
}
private fun handleClick() {
isFullscreen = !isFullscreen
toggleButtonVisibility()
if (isFullscreen) {
hideSystemUI(false)
} else {
showSystemUI(false)
}
}
}
| gpl-3.0 | 85548bd87e58b595e1dfb55a97e44114 | 31.953846 | 126 | 0.614846 | 5.441152 | false | false | false | false |
JetBrains/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/codeInsight/codevision/KotlinCodeVisionLimitedHint.kt | 1 | 5957 | // 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.codeInsight.codevision
import com.intellij.codeInsight.hints.settings.showInlaySettings
import com.intellij.codeInsight.navigation.actions.GotoDeclarationAction
import com.intellij.openapi.editor.Editor
import com.intellij.psi.PsiElement
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.CLASS_LOCATION
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.FUNCTION_LOCATION
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.INTERFACE_LOCATION
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.PROPERTY_LOCATION
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.logInheritorsClicked
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.logSettingsClicked
import org.jetbrains.kotlin.idea.codeInsight.codevision.KotlinCodeVisionUsagesCollector.Companion.logUsagesClicked
import org.jetbrains.kotlin.idea.highlighter.markers.OVERRIDDEN_FUNCTION
import org.jetbrains.kotlin.idea.highlighter.markers.OVERRIDDEN_PROPERTY
import org.jetbrains.kotlin.idea.highlighter.markers.SUBCLASSED_CLASS
import org.jetbrains.kotlin.psi.KtClass
import org.jetbrains.kotlin.psi.KtFunction
import org.jetbrains.kotlin.psi.KtProperty
import java.awt.event.MouseEvent
abstract class KotlinCodeVisionHint(hintKey: String) {
open val regularText: String = KotlinBundle.message(hintKey)
abstract fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?)
}
abstract class KotlinCodeVisionLimitedHint(num: Int, limitReached: Boolean, regularHintKey: String, tooManyHintKey: String) :
KotlinCodeVisionHint(regularHintKey) {
override val regularText: String =
if (limitReached) KotlinBundle.message(tooManyHintKey, num) else KotlinBundle.message(regularHintKey, num)
}
private const val IMPLEMENTATIONS_KEY = "hints.codevision.implementations.format"
private const val IMPLEMENTATIONS_TO_MANY_KEY = "hints.codevision.implementations.too_many.format"
private const val INHERITORS_KEY = "hints.codevision.inheritors.format"
private const val INHERITORS_TO_MANY_KEY = "hints.codevision.inheritors.to_many.format"
private const val OVERRIDES_KEY = "hints.codevision.overrides.format"
private const val OVERRIDES_TOO_MANY_KEY = "hints.codevision.overrides.to_many.format"
private const val USAGES_KEY = "hints.codevision.usages.format"
private const val USAGES_TOO_MANY_KEY = "hints.codevision.usages.too_many.format"
private const val SETTINGS_FORMAT = "hints.codevision.settings"
class Usages(usagesNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(usagesNum, limitReached, USAGES_KEY, USAGES_TOO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logUsagesClicked(editor.project)
GotoDeclarationAction.startFindUsages(editor, editor.project!!, element)
}
}
class FunctionOverrides(overridesNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(overridesNum, limitReached, OVERRIDES_KEY, OVERRIDES_TOO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logInheritorsClicked(editor.project, FUNCTION_LOCATION)
val navigationHandler = OVERRIDDEN_FUNCTION.navigationHandler
navigationHandler.navigate(event, (element as KtFunction).nameIdentifier)
}
}
class FunctionImplementations(implNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(implNum, limitReached, IMPLEMENTATIONS_KEY, IMPLEMENTATIONS_TO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logInheritorsClicked(editor.project, FUNCTION_LOCATION)
val navigationHandler = OVERRIDDEN_FUNCTION.navigationHandler
navigationHandler.navigate(event, (element as KtFunction).nameIdentifier)
}
}
class PropertyOverrides(overridesNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(overridesNum, limitReached, OVERRIDES_KEY, OVERRIDES_TOO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logInheritorsClicked(editor.project, PROPERTY_LOCATION)
val navigationHandler = OVERRIDDEN_PROPERTY.navigationHandler
navigationHandler.navigate(event, (element as KtProperty).nameIdentifier)
}
}
class ClassInheritors(inheritorsNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(inheritorsNum, limitReached, INHERITORS_KEY, INHERITORS_TO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logInheritorsClicked(editor.project, CLASS_LOCATION)
val navigationHandler = SUBCLASSED_CLASS.navigationHandler
navigationHandler.navigate(event, (element as KtClass).nameIdentifier)
}
}
class InterfaceImplementations(implNum: Int, limitReached: Boolean) :
KotlinCodeVisionLimitedHint(implNum, limitReached, IMPLEMENTATIONS_KEY, IMPLEMENTATIONS_TO_MANY_KEY) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
logInheritorsClicked(editor.project, INTERFACE_LOCATION)
val navigationHandler = SUBCLASSED_CLASS.navigationHandler
navigationHandler.navigate(event, (element as KtClass).nameIdentifier)
}
}
class SettingsHint : KotlinCodeVisionHint(SETTINGS_FORMAT) {
override fun onClick(editor: Editor, element: PsiElement, event: MouseEvent?) {
val project = element.project
logSettingsClicked(project)
showInlaySettings(project, element.language, null)
}
} | apache-2.0 | 4af74cedc46db0a1079900ed253bbadf | 49.923077 | 158 | 0.802585 | 4.285612 | false | false | false | false |
allotria/intellij-community | python/src/com/jetbrains/python/run/runAnything/PyConsoleRunAnythingProvider.kt | 5 | 1313 | // 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.run.runAnything
import com.intellij.ide.actions.runAnything.activity.RunAnythingAnActionProvider
import com.intellij.openapi.actionSystem.ActionManager
import com.intellij.openapi.actionSystem.DataContext
import com.jetbrains.python.PyBundle
import com.jetbrains.python.console.RunPythonOrDebugConsoleAction
import icons.PythonIcons
import javax.swing.Icon
/**
* @author vlan
*/
class PyConsoleRunAnythingProvider : RunAnythingAnActionProvider<RunPythonOrDebugConsoleAction>() {
override fun getCommand(value: RunPythonOrDebugConsoleAction) = helpCommand
override fun getHelpCommand() = "python"
override fun getHelpGroupTitle(): String? = "Python" // NON-NLS
override fun getValues(dataContext: DataContext, pattern: String): Collection<RunPythonOrDebugConsoleAction> {
val action = ActionManager.getInstance().getAction("com.jetbrains.python.console.RunPythonConsoleAction")
return listOfNotNull(action as? RunPythonOrDebugConsoleAction)
}
override fun getHelpIcon(): Icon = PythonIcons.Python.PythonConsole
override fun getHelpDescription(): String = PyBundle.message("python.console.run.anything.provider")
} | apache-2.0 | 29107814ba2883bac1907f04f168d855 | 42.8 | 140 | 0.814166 | 4.774545 | false | false | false | false |
allotria/intellij-community | platform/lang-impl/src/com/intellij/ide/actions/runAnything/activity/RunAnythingCommandLineProvider.kt | 3 | 3009 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.ide.actions.runAnything.activity
import com.intellij.openapi.actionSystem.DataContext
import com.intellij.util.execution.ParametersListUtil
import org.jetbrains.annotations.ApiStatus
@ApiStatus.Internal
abstract class RunAnythingCommandLineProvider : RunAnythingNotifiableProvider<String>() {
open fun getHelpCommandAliases(): List<String> = emptyList()
abstract override fun getHelpCommand(): String
protected abstract fun suggestCompletionVariants(dataContext: DataContext, commandLine: CommandLine): Sequence<String>
protected abstract fun run(dataContext: DataContext, commandLine: CommandLine): Boolean
override fun getCommand(value: String) = value
private fun getHelpCommands() = listOf(helpCommand) + getHelpCommandAliases()
override fun findMatchingValue(dataContext: DataContext, pattern: String) =
if (extractLeadingHelpPrefix(pattern) != null) getCommand(pattern) else null
private fun extractLeadingHelpPrefix(commandLine: String): Pair<String, String>? {
for (helpCommand in getHelpCommands()) {
val prefix = "$helpCommand "
when {
commandLine.startsWith(prefix) -> return helpCommand to commandLine.removePrefix(prefix)
prefix.startsWith(commandLine) -> return helpCommand to ""
}
}
return null
}
private fun parseCommandLine(commandLine: String): CommandLine? {
val (helpCommand, command) = extractLeadingHelpPrefix(commandLine) ?: return null
val parameters = ParametersListUtil.parse(command, true, true, true)
val toComplete = parameters.lastOrNull() ?: ""
val prefix = command.removeSuffix(toComplete).trim()
val nonEmptyParameters = parameters.filter { it.isNotEmpty() }
val completedParameters = parameters.dropLast(1).filter { it.isNotEmpty() }
return CommandLine(nonEmptyParameters, completedParameters, helpCommand, command.trim(), prefix, toComplete)
}
override fun getValues(dataContext: DataContext, pattern: String): List<String> {
val commandLine = parseCommandLine(pattern) ?: return emptyList()
val variants = suggestCompletionVariants(dataContext, commandLine)
val helpCommand = commandLine.helpCommand
val prefix = commandLine.prefix.let { if (it.isEmpty()) helpCommand else "$helpCommand $it" }
return variants.map { "$prefix $it" }.toList()
}
override fun run(dataContext: DataContext, value: String): Boolean {
val commandLine = parseCommandLine(value) ?: return false
return run(dataContext, commandLine)
}
class CommandLine(
val parameters: List<String>,
val completedParameters: List<String>,
val helpCommand: String,
val command: String,
val prefix: String,
val toComplete: String
) {
private val parameterSet by lazy { completedParameters.toSet() }
operator fun contains(command: String) = command in parameterSet
}
} | apache-2.0 | a3693bda6c79fe14ebf090bfecbe0009 | 41.394366 | 140 | 0.751412 | 4.77619 | false | false | false | false |
Skatteetaten/boober | src/main/kotlin/no/skatteetaten/aurora/boober/utils/CollectionUtils.kt | 1 | 6428 | package no.skatteetaten.aurora.boober.utils
import brave.Tracing
import brave.propagation.CurrentTraceContext
import io.fabric8.kubernetes.api.model.HasMetadata
import kotlinx.coroutines.ThreadContextElement
import kotlinx.coroutines.async
import kotlinx.coroutines.awaitAll
import kotlinx.coroutines.coroutineScope
import kotlinx.coroutines.newFixedThreadPoolContext
import kotlinx.coroutines.runBlocking
import kotlinx.coroutines.slf4j.MDCContext
import no.skatteetaten.aurora.boober.controller.security.SpringSecurityThreadContextElement
import no.skatteetaten.aurora.boober.model.AuroraResource
import kotlin.coroutines.AbstractCoroutineContextElement
import kotlin.coroutines.CoroutineContext
import kotlin.reflect.KClass
fun <K, V> Map<K, V>.addIfNotNull(value: Pair<K, V>?): Map<K, V> {
return value?.let {
this + it
} ?: this
}
fun <K, V> Map<K, V>.addIfNotNull(value: Map<K, V>?): Map<K, V> {
return value?.let {
this + it
} ?: this
}
fun <T> Set<T>.addIfNotNull(value: T?): Set<T> {
return value?.let {
this + it
} ?: this
}
fun Map<String, String>.normalizeLabels(): Map<String, String> {
val MAX_LABEL_VALUE_LENGTH = 63
val LABEL_PATTERN = "(([A-Za-z0-9][-A-Za-z0-9_.]*)?[A-Za-z0-9])?"
/**
* Returns a new Map where each value has been truncated as to not exceed the
* <code>MAX_LABEL_VALUE_LENGTH</code> max length.
* Truncation is done by cutting of characters from the start of the value, leaving only the last
* MAX_LABEL_VALUE_LENGTH characters.
*/
fun toOpenShiftLabelNameSafeMap(labels: Map<String, String>): Map<String, String> {
fun toOpenShiftSafeLabel(value: String): String {
val startIndex = (value.length - MAX_LABEL_VALUE_LENGTH).takeIf { it >= 0 } ?: 0
var tail = value.substring(startIndex)
while (true) {
val isLegal = tail.matches(Regex(LABEL_PATTERN))
if (isLegal) break
tail = tail.substring(1)
}
return tail
}
return labels.mapValues { toOpenShiftSafeLabel(it.value) }
}
return toOpenShiftLabelNameSafeMap(this)
}
fun MutableMap<String, Any>.deepSet(parts: List<String>, value: Map<String, Any>) {
if (parts.isEmpty()) {
value.forEach {
this[it.key] = it.value
}
return
}
val emptyMap: MutableMap<String, Any> = mutableMapOf()
val key = parts.first()
val subMap: MutableMap<String, Any> = this.getOrDefault(key, emptyMap) as MutableMap<String, Any>
this[parts.first()] = subMap
subMap.deepSet(parts.drop(1), value)
}
fun <T> Set<T>.addIfNotNull(value: Set<T>?): Set<T> {
return value?.let {
this + it
} ?: this
}
fun <T> List<T>.addIfNotNull(value: T?): List<T> {
return value?.let {
this + it
} ?: this
}
fun <T> List<T>.prepend(value: T): List<T> = listOf(value) + this
fun <T> List<T>.prependIfNotNull(value: T?): List<T> = value?.let(::prepend) ?: this
fun <T> List<T>.addIfNotNull(value: List<T>?): List<T> {
return value?.let {
this + it
} ?: this
}
fun <T> List<T>.addIf(condition: Boolean, value: T): List<T> = if (condition) this + listOf(value) else this
fun <T> List<T>.addIf(condition: Boolean, values: List<T>): List<T> = if (condition) this + values else this
fun <K, V> Map<K, V>?.nullOnEmpty(): Map<K, V>? {
if (this == null) {
return this
}
if (this.isEmpty()) {
return null
}
return this
}
fun <T> Collection<T>?.nullOnEmpty(): Collection<T>? {
if (this == null) {
return this
}
if (this.isEmpty()) {
return null
}
return this
}
fun <K, V> Map<out K, V?>.filterNullValues(): Map<K, V> {
val result = LinkedHashMap<K, V>()
for (entry in this) {
entry.value?.let {
result[entry.key] = it
}
}
return result
}
fun <T : Any, U : Any> List<Pair<T, U>>.toMultiMap() =
this.groupBy(keySelector = { it.first }) { it.second }
fun <T : Collection<*>> T?.takeIfNotEmpty(): T? {
return this.takeIf { it?.isEmpty() == false }
}
fun <K, V> Map<K, V>?.takeIfNotEmpty(): Map<K, V>? {
return this.takeIf { it?.isEmpty() == false }
}
fun <K, V> List<Map<K, V>>.toMap(): Map<K, V> = fold(emptyMap()) { acc, map -> acc + map }
// Implemented based on https://github.com/openzipkin/brave/issues/820#issuecomment-447614394
private class TracingContextElement : ThreadContextElement<CurrentTraceContext.Scope?>, AbstractCoroutineContextElement(Key) {
private val currentTraceContext: CurrentTraceContext? = Tracing.current()?.currentTraceContext()
private val initial = currentTraceContext?.get()
companion object Key : CoroutineContext.Key<TracingContextElement>
override fun updateThreadContext(context: CoroutineContext): CurrentTraceContext.Scope? {
return currentTraceContext?.maybeScope(initial)
}
override fun restoreThreadContext(context: CoroutineContext, oldState: CurrentTraceContext.Scope?) {
oldState?.close()
}
}
fun <A, B> Iterable<A>.parallelMap(f: suspend (A) -> B): List<B> {
val iter = this
return runBlocking(
threadPool + MDCContext() + TracingContextElement() + SpringSecurityThreadContextElement()
) {
iter.pmap(f)
}
}
val threadPool = newFixedThreadPoolContext(6, "boober")
// https://jivimberg.io/blog/2018/05/04/parallel-map-in-kotlin/
suspend fun <A, B> Iterable<A>.pmap(f: suspend (A) -> B): List<B> = coroutineScope {
map { async { f(it) } }.awaitAll()
}
inline fun <reified T : HasMetadata> Collection<AuroraResource>.findResourceByType(): T =
this.findResourceByType(T::class).firstOrNull() ?: throw Exception("No resource of specified type found")
inline fun <reified T : HasMetadata> Collection<AuroraResource>.findResourcesByType(suffix: String? = null): List<T> =
this.findResourceByType(T::class).filter { item ->
suffix?.let {
item.metadata.name.endsWith(it)
} ?: true
}
@Suppress("UNCHECKED_CAST")
fun <T : Any> Collection<AuroraResource>.findResourceByType(kclass: KClass<T>): List<T> =
filter { it.resource::class == kclass }
.map { it.resource as T }
fun countSetValues(vararg things: Any?) = things.count {
when (it) {
is String -> it.isNotBlank()
is Boolean -> it
else -> it != null
}
}
| apache-2.0 | b7c40adc04b25af33ad70156621ae1fd | 30.509804 | 126 | 0.649035 | 3.621408 | false | false | false | false |
allotria/intellij-community | platform/execution-impl/src/com/intellij/execution/stateWidget/StateWidgetAdditionActionsHolder.kt | 2 | 1670 | // 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.execution.stateWidget
import com.intellij.execution.ExecutorRegistryImpl
import com.intellij.execution.executors.ExecutorGroup
import com.intellij.execution.stateExecutionWidget.StateWidgetProcess
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
internal class StateWidgetAdditionActionsHolder(val executorGroup: ExecutorGroup<*>, val process: StateWidgetProcess) {
companion object {
@JvmStatic
fun getAdditionActionId(process: StateWidgetProcess) = "${process.moreActionSubGroupName}_additionAction"
@JvmStatic
fun getAdditionActionChooserGroupId(process: StateWidgetProcess) = "${process.moreActionSubGroupName}_additionActionChooserGroupId"
}
private var selectedAction: AnAction? = null
val moreActionChooserGroup: StateWidgetChooserAdditionGroup =
StateWidgetChooserAdditionGroup(executorGroup, process) { ex ->
object : ExecutorRegistryImpl.ExecutorAction(ex) {
override fun actionPerformed(e: AnActionEvent) {
super.actionPerformed(e)
selectedAction = this
}
override fun update(e: AnActionEvent) {
super.update(e)
e.presentation.isEnabledAndVisible = e.presentation.isEnabled && e.presentation.isVisible
}
}
}
val additionAction: StateWidgetAdditionAction = StateWidgetAdditionAction(executorGroup, process) { selectedAction }
init {
selectedAction = moreActionChooserGroup.getChildren(null)?.getOrNull(0)
}
} | apache-2.0 | b46b2384a9a2f6f88457f56311d365a5 | 39.756098 | 140 | 0.771856 | 4.717514 | false | false | false | false |
leafclick/intellij-community | platform/lang-api/src/com/intellij/execution/target/TargetEnvironmentConfiguration.kt | 1 | 1432 | // Copyright 2000-2019 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.execution.target
import com.intellij.execution.target.ContributedConfigurationBase.Companion.getTypeImpl
import com.intellij.openapi.project.Project
/**
* Base class for configuration instances contributed by the ["com.intellij.executionTargetType"][TargetEnvironmentType.EXTENSION_NAME] extension point.
*
* To be useful, target configuration should normally include at least one language runtime configuration, either introspected
* or explicitly edited by the user.
*
* All available target configurations can be retrieved via [com.intellij.execution.target.TargetEnvironmentsManager]
*/
abstract class TargetEnvironmentConfiguration(typeId: String) : ContributedConfigurationBase(typeId, TargetEnvironmentType.EXTENSION_NAME) {
val runtimes = ContributedConfigurationsList(LanguageRuntimeType.EXTENSION_NAME)
fun addLanguageRuntime(runtime: LanguageRuntimeConfiguration) = runtimes.addConfig(runtime)
fun removeLanguageRuntime(runtime: LanguageRuntimeConfiguration) = runtimes.removeConfig(runtime)
fun createEnvironmentFactory(project: Project): TargetEnvironmentFactory = getTargetType().createEnvironmentFactory(project, this)
}
fun <C : TargetEnvironmentConfiguration, T : TargetEnvironmentType<C>> C.getTargetType(): T = this.getTypeImpl() | apache-2.0 | 5e64071800d8d7bd4e5e49bde43d260b | 54.115385 | 152 | 0.824721 | 5.060071 | false | true | false | false |
leafclick/intellij-community | platform/statistics/devkit/src/com/intellij/internal/statistic/actions/OpenWhitelistFileAction.kt | 1 | 2291 | // Copyright 2000-2020 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package com.intellij.internal.statistic.actions
import com.intellij.icons.AllIcons
import com.intellij.internal.statistic.StatisticsBundle
import com.intellij.internal.statistic.eventLog.validator.persistence.BaseEventLogWhitelistPersistence
import com.intellij.internal.statistic.eventLog.validator.persistence.EventLogWhitelistPersistence
import com.intellij.internal.statistic.eventLog.validator.persistence.EventLogWhitelistSettingsPersistence
import com.intellij.notification.Notification
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnAction
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.fileEditor.FileEditorManager
import com.intellij.openapi.project.Project
import com.intellij.openapi.vfs.VfsUtil
import java.io.File
class OpenWhitelistFileAction(private val myRecorderId: String = "FUS")
: AnAction(StatisticsBundle.message("stats.open.0.whitelist.file", myRecorderId), null, AllIcons.FileTypes.Config) {
override fun actionPerformed(e: AnActionEvent) {
val project = e.project ?: return
val settings = EventLogWhitelistSettingsPersistence.getInstance().getPathSettings(myRecorderId)
val file = if (settings != null && settings.isUseCustomPath) {
File(settings.customPath)
}
else {
BaseEventLogWhitelistPersistence.getDefaultWhitelistFile(myRecorderId, EventLogWhitelistPersistence.WHITE_LIST_DATA_FILE)
}
openFileInEditor(file, project)
}
companion object {
fun openFileInEditor(file: File, project: Project) {
val virtualFile = VfsUtil.findFileByIoFile(file, true)
if (virtualFile == null) {
val notification = Notification("FeatureUsageStatistics",
StatisticsBundle.message("stats.feature.usage.statistics"),
StatisticsBundle.message("stats.file.0.does.not.exist", file.absolutePath),
NotificationType.WARNING)
notification.notify(project)
return
}
FileEditorManager.getInstance(project).openFile(virtualFile, true)
}
}
} | apache-2.0 | 7b4290a0fdb8d50e166e172a46c541a9 | 45.77551 | 140 | 0.755129 | 4.874468 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/defaultArguments/superCallCheck.kt | 2 | 794 | // TODO: muted automatically, investigate should it be ran for JS or not
// IGNORE_BACKEND: JS, NATIVE
// WITH_RUNTIME
open class MyClass {
fun def(i: Int = 0): Int {
return i
}
}
fun box():String {
val method = MyClass::class.java.getMethod("def\$default", MyClass::class.java, Int::class.java, Int::class.java, Any::class.java)
val result = method.invoke(null, MyClass(), -1, 1, null)
if (result != 0) return "fail 1: $result"
var failed = false
try {
method.invoke(null, MyClass(), -1, 1, "fail")
}
catch(e: Exception) {
val cause = e.cause
if (cause is UnsupportedOperationException && cause.message!!.startsWith("Super calls")) {
failed = true
}
}
return if (!failed) "fail" else "OK"
}
| apache-2.0 | 2cb19d845df5f650af8986e6ed129957 | 25.466667 | 134 | 0.599496 | 3.625571 | false | false | false | false |
JuliusKunze/kotlin-native | backend.native/tests/external/codegen/box/coroutines/await.kt | 2 | 2827 | // WITH_RUNTIME
// WITH_COROUTINES
// FILE: promise.kt
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
class Promise<T>(private val executor: ((T) -> Unit) -> Unit) {
private var value: Any? = null
private var thenList: MutableList<(T) -> Unit>? = mutableListOf()
init {
executor {
value = it
for (resolve in thenList!!) {
resolve(it)
}
thenList = null
}
}
fun <S> then(onFulfilled: (T) -> S): Promise<S> {
return Promise { resolve ->
if (thenList != null) {
thenList!!.add { resolve(onFulfilled(it)) }
}
else {
resolve(onFulfilled(value as T))
}
}
}
}
// FILE: queue.kt
import helpers.*
private val queue = mutableListOf<() -> Unit>()
fun <T> postpone(computation: () -> T): Promise<T> {
return Promise { resolve ->
queue += {
resolve(computation())
}
}
}
fun processQueue() {
while (queue.isNotEmpty()) {
queue.removeAt(0)()
}
}
// FILE: await.kt
import helpers.*
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
private var log = ""
private var inAwait = false
suspend fun <S> await(value: Promise<S>): S = suspendCoroutine { continuation ->
if (inAwait) {
throw IllegalStateException("Can't call await recursively")
}
inAwait = true
postpone {
value.then { result ->
continuation.resume(result)
}
}
inAwait = false
}
suspend fun <S> awaitAndLog(value: Promise<S>): S {
log += "before await;"
return await(value.then { result ->
log += "after await: $result;"
result
})
}
fun <T> async(c: suspend () -> T): Promise<T> {
return Promise { resolve ->
c.startCoroutine(handleResultContinuation(resolve))
}
}
fun <T> asyncOperation(resultSupplier: () -> T) = Promise<T> { resolve ->
log += "before async;"
postpone {
val result = resultSupplier()
log += "after async $result;"
resolve(result)
}
}
fun getLog() = log
// FILE: main.kt
import kotlin.coroutines.experimental.*
import kotlin.coroutines.experimental.intrinsics.*
private fun test() = async<String> {
val o = await(asyncOperation { "O" })
val k = awaitAndLog(asyncOperation { "K" })
return@async o + k
}
fun box(): String {
val resultPromise = test()
var result: String? = null
resultPromise.then { result = it }
processQueue()
if (result != "OK") return "fail1: $result"
if (getLog() != "before async;after async O;before async;before await;after async K;after await: K;") return "fail2: ${getLog()}"
return "OK"
}
| apache-2.0 | 45b1026a84d104e3e1efb1fdd3254b38 | 22.756303 | 133 | 0.583658 | 3.893939 | false | false | false | false |
JuliusKunze/kotlin-native | runtime/src/main/kotlin/kotlin/sequences/Sequences.kt | 2 | 68720 | /*
* Copyright 2010-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package kotlin.sequences
import kotlin.comparisons.*
/**
* Given an [iterator] function constructs a [Sequence] that returns values through the [Iterator]
* provided by that function.
* The values are evaluated lazily, and the sequence is potentially infinite.
*
* @sample samples.collections.Sequences.Building.sequenceFromIterator
*/
@kotlin.internal.InlineOnly
public inline fun <T> Sequence(crossinline iterator: () -> Iterator<T>): Sequence<T> = object : Sequence<T> {
override fun iterator(): Iterator<T> = iterator()
}
/**
* Creates a sequence that returns all values from this enumeration. The sequence is constrained to be iterated only once.
*/
@FixmeSequences
@kotlin.internal.InlineOnly
public inline fun<T: Enum<T>> T.asSequence(): Sequence<T> = TODO() // this.values().iterator().asSequence()
/**
* Creates a sequence that returns all elements from this iterator. The sequence is constrained to be iterated only once.
*
* @sample samples.collections.Sequences.Building.sequenceFromIterator
*/
public fun <T> Iterator<T>.asSequence(): Sequence<T> = Sequence { this }.constrainOnce()
/**
* Creates a sequence that returns the specified values.
*
* @sample samples.collections.Sequences.Building.sequenceOfValues
*/
public fun <T> sequenceOf(vararg elements: T): Sequence<T> = if (elements.isEmpty()) emptySequence() else elements.asSequence()
/**
* Returns an empty sequence.
*/
public fun <T> emptySequence(): Sequence<T> = EmptySequence
private object EmptySequence : Sequence<Nothing>, DropTakeSequence<Nothing> {
override fun iterator(): Iterator<Nothing> = EmptyIterator
override fun drop(n: Int) = EmptySequence
override fun take(n: Int) = EmptySequence
}
/**
* Returns a sequence of all elements from all sequences in this sequence.
*/
public fun <T> Sequence<Sequence<T>>.flatten(): Sequence<T> = flatten { it.iterator() }
/**
* Returns a sequence of all elements from all iterables in this sequence.
*/
public fun <T> Sequence<Iterable<T>>.flatten(): Sequence<T> = flatten { it.iterator() }
private fun <T, R> Sequence<T>.flatten(iterator: (T) -> Iterator<R>): Sequence<R> {
if (this is TransformingSequence<*, *>) {
return (this as TransformingSequence<*, T>).flatten(iterator)
}
return FlatteningSequence(this, { it }, iterator)
}
/**
* Returns a pair of lists, where
* *first* list is built from the first values of each pair from this sequence,
* *second* list is built from the second values of each pair from this sequence.
*/
public fun <T, R> Sequence<Pair<T, R>>.unzip(): Pair<List<T>, List<R>> {
val listT = ArrayList<T>()
val listR = ArrayList<R>()
for (pair in this) {
listT.add(pair.first)
listR.add(pair.second)
}
return listT to listR
}
/**
* A sequence that returns the values from the underlying [sequence] that either match or do not match
* the specified [predicate].
*
* @param sendWhen If `true`, values for which the predicate returns `true` are returned. Otherwise,
* values for which the predicate returns `false` are returned
*/
internal class FilteringSequence<T>(private val sequence: Sequence<T>,
private val sendWhen: Boolean = true,
private val predicate: (T) -> Boolean
) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator()
var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue
var nextItem: T? = null
private fun calcNext() {
while (iterator.hasNext()) {
val item = iterator.next()
if (predicate(item) == sendWhen) {
nextItem = item
nextState = 1
return
}
}
nextState = 0
}
override fun next(): T {
if (nextState == -1)
calcNext()
if (nextState == 0)
throw NoSuchElementException()
val result = nextItem
nextItem = null
nextState = -1
@Suppress("UNCHECKED_CAST")
return result as T
}
override fun hasNext(): Boolean {
if (nextState == -1)
calcNext()
return nextState == 1
}
}
}
/**
* A sequence which returns the results of applying the given [transformer] function to the values
* in the underlying [sequence].
*/
internal class TransformingSequence<T, R>
constructor(private val sequence: Sequence<T>, private val transformer: (T) -> R) : Sequence<R> {
override fun iterator(): Iterator<R> = object : Iterator<R> {
val iterator = sequence.iterator()
override fun next(): R {
return transformer(iterator.next())
}
override fun hasNext(): Boolean {
return iterator.hasNext()
}
}
internal fun <E> flatten(iterator: (R) -> Iterator<E>): Sequence<E> {
return FlatteningSequence<T, R, E>(sequence, transformer, iterator)
}
}
/**
* A sequence which returns the results of applying the given [transformer] function to the values
* in the underlying [sequence], where the transformer function takes the index of the value in the underlying
* sequence along with the value itself.
*/
internal class TransformingIndexedSequence<T, R>
constructor(private val sequence: Sequence<T>, private val transformer: (Int, T) -> R) : Sequence<R> {
override fun iterator(): Iterator<R> = object : Iterator<R> {
val iterator = sequence.iterator()
var index = 0
override fun next(): R {
return transformer(index++, iterator.next())
}
override fun hasNext(): Boolean {
return iterator.hasNext()
}
}
}
/**
* A sequence which combines values from the underlying [sequence] with their indices and returns them as
* [IndexedValue] objects.
*/
internal class IndexingSequence<T>
constructor(private val sequence: Sequence<T>) : Sequence<IndexedValue<T>> {
override fun iterator(): Iterator<IndexedValue<T>> = object : Iterator<IndexedValue<T>> {
val iterator = sequence.iterator()
var index = 0
override fun next(): IndexedValue<T> {
return IndexedValue(index++, iterator.next())
}
override fun hasNext(): Boolean {
return iterator.hasNext()
}
}
}
/**
* A sequence which takes the values from two parallel underlying sequences, passes them to the given
* [transform] function and returns the values returned by that function. The sequence stops returning
* values as soon as one of the underlying sequences stops returning values.
*/
internal class MergingSequence<T1, T2, V>
constructor(private val sequence1: Sequence<T1>,
private val sequence2: Sequence<T2>,
private val transform: (T1, T2) -> V
) : Sequence<V> {
override fun iterator(): Iterator<V> = object : Iterator<V> {
val iterator1 = sequence1.iterator()
val iterator2 = sequence2.iterator()
override fun next(): V {
return transform(iterator1.next(), iterator2.next())
}
override fun hasNext(): Boolean {
return iterator1.hasNext() && iterator2.hasNext()
}
}
}
internal class FlatteningSequence<T, R, E>
constructor(
private val sequence: Sequence<T>,
private val transformer: (T) -> R,
private val iterator: (R) -> Iterator<E>
) : Sequence<E> {
override fun iterator(): Iterator<E> = object : Iterator<E> {
val iterator = sequence.iterator()
var itemIterator: Iterator<E>? = null
override fun next(): E {
if (!ensureItemIterator())
throw NoSuchElementException()
return itemIterator!!.next()
}
override fun hasNext(): Boolean {
return ensureItemIterator()
}
private fun ensureItemIterator(): Boolean {
if (itemIterator?.hasNext() == false)
itemIterator = null
while (itemIterator == null) {
if (!iterator.hasNext()) {
return false
} else {
val element = iterator.next()
val nextItemIterator = iterator(transformer(element))
if (nextItemIterator.hasNext()) {
itemIterator = nextItemIterator
return true
}
}
}
return true
}
}
}
/**
* A sequence that supports drop(n) and take(n) operations
*/
internal interface DropTakeSequence<T> : Sequence<T> {
fun drop(n: Int): Sequence<T>
fun take(n: Int): Sequence<T>
}
/**
* A sequence that skips [startIndex] values from the underlying [sequence]
* and stops returning values right before [endIndex], i.e. stops at `endIndex - 1`
*/
internal class SubSequence<T> (
private val sequence: Sequence<T>,
private val startIndex: Int,
private val endIndex: Int
): Sequence<T>, DropTakeSequence<T> {
init {
require(startIndex >= 0) { "startIndex should be non-negative, but is $startIndex" }
require(endIndex >= 0) { "endIndex should be non-negative, but is $endIndex" }
require(endIndex >= startIndex) { "endIndex should be not less than startIndex, but was $endIndex < $startIndex"}
}
private val count: Int get() = endIndex - startIndex
override fun drop(n: Int): Sequence<T> = if (n >= count) emptySequence() else SubSequence(sequence, startIndex + n, endIndex)
override fun take(n: Int): Sequence<T> = if (n >= count) this else SubSequence(sequence, startIndex, startIndex + n)
override fun iterator() = object : Iterator<T> {
val iterator = sequence.iterator()
var position = 0
// Shouldn't be called from constructor to avoid premature iteration
private fun drop() {
while(position < startIndex && iterator.hasNext()) {
iterator.next()
position++
}
}
override fun hasNext(): Boolean {
drop()
return (position < endIndex) && iterator.hasNext()
}
override fun next(): T {
drop()
if (position >= endIndex)
throw NoSuchElementException()
position++
return iterator.next()
}
}
}
/**
* A sequence that returns at most [count] values from the underlying [sequence], and stops returning values
* as soon as that count is reached.
*/
internal class TakeSequence<T> (
private val sequence: Sequence<T>,
private val count: Int
) : Sequence<T>, DropTakeSequence<T> {
init {
require (count >= 0) { "count must be non-negative, but was $count." }
}
override fun drop(n: Int): Sequence<T> = if (n >= count) emptySequence() else SubSequence(sequence, n, count)
override fun take(n: Int): Sequence<T> = if (n >= count) this else TakeSequence(sequence, n)
override fun iterator(): Iterator<T> = object : Iterator<T> {
var left = count
val iterator = sequence.iterator()
override fun next(): T {
if (left == 0)
throw NoSuchElementException()
left--
return iterator.next()
}
override fun hasNext(): Boolean {
return left > 0 && iterator.hasNext()
}
}
}
/**
* A sequence that returns values from the underlying [sequence] while the [predicate] function returns
* `true`, and stops returning values once the function returns `false` for the next element.
*/
internal class TakeWhileSequence<T>
constructor(private val sequence: Sequence<T>,
private val predicate: (T) -> Boolean
) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator()
var nextState: Int = -1 // -1 for unknown, 0 for done, 1 for continue
var nextItem: T? = null
private fun calcNext() {
if (iterator.hasNext()) {
val item = iterator.next()
if (predicate(item)) {
nextState = 1
nextItem = item
return
}
}
nextState = 0
}
override fun next(): T {
if (nextState == -1)
calcNext() // will change nextState
if (nextState == 0)
throw NoSuchElementException()
@Suppress("UNCHECKED_CAST")
val result = nextItem as T
// Clean next to avoid keeping reference on yielded instance
nextItem = null
nextState = -1
return result
}
override fun hasNext(): Boolean {
if (nextState == -1)
calcNext() // will change nextState
return nextState == 1
}
}
}
/**
* A sequence that skips the specified number of values from the underlying [sequence] and returns
* all values after that.
*/
internal class DropSequence<T> (
private val sequence: Sequence<T>,
private val count: Int
) : Sequence<T>, DropTakeSequence<T> {
init {
require (count >= 0) { "count must be non-negative, but was $count." }
}
override fun drop(n: Int): Sequence<T> = DropSequence(sequence, count + n)
override fun take(n: Int): Sequence<T> = SubSequence(sequence, count, count + n)
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator()
var left = count
// Shouldn't be called from constructor to avoid premature iteration
private fun drop() {
while (left > 0 && iterator.hasNext()) {
iterator.next()
left--
}
}
override fun next(): T {
drop()
return iterator.next()
}
override fun hasNext(): Boolean {
drop()
return iterator.hasNext()
}
}
}
/**
* A sequence that skips the values from the underlying [sequence] while the given [predicate] returns `true` and returns
* all values after that.
*/
internal class DropWhileSequence<T>
constructor(private val sequence: Sequence<T>,
private val predicate: (T) -> Boolean
) : Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
val iterator = sequence.iterator()
var dropState: Int = -1 // -1 for not dropping, 1 for nextItem, 0 for normal iteration
var nextItem: T? = null
private fun drop() {
while (iterator.hasNext()) {
val item = iterator.next()
if (!predicate(item)) {
nextItem = item
dropState = 1
return
}
}
dropState = 0
}
override fun next(): T {
if (dropState == -1)
drop()
if (dropState == 1) {
@Suppress("UNCHECKED_CAST")
val result = nextItem as T
nextItem = null
dropState = 0
return result
}
return iterator.next()
}
override fun hasNext(): Boolean {
if (dropState == -1)
drop()
return dropState == 1 || iterator.hasNext()
}
}
}
internal class DistinctSequence<T, K>(private val source : Sequence<T>, private val keySelector : (T) -> K) : Sequence<T> {
override fun iterator(): Iterator<T> = DistinctIterator(source.iterator(), keySelector)
}
private class DistinctIterator<T, K>(private val source : Iterator<T>, private val keySelector : (T) -> K) : AbstractIterator<T>() {
private val observed = HashSet<K>()
override fun computeNext() {
while (source.hasNext()) {
val next = source.next()
val key = keySelector(next)
if (observed.add(key)) {
setNext(next)
return
}
}
done()
}
}
private class GeneratorSequence<T: Any>(private val getInitialValue: () -> T?, private val getNextValue: (T) -> T?): Sequence<T> {
override fun iterator(): Iterator<T> = object : Iterator<T> {
var nextItem: T? = null
var nextState: Int = -2 // -2 for initial unknown, -1 for next unknown, 0 for done, 1 for continue
private fun calcNext() {
nextItem = if (nextState == -2) getInitialValue() else getNextValue(nextItem!!)
nextState = if (nextItem == null) 0 else 1
}
override fun next(): T {
if (nextState < 0)
calcNext()
if (nextState == 0)
throw NoSuchElementException()
val result = nextItem as T
// Do not clean nextItem (to avoid keeping reference on yielded instance) -- need to keep state for getNextValue
nextState = -1
return result
}
override fun hasNext(): Boolean {
if (nextState < 0)
calcNext()
return nextState == 1
}
}
}
/**
* Returns a wrapper sequence that provides values of this sequence, but ensures it can be iterated only one time.
*
* [IllegalStateException] is thrown on iterating the returned sequence from the second time.
*/
public fun <T> Sequence<T>.constrainOnce(): Sequence<T> {
// as? does not work in js
//return this as? ConstrainedOnceSequence<T> ?: ConstrainedOnceSequence(this)
return if (this is ConstrainedOnceSequence<T>) this else ConstrainedOnceSequence(this)
}
@FixmeConcurrency
private class ConstrainedOnceSequence<T>(sequence: Sequence<T>) : Sequence<T> {
// TODO: not MT friendly.
private var sequenceRef : Sequence<T>? = sequence
override fun iterator(): Iterator<T> {
val sequence = sequenceRef
if (sequence == null) throw IllegalStateException("This sequence can be consumed only once.")
sequenceRef = null
return sequence.iterator()
}
}
/**
* Returns a sequence which invokes the function to calculate the next value on each iteration until the function returns `null`.
*
* The returned sequence is constrained to be iterated only once.
*
* @see constrainOnce
* @see kotlin.coroutines.experimental.buildSequence
*
* @sample samples.collections.Sequences.Building.generateSequence
*/
public fun <T : Any> generateSequence(nextFunction: () -> T?): Sequence<T> {
return GeneratorSequence(nextFunction, { nextFunction() }).constrainOnce()
}
/**
* Returns a sequence defined by the starting value [seed] and the function [nextFunction],
* which is invoked to calculate the next value based on the previous one on each iteration.
*
* The sequence produces values until it encounters first `null` value.
* If [seed] is `null`, an empty sequence is produced.
*
* The sequence can be iterated multiple times, each time starting with [seed].
*
* @see kotlin.coroutines.experimental.buildSequence
*
* @sample samples.collections.Sequences.Building.generateSequenceWithSeed
*/
@kotlin.internal.LowPriorityInOverloadResolution
public fun <T : Any> generateSequence(seed: T?, nextFunction: (T) -> T?): Sequence<T> =
if (seed == null)
EmptySequence
else
GeneratorSequence({ seed }, nextFunction)
/**
* Returns a sequence defined by the function [seedFunction], which is invoked to produce the starting value,
* and the [nextFunction], which is invoked to calculate the next value based on the previous one on each iteration.
*
* The sequence produces values until it encounters first `null` value.
* If [seedFunction] returns `null`, an empty sequence is produced.
*
* The sequence can be iterated multiple times.
*
* @see kotlin.coroutines.experimental.buildSequence
*
* @sample samples.collections.Sequences.Building.generateSequenceWithLazySeed
*/
public fun <T: Any> generateSequence(seedFunction: () -> T?, nextFunction: (T) -> T?): Sequence<T> =
GeneratorSequence(seedFunction, nextFunction)
/**
* Returns `true` if [element] is found in the sequence.
*/
public operator fun <@kotlin.internal.OnlyInputTypes T> Sequence<T>.contains(element: T): Boolean {
return indexOf(element) >= 0
}
/**
* Returns an element at the given [index] or throws an [IndexOutOfBoundsException] if the [index] is out of bounds of this sequence.
*/
public fun <T> Sequence<T>.elementAt(index: Int): T {
return elementAtOrElse(index) { throw IndexOutOfBoundsException("Sequence doesn't contain element at index $index.") }
}
/**
* Returns an element at the given [index] or the result of calling the [defaultValue] function if the [index] is out of bounds of this sequence.
*/
public fun <T> Sequence<T>.elementAtOrElse(index: Int, defaultValue: (Int) -> T): T {
if (index < 0)
return defaultValue(index)
val iterator = iterator()
var count = 0
while (iterator.hasNext()) {
val element = iterator.next()
if (index == count++)
return element
}
return defaultValue(index)
}
/**
* Returns an element at the given [index] or `null` if the [index] is out of bounds of this sequence.
*/
public fun <T> Sequence<T>.elementAtOrNull(index: Int): T? {
if (index < 0)
return null
val iterator = iterator()
var count = 0
while (iterator.hasNext()) {
val element = iterator.next()
if (index == count++)
return element
}
return null
}
/**
* Returns the first element matching the given [predicate], or `null` if no such element was found.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Sequence<T>.find(predicate: (T) -> Boolean): T? {
return firstOrNull(predicate)
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
@kotlin.internal.InlineOnly
public inline fun <T> Sequence<T>.findLast(predicate: (T) -> Boolean): T? {
return lastOrNull(predicate)
}
/**
* Returns first element.
* @throws [NoSuchElementException] if the sequence is empty.
*/
public fun <T> Sequence<T>.first(): T {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Sequence is empty.")
return iterator.next()
}
/**
* Returns the first element matching the given [predicate].
* @throws [NoSuchElementException] if no such element is found.
*/
public inline fun <T> Sequence<T>.first(predicate: (T) -> Boolean): T {
for (element in this) if (predicate(element)) return element
throw NoSuchElementException("Sequence contains no element matching the predicate.")
}
/**
* Returns the first element, or `null` if the sequence is empty.
*/
public fun <T> Sequence<T>.firstOrNull(): T? {
val iterator = iterator()
if (!iterator.hasNext())
return null
return iterator.next()
}
/**
* Returns the first element matching the given [predicate], or `null` if element was not found.
*/
public inline fun <T> Sequence<T>.firstOrNull(predicate: (T) -> Boolean): T? {
for (element in this) if (predicate(element)) return element
return null
}
/**
* Returns first index of [element], or -1 if the sequence does not contain element.
*/
public fun <@kotlin.internal.OnlyInputTypes T> Sequence<T>.indexOf(element: T): Int {
var index = 0
for (item in this) {
if (element == item)
return index
index++
}
return -1
}
/**
* Returns index of the first element matching the given [predicate], or -1 if the sequence does not contain such element.
*/
public inline fun <T> Sequence<T>.indexOfFirst(predicate: (T) -> Boolean): Int {
var index = 0
for (item in this) {
if (predicate(item))
return index
index++
}
return -1
}
/**
* Returns index of the last element matching the given [predicate], or -1 if the sequence does not contain such element.
*/
public inline fun <T> Sequence<T>.indexOfLast(predicate: (T) -> Boolean): Int {
var lastIndex = -1
var index = 0
for (item in this) {
if (predicate(item))
lastIndex = index
index++
}
return lastIndex
}
/**
* Returns the last element.
* @throws [NoSuchElementException] if the sequence is empty.
*/
public fun <T> Sequence<T>.last(): T {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Sequence is empty.")
var last = iterator.next()
while (iterator.hasNext())
last = iterator.next()
return last
}
/**
* Returns the last element matching the given [predicate].
* @throws [NoSuchElementException] if no such element is found.
*/
public inline fun <T> Sequence<T>.last(predicate: (T) -> Boolean): T {
var last: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
last = element
found = true
}
}
if (!found) throw NoSuchElementException("Sequence contains no element matching the predicate.")
@Suppress("UNCHECKED_CAST")
return last as T
}
/**
* Returns last index of [element], or -1 if the sequence does not contain element.
*/
public fun <@kotlin.internal.OnlyInputTypes T> Sequence<T>.lastIndexOf(element: T): Int {
var lastIndex = -1
var index = 0
for (item in this) {
if (element == item)
lastIndex = index
index++
}
return lastIndex
}
/**
* Returns the last element, or `null` if the sequence is empty.
*/
public fun <T> Sequence<T>.lastOrNull(): T? {
val iterator = iterator()
if (!iterator.hasNext())
return null
var last = iterator.next()
while (iterator.hasNext())
last = iterator.next()
return last
}
/**
* Returns the last element matching the given [predicate], or `null` if no such element was found.
*/
public inline fun <T> Sequence<T>.lastOrNull(predicate: (T) -> Boolean): T? {
var last: T? = null
for (element in this) {
if (predicate(element)) {
last = element
}
}
return last
}
/**
* Returns the single element, or throws an exception if the sequence is empty or has more than one element.
*/
public fun <T> Sequence<T>.single(): T {
val iterator = iterator()
if (!iterator.hasNext())
throw NoSuchElementException("Sequence is empty.")
val single = iterator.next()
if (iterator.hasNext())
throw IllegalArgumentException("Sequence has more than one element.")
return single
}
/**
* Returns the single element matching the given [predicate], or throws exception if there is no or more than one matching element.
*/
public inline fun <T> Sequence<T>.single(predicate: (T) -> Boolean): T {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) throw IllegalArgumentException("Sequence contains more than one matching element.")
single = element
found = true
}
}
if (!found) throw NoSuchElementException("Sequence contains no element matching the predicate.")
@Suppress("UNCHECKED_CAST")
return single as T
}
/**
* Returns single element, or `null` if the sequence is empty or has more than one element.
*/
public fun <T> Sequence<T>.singleOrNull(): T? {
val iterator = iterator()
if (!iterator.hasNext())
return null
val single = iterator.next()
if (iterator.hasNext())
return null
return single
}
/**
* Returns the single element matching the given [predicate], or `null` if element was not found or more than one element was found.
*/
public inline fun <T> Sequence<T>.singleOrNull(predicate: (T) -> Boolean): T? {
var single: T? = null
var found = false
for (element in this) {
if (predicate(element)) {
if (found) return null
single = element
found = true
}
}
if (!found) return null
return single
}
/**
* Returns a sequence containing all elements except first [n] elements.
*/
public fun <T> Sequence<T>.drop(n: Int): Sequence<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
return when {
n == 0 -> this
this is DropTakeSequence -> this.drop(n)
else -> DropSequence(this, n)
}
}
/**
* Returns a sequence containing all elements except first elements that satisfy the given [predicate].
*/
public fun <T> Sequence<T>.dropWhile(predicate: (T) -> Boolean): Sequence<T> {
return DropWhileSequence(this, predicate)
}
/**
* Returns a sequence containing only elements matching the given [predicate].
*/
public fun <T> Sequence<T>.filter(predicate: (T) -> Boolean): Sequence<T> {
return FilteringSequence(this, true, predicate)
}
/**
* Returns a sequence containing only elements matching the given [predicate].
* @param [predicate] function that takes the index of an element and the element itself
* and returns the result of predicate evaluation on the element.
*/
public fun <T> Sequence<T>.filterIndexed(predicate: (Int, T) -> Boolean): Sequence<T> {
// TODO: Rewrite with generalized MapFilterIndexingSequence
return TransformingSequence(FilteringSequence(IndexingSequence(this), true, { predicate(it.index, it.value) }), { it.value })
}
/**
* Appends all elements matching the given [predicate] to the given [destination].
* @param [predicate] function that takes the index of an element and the element itself
* and returns the result of predicate evaluation on the element.
*/
public inline fun <T, C : MutableCollection<in T>> Sequence<T>.filterIndexedTo(destination: C, predicate: (Int, T) -> Boolean): C {
forEachIndexed { index, element ->
if (predicate(index, element)) destination.add(element)
}
return destination
}
/**
* Returns a sequence containing all elements that are instances of specified type parameter R.
*/
public inline fun <reified R> Sequence<*>.filterIsInstance(): Sequence<@kotlin.internal.NoInfer R> {
@Suppress("UNCHECKED_CAST")
return filter { it is R } as Sequence<R>
}
/**
* Appends all elements that are instances of specified type parameter R to the given [destination].
*/
@Suppress("UNUSED_PARAMETER")
public inline fun <reified R, C : MutableCollection<in R>> Sequence<*>.filterIsInstanceTo(destination: C): C {
for (element in this) if (element is R) destination.add(element)
return destination
}
/**
* Returns a sequence containing all elements not matching the given [predicate].
*/
public fun <T> Sequence<T>.filterNot(predicate: (T) -> Boolean): Sequence<T> {
return FilteringSequence(this, false, predicate)
}
/**
* Returns a sequence containing all elements that are not `null`.
*/
public fun <T : Any> Sequence<T?>.filterNotNull(): Sequence<T> {
@Suppress("UNCHECKED_CAST")
return filterNot { it == null } as Sequence<T>
}
/**
* Appends all elements that are not `null` to the given [destination].
*/
public fun <C : MutableCollection<in T>, T : Any> Sequence<T?>.filterNotNullTo(destination: C): C {
for (element in this) if (element != null) destination.add(element)
return destination
}
/**
* Appends all elements not matching the given [predicate] to the given [destination].
*/
public inline fun <T, C : MutableCollection<in T>> Sequence<T>.filterNotTo(destination: C, predicate: (T) -> Boolean): C {
for (element in this) if (!predicate(element)) destination.add(element)
return destination
}
/**
* Appends all elements matching the given [predicate] to the given [destination].
*/
public inline fun <T, C : MutableCollection<in T>> Sequence<T>.filterTo(destination: C, predicate: (T) -> Boolean): C {
for (element in this) if (predicate(element)) destination.add(element)
return destination
}
/**
* Returns a sequence containing first [n] elements.
*/
public fun <T> Sequence<T>.take(n: Int): Sequence<T> {
require(n >= 0) { "Requested element count $n is less than zero." }
return when {
n == 0 -> emptySequence()
this is DropTakeSequence -> this.take(n)
else -> TakeSequence(this, n)
}
}
/**
* Returns a sequence containing first elements satisfying the given [predicate].
*/
public fun <T> Sequence<T>.takeWhile(predicate: (T) -> Boolean): Sequence<T> {
return TakeWhileSequence(this, predicate)
}
/**
* Returns a sequence that yields elements of this sequence sorted according to their natural sort order.
*/
public fun <T : Comparable<T>> Sequence<T>.sorted(): Sequence<T> {
return object : Sequence<T> {
override fun iterator(): Iterator<T> {
val sortedList = [email protected]()
sortedList.sort()
return sortedList.iterator()
}
}
}
/**
* Returns a sequence that yields elements of this sequence sorted according to natural sort order of the value returned by specified [selector] function.
*/
public inline fun <T, R : Comparable<R>> Sequence<T>.sortedBy(crossinline selector: (T) -> R?): Sequence<T> {
return sortedWith(compareBy(selector))
}
/**
* Returns a sequence that yields elements of this sequence sorted descending according to natural sort order of the value returned by specified [selector] function.
*/
public inline fun <T, R : Comparable<R>> Sequence<T>.sortedByDescending(crossinline selector: (T) -> R?): Sequence<T> {
return sortedWith(compareByDescending(selector))
}
/**
* Returns a sequence that yields elements of this sequence sorted descending according to their natural sort order.
*/
public fun <T : Comparable<T>> Sequence<T>.sortedDescending(): Sequence<T> {
return sortedWith(reverseOrder())
}
/**
* Returns a sequence that yields elements of this sequence sorted according to the specified [comparator].
*/
public fun <T> Sequence<T>.sortedWith(comparator: Comparator<in T>): Sequence<T> {
return object : Sequence<T> {
override fun iterator(): Iterator<T> {
val sortedList = [email protected]()
sortedList.sortWith(comparator)
return sortedList.iterator()
}
}
}
/**
* Returns a [Map] containing key-value pairs provided by [transform] function
* applied to elements of the given sequence.
*
* If any of two pairs would have the same key the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original sequence.
*/
public inline fun <T, K, V> Sequence<T>.associate(transform: (T) -> Pair<K, V>): Map<K, V> {
return associateTo(LinkedHashMap<K, V>(), transform)
}
/**
* Returns a [Map] containing the elements from the given sequence indexed by the key
* returned from [keySelector] function applied to each element.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original sequence.
*/
public inline fun <T, K> Sequence<T>.associateBy(keySelector: (T) -> K): Map<K, T> {
return associateByTo(LinkedHashMap<K, T>(), keySelector)
}
/**
* Returns a [Map] containing the values provided by [valueTransform] and indexed by [keySelector] functions applied to elements of the given sequence.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*
* The returned map preserves the entry iteration order of the original sequence.
*/
public inline fun <T, K, V> Sequence<T>.associateBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, V> {
return associateByTo(LinkedHashMap<K, V>(), keySelector, valueTransform)
}
/**
* Populates and returns the [destination] mutable map with key-value pairs,
* where key is provided by the [keySelector] function applied to each element of the given sequence
* and value is the element itself.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*/
public inline fun <T, K, M : MutableMap<in K, in T>> Sequence<T>.associateByTo(destination: M, keySelector: (T) -> K): M {
for (element in this) {
destination.put(keySelector(element), element)
}
return destination
}
/**
* Populates and returns the [destination] mutable map with key-value pairs,
* where key is provided by the [keySelector] function and
* and value is provided by the [valueTransform] function applied to elements of the given sequence.
*
* If any two elements would have the same key returned by [keySelector] the last one gets added to the map.
*/
public inline fun <T, K, V, M : MutableMap<in K, in V>> Sequence<T>.associateByTo(destination: M, keySelector: (T) -> K, valueTransform: (T) -> V): M {
for (element in this) {
destination.put(keySelector(element), valueTransform(element))
}
return destination
}
/**
* Populates and returns the [destination] mutable map with key-value pairs
* provided by [transform] function applied to each element of the given sequence.
*
* If any of two pairs would have the same key the last one gets added to the map.
*/
public inline fun <T, K, V, M : MutableMap<in K, in V>> Sequence<T>.associateTo(destination: M, transform: (T) -> Pair<K, V>): M {
for (element in this) {
destination += transform(element)
}
return destination
}
/**
* Appends all elements to the given [destination] collection.
*/
public fun <T, C : MutableCollection<in T>> Sequence<T>.toCollection(destination: C): C {
for (item in this) {
destination.add(item)
}
return destination
}
/**
* Returns a [HashSet] of all elements.
*/
public fun <T> Sequence<T>.toHashSet(): HashSet<T> {
return toCollection(HashSet<T>())
}
/**
* Returns a [List] containing all elements.
*/
public fun <T> Sequence<T>.toList(): List<T> {
return this.toMutableList().optimizeReadOnlyList()
}
/**
* Returns a [MutableList] filled with all elements of this sequence.
*/
public fun <T> Sequence<T>.toMutableList(): MutableList<T> {
return toCollection(ArrayList<T>())
}
/**
* Returns a [Set] of all elements.
*
* The returned set preserves the element iteration order of the original sequence.
*/
public fun <T> Sequence<T>.toSet(): Set<T> {
return toCollection(LinkedHashSet<T>()).optimizeReadOnlySet()
}
/**
* Returns a single sequence of all elements from results of [transform] function being invoked on each element of original sequence.
*/
public fun <T, R> Sequence<T>.flatMap(transform: (T) -> Sequence<R>): Sequence<R> {
return FlatteningSequence(this, transform, { it.iterator() })
}
/**
* Appends all elements yielded from results of [transform] function being invoked on each element of original sequence, to the given [destination].
*/
public inline fun <T, R, C : MutableCollection<in R>> Sequence<T>.flatMapTo(destination: C, transform: (T) -> Sequence<R>): C {
for (element in this) {
val list = transform(element)
destination.addAll(list)
}
return destination
}
/**
* Groups elements of the original sequence by the key returned by the given [keySelector] function
* applied to each element and returns a map where each group key is associated with a list of corresponding elements.
*
* The returned map preserves the entry iteration order of the keys produced from the original sequence.
*
* @sample samples.collections.Collections.Transformations.groupBy
*/
public inline fun <T, K> Sequence<T>.groupBy(keySelector: (T) -> K): Map<K, List<T>> {
return groupByTo(LinkedHashMap<K, MutableList<T>>(), keySelector)
}
/**
* Groups values returned by the [valueTransform] function applied to each element of the original sequence
* by the key returned by the given [keySelector] function applied to the element
* and returns a map where each group key is associated with a list of corresponding values.
*
* The returned map preserves the entry iteration order of the keys produced from the original sequence.
*
* @sample samples.collections.Collections.Transformations.groupByKeysAndValues
*/
public inline fun <T, K, V> Sequence<T>.groupBy(keySelector: (T) -> K, valueTransform: (T) -> V): Map<K, List<V>> {
return groupByTo(LinkedHashMap<K, MutableList<V>>(), keySelector, valueTransform)
}
/**
* Groups elements of the original sequence by the key returned by the given [keySelector] function
* applied to each element and puts to the [destination] map each group key associated with a list of corresponding elements.
*
* @return The [destination] map.
*
* @sample samples.collections.Collections.Transformations.groupBy
*/
public inline fun <T, K, M : MutableMap<in K, MutableList<T>>> Sequence<T>.groupByTo(destination: M, keySelector: (T) -> K): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<T>() }
list.add(element)
}
return destination
}
/**
* Groups values returned by the [valueTransform] function applied to each element of the original sequence
* by the key returned by the given [keySelector] function applied to the element
* and puts to the [destination] map each group key associated with a list of corresponding values.
*
* @return The [destination] map.
*
* @sample samples.collections.Collections.Transformations.groupByKeysAndValues
*/
public inline fun <T, K, V, M : MutableMap<in K, MutableList<V>>> Sequence<T>.groupByTo(destination: M, keySelector: (T) -> K, valueTransform: (T) -> V): M {
for (element in this) {
val key = keySelector(element)
val list = destination.getOrPut(key) { ArrayList<V>() }
list.add(valueTransform(element))
}
return destination
}
/**
* Creates a [Grouping] source from a sequence to be used later with one of group-and-fold operations
* using the specified [keySelector] function to extract a key from each element.
*/
public inline fun <T, K> Sequence<T>.groupingBy(crossinline keySelector: (T) -> K): Grouping<T, K> {
return object : Grouping<T, K> {
override fun sourceIterator(): Iterator<T> = [email protected]()
override fun keyOf(element: T): K = keySelector(element)
}
}
/**
* Returns a sequence containing the results of applying the given [transform] function
* to each element in the original sequence.
*/
public fun <T, R> Sequence<T>.map(transform: (T) -> R): Sequence<R> {
return TransformingSequence(this, transform)
}
/**
* Returns a sequence containing the results of applying the given [transform] function
* to each element and its index in the original sequence.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public fun <T, R> Sequence<T>.mapIndexed(transform: (Int, T) -> R): Sequence<R> {
return TransformingIndexedSequence(this, transform)
}
/**
* Returns a sequence containing only the non-null results of applying the given [transform] function
* to each element and its index in the original sequence.
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public fun <T, R : Any> Sequence<T>.mapIndexedNotNull(transform: (Int, T) -> R?): Sequence<R> {
return TransformingIndexedSequence(this, transform).filterNotNull()
}
/**
* Applies the given [transform] function to each element and its index in the original sequence
* and appends only the non-null results to the given [destination].
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline fun <T, R : Any, C : MutableCollection<in R>> Sequence<T>.mapIndexedNotNullTo(destination: C, transform: (Int, T) -> R?): C {
forEachIndexed { index, element -> transform(index, element)?.let { destination.add(it) } }
return destination
}
/**
* Applies the given [transform] function to each element and its index in the original sequence
* and appends the results to the given [destination].
* @param [transform] function that takes the index of an element and the element itself
* and returns the result of the transform applied to the element.
*/
public inline fun <T, R, C : MutableCollection<in R>> Sequence<T>.mapIndexedTo(destination: C, transform: (Int, T) -> R): C {
var index = 0
for (item in this)
destination.add(transform(index++, item))
return destination
}
/**
* Returns a sequence containing only the non-null results of applying the given [transform] function
* to each element in the original sequence.
*/
public fun <T, R : Any> Sequence<T>.mapNotNull(transform: (T) -> R?): Sequence<R> {
return TransformingSequence(this, transform).filterNotNull()
}
/**
* Applies the given [transform] function to each element in the original sequence
* and appends only the non-null results to the given [destination].
*/
public inline fun <T, R : Any, C : MutableCollection<in R>> Sequence<T>.mapNotNullTo(destination: C, transform: (T) -> R?): C {
forEach { element -> transform(element)?.let { destination.add(it) } }
return destination
}
/**
* Applies the given [transform] function to each element of the original sequence
* and appends the results to the given [destination].
*/
public inline fun <T, R, C : MutableCollection<in R>> Sequence<T>.mapTo(destination: C, transform: (T) -> R): C {
for (item in this)
destination.add(transform(item))
return destination
}
/**
* Returns a sequence of [IndexedValue] for each element of the original sequence.
*/
public fun <T> Sequence<T>.withIndex(): Sequence<IndexedValue<T>> {
return IndexingSequence(this)
}
/**
* Returns a sequence containing only distinct elements from the given sequence.
*
* The elements in the resulting sequence are in the same order as they were in the source sequence.
*/
public fun <T> Sequence<T>.distinct(): Sequence<T> {
return this.distinctBy { it }
}
/**
* Returns a sequence containing only elements from the given sequence
* having distinct keys returned by the given [selector] function.
*
* The elements in the resulting sequence are in the same order as they were in the source sequence.
*/
public fun <T, K> Sequence<T>.distinctBy(selector: (T) -> K): Sequence<T> {
return DistinctSequence(this, selector)
}
/**
* Returns a mutable set containing all distinct elements from the given sequence.
*
* The returned set preserves the element iteration order of the original sequence.
*/
public fun <T> Sequence<T>.toMutableSet(): MutableSet<T> {
val set = LinkedHashSet<T>()
for (item in this) set.add(item)
return set
}
/**
* Returns `true` if all elements match the given [predicate].
*/
public inline fun <T> Sequence<T>.all(predicate: (T) -> Boolean): Boolean {
for (element in this) if (!predicate(element)) return false
return true
}
/**
* Returns `true` if sequence has at least one element.
*/
public fun <T> Sequence<T>.any(): Boolean {
for (element in this) return true
return false
}
/**
* Returns `true` if at least one element matches the given [predicate].
*/
public inline fun <T> Sequence<T>.any(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return true
return false
}
/**
* Returns the number of elements in this sequence.
*/
public fun <T> Sequence<T>.count(): Int {
var count = 0
for (element in this) count++
return count
}
/**
* Returns the number of elements matching the given [predicate].
*/
public inline fun <T> Sequence<T>.count(predicate: (T) -> Boolean): Int {
var count = 0
for (element in this) if (predicate(element)) count++
return count
}
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right to current accumulator value and each element.
*/
public inline fun <T, R> Sequence<T>.fold(initial: R, operation: (R, T) -> R): R {
var accumulator = initial
for (element in this) accumulator = operation(accumulator, element)
return accumulator
}
/**
* Accumulates value starting with [initial] value and applying [operation] from left to right
* to current accumulator value and each element with its index in the original sequence.
* @param [operation] function that takes the index of an element, current accumulator value
* and the element itself, and calculates the next accumulator value.
*/
public inline fun <T, R> Sequence<T>.foldIndexed(initial: R, operation: (Int, R, T) -> R): R {
var index = 0
var accumulator = initial
for (element in this) accumulator = operation(index++, accumulator, element)
return accumulator
}
/**
* Performs the given [action] on each element.
*/
public inline fun <T> Sequence<T>.forEach(action: (T) -> Unit): Unit {
for (element in this) action(element)
}
/**
* Performs the given [action] on each element, providing sequential index with the element.
* @param [action] function that takes the index of an element and the element itself
* and performs the desired action on the element.
*/
public inline fun <T> Sequence<T>.forEachIndexed(action: (Int, T) -> Unit): Unit {
var index = 0
for (item in this) action(index++, item)
}
/**
* Returns the largest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
public fun Sequence<Double>.max(): Double? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
if (max.isNaN()) return max
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (max < e) max = e
}
return max
}
/**
* Returns the largest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
public fun Sequence<Float>.max(): Float? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
if (max.isNaN()) return max
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (max < e) max = e
}
return max
}
/**
* Returns the largest element or `null` if there are no elements.
*/
public fun <T : Comparable<T>> Sequence<T>.max(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (max < e) max = e
}
return max
}
/**
* Returns the first element yielding the largest value of the given function or `null` if there are no elements.
*/
public inline fun <T, R : Comparable<R>> Sequence<T>.maxBy(selector: (T) -> R): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var maxElem = iterator.next()
var maxValue = selector(maxElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = selector(e)
if (maxValue < v) {
maxElem = e
maxValue = v
}
}
return maxElem
}
/**
* Returns the first element having the largest value according to the provided [comparator] or `null` if there are no elements.
*/
public fun <T> Sequence<T>.maxWith(comparator: Comparator<in T>): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var max = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (comparator.compare(max, e) < 0) max = e
}
return max
}
/**
* Returns the smallest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
public fun Sequence<Double>.min(): Double? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
if (min.isNaN()) return min
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (min > e) min = e
}
return min
}
/**
* Returns the smallest element or `null` if there are no elements.
*
* If any of elements is `NaN` returns `NaN`.
*/
public fun Sequence<Float>.min(): Float? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
if (min.isNaN()) return min
while (iterator.hasNext()) {
val e = iterator.next()
if (e.isNaN()) return e
if (min > e) min = e
}
return min
}
/**
* Returns the smallest element or `null` if there are no elements.
*/
public fun <T : Comparable<T>> Sequence<T>.min(): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (min > e) min = e
}
return min
}
/**
* Returns the first element yielding the smallest value of the given function or `null` if there are no elements.
*/
public inline fun <T, R : Comparable<R>> Sequence<T>.minBy(selector: (T) -> R): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var minElem = iterator.next()
var minValue = selector(minElem)
while (iterator.hasNext()) {
val e = iterator.next()
val v = selector(e)
if (minValue > v) {
minElem = e
minValue = v
}
}
return minElem
}
/**
* Returns the first element having the smallest value according to the provided [comparator] or `null` if there are no elements.
*/
public fun <T> Sequence<T>.minWith(comparator: Comparator<in T>): T? {
val iterator = iterator()
if (!iterator.hasNext()) return null
var min = iterator.next()
while (iterator.hasNext()) {
val e = iterator.next()
if (comparator.compare(min, e) > 0) min = e
}
return min
}
/**
* Returns `true` if the sequence has no elements.
*/
public fun <T> Sequence<T>.none(): Boolean {
for (element in this) return false
return true
}
/**
* Returns `true` if no elements match the given [predicate].
*/
public inline fun <T> Sequence<T>.none(predicate: (T) -> Boolean): Boolean {
for (element in this) if (predicate(element)) return false
return true
}
/**
* Returns a sequence which performs the given [action] on each element of the original sequence as they pass though it.
*/
public fun <T> Sequence<T>.onEach(action: (T) -> Unit): Sequence<T> {
return map {
action(it)
it
}
}
/**
* Accumulates value starting with the first element and applying [operation] from left to right to current accumulator value and each element.
*/
public inline fun <S, T: S> Sequence<T>.reduce(operation: (S, T) -> S): S {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty sequence can't be reduced.")
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(accumulator, iterator.next())
}
return accumulator
}
/**
* Accumulates value starting with the first element and applying [operation] from left to right
* to current accumulator value and each element with its index in the original sequence.
* @param [operation] function that takes the index of an element, current accumulator value
* and the element itself and calculates the next accumulator value.
*/
public inline fun <S, T: S> Sequence<T>.reduceIndexed(operation: (Int, S, T) -> S): S {
val iterator = this.iterator()
if (!iterator.hasNext()) throw UnsupportedOperationException("Empty sequence can't be reduced.")
var index = 1
var accumulator: S = iterator.next()
while (iterator.hasNext()) {
accumulator = operation(index++, accumulator, iterator.next())
}
return accumulator
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the sequence.
*/
public inline fun <T> Sequence<T>.sumBy(selector: (T) -> Int): Int {
var sum: Int = 0
for (element in this) {
sum += selector(element)
}
return sum
}
/**
* Returns the sum of all values produced by [selector] function applied to each element in the sequence.
*/
public inline fun <T> Sequence<T>.sumByDouble(selector: (T) -> Double): Double {
var sum: Double = 0.0
for (element in this) {
sum += selector(element)
}
return sum
}
/**
* Returns an original collection containing all the non-`null` elements, throwing an [IllegalArgumentException] if there are any `null` elements.
*/
public fun <T : Any> Sequence<T?>.requireNoNulls(): Sequence<T> {
return map { it ?: throw IllegalArgumentException("null element found in $this.") }
}
/**
* Returns a sequence containing all elements of the original sequence without the first occurrence of the given [element].
*/
public operator fun <T> Sequence<T>.minus(element: T): Sequence<T> {
return object: Sequence<T> {
override fun iterator(): Iterator<T> {
var removed = false
return [email protected] { if (!removed && it == element) { removed = true; false } else true }.iterator()
}
}
}
/**
* Returns a sequence containing all elements of original sequence except the elements contained in the given [elements] array.
*
* Note that the source sequence and the array being subtracted are iterated only when an `iterator` is requested from
* the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
*/
public operator fun <T> Sequence<T>.minus(elements: Array<out T>): Sequence<T> {
if (elements.isEmpty()) return this
return object: Sequence<T> {
override fun iterator(): Iterator<T> {
val other = elements.toHashSet()
return [email protected] { it in other }.iterator()
}
}
}
/**
* Returns a sequence containing all elements of original sequence except the elements contained in the given [elements] collection.
*
* Note that the source sequence and the collection being subtracted are iterated only when an `iterator` is requested from
* the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
*/
public operator fun <T> Sequence<T>.minus(elements: Iterable<T>): Sequence<T> {
return object: Sequence<T> {
override fun iterator(): Iterator<T> {
val other = elements.convertToSetForSetOperation()
if (other.isEmpty())
return [email protected]()
else
return [email protected] { it in other }.iterator()
}
}
}
/**
* Returns a sequence containing all elements of original sequence except the elements contained in the given [elements] sequence.
*
* Note that the source sequence and the sequence being subtracted are iterated only when an `iterator` is requested from
* the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
*/
public operator fun <T> Sequence<T>.minus(elements: Sequence<T>): Sequence<T> {
return object: Sequence<T> {
override fun iterator(): Iterator<T> {
val other = elements.toHashSet()
if (other.isEmpty())
return [email protected]()
else
return [email protected] { it in other }.iterator()
}
}
}
/**
* Returns a sequence containing all elements of the original sequence without the first occurrence of the given [element].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Sequence<T>.minusElement(element: T): Sequence<T> {
return minus(element)
}
/**
* Splits the original sequence into pair of lists,
* where *first* list contains elements for which [predicate] yielded `true`,
* while *second* list contains elements for which [predicate] yielded `false`.
*/
public inline fun <T> Sequence<T>.partition(predicate: (T) -> Boolean): Pair<List<T>, List<T>> {
val first = ArrayList<T>()
val second = ArrayList<T>()
for (element in this) {
if (predicate(element)) {
first.add(element)
} else {
second.add(element)
}
}
return Pair(first, second)
}
/**
* Returns a sequence containing all elements of the original sequence and then the given [element].
*/
public operator fun <T> Sequence<T>.plus(element: T): Sequence<T> {
return sequenceOf(this, sequenceOf(element)).flatten()
}
/**
* Returns a sequence containing all elements of original sequence and then all elements of the given [elements] array.
*
* Note that the source sequence and the array being added are iterated only when an `iterator` is requested from
* the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
*/
public operator fun <T> Sequence<T>.plus(elements: Array<out T>): Sequence<T> {
return this.plus(elements.asList())
}
/**
* Returns a sequence containing all elements of original sequence and then all elements of the given [elements] collection.
*
* Note that the source sequence and the collection being added are iterated only when an `iterator` is requested from
* the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
*/
public operator fun <T> Sequence<T>.plus(elements: Iterable<T>): Sequence<T> {
return sequenceOf(this, elements.asSequence()).flatten()
}
/**
* Returns a sequence containing all elements of original sequence and then all elements of the given [elements] sequence.
*
* Note that the source sequence and the sequence being added are iterated only when an `iterator` is requested from
* the resulting sequence. Changing any of them between successive calls to `iterator` may affect the result.
*/
public operator fun <T> Sequence<T>.plus(elements: Sequence<T>): Sequence<T> {
return sequenceOf(this, elements).flatten()
}
/**
* Returns a sequence containing all elements of the original sequence and then the given [element].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Sequence<T>.plusElement(element: T): Sequence<T> {
return plus(element)
}
/**
* Returns a sequence of pairs built from elements of both sequences with same indexes.
* Resulting sequence has length of shortest input sequence.
*/
public infix fun <T, R> Sequence<T>.zip(other: Sequence<R>): Sequence<Pair<T, R>> {
return MergingSequence(this, other) { t1, t2 -> t1 to t2 }
}
/**
* Returns a sequence of values built from elements of both collections with same indexes using provided [transform]. Resulting sequence has length of shortest input sequences.
*/
public fun <T, R, V> Sequence<T>.zip(other: Sequence<R>, transform: (T, R) -> V): Sequence<V> {
return MergingSequence(this, other, transform)
}
/**
* Appends the string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*/
public fun <T, A : Appendable> Sequence<T>.joinTo(buffer: A, separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): A {
buffer.append(prefix)
var count = 0
for (element in this) {
if (++count > 1) buffer.append(separator)
if (limit < 0 || count <= limit) {
buffer.appendElement(element, transform)
} else break
}
if (limit >= 0 && count > limit) buffer.append(truncated)
buffer.append(postfix)
return buffer
}
/**
* Creates a string from all the elements separated using [separator] and using the given [prefix] and [postfix] if supplied.
*
* If the collection could be huge, you can specify a non-negative value of [limit], in which case only the first [limit]
* elements will be appended, followed by the [truncated] string (which defaults to "...").
*/
public fun <T> Sequence<T>.joinToString(separator: CharSequence = ", ", prefix: CharSequence = "", postfix: CharSequence = "", limit: Int = -1, truncated: CharSequence = "...", transform: ((T) -> CharSequence)? = null): String {
return joinTo(StringBuilder(), separator, prefix, postfix, limit, truncated, transform).toString()
}
/**
* Creates an [Iterable] instance that wraps the original sequence returning its elements when being iterated.
*/
public fun <T> Sequence<T>.asIterable(): Iterable<T> {
return Iterable { this.iterator() }
}
/**
* Returns this sequence as a [Sequence].
*/
@kotlin.internal.InlineOnly
public inline fun <T> Sequence<T>.asSequence(): Sequence<T> {
return this
}
/**
* Returns an average value of elements in the sequence.
*/
public fun Sequence<Byte>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) 0.0 else sum / count
}
/**
* Returns an average value of elements in the sequence.
*/
public fun Sequence<Short>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) 0.0 else sum / count
}
/**
* Returns an average value of elements in the sequence.
*/
public fun Sequence<Int>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) 0.0 else sum / count
}
/**
* Returns an average value of elements in the sequence.
*/
public fun Sequence<Long>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) 0.0 else sum / count
}
/**
* Returns an average value of elements in the sequence.
*/
public fun Sequence<Float>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) 0.0 else sum / count
}
/**
* Returns an average value of elements in the sequence.
*/
public fun Sequence<Double>.average(): Double {
var sum: Double = 0.0
var count: Int = 0
for (element in this) {
sum += element
count += 1
}
return if (count == 0) 0.0 else sum / count
}
/**
* Returns the sum of all elements in the sequence.
*/
public fun Sequence<Byte>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the sequence.
*/
public fun Sequence<Short>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the sequence.
*/
public fun Sequence<Int>.sum(): Int {
var sum: Int = 0
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the sequence.
*/
public fun Sequence<Long>.sum(): Long {
var sum: Long = 0L
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the sequence.
*/
public fun Sequence<Float>.sum(): Float {
var sum: Float = 0.0f
for (element in this) {
sum += element
}
return sum
}
/**
* Returns the sum of all elements in the sequence.
*/
public fun Sequence<Double>.sum(): Double {
var sum: Double = 0.0
for (element in this) {
sum += element
}
return sum
}
| apache-2.0 | da47998eb76afdb92febf49335542de2 | 32.375425 | 244 | 0.652896 | 4.130056 | false | false | false | false |
smmribeiro/intellij-community | plugins/kotlin/project-wizard/core/src/org/jetbrains/kotlin/tools/projectWizard/Versions.kt | 1 | 1907 | /*
* Copyright 2010-2020 JetBrains s.r.o. and Kotlin Programming Language contributors.
* Use of this source code is governed by the Apache 2.0 license that can be found in the license/LICENSE.txt file.
*/
package org.jetbrains.kotlin.tools.projectWizard
import org.jetbrains.kotlin.tools.projectWizard.settings.version.Version
@Suppress("ClassName", "SpellCheckingInspection")
object Versions {
val KOTLIN = version("1.4.10") // used as fallback version
val GRADLE = version("6.6.1")
val KTOR = version("1.5.2")
val JUNIT = version("4.13")
val JUNIT5 = version("5.6.0")
val JETBRAINS_COMPOSE = version("1.0.0")
val KOTLIN_VERSION_FOR_COMPOSE = version("1.5.31")
val GRADLE_VERSION_FOR_COMPOSE = version("6.9")
object COMPOSE {
val ANDROID_ACTIVITY_COMPOSE = version("1.3.0")
}
object ANDROID {
val ANDROID_MATERIAL = version("1.2.1")
val ANDROIDX_APPCOMPAT = version("1.2.0")
val ANDROIDX_CONSTRAINTLAYOUT = version("2.0.2")
val ANDROIDX_KTX = version("1.3.1")
}
object KOTLINX {
val KOTLINX_HTML = version("0.7.2")
val KOTLINX_NODEJS: Version = version("0.0.7")
}
object JS_WRAPPERS {
val KOTLIN_REACT = wrapperVersion("17.0.2")
val KOTLIN_REACT_DOM = KOTLIN_REACT
val KOTLIN_STYLED = wrapperVersion("5.3.0")
val KOTLIN_REACT_ROUTER_DOM = wrapperVersion("5.2.0")
val KOTLIN_REDUX = wrapperVersion("4.0.5")
val KOTLIN_REACT_REDUX = wrapperVersion("7.2.3")
private fun wrapperVersion(version: String): Version =
version("$version-pre.206-kotlin-1.5.10")
}
object GRADLE_PLUGINS {
val ANDROID = version("4.0.2")
}
object MAVEN_PLUGINS {
val SUREFIRE = version("2.22.2")
val FAILSAFE = SUREFIRE
}
}
private fun version(version: String) = Version.fromString(version)
| apache-2.0 | d1d7a1207d50737e9d749751875a4f10 | 30.783333 | 115 | 0.64237 | 3.54461 | false | false | false | false |
smmribeiro/intellij-community | platform/script-debugger/backend/src/debugger/ScriptManagerBase.kt | 25 | 1796 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.jetbrains.debugger
import com.intellij.util.Url
import org.jetbrains.concurrency.Promise
import org.jetbrains.concurrency.PromiseManager
import org.jetbrains.concurrency.rejectedPromise
abstract class ScriptManagerBase<SCRIPT : ScriptBase> : ScriptManager {
@Suppress("UNCHECKED_CAST")
@SuppressWarnings("unchecked")
private val scriptSourceLoader = object : PromiseManager<ScriptBase, String>(ScriptBase::class.java) {
override fun load(script: ScriptBase) = loadScriptSource(script as SCRIPT)
}
protected abstract fun loadScriptSource(script: SCRIPT): Promise<String>
override fun getSource(script: Script): Promise<String> {
if (!containsScript(script)) {
return rejectedPromise("No Script")
}
@Suppress("UNCHECKED_CAST")
return scriptSourceLoader.get(script as SCRIPT)
}
override fun hasSource(script: Script): Boolean {
@Suppress("UNCHECKED_CAST")
return scriptSourceLoader.has(script as SCRIPT)
}
fun setSource(script: SCRIPT, source: String?) {
scriptSourceLoader.set(script, source)
}
}
val Url.isSpecial: Boolean
get() = !isInLocalFileSystem && (scheme == null || scheme == VM_SCHEME || authority == null) | apache-2.0 | 72a2805c94bee2358a12561243dba85e | 34.235294 | 104 | 0.744989 | 4.235849 | false | false | false | false |
smmribeiro/intellij-community | platform/diff-impl/src/com/intellij/diff/tools/combined/CombinedDiffScrollSupport.kt | 1 | 4022 | // 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.diff.tools.combined
import com.intellij.diff.tools.util.PrevNextDifferenceIterable
import com.intellij.diff.util.DiffUtil
import com.intellij.openapi.Disposable
import com.intellij.openapi.editor.*
import com.intellij.openapi.editor.impl.ScrollingModelImpl
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.Disposer
import java.awt.Point
import javax.swing.JScrollPane
import javax.swing.SwingUtilities
enum class ScrollPolicy {
DIFF_BLOCK, DIFF_CHANGE
}
internal class CombinedDiffScrollSupport(project: Project?, private val viewer: CombinedDiffViewer) {
internal val currentPrevNextIterable = CombinedDiffPrevNextDifferenceIterable()
internal val blockIterable = CombinedDiffPrevNextBlocksIterable()
private val combinedEditorsScrollingModel = ScrollingModelImpl(CombinedEditorsScrollingModelHelper(project, viewer))
fun scroll(index: Int, block: CombinedDiffBlock, scrollPolicy: ScrollPolicy){
if (scrollPolicy == ScrollPolicy.DIFF_BLOCK || !block.content.viewer.isEditorBased) {
scrollToDiffBlock(index)
}
else if (scrollPolicy == ScrollPolicy.DIFF_CHANGE) {
scrollToDiffChangeWithCaret()
}
}
private fun scrollToDiffChangeWithCaret() {
if (viewer.getCurrentDiffViewer().isEditorBased) { //avoid scrolling for non editor based viewers
combinedEditorsScrollingModel.scrollToCaret(ScrollType.CENTER)
}
}
private fun scrollToDiffBlock(index: Int) {
if (index in viewer.diffBlocks.indices) {
viewer.contentPanel.components.getOrNull(index)?.bounds?.let(viewer.contentPanel::scrollRectToVisible)
}
}
internal inner class CombinedDiffPrevNextDifferenceIterable : PrevNextDifferenceIterable {
override fun canGoNext(): Boolean {
return viewer.getDifferencesIterable()?.canGoNext() == true
}
override fun canGoPrev(): Boolean {
return viewer.getDifferencesIterable()?.canGoPrev() == true
}
override fun goNext() {
viewer.getDifferencesIterable()?.goNext()
scrollToDiffChangeWithCaret()
}
override fun goPrev() {
viewer.getDifferencesIterable()?.goPrev()
scrollToDiffChangeWithCaret()
}
}
internal inner class CombinedDiffPrevNextBlocksIterable : PrevNextDifferenceIterable {
var index = 0
override fun canGoNext(): Boolean = index < viewer.diffBlocks.size - 1
override fun canGoPrev(): Boolean = index > 0
override fun goNext() {
index++
}
override fun goPrev() {
index--
}
}
private inner class CombinedEditorsScrollingModelHelper(project: Project?, disposable: Disposable) :
ScrollingModel.Supplier, ScrollingModel.ScrollingHelper, Disposable {
private val dummyEditor: Editor //needed for ScrollingModelImpl initialization
init {
dummyEditor = DiffUtil.createEditor(EditorFactory.getInstance().createDocument(""), project, true, true)
Disposer.register(disposable, this)
}
override fun getEditor(): Editor = viewer.getDiffViewer(blockIterable.index)?.editor ?: dummyEditor
override fun getScrollPane(): JScrollPane = viewer.scrollPane
override fun getScrollingHelper(): ScrollingModel.ScrollingHelper = this
override fun calculateScrollingLocation(editor: Editor, pos: VisualPosition): Point {
val targetLocationInEditor = editor.visualPositionToXY(pos)
return SwingUtilities.convertPoint(editor.component, targetLocationInEditor, scrollPane.viewport.view)
}
override fun calculateScrollingLocation(editor: Editor, pos: LogicalPosition): Point {
val targetLocationInEditor = editor.logicalPositionToXY(pos)
return SwingUtilities.convertPoint(editor.component, targetLocationInEditor, scrollPane.viewport.view)
}
override fun dispose() {
EditorFactory.getInstance().releaseEditor(dummyEditor)
}
}
}
| apache-2.0 | 0681d548ceebf1ca06aa330b3f5b5350 | 34.280702 | 158 | 0.757086 | 4.687646 | false | false | false | false |
google/intellij-community | plugins/kotlin/fir/src/org/jetbrains/kotlin/idea/quickfix/KotlinK2QuickFixRegistrar.kt | 2 | 13248 | // Copyright 2000-2022 JetBrains s.r.o. and contributors. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.kotlin.idea.quickfix
import org.jetbrains.kotlin.analysis.api.fir.diagnostics.KtFirDiagnostic
import org.jetbrains.kotlin.idea.core.overrideImplement.MemberNotImplementedQuickfixFactories
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.KotlinQuickFixRegistrar
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.KotlinQuickFixesList
import org.jetbrains.kotlin.idea.codeinsight.api.applicators.fixes.KtQuickFixesListBuilder
import org.jetbrains.kotlin.idea.quickfix.fixes.*
class KotlinK2QuickFixRegistrar : KotlinQuickFixRegistrar() {
private val keywords = KtQuickFixesListBuilder.registerPsiQuickFix {
registerPsiQuickFixes(KtFirDiagnostic.RedundantModifier::class, RemoveModifierFixBase.removeRedundantModifier)
registerPsiQuickFixes(KtFirDiagnostic.IncompatibleModifiers::class, RemoveModifierFixBase.removeNonRedundantModifier)
registerPsiQuickFixes(KtFirDiagnostic.RepeatedModifier::class, RemoveModifierFixBase.removeNonRedundantModifier)
registerPsiQuickFixes(KtFirDiagnostic.DeprecatedModifierPair::class, RemoveModifierFixBase.removeRedundantModifier)
registerPsiQuickFixes(KtFirDiagnostic.TypeParametersInEnum::class, RemoveModifierFixBase.removeRedundantModifier)
registerPsiQuickFixes(KtFirDiagnostic.RedundantOpenInInterface::class, RemoveModifierFixBase.removeRedundantOpenModifier)
registerPsiQuickFixes(KtFirDiagnostic.NonAbstractFunctionWithNoBody::class, AddFunctionBodyFix, AddModifierFix.addAbstractModifier)
registerPsiQuickFixes(
KtFirDiagnostic.AbstractPropertyInNonAbstractClass::class,
AddModifierFix.addAbstractToContainingClass,
RemoveModifierFixBase.removeAbstractModifier
)
registerPsiQuickFixes(
KtFirDiagnostic.AbstractFunctionInNonAbstractClass::class,
AddModifierFix.addAbstractToContainingClass,
RemoveModifierFixBase.removeAbstractModifier
)
registerPsiQuickFixes(
KtFirDiagnostic.NonFinalMemberInFinalClass::class,
AddModifierFix.addOpenToContainingClass,
RemoveModifierFixBase.removeOpenModifier
)
registerPsiQuickFixes(
KtFirDiagnostic.PrivateSetterForOpenProperty::class,
AddModifierFix.addFinalToProperty,
RemoveModifierFixBase.removePrivateModifier
)
registerPsiQuickFixes(
KtFirDiagnostic.PrivateSetterForAbstractProperty::class,
RemoveModifierFixBase.removePrivateModifier
)
registerPsiQuickFixes(
KtFirDiagnostic.NestedClassNotAllowed::class,
AddModifierFix.addInnerModifier
)
registerPsiQuickFixes(
KtFirDiagnostic.WrongModifierTarget::class,
RemoveModifierFixBase.removeNonRedundantModifier,
ChangeVariableMutabilityFix.CONST_VAL_FACTORY
)
registerPsiQuickFixes(
KtFirDiagnostic.AbstractMemberNotImplemented::class,
AddModifierFix.addAbstractModifier
)
registerPsiQuickFixes(
KtFirDiagnostic.AbstractClassMemberNotImplemented::class,
AddModifierFix.addAbstractModifier
)
registerPsiQuickFixes(
KtFirDiagnostic.VirtualMemberHidden::class,
AddModifierFix.addOverrideModifier
)
registerPsiQuickFixes(
KtFirDiagnostic.AbstractPropertyInPrimaryConstructorParameters::class,
RemoveModifierFixBase.removeAbstractModifier
)
registerPsiQuickFixes(KtFirDiagnostic.ValOrVarOnLoopParameter::class, RemoveValVarFromParameterFix)
registerPsiQuickFixes(KtFirDiagnostic.ValOrVarOnFunParameter::class, RemoveValVarFromParameterFix)
registerPsiQuickFixes(KtFirDiagnostic.ValOrVarOnCatchParameter::class, RemoveValVarFromParameterFix)
registerPsiQuickFixes(KtFirDiagnostic.ValOrVarOnSecondaryConstructorParameter::class, RemoveValVarFromParameterFix)
}
private val propertyInitialization = KtQuickFixesListBuilder.registerPsiQuickFix {
registerPsiQuickFixes(
KtFirDiagnostic.MustBeInitializedOrBeAbstract::class,
AddModifierFix.addAbstractModifier,
)
registerApplicators(InitializePropertyQuickFixFactories.initializePropertyFactory)
registerApplicator(AddLateInitFactory.addLateInitFactory)
registerApplicators(AddAccessorsFactories.addAccessorsToUninitializedProperty)
registerPsiQuickFixes(KtFirDiagnostic.LocalVariableWithTypeParameters::class, RemovePsiElementSimpleFix.RemoveTypeParametersFactory)
registerPsiQuickFixes(
KtFirDiagnostic.LocalVariableWithTypeParametersWarning::class,
RemovePsiElementSimpleFix.RemoveTypeParametersFactory
)
}
private val overrides = KtQuickFixesListBuilder.registerPsiQuickFix {
registerApplicator(ChangeTypeQuickFixFactories.changeFunctionReturnTypeOnOverride)
registerApplicator(ChangeTypeQuickFixFactories.changePropertyReturnTypeOnOverride)
registerApplicator(ChangeTypeQuickFixFactories.changeVariableReturnTypeOnOverride)
registerApplicator(MemberNotImplementedQuickfixFactories.abstractMemberNotImplemented)
registerApplicator(MemberNotImplementedQuickfixFactories.abstractClassMemberNotImplemented)
registerApplicator(MemberNotImplementedQuickfixFactories.manyInterfacesMemberNotImplemented)
registerApplicator(MemberNotImplementedQuickfixFactories.manyImplMemberNotImplemented)
}
private val imports = KtQuickFixesListBuilder.registerPsiQuickFix {
registerApplicator(ImportQuickFix.FACTORY)
registerPsiQuickFixes(KtFirDiagnostic.ConflictingImport::class, RemovePsiElementSimpleFix.RemoveImportFactory)
}
private val mutability = KtQuickFixesListBuilder.registerPsiQuickFix {
registerPsiQuickFixes(KtFirDiagnostic.VarOverriddenByVal::class, ChangeVariableMutabilityFix.VAR_OVERRIDDEN_BY_VAL_FACTORY)
registerPsiQuickFixes(KtFirDiagnostic.VarAnnotationParameter::class, ChangeVariableMutabilityFix.VAR_ANNOTATION_PARAMETER_FACTORY)
registerPsiQuickFixes(KtFirDiagnostic.InapplicableLateinitModifier::class, ChangeVariableMutabilityFix.LATEINIT_VAL_FACTORY)
registerPsiQuickFixes(KtFirDiagnostic.ValWithSetter::class, ChangeVariableMutabilityFix.VAL_WITH_SETTER_FACTORY)
registerPsiQuickFixes(KtFirDiagnostic.MustBeInitialized::class, ChangeVariableMutabilityFix.MUST_BE_INITIALIZED_FACTORY)
}
private val expressions = KtQuickFixesListBuilder.registerPsiQuickFix {
registerApplicator(ReplaceWithDotCallFixFactory.replaceWithDotCallFactory)
registerPsiQuickFixes(KtFirDiagnostic.UnnecessaryNotNullAssertion::class, RemoveExclExclCallFix)
registerPsiQuickFixes(KtFirDiagnostic.UselessElvis::class, RemoveUselessElvisFix)
registerPsiQuickFixes(KtFirDiagnostic.UselessElvisRightIsNull::class, RemoveUselessElvisFix)
registerPsiQuickFixes(KtFirDiagnostic.UselessCast::class, RemoveUselessCastFix)
registerPsiQuickFixes(KtFirDiagnostic.UselessIsCheck::class, RemoveUselessIsCheckFix, RemoveUselessIsCheckFixForWhen)
registerApplicator(ReplaceCallFixFactories.unsafeCallFactory)
registerApplicator(ReplaceCallFixFactories.unsafeInfixCallFactory)
registerApplicator(ReplaceCallFixFactories.unsafeOperatorCallFactory)
registerApplicator(ReplaceCallFixFactories.unsafeImplicitInvokeCallFactory)
registerApplicator(AddExclExclCallFixFactories.unsafeCallFactory)
registerApplicator(AddExclExclCallFixFactories.unsafeInfixCallFactory)
registerApplicator(AddExclExclCallFixFactories.unsafeOperatorCallFactory)
registerApplicator(AddExclExclCallFixFactories.iteratorOnNullableFactory)
registerApplicator(TypeMismatchFactories.argumentTypeMismatchFactory)
registerApplicator(TypeMismatchFactories.returnTypeMismatchFactory)
registerApplicator(TypeMismatchFactories.assignmentTypeMismatch)
registerApplicator(TypeMismatchFactories.initializerTypeMismatch)
registerApplicator(TypeMismatchFactories.smartcastImpossibleFactory)
registerApplicator(WrapWithSafeLetCallFixFactories.forUnsafeCall)
registerApplicator(WrapWithSafeLetCallFixFactories.forUnsafeImplicitInvokeCall)
registerApplicator(WrapWithSafeLetCallFixFactories.forUnsafeInfixCall)
registerApplicator(WrapWithSafeLetCallFixFactories.forUnsafeOperatorCall)
registerApplicator(WrapWithSafeLetCallFixFactories.forArgumentTypeMismatch)
registerPsiQuickFixes(KtFirDiagnostic.NullableSupertype::class, RemoveNullableFix.removeForSuperType)
registerPsiQuickFixes(KtFirDiagnostic.InapplicableLateinitModifier::class, RemoveNullableFix.removeForLateInitProperty)
registerPsiQuickFixes(
KtFirDiagnostic.TypeArgumentsRedundantInSuperQualifier::class,
RemovePsiElementSimpleFix.RemoveTypeArgumentsFactory
)
}
private val whenStatements = KtQuickFixesListBuilder.registerPsiQuickFix {
// TODO: NON_EXHAUSTIVE_WHEN[_ON_SEALED_CLASS] will be replaced in future. We need to register the fix for those diagnostics as well
registerPsiQuickFixes(KtFirDiagnostic.NoElseInWhen::class, AddWhenElseBranchFix)
registerApplicator(AddWhenRemainingBranchFixFactories.noElseInWhen)
registerPsiQuickFixes(KtFirDiagnostic.CommaInWhenConditionWithoutArgument::class, CommaInWhenConditionWithoutArgumentFix)
registerPsiQuickFixes(KtFirDiagnostic.SenselessNullInWhen::class, RemoveWhenBranchFix)
}
private val typeMismatch = KtQuickFixesListBuilder.registerPsiQuickFix {
registerApplicator(ChangeTypeQuickFixFactories.componentFunctionReturnTypeMismatch)
registerApplicator(ChangeTypeQuickFixFactories.returnTypeMismatch)
registerApplicator(AddToStringFixFactories.typeMismatch)
registerApplicator(AddToStringFixFactories.argumentTypeMismatch)
registerApplicator(AddToStringFixFactories.assignmentTypeMismatch)
registerApplicator(AddToStringFixFactories.returnTypeMismatch)
registerApplicator(AddToStringFixFactories.initializerTypeMismatch)
registerApplicator(CastExpressionFixFactories.smartcastImpossible)
registerApplicator(CastExpressionFixFactories.typeMismatch)
registerApplicator(CastExpressionFixFactories.throwableTypeMismatch)
registerApplicator(CastExpressionFixFactories.argumentTypeMismatch)
registerApplicator(CastExpressionFixFactories.assignmentTypeMismatch)
registerApplicator(CastExpressionFixFactories.returnTypeMismatch)
registerApplicator(CastExpressionFixFactories.initializerTypeMismatch)
}
private val needExplicitType = KtQuickFixesListBuilder.registerPsiQuickFix {
registerApplicator(SpecifyExplicitTypeFixFactories.ambiguousAnonymousTypeInferred)
registerApplicator(SpecifyExplicitTypeFixFactories.noExplicitReturnTypeInApiMode)
registerApplicator(SpecifyExplicitTypeFixFactories.noExplicitReturnTypeInApiModeWarning)
}
private val superKeyword = KtQuickFixesListBuilder.registerPsiQuickFix {
registerApplicator(SpecifySuperTypeFixFactory.ambiguousSuper)
}
private val vararg = KtQuickFixesListBuilder.registerPsiQuickFix {
registerPsiQuickFixes(
KtFirDiagnostic.AssigningSingleElementToVarargInNamedFormAnnotationError::class,
ReplaceWithArrayCallInAnnotationFix
)
registerPsiQuickFixes(
KtFirDiagnostic.AssigningSingleElementToVarargInNamedFormAnnotationWarning::class,
ReplaceWithArrayCallInAnnotationFix
)
registerApplicator(SurroundWithArrayOfWithSpreadOperatorInFunctionFixFactory.assigningSingleElementToVarargInNamedFormFunction)
registerApplicator(SurroundWithArrayOfWithSpreadOperatorInFunctionFixFactory.assigningSingleElementToVarargInNamedFormFunctionWarning)
registerPsiQuickFixes(KtFirDiagnostic.RedundantSpreadOperatorInNamedFormInAnnotation::class, ReplaceWithArrayCallInAnnotationFix)
registerPsiQuickFixes(KtFirDiagnostic.RedundantSpreadOperatorInNamedFormInFunction::class, RemoveRedundantSpreadOperatorFix)
registerPsiQuickFixes(KtFirDiagnostic.NonVarargSpread::class, RemovePsiElementSimpleFix.RemoveSpreadFactory)
}
private val visibility = KtQuickFixesListBuilder.registerPsiQuickFix {
registerApplicator(ChangeVisibilityFixFactories.noExplicitVisibilityInApiMode)
registerApplicator(ChangeVisibilityFixFactories.noExplicitVisibilityInApiModeWarning)
}
override val list: KotlinQuickFixesList = KotlinQuickFixesList.createCombined(
keywords,
propertyInitialization,
overrides,
imports,
mutability,
expressions,
whenStatements,
typeMismatch,
needExplicitType,
superKeyword,
vararg,
visibility,
)
}
| apache-2.0 | 488dd40da71277fcaa5f9e79c12db2cd | 58.945701 | 158 | 0.804197 | 6.057613 | false | false | false | false |
kickstarter/android-oss | app/src/main/java/com/kickstarter/ui/activities/NotificationsActivity.kt | 1 | 15239 | package com.kickstarter.ui.activities
import android.content.Intent
import android.os.Bundle
import android.view.View
import android.widget.AdapterView
import android.widget.ArrayAdapter
import android.widget.ImageButton
import androidx.core.content.ContextCompat
import androidx.core.view.isGone
import com.kickstarter.R
import com.kickstarter.databinding.ActivityNotificationsBinding
import com.kickstarter.libs.BaseActivity
import com.kickstarter.libs.qualifiers.RequiresActivityViewModel
import com.kickstarter.libs.utils.AnimationUtils
import com.kickstarter.libs.utils.ViewUtils
import com.kickstarter.libs.utils.extensions.intValueOrZero
import com.kickstarter.libs.utils.extensions.isTrue
import com.kickstarter.models.User
import com.kickstarter.viewmodels.NotificationsViewModel
import rx.android.schedulers.AndroidSchedulers
@RequiresActivityViewModel(NotificationsViewModel.ViewModel::class)
class NotificationsActivity : BaseActivity<NotificationsViewModel.ViewModel>() {
private val green = R.color.kds_create_700
private val grey = R.color.kds_support_400
private val circleOutline = R.drawable.circle_gray_outline
private val circleFilled = R.drawable.circle_gray_filled
private val subscribeString = R.string.profile_settings_accessibility_subscribe_notifications
private val subscribeMobileString = R.string.profile_settings_accessibility_subscribe_mobile_notifications
private val unableToSaveString = R.string.profile_settings_error
private val unsubscribeMobileString = R.string.profile_settings_accessibility_unsubscribe_mobile_notifications
private val unsubscribeString = R.string.profile_settings_accessibility_unsubscribe_notifications
private var notifyMobileOfBackings: Boolean = false
private var notifyMobileOfComments: Boolean = false
private var notifyMobileOfCommentReplies: Boolean = false
private var notifyMobileOfCreatorEdu: Boolean = false
private var notifyMobileOfFollower: Boolean = false
private var notifyMobileOfFriendActivity: Boolean = false
private var notifyMobileOfMessages: Boolean = false
private var notifyMobileOfPostLikes: Boolean = false
private var notifyMobileOfUpdates: Boolean = false
private var notifyMobileOfMarketingUpdates: Boolean = false
private var notifyOfBackings: Boolean = false
private var notifyOfComments: Boolean = false
private var notifyOfCreatorDigest: Boolean = false
private var notifyOfCreatorEdu: Boolean = false
private var notifyOfFollower: Boolean = false
private var notifyOfFriendActivity: Boolean = false
private var notifyOfMessages: Boolean = false
private var notifyOfUpdates: Boolean = false
private lateinit var binding: ActivityNotificationsBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityNotificationsBinding.inflate(layoutInflater)
setContentView(binding.root)
this.viewModel.outputs.creatorDigestFrequencyIsGone()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
binding.emailFrequencyRow.isGone = it
}
this.viewModel.outputs.creatorNotificationsAreGone()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe {
binding.creatorNotificationsSection.isGone = it
}
this.viewModel.outputs.user()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { this.displayPreferences(it) }
this.viewModel.errors.unableToSavePreferenceError()
.compose(bindToLifecycle())
.observeOn(AndroidSchedulers.mainThread())
.subscribe { _ -> ViewUtils.showToast(this, getString(this.unableToSaveString)) }
val emailFrequencyStrings = User.EmailFrequency.getStrings(this.resources)
val arrayAdapter = ArrayAdapter<String>(this, R.layout.item_spinner, emailFrequencyStrings)
arrayAdapter.setDropDownViewResource(R.layout.item_spinner_dropdown)
binding.emailFrequencySpinner.adapter = arrayAdapter
setUpClickListeners()
}
private fun displayPreferences(user: User) {
binding.projectNotificationsCount.text = user.backedProjectsCount().intValueOrZero().toString()
displayMarketingUpdates(user)
displayBackingsNotificationSettings(user)
displayCommentsNotificationSettings(user)
displayCommentRepliesNotificationSettings(user)
displayCreatorTipsNotificationSettings(user)
displayFollowerNotificationSettings(user)
displayFriendActivityNotificationSettings(user)
displayMessagesNotificationSettings(user)
displayPostLikesNotificationSettings(user)
displayUpdatesNotificationSettings(user)
}
private fun displayMarketingUpdates(user: User) {
this.notifyMobileOfMarketingUpdates = user.notifyMobileOfMarketingUpdate().isTrue()
toggleImageButtonIconColor(binding.marketingUpdatesPhoneIcon, this.notifyMobileOfMarketingUpdates, true)
}
private fun displayBackingsNotificationSettings(user: User) {
this.notifyMobileOfBackings = user.notifyMobileOfBackings().isTrue()
this.notifyOfBackings = user.notifyOfBackings().isTrue()
this.notifyOfCreatorDigest = user.notifyOfCreatorDigest().isTrue()
val frequencyIndex = when {
notifyOfCreatorDigest -> User.EmailFrequency.DAILY_SUMMARY.ordinal
else -> User.EmailFrequency.TWICE_A_DAY_SUMMARY.ordinal
}
toggleImageButtonIconColor(binding.backingsPhoneIcon, this.notifyMobileOfBackings, true)
toggleImageButtonIconColor(binding.backingsMailIcon, this.notifyOfBackings)
if (frequencyIndex != binding.emailFrequencySpinner.selectedItemPosition) {
binding.emailFrequencySpinner.setSelection(frequencyIndex, false)
}
binding.emailFrequencySpinner.onItemSelectedListener = object : AdapterView.OnItemSelectedListener {
override fun onNothingSelected(parent: AdapterView<*>?) {
}
override fun onItemSelected(parent: AdapterView<*>?, view: View?, position: Int, id: Long) {
if (frequencyIndex != position) {
viewModel.inputs.notifyOfCreatorDigest(position == User.EmailFrequency.DAILY_SUMMARY.ordinal)
}
}
}
}
private fun displayCommentsNotificationSettings(user: User) {
this.notifyMobileOfComments = user.notifyMobileOfComments().isTrue()
this.notifyOfComments = user.notifyOfComments().isTrue()
toggleImageButtonIconColor(binding.commentsPhoneIcon, this.notifyMobileOfComments, true)
toggleImageButtonIconColor(binding.commentsMailIcon, this.notifyOfComments)
}
private fun displayCommentRepliesNotificationSettings(user: User) {
this.notifyMobileOfCommentReplies = user.notifyOfCommentReplies().isTrue()
toggleImageButtonIconColor(binding.commentRepliesMailIcon, this.notifyMobileOfCommentReplies)
}
private fun displayCreatorTipsNotificationSettings(user: User) {
this.notifyMobileOfCreatorEdu = user.notifyMobileOfCreatorEdu().isTrue()
this.notifyOfCreatorEdu = user.notifyOfCreatorEdu().isTrue()
toggleImageButtonIconColor(binding.creatorEduPhoneIcon, this.notifyMobileOfCreatorEdu, true)
toggleImageButtonIconColor(binding.creatorEduMailIcon, this.notifyOfCreatorEdu)
}
private fun displayFollowerNotificationSettings(user: User) {
this.notifyMobileOfFollower = user.notifyMobileOfFollower().isTrue()
this.notifyOfFollower = user.notifyOfFollower().isTrue()
toggleImageButtonIconColor(binding.newFollowersPhoneIcon, this.notifyMobileOfFollower, true)
toggleImageButtonIconColor(binding.newFollowersMailIcon, this.notifyOfFollower)
}
private fun displayFriendActivityNotificationSettings(user: User) {
this.notifyMobileOfFriendActivity = user.notifyMobileOfFriendActivity().isTrue()
this.notifyOfFriendActivity = user.notifyOfFriendActivity().isTrue()
toggleImageButtonIconColor(binding.friendActivityPhoneIcon, this.notifyMobileOfFriendActivity, true)
toggleImageButtonIconColor(binding.friendActivityMailIcon, this.notifyOfFriendActivity)
}
private fun displayMessagesNotificationSettings(user: User) {
this.notifyMobileOfMessages = user.notifyMobileOfMessages().isTrue()
this.notifyOfMessages = user.notifyOfMessages().isTrue()
toggleImageButtonIconColor(binding.messagesPhoneIcon, this.notifyMobileOfMessages, true)
toggleImageButtonIconColor(binding.messagesMailIcon, this.notifyOfMessages)
}
private fun displayPostLikesNotificationSettings(user: User) {
this.notifyMobileOfPostLikes = user.notifyMobileOfPostLikes().isTrue()
toggleImageButtonIconColor(binding.postLikesPhoneIcon, this.notifyMobileOfPostLikes, true)
}
private fun displayUpdatesNotificationSettings(user: User) {
this.notifyMobileOfUpdates = user.notifyMobileOfUpdates().isTrue()
this.notifyOfUpdates = user.notifyOfUpdates().isTrue()
toggleImageButtonIconColor(binding.projectUpdatesPhoneIcon, this.notifyMobileOfUpdates, true)
toggleImageButtonIconColor(binding.projectUpdatesMailIcon, this.notifyOfUpdates)
}
private fun getEnabledColorResId(enabled: Boolean): Int {
return if (enabled) this.green else this.grey
}
private fun getEnabledBackgroundResId(enabled: Boolean): Int {
return if (enabled) this.circleFilled else this.circleOutline
}
private fun setContentDescription(view: View, enabled: Boolean, typeMobile: Boolean) {
var contentDescription = ""
if (typeMobile && enabled) {
contentDescription = getString(this.unsubscribeMobileString)
}
if (typeMobile && !enabled) {
contentDescription = getString(this.subscribeMobileString)
}
if (!typeMobile && enabled) {
contentDescription = getString(this.unsubscribeString)
}
if (!typeMobile && !enabled) {
contentDescription = getString(this.subscribeString)
}
view.contentDescription = contentDescription
}
private fun setUpClickListeners() {
binding.manageProjectNotifications.setOnClickListener {
startProjectNotificationsSettingsActivity()
}
binding.backingsMailIcon.setOnClickListener {
this.viewModel.inputs.notifyOfBackings(!this.notifyOfBackings)
}
binding.backingsPhoneIcon.setOnClickListener {
this.viewModel.inputs.notifyMobileOfBackings(!this.notifyMobileOfBackings)
}
binding.backingsRow.setOnClickListener {
AnimationUtils.notificationBounceAnimation(binding.backingsPhoneIcon, binding.backingsMailIcon)
}
binding.commentsMailIcon.setOnClickListener {
this.viewModel.inputs.notifyOfComments(!this.notifyOfComments)
}
binding.commentsPhoneIcon.setOnClickListener {
this.viewModel.inputs.notifyMobileOfComments(!this.notifyMobileOfComments)
}
binding.commentRepliesMailIcon.setOnClickListener {
this.viewModel.inputs.notifyOfCommentReplies(!this.notifyMobileOfCommentReplies)
}
binding.commentRepliesRow.setOnClickListener {
AnimationUtils.notificationBounceAnimation(null, binding.commentRepliesMailIcon)
}
binding.commentsRow.setOnClickListener {
AnimationUtils.notificationBounceAnimation(binding.commentsPhoneIcon, binding.commentsMailIcon)
}
binding.creatorEduMailIcon.setOnClickListener {
this.viewModel.inputs.notifyOfCreatorEdu(!this.notifyOfCreatorEdu)
}
binding.creatorEduPhoneIcon.setOnClickListener {
this.viewModel.inputs.notifyMobileOfCreatorEdu(!this.notifyMobileOfCreatorEdu)
}
binding.creatorEduRow.setOnClickListener {
AnimationUtils.notificationBounceAnimation(binding.creatorEduPhoneIcon, binding.creatorEduMailIcon)
}
binding.friendActivityMailIcon.setOnClickListener {
this.viewModel.inputs.notifyOfFriendActivity(!this.notifyOfFriendActivity)
}
binding.friendActivityPhoneIcon.setOnClickListener {
this.viewModel.inputs.notifyMobileOfFriendActivity(!this.notifyMobileOfFriendActivity)
}
binding.friendsBackProjectRow.setOnClickListener {
AnimationUtils.notificationBounceAnimation(binding.friendActivityPhoneIcon, binding.friendActivityMailIcon)
}
binding.messagesMailIcon.setOnClickListener {
this.viewModel.inputs.notifyOfMessages(!this.notifyOfMessages)
}
binding.messagesPhoneIcon.setOnClickListener {
this.viewModel.inputs.notifyMobileOfMessages(!this.notifyMobileOfMessages)
}
binding.messagesNotificationRow.setOnClickListener {
AnimationUtils.notificationBounceAnimation(binding.messagesPhoneIcon, binding.messagesMailIcon)
}
binding.newFollowersMailIcon.setOnClickListener {
this.viewModel.inputs.notifyOfFollower(!this.notifyOfFollower)
}
binding.newFollowersPhoneIcon.setOnClickListener {
this.viewModel.inputs.notifyMobileOfFollower(!this.notifyMobileOfFollower)
}
binding.newFollowersRow.setOnClickListener {
AnimationUtils.notificationBounceAnimation(binding.newFollowersPhoneIcon, binding.newFollowersMailIcon)
}
binding.postLikesPhoneIcon.setOnClickListener {
this.viewModel.inputs.notifyMobileOfPostLikes(!this.notifyMobileOfPostLikes)
}
binding.projectUpdatesMailIcon.setOnClickListener {
this.viewModel.inputs.notifyOfUpdates(!this.notifyOfUpdates)
}
binding.projectUpdatesPhoneIcon.setOnClickListener {
this.viewModel.inputs.notifyMobileOfUpdates(!this.notifyMobileOfUpdates)
}
binding.marketingUpdatesPhoneIcon.setOnClickListener {
this.viewModel.inputs.notifyMobileOfMarketingUpdate(!this.notifyMobileOfMarketingUpdates)
}
binding.projectUpdatesRow.setOnClickListener {
AnimationUtils.notificationBounceAnimation(binding.projectUpdatesPhoneIcon, binding.projectUpdatesMailIcon)
}
}
private fun startProjectNotificationsSettingsActivity() {
startActivity(Intent(this, ProjectNotificationSettingsActivity::class.java))
}
private fun toggleImageButtonIconColor(imageButton: ImageButton, enabled: Boolean, typeMobile: Boolean = false) {
val color = getEnabledColorResId(enabled)
imageButton.setColorFilter(ContextCompat.getColor(this, color))
val background = getEnabledBackgroundResId(enabled)
imageButton.setBackgroundResource(background)
setContentDescription(imageButton, enabled, typeMobile)
}
}
| apache-2.0 | d8c595194ea1776c5745feafb1b817d9 | 42.664756 | 119 | 0.742437 | 5.269364 | false | false | false | false |
VREMSoftwareDevelopment/WiFiAnalyzer | app/src/main/kotlin/com/vrem/wifianalyzer/permission/SystemPermission.kt | 1 | 2578 | /*
* WiFiAnalyzer
* Copyright (C) 2015 - 2022 VREM Software Development <[email protected]>
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package com.vrem.wifianalyzer.permission
import android.annotation.TargetApi
import android.app.Activity
import android.content.Context
import android.location.LocationManager
import android.os.Build
import com.vrem.annotation.OpenClass
import com.vrem.util.buildMinVersionM
import com.vrem.util.buildMinVersionP
@OpenClass
class SystemPermission(private val activity: Activity) {
fun enabled(): Boolean = !buildMinVersionM() || providerEnabledAndroidM()
@TargetApi(Build.VERSION_CODES.M)
private fun providerEnabledAndroidM(): Boolean =
try {
val locationManager = activity.getSystemService(Context.LOCATION_SERVICE) as LocationManager
locationEnabled(locationManager) || networkProviderEnabled(locationManager) || gpsProviderEnabled(locationManager)
} catch (e: Exception) {
false
}
private fun gpsProviderEnabled(locationManager: LocationManager): Boolean =
try {
locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)
} catch (e: Exception) {
false
}
private fun networkProviderEnabled(locationManager: LocationManager): Boolean =
try {
locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)
} catch (e: Exception) {
false
}
private fun locationEnabled(locationManager: LocationManager): Boolean =
buildMinVersionP() && locationEnabledAndroidP(locationManager)
@TargetApi(Build.VERSION_CODES.P)
private fun locationEnabledAndroidP(locationManager: LocationManager): Boolean =
try {
locationManager.isLocationEnabled
} catch (e: Exception) {
false
}
} | gpl-3.0 | d26a5a83037790f5f622d50292dbc2d1 | 37.492537 | 130 | 0.695888 | 5.04501 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/formatter/Utils.kt | 2 | 1543 | // 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.formatter
import com.intellij.openapi.fileEditor.FileDocumentManager
import com.intellij.openapi.util.TextRange
import com.intellij.openapi.util.registry.Registry
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import com.intellij.psi.codeStyle.CodeStyleManager
import org.jetbrains.kotlin.config.LanguageFeature
import org.jetbrains.kotlin.idea.project.languageVersionSettings
import org.jetbrains.kotlin.idea.util.module
fun PsiFile.commitAndUnblockDocument(): Boolean {
val virtualFile = this.virtualFile ?: return false
val document = FileDocumentManager.getInstance().getDocument(virtualFile) ?: return false
val documentManager = PsiDocumentManager.getInstance(project)
documentManager.doPostponedOperationsAndUnblockDocument(document)
documentManager.commitDocument(document)
return true
}
fun PsiFile.adjustLineIndent(startOffset: Int, endOffset: Int) {
if (!commitAndUnblockDocument()) return
CodeStyleManager.getInstance(project).adjustLineIndent(this, TextRange(startOffset, endOffset))
}
fun trailingCommaAllowedInModule(source: PsiElement): Boolean =
Registry.`is`("kotlin.formatter.allowTrailingCommaInAnyProject", false) ||
source.module?.languageVersionSettings?.supportsFeature(LanguageFeature.TrailingCommas) == true
| apache-2.0 | 6268592df0aaaa12a428aeaadd4b89f8 | 47.21875 | 158 | 0.815295 | 4.977419 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/idea/tests/testData/structuralsearch/binaryExpression/binaryPlusAssign.kt | 8 | 287 | class Foo {
operator fun plusAssign(other: Foo) { print(other) }
}
fun foo() {
var z = 1
<warning descr="SSR">z += 2</warning>
<warning descr="SSR">z = z + 2</warning>
print(z)
var x = Foo()
val y = Foo()
<warning descr="SSR">x.plusAssign(y)</warning>
} | apache-2.0 | 148dddbfcb55fe9924dd39f85b8177a1 | 19.571429 | 56 | 0.560976 | 3.086022 | false | false | false | false |
siosio/intellij-community | java/java-impl/src/com/intellij/refactoring/extractMethod/newImpl/CallBuilder.kt | 1 | 5818 | // 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.refactoring.extractMethod.newImpl
import com.intellij.openapi.project.Project
import com.intellij.psi.*
import com.intellij.psi.impl.source.resolve.JavaResolveUtil
import com.intellij.psi.util.PsiUtil
import com.intellij.refactoring.extractMethod.newImpl.ExtractMethodHelper.createDeclaration
import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput
import com.intellij.refactoring.extractMethod.newImpl.structures.DataOutput.*
import com.intellij.refactoring.extractMethod.newImpl.structures.FlowOutput
import com.intellij.refactoring.extractMethod.newImpl.structures.FlowOutput.*
import com.intellij.refactoring.util.RefactoringChangeUtil
class CallBuilder(project: Project, private val context: PsiElement) {
private val factory: PsiElementFactory = PsiElementFactory.getInstance(project)
private fun expressionOf(expression: String) = factory.createExpressionFromText(expression, context)
private fun statementsOf(vararg statements: String) = statements.map { statement -> factory.createStatementFromText(statement, context) }
private fun createDeclaration(type: PsiType?, name: String, initializer: String): PsiStatement {
return if (type != null) {
factory.createVariableDeclarationStatement(name, type, expressionOf(initializer))
} else {
factory.createStatementFromText("$name = $initializer;", context)
}
}
private fun variableDeclaration(methodCall: String, dataOutput: DataOutput): List<PsiStatement> {
val declaration = when (dataOutput) {
is VariableOutput -> createDeclaration(dataOutput.type.takeIf { dataOutput.declareType }, dataOutput.name, methodCall)
is ExpressionOutput -> createDeclaration(dataOutput.type, dataOutput.name!!, methodCall)
ArtificialBooleanOutput, is EmptyOutput -> null
}
val declarationStatement = declaration as? PsiDeclarationStatement
val declaredVariable = declarationStatement?.declaredElements?.firstOrNull() as? PsiVariable
if (dataOutput is VariableOutput && declaredVariable != null) {
val needsFinal = dataOutput.variable.hasModifierProperty(PsiModifier.FINAL)
PsiUtil.setModifierProperty(declaredVariable, PsiModifier.FINAL, needsFinal)
}
return listOfNotNull(declaration)
}
private fun conditionalExit(methodCall: String, flow: ConditionalFlow, dataOutput: DataOutput): List<PsiStatement> {
val exit = when (dataOutput) {
is VariableOutput -> "if (${dataOutput.name} == null) ${flow.statements.first().text}"
is ExpressionOutput -> "if (${dataOutput.name} != null) return ${dataOutput.name};"
ArtificialBooleanOutput -> "if ($methodCall) ${flow.statements.first().text}"
is EmptyOutput -> throw IllegalArgumentException()
}
return statementsOf(exit)
}
private fun unconditionalExit(methodCall: String, flow: UnconditionalFlow, dataOutput: DataOutput): List<PsiStatement> {
return when (dataOutput) {
is VariableOutput -> statementsOf(
flow.statements.first().text
)
is ExpressionOutput -> statementsOf(
"return $methodCall;"
)
ArtificialBooleanOutput -> throw IllegalStateException()
is EmptyOutput -> when {
flow.isDefaultExit -> statementsOf("$methodCall;")
else -> statementsOf(
"$methodCall;",
flow.statements.first().text
)
}
}
}
private fun createFlowStatements(methodCall: String, flowOutput: FlowOutput, dataOutput: DataOutput): List<PsiStatement> {
return when (flowOutput) {
is ConditionalFlow -> conditionalExit(methodCall, flowOutput, dataOutput)
is UnconditionalFlow -> unconditionalExit(methodCall, flowOutput, dataOutput)
EmptyFlow -> if (dataOutput !is VariableOutput) statementsOf("$methodCall;") else emptyList()
}
}
fun buildCall(methodCall: String, flowOutput: FlowOutput, dataOutput: DataOutput, exposedDeclarations: List<PsiVariable>): List<PsiStatement> {
val variableDeclaration = if (flowOutput !is ConditionalFlow && dataOutput is ExpressionOutput) emptyList() else variableDeclaration(methodCall, dataOutput)
return variableDeclaration + createFlowStatements(methodCall, flowOutput, dataOutput) + exposedDeclarations.map { createDeclaration(it) }
}
fun buildExpressionCall(methodCall: String, dataOutput: DataOutput): List<PsiElement> {
require(dataOutput is ExpressionOutput)
val expression = if (dataOutput.name != null) "${dataOutput.name} = $methodCall" else methodCall
return listOf(factory.createExpressionFromText(expression, context))
}
fun createMethodCall(method: PsiMethod, parameters: List<PsiExpression>): PsiMethodCallExpression {
val name = if (method.isConstructor) "this" else method.name
val callText = name + "(" + parameters.joinToString { it.text } + ")"
val factory = PsiElementFactory.getInstance(method.project)
val callElement = factory.createExpressionFromText(callText, context) as PsiMethodCallExpression
val methodClass = findParentClass(method)!!
if (methodClass != findParentClass(context) && callElement.resolveMethod() != null && callElement.resolveMethod() != method && !method.isConstructor) {
val ref = if (method.hasModifierProperty(PsiModifier.STATIC)) factory.createReferenceExpression(methodClass) else RefactoringChangeUtil.createThisExpression(PsiManager.getInstance(method.project), methodClass)
callElement.methodExpression.qualifierExpression = ref
}
return callElement
}
private fun findParentClass(context: PsiElement): PsiClass? {
return JavaResolveUtil.findParentContextOfClass(context, PsiClass::class.java, false) as? PsiClass
}
} | apache-2.0 | b5d6a245c4b577785d20bab8c09ac2ce | 51.9 | 215 | 0.758508 | 4.80033 | false | false | false | false |
siosio/intellij-community | plugins/kotlin/gradle/gradle-tooling/src/KotlinNativeHomeEvaluator.kt | 1 | 1798 | // 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.gradle
import org.gradle.api.Project
// KT-29613, KT-29783
object KotlinNativeHomeEvaluator {
// this property is defined in org.jetbrains.kotlin.gradle.plugin.mpp.AbstractKotlinNativeTargetPreset
private const val KOTLIN_NATIVE_HOME_PRIVATE_PROPERTY = "konanHome"
private const val FALLBACK_ACCESSOR_CLASS = "org.jetbrains.kotlin.compilerRunner.KotlinNativeToolRunnerKt"
private const val FALLBACK_ACCESSOR_METHOD = "getKonanHome"
fun getKotlinNativeHome(project: Project): String? =
getKotlinNativeHomePrimary(project) ?: getKotlinNativeHomeFallback(project)
// Read Kotlin/Native home from the predefined property in Gradle plugin.
// Should work for Gradle plugin with version >= 1.3.20.
private fun getKotlinNativeHomePrimary(project: Project) = project.findProperty(KOTLIN_NATIVE_HOME_PRIVATE_PROPERTY) as String?
// Evaluate Kotlin/Native home using reflection by internal val declared in Gradle plugin.
// This should work for Gradle plugin with version < 1.3.20.
private fun getKotlinNativeHomeFallback(project: Project): String? {
val kotlinExtensionClassLoader = project.extensions.findByName("kotlin")?.javaClass?.classLoader ?: return null
val accessorClass = try {
Class.forName(FALLBACK_ACCESSOR_CLASS, true, kotlinExtensionClassLoader)
} catch (e: ClassNotFoundException) {
return null
}
val accessorMethod = accessorClass.getMethodOrNull(FALLBACK_ACCESSOR_METHOD, Project::class.java) ?: return null
return accessorMethod.invoke(null, project) as String
}
}
| apache-2.0 | 18c08e66374c471746478b199a43ad5f | 51.882353 | 158 | 0.750278 | 4.575064 | false | false | false | false |
jwren/intellij-community | plugins/settings-sync/tests/com/intellij/settingsSync/GitSettingsLogTest.kt | 1 | 6888 | package com.intellij.settingsSync
import com.intellij.testFramework.DisposableRule
import com.intellij.testFramework.TemporaryDirectory
import com.intellij.util.TimeoutUtil.sleep
import com.intellij.util.io.createDirectories
import com.intellij.util.io.createFile
import com.intellij.util.io.readText
import org.eclipse.jgit.revwalk.RevCommit
import org.eclipse.jgit.revwalk.RevWalk
import org.eclipse.jgit.storage.file.FileRepositoryBuilder
import org.junit.Assert.*
import org.junit.Before
import org.junit.Rule
import org.junit.Test
import org.junit.rules.RuleChain
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import java.nio.file.Path
import kotlin.io.path.div
import kotlin.io.path.writeText
@RunWith(JUnit4::class)
internal class GitSettingsLogTest {
private val tempDirManager = TemporaryDirectory()
private val disposableRule = DisposableRule()
@Rule
@JvmField
val ruleChain: RuleChain = RuleChain.outerRule(tempDirManager).around(disposableRule)
private lateinit var configDir: Path
private lateinit var settingsSyncStorage: Path
@Before
fun setUp() {
val mainDir = tempDirManager.createDir()
configDir = mainDir.resolve("rootconfig").createDirectories()
settingsSyncStorage = configDir.resolve("settingsSync")
}
@Test
fun `copy files initially`() {
val keymapContent = "keymapContent"
val keymapsFolder = configDir / "keymaps"
(keymapsFolder / "mykeymap.xml").createFile().writeText(keymapContent)
val editorContent = "editorContent"
val editorXml = (configDir / "options" / "editor.xml").createFile()
editorXml.writeText(editorContent)
val settingsLog = GitSettingsLog(settingsSyncStorage, configDir, disposableRule.disposable) {
listOf(keymapsFolder, editorXml)
}
settingsLog.initialize()
settingsLog.logExistingSettings()
settingsLog.collectCurrentSnapshot().assertSettingsSnapshot {
fileState("keymaps/mykeymap.xml", keymapContent)
fileState("options/editor.xml", editorContent)
}
}
@Test
fun `merge conflict should be resolved as last modified`() {
val editorXml = (configDir / "options" / "editor.xml").createFile()
editorXml.writeText("editorContent")
val settingsLog = GitSettingsLog(settingsSyncStorage, configDir, disposableRule.disposable) {
listOf(editorXml)
}
settingsLog.initialize()
settingsLog.applyIdeState(settingsSnapshot {
fileState("options/editor.xml", "ideEditorContent")
})
sleep(1000) // to make sure commits have different timestamps (they are of 1-second granularity)
settingsLog.applyCloudState(settingsSnapshot {
fileState("options/editor.xml", "cloudEditorContent")
})
settingsLog.advanceMaster()
assertEquals("Incorrect content", "cloudEditorContent", (settingsSyncStorage / "options" / "editor.xml").readText())
assertMasterIsMergeOfIdeAndCloud()
}
@Test
fun `delete-modify merge conflict should be resolved as last modified`() {
val editorXml = (configDir / "options" / "editor.xml").createFile()
editorXml.writeText("editorContent")
val settingsLog = GitSettingsLog(settingsSyncStorage, configDir, disposableRule.disposable) {
listOf(editorXml)
}
settingsLog.initialize()
settingsLog.applyIdeState(settingsSnapshot {
fileState(FileState.Deleted("options/editor.xml"))
})
sleep(1000) // to make sure commits have different timestamps (they are of 1-second granularity)
settingsLog.applyCloudState(settingsSnapshot {
fileState("options/editor.xml", "cloudEditorContent")
})
settingsLog.advanceMaster()
assertEquals("Incorrect content", "cloudEditorContent", (settingsSyncStorage / "options" / "editor.xml").readText())
assertMasterIsMergeOfIdeAndCloud()
}
@Test
fun `modify-delete merge conflict should be resolved as last modified`() {
val editorXml = (configDir / "options" / "editor.xml").createFile()
editorXml.writeText("editorContent")
val settingsLog = GitSettingsLog(settingsSyncStorage, configDir, disposableRule.disposable) {
listOf(editorXml)
}
settingsLog.initialize()
settingsLog.applyCloudState(settingsSnapshot {
fileState("options/editor.xml", "moreCloudEditorContent")
})
sleep(1000) // to make sure commits have different timestamps (they are of 1-second granularity)
settingsLog.applyIdeState(settingsSnapshot {
fileState(FileState.Deleted("options/editor.xml"))
})
settingsLog.advanceMaster()
assertEquals("Incorrect deleted file content", DELETED_FILE_MARKER, (settingsSyncStorage / "options" / "editor.xml").readText())
assertMasterIsMergeOfIdeAndCloud()
}
//@Test
// todo requires a more previse merge conflict strategy implementation
@Suppress("unused")
fun `merge conflict should be resolved as last modified for the particular file`() {
val editorXml = (configDir / "options" / "editor.xml").createFile()
editorXml.writeText("editorContent")
val lafXml = (configDir / "options" / "laf.xml").createFile()
editorXml.writeText("lafContent")
val settingsLog = GitSettingsLog(settingsSyncStorage, configDir, disposableRule.disposable) {
listOf(lafXml, editorXml)
}
settingsLog.initialize()
settingsLog.applyIdeState(settingsSnapshot {
fileState("editor.xml", "ideEditorContent")
})
settingsLog.applyCloudState(settingsSnapshot {
fileState("laf.xml", "cloudLafContent")
})
settingsLog.applyCloudState(settingsSnapshot {
fileState("editor.xml", "cloudEditorContent")
})
settingsLog.applyIdeState(settingsSnapshot {
fileState("laf.xml", "ideEditorContent")
})
settingsLog.advanceMaster()
assertEquals("Incorrect content", "cloudEditorContent", editorXml.readText())
assertEquals("Incorrect content", "ideLafContent", lafXml.readText())
assertMasterIsMergeOfIdeAndCloud()
}
private fun assertMasterIsMergeOfIdeAndCloud() {
val dotGit = settingsSyncStorage.resolve(".git")
FileRepositoryBuilder.create(dotGit.toFile()).use { repository ->
val walk = RevWalk(repository)
try {
val commit: RevCommit = walk.parseCommit(repository.findRef("master").objectId)
walk.markStart(commit)
val parents = commit.parents
assertEquals(2, parents.size)
val ide = repository.findRef("ide")!!
val cloud = repository.findRef("cloud")!!
val (parent1, parent2) = parents
if (parent1.id == ide.objectId) {
assertTrue(parent2.id == cloud.objectId)
}
else if (parent1.id == cloud.objectId) {
assertTrue(parent2.id == ide.objectId)
}
else {
fail("Neither ide nor cloud are parents of master")
}
walk.dispose()
}
finally {
walk.dispose()
walk.close()
}
}
}
} | apache-2.0 | 7092c40bf90b83a9902af020f2da37e5 | 34.510309 | 132 | 0.719803 | 4.39566 | false | true | false | false |
google/playhvz | Android/ghvzApp/app/src/main/java/com/app/playhvz/screens/missions/MissionDashboardFragment.kt | 1 | 5735 | /*
* Copyright 2020 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.app.playhvz.screens.missions
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.navigation.fragment.findNavController
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.app.playhvz.R
import com.app.playhvz.common.globals.SharedPreferencesConstants
import com.app.playhvz.firebase.classmodels.Game
import com.app.playhvz.firebase.classmodels.Mission
import com.app.playhvz.firebase.classmodels.Player
import com.app.playhvz.firebase.viewmodels.GameViewModel
import com.app.playhvz.firebase.viewmodels.MissionListViewModel
import com.app.playhvz.navigation.NavigationUtil
import com.app.playhvz.utils.PlayerUtils
import com.google.android.material.floatingactionbutton.FloatingActionButton
/** Fragment for showing a list of missions.*/
class MissionDashboardFragment : Fragment() {
companion object {
private val TAG = MissionDashboardFragment::class.qualifiedName
}
lateinit var gameViewModel: GameViewModel
lateinit var missionViewModel: MissionListViewModel
lateinit var fab: FloatingActionButton
lateinit var recyclerView: RecyclerView
lateinit var adapter: MissionDashboardAdapter
var gameId: String? = null
var playerId: String? = null
var game: Game? = null
var player: Player? = null
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
val sharedPrefs = activity?.getSharedPreferences(
SharedPreferencesConstants.PREFS_FILENAME,
0
)!!
gameViewModel = GameViewModel()
missionViewModel = MissionListViewModel()
gameId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_GAME_ID, null)
playerId = sharedPrefs.getString(SharedPreferencesConstants.CURRENT_PLAYER_ID, null)
}
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
val view = inflater.inflate(R.layout.fragment_mission_dashboard, container, false)
fab = activity?.findViewById(R.id.floating_action_button)!!
recyclerView = view.findViewById(R.id.mission_list)
adapter = MissionDashboardAdapter(listOf(), requireContext(), findNavController())
recyclerView.layoutManager = LinearLayoutManager(context)
recyclerView.adapter = adapter
setupObservers()
setupToolbar()
return view
}
fun setupToolbar() {
val toolbar = (activity as AppCompatActivity).supportActionBar
if (toolbar != null) {
toolbar.title = requireContext().getString(R.string.mission_title)
}
}
private fun setupFab(isAdmin: Boolean) {
if (!isAdmin) {
fab.visibility = View.GONE
return
}
fab.visibility = View.VISIBLE
fab.setOnClickListener {
createMission()
}
fab.visibility = View.VISIBLE
}
private fun setupObservers() {
if (gameId == null || playerId == null) {
return
}
gameViewModel.getGameAndAdminObserver(this, gameId!!, playerId!!)
.observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverGameAndAdminStatus ->
updateGame(serverGameAndAdminStatus)
})
PlayerUtils.getPlayer(gameId!!, playerId!!)
.observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverPlayer ->
updatePlayer(serverPlayer)
})
}
private fun updateGame(serverUpdate: GameViewModel.GameWithAdminStatus?) {
if (serverUpdate == null) {
NavigationUtil.navigateToGameList(findNavController(), requireActivity())
}
game = serverUpdate!!.game
setupFab(serverUpdate.isAdmin)
adapter.setIsAdmin(serverUpdate.isAdmin)
adapter.notifyDataSetChanged()
if (serverUpdate.isAdmin) {
missionViewModel.getAllMissionsInGame(this, gameId!!)
.observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverMissionList ->
updateMissionList(serverMissionList)
})
} else {
missionViewModel.getMissionListOfMissionsPlayerIsIn(this, gameId!!, playerId!!)
.observe(viewLifecycleOwner, androidx.lifecycle.Observer { serverMissionList ->
updateMissionList(serverMissionList)
})
}
}
private fun updatePlayer(serverPlayer: Player?) {
if (serverPlayer == null) {
NavigationUtil.navigateToGameList(findNavController(), requireActivity())
}
}
private fun updateMissionList(updatedMissionList: Map<String, Mission?>) {
adapter.setData(updatedMissionList)
adapter.notifyDataSetChanged()
}
private fun createMission() {
NavigationUtil.navigateToMissionSettings(findNavController(), null)
}
} | apache-2.0 | b207b7793cd6fbf5e118f45734855cdd | 36.490196 | 98 | 0.696251 | 5.052863 | false | false | false | false |
androidx/androidx | compose/foundation/foundation/src/commonMain/kotlin/androidx/compose/foundation/text/selection/Selection.kt | 3 | 2720 | /*
* Copyright 2021 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.foundation.text.selection
import androidx.compose.runtime.Immutable
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.style.ResolvedTextDirection
/**
* Information about the current Selection.
*/
@Immutable
internal data class Selection(
/**
* Information about the start of the selection.
*/
val start: AnchorInfo,
/**
* Information about the end of the selection.
*/
val end: AnchorInfo,
/**
* The flag to show that the selection handles are dragged across each other. After selection
* is initialized, if user drags one handle to cross the other handle, this is true, otherwise
* it's false.
*/
// If selection happens in single widget, checking [TextRange.start] > [TextRange.end] is
// enough.
// But when selection happens across multiple widgets, this value needs more complicated
// calculation. To avoid repeated calculation, making it as a flag is cheaper.
val handlesCrossed: Boolean = false
) {
/**
* Contains information about an anchor (start/end) of selection.
*/
@Immutable
internal data class AnchorInfo(
/**
* Text direction of the character in selection edge.
*/
val direction: ResolvedTextDirection,
/**
* Character offset for the selection edge. This offset is within individual child text
* composable.
*/
val offset: Int,
/**
* The id of the [Selectable] which contains this [Selection] Anchor.
*/
val selectableId: Long
)
fun merge(other: Selection?): Selection {
if (other == null) return this
var selection = this
selection = if (handlesCrossed) {
selection.copy(start = other.start)
} else {
selection.copy(end = other.end)
}
return selection
}
/**
* Returns the selection offset information as a [TextRange]
*/
fun toTextRange(): TextRange {
return TextRange(start.offset, end.offset)
}
} | apache-2.0 | 4be06c270122c5a691379ca94a54bd42 | 29.573034 | 98 | 0.659559 | 4.617997 | false | false | false | false |
GunoH/intellij-community | plugins/markdown/test/src/org/intellij/plugins/markdown/model/SingleFileHeaderFindUsagesTest.kt | 7 | 1251 | package org.intellij.plugins.markdown.model
import com.intellij.testFramework.fixtures.BasePlatformTestCase
import com.intellij.util.io.readText
import junit.framework.TestCase
import org.intellij.plugins.markdown.MarkdownTestingUtil
import org.junit.Test
import org.junit.runner.RunWith
import org.junit.runners.JUnit4
import kotlin.io.path.Path
@RunWith(JUnit4::class)
class SingleFileHeaderFindUsagesTest: BasePlatformTestCase() {
@Test
fun `find usages`() = doTest()
private fun doTest() {
val testName = getTestName(true)
val contentFile = "$testName.md"
val expectedFile = "${testName}_expected.txt"
val usages = myFixture.testFindUsagesUsingAction(contentFile).map { it.toString() }.sorted()
val text = usages.joinToString(separator = "\n", postfix = "\n")
val expectedFilePath = "$testDataPath/$expectedFile"
val expected = Path(expectedFilePath).readText()
TestCase.assertEquals(expected, text)
}
override fun getTestName(lowercaseFirstLetter: Boolean): String {
val name = super.getTestName(lowercaseFirstLetter)
return name.trimStart().replace(' ', '_')
}
override fun getTestDataPath(): String {
return "${MarkdownTestingUtil.TEST_DATA_PATH}/model/headers/usages/file"
}
}
| apache-2.0 | 370afa2a184145ea3abc74aa83804dd4 | 32.810811 | 96 | 0.752198 | 4.358885 | false | true | false | false |
GunoH/intellij-community | plugins/kotlin/idea/src/org/jetbrains/kotlin/idea/inspections/coroutines/SuspendFunctionOnCoroutineScopeInspection.kt | 1 | 11845 | // 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.inspections.coroutines
import com.intellij.codeInsight.FileModificationService
import com.intellij.codeInspection.IntentionWrapper
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType.GENERIC_ERROR_OR_WARNING
import com.intellij.codeInspection.ProblemsHolder
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElementVisitor
import org.jetbrains.kotlin.descriptors.DeclarationDescriptor
import org.jetbrains.kotlin.descriptors.ReceiverParameterDescriptor
import org.jetbrains.kotlin.idea.base.resources.KotlinBundle
import org.jetbrains.kotlin.idea.caches.resolve.analyzeWithContent
import org.jetbrains.kotlin.idea.caches.resolve.resolveToDescriptorIfAny
import org.jetbrains.kotlin.idea.core.ShortenReferences
import org.jetbrains.kotlin.idea.base.psi.replaced
import org.jetbrains.kotlin.idea.base.util.reformatted
import org.jetbrains.kotlin.idea.codeinsight.api.classic.inspections.AbstractKotlinInspection
import org.jetbrains.kotlin.idea.inspections.UnusedReceiverParameterInspection
import org.jetbrains.kotlin.idea.intentions.ConvertReceiverToParameterIntention
import org.jetbrains.kotlin.idea.intentions.MoveMemberToCompanionObjectIntention
import org.jetbrains.kotlin.idea.util.application.executeWriteCommand
import com.intellij.openapi.application.runWriteAction
import org.jetbrains.kotlin.lexer.KtTokens
import org.jetbrains.kotlin.psi.*
import org.jetbrains.kotlin.psi.psiUtil.containingClassOrObject
import org.jetbrains.kotlin.psi.psiUtil.forEachDescendantOfType
import org.jetbrains.kotlin.psi.psiUtil.getNonStrictParentOfType
import org.jetbrains.kotlin.resolve.BindingContext
import org.jetbrains.kotlin.resolve.calls.util.getResolvedCall
import org.jetbrains.kotlin.resolve.descriptorUtil.fqNameSafe
import org.jetbrains.kotlin.resolve.scopes.receivers.ExpressionReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ImplicitReceiver
import org.jetbrains.kotlin.resolve.scopes.receivers.ReceiverValue
import org.jetbrains.kotlin.types.KotlinType
class SuspendFunctionOnCoroutineScopeInspection : AbstractKotlinInspection() {
override fun buildVisitor(holder: ProblemsHolder, isOnTheFly: Boolean): PsiElementVisitor {
return namedFunctionVisitor(fun(function: KtNamedFunction) {
if (!function.hasModifier(KtTokens.SUSPEND_KEYWORD)) return
if (!function.hasBody()) return
val context = function.analyzeWithContent()
val descriptor = context[BindingContext.FUNCTION, function] ?: return
val (extensionOfCoroutineScope, memberOfCoroutineScope) = with(descriptor) {
extensionReceiverParameter.ofCoroutineScopeType() to dispatchReceiverParameter.ofCoroutineScopeType()
}
if (!extensionOfCoroutineScope && !memberOfCoroutineScope) return
fun DeclarationDescriptor.isReceiverOfAnalyzedFunction(): Boolean {
if (extensionOfCoroutineScope && this == descriptor) return true
if (memberOfCoroutineScope && this == descriptor.containingDeclaration) return true
return false
}
fun checkSuspiciousReceiver(receiver: ReceiverValue, problemExpression: KtExpression) {
when (receiver) {
is ImplicitReceiver -> if (!receiver.declarationDescriptor.isReceiverOfAnalyzedFunction()) return
is ExpressionReceiver -> {
val receiverThisExpression = receiver.expression as? KtThisExpression ?: return
if (receiverThisExpression.getTargetLabel() != null) {
val instanceReference = receiverThisExpression.instanceReference
if (context[BindingContext.REFERENCE_TARGET, instanceReference]?.isReceiverOfAnalyzedFunction() != true) return
}
}
}
val fixes = mutableListOf<LocalQuickFix>()
val reportElement = (problemExpression as? KtCallExpression)?.calleeExpression ?: problemExpression
holder.registerProblem(
reportElement,
MESSAGE,
GENERIC_ERROR_OR_WARNING,
WrapWithCoroutineScopeFix(removeReceiver = false, wrapCallOnly = true)
)
fixes += WrapWithCoroutineScopeFix(removeReceiver = extensionOfCoroutineScope, wrapCallOnly = false)
if (extensionOfCoroutineScope) {
fixes += IntentionWrapper(ConvertReceiverToParameterIntention())
}
if (memberOfCoroutineScope) {
val containingDeclaration = function.containingClassOrObject
if (containingDeclaration is KtClass && !containingDeclaration.isInterface() && function.hasBody()) {
fixes += IntentionWrapper(MoveMemberToCompanionObjectIntention())
}
}
holder.registerProblem(
with(function) { receiverTypeReference ?: nameIdentifier ?: funKeyword ?: this },
MESSAGE,
GENERIC_ERROR_OR_WARNING,
*fixes.toTypedArray()
)
}
function.forEachDescendantOfType(fun(callExpression: KtCallExpression) {
val resolvedCall = callExpression.getResolvedCall(context) ?: return
val extensionReceiverParameter = resolvedCall.resultingDescriptor.extensionReceiverParameter ?: return
if (!extensionReceiverParameter.type.isCoroutineScope()) return
val extensionReceiver = resolvedCall.extensionReceiver ?: return
checkSuspiciousReceiver(extensionReceiver, callExpression)
})
function.forEachDescendantOfType(fun(nameReferenceExpression: KtNameReferenceExpression) {
if (nameReferenceExpression.getReferencedName() != COROUTINE_CONTEXT) return
val resolvedCall = nameReferenceExpression.getResolvedCall(context) ?: return
if (resolvedCall.resultingDescriptor.fqNameSafe.asString() == "$COROUTINE_SCOPE.$COROUTINE_CONTEXT") {
val dispatchReceiver = resolvedCall.dispatchReceiver ?: return
checkSuspiciousReceiver(dispatchReceiver, nameReferenceExpression)
}
})
})
}
private class WrapWithCoroutineScopeFix(
private val removeReceiver: Boolean,
private val wrapCallOnly: Boolean
) : LocalQuickFix {
override fun getFamilyName(): String = KotlinBundle.message("wrap.with.coroutine.scope.fix.family.name")
override fun getName(): String =
when {
removeReceiver && !wrapCallOnly -> KotlinBundle.message("wrap.with.coroutine.scope.fix.text3")
wrapCallOnly -> KotlinBundle.message("wrap.with.coroutine.scope.fix.text2")
else -> KotlinBundle.message("wrap.with.coroutine.scope.fix.text")
}
override fun startInWriteAction() = false
override fun applyFix(project: Project, descriptor: ProblemDescriptor) {
val problemElement = descriptor.psiElement ?: return
val function = problemElement.getNonStrictParentOfType<KtNamedFunction>() ?: return
val functionDescriptor = function.resolveToDescriptorIfAny()
if (!FileModificationService.getInstance().preparePsiElementForWrite(function)) return
val bodyExpression = function.bodyExpression
fun getExpressionToWrapCall(): KtExpression? {
var result = problemElement as? KtExpression ?: return null
while (result.parent is KtQualifiedExpression || result.parent is KtCallExpression) {
result = result.parent as KtExpression
}
return result
}
var expressionToWrap = when {
wrapCallOnly -> getExpressionToWrapCall()
else -> bodyExpression
} ?: return
if (functionDescriptor?.extensionReceiverParameter.ofCoroutineScopeType()) {
val context = function.analyzeWithContent()
expressionToWrap.forEachDescendantOfType<KtDotQualifiedExpression> {
val receiverExpression = it.receiverExpression as? KtThisExpression
val selectorExpression = it.selectorExpression
if (receiverExpression?.getTargetLabel() != null && selectorExpression != null) {
if (context[BindingContext.REFERENCE_TARGET, receiverExpression.instanceReference] == functionDescriptor) {
runWriteAction {
if (it === expressionToWrap) {
expressionToWrap = it.replaced(selectorExpression)
} else {
it.replace(selectorExpression)
}
}
}
}
}
}
val factory = KtPsiFactory(function)
val blockExpression = function.bodyBlockExpression
project.executeWriteCommand(name, this) {
val result = when {
expressionToWrap != bodyExpression -> expressionToWrap.replaced(
factory.createExpressionByPattern("$COROUTINE_SCOPE_WRAPPER { $0 }", expressionToWrap)
)
blockExpression == null -> bodyExpression.replaced(
factory.createExpressionByPattern("$COROUTINE_SCOPE_WRAPPER { $0 }", bodyExpression)
)
else -> {
val bodyText = buildString {
for (statement in blockExpression.statements) {
append(statement.text)
append("\n")
}
}
blockExpression.replaced(
factory.createBlock("$COROUTINE_SCOPE_WRAPPER { $bodyText }")
)
}
}
ShortenReferences.DEFAULT.process(result.reformatted() as KtElement)
}
val receiverTypeReference = function.receiverTypeReference
if (removeReceiver && !wrapCallOnly && receiverTypeReference != null) {
UnusedReceiverParameterInspection.RemoveReceiverFix.apply(receiverTypeReference, project)
}
}
}
companion object {
private const val COROUTINE_SCOPE = "kotlinx.coroutines.CoroutineScope"
private const val COROUTINE_SCOPE_WRAPPER = "kotlinx.coroutines.coroutineScope"
private const val COROUTINE_CONTEXT = "coroutineContext"
private val MESSAGE get() = KotlinBundle.message("ambiguous.coroutinecontext.due.to.coroutinescope.receiver.of.suspend.function")
private fun KotlinType.isCoroutineScope(): Boolean =
constructor.declarationDescriptor?.fqNameSafe?.asString() == COROUTINE_SCOPE
private fun ReceiverParameterDescriptor?.ofCoroutineScopeType(): Boolean {
if (this == null) return false
if (type.isCoroutineScope()) return true
return type.constructor.supertypes.reversed().any { it.isCoroutineScope() }
}
}
} | apache-2.0 | 8c8ded3d5b38347f8cceae524c24729a | 53.091324 | 158 | 0.650485 | 6.230931 | false | false | false | false |
smmribeiro/intellij-community | plugins/gradle/tooling-proxy/src/org/jetbrains/plugins/gradle/tooling/proxy/OutputWrapper.kt | 12 | 898 | // Copyright 2000-2021 JetBrains s.r.o. Use of this source code is governed by the Apache 2.0 license that can be found in the LICENSE file.
package org.jetbrains.plugins.gradle.tooling.proxy
import java.io.OutputStream
import java.nio.charset.StandardCharsets
class OutputWrapper(private val listener: (String) -> Unit) : OutputStream() {
private var myBuffer: StringBuilder? = null
override fun write(b: Int) {
if (myBuffer == null) {
myBuffer = StringBuilder()
}
myBuffer!!.append(b.toChar())
}
override fun write(b: ByteArray, off: Int, len: Int) {
if (myBuffer == null) {
myBuffer = StringBuilder()
}
myBuffer!!.append(String(b, off, len, StandardCharsets.UTF_8))
}
override fun flush() {
doFlush()
}
private fun doFlush() {
if (myBuffer == null) return
listener.invoke(myBuffer.toString())
myBuffer!!.setLength(0)
}
} | apache-2.0 | 55db18039f27ce2c3f46139df8702608 | 27.09375 | 140 | 0.678174 | 3.726141 | false | false | false | false |
BenWoodworth/FastCraft | fastcraft-core/src/main/kotlin/net/benwoodworth/fastcraft/crafting/model/FastCraftRecipe.kt | 1 | 1608 | package net.benwoodworth.fastcraft.crafting.model
import net.benwoodworth.fastcraft.platform.recipe.FcCraftingRecipePrepared
import net.benwoodworth.fastcraft.platform.world.FcItemStack
import kotlin.math.ceil
class FastCraftRecipe(
private val fastCraftGuiModel: FastCraftGuiModel,
val preparedRecipe: FcCraftingRecipePrepared,
fcItemStackOperations: FcItemStack.Operations,
) : FcItemStack.Operations by fcItemStackOperations {
var multiplier: Int = 1
private set
init {
setCraftAmount(fastCraftGuiModel.craftAmount)
}
fun setCraftAmount(amount: Int?) {
if (amount == null) {
multiplier = 1
return
}
val baseAmount = preparedRecipe.resultsPreview.first().amount
var newMultiplier = ceil(amount.toDouble() / baseAmount).toInt()
if (baseAmount * newMultiplier > 64) {
newMultiplier = amount / baseAmount
}
if (newMultiplier < 1) {
newMultiplier = 1
}
multiplier = newMultiplier
}
fun canCraft(): Boolean {
fastCraftGuiModel.updateInventoryItemAmounts()
val remainingItems = fastCraftGuiModel.inventoryItemAmounts.copy()
preparedRecipe.ingredients.values.forEach { itemStack ->
val amountLeft = remainingItems[itemStack]
val removeAmount = itemStack.amount * multiplier
when {
amountLeft < removeAmount -> return false
else -> remainingItems[itemStack] = amountLeft - removeAmount
}
}
return true
}
}
| gpl-3.0 | e2c06d66a5a39834c7c9065139bd1260 | 28.236364 | 77 | 0.654851 | 4.962963 | false | false | false | false |
Phakx/AdventOfCode | 2017/src/main/kotlin/dayfive/DayFive.kt | 1 | 1604 | package main.kotlin.dayfive
import java.io.File
import java.net.URLDecoder
class DayFive {
fun solvePart1() {
val input = File(load_file()).readLines().map({ item -> item.toInt() }).toMutableList()
var index = 0
var current_index: Int
var counter = 0
while (true) {
try {
current_index = index
index += input[index]
input[current_index]++
counter += 1
} catch (e: Exception) {
println("Part 1: $counter")
return
}
}
}
fun solvePart2() {
val input = File(load_file()).readLines().map({ item -> item.toInt() }).toMutableList()
var index = 0
var current_index: Int
var counter = 0
while (true) {
try {
current_index = index
index += input[index]
if (input[current_index] >= 3) {
input[current_index]--
} else {
input[current_index]++
}
counter += 1
} catch (e: Exception) {
println("Part 2: $counter")
return
}
}
}
private fun load_file(): String? {
val resource = this::class.java.classLoader.getResource("dayfive" + File.separator + "input")
val file = URLDecoder.decode(resource.file, "UTF-8")
return file
}
}
fun main(args: Array<String>) {
val solver = DayFive()
solver.solvePart1()
solver.solvePart2()
} | mit | a67155806d9eb1e7544bfb92fc98f287 | 26.20339 | 101 | 0.477556 | 4.492997 | false | false | false | false |
nicolas-raoul/apps-android-commons | app/src/main/java/fr/free/nrw/commons/upload/worker/UploadWorker.kt | 1 | 18642 | package fr.free.nrw.commons.upload.worker
import android.annotation.SuppressLint
import android.content.Context
import android.graphics.BitmapFactory
import androidx.core.app.NotificationCompat
import androidx.core.app.NotificationManagerCompat
import androidx.work.CoroutineWorker
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.di.ApplicationlessInjection
import fr.free.nrw.commons.media.MediaClient
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.flow.asFlow
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.flow.map
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 uploadClient: UploadClient
@Inject
lateinit var mediaClient: MediaClient
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?.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 {
notificationManager = NotificationManagerCompat.from(appContext)
val processingUploads = getNotificationBuilder(
CommonsApplication.NOTIFICATION_CHANNEL_ID_ALL
)!!
withContext(Dispatchers.IO) {
//Doing this so that retry requests do not create new work requests and while a work is
// already running, all the requests should go through this, so kind of a queue
while (contributionDao.getContribution(statesToProcess)
.blockingGet().isNotEmpty()
) {
val queuedContributions = contributionDao.getContribution(statesToProcess)
.blockingGet()
//Showing initial notification for the number of uploads being processed
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()
)
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.save(contribution)
}
} else {
contribution.transferred = 0
contribution.state = Contribution.STATE_IN_PROGRESS
contributionDao.save(contribution)
uploadContribution(contribution = contribution)
}
}.collect()
//Dismiss the global notification
notificationManager?.cancel(
PROCESSING_UPLOADS_NOTIFICATION_TAG,
PROCESSING_UPLOADS_NOTIFICATION_ID
)
//No need to keep looking if the limited connection mode is on,
//If the user toggles it, the work manager will be started again
if(isLimitedConnectionModeEnabled()){
break;
}
}
}
//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
).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
).blockingSingle()
if (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)
showSuccessNotification(contribution)
}else{
Timber.d(
"WikiDataEdit not required, making wikidata edit"
)
makeWikiDataEdit(uploadResult, 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)
if (STASH_ERROR_CODES.contains(exception.message)) {
clearChunks(contribution)
}
}
}
StashUploadState.PAUSED -> {
showPausedNotification(contribution)
contribution.state = Contribution.STATE_PAUSED
contributionDao.save(contribution).blockingGet()
}
else -> {
Timber.e("""upload file to stash failed with status: ${stashUploadResult.state}""")
showFailedNotification(contribution)
contribution.state = Contribution.STATE_FAILED
contribution.chunkInfo = null
contributionDao.save(contribution).blockingAwait()
}
}
}catch (exception: Exception){
Timber.e(exception)
Timber.e("Stash upload failed for contribution: $filename")
showFailedNotification(contribution)
}
}
private fun clearChunks(contribution: Contribution) {
contribution.chunkInfo=null
contributionDao.save(contribution).blockingAwait()
}
/**
* 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)
}
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.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()
)
}
} | apache-2.0 | a3c95062b3b21c9a11f14ac21fe9a7f7 | 37.758836 | 103 | 0.580249 | 5.959719 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | livingdoc-tests/src/test/kotlin/org/livingdoc/example/CalculatorDocumentHtmlEmptyCell.kt | 2 | 2906 | package org.livingdoc.example
import org.assertj.core.api.Assertions.assertThat
import org.livingdoc.api.documents.ExecutableDocument
import org.livingdoc.api.fixtures.decisiontables.BeforeRow
import org.livingdoc.api.fixtures.decisiontables.Check
import org.livingdoc.api.fixtures.decisiontables.DecisionTableFixture
import org.livingdoc.api.fixtures.decisiontables.Input
import org.livingdoc.api.tagging.Tag
@Tag("html")
@ExecutableDocument("local://CalculatorEmptyCell.html")
class CalculatorDocumentHtmlEmptyCell {
@DecisionTableFixture()
class CalculatorDecisionTableFixture {
private lateinit var sut: Calculator
@Input("a")
private var valueA: Float = 0f
private var valueB: Float = 0f
@BeforeRow
fun beforeRow() {
sut = Calculator()
}
@Input("b")
fun setValueB(valueB: Float) {
this.valueB = valueB
}
@Check("a + b = ?")
fun checkSum(expectedValue: Float?) {
val result = sut.sum(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a - b = ?")
fun checkDiff(expectedValue: Float?) {
val result = sut.diff(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a * b = ?")
fun checkMultiply(expectedValue: Float?) {
val result = sut.multiply(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a / b = ?")
fun checkDivide(expectedValue: Float?) {
val result = sut.divide(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
}
@DecisionTableFixture()
class CalculatorDecisionTableFixture2 {
private lateinit var sut: Calculator
@Input("x")
private var valueA: Float = 0f
private var valueB: Float = 0f
@BeforeRow
fun beforeRow() {
sut = Calculator()
}
@Input("y")
fun setValueB(valueB: Float) {
this.valueB = valueB
}
@Check("a + b = ?")
fun checkSum(expectedValue: Float?) {
val result = sut.sum(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a - b = ?")
fun checkDiff(expectedValue: Float?) {
val result = sut.diff(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a * b = ?")
fun checkMultiply(expectedValue: Float?) {
val result = sut.multiply(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
@Check("a / b = ?")
fun checkDivide(expectedValue: Float?) {
val result = sut.divide(valueA, valueB)
assertThat(result).isEqualTo(expectedValue)
}
}
}
| apache-2.0 | 6d0ec2f0eef97a26b21aa5793a6f23fc | 27.490196 | 69 | 0.594288 | 4.679549 | false | false | false | false |
testIT-LivingDoc/livingdoc2 | buildSrc/src/main/kotlin/Versions.kt | 2 | 814 | import org.gradle.api.JavaVersion
object Versions {
//Language
val jvmTarget = JavaVersion.VERSION_1_8
val kotlinVersion = "1.3.50"
val kotlinApi = "1.3"
//Dependencies
val slf4j = "1.7.25"
val snakeyaml= "1.18"
val jsoup = "1.11.2"
val flexmark = "0.28.32"
val klaxon = "5.2"
val gherkin = "9.0.0"
const val jgit = "5.6.1.202002131546-r"
//Test
val junitPlatform = "1.5.2"
val junitJupiter = "5.5.2"
val mockk = "1.9.3"
val logback = "1.2.3"
val assertJ = "3.11.1"
val wiremock = "2.25.1"
//Plugins
val buildScanPlugin = "2.2.1"
val spotlessPlugin = "3.23.0"
val dokkaPlugin = "0.10.0"
//AsciiDoctor
val asciidoctorPlugin = "1.5.3"
//Tools
val detektVersion = "1.0.1"
val ktlint = "0.33.0"
}
| apache-2.0 | 101389b34fad6b189d97df4267409137 | 19.871795 | 43 | 0.574939 | 2.686469 | false | false | false | false |
twbarber/cash-register | cash-register-public/src/main/kotlin/com/twbarber/register/public/data/Balance.kt | 1 | 2639 | package com.twbarber.register.public.data
import com.twbarber.register.public.data.MoneyValue.TWENTY
import com.twbarber.register.public.data.MoneyValue.TEN
import com.twbarber.register.public.data.MoneyValue.FIVE
import com.twbarber.register.public.data.MoneyValue.TWO
import java.util.*
data class Balance(val twenties: Int, val tens: Int, val fives: Int, val twos: Int, val ones: Int) {
private val INPUT_IS_NEGATIVE = "Must provide a non-negative value for all bills."
private fun resultIsNegative(bill: String) : String { return "Not enough $bill to complete transaction." }
init {
require(this.twenties >=0 && this.tens >=0 && this.fives >=0
&& this.twos >=0 && this.ones >=0) { INPUT_IS_NEGATIVE }
}
fun total() : Int = TWENTY.value * twenties + TEN.value * tens + FIVE.value * fives + TWO.value * twos + ones
fun bills() : String = "$twenties $tens $fives $twos $ones"
fun allBills() : ArrayList<Int> {
val bills = ArrayList<Int>()
for (i in 1..twenties) bills.add(20)
for (i in 1..tens) bills.add(10)
for (i in 1..fives) bills.add(5)
for (i in 1..twos) bills.add(2)
for (i in 1..ones) bills.add(1)
return bills
}
fun take(transaction: Balance) : Balance {
require(this.twenties - transaction.twenties >= 0) { resultIsNegative("twenties") }
require(this.tens - transaction.tens >= 0) { resultIsNegative("tens") }
require(this.fives - transaction.fives >= 0) { resultIsNegative("fives") }
require(this.twos - transaction.twos >= 0) { resultIsNegative("twos") }
require(this.ones - transaction.ones >= 0) { resultIsNegative("ones") }
return Balance(this.twenties - transaction.twenties, this.tens - transaction.tens,
this.fives - transaction.fives, this.twos - transaction.twos, this.ones - transaction.ones)
}
fun put(transaction: Balance) : Balance {
require(transaction.twenties >= 0) { resultIsNegative("twenties") }
require(transaction.tens >= 0) { resultIsNegative("tens") }
require(transaction.fives >= 0) { resultIsNegative("fives") }
require(transaction.twos >= 0) { resultIsNegative("twos") }
require(transaction.ones >= 0) { resultIsNegative("ones") }
return Balance(this.twenties + transaction.twenties, this.tens + transaction.tens,
this.fives + transaction.fives, this.twos + transaction.twos, this.ones + transaction.ones)
}
fun show() : String {
val total = total()
val bills = bills()
return "\$$total $bills"
}
} | mit | 179275a87604aca61ba091c82c94cc38 | 43 | 113 | 0.644183 | 3.418394 | false | false | false | false |
Softmotions/ncms | ncms-engine/ncms-engine-core/src/main/java/com/softmotions/ncms/mtt/http/MttABMarksAction.kt | 1 | 2993 | package com.softmotions.ncms.mtt.http
import com.google.inject.Singleton
import com.softmotions.web.*
import org.slf4j.LoggerFactory
import javax.annotation.concurrent.ThreadSafe
import javax.servlet.http.Cookie
import javax.servlet.http.HttpServletResponse
/**
* Set A/B marks action.
*
* @author Adamansky Anton ([email protected])
*/
@Singleton
@ThreadSafe
@Suppress("UNCHECKED_CAST")
class MttABMarksAction : MttActionHandler {
private val log = LoggerFactory.getLogger(javaClass)
override val type = "abmarks"
override fun execute(ctx: MttActionHandlerContext,
rmc: MttRequestModificationContext,
resp: HttpServletResponse): Boolean {
val spec = ctx.spec
if (!ctx.containsKey("marks")) {
synchronized(this) {
if (ctx.containsKey("marks")) return@synchronized
ctx["marks"] = spec.path("marks")
.asText()
.split(',')
.filter { it.isNotBlank() }.map { it.trim().toLowerCase() }
.toSet()
}
}
val req = rmc.req
val rid = (req.getAttribute(MttHttpFilter.MTT_RIDS_KEY) as Collection<Long>).last()
val cookieName = "_abm_${rid}"
if (req[cookieName] != null) {
if (log.isDebugEnabled) {
log.debug("Skipping AB cookie set due to existing req " +
"attribute: ${cookieName}=${req[cookieName]}")
}
rmc.paramsForRedirect[cookieName] = (req[cookieName] as Set<String>).joinToString(",");
return false
}
val marks = ctx["marks"] as Set<String>
var cookie = req.cookie(cookieName)
if (cookie != null) {
if (log.isDebugEnabled) {
log.debug("Skipping AB cookie set due to existing " +
"cookie: ${cookieName}=${cookie.decodeValue()}")
}
rmc.paramsForRedirect[cookieName] = cookie.decodeValue();
return false
}
val time = spec.path("time").asInt()
val units = spec.path("units").asText("")
if (units.isEmpty()) {
log.error("Invalid action spec: ${spec}")
return false
}
cookie = Cookie(cookieName, null)
cookie.setEncodedValue(marks.joinToString(","));
cookie.maxAge = when (units) {
"days" -> time * 24 * 60 * 60
"minutes" -> time * 60
else -> {
log.error("Invalid action units, spec=${spec}")
time
}
}
resp.addCookie(cookie);
req[cookieName] = marks
rmc.paramsForRedirect[cookieName] = cookie.decodeValue();
if (log.isDebugEnabled) {
log.debug("Set AB cookie ${cookieName}=${cookie.decodeValue()} " +
"maxAge=${cookie.maxAge}")
}
return false
}
} | apache-2.0 | ade7c332b45d314a0ec2c16bb575abc4 | 32.266667 | 99 | 0.545941 | 4.521148 | false | false | false | false |
ZoranPandovski/al-go-rithms | sort/heap_sort/Kotlin/HeapSort.kt | 1 | 1545 | /*
Heapsort is an in-place sorting algorithm with worst case and average complexity of O(n*logn).
The basic idea is to turn the array into a binary heap structure, which has the property that it allows efficient retrieval and removal of the maximal element.
We repeatedly "remove" the maximal element from the heap, thus building the sorted list from back to front.
Heapsort requires random access, so can only be used on an array-like data structure.
*/
fun heapSort(a: IntArray) {
heapify(a)
var end = a.size - 1
while (end > 0) {
val temp = a[end]
a[end] = a[0]
a[0] = temp
end--
siftDown(a, 0, end)
}
}
fun heapify(a: IntArray) {
var start = (a.size - 2) / 2
while (start >= 0) {
siftDown(a, start, a.size - 1)
start--
}
}
fun siftDown(a: IntArray, start: Int, end: Int) {
var root = start
while (root * 2 + 1 <= end) {
var child = root * 2 + 1
if (child + 1 <= end && a[child] < a[child + 1]) child++
if (a[root] < a[child]) {
val temp = a[root]
a[root] = a[child]
a[child] = temp
root = child
}
else return
}
}
fun main(args: Array<String>) {
val aa = arrayOf(
intArrayOf(100, 2, 56, 200, -52, 3, 99, 33, 177, -199),
intArrayOf(4, 65, 2, -31, 0, 99, 2, 83, 782, 1),
intArrayOf(12, 11, 15, 10, 9, 1, 2, 3, 13, 14, 4, 5, 6, 7, 8)
)
for (a in aa) {
heapSort(a)
println(a.joinToString(", "))
}
} | cc0-1.0 | 52bc734cd3122a56d3e6792f8ac342e1 | 28.169811 | 159 | 0.54822 | 3.198758 | false | false | false | false |
google/intellij-gn-plugin | src/main/java/com/google/idea/gn/config/GnProjectConfigurable.kt | 1 | 1116 | // Copyright (c) 2020 Google LLC All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package com.google.idea.gn.config
import com.intellij.openapi.Disposable
import com.intellij.openapi.options.Configurable
import com.intellij.openapi.project.Project
import javax.swing.JComponent
class GnProjectConfigurable(project: Project) : GnConfigurableBase(
project), Configurable.NoScroll, Disposable {
private var modified: Boolean = false
override fun isModified() = modified
override fun getDisplayName(): String {
return "Gn"
}
override fun apply() {
settings.modify {
it.projectRoot = projectPathField.text
}
}
private val projectPathField = pathToDirectoryTextField(
this,
"Select Project's Gn root",
onTextChanged = fun() {
modified = true
}
).apply {
isEditable = false
project.gnRoot?.let {
text = it.path
}
}
override fun createComponent(): JComponent? = layout {
row("Gn root", projectPathField)
}
override fun dispose() {
}
}
| bsd-3-clause | eef58957fd946f4d672a511f8e51517e | 21.77551 | 67 | 0.694444 | 4.325581 | false | true | false | false |
rjhdby/motocitizen | Motocitizen/src/motocitizen/ui/frames/create/TypeFrame.kt | 1 | 1204 | package motocitizen.ui.frames.create
import android.support.v4.app.FragmentActivity
import android.view.View
import motocitizen.dictionary.Type
import motocitizen.main.R
import motocitizen.ui.frames.FrameInterface
import motocitizen.utils.hide
import motocitizen.utils.show
class TypeFrame(val context: FragmentActivity, val callback: (Type) -> Unit) : FrameInterface {
private val view = context.findViewById<View>(R.id.create_type_frame)
init {
intArrayOf(R.id.ACCIDENT, R.id.BREAK, R.id.STEAL, R.id.OTHER)
.forEach { setListener(it, typeSelectListener(it)) }
}
override fun show() = view.show()
override fun hide() = view.hide()
private fun setListener(id: Int, listener: View.OnClickListener) {
context.findViewById<View>(id).setOnClickListener(listener)
}
private fun typeSelectListener(id: Int): View.OnClickListener = View.OnClickListener { callback(getSelectedType(id)) }
private fun getSelectedType(id: Int): Type = when (id) {
R.id.ACCIDENT -> Type.MOTO_AUTO
R.id.BREAK -> Type.BREAK
R.id.STEAL -> Type.STEAL
R.id.OTHER -> Type.OTHER
else -> Type.OTHER
}
} | mit | 1ef3868f876c72f689d7928117c260d9 | 32.472222 | 122 | 0.687708 | 3.786164 | false | false | false | false |
tommyettinger/SquidSetup | src/main/kotlin/com/github/czyzby/setup/data/platforms/iOS.kt | 1 | 7310 | package com.github.czyzby.setup.data.platforms
import com.github.czyzby.setup.data.files.CopiedFile
import com.github.czyzby.setup.data.files.SourceFile
import com.github.czyzby.setup.data.files.path
import com.github.czyzby.setup.data.gradle.GradleFile
import com.github.czyzby.setup.data.libs.official.Controllers
import com.github.czyzby.setup.data.libs.official.OfficialExtension
import com.github.czyzby.setup.data.project.Project
import com.github.czyzby.setup.views.GdxPlatform
/**
* Represents iOS backend.
* @author MJ
*/
@GdxPlatform
class iOS : Platform {
companion object {
const val ID = "ios"
}
override val id = ID
override val isStandard = false
override fun createGradleFile(project: Project): GradleFile = iOSGradleFile(project)
override fun initiate(project: Project) {
project.rootGradle.buildDependencies.add("\"com.mobidevelop.robovm:robovm-gradle-plugin:\$robovmVersion\"")
project.properties["robovmVersion"] = project.advanced.robovmVersion
// Including RoboVM config files:
project.files.add(CopiedFile(projectName = ID, path = "Info.plist.xml",
original = path("generator", "ios", "Info.plist.xml")))
project.files.add(SourceFile(projectName = ID, fileName = "robovm.properties", content = """app.version=${project.advanced.version.replace("[^0-9\\.]", "")}
app.id=${project.basic.rootPackage}
app.mainclass=${project.basic.rootPackage}.ios.IOSLauncher
app.executable=IOSLauncher
app.build=1
app.name=${project.basic.name}"""))
project.files.add(SourceFile(projectName = ID, fileName = "robovm.xml", content = """<config>
<executableName>${'$'}{app.executable}</executableName>
<mainClass>${'$'}{app.mainclass}</mainClass>
<os>ios</os>
<target>ios</target>
<iosInfoPList>Info.plist.xml</iosInfoPList>
<treeShaker>conservative</treeShaker>
<resources>
<resource>
<directory>../assets</directory>
<includes>
<include>**</include>
</includes>
<skipPngCrush>true</skipPngCrush>
</resource>
<resource>
<directory>data</directory>
</resource>
</resources>
<forceLinkClasses>
<pattern>com.badlogic.gdx.scenes.scene2d.ui.*</pattern>
<pattern>com.badlogic.gdx.graphics.g3d.particles.**</pattern>
<pattern>com.android.okhttp.HttpHandler</pattern>
<pattern>com.android.okhttp.HttpsHandler</pattern>
<pattern>com.android.org.conscrypt.**</pattern>
<pattern>com.android.org.bouncycastle.jce.provider.BouncyCastleProvider</pattern>
<pattern>com.android.org.bouncycastle.jcajce.provider.keystore.BC${'$'}Mappings</pattern>
<pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi</pattern>
<pattern>com.android.org.bouncycastle.jcajce.provider.keystore.bc.BcKeyStoreSpi${'$'}Std</pattern>
<pattern>com.android.org.bouncycastle.jce.provider.PKIXCertPathValidatorSpi</pattern>
<pattern>com.android.org.bouncycastle.crypto.digests.AndroidDigestFactoryOpenSSL</pattern>
<pattern>org.apache.harmony.security.provider.cert.DRLCertFactory</pattern>
<pattern>org.apache.harmony.security.provider.crypto.CryptoProvider</pattern>
${if (project.extensions.getSelectedOfficialExtensions().find { it.id == "gdx-controllers" } != null) "\t\t<pattern>com.badlogic.gdx.controllers.IosControllerManager</pattern>" else ""}
</forceLinkClasses>
<libs>
<lib>z</lib>
</libs>
<frameworks>
<framework>UIKit</framework>
<framework>OpenGLES</framework>
<framework>QuartzCore</framework>
<framework>CoreGraphics</framework>
<framework>OpenAL</framework>
<framework>AudioToolbox</framework>
<framework>AVFoundation</framework>
<framework>GameController</framework>
${if (project.extensions.getSelectedOfficialExtensions().find { it.id == "gdx-controllers" } != null) "\t\t<framework>GameKit</framework>" else ""}
</frameworks>
</config>"""))
project.files.add(CopiedFile(projectName = ID, path = path("data", "Media.xcassets", "Contents.json"),
original = path("generator", "ios", "data", "Media.xcassets", "Contents.json")))
arrayOf(
"[email protected]",
"Contents.json",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]",
"[email protected]"
).forEach {
project.files.add(CopiedFile(projectName = ID, path = path("data", "Media.xcassets", "AppIcon.appiconset", it),
original = path("generator", "ios", "data", "Media.xcassets", "AppIcon.appiconset", it)))
}
arrayOf(
"Contents.json",
"[email protected]",
"[email protected]",
"[email protected]"
).forEach {
project.files.add(CopiedFile(projectName = ID, path = path("data", "Media.xcassets", "Logo.imageset", it),
original = path("generator", "ios", "data", "Media.xcassets", "Logo.imageset", it)))
}
project.files.add(CopiedFile(projectName = ID, path = path("data", "Base.lproj", "LaunchScreen.storyboard"),
original = path("generator", "ios", "data", "Base.lproj", "LaunchScreen.storyboard")))
// Including reflected classes:
if (project.reflectedClasses.isNotEmpty() || project.reflectedPackages.isNotEmpty()) {
project.files.add(SourceFile(projectName = ID, sourceFolderPath = path("src", "main", "resources"),
packageName = "META-INF.robovm.ios", fileName = "robovm.xml", content = """<config>
<forceLinkClasses>
${project.reflectedPackages.joinToString(separator = "\n") { " <pattern>${it}.**</pattern>" }}
${project.reflectedClasses.joinToString(separator = "\n") { " <pattern>${it}</pattern>" }}
</forceLinkClasses>
</config>"""))
}
}
}
class iOSGradleFile(val project: Project) : GradleFile(iOS.ID) {
init {
dependencies.add("project(':${Core.ID}')")
addDependency("com.mobidevelop.robovm:robovm-rt:\$robovmVersion")
addDependency("com.mobidevelop.robovm:robovm-cocoatouch:\$robovmVersion")
addDependency("com.badlogicgames.gdx:gdx-backend-robovm:\$gdxVersion")
addDependency("com.badlogicgames.gdx:gdx-platform:\$gdxVersion:natives-ios")
}
override fun getContent() = """apply plugin: 'robovm'
[compileJava, compileTestJava]*.options*.encoding = 'UTF-8'
ext {
mainClassName = "${project.basic.rootPackage}.ios.IOSLauncher"
}
launchIPhoneSimulator.dependsOn build
launchIPadSimulator.dependsOn build
launchIOSDevice.dependsOn build
createIPA.dependsOn build
eclipse.project {
name = appName + "-ios"
natures 'org.robovm.eclipse.RoboVMNature'
}
dependencies {
${joinDependencies(dependencies)}}
"""
}
| apache-2.0 | 13f7083d0e816a9b96db2a86d9c9809e | 41.5 | 185 | 0.683447 | 3.534816 | false | false | false | false |
gradle/gradle | subprojects/kotlin-dsl/src/integTest/kotlin/org/gradle/kotlin/dsl/codegen/ApiTypeProviderTest.kt | 3 | 7480 | /*
* Copyright 2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.gradle.kotlin.dsl.codegen
import org.gradle.api.Action
import org.gradle.api.NamedDomainObjectFactory
import org.gradle.api.Plugin
import org.gradle.api.file.ContentFilterable
import org.gradle.api.internal.file.copy.CopySpecSource
import org.gradle.api.model.ObjectFactory
import org.gradle.api.plugins.PluginCollection
import org.gradle.api.specs.Spec
import org.gradle.api.tasks.AbstractCopyTask
import org.gradle.kotlin.dsl.fixtures.AbstractKotlinIntegrationTest
import org.gradle.kotlin.dsl.fixtures.codegen.GenericsVariance
import org.gradle.kotlin.dsl.support.canonicalNameOf
import org.hamcrest.CoreMatchers.equalTo
import org.hamcrest.CoreMatchers.nullValue
import org.junit.Assert.assertFalse
import org.hamcrest.MatcherAssert.assertThat
import org.junit.Assert.assertTrue
import org.junit.Test
class ApiTypeProviderTest : AbstractKotlinIntegrationTest() {
@Test
fun `provides a source code generation oriented model over a classpath`() {
val jars = listOf(
withClassJar(
"some.jar",
Plugin::class.java,
PluginCollection::class.java,
ObjectFactory::class.java
)
)
apiTypeProviderFor(jars).use { api ->
assertThat(api.typeOrNull<Test>(), nullValue())
api.type<PluginCollection<*>>().apply {
assertThat(sourceName, equalTo("org.gradle.api.plugins.PluginCollection"))
assertTrue(isPublic)
assertThat(typeParameters.size, equalTo(1))
typeParameters.single().apply {
assertThat(sourceName, equalTo("T"))
assertThat(bounds.size, equalTo(1))
assertThat(bounds.single().sourceName, equalTo("org.gradle.api.Plugin"))
}
functions.single { it.name == "withType" }.apply {
assertThat(typeParameters.size, equalTo(1))
typeParameters.single().apply {
assertThat(sourceName, equalTo("S"))
assertThat(bounds.size, equalTo(1))
assertThat(bounds.single().sourceName, equalTo("T"))
}
assertThat(parameters.size, equalTo(1))
parameters.single().type.apply {
assertThat(sourceName, equalTo("java.lang.Class"))
assertThat(typeArguments.size, equalTo(1))
typeArguments.single().apply {
assertThat(sourceName, equalTo("S"))
}
}
returnType.apply {
assertThat(sourceName, equalTo("org.gradle.api.plugins.PluginCollection"))
assertThat(typeArguments.size, equalTo(1))
typeArguments.single().apply {
assertThat(sourceName, equalTo("S"))
}
}
}
}
api.type<ObjectFactory>().apply {
functions.single { it.name == "newInstance" }.apply {
parameters.drop(1).single().type.apply {
assertThat(sourceName, equalTo("kotlin.Array"))
assertThat(typeArguments.single().sourceName, equalTo("Any"))
}
}
}
}
}
@Test
fun `maps generic question mark to star projection`() {
val jars = listOf(withClassJar("some.jar", ContentFilterable::class.java))
apiTypeProviderFor(jars).use { api ->
api.type<ContentFilterable>().functions.single { it.name == "expand" && it.parameters.size == 1 }.apply {
assertTrue(typeParameters.isEmpty())
parameters.single().type.apply {
assertThat(sourceName, equalTo("kotlin.collections.Map"))
assertThat(typeArguments.size, equalTo(2))
assertThat(typeArguments[0].sourceName, equalTo("String"))
assertThat(typeArguments[1].sourceName, equalTo("*"))
}
}
}
}
@Test
fun `includes function overrides that change signature, excludes overrides that don't`() {
val jars = listOf(withClassJar("some.jar", AbstractCopyTask::class.java, CopySpecSource::class.java))
apiTypeProviderFor(jars).use { api ->
val type = api.type<AbstractCopyTask>()
assertThat(type.functions.filter { it.name == "filter" }.size, equalTo(4))
assertThat(type.functions.filter { it.name == "getRootSpec" }.size, equalTo(0))
}
}
@Test
fun `provides generic bounds`() {
fun ApiFunctionParameter.assertSingleTypeArgumentWithVariance(variance: Variance) =
assertThat(type.typeArguments.single().variance, equalTo(variance))
val jars = listOf(withClassJar("some.jar", GenericsVariance::class.java))
apiTypeProviderFor(jars).use { api ->
api.type<GenericsVariance>().functions.forEach { function ->
when (function.name) {
"invariant" -> function.parameters.single().assertSingleTypeArgumentWithVariance(Variance.INVARIANT)
"covariant" -> function.parameters.single().assertSingleTypeArgumentWithVariance(Variance.COVARIANT)
"contravariant" -> function.parameters.single().assertSingleTypeArgumentWithVariance(Variance.CONTRAVARIANT)
}
}
}
}
@Test
fun `provides if a type is a SAM`() {
val jars = listOf(
withClassJar(
"some.jar",
Action::class.java,
NamedDomainObjectFactory::class.java,
ObjectFactory::class.java,
PluginCollection::class.java,
Spec::class.java
)
)
apiTypeProviderFor(jars).use { api ->
assertTrue(api.type<Action<*>>().isSAM)
assertTrue(api.type<NamedDomainObjectFactory<*>>().isSAM)
assertFalse(api.type<ObjectFactory>().isSAM)
assertFalse(api.type<PluginCollection<*>>().isSAM)
assertTrue(
api.type<PluginCollection<*>>().functions
.filter { it.name == "matching" }
.single { it.parameters.single().type.sourceName == Spec::class.qualifiedName }
.parameters.single().type.type!!.isSAM
)
assertTrue(api.type<Spec<*>>().isSAM)
}
}
private
inline fun <reified T> ApiTypeProvider.type() =
typeOrNull<T>()!!
private
inline fun <reified T> ApiTypeProvider.typeOrNull() =
type(canonicalNameOf<T>())
}
| apache-2.0 | 34c740a2a295a8d75d37a859bf0fc112 | 36.969543 | 128 | 0.589572 | 5.003344 | false | true | false | false |
VerifAPS/verifaps-lib | smv/src/main/kotlin/edu/kit/iti/formal/smv/SMVPrinter.kt | 1 | 8027 | package edu.kit.iti.formal.smv
import edu.kit.iti.formal.smv.ast.*
import edu.kit.iti.formal.util.CodeWriter
import org.jetbrains.annotations.NotNull
import java.io.BufferedWriter
import java.io.File
import java.io.FileWriter
import java.util.regex.Pattern
class SMVPrinter(val stream: CodeWriter = CodeWriter()) : SMVAstVisitor<Unit> {
val sort = true
override fun visit(top: SMVAst) {
throw IllegalArgumentException("not implemented for $top")
}
override fun visit(be: SBinaryExpression) {
val pleft = precedence(be.left)
val pright = precedence(be.right)
val pown = precedence(be)
if (pleft > pown) stream.print('(')
be.left.accept(this)
if (pleft > pown) stream.print(')')
stream.print(" " + be.operator.symbol() + " ")
if (pright > pown) stream.print('(')
be.right.accept(this)
if (pright > pown) stream.print(')')
}
private fun precedence(expr: SMVExpr): Int {
if (expr is SBinaryExpression) {
val operator = expr.operator
return operator.precedence()
}
if (expr is SUnaryExpression) {
return expr.operator.precedence()
}
return if (expr is SLiteral || expr is SVariable
|| expr is SFunction) {
-1
} else 1000
}
override fun visit(ue: SUnaryExpression) {
if (ue.expr is SBinaryExpression) {
stream.print(ue.operator.symbol())
stream.print("(")
ue.expr.accept(this)
stream.print(")")
} else {
stream.print(ue.operator.symbol())
ue.expr.accept(this)
}
}
override fun visit(l: SLiteral) {
stream.print(l.dataType.format(l.value))
}
override fun visit(a: SAssignment) {
a.target.accept(this)
stream.print(" := ")
a.expr.accept(this)
stream.print(";").nl()
}
override fun visit(ce: SCaseExpression) {
stream.print("case").increaseIndent()
for ((condition, then) in ce.cases) {
stream.nl()
condition.accept(this)
stream.print(" : ")
then.accept(this)
stream.print("; ")
}
stream.decreaseIndent().nl().print("esac")
}
override fun visit(m: SMVModule) {
stream.print("MODULE ")
stream.print(m.name)
if (!m.moduleParameters.isEmpty()) {
stream.print("(");
m.moduleParameters.forEachIndexed { index, sVariable ->
sVariable.accept(this)
if (index + 1 < m.moduleParameters.size) stream.print(", ")
}
stream.print(")")
}
stream.nl()
printVariables("IVAR", m.inputVars)
printVariables("FROZENVAR", m.frozenVars)
printVariables("VAR", m.stateVars)
printDefinition(m.definitions)
printSection("LTLSPEC", m.ltlSpec)
printSection("CTLSPEC", m.ctlSpec)
printSection("INVARSPEC", m.invariantSpecs)
printSection("INVAR", m.invariants)
printSectionSingle("INIT", m.initExpr)
printSectionSingle("TRANS", m.transExpr)
if (m.initAssignments.size > 0 || m.nextAssignments.size > 0) {
stream.print("ASSIGN").increaseIndent()
printAssignments("init", m.initAssignments)
printAssignments("next", m.nextAssignments)
stream.decreaseIndent()
}
stream.nl().print("-- end of module ${m.name}").nl()
}
private fun printSectionSingle(section: String, exprs: List<SMVExpr>) {
if (!exprs.isEmpty()) {
stream.print(section).increaseIndent().nl()
exprs.conjunction().accept(this)
stream.print(";").decreaseIndent().nl()
}
}
private fun printDefinition(assignments: List<SAssignment>) {
stream.printf("DEFINE").increaseIndent()
for ((target, expr) in assignments) {
stream.nl().print(target.name).print(" := ")
expr.accept(this)
stream.print(";")
}
stream.decreaseIndent().nl()
}
private fun printAssignments(func: String, a: List<SAssignment>) {
val assignments = if (sort) a.sortedBy { it.target.name } else a
for ((target, expr) in assignments) {
stream.nl().print(func).print('(').print(quoted(target.name)).print(") := ")
expr.accept(this)
stream.print(";")
}
}
private fun printSection(section: String, exprs: List<SMVExpr>) {
if (exprs.isNotEmpty()) {
exprs.forEach { e ->
stream.nl().print(section).increaseIndent().nl()
e.accept(this)
stream.decreaseIndent().nl().nl()
}
}
}
override fun visit(func: SFunction) {
when (func.name) {
SMVFacade.FUNCTION_ID_BIT_ACCESS ->
visitBitAccess(func)
}
stream.print(func.name)
stream.print('(')
func.arguments.forEachIndexed { i, e ->
e.accept(this)
if (i + 1 < func.arguments.size)
stream.print(", ")
}
stream.print(')')
}
private fun visitBitAccess(func: SFunction) {
TODO("not implemented")
}
override fun visit(quantified: SQuantified) {
when (quantified.operator.arity()) {
1 -> {
stream.print(quantified.operator.symbol())
stream.print("( ")
quantified[0].accept(this)
stream.print(")")
}
2 -> {
stream.print("( ")
(quantified[0].accept(this))
stream.print(")")
stream.print(quantified.operator.symbol())
stream.print("( ")
(quantified[1].accept(this))
stream.print(")")
}
else -> throw IllegalStateException("too much arity")
}
}
private fun printVariables(type: String, v: List<SVariable>) {
val vars =
if (sort) v.sorted()
else v
if (vars.isNotEmpty()) {
stream.print(type).increaseIndent()
for (svar in vars) {
stream.nl()
printQuoted(svar.name)
stream.print(" : ")
stream.print(svar.dataType?.repr() ?: "<")
stream.print(";")
}
stream.decreaseIndent().nl().print("-- end of $type").nl()
}
}
override fun visit(v: SVariable) = printQuoted(v.name)
fun printQuoted(name: String) {
stream.print(quoted(name))
}
companion object {
private val RESERVED_KEYWORDS = hashSetOf("A", "E", "F", "G", "INIT", "MODULE", "case", "easc",
"next", "init", "TRUE", "FALSE", "in", "mod", "union", "process", "AU", "EU", "U", "V", "S",
"T", "EG", "EX", "EF", "AG", "AX", "AF", "X", "Y", "Z", "H", "O", "min", "max")
private val regex by lazy {
val rk = RESERVED_KEYWORDS.joinToString("|", "(", ")")
"(?<![a-zA-Z\$_])($rk)(?![a-zA-Z\$_])".toRegex()
}
fun quoted(name: String) :String {
/*return regex.replace(name) {
"\"${it.value}\""
}*/
return if (name in RESERVED_KEYWORDS) "\"$name\"" else name
}
@JvmStatic
fun toString(m: SMVAst): String {
val s = CodeWriter()
val p = SMVPrinter(s)
m.accept(p)
return s.stream.toString()
}
@JvmStatic
fun toFile(m: @NotNull SMVAst, file: @NotNull File, append: Boolean = false) {
BufferedWriter(FileWriter(file, append)).use { stream ->
CodeWriter(stream).let {
val p = SMVPrinter(it)
m.accept(p)
}
}
}
}
}
| gpl-3.0 | 09ba844f3f18c01b9cc88fb35d3efcf8 | 29.405303 | 108 | 0.51987 | 4.139763 | false | false | false | false |
AlmasB/FXGL | fxgl/src/main/kotlin/com/almasb/fxgl/app/scene/IntroScene.kt | 1 | 7091 | /*
* FXGL - JavaFX Game Library. The MIT License (MIT).
* Copyright (c) AlmasB ([email protected]).
* See LICENSE for details.
*/
package com.almasb.fxgl.app.scene
import com.almasb.fxgl.animation.AnimatedPoint2D
import com.almasb.fxgl.animation.Interpolators
import com.almasb.fxgl.core.util.EmptyRunnable
import com.almasb.fxgl.dsl.animationBuilder
import com.almasb.fxgl.dsl.image
import com.almasb.fxgl.dsl.random
import com.almasb.fxgl.texture.toPixels
import javafx.geometry.Point2D
import javafx.scene.canvas.Canvas
import javafx.scene.canvas.GraphicsContext
import javafx.scene.paint.Color
import javafx.util.Duration
import java.util.function.Consumer
/**
* Intro animation / video played before game starts
* if intro is enabled in settings.
*
* Call [finishIntro] when your intro completed
* so that the game can proceed to the next state.
*
* @author Almas Baimagambetov (AlmasB) ([email protected])
*/
abstract class IntroScene : FXGLScene() {
internal var onFinished: Runnable = EmptyRunnable
override fun onCreate() {
startIntro()
}
/**
* Closes intro and initializes the next game state, whether it's a menu or game.
*
* Note: call this when your intro completes, otherwise
* the game won't proceed to next state.
*/
protected fun finishIntro() {
onFinished.run()
}
/**
* Starts the intro animation / video.
*/
abstract fun startIntro()
}
/**
* This is the default FXGL Intro animation.
*
* @author Almas Baimagambetov (AlmasB) ([email protected])
*/
class FXGLIntroScene : IntroScene() {
private val pixels1: MutableList<Pixel>
private val pixels2: MutableList<Pixel>
private val fxglLogo = image("intro/fxgl_logo.png")
private val javafxLogo = image("intro/javafx_logo.png")
private val g: GraphicsContext
private var delayIndex = 0.0
init {
setBackgroundColor(Color.BLACK)
val fxglLogoPixels = toPixels(fxglLogo)
pixels1 = fxglLogoPixels
.filter { (_, _, color) -> color != Color.TRANSPARENT }
.mapIndexed { index, (x, y, color) ->
Pixel(
layoutX = x + (appWidth / 2.0 - fxglLogo.width / 2.0),
layoutY = y + (appHeight / 2.0 - fxglLogo.height / 2.0),
scaleX = 0.0,
scaleY = 0.0,
fill = color,
index = index
)
}.toMutableList()
pixels2 = toPixels(javafxLogo)
.filter { (_, _, color) -> color != Color.TRANSPARENT }
.map { (x, y, color) ->
Pixel(layoutX = x + 0.0, layoutY = y + 0.0, fill = color)
}.toMutableList()
// add the difference in pixels as TRANSPARENT
val numPixels = pixels1.size - pixels2.size
pixels2 += fxglLogoPixels.filter { (_, _, color) -> color == Color.TRANSPARENT }
.take(numPixels)
.map { (x, y, _) ->
Pixel(layoutX = x + 0.0, layoutY = y + 0.0)
}
val canvas = Canvas(appWidth.toDouble(), appHeight.toDouble())
g = canvas.graphicsContext2D
contentRoot.children += canvas
}
private fun playAnim1() {
delayIndex = 0.0
pixels1.forEach { p ->
animationBuilder(this)
.autoReverse(true)
.repeat(2)
.delay(Duration.seconds(delayIndex + 0.001))
.duration(Duration.seconds(0.8))
.interpolator(Interpolators.SMOOTH.EASE_OUT())
.animate(AnimatedPoint2D(Point2D(0.0, 0.0), Point2D(1.0, 1.0)))
.onProgress(Consumer {
p.scaleX = it.x
p.scaleY = it.y
})
.buildAndPlay()
delayIndex += 0.0001
}
timer.runOnceAfter({
playAnim2()
}, Duration.seconds(3.0))
timer.runOnceAfter({
playAnim3()
}, Duration.seconds(5.5))
timer.runOnceAfter({
finishIntro()
}, Duration.seconds(7.9))
}
private fun playAnim2() {
delayIndex = 0.0
val centerX = appWidth / 2.0 - javafxLogo.width / 2.0
val centerY = appHeight / 2.0 - javafxLogo.height / 2.0
pixels1.forEach { p ->
val p2 = pixels2[p.index]
val offsetX = random(-250, 250)
val offsetY = random(-250, 250)
val baseX = centerX - p.layoutX + p2.layoutX
val baseY = centerY - p.layoutY + p2.layoutY
p.translateX = baseX + offsetX
p.translateY = baseY + offsetY
p.fill = p2.fill
animationBuilder(this)
.delay(Duration.seconds(delayIndex + 0.001))
.duration(Duration.seconds(0.75))
.interpolator(Interpolators.EXPONENTIAL.EASE_OUT())
.animate(AnimatedPoint2D(Point2D(0.0, 0.0), Point2D(1.0, 1.0)))
.onProgress(Consumer {
p.scaleX = it.x
p.scaleY = it.y
p.translateX = baseX + offsetX - offsetX * it.x * it.x
p.translateY = baseY + offsetY - offsetY * it.y * it.x
})
.buildAndPlay()
delayIndex += 0.0001
}
}
private fun playAnim3() {
delayIndex = 0.0
pixels1.sortedBy { it.layoutX }.forEach { p ->
animationBuilder(this)
.delay(Duration.seconds(random(delayIndex, delayIndex + 0.21)))
.duration(Duration.seconds(1.05))
.interpolator(Interpolators.EXPONENTIAL.EASE_IN())
.animate(AnimatedPoint2D(
Point2D(p.translateX, p.translateY),
Point2D(appWidth * 2.0, appHeight / 2.0))
)
.onProgress(Consumer {
p.translateX = it.x
p.translateY = it.y
})
.buildAndPlay()
delayIndex += 0.0001
}
}
override fun onUpdate(tpf: Double) {
g.clearRect(0.0, 0.0, appWidth.toDouble(), appHeight.toDouble())
pixels1.forEach {
g.fill = it.fill
g.fillRect(it.layoutX + it.translateX, it.layoutY + it.translateY, it.scaleX, it.scaleY)
}
}
override fun startIntro() = playAnim1()
}
private data class Pixel(
var layoutX: Double = 0.0,
var layoutY: Double = 0.0,
var translateX: Double = 0.0,
var translateY: Double = 0.0,
var scaleX: Double = 1.0,
var scaleY: Double = 1.0,
var fill: Color = Color.TRANSPARENT,
var index: Int = 0,
var colorProgress: Double = 0.0
) | mit | a01f95c963dbb2628d874354b9179657 | 30.380531 | 100 | 0.532506 | 4.163829 | false | false | false | false |
manami-project/manami | manami-gui/src/main/kotlin/io/github/manamiproject/manami/gui/ManamiAccess.kt | 1 | 10331 | package io.github.manamiproject.manami.gui
import io.github.manamiproject.manami.app.Manami
import io.github.manamiproject.manami.app.ManamiApp
import io.github.manamiproject.manami.app.cache.populator.CachePopulatorFinishedEvent
import io.github.manamiproject.manami.app.cache.populator.NumberOfEntriesPerMetaDataProviderEvent
import io.github.manamiproject.manami.app.extensions.castToSet
import io.github.manamiproject.manami.app.file.FileOpenedEvent
import io.github.manamiproject.manami.app.file.SavedAsFileEvent
import io.github.manamiproject.manami.app.inconsistencies.InconsistenciesCheckFinishedEvent
import io.github.manamiproject.manami.app.inconsistencies.InconsistenciesProgressEvent
import io.github.manamiproject.manami.app.inconsistencies.animelist.deadentries.AnimeListDeadEntriesInconsistenciesResultEvent
import io.github.manamiproject.manami.app.inconsistencies.animelist.metadata.AnimeListMetaDataInconsistenciesResultEvent
import io.github.manamiproject.manami.app.inconsistencies.lists.deadentries.DeadEntriesInconsistenciesResultEvent
import io.github.manamiproject.manami.app.inconsistencies.lists.metadata.MetaDataInconsistenciesResultEvent
import io.github.manamiproject.manami.app.lists.ListChangedEvent
import io.github.manamiproject.manami.app.lists.ListChangedEvent.EventType.ADDED
import io.github.manamiproject.manami.app.lists.ListChangedEvent.EventType.REMOVED
import io.github.manamiproject.manami.app.lists.ignorelist.AddIgnoreListStatusUpdateEvent
import io.github.manamiproject.manami.app.lists.watchlist.AddWatchListStatusUpdateEvent
import io.github.manamiproject.manami.app.relatedanime.RelatedAnimeFinishedEvent
import io.github.manamiproject.manami.app.relatedanime.RelatedAnimeFoundEvent
import io.github.manamiproject.manami.app.relatedanime.RelatedAnimeStatusEvent
import io.github.manamiproject.manami.app.search.FileSearchAnimeListResultsEvent
import io.github.manamiproject.manami.app.search.FileSearchIgnoreListResultsEvent
import io.github.manamiproject.manami.app.search.FileSearchWatchListResultsEvent
import io.github.manamiproject.manami.app.search.anime.AnimeEntryFinishedEvent
import io.github.manamiproject.manami.app.search.anime.AnimeEntryFoundEvent
import io.github.manamiproject.manami.app.search.anime.AnimeSearchEntryFoundEvent
import io.github.manamiproject.manami.app.search.anime.AnimeSearchFinishedEvent
import io.github.manamiproject.manami.app.search.season.AnimeSeasonEntryFoundEvent
import io.github.manamiproject.manami.app.search.season.AnimeSeasonSearchFinishedEvent
import io.github.manamiproject.manami.app.commands.history.FileSavedStatusChangedEvent
import io.github.manamiproject.manami.app.commands.history.UndoRedoStatusEvent
import io.github.manamiproject.manami.app.events.EventListType.*
import io.github.manamiproject.manami.app.inconsistencies.animelist.episodes.AnimeListEpisodesInconsistenciesResultEvent
import io.github.manamiproject.manami.app.migration.MetaDataMigrationProgressEvent
import io.github.manamiproject.manami.app.migration.MetaDataMigrationResultEvent
import io.github.manamiproject.manami.app.search.similaranime.SimilarAnimeFoundEvent
import io.github.manamiproject.manami.app.search.similaranime.SimilarAnimeSearchFinishedEvent
import io.github.manamiproject.manami.app.versioning.NewVersionAvailableEvent
import io.github.manamiproject.manami.gui.events.*
import tornadofx.Controller
class ManamiAccess(private val manami: ManamiApp = manamiInstance) : Controller(), ManamiApp by manami {
init {
(manami as Manami).eventMapping {
fire(
when(this) {
is FileOpenedEvent -> FileOpenedGuiEvent(this.fileName)
is SavedAsFileEvent -> SavedAsFileGuiEvent(this.fileName)
is ListChangedEvent<*> -> mapListChangeEvent(this)
is AddWatchListStatusUpdateEvent -> AddWatchListStatusUpdateGuiEvent(this.finishedTasks, this.tasks)
is AddIgnoreListStatusUpdateEvent -> AddIgnoreListStatusUpdateGuiEvent(this.finishedTasks, this.tasks)
is FileSavedStatusChangedEvent -> FileSavedStatusChangedGuiEvent(this.isFileSaved)
is UndoRedoStatusEvent -> UndoRedoStatusGuiEvent(this.isUndoPossible, this.isRedoPossible)
is RelatedAnimeFoundEvent -> mapRelatedAnimeFoundEvent(this)
is RelatedAnimeStatusEvent -> mapRelatedAnimeStatusEvent(this)
is RelatedAnimeFinishedEvent -> mapRelatedAnimeFinsihedEvent(this)
is AnimeSeasonEntryFoundEvent -> AnimeSeasonEntryFoundGuiEvent(this.anime)
is AnimeSeasonSearchFinishedEvent -> AnimeSeasonSearchFinishedGuiEvent
is CachePopulatorFinishedEvent -> CachePopulatorFinishedGuiEvent
is FileSearchAnimeListResultsEvent -> FileSearchAnimeListResultsGuiEvent(this.anime)
is FileSearchWatchListResultsEvent -> FileSearchWatchListResultsGuiEvent(this.anime)
is FileSearchIgnoreListResultsEvent -> FileSearchIgnoreListResultsGuiEvent(this.anime)
is AnimeSearchEntryFoundEvent -> AnimeSearchEntryFoundGuiEvent(this.anime)
is AnimeSearchFinishedEvent -> AnimeSearchFinishedGuiEvent
is AnimeEntryFoundEvent -> AnimeEntryFoundGuiEvent(this.anime)
is AnimeEntryFinishedEvent -> AnimeEntryFinishedGuiEvent
is NumberOfEntriesPerMetaDataProviderEvent -> NumberOfEntriesPerMetaDataProviderGuiEvent(this.entries)
is InconsistenciesProgressEvent -> InconsistenciesProgressGuiEvent(this.finishedTasks, this.numberOfTasks)
is InconsistenciesCheckFinishedEvent -> InconsistenciesCheckFinishedGuiEvent
is MetaDataInconsistenciesResultEvent -> MetaDataInconsistenciesResultGuiEvent(this.numberOfAffectedEntries)
is DeadEntriesInconsistenciesResultEvent -> DeadEntriesInconsistenciesResultGuiEvent(this.numberOfAffectedEntries)
is AnimeListMetaDataInconsistenciesResultEvent -> AnimeListMetaDataInconsistenciesResultGuiEvent(this.diff)
is AnimeListDeadEntriesInconsistenciesResultEvent -> AnimeListDeadEntriesInconsistenciesResultGuiEvent(this.entries)
is AnimeListEpisodesInconsistenciesResultEvent -> AnimeListEpisodesInconsistenciesResultGuiEvent(this.entries)
is SimilarAnimeSearchFinishedEvent -> SimilarAnimeSearchFinishedGuiEvent
is SimilarAnimeFoundEvent -> SimilarAnimeFoundGuiEvent(this.entries)
is NewVersionAvailableEvent -> NewVersionAvailableGuiEvent(this.version)
is MetaDataMigrationProgressEvent -> MetaDataProviderMigrationGuiEvent(this.finishedTasks, this.numberOfTasks)
is MetaDataMigrationResultEvent -> MetaDataMigrationResultGuiEvent(
animeListEntriesWithoutMapping = animeListEntriesWithoutMapping,
animeListEntiresMultipleMappings = animeListEntiresMultipleMappings,
animeListMappings = animeListMappings,
watchListEntriesWithoutMapping = watchListEntriesWithoutMapping,
watchListEntiresMultipleMappings = watchListEntiresMultipleMappings,
watchListMappings = watchListMappings,
ignoreListEntriesWithoutMapping = ignoreListEntriesWithoutMapping,
ignoreListEntiresMultipleMappings = ignoreListEntiresMultipleMappings,
ignoreListMappings = ignoreListMappings,
)
else -> throw IllegalStateException("Unmapped event: [${this::class.simpleName}]")
}
)
}
}
private fun mapListChangeEvent(listChangedEvent: ListChangedEvent<*>): GuiEvent {
return when(listChangedEvent.list) {
ANIME_LIST -> createAnimeListEvent(listChangedEvent)
WATCH_LIST -> createWatchListEvent(listChangedEvent)
IGNORE_LIST -> createIgnoreListEvent(listChangedEvent)
}
}
private fun mapRelatedAnimeFoundEvent(event: RelatedAnimeFoundEvent): GuiEvent {
return when(event.listType) {
ANIME_LIST -> AnimeListRelatedAnimeFoundGuiEvent(event.anime)
WATCH_LIST -> throw IllegalStateException("Unsupported list type")
IGNORE_LIST -> IgnoreListRelatedAnimeFoundGuiEvent(event.anime)
}
}
private fun mapRelatedAnimeStatusEvent(event: RelatedAnimeStatusEvent): GuiEvent {
return when(event.listType) {
ANIME_LIST -> AnimeListRelatedAnimeStatusGuiEvent(event.finishedChecking, event.toBeChecked)
WATCH_LIST -> throw IllegalStateException("Unsupported list type")
IGNORE_LIST -> IgnoreListRelatedAnimeStatusGuiEvent(event.finishedChecking, event.toBeChecked)
}
}
private fun mapRelatedAnimeFinsihedEvent(event: RelatedAnimeFinishedEvent): GuiEvent {
return when(event.listType) {
ANIME_LIST -> AnimeListRelatedAnimeFinishedGuiEvent
WATCH_LIST -> throw IllegalStateException("Unsupported list type")
IGNORE_LIST -> IgnoreListRelatedAnimeFinishedGuiEvent
}
}
private fun createAnimeListEvent(listChangedEvent: ListChangedEvent<*>): GuiEvent {
return when(listChangedEvent.type) {
ADDED -> AddAnimeListEntryGuiEvent(listChangedEvent.obj.castToSet())
REMOVED -> RemoveAnimeListEntryGuiEvent(listChangedEvent.obj.castToSet())
}
}
private fun createWatchListEvent(listChangedEvent: ListChangedEvent<*>): GuiEvent {
return when(listChangedEvent.type) {
ADDED -> AddWatchListEntryGuiEvent(listChangedEvent.obj.castToSet())
REMOVED -> RemoveWatchListEntryGuiEvent(listChangedEvent.obj.castToSet())
}
}
private fun createIgnoreListEvent(listChangedEvent: ListChangedEvent<*>): GuiEvent {
return when(listChangedEvent.type) {
ADDED -> AddIgnoreListEntryGuiEvent(listChangedEvent.obj.castToSet())
REMOVED -> RemoveIgnoreListEntryGuiEvent(listChangedEvent.obj.castToSet())
}
}
} | agpl-3.0 | c0f77f3f8fec38957067971699c1fa09 | 66.973684 | 136 | 0.757526 | 5.29252 | false | false | false | false |
cketti/k-9 | app/core/src/main/java/com/fsck/k9/notification/NewMailNotificationController.kt | 2 | 3278 | package com.fsck.k9.notification
import androidx.core.app.NotificationManagerCompat
import com.fsck.k9.Account
import com.fsck.k9.controller.MessageReference
import com.fsck.k9.mailstore.LocalMessage
/**
* Handle notifications for new messages.
*/
internal class NewMailNotificationController(
private val notificationManager: NotificationManagerCompat,
private val newMailNotificationManager: NewMailNotificationManager,
private val summaryNotificationCreator: SummaryNotificationCreator,
private val singleMessageNotificationCreator: SingleMessageNotificationCreator
) {
fun restoreNewMailNotifications(accounts: List<Account>) {
for (account in accounts) {
val notificationData = newMailNotificationManager.restoreNewMailNotifications(account)
if (notificationData != null) {
processNewMailNotificationData(notificationData)
}
}
}
fun addNewMailNotification(account: Account, message: LocalMessage, silent: Boolean) {
val notificationData = newMailNotificationManager.addNewMailNotification(account, message, silent)
if (notificationData != null) {
processNewMailNotificationData(notificationData)
}
}
fun removeNewMailNotifications(
account: Account,
clearNewMessageState: Boolean,
selector: (List<MessageReference>) -> List<MessageReference>
) {
val notificationData = newMailNotificationManager.removeNewMailNotifications(
account,
clearNewMessageState,
selector
)
if (notificationData != null) {
processNewMailNotificationData(notificationData)
}
}
fun clearNewMailNotifications(account: Account, clearNewMessageState: Boolean) {
val cancelNotificationIds = newMailNotificationManager.clearNewMailNotifications(account, clearNewMessageState)
cancelNotifications(cancelNotificationIds)
}
private fun processNewMailNotificationData(notificationData: NewMailNotificationData) {
cancelNotifications(notificationData.cancelNotificationIds)
for (singleNotificationData in notificationData.singleNotificationData) {
createSingleNotification(notificationData.baseNotificationData, singleNotificationData)
}
notificationData.summaryNotificationData?.let { summaryNotificationData ->
createSummaryNotification(notificationData.baseNotificationData, summaryNotificationData)
}
}
private fun cancelNotifications(notificationIds: List<Int>) {
for (notificationId in notificationIds) {
notificationManager.cancel(notificationId)
}
}
private fun createSingleNotification(
baseNotificationData: BaseNotificationData,
singleNotificationData: SingleNotificationData
) {
singleMessageNotificationCreator.createSingleNotification(baseNotificationData, singleNotificationData)
}
private fun createSummaryNotification(
baseNotificationData: BaseNotificationData,
summaryNotificationData: SummaryNotificationData
) {
summaryNotificationCreator.createSummaryNotification(baseNotificationData, summaryNotificationData)
}
}
| apache-2.0 | 984178f8656efd8dfdcd7274295994a9 | 36.25 | 119 | 0.741611 | 6.184906 | false | false | false | false |
Llullas/Activity-Analizer | app/src/main/java/com/dedudevgmail/activityanalyzer/model/ModelModule.kt | 1 | 1930 | package com.dedudevgmail.activityanalyzer.model
import android.content.Context
import android.hardware.SensorManager
import com.dedudevgmail.activityanalyzer.model.auth.AuthSource
import com.dedudevgmail.activityanalyzer.model.auth.FirebaseAuthService
import com.dedudevgmail.activityanalyzer.model.dataaqu.SensorService
import com.dedudevgmail.activityanalyzer.model.dataaqu.SensorSource
import com.dedudevgmail.activityanalyzer.model.database.DatabaseSource
import com.dedudevgmail.activityanalyzer.model.database.FirebaseDatabaseService
import com.dedudevgmail.activityanalyzer.model.file.FileService
import com.dedudevgmail.activityanalyzer.model.file.FileSource
import com.dedudevgmail.activityanalyzer.model.scheduler.SchedulerProvider
import com.dedudevgmail.activityanalyzer.model.storage.FirebaseStorageService
import com.dedudevgmail.activityanalyzer.model.storage.StorageSource
import dagger.Module
import dagger.Provides
import io.reactivex.disposables.CompositeDisposable
import javax.inject.Singleton
/**
* com.dedudevgmail.activityanalyzer.modules
* Created by Llullas on 07.06.2017.
*/
@Module
class ModelModule {
@Singleton
@Provides
fun provideFileSource(context: Context): FileSource = FileService.getInstance(context)
@Singleton
@Provides
fun provideScheduler(): SchedulerProvider = SchedulerProvider.getInstance()
@Singleton
@Provides
fun provideAuthSource(): AuthSource = FirebaseAuthService.getInstance()
@Singleton
@Provides
fun provideDatabaseSource(): DatabaseSource = FirebaseDatabaseService.getInstance()
@Singleton
@Provides
fun provideStorageSource(): StorageSource = FirebaseStorageService.getInstance()
@Singleton
@Provides
fun providesSensorSource(sensorManager: SensorManager, context: Context): SensorSource = SensorService.getInstance(sensorManager, context)
@Singleton
@Provides
fun providesCompositeDisposable(): CompositeDisposable = CompositeDisposable()
} | apache-2.0 | cd48cff55b084f718906f73cdc861d65 | 33.482143 | 139 | 0.849741 | 4.177489 | false | false | false | false |
LorittaBot/Loritta | discord/loritta-bot-common/src/main/kotlin/net/perfectdreams/loritta/cinnamon/discord/interactions/BarebonesInteractionContext.kt | 1 | 11557 | package net.perfectdreams.loritta.cinnamon.discord.interactions
import dev.kord.rest.builder.interaction.ModalBuilder
import dev.kord.rest.builder.message.EmbedBuilder
import net.perfectdreams.discordinteraktions.common.BarebonesInteractionContext
import net.perfectdreams.discordinteraktions.common.builder.message.allowedMentions
import net.perfectdreams.discordinteraktions.common.builder.message.create.InteractionOrFollowupMessageCreateBuilder
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.CommandException
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.EphemeralCommandException
import net.perfectdreams.loritta.cinnamon.discord.interactions.commands.styled
import net.perfectdreams.loritta.cinnamon.discord.interactions.modals.CinnamonModalExecutorDeclaration
import net.perfectdreams.loritta.common.emotes.Emote
import net.perfectdreams.loritta.cinnamon.emotes.Emotes
import net.perfectdreams.loritta.cinnamon.entities.LorittaReply
open class BarebonesInteractionContext(
open val interaKTionsContext: BarebonesInteractionContext
) {
/**
* Defers the application command request message with a public message
*/
suspend fun deferChannelMessage() = interaKTionsContext.deferChannelMessage()
/**
* Defers the application command request message with a ephemeral message
*/
suspend fun deferChannelMessageEphemerally() = interaKTionsContext.deferChannelMessageEphemerally()
suspend fun sendMessage(message: String, embed: EmbedBuilder? = null) {
interaKTionsContext.sendMessage {
// Disable ALL mentions, to avoid a "@everyone 3.0" moment
allowedMentions {
repliedUser = true
}
content = message
if (embed != null)
embeds = (embeds ?: mutableListOf()).apply { this.add(embed) }
}
}
suspend inline fun sendMessage(block: InteractionOrFollowupMessageCreateBuilder.() -> (Unit)) = interaKTionsContext.sendMessage {
// Disable ALL mentions, to avoid a "@everyone 3.0" moment
allowedMentions {
repliedUser = true
}
block()
}
suspend inline fun sendEphemeralMessage(block: InteractionOrFollowupMessageCreateBuilder.() -> (Unit)) = interaKTionsContext.sendEphemeralMessage {
// Disable ALL mentions, to avoid a "@everyone 3.0" moment
allowedMentions {
repliedUser = true
}
apply(block)
}
suspend inline fun sendMessage(builder: InteractionOrFollowupMessageCreateBuilder) = interaKTionsContext.sendPublicMessage(builder)
suspend inline fun sendEphemeralMessage(builder: InteractionOrFollowupMessageCreateBuilder) = interaKTionsContext.sendEphemeralMessage(builder)
suspend fun sendEmbed(message: String = "", embed: EmbedBuilder.() -> Unit) {
sendMessage(message, EmbedBuilder().apply(embed))
}
/**
* Sends a Loritta-styled formatted message
*
* By default, Loritta-styled formatting looks like this: `[prefix] **|** [content]`, however implementations can change the look and feel of the message.
*
* Prefixes should *not* be used for important behavior of the command!
*
* @param content the content of the message
* @param prefix the prefix of the message
*/
suspend fun sendReply(content: String, prefix: Emote, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}) = sendMessage {
styled(content, prefix)
apply(block)
}
/**
* Sends a Loritta-styled formatted message
*
* By default, Loritta-styled formatting looks like this: `[prefix] **|** [content]`, however implementations can change the look and feel of the message.
*
* Prefixes should *not* be used for important behavior of the command!
*
* @param content the content of the message
* @param prefix the prefix of the message
*/
suspend fun sendReply(content: String, prefix: String = Emotes.DefaultStyledPrefix.asMention, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}) = sendMessage {
styled(content, prefix)
apply(block)
}
/**
* Sends a Loritta-styled formatted message to this builder
*
* By default, Loritta-styled formatting looks like this: `[prefix] **|** [content]`, however implementations can change the look and feel of the message.
*
* Prefixes should *not* be used for important behavior of the command!
*
* @param reply the already built LorittaReply
*/
suspend fun sendReply(reply: LorittaReply, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}) = sendMessage {
styled(reply)
apply(block)
}
/**
* Sends a Loritta-styled formatted ephemeral message
*
* By default, Loritta-styled formatting looks like this: `[prefix] **|** [content]`, however implementations can change the look and feel of the message.
*
* Prefixes should *not* be used for important behavior of the command!
*
* @param content the content of the message
* @param prefix the prefix of the message
*/
suspend fun sendEphemeralReply(content: String, prefix: Emote, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}) = sendEphemeralMessage {
styled(content, prefix)
apply(block)
}
/**
* Sends a Loritta-styled formatted message
*
* By default, Loritta-styled formatting looks like this: `[prefix] **|** [content]`, however implementations can change the look and feel of the message.
*
* Prefixes should *not* be used for important behavior of the command!
*
* @param content the content of the message
* @param prefix the prefix of the message
*/
suspend fun sendEphemeralReply(content: String, prefix: String = Emotes.DefaultStyledPrefix.asMention, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}) = sendEphemeralMessage {
styled(content, prefix)
apply(block)
}
/**
* Sends a Loritta-styled formatted message to this builder
*
* By default, Loritta-styled formatting looks like this: `[prefix] **|** [content]`, however implementations can change the look and feel of the message.
*
* Prefixes should *not* be used for important behavior of the command!
*
* @param reply the already built LorittaReply
*/
suspend fun sendEphemeralReply(reply: LorittaReply, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}) = sendEphemeralMessage {
styled(reply)
apply(block)
}
/**
* Throws a [CommandException] with a specific [content] and [prefix], halting command execution
*
* @param reply the message that will be sent
* @param prefix the reply prefix
* @param block the message block, used for customization of the message
* @see fail
* @see CommandException
*/
inline fun fail(content: String, prefix: Emote, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}): Nothing = fail(
LorittaReply(
content, prefix.asMention
),
block
)
/**
* Throws a [CommandException] with a specific [content] and [prefix], halting command execution
*
* @param reply the message that will be sent
* @param block the message block, used for customization of the message
* @see fail
* @see CommandException
*/
inline fun fail(content: String, prefix: String = Emotes.DefaultStyledPrefix.asMention, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}): Nothing = fail(
LorittaReply(
content, prefix
),
block
)
/**
* Throws a [CommandException] with a specific [reply], halting command execution
*
* @param reply the message that will be sent
* @param block the message block, used for customization of the message
* @see fail
* @see CommandException
*/
inline fun fail(reply: LorittaReply, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}): Nothing = fail {
styled(reply)
apply(block)
}
/**
* Throws a [CommandException] with a specific message [block], halting command execution
*
* @param reply the message that will be sent
* @see fail
* @see CommandException
*/
inline fun fail(block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}): Nothing = throw CommandException(
InteractionOrFollowupMessageCreateBuilder(false).apply {
// Disable ALL mentions, to avoid a "@everyone 3.0" moment
allowedMentions {
repliedUser = true
}
apply(block)
}
)
/**
* Throws a [CommandException] with a specific [content] and [prefix], ephemerally, halting command execution
*
* @param reply the message that will be sent
* @param prefix the reply prefix
* @param block the message block, used for customization of the message
* @see fail
* @see CommandException
*/
inline fun failEphemerally(content: String, prefix: Emote, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}): Nothing = failEphemerally(
LorittaReply(
content, prefix.asMention
),
block
)
/**
* Throws a [CommandException] with a specific [content] and [prefix], ephemerally, halting command execution
*
* @param reply the message that will be sent
* @param block the message block, used for customization of the message
* @see fail
* @see CommandException
*/
inline fun failEphemerally(content: String, prefix: String = Emotes.DefaultStyledPrefix.asMention, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}): Nothing = failEphemerally(
LorittaReply(
content, prefix
),
block
)
/**
* Throws a [CommandException] with a specific [reply], ephemerally, halting command execution
*
* @param reply the message that will be sent
* @param block the message block, used for customization of the message
* @see fail
* @see CommandException
*/
inline fun failEphemerally(reply: LorittaReply, block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}): Nothing = failEphemerally {
styled(reply)
apply(block)
}
/**
* Throws a [CommandException] with a specific message [block], ephemerally, halting command execution
*
* @param reply the message that will be sent
* @see fail
* @see CommandException
*/
inline fun failEphemerally(block: InteractionOrFollowupMessageCreateBuilder.() -> Unit = {}): Nothing = throw EphemeralCommandException(
InteractionOrFollowupMessageCreateBuilder(true).apply {
// Disable ALL mentions, to avoid a "@everyone 3.0" moment
allowedMentions {
repliedUser = true
}
apply(block)
}
)
suspend fun sendModal(declaration: CinnamonModalExecutorDeclaration, title: String, builder: ModalBuilder.() -> (Unit)) = interaKTionsContext.sendModal(declaration.id, title, builder)
suspend fun sendModal(declaration: CinnamonModalExecutorDeclaration, data: String, title: String, builder: ModalBuilder.() -> (Unit)) = interaKTionsContext.sendModal(declaration.id, data, title, builder)
} | agpl-3.0 | aee3cc331a2d642d9b6b99e35c593f28 | 39.271777 | 207 | 0.68028 | 5.029156 | false | false | false | false |
mfklauberg/projetosacademicosfurb | compiladores/core/src/test/kotlin/ui/controller/impl/FileController.kt | 2 | 2277 | package ui.controller.impl
import ui.controller.IFileController
import java.io.BufferedWriter
import java.io.FileNotFoundException
import java.io.FileWriter
import java.nio.charset.Charset
import java.nio.file.Files
import java.nio.file.Path
import java.nio.file.Paths
/**
* FURB - Bacharelado em Ciências da Computação
* Compiladores - Interface
*
* Fábio Luiz Fischer & Matheus Felipe Klauberg
**/
class FileController : IFileController {
override fun new(path: String, extension: String, fileContent: String, override: Boolean) {
val filePath: Path = getPath(path, extension)
if (override.not())
if (Files.exists(filePath))
throw IllegalArgumentException("Arquivo ${filePath.fileName} ja existe. Sobrescrever?")
BufferedWriter(FileWriter(filePath.toFile())).use {
writer ->
writer.write(fileContent)
}
}
override fun save(path: String, extension: String, fileContent: String) {
val filePath: Path = getPath(path, extension)
if (!Files.exists(filePath))
Files.createFile(filePath)
BufferedWriter(FileWriter(filePath.toFile())).use {
writer ->
writer.write(fileContent)
}
}
override fun saveAs(path: String, extension: String, fileContent: String, override: Boolean) {
val filePath: Path = getPath(path, extension)
if (override.not())
if (Files.exists(filePath))
throw IllegalArgumentException("Arquivo $path ja existe!")
BufferedWriter(FileWriter(filePath.toFile())).use {
writer ->
writer.write(fileContent)
}
}
override fun getPath(path: String, extension: String): Path = Paths.get(if (path.endsWith(extension)) path else "$path$extension")
override fun getContent(path: String, extension: String, charset: Charset): String {
val filePath = getPath(path, extension)
if (Files.exists(filePath).not())
throw FileNotFoundException("Arquivo ${filePath.fileName} não encontrado!")
return filePath.toFile().readText(charset = charset)
}
override fun getFileName(path: String): String = Paths.get(path).toString().replace(".txt", "")
} | mit | 0954cc1d09eb00f18a991ebbabb3135f | 31.471429 | 134 | 0.658451 | 4.30303 | false | false | false | false |
VladRassokhin/intellij-hcl | src/kotlin/org/intellij/plugins/hcl/terraform/config/generate/AbstractGenerate.kt | 1 | 5160 | /*
* Copyright 2000-2017 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.intellij.plugins.hcl.terraform.config.generate
import com.intellij.codeInsight.CodeInsightUtilBase
import com.intellij.codeInsight.actions.SimpleCodeInsightAction
import com.intellij.codeInsight.lookup.LookupElement
import com.intellij.codeInsight.lookup.LookupElementBuilder
import com.intellij.codeInsight.template.*
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiDocumentManager
import com.intellij.psi.PsiFile
import com.intellij.psi.PsiWhiteSpace
import com.intellij.psi.util.PsiTreeUtil
import org.intellij.plugins.hcl.psi.HCLBlock
import org.intellij.plugins.hcl.terraform.config.codeinsight.InsertHandlersUtil.addHCLBlockRequiredProperties
import org.intellij.plugins.hcl.terraform.config.codeinsight.TerraformConfigCompletionContributor
import org.intellij.plugins.hcl.terraform.config.patterns.TerraformPatterns
import java.util.*
abstract class AbstractGenerate : SimpleCodeInsightAction() {
override fun invoke(project: Project, editor: Editor, file: PsiFile) {
if (!CodeInsightUtilBase.prepareEditorForWrite(editor)) return
setCaretToNearbyRoot(editor, file)
val offset = editor.caretModel.currentCaret.offset
val marker = editor.document.createRangeMarker(offset, offset)
marker.isGreedyToLeft = true
marker.isGreedyToRight = true
TemplateManager.getInstance(project).startTemplate(editor, template, false, null, object : TemplateEditingAdapter() {
override fun templateFinished(template: Template?, brokenOff: Boolean) {
if (!brokenOff) {
val element = file.findElementAt(marker.startOffset)
val block = PsiTreeUtil.getParentOfType(element, HCLBlock::class.java, false)
if (block != null) {
if (TextRange(marker.startOffset, marker.endOffset).contains(block.textOffset)) {
// It's our new block
// Invoke add properties quick fix
addHCLBlockRequiredProperties(file, project, block)
}
}
}
}
})
}
private fun setCaretToNearbyRoot(editor: Editor, file: PsiFile) {
val offset = editor.caretModel.currentCaret.offset
val node = file.node.findLeafElementAt(offset) ?: return
var element = node.psi
while (element != null) {
val parent = element.parent
if (parent is PsiFile) break
element = parent
}
if (element != null && element !is PsiWhiteSpace) {
val line = editor.document.getLineNumber(offset)
val start = editor.document.getLineNumber(element.node.startOffset)
val end = editor.document.getLineNumber(element.node.startOffset + element.node.textLength)
if (line - start < end - line) {
// Place before element
editor.caretModel.currentCaret.moveToOffset(editor.document.getLineStartOffset(start))
} else {
// Place after element
if (editor.document.lineCount == end + 1) {
editor.document.insertString(element.node.startOffset + element.node.textLength, "\n")
}
editor.caretModel.currentCaret.moveToOffset(editor.document.getLineEndOffset(end + 1))
}
}
}
abstract val template: Template
override fun isValidForFile(project: Project, editor: Editor, file: PsiFile): Boolean {
return TerraformPatterns.TerraformConfigFile.accepts(file)
}
companion object {
val InvokeCompletionExpression: Expression = object : Expression() {
override fun calculateQuickResult(context: ExpressionContext?): Result? {
return null //calculateResult(context)
}
override fun calculateResult(context: ExpressionContext?): Result? {
val lookupItems = calculateLookupItems(context)
if (lookupItems == null || lookupItems.isEmpty()) return TextResult("")
return TextResult(lookupItems[0].lookupString)
}
override fun calculateLookupItems(context: ExpressionContext?): Array<out LookupElement>? {
if (context == null) return null
val editor = context.editor ?: return null
val file = PsiDocumentManager.getInstance(context.project).getPsiFile(editor.document) ?: return null
val element = file.findElementAt(context.startOffset) ?: return null
val consumer = ArrayList<LookupElementBuilder>()
TerraformConfigCompletionContributor.BlockTypeOrNameCompletionProvider.doCompletion(element, consumer)
consumer.sortBy { it.lookupString }
return consumer.toTypedArray()
}
}
}
}
| apache-2.0 | 281affd443b0b69e2be51e99f4678a63 | 42.361345 | 121 | 0.729845 | 4.690909 | false | true | false | false |
DevCharly/kotlin-ant-dsl | src/main/kotlin/com/devcharly/kotlin/ant/taskdefs/javadoc-extensioninfo.kt | 1 | 1979 | /*
* Copyright 2016 Karl Tauber
*
* 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.devcharly.kotlin.ant
import org.apache.tools.ant.taskdefs.Javadoc.ExtensionInfo
import org.apache.tools.ant.types.Path
import org.apache.tools.ant.types.Reference
/******************************************************************************
DO NOT EDIT - this file was generated
******************************************************************************/
interface IExtensionInfoNested : INestedComponent {
fun extensioninfo(
name: String? = null,
path: String? = null,
pathref: String? = null,
nested: (KExtensionInfo.() -> Unit)? = null)
{
_addExtensionInfo(ExtensionInfo().apply {
component.project.setProjectReference(this);
_init(name, path, pathref, nested)
})
}
fun _addExtensionInfo(value: ExtensionInfo)
}
fun ExtensionInfo._init(
name: String?,
path: String?,
pathref: String?,
nested: (KExtensionInfo.() -> Unit)?)
{
if (name != null)
setName(name)
if (path != null)
setPath(Path(project, path))
if (pathref != null)
setPathRef(Reference(project, pathref))
if (nested != null)
nested(KExtensionInfo(this))
}
class KExtensionInfo(val component: ExtensionInfo) {
fun path(location: String? = null, path: String? = null, cache: Boolean? = null, nested: (KPath.() -> Unit)? = null) {
component.createPath().apply {
component.project.setProjectReference(this)
_init(location, path, cache, nested)
}
}
}
| apache-2.0 | c36a87f9313ea77adfedfb57df318c83 | 28.984848 | 119 | 0.659424 | 3.712946 | false | false | false | false |
world-federation-of-advertisers/common-jvm | src/main/kotlin/org/wfanet/measurement/common/graphviz/Dot.kt | 1 | 4787 | // Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package org.wfanet.measurement.common.graphviz
/** Builds a DOT-language digraph. */
fun digraph(name: String? = null, init: Graph.() -> Unit): String {
val graph = PrintableGraph("digraph${name.withSpaceBefore()}").apply(init)
return Printer().also(graph::render).toString()
}
@DslMarker annotation class GraphvizDsl
@GraphvizDsl interface Element
interface Attributes : Element {
fun set(pair: Pair<String, String>)
}
interface Scope : Element {
fun node(name: String, initAttributes: Attributes.() -> Unit = {})
fun edge(pair: Pair<String, String>, initAttributes: Attributes.() -> Unit = {})
fun scope(name: String? = null, init: Scope.() -> Unit)
fun attributes(init: Attributes.() -> Unit)
}
interface Graph : Scope {
fun subgraph(name: String? = null, init: Graph.() -> Unit)
}
@GraphvizDsl
private interface Printable {
fun render(printer: Printer)
}
private class Printer {
private var indent: Int = 0
private val buffer = StringBuffer()
fun outputLine(string: String) {
outputIndent()
buffer.appendLine(string)
}
fun output(string: String) {
buffer.append(string)
}
fun outputIndent() {
repeat(indent) { buffer.append(" ") }
}
fun endLine() {
output("\n")
}
fun withIndent(block: () -> Unit) {
indent++
block()
indent--
}
override fun toString(): String {
return buffer.toString()
}
}
private abstract class GenericAttributes : Attributes, Printable {
protected val attributes = mutableMapOf<String, String>()
final override fun set(pair: Pair<String, String>) {
attributes[pair.first] = pair.second
}
}
private class CommaSeparatedAttributes : GenericAttributes() {
override fun render(printer: Printer) {
if (attributes.isEmpty()) return
val string =
attributes.toList().joinToString(", ", prefix = " [", postfix = "]") { (k, v) -> "$k=\"$v\"" }
printer.output(string)
}
}
private class NewlineAttributes : GenericAttributes() {
override fun render(printer: Printer) {
for ((key, value) in attributes) {
printer.outputLine("$key=\"$value\"")
}
}
}
private open class PrintableScope(private val name: String?) : Scope, Printable {
private val children = mutableListOf<Printable>()
private val attributes = NewlineAttributes()
override fun render(printer: Printer) {
with(printer) {
outputLine("${name.withSpaceAfter()}{")
withIndent {
attributes.render(this)
for (child in children) child.render(this)
}
outputLine("}")
}
}
protected fun addChild(child: Printable) {
children.add(child)
}
override fun node(name: String, initAttributes: Attributes.() -> Unit) {
addChild(Node(name, CommaSeparatedAttributes().apply(initAttributes)))
}
override fun edge(pair: Pair<String, String>, initAttributes: Attributes.() -> Unit) {
addChild(Edge(pair.first, pair.second, CommaSeparatedAttributes().apply(initAttributes)))
}
override fun scope(name: String?, init: Scope.() -> Unit) {
addChild(PrintableScope(name).apply(init))
}
override fun attributes(init: Attributes.() -> Unit) {
attributes.apply(init)
}
}
@GraphvizDsl
private class PrintableGraph(name: String) : Graph, PrintableScope(name) {
override fun subgraph(name: String?, init: Graph.() -> Unit) {
addChild(PrintableGraph("subgraph${name.withSpaceBefore()}").apply(init))
}
}
@GraphvizDsl
private abstract class EdgeOrNode(private val attributes: CommaSeparatedAttributes) : Printable {
abstract val body: String
override fun render(printer: Printer) {
printer.outputIndent()
printer.output(body)
attributes.render(printer)
printer.endLine()
}
}
@GraphvizDsl
private class Edge(from: String, to: String, attributes: CommaSeparatedAttributes) :
EdgeOrNode(attributes) {
override val body: String = "$from -> $to"
}
@GraphvizDsl
private class Node(override val body: String, attributes: CommaSeparatedAttributes) :
EdgeOrNode(attributes)
private fun String?.withSpaceBefore(): String {
return this?.let { " $this" } ?: ""
}
private fun String?.withSpaceAfter(): String {
return this?.let { "$this " } ?: ""
}
| apache-2.0 | faeadcc4429a3f0ce129125a27067c53 | 26.354286 | 100 | 0.689367 | 3.94967 | false | false | false | false |
anton-okolelov/intellij-rust | src/main/kotlin/org/rust/ide/inspections/fixes/import/AutoImportHintFix.kt | 1 | 1924 | /*
* Use of this source code is governed by the MIT license that can be
* found in the LICENSE file.
*/
package org.rust.ide.inspections.fixes.import
import com.intellij.codeInsight.daemon.impl.ShowAutoImportPass
import com.intellij.codeInsight.hint.HintManager
import com.intellij.codeInsight.intention.HighPriorityAction
import com.intellij.codeInspection.HintAction
import com.intellij.codeInspection.LocalQuickFixOnPsiElement
import com.intellij.openapi.editor.Editor
import com.intellij.openapi.project.Project
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import org.rust.lang.core.psi.RsPath
class AutoImportHintFix(
path: RsPath,
private val hint: String,
private val multiple: Boolean
) : LocalQuickFixOnPsiElement(path), HintAction, HighPriorityAction {
private val delegate: AutoImportFix = AutoImportFix(path)
override fun getFamilyName(): String = delegate.familyName
override fun getText(): String = delegate.name
override fun startInWriteAction(): Boolean = delegate.startInWriteAction()
override fun isAvailable(project: Project, editor: Editor?, file: PsiFile?): Boolean = delegate.isAvailable
override fun showHint(editor: Editor): Boolean {
if (HintManager.getInstance().hasShownHintsThatWillHideByOtherHint(true)) return false
val message = ShowAutoImportPass.getMessage(multiple, hint)
val element = startElement
HintManager.getInstance().showQuestionHint(
editor, message, element.textOffset, element.textRange.endOffset) {
delegate.invoke(element.project)
true
}
return true
}
override fun invoke(project: Project, file: PsiFile, startElement: PsiElement, endElement: PsiElement) {
delegate.invoke(project)
}
override fun invoke(project: Project, editor: Editor?, file: PsiFile?) {
delegate.invoke(project)
}
}
| mit | 129ecaa0977099b7c9331008dde2e02a | 35.301887 | 111 | 0.747401 | 4.704156 | false | false | false | false |
Shashi-Bhushan/General | cp-trials/src/main/kotlin/in/shabhushan/cp_trials/logic/TwoSum.kt | 1 | 967 | package `in`.shabhushan.cp_trials.logic
object TwoSum {
fun twoSum2(
nums: IntArray,
target: Int
): IntArray {
val map = nums.mapIndexed { index, element ->
element to index
}.toMap()
val keys = map.keys
nums.forEachIndexed { index, element ->
val otherNumber = target - element
if (otherNumber in keys && map[otherNumber] != index)
return intArrayOf(index, map[otherNumber] ?: error("err-other-number-not-found"))
}
throw IllegalArgumentException("err-no-two-sum-solution")
}
fun twoSum(
nums: IntArray,
target: Int
): IntArray {
val map = mutableMapOf<Int, Int>()
nums.forEachIndexed { index, element ->
val otherNumber = target - element
if (otherNumber in map.keys)
return intArrayOf(map[otherNumber] ?: error("err-other-number-not-found"), index)
map[element] = index
}
throw IllegalArgumentException("err-no-two-sum-solution")
}
}
| gpl-2.0 | 94fe30fa8bc30847e1b0104e2b9fdccf | 22.585366 | 89 | 0.640124 | 3.946939 | false | false | false | false |
Kotlin/dokka | core/testdata/format/website-html/sampleWithAsserts.kt | 1 | 688 | import java.io.FileNotFoundException
import java.io.File
/**
* @sample sample
*/
fun a(): String {
return "Hello, Work"
}
fun b(): String {
return "Hello, Rest"
}
/**
* @throws FileNotFoundException every time
*/
fun readSomeFile(f: File) {
throw FileNotFoundException("BOOM")
}
fun sample() {
assertPrints(a(), "Hello, Work")
assertTrue(a() == b())
assertTrue(a() == b(), "A eq B")
assertFails("reading file now") { readSomeFile(File("some.txt")) }
assertFailsWith<FileNotFoundException> { readSomeFile(File("some.txt")) }
assertFails { readSomeFile(File("some.txt")) }
fun indented() {
assertFalse(a() != b(), "A neq B")
}
} | apache-2.0 | fd34d174d013da8b576c119d86ded0c3 | 19.264706 | 77 | 0.619186 | 3.492386 | false | false | false | false |
OurFriendIrony/MediaNotifier | app/src/main/kotlin/uk/co/ourfriendirony/medianotifier/general/MultiDateDeserializer.kt | 1 | 1390 | package uk.co.ourfriendirony.medianotifier.general
import android.util.Log
import com.fasterxml.jackson.core.JsonParser
import com.fasterxml.jackson.databind.DeserializationContext
import com.fasterxml.jackson.databind.JsonNode
import com.fasterxml.jackson.databind.deser.std.StdDeserializer
import java.io.IOException
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.*
class MultiDateDeserializer @JvmOverloads constructor(vc: Class<*>? = null) :
StdDeserializer<Date?>(vc) {
@Throws(IOException::class)
override fun deserialize(jp: JsonParser, ctxt: DeserializationContext): Date? {
val node = jp.codec.readTree<JsonNode>(jp)
val date = node.textValue()
for (DATE_FORMAT in DATE_FORMATS) {
try {
return SimpleDateFormat(DATE_FORMAT, Locale.UK).parse(date)
} catch (e: ParseException) {
// Ignore and check the next deserialise pattern
}
}
val errorMessage =
"Unparseable date: \"" + date + "\". Supported formats: " + DATE_FORMATS.contentToString()
Log.w("[DATE PARSE]", errorMessage)
return null
}
companion object {
private const val serialVersionUID = 1L
private val DATE_FORMATS = arrayOf(
"yyyy-MM-dd",
"yyyy-MM",
"yyyy"
)
}
} | apache-2.0 | 97d1b7d1f99320bf4dfa45193e6d82e7 | 33.775 | 102 | 0.656115 | 4.498382 | false | false | false | false |
toastkidjp/Yobidashi_kt | app/src/test/java/jp/toastkid/yobidashi/search/SearchActionTest.kt | 2 | 5478 | /*
* Copyright (c) 2021 toastkidjp.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompany this distribution.
* The Eclipse Public License is available at http://www.eclipse.org/legal/epl-v10.html.
*/
package jp.toastkid.yobidashi.search
import android.content.Context
import android.net.Uri
import io.mockk.MockKAnnotations
import io.mockk.Runs
import io.mockk.every
import io.mockk.impl.annotations.MockK
import io.mockk.impl.annotations.SpyK
import io.mockk.just
import io.mockk.mockk
import io.mockk.mockkObject
import io.mockk.mockkStatic
import io.mockk.unmockkAll
import io.mockk.verify
import jp.toastkid.lib.BrowserViewModel
import jp.toastkid.lib.Urls
import jp.toastkid.lib.preference.PreferenceApplier
import jp.toastkid.search.UrlFactory
import jp.toastkid.yobidashi.search.history.SearchHistoryInsertion
import org.junit.After
import org.junit.Before
import org.junit.Test
class SearchActionTest {
private lateinit var searchAction: SearchAction
@MockK
private lateinit var activityContext: Context
private var category: String = "test"
private var query: String = "test"
private var currentUrl: String = "https://search.yahoo.co.jp"
private var onBackground: Boolean = false
private var saveHistory: Boolean = true
@MockK
private lateinit var viewModelSupplier: (Context) -> BrowserViewModel?
@MockK
private lateinit var preferenceApplierSupplier: (Context) -> PreferenceApplier
@MockK
private lateinit var urlFactory: UrlFactory
@MockK
private lateinit var browserViewModel: BrowserViewModel
@MockK
private lateinit var searchHistoryInsertion: SearchHistoryInsertion
@SpyK(recordPrivateCalls = true)
private var preferenceApplier: PreferenceApplier = mockk()
@Before
fun setUp() {
MockKAnnotations.init(this)
every { preferenceApplier getProperty "isEnableSearchHistory" }.returns(true)
every { preferenceApplierSupplier.invoke(any()) }.returns(preferenceApplier)
every { viewModelSupplier.invoke(any()) }.returns(browserViewModel)
every { urlFactory.invoke(any(), any(), any()) }.returns(mockk())
every { activityContext.getString(any(), any()) }.returns("test")
every { browserViewModel.openBackground(any(), any()) }.just(Runs)
every { browserViewModel.open(any()) }.just(Runs)
mockkObject(Urls)
every { Urls.isValidUrl(any()) }.returns(false)
mockkObject(SearchHistoryInsertion)
every { SearchHistoryInsertion.make(any(), any(), any()) }.returns(searchHistoryInsertion)
every { searchHistoryInsertion.insert() }.returns(mockk())
mockkStatic(Uri::class)
every { Uri.parse(any()) }.returns(mockk())
searchAction = SearchAction(
activityContext,
category,
query,
currentUrl,
onBackground,
saveHistory,
viewModelSupplier,
preferenceApplierSupplier,
urlFactory
)
}
@After
fun tearDown() {
unmockkAll()
}
@Test
fun testOpenSearchByNewTabOnForeground() {
searchAction.invoke()
verify(exactly = 1) { browserViewModel.open(any()) }
verify(exactly = 0) { browserViewModel.openBackground(any(), any()) }
verify(exactly = 1) { urlFactory.invoke(any(), any(), any()) }
verify(exactly = 1) { searchHistoryInsertion.insert() }
}
@Test
fun testOpenSearchOnBackground() {
searchAction = SearchAction(
activityContext,
category,
query,
currentUrl,
true,
saveHistory,
viewModelSupplier,
preferenceApplierSupplier,
urlFactory
)
searchAction.invoke()
verify(exactly = 0) { browserViewModel.open(any()) }
verify(exactly = 1) { browserViewModel.openBackground(any(), any()) }
verify(exactly = 1) { urlFactory.invoke(any(), any(), any()) }
verify(exactly = 1) { searchHistoryInsertion.insert() }
}
@Test
fun testOpenUrlOnForeground() {
searchAction = SearchAction(
activityContext,
category,
query,
currentUrl,
onBackground,
false,
viewModelSupplier,
preferenceApplierSupplier,
urlFactory
)
searchAction.invoke()
verify(exactly = 1) { browserViewModel.open(any()) }
verify(exactly = 1) { urlFactory.invoke(any(), any(), any()) }
verify(exactly = 0) { searchHistoryInsertion.insert() }
}
@Test
fun testIsNotEnableSearchHistory() {
every { preferenceApplier getProperty "isEnableSearchHistory" }.returns(false)
searchAction.invoke()
verify(exactly = 1) { browserViewModel.open(any()) }
verify(exactly = 1) { urlFactory.invoke(any(), any(), any()) }
verify(exactly = 0) { searchHistoryInsertion.insert() }
}
@Test
fun testIsValidUrl() {
every { Urls.isValidUrl(any()) }.returns(true)
searchAction.invoke()
verify(exactly = 1) { browserViewModel.open(any()) }
verify(exactly = 0) { urlFactory.invoke(any(), any(), any()) }
verify(exactly = 1) { searchHistoryInsertion.insert() }
}
} | epl-1.0 | bc75a7d764bdd9ecad1cd66effc5138e | 28.939891 | 98 | 0.650785 | 4.634518 | false | true | false | false |
ntemplon/legends-of-omterra | core/src/com/jupiter/europa/entity/component/CollisionComponent.kt | 1 | 3376 | /*
* The MIT License
*
* Copyright 2015 Nathan Templon.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*
*/
package com.jupiter.europa.entity.component
import com.badlogic.ashley.core.Component
import com.badlogic.gdx.utils.Json
import com.badlogic.gdx.utils.Json.Serializable
import com.badlogic.gdx.utils.JsonValue
import com.jupiter.europa.entity.messaging.PositionChangedMessage
import com.jupiter.europa.geometry.Size
import com.jupiter.europa.util.RectangularBoundedObject
import java.awt.Point
import java.awt.Rectangle
/**
* @author Nathan Templon
*/
public class CollisionComponent : Component, RectangularBoundedObject, Serializable {
// Fields
private var bounds: Rectangle = Rectangle()
// Properties
override fun getBounds(): Rectangle {
return this.bounds
}
public fun setLocation(location: Point) {
this.bounds = Rectangle(location.x, location.y, this.bounds.width, this.bounds.height)
}
public fun setSize(size: Size) {
this.bounds = Rectangle(this.bounds.x, this.bounds.y, size.width, size.height)
}
// Initialization
public constructor() {
this.bounds = Rectangle()
}
public constructor(size: Size) {
this.bounds = Rectangle(0, 0, size.width, size.height)
}
public constructor(location: Point, size: Size) {
this.bounds = Rectangle(location.x, location.y, size.width, size.height)
}
// Serializable (Json) Implementation
override fun write(json: Json) {
json.writeValue(X_KEY, this.getBounds().x)
json.writeValue(Y_KEY, this.getBounds().y)
json.writeValue(WIDTH_KEY, this.getBounds().width)
json.writeValue(HEIGHT_KEY, this.getBounds().height)
}
override fun read(json: Json, jsonData: JsonValue) {
this.bounds = Rectangle(jsonData.getInt(X_KEY), jsonData.getInt(Y_KEY), jsonData.getInt(WIDTH_KEY), jsonData.getInt(HEIGHT_KEY))
}
// Private Methods
private fun handlePositionChanged(message: PositionChangedMessage) {
this.setLocation(message.oldLocation)
}
companion object {
// Constants
public val X_KEY: String = "bounds-x"
public val Y_KEY: String = "bounds-y"
public val WIDTH_KEY: String = "bounds-width"
public val HEIGHT_KEY: String = "bounds-height"
}
}
| mit | 31818fb3457e27b7215622fcd10b7abd | 31.776699 | 136 | 0.711197 | 4.178218 | false | false | false | false |
daemontus/glucose | app/src/main/java/com/github/daemontus/glucose/demo/presentation/ShowListPresenter.kt | 2 | 2677 | package com.github.daemontus.glucose.demo.presentation
import android.content.Context
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.widget.ImageView
import android.widget.TextView
import com.github.daemontus.glucose.demo.R
import com.github.daemontus.glucose.demo.data.Show
import com.github.daemontus.glucose.demo.domain.ShowRepository
import com.glucose.app.Presenter
import com.glucose.app.PresenterDelegate
import com.glucose.app.PresenterHost
import com.glucose.app.presenter.findView
import com.jakewharton.rxbinding.view.clicks
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.subjects.PublishSubject
class ShowListPresenter(context: PresenterHost, parent: ViewGroup?)
: Presenter(context, R.layout.presenter_show_list, parent) {
val showClickSubject: PublishSubject<Show> = PublishSubject.create<Show>()
val showList = findView<RecyclerView>(R.id.show_list).apply {
this.layoutManager = LinearLayoutManager(host.activity)
}
val repository = ShowRepository()
override fun onAttach(arguments: Bundle) {
super.onAttach(arguments)
repository.getShows().observeOn(AndroidSchedulers.mainThread())
.subscribe {
showList.adapter = ShowAdapter(it, host.activity, showClickSubject)
}
}
class ShowAdapter(
val items: List<Show>,
val host: Context,
val clickObserver: Observer<Show>
) : RecyclerView.Adapter<ShowAdapter.ShowHolder>() {
override fun onBindViewHolder(holder: ShowHolder, position: Int) {
holder.render(items[position])
}
override fun onCreateViewHolder(parent: ViewGroup?, viewType: Int): ShowHolder
= ShowHolder(LayoutInflater.from(host).inflate(R.layout.item_show, parent, false), clickObserver)
override fun getItemCount(): Int {
return items.size
}
class ShowHolder(
itemView: View, clickObserver: Observer<Show>
) : RecyclerView.ViewHolder(itemView) {
val image = itemView.findViewById(R.id.show_image) as ImageView
val title = itemView.findViewById(R.id.show_title) as TextView
private var item: Show? = null
fun render(show: Show) {
item = show
title.text = show.name
}
init {
itemView.clicks().map { item!! }.subscribe(clickObserver)
}
}
}
} | mit | f8d392bb73e96afc8aec27772baf55cb | 32.898734 | 113 | 0.68771 | 4.439469 | false | false | false | false |
http4k/http4k | http4k-jsonrpc/src/main/kotlin/org/http4k/jsonrpc/internal.kt | 1 | 1549 | package org.http4k.jsonrpc
import org.http4k.format.Json
import org.http4k.format.JsonType
internal class ParamMappingJsonRequestHandler<NODE : Any, IN, OUT : Any>(json: Json<NODE>,
paramsFieldNames: Iterable<String>,
paramsLens: Mapping<NODE, IN>,
function: (IN) -> OUT,
resultLens: Mapping<OUT, NODE>) : JsonRpcHandler<NODE, NODE> {
private val handler: (NODE) -> NODE = {
val input = when (json.typeOf(it)) {
JsonType.Array -> {
val elements = json.elements(it).toList()
paramsFieldNames.mapIndexed { index: Int, name: String ->
name to elements.getOrElse(index) { json.nullNode() }
}.takeUnless { it.isEmpty() }
?.let { json.obj(it) }
?: json.nullNode()
}
else -> it
}
paramsLens(input).let(function).let(resultLens)
}
override fun invoke(request: NODE): NODE = handler(request)
}
internal class NoParamsJsonRequestHandler<NODE, OUT : Any>(function: () -> OUT, resultLens: Mapping<OUT, NODE>) :
JsonRpcHandler<NODE, NODE> {
private val handler: (NODE) -> NODE = { function().let(resultLens) }
override fun invoke(request: NODE): NODE = handler(request)
}
| apache-2.0 | 5c7dd0b8e9f34ab01474cb908b07489a | 43.257143 | 135 | 0.495804 | 4.795666 | false | false | false | false |
mehulsbhatt/emv-bertlv | src/main/java/io/github/binaryfoo/decoders/PopulatedDOLDecoder.kt | 1 | 1990 | package io.github.binaryfoo.decoders
import io.github.binaryfoo.DecodedData
import io.github.binaryfoo.Decoder
import io.github.binaryfoo.TagInfo
import io.github.binaryfoo.TagMetaData
import io.github.binaryfoo.tlv.ISOUtil
import io.github.binaryfoo.tlv.Tag
import java.nio.ByteBuffer
import java.util.ArrayList
public class PopulatedDOLDecoder : Decoder {
override fun decode(input: String, startIndexInBytes: Int, session: DecodeSession): MutableList<DecodedData> {
val fields = input.split(":")
val pdol = fields[0]
val populatedPDOL = fields[1]
return decode(pdol, populatedPDOL, pdol.length() / 2, session)
}
public fun decode(pdol: String, populatedPDOL: String, startIndexInBytes: Int, session: DecodeSession): MutableList<DecodedData> {
val decoded = ArrayList<DecodedData>()
val values = ByteBuffer.wrap(ISOUtil.hex2byte(populatedPDOL))
val elements = DOLParser().parse(ISOUtil.hex2byte(pdol))
var offset = startIndexInBytes
for (element in elements) {
val value = ByteArray(element.length)
values.get(value)
val tagMetaData = session.tagMetaData
val tag = element.tag
val tagInfo = tagMetaData!!.get(tag)
val valueAsHexString = ISOUtil.hexString(value)
val children = tagInfo.decoder.decode(valueAsHexString, offset, session)
val decodedData = DecodedData.withTag(tag, tagMetaData, tagInfo.decodePrimitiveTlvValue(valueAsHexString), offset, offset + value.size, children)
decoded.add(decodedData)
offset += value.size
}
return decoded
}
override fun validate(input: String?): String? {
val fields = input?.split(":")?.size ?: 0
if (fields != 2) {
return "Put : between the DOL and the populated list"
}
return null
}
override fun getMaxLength(): Int {
return Integer.MAX_VALUE
}
}
| mit | 3b50e4d566580150056ca8f8a523117d | 37.269231 | 157 | 0.668844 | 4.326087 | false | false | false | false |
vilnius/tvarkau-vilniu | app/src/main/java/lt/vilnius/tvarkau/api/ApiHeadersInterceptor.kt | 1 | 1397 | package lt.vilnius.tvarkau.api
import lt.vilnius.tvarkau.prefs.AppPreferences
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import javax.inject.Inject
import javax.inject.Singleton
@Singleton
class ApiHeadersInterceptor @Inject constructor(
private val appPreferences: AppPreferences
) : Interceptor {
override fun intercept(chain: Interceptor.Chain): Response {
val requestBuilder = chain.request().newBuilder()
appendToken(chain, requestBuilder)
return chain.proceed(requestBuilder.build())
}
private fun appendToken(chain: Interceptor.Chain, requestBuilder: Request.Builder) {
val containsTokenHeader = chain.request().headers().names().contains(HTTP_HEADER_OAUTH)
if (appPreferences.apiToken.isSet() && !containsTokenHeader) {
applyToken(requestBuilder)
}
}
fun applyToken(requestBuilder: Request.Builder) {
val tokenValue = appPreferences.apiToken.get()
requestBuilder.addHeader(HTTP_HEADER_OAUTH, formatTokenForHeader(tokenValue.accessToken))
requestBuilder.addHeader(HTTP_HEADER_CITY, appPreferences.selectedCity.get().id.toString())
}
private fun formatTokenForHeader(token: String) = "Bearer $token"
companion object {
const val HTTP_HEADER_OAUTH = "Authorization"
const val HTTP_HEADER_CITY = "X-City-ID"
}
}
| mit | 23a213f264ce4a5f2d8f7ec02096bde0 | 31.488372 | 99 | 0.725841 | 4.550489 | false | false | false | false |
budioktaviyan/reactive-concept-kotlin | app/src/main/kotlin/com/baculsoft/sample/kotlinreactive/observable/ObservableActivity.kt | 1 | 1920 | package com.baculsoft.sample.kotlinreactive.observable
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.support.v7.widget.Toolbar
import android.view.MenuItem
import android.widget.Button
import android.widget.TextView
import com.baculsoft.sample.kotlinreactive.R
import com.baculsoft.sample.kotlinreactive.ext.statusBarHeight
import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.schedulers.Schedulers
import org.jetbrains.anko.find
import org.jetbrains.anko.setContentView
class ObservableActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
ObservableUI().setContentView(this)
setToolbar()
addListener()
}
override fun onOptionsItemSelected(item: MenuItem?): Boolean {
when (item?.itemId) {
android.R.id.home -> {
onBackPressed()
}
}
return super.onOptionsItemSelected(item)
}
private fun setToolbar() {
val toolbar = find<Toolbar>(R.id.toolbar_observable)
toolbar.title = resources.getString(R.string.menu_observable)
toolbar.navigationIcon = ContextCompat.getDrawable(this, R.drawable.bg_arrow_back)
toolbar.setPadding(0, toolbar.statusBarHeight, 0, 0)
setSupportActionBar(toolbar)
}
private fun addListener() {
val button = find<Button>(R.id.btn_observable)
val textView = find<TextView>(R.id.tv_observable)
button.setOnClickListener { doSubscribe(textView) }
}
private fun doSubscribe(textView: TextView) {
Observable.just("Hello Reactive!").observeOn(AndroidSchedulers.mainThread()).subscribeOn(Schedulers.io()).subscribe({ textView.text = it.toString() }, { it.printStackTrace() })
}
} | apache-2.0 | cb3628c3a8cc303c0df76ef542628c87 | 33.927273 | 184 | 0.722917 | 4.549763 | false | false | false | false |
rock3r/detekt | detekt-core/src/main/kotlin/io/gitlab/arturbosch/detekt/core/KtTreeCompiler.kt | 1 | 1988 | package io.gitlab.arturbosch.detekt.core
import org.jetbrains.kotlin.psi.KtFile
import java.nio.file.Files
import java.nio.file.Path
import java.util.stream.Collectors
class KtTreeCompiler(
private val settings: ProcessingSettings,
private val compiler: KtCompiler = KtCompiler(settings.environment)
) {
companion object {
val KT_ENDINGS = setOf("kt", "kts")
fun instance(settings: ProcessingSettings): KtTreeCompiler = KtTreeCompiler(settings)
}
fun compile(path: Path): List<KtFile> {
require(Files.exists(path)) { "Given path $path does not exist!" }
return when {
path.isFile() && path.isKotlinFile() -> listOf(compiler.compile(path, path))
path.isDirectory() -> compileProject(path)
else -> {
settings.info("Ignoring a file detekt cannot handle: $path")
emptyList()
}
}
}
private fun compileProject(project: Path): List<KtFile> {
val kotlinFiles = Files.walk(project)
.filter(Path::isFile)
.filter { it.isKotlinFile() }
.filter { !isIgnored(it) }
return if (settings.parallelCompilation) {
val service = settings.taskPool
val tasks = kotlinFiles.map { path ->
service.task { compiler.compile(project, path) }
.recover { settings.error("Could not compile '$path'.", it); null }
}.collect(Collectors.toList())
return awaitAll(tasks).filterNotNull()
} else {
kotlinFiles.map { compiler.compile(project, it) }.collect(Collectors.toList())
}
}
private fun Path.isKotlinFile(): Boolean {
val fullPath = toAbsolutePath().toString()
val kotlinEnding = fullPath.substring(fullPath.lastIndexOf('.') + 1)
return kotlinEnding in KT_ENDINGS
}
private fun isIgnored(path: Path): Boolean = settings.pathFilters?.isIgnored(path) ?: false
}
| apache-2.0 | fa291bfc4eb9f276b3e27b8714f8dbb3 | 35.814815 | 95 | 0.619215 | 4.467416 | false | false | false | false |
tokenbrowser/token-android-client | app/src/main/java/com/toshi/viewModel/DappViewModel.kt | 1 | 3534 | /*
* Copyright (c) 2017. Toshi Inc
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.toshi.viewModel
import android.arch.lifecycle.MutableLiveData
import android.arch.lifecycle.ViewModel
import com.toshi.R
import com.toshi.model.network.dapp.Dapp
import com.toshi.model.network.dapp.DappSearchResult
import com.toshi.model.network.dapp.DappSections
import com.toshi.util.SingleLiveEvent
import com.toshi.view.BaseApplication
import rx.Single
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import rx.subjects.PublishSubject
import rx.subscriptions.CompositeSubscription
import java.util.concurrent.TimeUnit
class DappViewModel : ViewModel() {
private val dappManager by lazy { BaseApplication.get().dappManager }
private val subscriptions by lazy { CompositeSubscription() }
private val searchSubject by lazy { PublishSubject.create<String>() }
val searchResult by lazy { MutableLiveData<DappSearchResult>() }
val dappsError by lazy { SingleLiveEvent<Int>() }
val dappSections by lazy { MutableLiveData<DappSections>() }
val allDapps by lazy { MutableLiveData<List<Dapp>>() }
init {
getFeaturedDapps()
initSearchListener()
}
private fun getFeaturedDapps() {
val sub = dappManager
.getFrontPageDapps()
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ dappSections.value = it },
{ R.string.error_fetching_dapps }
)
subscriptions.add(sub)
}
fun search(input: String) = searchSubject.onNext(input)
private fun initSearchListener() {
val sub = searchSubject
.debounce(500, TimeUnit.MILLISECONDS)
.flatMap { searchForDapps(it).toObservable() }
.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ searchResult.value = it },
{ dappsError.value = R.string.error_fetching_dapps }
)
subscriptions.add(sub)
}
private fun searchForDapps(input: String): Single<DappSearchResult> {
return dappManager.search(input)
}
fun getAllDapps() {
if (allDapps.value != null) return
val sub = dappManager
.getAllDapps()
.map { it.results.dapps }
.observeOn(AndroidSchedulers.mainThread())
.subscribe(
{ allDapps.value = it },
{ dappsError.value = R.string.error_fetching_dapps }
)
subscriptions.add(sub)
}
fun getCategories() = searchResult.value?.results?.categories ?: emptyMap()
override fun onCleared() {
super.onCleared()
subscriptions.clear()
}
} | gpl-3.0 | b8f3354f06e9ea1626ae353403aba6a7 | 33.320388 | 79 | 0.642615 | 4.519182 | false | false | false | false |
aptyr/github-to-firebase-example | app/src/main/java/com/aptyr/clonegithubtofirebase/ui/adapter/UsersAdapter.kt | 1 | 2870 | package com.aptyr.clonegithubtofirebase.ui.adapter
/**
* Copyright (C) 2016 Aptyr (github.com/aptyr)
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.aptyr.clonegithubtofirebase.R
import java.util.ArrayList
import com.aptyr.clonegithubtofirebase.model.User
import com.aptyr.clonegithubtofirebase.ui.widget.UsersRecyclerViewRow
class UsersAdapter : RecyclerView.Adapter<UsersAdapter.ViewHolder>() {
interface ItemClickListener {
fun onItemClick(position: Int)
}
private val mUsers = ArrayList<User>()
private var mViewHolder: ViewHolder? = null
private var mItemClickListener: ItemClickListener? = null
private var mExpandRowPosition = -1
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val view = LayoutInflater.from(parent.context).inflate(R.layout.item_user, parent, false)
mViewHolder = ViewHolder(view)
mViewHolder!!.mItemClickListener = mItemClickListener
return mViewHolder!!
}
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val user = mUsers[position]
holder.rowView?.setData(user)
}
override fun getItemCount(): Int {
return mUsers.size
}
fun addUsers(users: List<User>) {
Log.d("addusers", "$users")
mUsers.addAll(users)
notifyItemRangeInserted(mUsers.size - users.size, users.size)
}
fun setItemClickListener(clickListener: ItemClickListener) {
mItemClickListener = clickListener
}
fun expandRow(position: Int) {
if (position == mExpandRowPosition)
return
val old = mExpandRowPosition
mExpandRowPosition = position
if (old != -1)
notifyItemChanged(old)
notifyItemChanged(position)
}
class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
var rowView: UsersRecyclerViewRow? = null
var mItemClickListener: ItemClickListener? = null
init {
rowView = itemView.findViewById(R.id.row) as UsersRecyclerViewRow
rowView?.setOnClickListener({ view -> mItemClickListener?.onItemClick(adapterPosition) })
}
}
}
| apache-2.0 | 76a0c95e846ace8965a07582df732bf9 | 29.531915 | 101 | 0.707666 | 4.442724 | false | false | false | false |
pdvrieze/ProcessManager | ProcessEngine/core/src/commonMain/kotlin/nl/adaptivity/process/engine/processUtil.kt | 1 | 4398 | /*
* Copyright (c) 2016.
*
* This file is part of ProcessManager.
*
* ProcessManager is free software: you can redistribute it and/or modify it under the terms of version 3 of the
* GNU Lesser General Public License as published by the Free Software Foundation.
*
* ProcessManager 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 Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License along with ProcessManager. If not,
* see <http://www.gnu.org/licenses/>.
*/
package nl.adaptivity.process.engine
import net.devrieze.util.Handle
import net.devrieze.util.HandleNotFoundException
import net.devrieze.util.security.SecureObject
import nl.adaptivity.process.engine.processModel.ProcessNodeInstance
import nl.adaptivity.process.processModel.ProcessModel
import nl.adaptivity.process.processModel.ProcessNode
import nl.adaptivity.process.processModel.RootProcessModel
import nl.adaptivity.process.util.Identifiable
import nl.adaptivity.process.util.Identifier
/**
* Utilities for handling process things
*/
fun <N: ProcessNode> N?.mustExist(id:Identifiable): N = this ?: throw ProcessException("The node with id $id is missing")
@Suppress("NOTHING_TO_INLINE")
inline fun <N: ProcessNode> N?.mustExist(id:String): N = mustExist(Identifier(id))
fun <T: ProcessNode> ProcessModel<T>.requireNode(id:Identifiable):T = getNode(id).mustExist(id)
@Suppress("NOTHING_TO_INLINE")
inline fun <T: ProcessNode> ProcessModel<T>.requireNode(id:String):T = requireNode(Identifier(id))
/**
* Verify that the node instance exists. If it doesn't exist this is an internal error
* @return The node
* @throws IllegalStateException If it doesn't
*/
fun <T: ProcessTransaction, N: ProcessNodeInstance<*>> N?.mustExist(handle: Handle<SecureObject<ProcessNodeInstance<*>>>): N = this ?: throw IllegalStateException("Node instance missing: $handle")
/**
* Verify that the node exists. Non-existance could be user errror.
* @return The node
* @throws HandleNotFoundException If it doesn't.
*/
fun <T: ProcessTransaction, N: ProcessNodeInstance<*>> N?.shouldExist(handle: Handle<SecureObject<ProcessNodeInstance<*>>>): N = this ?: throw HandleNotFoundException("Node instance missing: $handle")
/**
* Verify that the object instance exists. If it doesn't exist this is an internal error
* @return The node
* @throws IllegalStateException If it doesn't
*/
fun <N:SecureObject<V>, V:Any> N?.mustExist(handle: Handle<SecureObject<V>>): N = this ?: throw IllegalStateException("Process engine element missing: $handle")
/**
* Verify that the object exists. If it doesn't exist this is an internal error
* @return The node
* @throws IllegalStateException If it doesn't
*/
fun <N:SecureObject<V>, V:Any> N?.shouldExist(handle: Handle<SecureObject<V>>): N = this ?: throw HandleNotFoundException("Process engine element missing: $handle")
/**
* Verify that the node instance exists. If it doesn't exist this is an internal error
* @return The node
* @throws IllegalStateException If it doesn't
*/
fun <T: ProcessTransaction> ProcessInstance?.mustExist(handle: Handle<SecureObject<ProcessInstance>>): ProcessInstance = this ?: throw IllegalStateException("Node instance missing: $handle")
/**
* Verify that the node exists. Non-existance could be user errror.
* @return The node
* @throws HandleNotFoundException If it doesn't.
*/
fun <T: ProcessTransaction> ProcessInstance?.shouldExist(handle: Handle<SecureObject<ProcessInstance>>): ProcessInstance = this ?: throw HandleNotFoundException("Node instance missing: $handle")
/**
* Verify that the node instance exists. If it doesn't exist this is an internal error
* @return The node
* @throws IllegalStateException If it doesn't
*/
fun <N: ProcessNode, M: RootProcessModel<N>> M?.mustExist(handle: Handle<RootProcessModel<N>>): M = this ?: throw IllegalStateException("Node instance missing: $handle")
/**
* Verify that the node exists. Non-existance could be user errror.
* @return The node
* @throws HandleNotFoundException If it doesn't.
*/
fun <N: ProcessNode, M: RootProcessModel<N>> M?.shouldExist(handle: Handle<RootProcessModel<N>>): M = this ?: throw HandleNotFoundException("Node instance missing: $handle")
| lgpl-3.0 | 71b32b22e98265de5ab1fa51563009df | 44.340206 | 200 | 0.760573 | 4.228846 | false | false | false | false |
akvo/akvo-flow-mobile | app/src/main/java/org/akvo/flow/presentation/survey/SurveyPresenter.kt | 1 | 7774 | /*
* Copyright (C) 2018-2021 Stichting Akvo (Akvo Foundation)
*
* This file is part of Akvo Flow.
*
* Akvo Flow is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Akvo Flow is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Akvo Flow. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.akvo.flow.presentation.survey
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.SupervisorJob
import kotlinx.coroutines.cancelChildren
import kotlinx.coroutines.launch
import org.akvo.flow.BuildConfig
import org.akvo.flow.utils.entity.SurveyGroup
import org.akvo.flow.domain.entity.ApkData
import org.akvo.flow.domain.entity.DomainForm
import org.akvo.flow.domain.interactor.apk.GetApkDataPreferences
import org.akvo.flow.domain.interactor.apk.SaveApkUpdateNotified
import org.akvo.flow.domain.interactor.datapoints.MarkDatapointViewed
import org.akvo.flow.domain.interactor.forms.GetFormInstance
import org.akvo.flow.domain.interactor.forms.GetRegistrationForm
import org.akvo.flow.domain.interactor.forms.GetSavedFormInstance
import org.akvo.flow.domain.interactor.users.GetSelectedUser
import org.akvo.flow.domain.interactor.users.ResultCode
import org.akvo.flow.domain.util.VersionHelper
import org.akvo.flow.presentation.Presenter
import org.akvo.flow.presentation.entity.ViewApkMapper
import org.akvo.flow.util.ConstantUtil
import java.util.HashMap
import javax.inject.Inject
class SurveyPresenter @Inject constructor(
private val getApkDataPreferences: GetApkDataPreferences,
private val saveApkUpdateNotified: SaveApkUpdateNotified,
private val versionHelper: VersionHelper,
private val viewApkMapper: ViewApkMapper,
private val getSelectedUser: GetSelectedUser,
private val markDatapointViewed: MarkDatapointViewed,
private val getRegistrationForm: GetRegistrationForm,
private val getFormInstance: GetFormInstance
) : Presenter {
private var view: SurveyView? = null
private var job = SupervisorJob()
private val uiScope = CoroutineScope(Dispatchers.Main + job)
override fun destroy() {
uiScope.coroutineContext.cancelChildren()
}
fun setView(view: SurveyView?) {
this.view = view
}
fun verifyApkUpdate() {
uiScope.launch {
val result = getApkDataPreferences.execute()
showApkUpdateIfNeeded(result.apkData, result.notificationTime)
}
}
private fun showApkUpdateIfNeeded(apkData: ApkData?, lastNotified: Long) {
if (ApkData.NOT_SET_VALUE != apkData && shouldNotifyNewVersion(lastNotified)
&& versionHelper.isNewerVersion(BuildConfig.VERSION_NAME, apkData!!.version)
) {
notifyNewVersionAvailable(apkData)
}
}
private fun notifyNewVersionAvailable(apkData: ApkData?) {
uiScope.launch {
saveApkUpdateNotified.execute()
view?.showNewVersionAvailable(viewApkMapper.transform(apkData))
}
}
private fun shouldNotifyNewVersion(lastNotified: Long): Boolean {
return if (lastNotified == NOT_NOTIFIED) {
true
} else {
System.currentTimeMillis() - lastNotified >= ConstantUtil.UPDATE_NOTIFICATION_DELAY_IN_MS
}
}
fun onDatapointSelected(datapointId: String, survey: SurveyGroup?) {
uiScope.launch {
val userResult = getSelectedUser.execute()
if (userResult.resultCode == ResultCode.SUCCESS) {
if (survey != null && survey.isMonitored) {
//show a list of forms/submissions
view?.displayRecord(datapointId)
markDataPointViewed(datapointId)
} else {
//only one form possible
val domainForm = fetchRegistrationForm(survey)
if (domainForm != null) {
if (domainForm.cascadeDownloaded) {
markDataPointViewed(datapointId)
val params: MutableMap<String, Any> = HashMap(4)
params[GetSavedFormInstance.PARAM_FORM_ID] = domainForm.formId
params[GetSavedFormInstance.PARAM_DATAPOINT_ID] = datapointId
val result = getFormInstance.execute(params)
if (result is GetFormInstance.GetFormInstanceResult.GetFormInstanceResultSuccess) {
//instance exists, open it
view?.navigateToForm(datapointId,
result.surveyInstanceId,
result.readOnly,
domainForm.formId)
} else {
//no instance exist yet
view?.navigateToForm(domainForm.formId,
userResult.user,
datapointId)
}
} else {
view?.showMissingCascadeError()
view?.enableClickListener()
}
} else {
view?.showMissingFormError()
view?.enableClickListener()
}
}
} else {
view?.showMissingUserError()
view?.enableClickListener()
}
}
}
private suspend fun markDataPointViewed(datapointId: String) {
val params: MutableMap<String?, Any> = HashMap(2)
params[MarkDatapointViewed.PARAM_DATAPOINT_ID] = datapointId
markDatapointViewed.execute(params)
}
fun onAddDataPointTap(surveyGroup: SurveyGroup) {
uiScope.launch {
val userResult = getSelectedUser.execute()
if (userResult.resultCode == ResultCode.SUCCESS) {
val domainForm = fetchRegistrationForm(surveyGroup)
if (domainForm != null) {
if (domainForm.cascadeDownloaded) {
view?.openEmptyForm(userResult.user, domainForm.formId)
} else {
view?.showMissingCascadeError()
}
} else {
view?.showMissingFormError()
}
} else {
view?.showMissingUserError()
}
}
}
private suspend fun fetchRegistrationForm(survey: SurveyGroup?): DomainForm? {
if (survey != null) {
val params: MutableMap<String, Any> = HashMap(2)
params[GetRegistrationForm.PARAM_SURVEY_ID] = survey.id
params[GetRegistrationForm.PARAM_REGISTRATION_FORM_ID] =
survey.registerSurveyId ?: ""
return getRegistrationForm.execute(params).form
}
return null
}
fun checkSelectedUser() {
uiScope.launch {
val userResult = getSelectedUser.execute()
if (userResult.resultCode == ResultCode.SUCCESS) {
view?.displaySelectedUser(userResult.user.name!!)
}
}
}
companion object {
private const val NOT_NOTIFIED: Long = -1
}
}
| gpl-3.0 | a88f7cdba6f019334f8be1a1d4fb7219 | 39.072165 | 111 | 0.614741 | 4.8801 | false | false | false | false |
perseacado/feedback-ui | feedback-ui-slack/src/main/java/com/github/perseacado/feedbackui/slack/SlackFeedbackService.kt | 1 | 1805 | package com.github.perseacado.feedbackui.slack
import com.github.perseacado.feedbackui.core.FeedbackMessage
import com.github.perseacado.feedbackui.core.FeedbackService
import com.github.perseacado.feedbackui.slack.client.SlackClientFactory
import org.apache.commons.codec.binary.Base64
import org.springframework.beans.factory.annotation.Autowired
import org.springframework.stereotype.Service
/**
* @author Marco Eigletsberger, 24.06.16.
*/
@Service
internal open class SlackFeedbackService @Autowired constructor(
val slackProperties: SlackConfigurationProperties
) : FeedbackService {
private val slackClient = SlackClientFactory.create(slackProperties.token!!)
override fun processFeedback(feedbackMessage: FeedbackMessage) {
val filename = "feedback_" + System.currentTimeMillis()
val imageData = Base64.decodeBase64(feedbackMessage.screenshot)
val slackUsername = slackProperties.username!!
val slackChannel = slackProperties.channel!!
val imageUrl = slackClient.uploadFile(filename, slackChannel!!, imageData)
val attachment = createAttachment(feedbackMessage, imageUrl)
slackClient.postMessage(slackUsername, attachment, slackChannel, imageUrl)
}
private fun createAttachment(feedbackDto: FeedbackMessage, imageUrl: String): String {
return "[{\"pretext\": \"New feedback has arrived!\", \"fields\": [" +
"{\"title\": \"Who?\", \"value\": \"" + feedbackDto.from + "\" }," +
"{\"title\": \"Where?\", \"value\": \"" + feedbackDto.url + "\" }," +
"{\"title\": \"Browser?\", \"value\": \"" + feedbackDto.userAgent + "\" }," +
"{\"title\": \"What?\", \"value\": \"" + feedbackDto.message + "\" }" +
"], \"image_url\": \"" + imageUrl + "\" }]"
}
} | mit | 7923294515a2add09328cdbacf67e109 | 46.526316 | 90 | 0.680886 | 4.328537 | false | false | false | false |
Ruben-Sten/TeXiFy-IDEA | src/nl/hannahsten/texifyidea/inspections/TexifyRegexInspection.kt | 1 | 12248 | package nl.hannahsten.texifyidea.inspections
import com.intellij.codeInspection.InspectionManager
import com.intellij.codeInspection.LocalQuickFix
import com.intellij.codeInspection.ProblemDescriptor
import com.intellij.codeInspection.ProblemHighlightType
import com.intellij.openapi.project.Project
import com.intellij.openapi.util.TextRange
import com.intellij.psi.PsiElement
import com.intellij.psi.PsiFile
import nl.hannahsten.texifyidea.psi.LatexRawText
import nl.hannahsten.texifyidea.util.*
import nl.hannahsten.texifyidea.util.files.document
import java.util.regex.Matcher
import java.util.regex.Pattern
/**
* @author Hannah Schellekens
*/
abstract class TexifyRegexInspection(
/**
* The display name of the inspection.
*/
val inspectionDisplayName: String,
/**
* The short name of the inspection (same name as the html info file).
*/
override val inspectionId: String,
/**
* The regex pattern that targets the text for the inspection.
*/
val pattern: Pattern,
/**
* The error message that shows up when you hover over the problem descriptor.
*/
val errorMessage: (Matcher) -> String,
/**
* What to replace in the document.
*/
val replacement: (Matcher, PsiFile) -> String = { _, _ -> "" },
/**
* Fetches different groups from a matcher.
*/
val groupFetcher: (Matcher) -> List<String> = { listOf() },
/**
* The range in the found pattern that must be replaced.
*/
val replacementRange: (Matcher) -> IntRange = { it.start()..it.end() },
/**
* The highlight level of the problem, GENERIC_ERROR_OR_WARNING by default.
*/
val highlight: ProblemHighlightType = ProblemHighlightType.GENERIC_ERROR_OR_WARNING,
/**
* Name of the quick fix.
*/
val quickFixName: (Matcher) -> String = { "Do fix pls" },
/**
* `true` when the inspection is in mathmode, `false` (default) when not in math mode.
*/
val mathMode: Boolean = false,
/**
* Predicate that if `true`, cancels the inspection.
*/
val cancelIf: (Matcher, PsiFile) -> Boolean = { _, _ -> false },
/**
* Provides the text ranges that mark the squiggly warning thingies.
*/
val highlightRange: (Matcher) -> TextRange = { TextRange(it.start(), it.end()) },
/**
* In which inspection inspectionGroup the inspection lies.
*/
override val inspectionGroup: InsightGroup = InsightGroup.LATEX
) : TexifyInspectionBase() {
companion object {
/**
* Get the IntRange that spans the inspectionGroup with the given id.
*/
fun Matcher.groupRange(groupId: Int): IntRange = start(groupId)..end(groupId)
/**
* Checks if the matched element is a child of a certain PsiElement.
*/
inline fun <reified T : PsiElement> isInElement(matcher: Matcher, file: PsiFile): Boolean {
val element = file.findElementAt(matcher.start()) ?: return false
return element.hasParent(T::class)
}
}
override fun getDisplayName() = inspectionDisplayName
override fun checkContext(element: PsiElement) = element.isSuppressed().not() && element.firstParentOfType(LatexRawText::class) == null
override fun inspectFile(file: PsiFile, manager: InspectionManager, isOntheFly: Boolean): MutableList<ProblemDescriptor> {
// Find all patterns.
val text = file.text
val matcher = pattern.matcher(text)
return if (!isOntheFly && runForWholeFile()) {
inspectFileNotOnTheFly(file, manager, matcher)
}
else {
inspectFileOnTheFly(file, manager, matcher)
}
}
/**
* The file is inspected 'not on the fly' when the 'fix all problems in file' menu is used.
* If that is the case and we need to run the inspection for the
* whole file at once, we create only one problem descriptor for
* the whole file, which has all the problem locations.
* Then the problem descriptor will be applied and we can take
* control of handling the displacements of the fixed regex locations ourselves.
* The reason we do not always want one problem descriptor is
* that it would be rendered in IntelliJ as one global warning
* bar at the top of the file, instead of at the correct locations.
*/
private fun inspectFileNotOnTheFly(file: PsiFile, manager: InspectionManager, matcher: Matcher): MutableList<ProblemDescriptor> {
val replacementRanges = arrayListOf<IntRange>()
val replacements = arrayListOf<String>()
val groups = arrayListOf<List<String>>()
var quickFixName = ""
var errorMessage = ""
// For each pattern, just save the replacement location and value
// We use the fact that the matcher finds issues in increasing order when applying fixes
while (matcher.find()) {
// Pre-checks.
if (cancelIf(matcher, file)) {
continue
}
groups.add(groupFetcher(matcher))
val range = replacementRange(matcher)
val replacementContent = replacement(matcher, file)
// Just take the last error/name even if it may not apply to all problems at once
// (they may each have a different error message) because we have to choose only one for the one problem descriptor.
errorMessage = errorMessage(matcher)
quickFixName = quickFixName(matcher)
// Correct context.
val element = file.findElementAt(matcher.start()) ?: continue
if (!checkContext(matcher, element)) {
continue
}
replacementRanges.add(range)
replacements.add(replacementContent)
}
if (replacementRanges.isNotEmpty()) {
// We cannot give one TextRange because there are multiple,
// but it does not matter since the user won't see this anyway.
val problemDescriptor = manager.createProblemDescriptor(
file,
null as TextRange?,
errorMessage,
highlight,
false,
RegexFixes(
quickFixName,
replacements,
replacementRanges,
groups,
this::applyFixes
)
)
return mutableListOf(problemDescriptor)
}
else {
return mutableListOf()
}
}
/**
* Inspect the file and create a list of all problem descriptors.
*/
private fun inspectFileOnTheFly(file: PsiFile, manager: InspectionManager, matcher: Matcher): MutableList<ProblemDescriptor> {
val descriptors = descriptorList()
while (matcher.find()) {
// Pre-checks.
if (cancelIf(matcher, file)) {
continue
}
val groups = groupFetcher(matcher)
val textRange = highlightRange(matcher)
val range = replacementRange(matcher)
val error = errorMessage(matcher)
val quickFix = quickFixName(matcher)
val replacementContent = replacement(matcher, file)
// Correct context.
val element = file.findElementAt(matcher.start()) ?: continue
if (!checkContext(matcher, element)) {
continue
}
descriptors.add(
manager.createProblemDescriptor(
file,
textRange,
error,
highlight,
true,
RegexFixes(
quickFix,
arrayListOf(replacementContent),
arrayListOf(range),
arrayListOf(groups),
this::applyFixes
)
)
)
}
return descriptors
}
/**
* Checks if the element is in the correct context.
*
* By default checks for math mode.
*
* @return `true` if the inspection is allowed in the context, `false` otherwise.
*/
open fun checkContext(matcher: Matcher, element: PsiElement): Boolean {
if (element.isComment()) {
return false
}
return mathMode == element.inMathContext() && checkContext(element)
}
/**
* We assume the quickfix of this inspection replaces text (like <<) by
* content with a different length (like \ll), so we have to make
* sure it is run for the whole file at once.
* It can be disabled by overriding this method.
*/
override fun runForWholeFile(): Boolean {
return true
}
/**
* Replaces all text in the replacementRange by the correct replacement.
*
* @return The total increase in document length, e.g. if << is replaced by
* \ll and \usepackage{amsmath} is added then the total increase is 3 + 20 - 2.
*/
open fun applyFix(descriptor: ProblemDescriptor, replacementRange: IntRange, replacement: String, groups: List<String>): Int {
val file = descriptor.psiElement as PsiFile
val document = file.document() ?: return 0
document.replaceString(replacementRange.first, replacementRange.last, replacement)
return replacement.length - replacementRange.length
}
/**
* Replaces all text for all replacementRanges by the correct replacements.
*
* We assume the quickfix of an inspection performs replacements which could
* have a different length than the original text, the inspection
* should override [runForWholeFile] to explicitly refute this assumption.
*
* @param groups Regex groups as matched by the regex matcher.
* @param replacementRanges These replacement ranges have to be ordered increasingly and have to be non-overlapping.
*/
open fun applyFixes(
descriptor: ProblemDescriptor,
replacementRanges: List<IntRange>,
replacements: List<String>,
groups: List<List<String>>
) {
val fixFunction = { replacementRange: IntRange, replacement: String, group: List<String> -> applyFix(descriptor, replacementRange, replacement, group) }
applyFixes(fixFunction, replacementRanges, replacements, groups)
}
/**
* See [applyFixes].
*/
open fun applyFixes(
fixFunction: (IntRange, String, List<String>) -> Int,
replacementRanges: List<IntRange>,
replacements: List<String>,
groups: List<List<String>>
) {
require(replacementRanges.size == replacements.size) { "The number of replacement values has to equal the number of ranges of those replacements." }
// Remember how much a replacement changed the locations of the fixes still to be applied.
// This is cumulative, but may be negative.
var accumulatedDisplacement = 0
// Loop over all fixes manually, in order to fix the regex locations
for (i in replacements.indices) {
val replacementRange = replacementRanges[i]
val replacement = replacements[i]
val newRange = IntRange(replacementRange.first + accumulatedDisplacement, replacementRange.last + accumulatedDisplacement)
val replacementLength = fixFunction(newRange, replacement, groups[i])
// Fix the locations of the next fixes
accumulatedDisplacement += replacementLength
}
}
/**
* @author Hannah Schellekens
*/
open class RegexFixes(
private val fixName: String,
val replacements: List<String>,
val replacementRanges: List<IntRange>,
val groups: List<List<String>>,
val fixFunction: (ProblemDescriptor, List<IntRange>, List<String>, List<List<String>>) -> Unit
) : LocalQuickFix {
override fun getFamilyName(): String = fixName
override fun applyFix(project: Project, problemDescriptor: ProblemDescriptor) {
fixFunction(problemDescriptor, replacementRanges, replacements, groups)
}
}
}
| mit | eb05a52f4e6adb872c6bb0468516a1d4 | 34.398844 | 160 | 0.622632 | 5.059067 | false | false | false | false |
cronokirby/FlashKi | src/com/cronokirby/flashki/models/Deck.kt | 1 | 870 | package com.cronokirby.flashki.models
/**
* A deck of cards to study
*
* Contains the list of cards, as well as metadata surrounding them.
*
* @param cards the list of cards this deck will contain
* @param metaData the metadata associated with this deck
*/
class Deck(val cards: List<Card>, val metaData: DeckMeta) {
val cardCount = cards.size
companion object {
fun empty(): Deck {
return Deck(listOf(), DeckMeta(Category(""), ""))
}
}
override fun equals(other: Any?): Boolean {
if (this === other) return true
if (javaClass != other?.javaClass) return false
other as Deck
if (metaData != other.metaData) return false
if (cardCount != other.cardCount) return false
return true
}
override fun hashCode(): Int {
return metaData.hashCode()
}
} | mit | c302691ea21d4255f46328b24fff869e | 22.540541 | 68 | 0.622989 | 4.35 | false | false | false | false |
SimonVT/cathode | trakt-api/src/main/java/net/simonvt/cathode/api/entity/SyncResponse.kt | 1 | 1297 | /*
* Copyright (C) 2014 Simon Vig Therkildsen
*
* 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.simonvt.cathode.api.entity
data class SyncResponse(
val added: Success? = null,
val existing: Success? = null,
val deleted: Success? = null,
val not_found: Errors? = null
)
data class Success(
val movies: Int? = null,
val shows: Int? = null,
val seasons: Int? = null,
val episodes: Int? = null
)
data class Errors(
val movies: List<ErrorMovie>? = null,
val shows: List<ErrorShow>? = null,
val seasons: List<ErrorSeason>? = null,
val episodes: List<ErrorEpisode>? = null,
val ids: List<Int>? = null
)
data class ErrorShow(val ids: Ids)
data class ErrorSeason(val ids: Ids)
data class ErrorEpisode(val ids: Ids)
data class ErrorMovie(val ids: Ids)
| apache-2.0 | 74ab70535fba1642c4302b033793f1a2 | 28.477273 | 75 | 0.713955 | 3.633053 | false | false | false | false |
minjaesong/terran-basic-java-vm | src/net/torvald/terranvm/runtime/TerranVM.kt | 1 | 38503 | package net.torvald.terranvm.runtime
import net.torvald.terranvm.*
import net.torvald.terranvm.assets.FreshNewParametreRAM
import java.io.InputStream
import java.io.OutputStream
import java.io.Serializable
import java.nio.charset.Charset
import kotlin.collections.ArrayList
import kotlin.math.roundToLong
typealias Number = Double
/**
* VM with minimal operation system that takes care of mallocs. Endianness is LITTLE
*
* @param memSize Memory size in bytes, max size is (2 GB - 1 byte)
* @param stackSize Note: stack is separated from system memory
*
* @throws ArrayIndexOutOfBoundsException whenever
*
* Created by minjaesong on 2017-05-09.
*/
class TerranVM(inMemSize: Int,
//var stackSize: Int = inMemSize.ushr(4).shl(2),
var stdout: OutputStream = System.out,
var stdin: InputStream = System.`in`,
var suppressWarnings: Boolean = false,
// following is an options for TerranVM's micro operation system
val doNotInstallInterrupts: Boolean = false,
// to load from saved shits
val parametreRAM: ByteArray = FreshNewParametreRAM(),
internal val memory: ByteArray = ByteArray(inMemSize),
private val mallocList: ArrayList<Int> = ArrayList<Int>(64),
var terminate: Boolean = false,
var isRunning: Boolean = false,
private val contextHolder: HashMap<Int, Context> = hashMapOf( 0 to Context() ), // main context is always ID 0
private var uptimeHolder: Long = 0L
) : Runnable, Serializable {
var context: Context = contextHolder[0]!!
private set
private var contextID: Int = 0
private val memSize = inMemSize.ushr(2).shl(2)
val bytes_ffffffff = (-1).toLittle()
val bytes_00000000 = byteArrayOf(0, 0, 0, 0)
private val DEBUG = false
private val ERROR = true
/** Memory offsets; bytes_they_take * 4 */
var stackSize: Int? = null
private set
class Pointer(val parent: TerranVM, memoryAddress: Int, type: PointerType = Pointer.PointerType.BYTE, val noCast: Boolean = false) {
/*
VOID in memory: 0x00
BOOLEAN in memory: 0x00 if false, 0xFF if true
*/
val traceMemAddrChange = false
var memAddr: Int = memoryAddress
set(value) {
if (traceMemAddrChange) {
println("!! Pointer: memAddr change $memAddr -> $value")
}
field = value
}
var type = type
set(value) {
if (noCast) throw TypeCastException("This pointer is not castable")
else field = value
}
fun cast(value: PointerType) { type = value }
enum class PointerType { BYTE, INT32, DOUBLE, BOOLEAN, VOID, INT16, INT64 }
companion object {
fun sizeOf(type: PointerType) = when(type) {
PointerType.BYTE -> 1 // Internal for ByteArray (and thus String)
PointerType.BOOLEAN -> 1 //
PointerType.DOUBLE -> 8 // NUMBER in TBASIC
PointerType.INT32 -> 4 // internal use; non-TBASIC
PointerType.VOID -> 1 // also NIL in TBASIC
PointerType.INT16 -> 2 // non-TBASIC
PointerType.INT64 -> 8 // non-TBASIC
}
}
fun size() = sizeOf(type)
operator fun plusAssign(offset: Int) { memAddr += size() * offset }
operator fun minusAssign(offset: Int) { memAddr -= size() * offset }
operator fun plus(offset: Int) = Pointer(parent, memAddr + size() * offset, type)
operator fun minus(offset: Int) = Pointer(parent, memAddr - size() * offset, type)
fun inc() { plusAssign(1) }
fun dec() { minusAssign(1) }
fun toBoolean() = (type != PointerType.VOID && (type == PointerType.BOOLEAN && readData() as Boolean))
/**
* Usage: ```readData() as Number```
*/
fun readData(): Any = when(type) {
PointerType.VOID -> 0x00.toByte() // cast it to TBASNil if you're working with TBASIC
PointerType.BOOLEAN -> (parent.memory[memAddr] != 0.toByte())
PointerType.BYTE -> parent.memory[memAddr]
PointerType.INT32 -> {
parent.memory[memAddr].toInt() or parent.memory[memAddr + 1].toInt().shl(8) or
parent.memory[memAddr + 2].toInt().shl(16) or parent.memory[memAddr + 3].toInt().shl(24)
}
PointerType.DOUBLE -> {
java.lang.Double.longBitsToDouble(
parent.memory[memAddr].toLong() or parent.memory[memAddr + 1].toLong().shl(8) or
parent.memory[memAddr + 2].toLong().shl(16) or parent.memory[memAddr + 3].toLong().shl(24) or
parent.memory[memAddr + 4].toLong().shl(32) or parent.memory[memAddr + 5].toLong().shl(40) or
parent.memory[memAddr + 6].toLong().shl(48) or parent.memory[memAddr + 7].toLong().shl(56)
)
}
PointerType.INT64 -> {
parent.memory[memAddr].toLong() or parent.memory[memAddr + 1].toLong().shl(8) or
parent.memory[memAddr + 2].toLong().shl(16) or parent.memory[memAddr + 3].toLong().shl(24) or
parent.memory[memAddr + 4].toLong().shl(32) or parent.memory[memAddr + 5].toLong().shl(40) or
parent.memory[memAddr + 6].toLong().shl(48) or parent.memory[memAddr + 7].toLong().shl(56)
}
PointerType.INT16 -> {
(parent.memory[memAddr].toInt() or parent.memory[memAddr + 1].toInt().shl(8)).toShort()
}
}
fun readAsDouble(): Double {
if (type == PointerType.DOUBLE)
return readData() as Double
else if (type == PointerType.INT64)
return java.lang.Double.longBitsToDouble(readData() as Long)
else
throw TypeCastException("The pointer is neither DOUBLE nor INT64")
}
fun readAsLong(): Long {
if (type == PointerType.DOUBLE || type == PointerType.INT64)
return parent.memory[memAddr].toLong() or parent.memory[memAddr + 1].toLong().shl(8) or
parent.memory[memAddr + 2].toLong().shl(16) or parent.memory[memAddr + 3].toLong().shl(24) or
parent.memory[memAddr + 4].toLong().shl(32) or parent.memory[memAddr + 5].toLong().shl(40) or
parent.memory[memAddr + 6].toLong().shl(48) or parent.memory[memAddr + 7].toLong().shl(56)
else
throw TypeCastException("The pointer is neither DOUBLE nor INT64")
}
fun write(byte: Byte) { parent.memory[memAddr] = byte }
fun write(double: Double) {
val doubleBytes = java.lang.Double.doubleToRawLongBits(double)
write(doubleBytes)
}
fun write(int: Int) {
(0..3).forEach { parent.memory[memAddr + it] = int.ushr(8 * it).and(0xFF).toByte() }
}
fun write(long: Long) {
(0..7).forEach { parent.memory[memAddr + it] = long.ushr(8 * it).and(0xFF).toByte() }
}
fun write(byteArray: ByteArray) {
if (parent.memory.size < memAddr + byteArray.size) throw ArrayIndexOutOfBoundsException("Out of memory")
System.arraycopy(byteArray, 0, parent.memory, memAddr, byteArray.size)
}
fun write(string: String) {
val strBytes = string.toByteArray(TerranVM.charset)
write(strBytes.size.toLittle() + strBytes) // according to TBASString
}
fun write(boolean: Boolean) {
if (boolean) write(0xFF.toByte()) else write(0.toByte())
}
fun write(value: Any) {
if (value is Byte) write(value as Byte)
else if (value is Double) write (value as Double)
else if (value is Int) write(value as Int)
else if (value is Long) write(value as Long)
else if (value is ByteArray) write(value as ByteArray)
else if (value is String) write(value as String)
else if (value is Pointer) write(value.readData())
else throw IllegalArgumentException("Unsupported type: ${value.javaClass.canonicalName}")
}
fun toLittle() = memAddr.toLittle()
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
////////////////////////////
// Memory Management Unit //
////////////////////////////
fun memSliceBySize(from: Int, size: Int): ByteArray = memory.sliceArray(from until from + size)
fun memSlice(from: Int, to: Int): ByteArray = memory.sliceArray(from..to)
//private val mallocList = ArrayList<Int>(64) // can be as large as memSize
private fun addToMallocList(range: IntRange) { range.forEach { mallocList.add(it) } }
private fun removeFromMallocList(range: IntRange) { range.forEach { mallocList.remove(it) } }
/**
* Return starting position of empty space
*/
private fun findEmptySlotForMalloc(size: Int): Int {
val veryStartPoint = ivtSize
if (mallocList.isEmpty())
return veryStartPoint
mallocList.sort()
val candidates = ArrayList<Pair<Int, Int>>() // startingPos, size
for (it in 1..mallocList.lastIndex) {
val gap = mallocList[it] - 1 - (if (it == 0) veryStartPoint else mallocList[it - 1])
if (gap >= size) {
candidates.add(Pair(mallocList[it] + 1, gap))
}
}
if (candidates.isNotEmpty()) {
candidates.sortBy { it.second } // tight gap comes first
return candidates.first().first
}
else {
return mallocList.last() + 1
}
}
/**
* This function assumes all pointers are well placed, without gaps
*
* Will throw nullPointerException if program is not loaded
*/
fun malloc(size: Int): Pointer {
if (size % 4 != 0)
return malloc(size.roundToFour())
else {
val addr = findEmptySlotForMalloc(size)
addToMallocList(addr until addr + size)
return Pointer(this, addr)
}
}
fun calloc(size: Int): Pointer {
if (size % 4 != 0)
return malloc(size.roundToFour())
else {
val addr = findEmptySlotForMalloc(size)
addToMallocList(addr until addr + size)
(0..size - 1).forEach { memory[addr + it] = 0.toByte() }
return Pointer(this, addr)
}
}
fun freeBlock(variable: TBASValue) {
freeBlock(variable.pointer.memAddr until variable.pointer.memAddr + variable.sizeOf())
}
fun freeBlock(range: IntRange) {
removeFromMallocList(range)
}
fun reduceAllocatedBlock(range: IntRange, sizeToReduce: Int) {
if (sizeToReduce == 0) return
if (sizeToReduce < 0) throw IllegalArgumentException("Reducing negative amount of space ($range, $sizeToReduce)")
val residual = (range.last - sizeToReduce + 1)..range.last
removeFromMallocList(residual)
}
///////////////////////////////////////////////////////////////////////////////////////////////////////////////
val peripherals = Array<VMPeripheralWrapper?>(255, { null }) // peri addr: 0x00..0xFE;
/** - 0x00: system timer
* - 0x01: keyboard
* - 0x02: real-time clock
* - 0x03: primary display adaptor
* - 0x04: reserved
* - 0x05: reserved
* - 0x06: serial port
* - 0x07: serial port
* - 0x08: disk drive A
* - 0x09: disk drive B
* - 0x0A: disk drive C
* - 0x0B: disk drive D
* - 0x0C: SCSI
* - 0x0D: SCSI
* - 0x0E: SCSI
* - 0x0F: SCSI
* - 0x10..0xFE: user space
* - 0xFF: Used to address BIOS/UEFI
*
* (see IRQ_ vars in the companion object)
*/
val bios = TerranVMReferenceBIOS(this)
/**
* Memory Map
*
* 0 96 96+stkSize userSpaceStart memSize
* | IVT | Stack | Program Space | User Space | (more program-user space pair, managed by MMU) |
*
* Reg: Register
* - Function arguments
* - etc.
*
*
* Memory-mapped peripherals must be mapped to their own memory hardware. In other words,
* they don't share your computer's main memory.
*/
//internal val memory = ByteArray(memSize)
val ivtSize = 4 * TerranVM.interruptCount
init {
// initialise default (index zero) program start position with IVT size
// must match with "veryStartPoint" of findEmptySlotForMalloc
context.st = ivtSize
}
//var userSpaceStart: Int? = null // lateinit
// private set
//var terminate = false
//var isRunning = false
// private set
var r1: Int; get() = context.r1; set(value) { context.r1= value }
var r2: Int; get() = context.r2; set(value) { context.r2= value }
var r3: Int; get() = context.r3; set(value) { context.r3= value }
var r4: Int; get() = context.r4; set(value) { context.r4= value }
var r5: Int; get() = context.r5; set(value) { context.r5= value }
var r6: Int; get() = context.r6; set(value) { context.r6= value }
var r7: Int; get() = context.r7; set(value) { context.r7= value }
var r8: Int; get() = context.r8; set(value) { context.r8= value }
var r9: Int; get() = context.r9; set(value) { context.r9= value }
var r10: Int; get() = context.r10; set(value) { context.r10= value }
var r11: Int; get() = context.r11; set(value) { context.r11= value }
var r12: Int; get() = context.r12; set(value) { context.r12= value }
var r13: Int; get() = context.r13; set(value) { context.r13= value }
var r14: Int; get() = context.r14; set(value) { context.r14= value }
var r15: Int; get() = context.r15; set(value) { context.r15= value }
var cp: Int; get() = context.cp; set(value) { context.cp= value } // compare register
/** Memory address (not offset !) */
var pc: Int; get() = context.pc; set(value) { context.pc= value } // program counter
/** Memory address (not offset !) */
var sp: Int; get() = context.sp; set(value) { context.sp= value } // stack pointer
/** It would be easier for you to put memory address in here (not offset !) */
var lr: Int; get() = context.lr; set(value) { context.lr= value } // link register
var st: Int; get() = context.st; set(value) { context.st= value } // starting point
var instPerSec = 0L
private var ipsTimer = 0L // ms
fun writeregFloat(register: Int, data: Float) {
when (register) {
1 -> r1 = data.toRawBits()
2 -> r2 = data.toRawBits()
3 -> r3 = data.toRawBits()
4 -> r4 = data.toRawBits()
5 -> r5 = data.toRawBits()
6 -> r6 = data.toRawBits()
7 -> r7 = data.toRawBits()
8 -> r8 = data.toRawBits()
9 -> r9 = data.toRawBits()
10 -> r10 = data.toRawBits()
11 -> r11 = data.toRawBits()
12 -> r12 = data.toRawBits()
13 -> r13 = data.toRawBits()
14 -> r14 = data.toRawBits()
15 -> r15 = data.toRawBits()
0 -> throw IllegalArgumentException("Cannot write to '0' register")
else -> throw IllegalArgumentException("No such register: r$register")
}
}
fun writeregInt(register: Int, data: Int) {
when (register) {
1 -> r1 = data
2 -> r2 = data
3 -> r3 = data
4 -> r4 = data
5 -> r5 = data
6 -> r6 = data
7 -> r7 = data
8 -> r8 = data
9 -> r9 = data
10 -> r10 = data
11 -> r11 = data
12 -> r12 = data
13 -> r13 = data
14 -> r14 = data
15 -> r15 = data
0 -> throw IllegalArgumentException("Cannot write to '0' register")
else -> throw IllegalArgumentException("No such register: r$register")
}
}
fun readregInt(register: Int) = when (register) {
0 -> 0
1 -> r1
2 -> r2
3 -> r3
4 -> r4
5 -> r5
6 -> r6
7 -> r7
8 -> r8
9 -> r9
10 -> r10
11 -> r11
12 -> r12
13 -> r13
14 -> r14
15 -> r15
else -> throw IllegalArgumentException("No such register: r$register")
}
fun readregFloat(register: Int) = when (register) {
0 -> 0f
1 -> java.lang.Float.intBitsToFloat(r1)
2 -> java.lang.Float.intBitsToFloat(r2)
3 -> java.lang.Float.intBitsToFloat(r3)
4 -> java.lang.Float.intBitsToFloat(r4)
5 -> java.lang.Float.intBitsToFloat(r5)
6 -> java.lang.Float.intBitsToFloat(r6)
7 -> java.lang.Float.intBitsToFloat(r7)
8 -> java.lang.Float.intBitsToFloat(r8)
9 -> java.lang.Float.intBitsToFloat(r9)
10 -> java.lang.Float.intBitsToFloat(r10)
11 -> java.lang.Float.intBitsToFloat(r11)
12 -> java.lang.Float.intBitsToFloat(r12)
13 -> java.lang.Float.intBitsToFloat(r13)
14 -> java.lang.Float.intBitsToFloat(r14)
15 -> java.lang.Float.intBitsToFloat(r15)
else -> throw IllegalArgumentException("No such register: r$register")
}
//private var uptimeHolder = 0L
val uptime: Int // uptime register
get() {
val currentTime = System.currentTimeMillis()
val ret = currentTime - uptimeHolder
return ret.toInt()
}
init {
if (memSize > 4.MB()) {
warn("VM memory size might be too large — recommended max is 4 MBytes")
}
else if (memSize < 512) { // arbitrary amount: maximum allowed by FlowerPot instruction set (256 16-bit words)
throw Error("VM memory size too small — minimum allowed is 512 bytes")
}
else if (memSize > 16.MB()) {
throw Error("Memory size too large -- maximum allowed is 16 MBytes")
}
hardReset()
VMOpcodesRISC.invoke(this)
if (!doNotInstallInterrupts) {
setDefaultInterrupts()
}
}
fun loadProgramDynamic(programImage: ProgramImage, contextID: Int? = null) {
val newContextID = contextID ?: contextHolder.size
val newContext = if (contextID == null) {
contextHolder[newContextID] = Context()
contextHolder[newContextID]!!
}
else {
contextHolder[contextID]!!
}
val newPrgStartingPtr = malloc(programImage.bytes.size).memAddr
newContext.st = newPrgStartingPtr + stackSize!! * 4
newContext.pc = newContext.st + programImage.stackSize * 4
val opcodes = programImage.bytes
if (opcodes.size + newContext.st >= memory.size) {
throw Error("Out of memory -- required: ${opcodes.size + newContext.st} (${opcodes.size} for program), installed: ${memory.size}")
}
System.arraycopy(opcodes, 0, memory, newPrgStartingPtr, opcodes.size)
// HALT guard
memory[opcodes.size + newContext.st] = 0
memory[opcodes.size + newContext.st + 1] = 0
memory[opcodes.size + newContext.st + 2] = 0
memory[opcodes.size + newContext.st + 3] = 0
warn("Program loaded; context ID: $newContextID, pc: $pcHex")
}
/**
* Loads program as current context ID
*/
fun loadProgram(programImage: ProgramImage) {
val opcodes = programImage.bytes
if (opcodes.size + st >= memory.size) {
throw Error("Out of memory -- required: ${opcodes.size + st} (${opcodes.size} for program), installed: ${memory.size}")
}
stackSize = programImage.stackSize
softReset()
val newProgramPtr = malloc(opcodes.size)
System.arraycopy(opcodes, 0, memory, newProgramPtr.memAddr, opcodes.size)
// HALT guard
memory[opcodes.size + st] = 0
memory[opcodes.size + st + 1] = 0
memory[opcodes.size + st + 2] = 0
memory[opcodes.size + st + 3] = 0
pc = st + stackSize!! * 4
warn("Program loaded; context ID: $contextID, pc: $pcHex")
}
/**
* @return size of the interrupts. 0 if doNotInstallInterrupts == true
*/
private fun setDefaultInterrupts(): Int {
if (!doNotInstallInterrupts) {
val assembler = Assembler(this)
val intOOM = assembler("""
.code;
loadwordi r1, 024Eh; call r1, FFh; # N
loadwordi r1, 024Fh; call r1, FFh; # O
loadwordi r1, 024Dh; call r1, FFh; # M
loadwordi r1, 0245h; call r1, FFh; # E
loadwordi r1, 024Dh; call r1, FFh; # M
halt;
""").bytes
val intSegfault = assembler("""
.code;
loadwordi r1, 0253h; call r1, FFh; # S
loadwordi r1, 0245h; call r1, FFh; # E
loadwordi r1, 0247h; call r1, FFh; # G
loadwordi r1, 0246h; call r1, FFh; # F
loadwordi r1, 0255h; call r1, FFh; # U
halt;
""").bytes
val intDivZero = assembler("""
.code;
loadwordi r1, 0244h; call r1, FFh; # D
loadwordi r1, 0249h; call r1, FFh; # I
loadwordi r1, 0256h; call r1, FFh; # V
loadwordi r1, 022Fh; call r1, FFh; # /
loadwordi r1, 0230h; call r1, FFh; # 0
halt;
""").bytes
val intIllegalOp = assembler("""
.code;
loadwordi r1, 0249h; call r1, FFh; # I
loadwordi r1, 024Ch; call r1, FFh; # L
loadwordi r1, 024Ch; call r1, FFh; # L
loadwordi r1, 024Fh; call r1, FFh; # O
loadwordi r1, 0250h; call r1, FFh; # P
halt;
""").bytes
val intStackOverflow = assembler("""
.code;
loadwordi r1, 0253h; call r1, FFh; # S
loadwordi r1, 0254h; call r1, FFh; # T
loadwordi r1, 024Fh; call r1, FFh; # O
loadwordi r1, 0256h; call r1, FFh; # V
loadwordi r1, 0246h; call r1, FFh; # F
halt;
""").bytes
val intMathFuck = assembler("""
.code;
loadwordi r1, 024Dh; call r1, FFh; # M
loadwordi r1, 0254h; call r1, FFh; # T
loadwordi r1, 0246h; call r1, FFh; # F
loadwordi r1, 0243h; call r1, FFh; # C
loadwordi r1, 024Bh; call r1, FFh; # K
halt;
""").bytes
val intOOMPtr = malloc(intOOM.size)
val intSegfaultPtr = malloc(intSegfault.size)
val intDivZeroPtr = malloc(intDivZero.size)
val intIllegalOpPtr = malloc(intIllegalOp.size)
val intStackOvflPtr = malloc(intStackOverflow.size)
val intMathErrPtr = malloc(intMathFuck.size)
intOOMPtr.write(intOOM)
intSegfaultPtr.write(intSegfault)
intDivZeroPtr.write(intDivZero)
intIllegalOpPtr.write(intIllegalOp)
intStackOvflPtr.write(intStackOverflow)
intMathErrPtr.write(intMathFuck)
r3 = 0
r1 = intOOMPtr.memAddr
r2 = INT_OUT_OF_MEMORY * 4
VMOpcodesRISC.STOREWORD(2, 1, 3)
r1 = intSegfaultPtr.memAddr
r2 = INT_SEGFAULT * 4
VMOpcodesRISC.STOREWORD(2, 1, 3)
r1 = intDivZeroPtr.memAddr
r2 = INT_DIV_BY_ZERO * 4
VMOpcodesRISC.STOREWORD(2, 1, 3)
r1 = intIllegalOpPtr.memAddr
r2 = INT_ILLEGAL_OP * 4
VMOpcodesRISC.STOREWORD(2, 1, 3)
r1 = intStackOvflPtr.memAddr
r2 = INT_STACK_OVERFLOW * 4
VMOpcodesRISC.STOREWORD(2, 1, 3)
r1 = intMathErrPtr.memAddr
r2 = INT_MATH_ERROR * 4
VMOpcodesRISC.STOREWORD(2, 1, 3)
return intOOM.size + intSegfault.size + intDivZero.size + intIllegalOp.size + intStackOverflow.size + intMathFuck.size
}
return 0
}
fun softReset() {
println("[TerranVM] SOFT RESET")
terminate = false
// reset malloc table
mallocList.clear()
instPerSec = 0
// reset registers
r1 = 0
r2 = 0
r3 = 0
r4 = 0
r5 = 0
r6 = 0
r7 = 0
r8 = 0
r9 = 0
r10 = 0
r11 = 0
r12 = 0
r13 = 0
r14 = 0
r15 = 0
cp = 0
pc = 0
sp = 0
lr = 0
st = interruptCount * 4
//... but don't reset the uptime
resumeExec()
yieldRequested = false
}
fun hardReset() {
softReset()
println("[TerranVM] IT WAS HARD RESET ACTUALLY")
// reset system uptime timer
uptimeHolder = 0L
// wipe memory
for (i in 0 until memSize step 4) {
System.arraycopy(bytes_00000000, 0, memory, i, 4)
}
}
var delayInMills: Int? = null
fun execDebugMain(any: Any?) { if (DEBUG) println(any) }
fun execDebugError(any: Any?) { if (ERROR) System.err.println(any) }
private var pauseRequested = false
private var yieldRequested = false
var yieldFlagged = false
var isPaused = false // is this actually paused?
private set
fun pauseExec() {
pauseRequested = true
}
fun resumeExec() {
vmThread?.resume()
isPaused = false
}
/**
* resume execution with resumeExec()
*/
fun requestToYield() {
yieldRequested = true
}
val pcHex: String; get() = pc.toLong().and(0xffffffff).toString(16).toUpperCase() + "h"
var vmThread: Thread? = null
private set
//private var runcnt = 0
@Synchronized override fun run() {
execDebugMain("Execution stanted; PC: $pcHex")
isRunning = true
uptimeHolder = System.currentTimeMillis()
var ipsCtr = 0L
while (!terminate) {
val ipsCtrNanoSec = System.nanoTime()
//if (DEBUG && runcnt >= 500) break
//runcnt++
if (vmThread == null) {
vmThread = Thread.currentThread()
}
//print("["); (userSpaceStart!!..849).forEach { print("${memory[it].toUint()} ") }; println("]")
if (pauseRequested) {
println("[TerranVM] execution paused")
isPaused = true
vmThread!!.suspend() // fuck it, i'll use this anyway
pauseRequested = false
}
if (yieldRequested && yieldFlagged) {
println("[TerranVM] VM is paused due to yield request")
isPaused = true
vmThread!!.suspend() // fuck it, i'll use this anyway
yieldRequested = false
yieldFlagged = false
}
if (pc >= memory.size) {
val oldpc = pc
execDebugError("Out of memory: Illegal PC; pc ${oldpc.toLong().and(0xffffffff).toString(16).toUpperCase()}h")
interruptOutOfMem()
}
else if (pc < 0) {
val oldpc = pc
execDebugError("Segmentation fault: Illegal PC; pc ${oldpc.toLong().and(0xffffffff).toString(16).toUpperCase()}h")
interruptSegmentationFault()
}
var opcode = memory[pc].toUint() or memory[pc + 1].toUint().shl(8) or memory[pc + 2].toUint().shl(16) or memory[pc + 3].toUint().shl(24)
execDebugMain("pc: $pcHex; opcode: ${opcode.toReadableBin()}; ${opcode.toReadableOpcode()}")
// execute
pc += 4
ipsCtr += 1
// invoke function
try {
VMOpcodesRISC.decodeAndExecute(opcode)
}
catch (oom: ArrayIndexOutOfBoundsException) {
execDebugError("[TBASRT] out-of-bound memory address access: from opcode ${opcode.toReadableBin()}; ${opcode.toReadableOpcode()}")
execDebugError("r1: $r1; ${r1.to8HexString()}; ${readregFloat(1)}f")
execDebugError("r2: $r2; ${r2.to8HexString()}; ${readregFloat(2)}f")
execDebugError("r3: $r3; ${r3.to8HexString()}; ${readregFloat(3)}f")
execDebugError("r4: $r4; ${r4.to8HexString()}; ${readregFloat(4)}f")
execDebugError("r5: $r5; ${r5.to8HexString()}; ${readregFloat(5)}f")
execDebugError("r6: $r6; ${r6.to8HexString()}; ${readregFloat(6)}f")
execDebugError("r7: $r7; ${r7.to8HexString()}; ${readregFloat(7)}f")
execDebugError("r8: $r8; ${r8.to8HexString()}; ${readregFloat(8)}f")
execDebugError("r9: $r9; ${r9.to8HexString()}; ${readregFloat(9)}f")
execDebugError("r10: $r10; ${r10.to8HexString()}; ${readregFloat(10)}f")
execDebugError("r11: $r11; ${r11.to8HexString()}; ${readregFloat(11)}f")
execDebugError("r12: $r12; ${r12.to8HexString()}; ${readregFloat(12)}f")
execDebugError("r13: $r13; ${r13.to8HexString()}; ${readregFloat(13)}f")
execDebugError("r14: $r14; ${r14.to8HexString()}; ${readregFloat(14)}f")
execDebugError("r15: $r15; ${r15.to8HexString()}; ${readregFloat(15)}f")
execDebugError("pc: $pc; ${pc.toHexString()}")
oom.printStackTrace()
interruptOutOfMem()
}
catch (e: UnknownOpcodeExpection) {
execDebugError("r1: $r1; ${r1.to8HexString()}; ${readregFloat(1)}f")
execDebugError("r2: $r2; ${r2.to8HexString()}; ${readregFloat(2)}f")
execDebugError("r3: $r3; ${r3.to8HexString()}; ${readregFloat(3)}f")
execDebugError("r4: $r4; ${r4.to8HexString()}; ${readregFloat(4)}f")
execDebugError("r5: $r5; ${r5.to8HexString()}; ${readregFloat(5)}f")
execDebugError("r6: $r6; ${r6.to8HexString()}; ${readregFloat(6)}f")
execDebugError("r7: $r7; ${r7.to8HexString()}; ${readregFloat(7)}f")
execDebugError("r8: $r8; ${r8.to8HexString()}; ${readregFloat(8)}f")
execDebugError("r9: $r9; ${r9.to8HexString()}; ${readregFloat(9)}f")
execDebugError("r10: $r10; ${r10.to8HexString()}; ${readregFloat(10)}f")
execDebugError("r11: $r11; ${r11.to8HexString()}; ${readregFloat(11)}f")
execDebugError("r12: $r12; ${r12.to8HexString()}; ${readregFloat(12)}f")
execDebugError("r13: $r13; ${r13.to8HexString()}; ${readregFloat(13)}f")
execDebugError("r14: $r14; ${r14.to8HexString()}; ${readregFloat(14)}f")
execDebugError("r15: $r15; ${r15.to8HexString()}; ${readregFloat(15)}f")
execDebugError("pc: $pc; ${pc.toHexString()}")
e.printStackTrace()
VMOpcodesRISC.HALT()
}
if (opcode == 0) {
execDebugMain("HALT at PC $pcHex")
}
if (delayInMills != null) {
Thread.sleep(delayInMills!!.toLong())
}
// count instructions per second
ipsTimer += System.nanoTime() - ipsCtrNanoSec
if (ipsTimer >= 1000000000) {
instPerSec = (ipsCtr * (1000000000.0 / ipsTimer)).roundToLong()
ipsTimer -= 1000000000
ipsCtr -= instPerSec
}
}
isRunning = false
}
fun performContextSwitch(contextID: Int) {
if (!contextHolder.containsKey(contextID)) {
// if specified context is not there, create one right away
contextHolder[contextID] = Context()
}
context = contextHolder[contextID]!!
warn("Context switch ${this.contextID} --> $contextID")
this.contextID = contextID
if (delayInMills != null) {
Thread.sleep(delayInMills!!.toLong() * 18) // arbitrary 18x delay
}
}
///////////////
// CONSTANTS //
///////////////
companion object {
val charset: Charset = Charset.forName("CP437")
const val interruptCount = 64
const val INT_NULL_PTR = 0
const val INT_DIV_BY_ZERO = 1
const val INT_ILLEGAL_OP = 2
const val INT_OUT_OF_MEMORY = 3
const val INT_STACK_OVERFLOW = 4
const val INT_MATH_ERROR = 5
const val INT_SEGFAULT = 6
const val INT_KEYPRESS = 7
const val INT_PERI_INPUT = 8
const val INT_PERI_OUTPUT = 9
const val INT_INTERRUPT = 10
const val INT_SERIAL0 = 11
const val INT_SERIAL1 = 12
const val INT_RASTER_FBUFFER = 16 // required to fire interrupt following every screen refresh
const val IRQ_SYSTEM_TIMER = 0
const val IRQ_KEYBOARD = 1
const val IRQ_RTC = 2
const val IRQ_PRIMARY_DISPLAY = 3
const val IRQ_SERIAL_1 = 6
const val IRQ_SERIAL_2 = 7
const val IRQ_DISK_A = 8
const val IRQ_DISK_B = 9
const val IRQ_DISK_C = 10
const val IRQ_DISK_D = 11
const val IRQ_SCSI_1 = 12
const val IRQ_SCSI_2 = 13
const val IRQ_SCSI_3 = 14
const val IRQ_SCSI_4 = 15
const val IRQ_BIOS = 255
}
private fun warn(any: Any?) { if (!suppressWarnings) println("[TBASRT] WARNING: $any") }
// Interrupt handlers (its just JMPs) //
fun interruptDivByZero() { VMOpcodesRISC.JSRI(memSliceBySize(INT_DIV_BY_ZERO * 4, 4).toLittleInt().ushr(2)) }
fun interruptIllegalOp() { VMOpcodesRISC.JSRI(memSliceBySize(INT_ILLEGAL_OP * 4, 4).toLittleInt().ushr(2)) }
fun interruptOutOfMem() { VMOpcodesRISC.JSRI(memSliceBySize(INT_OUT_OF_MEMORY * 4, 4).toLittleInt().ushr(2)) }
fun interruptStackOverflow() { VMOpcodesRISC.JSRI(memSliceBySize(INT_STACK_OVERFLOW * 4, 4).toLittleInt().ushr(2)) }
fun interruptMathError() { VMOpcodesRISC.JSRI(memSliceBySize(INT_MATH_ERROR * 4, 4).toLittleInt().ushr(2)) }
fun interruptSegmentationFault() { VMOpcodesRISC.JSRI(memSliceBySize(INT_SEGFAULT * 4, 4).toLittleInt().ushr(2)) }
fun interruptKeyPress() { VMOpcodesRISC.JSRI(memSliceBySize(INT_KEYPRESS * 4, 4).toLittleInt().ushr(2)) }
fun interruptPeripheralInput() { VMOpcodesRISC.JSRI(memSliceBySize(INT_PERI_INPUT * 4, 4).toLittleInt().ushr(2)) }
fun interruptPeripheralOutput() { VMOpcodesRISC.JSRI(memSliceBySize(INT_PERI_OUTPUT * 4, 4).toLittleInt().ushr(2)) }
fun interruptStopExecution() { VMOpcodesRISC.JSRI(memSliceBySize(INT_INTERRUPT * 4, 4).toLittleInt().ushr(2)) }
data class Context(
var r1: Int = 0,
var r2: Int = 0,
var r3: Int = 0,
var r4: Int = 0,
var r5: Int = 0,
var r6: Int = 0,
var r7: Int = 0,
var r8: Int = 0,
var r9: Int = 0,
var r10: Int = 0,
var r11: Int = 0,
var r12: Int = 0,
var r13: Int = 0,
var r14: Int = 0,
var r15: Int = 0,
var cp: Int = 0, // compare register
var pc: Int = 0, // program counter
var sp: Int = 0, // stack pointer
var lr: Int = 0, // link register
var st: Int = 0 // starting point, word-wise
)
}
fun Int.KB() = this shl 10
fun Int.MB() = this shl 20
fun Int.to8HexString() = this.toLong().and(0xffffffff).toString(16).padStart(8, '0').toUpperCase() + "h"
fun Int.toHexString() = this.toLong().and(0xffffffff).toString(16).toUpperCase() + "h"
/** Turn string into byte array with null terminator */
fun String.toCString() = this.toByteArray(TerranVM.charset) + 0
fun Int.toLittle() = byteArrayOf(
this.and(0xFF).toByte(),
this.ushr(8).and(0xFF).toByte(),
this.ushr(16).and(0xFF).toByte(),
this.ushr(24).and(0xFF).toByte()
)
fun Long.toLittle() = byteArrayOf(
this.and(0xFF).toByte(),
this.ushr(8).and(0xFF).toByte(),
this.ushr(16).and(0xFF).toByte(),
this.ushr(24).and(0xFF).toByte(),
this.ushr(32).and(0xFF).toByte(),
this.ushr(40).and(0xFF).toByte(),
this.ushr(48).and(0xFF).toByte(),
this.ushr(56).and(0xFF).toByte()
)
fun Double.toLittle() = java.lang.Double.doubleToRawLongBits(this).toLittle()
fun Float.toLittle() = java.lang.Float.floatToRawIntBits(this).toLittle()
fun Boolean.toLittle() = byteArrayOf(if (this) 0xFF.toByte() else 0.toByte())
fun ByteArray.toLittleInt() =
if (this.size != 4) throw Error()
else this[0].toUint() or
this[1].toUint().shl(8) or
this[2].toUint().shl(16) or
this[3].toUint().shl(24)
fun ByteArray.toLittleLong() =
if (this.size != 8) throw Error()
else this[0].toUlong() or
this[1].toUlong().shl(8) or
this[2].toUlong().shl(16) or
this[3].toUlong().shl(24) or
this[4].toUlong().shl(32) or
this[5].toUlong().shl(40) or
this[6].toUlong().shl(48) or
this[7].toUlong().shl(56)
fun ByteArray.toLittleDouble() = java.lang.Double.longBitsToDouble(this.toLittleLong())
fun Byte.toUlong() = java.lang.Byte.toUnsignedLong(this)
fun Byte.toUint() = java.lang.Byte.toUnsignedInt(this)
/**
* Return first occurrence of the byte pattern
* @return starting index of the first occurrence of the pattern, or null if not found
* @see https://en.wikipedia.org/wiki/Knuth%E2%80%93Morris%E2%80%93Pratt_algorithm
*/
fun ByteArray.search(pattern: ByteArray, start: Int = 0, length: Int = pattern.size - start): Int? {
/*
this: text to be searched
pattern: the word sought
*/
var m = 0
var i = 0
val T = IntArray(this.size, { -1 })
//println("Searching pattern (ptn len: ${pattern.size})")
while (m + 1 < this.size) {
//println("m: $m, i: $i")
if (pattern[i] == this[m + i]) {
i += 1
if (i == pattern.size) {
/*val return_m = m
m = m + i - T[i]
i = T[i]
return return_m*/
return m
}
}
else {
if (T[i] > -1) {
m = m + i - T[i]
i = T[i]
}
else {
m += i + 1
i = 0
}
}
}
return null
}
fun Int.roundToFour() = this + ((4 - (this % 4)) % 4)
| mit | a21a54ec27168117b254e63a83eaf3d5 | 34.846369 | 148 | 0.556742 | 3.681297 | false | false | false | false |
Mauin/detekt | detekt-rules/src/main/kotlin/io/gitlab/arturbosch/detekt/rules/naming/EnumNaming.kt | 1 | 1425 | package io.gitlab.arturbosch.detekt.rules.naming
import io.gitlab.arturbosch.detekt.api.CodeSmell
import io.gitlab.arturbosch.detekt.api.Config
import io.gitlab.arturbosch.detekt.api.Debt
import io.gitlab.arturbosch.detekt.api.Entity
import io.gitlab.arturbosch.detekt.api.Issue
import io.gitlab.arturbosch.detekt.api.LazyRegex
import io.gitlab.arturbosch.detekt.api.Rule
import io.gitlab.arturbosch.detekt.api.Severity
import io.gitlab.arturbosch.detekt.rules.identifierName
import org.jetbrains.kotlin.psi.KtEnumEntry
/**
* Reports when enum names which do not follow the specified naming convention are used.
*
* @configuration enumEntryPattern - naming pattern (default: '^[A-Z][_a-zA-Z0-9]*')
* @active since v1.0.0
* @author Marvin Ramin
*/
class EnumNaming(config: Config = Config.empty) : Rule(config) {
override val issue = Issue(javaClass.simpleName,
Severity.Style,
"Enum names should follow the naming convention set in the projects configuration.",
debt = Debt.FIVE_MINS)
private val enumEntryPattern by LazyRegex(ENUM_PATTERN, "^[A-Z][_a-zA-Z0-9]*")
override fun visitEnumEntry(enumEntry: KtEnumEntry) {
if (!enumEntry.identifierName().matches(enumEntryPattern)) {
report(CodeSmell(
issue,
Entity.from(enumEntry),
message = "Enum entry names should match the pattern: $enumEntryPattern"))
}
}
companion object {
const val ENUM_PATTERN = "enumEntryPattern"
}
}
| apache-2.0 | 951405b678b8220daef45ee7ff52bbff | 32.928571 | 88 | 0.762105 | 3.598485 | false | true | false | false |
Mithrandir21/Duopoints | app/src/main/java/com/duopoints/android/fragments/relprofile/details/RelationshipProfileDetailsFrag.kt | 1 | 3023 | package com.duopoints.android.fragments.relprofile.details
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.duopoints.android.R
import com.duopoints.android.fragments.base.BasePresenterFrag
import com.duopoints.android.fragments.userprofile.UserProfileFrag
import com.duopoints.android.rest.models.composites.CompositeRelationship
import com.duopoints.android.ui.lists.RelationshipDetailsAdapter
import com.duopoints.android.ui.lists.base.AdapterDelegatesManager
import com.duopoints.android.ui.lists.base.BaseAdapter
import com.duopoints.android.ui.lists.layouts.linear.PreFetchVerticalLayoutManager
import com.evernote.android.state.State
import kotlinx.android.synthetic.main.frag_relationship_profile_details.*
class RelationshipProfileDetailsFrag : BasePresenterFrag<RelationshipProfileDetailsPresenter>() {
@State
lateinit var compositeRelationship: CompositeRelationship
lateinit var adapter: BaseAdapter
override fun createPresenter(): RelationshipProfileDetailsPresenter {
return RelationshipProfileDetailsPresenter(this)
}
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
return createAndBindView(R.layout.frag_relationship_profile_details, inflater, container)
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
mainActivity.setToolbar(relationshipProfileDetailsToolbar)
// Setup RecyclerView
adapter = BaseAdapter(AdapterDelegatesManager().addDelegate(RelationshipDetailsAdapter()))
relationshipDetailsLceRecyclerView.recyclerView.isNestedScrollingEnabled = false
relationshipDetailsLceRecyclerView.recyclerView.layoutManager = PreFetchVerticalLayoutManager(context)
relationshipDetailsLceRecyclerView.recyclerView.adapter = adapter
relationshipProfileDetailsView.setupProfile(compositeRelationship,
View.OnClickListener { mainActivity.addFragment(UserProfileFrag.newInstance(compositeRelationship.userOne), true) },
View.OnClickListener { mainActivity.addFragment(UserProfileFrag.newInstance(compositeRelationship.userTwo), true) })
relationshipProfileDetailsView.hideProfileActionBtn()
presenter.loadRelationshipDetails(compositeRelationship)
}
/**************************
* PRESENTER - CALL BACKS
**************************/
fun onRelationshipDetailsLoaded(details: List<RelationshipDetailsItem>) {
adapter.replaceData(details)
relationshipDetailsLceRecyclerView.loaded(details.isEmpty())
}
companion object {
fun newInstance(compositeRelationship: CompositeRelationship): RelationshipProfileDetailsFrag {
val frag = RelationshipProfileDetailsFrag()
frag.compositeRelationship = compositeRelationship
return frag
}
}
} | gpl-3.0 | 7ae3f57d1fced2f0af7e43997e722d2c | 39.864865 | 132 | 0.773404 | 5.496364 | false | false | false | false |
FHannes/intellij-community | plugins/groovy/groovy-psi/src/org/jetbrains/plugins/groovy/transformations/impl/GroovyObjectTransformationSupport.kt | 13 | 2449 | /*
* 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.transformations.impl
import com.intellij.openapi.util.Key
import com.intellij.psi.PsiMethod
import org.jetbrains.plugins.groovy.GroovyLanguage
import org.jetbrains.plugins.groovy.lang.psi.api.auxiliary.modifiers.GrModifierFlags
import org.jetbrains.plugins.groovy.lang.psi.impl.statements.expressions.TypesUtil
import org.jetbrains.plugins.groovy.lang.psi.impl.synthetic.GrMethodWrapper
import org.jetbrains.plugins.groovy.lang.psi.util.GrTraitUtil
import org.jetbrains.plugins.groovy.lang.psi.util.GroovyCommonClassNames.GROOVY_OBJECT
import org.jetbrains.plugins.groovy.transformations.AstTransformationSupport
import org.jetbrains.plugins.groovy.transformations.TransformationContext
class GroovyObjectTransformationSupport : AstTransformationSupport {
companion object {
private val ORIGIN_INFO = "via GroovyObject"
private val KEY: Key<Boolean> = Key.create("groovy.object.method")
private fun TransformationContext.findClass(fqn: String) = psiFacade.findClass(fqn, resolveScope)
@JvmStatic fun isGroovyObjectSupportMethod(method: PsiMethod) = method.getUserData(KEY) == true
}
override fun applyTransformation(context: TransformationContext) {
if (context.codeClass.isInterface) return
if (context.superClass?.language == GroovyLanguage) return
val groovyObject = context.findClass(GROOVY_OBJECT)
if (groovyObject == null || !GrTraitUtil.isInterface(groovyObject)) return
context.addInterface(TypesUtil.createType(groovyObject))
val implementedMethods = groovyObject.methods.map {
GrMethodWrapper.wrap(it).apply {
setContext(context.codeClass)
modifierList.removeModifier(GrModifierFlags.ABSTRACT_MASK)
originInfo = ORIGIN_INFO
putUserData(KEY, true)
}
}
context.addMethods(implementedMethods)
}
} | apache-2.0 | ee0ff78507f50424f90b18e10d552e2f | 41.241379 | 101 | 0.781135 | 4.357651 | false | false | false | false |
cloose/luftbild4p3d | src/test/kotlin/org/luftbild4p3d/app/WorkFolderTest.kt | 1 | 1822 | package org.luftbild4p3d.app
import org.junit.Test
import org.luftbild4p3d.bing.LevelOfDetail
import kotlin.test.assertEquals
class WorkFolderTest {
@Test
fun assemblesWorkFolderNameFromPositiveLatitudeAndLongitude() {
val workFolder = WorkFolder("", 54, 9, LevelOfDetail.LOD16)
assertEquals("+54+009", workFolder.name)
}
@Test
fun assemblesWorkFolderNameFromNegativeLatitudeAndLongitude() {
val workFolder = WorkFolder("", -8, -21, LevelOfDetail.LOD16)
assertEquals("-08-021", workFolder.name)
}
@Test
fun assemblesImageFolderNameFromLevelOfDetail() {
val workFolder = WorkFolder("", 54, 9, LevelOfDetail.LOD16)
assertEquals("BI16", workFolder.imageFolderName)
}
@Test
fun assemblesImageFolderPathFromWorkFolderNameAndImageFolderName() {
val workFolder = WorkFolder("", 54, 9, LevelOfDetail.LOD16)
assertEquals("+54+009/BI16", workFolder.imageFolderPath)
}
@Test
fun assemblesSceneryFolderName() {
val workFolder = WorkFolder("", 54, 9, LevelOfDetail.LOD16)
assertEquals("scenery", workFolder.sceneryFolderName)
}
@Test
fun assemblesSceneryFolderPathFromWorkFolderNameAndSceneryFolderName() {
val workFolder = WorkFolder("", 54, 9, LevelOfDetail.LOD16)
assertEquals("+54+009/scenery", workFolder.sceneryFolderPath)
}
@Test
fun assemblesTextureFolderName() {
val workFolder = WorkFolder("", 54, 9, LevelOfDetail.LOD16)
assertEquals("texture", workFolder.textureFolderName)
}
@Test
fun assemblesTextureFolderPathFromWorkFolderNameAndTextureFolderName() {
val workFolder = WorkFolder("", 54, 9, LevelOfDetail.LOD16)
assertEquals("+54+009/texture", workFolder.textureFolderPath)
}
} | gpl-3.0 | db525f8d5f9825544d612555be5f6e0e | 27.046154 | 76 | 0.697036 | 3.995614 | false | true | false | false |
andela-kogunde/CheckSmarter | app/src/main/kotlin/com/andela/checksmarter/adapters/CheckSmarterAdapter.kt | 1 | 3763 | package com.andela.checksmarter.adapters
import android.content.Context
import android.support.v7.app.AlertDialog
import android.support.v7.widget.RecyclerView
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import com.andela.checksmarter.R
import com.andela.checksmarter.model.CheckSmarterJava
import com.andela.checksmarter.views.CheckSmarterItemView
import io.realm.Realm
import kotlinx.android.synthetic.main.check_smarter_item_view.view.*
import java.util.Collections
import rx.functions.Action1
import kotlin.properties.Delegates
/**
* Created by CodeKenn on 18/04/16.
*/
class CheckSmarterAdapter(private val checkSmarterClickListener: CheckSmarterAdapter.CheckSmarterClickListener) :
RecyclerView.Adapter<CheckSmarterAdapter.ViewHolder>(), Action1<List<CheckSmarterJava>> {
interface CheckSmarterClickListener {
fun onCheckSmarterClick(checkSmarter: CheckSmarterJava)
fun onCheckSmarterLongClick(checkSmarter: CheckSmarterJava)
}
private val realm = Realm.getDefaultInstance()
private var checkSmarters = emptyList<CheckSmarterJava>()
private var context: Context by Delegates.notNull()
init {
setHasStableIds(true)
}
override fun call(checkSmarters: List<CheckSmarterJava>) {
this.checkSmarters = checkSmarters
notifyDataSetChanged()
}
override fun onCreateViewHolder(viewGroup: ViewGroup, i: Int): ViewHolder {
this.context = viewGroup.context
val view = LayoutInflater.from(viewGroup.context).inflate(
R.layout.check_smarter_item_view, viewGroup, false) as CheckSmarterItemView
return ViewHolder(view)
}
override fun onBindViewHolder(viewHolder: ViewHolder, i: Int) {
viewHolder.bindTo(checkSmarters[i])
}
override fun getItemCount(): Int {
return checkSmarters.size
}
override fun getItemId(position: Int): Long {
return position.toLong()
}
fun displayDialog(position: Int) {
val view = LayoutInflater.from(this.context).inflate(R.layout.options_layout, null)
val alertDialog = AlertDialog.Builder(this.context)
.setView(view)
.create()
alertDialog.show()
val delete = view.findViewById(R.id.delete)
delete.setOnClickListener {
realm.beginTransaction()
checkSmarters.get(position).removeFromRealm()
realm.commitTransaction()
notifyItemRemoved(position)
Log.d("HELLO", "DELETE ${position}")
alertDialog.dismiss()
}
}
inner class ViewHolder(val checkSmarterItemView: CheckSmarterItemView) :
RecyclerView.ViewHolder(checkSmarterItemView) {
init {
this.checkSmarterItemView.setOnClickListener {
val checkSmarter = checkSmarters[adapterPosition]
checkSmarterClickListener.onCheckSmarterClick(checkSmarter)
}
this.checkSmarterItemView.setOnLongClickListener {
val checkSmarter = checkSmarters[adapterPosition]
realm.beginTransaction()
checkSmarter.isCheck = !checkSmarter.isCheck
realm.commitTransaction()
notifyItemChanged(0)
//TODO: Play pop sound
checkSmarterClickListener.onCheckSmarterLongClick(checkSmarter)
true
}
this.checkSmarterItemView.checkSmarterOptions.setOnClickListener {
displayDialog(adapterPosition)
}
}
fun bindTo(checkSmarter: CheckSmarterJava) {
checkSmarterItemView.bindTo(checkSmarter)
}
}
}
| mit | cd3cc3ea31cca069e00f7ffd8918a8bf | 32.300885 | 113 | 0.683231 | 5.112772 | false | false | false | false |
aglne/mycollab | mycollab-web/src/main/java/com/mycollab/vaadin/ui/ThemeManager.kt | 3 | 18494 | /**
* 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:></http:>//www.gnu.org/licenses/>.
*/
package com.mycollab.vaadin.ui
import com.mycollab.common.i18n.ShellI18nEnum
import com.mycollab.core.UserInvalidInputException
import com.mycollab.core.utils.ColorUtils
import com.mycollab.module.user.domain.AccountTheme
import com.mycollab.module.user.service.AccountThemeService
import com.mycollab.spring.AppContextUtil
import com.mycollab.vaadin.AppUI
import com.mycollab.vaadin.UserUIContext
import com.vaadin.icons.VaadinIcons
import com.vaadin.server.Page
/**
* @author MyCollab Ltd.
* @since 4.1.2
*/
object ThemeManager {
@JvmStatic
fun loadDesktopTheme(sAccountId: Int) {
val themeService = AppContextUtil.getSpringBean(AccountThemeService::class.java)
var accountTheme = themeService.findTheme(sAccountId)
if (accountTheme == null) {
accountTheme = themeService.findDefaultTheme(AppUI.accountId)
if (accountTheme == null) {
throw UserInvalidInputException(UserUIContext.getMessage(ShellI18nEnum.ERROR_CAN_NOT_LOAD_THEME))
}
}
val extraStyles = StringBuilder()
/* Top Menu */
if (accountTheme.topmenubg != null) {
extraStyles.append(".topNavigation { background-color: #${accountTheme.topmenubg}; }")
extraStyles.append("#login-header { background-color: #${accountTheme.topmenubg}; }")
extraStyles.append(".topNavigation #mainLogo { background-color: #${accountTheme.topmenubg}; }")
}
if (accountTheme.topmenubgselected != null) {
extraStyles.append(".topNavigation .serviceMenuContainer .service-menu .v-button.selected { background-color: #${accountTheme.topmenubgselected}; }")
extraStyles.append(".topNavigation .serviceMenuContainer .service-menu .v-button:hover { background-color: #${accountTheme.topmenubgselected}; }")
extraStyles.append(".v-button.add-btn-popup:hover { background-color: #${accountTheme.topmenubgselected}; }")
extraStyles.append(".topNavigation .v-button.ad { background-color: #${accountTheme.topmenubgselected}; }")
}
if (accountTheme.topmenutext != null) {
extraStyles.append(".topNavigation .v-button { color: #${accountTheme.topmenutext}; }")
extraStyles.append(".subDomain { color: #${accountTheme.topmenutext}; }")
extraStyles.append(".accountMenuContainer .v-popup-indicator::before { color: #${accountTheme.topmenutext}; }")
}
if (accountTheme.topmenutextselected != null) {
extraStyles.append(".topNavigation .serviceMenuContainer .service-menu .v-button.selected { color: #${accountTheme.topmenutextselected}; }")
extraStyles.append(".topNavigation .serviceMenuContainer .service-menu .v-button:hover { color: #${accountTheme.topmenutextselected}; }")
extraStyles.append(".v-button.add-btn-popup:hover { color: #${accountTheme.topmenutextselected}; }")
extraStyles.append(".topNavigation .v-button.ad { color: #${accountTheme.topmenutextselected}; }")
extraStyles.append(".topNavigation .v-button.ad .v-icon { color: #${accountTheme.topmenutextselected}; }")
}
/* Vertical Tabsheet */
if (accountTheme.vtabsheetbg != null) {
extraStyles.append(".vertical-tabsheet .navigator-wrap { background-color: #${accountTheme.vtabsheetbg}; }")
}
if (accountTheme.vtabsheettext != null) {
extraStyles.append(".vertical-tabsheet .v-button-tab > .v-button-wrap { color: #${accountTheme.vtabsheettext}; }")
extraStyles.append(".closed-button .v-button-wrap .v-icon { color: #${accountTheme.vtabsheettext}; }")
extraStyles.append(".expand-button .v-button-wrap .v-icon { color: #${accountTheme.vtabsheettext}; }")
extraStyles.append(".project-info .header { color: #${accountTheme.vtabsheettext}; }")
extraStyles.append(".intro-text-wrap .v-label { color: #${accountTheme.vtabsheettext}; }")
}
if (accountTheme.vtabsheetbgselected != null) {
extraStyles.append(".vertical-tabsheet .v-button-tab.tab-selected { background-color: #${accountTheme.vtabsheetbgselected};}")
extraStyles.append(".vertical-tabsheet .v-button-tab:hover {background-color: #${accountTheme.vtabsheetbgselected};}")
}
if (accountTheme.vtabsheettextselected != null) {
extraStyles.append(".vertical-tabsheet .v-button-tab.tab-selected > .v-button-wrap { color: #${accountTheme.vtabsheettextselected}; }")
extraStyles.append(".vertical-tabsheet .v-button-tab.tab-selected { box-shadow: inset 5px 0px 0px 0px #${accountTheme.vtabsheettextselected}; }")
extraStyles.append(".vertical-tabsheet .v-button-tab.group-tab-selected { box-shadow: inset 5px 0px 0px 0px #${accountTheme.vtabsheettextselected}; }")
//Color while hover on sidebar menu
extraStyles.append(".vertical-tabsheet .v-button-tab .v-button-wrap:hover {color: #${accountTheme.vtabsheettextselected}!important;}")
extraStyles.append(".vertical-tabsheet .v-button-tab:hover .v-button-wrap {color: #${accountTheme.vtabsheettextselected}!important;}")
}
/* Action Buttons */
if (accountTheme.actionbtn != null) {
extraStyles.append(".v-button.v-button-action-button, .v-button-action-button:focus { background-color: #${accountTheme.actionbtn}; }")
extraStyles.append(".splitbutton:hover .v-button.v-button-action-button, .v-button-action-button:hover { background-color: ${ColorUtils.darkerColor("#" + accountTheme.actionbtn)}; }")
extraStyles.append(".upload-field .v-upload-immediate .v-button {background-color: #${accountTheme.actionbtn};}")
extraStyles.append(".upload-field .v-upload-immediate .v-button:hover {background-color: ${ColorUtils.darkerColor("#" + accountTheme.actionbtn)};}")
extraStyles.append(".optionPopupContent .action-wrap:hover {background-color: #${accountTheme.actionbtn}};")
extraStyles.append(".v-buttongroup.toggle-btn-group .v-button.active { background-color: #${accountTheme.actionbtn}; }")
//Button paging
extraStyles.append(".v-button.buttonPaging.current, .v-button.buttonPaging:hover { background-color:#${accountTheme.actionbtn}; }")
//Selection background of selected item
extraStyles.append(".v-filterselect-suggestpopup .gwt-MenuItem-selected { background-color:#${accountTheme.actionbtn}; }")
//Year block of activity stream
extraStyles.append(".v-label.year-lbl { box-shadow: 0 0 0 5px #${accountTheme.actionbtn};}")
//Date label of activity stream
extraStyles.append(".activity-list .feed-block-wrap .date-lbl { background-color:#${accountTheme.actionbtn};}")
extraStyles.append(".activity-list .feed-block-wrap .date-lbl::after{ border-left-color:#${accountTheme.actionbtn};}")
extraStyles.append(".activity-list .feed-block-wrap:hover .date-lbl { background-color:${ColorUtils.darkerColor("#" + accountTheme.actionbtn)};}")
extraStyles.append(".activity-list .feed-block-wrap:hover .date-lbl::after{ border-left-color:${ColorUtils.darkerColor("#" + accountTheme.actionbtn)};}")
// Button group default button
extraStyles.append(".toggle-btn-group .v-button.btn-group-default {background-color:#${accountTheme.actionbtn};}")
extraStyles.append(".toggle-btn-group .v-button.btn-group-default:hover {background-color:${ColorUtils.darkerColor("#" + accountTheme.actionbtn)};}")
extraStyles.append(".v-context-menu-container .v-context-menu .v-context-submenu:hover {background-color:#${accountTheme.actionbtn};}")
//Styles for field-note
extraStyles.append(".field-note {color: #${accountTheme.actionbtn}; border: 1px solid ${ColorUtils.darkerColor("#" + accountTheme.actionbtn, 0.1)};}")
extraStyles.append(".field-note:hover {border-color: ${ColorUtils.darkerColor("#" + accountTheme.actionbtn, 0.15)};}")
extraStyles.append(".field-note a:visited {color: #${accountTheme.actionbtn};}")
extraStyles.append(".field-note a:link {color: #${accountTheme.actionbtn};}")
}
if (accountTheme.actionbtntext != null) {
extraStyles.append(".v-button.v-button-action-button, .v-button-action-button:focus { color: #${accountTheme.actionbtntext}; }")
extraStyles.append(".upload-field .v-upload-immediate .v-button, .upload-field .v-upload-immediate .v-button:focus {color: #${accountTheme.actionbtntext};}")
extraStyles.append(".optionPopupContent .action-wrap .v-button-action .v-button-wrap:hover {color: #${accountTheme.actionbtntext}};")
//Button paging
extraStyles.append(".v-button.buttonPaging.current, .v-button.buttonPaging:hover { color:#${accountTheme.actionbtntext}; }")
//Selection text color of selected item
extraStyles.append(".v-filterselect-suggestpopup .gwt-MenuItem-selected { color:#${accountTheme.actionbtntext}; }")
//Date label of activity stream
extraStyles.append(".activity-list .feed-block-wrap .date-lbl { color:#${accountTheme.actionbtntext};}")
extraStyles.append(".v-button.v-button-block {color:#${accountTheme.actionbtntext};}")
extraStyles.append(".v-context-menu-container .v-context-menu .v-context-submenu:hover {color:#${accountTheme.actionbtntext};}")
extraStyles.append(".toggle-btn-group .v-button.btn-group-default {color:#${accountTheme.actionbtntext};}")
}
if (accountTheme.actionbtnborder != null) {
extraStyles.append(".toggle-btn-group .v-button.btn-group-default {border: 1px solid #${accountTheme.actionbtnborder};}")
extraStyles.append(".v-button.v-button-action-button, .v-button-action-button:focus { border: 1px solid #${accountTheme.actionbtnborder}; }")
}
/* Option Buttons */
if (accountTheme.optionbtn != null) {
extraStyles.append(".v-button.v-button-option-button, .v-button-option-button:focus { background-color: #${accountTheme.optionbtn};}")
extraStyles.append(".splitbutton:hover .v-button-option-button, .v-button-option-button:hover { background-color: ${ColorUtils.darkerColor("#" + accountTheme.optionbtn)};}")
//Set toggle button group background
extraStyles.append(".toggle-btn-group .v-button { background-color: #${accountTheme.optionbtn};}")
extraStyles.append(".toggle-btn-group .v-button:hover { background-color: ${ColorUtils.darkerColor("#" + accountTheme.optionbtn)};}")
}
if (accountTheme.optionbtntext != null) {
extraStyles.append(".v-button.v-button-option-button, .v-button-option-button:focus { color: #${accountTheme.optionbtntext}; }")
extraStyles.append(".toggle-btn-group .v-button { color: #${accountTheme.optionbtntext}; }")
}
if (accountTheme.optionbtnborder != null) {
extraStyles.append(".toggle-btn-group .v-button { border: 1px solid #${accountTheme.optionbtnborder};}")
extraStyles.append(".v-button.v-button-option-button, .v-button-option-button:focus { border: 1px solid #${accountTheme.optionbtnborder}; }")
}
/* Danger Buttons */
if (accountTheme.dangerbtn != null) {
extraStyles.append(".v-button.v-button-danger-button, .v-button-danger-button:focus { background-color: #${accountTheme.dangerbtn}; }")
extraStyles.append(".v-button-danger-button:hover { background-color: ${ColorUtils.darkerColor("#" + accountTheme.dangerbtn, 0.1)}; }")
extraStyles.append(".v-button.v-button-link.danger,.v-button.v-button-link.danger:hover { color: #${accountTheme.dangerbtn}; }")
//Set style of popup content action
extraStyles.append(".optionPopupContent .action-wrap.danger .v-button-action { color: #${accountTheme.dangerbtn}; }")
extraStyles.append(".optionPopupContent .action-wrap.danger:hover {background-color: #${accountTheme.dangerbtn};}")
}
if (accountTheme.dangerbtntext != null) {
extraStyles.append(".v-button.v-button-danger-button, .v-button-danger-button:focus { color: #${accountTheme.dangerbtntext}; }")
}
if (accountTheme.dangerbtnborder != null) {
extraStyles.append(".v-button.v-button-danger-button, .v-button-danger-button:focus { border: 1px solid #${accountTheme.dangerbtnborder}; }")
}
if (extraStyles.isNotBlank()) {
Page.getCurrent().styles.add(extraStyles.toString())
}
Page.getCurrent().styles.add(".window-max-height{max-height: ${UIUtils.browserHeight - 220}px;}")
Page.getCurrent().styles.add(".content-height{min-height: ${UIUtils.browserHeight - 45}px;}")
Page.getCurrent().styles.add(".vertical-tabsheet .v-button-tab.collapsed-tab::after{content: '${String(Character.toChars(VaadinIcons.ANGLE_RIGHT.codepoint))}';" +
"color: #${accountTheme.vtabsheettext};}")
Page.getCurrent().styles.add(".vertical-tabsheet .v-button-tab.un-collapsed-tab::after{content: '${String(Character.toChars(VaadinIcons.ANGLE_DOWN.codepoint))}';" +
"color: #${accountTheme.vtabsheettext};}")
}
@JvmStatic
fun loadDemoTheme(accountTheme: AccountTheme) {
val demoExtraStyles = StringBuilder()
/* Top Menu */
if (accountTheme.topmenubg != null) {
demoExtraStyles.append(".example-block .topNavigation { background-color: #${accountTheme.topmenubg}; }")
}
if (accountTheme.topmenubgselected != null) {
demoExtraStyles.append(".example-block .topNavigation .service-menu.v-buttongroup .v-button.selected { background-color: #${accountTheme.topmenubgselected}; }")
}
if (accountTheme.topmenutext != null) {
demoExtraStyles.append(".example-block .topNavigation .v-button-caption { color: #${accountTheme.topmenutext}; }")
}
if (accountTheme.topmenutextselected != null) {
demoExtraStyles.append(".example-block .topNavigation .service-menu.v-buttongroup .v-button.selected .v-button-caption { color: #${accountTheme.topmenutextselected}; }")
}
/* Vertical Tabsheet */
if (accountTheme.vtabsheetbg != null) {
demoExtraStyles.append(".example-block .navigator-wrap { background-color: #${accountTheme.vtabsheetbg}; }")
}
if (accountTheme.vtabsheetbgselected != null) {
demoExtraStyles.append(".example-block .vertical-tabsheet .v-button-tab.tab-selected { background-color: #${accountTheme.vtabsheetbgselected}; }")
}
if (accountTheme.vtabsheettext != null) {
demoExtraStyles.append(".example-block .vertical-tabsheet .v-button-tab > .v-button-wrap > .v-button-caption { color: #${accountTheme.vtabsheettext}; }")
}
if (accountTheme.vtabsheettextselected != null) {
demoExtraStyles.append(".example-block .vertical-tabsheet .v-button-tab.tab-selected > .v-button-wrap > .v-button-caption { color: #${accountTheme.vtabsheettextselected}; }")
}
/* Action Buttons */
if (accountTheme.actionbtn != null) {
demoExtraStyles.append(".example-block .v-button.v-button-action-button, .example-block .v-button-action-button:focus { background-color: #${accountTheme.actionbtn}; }")
}
if (accountTheme.actionbtntext != null) {
demoExtraStyles.append(".example-block .v-button.v-button-action-button, .example-block .v-button-action-button:focus { color: #${accountTheme.actionbtntext}; }")
}
if (accountTheme.actionbtnborder != null) {
demoExtraStyles.append(".example-block .v-button.v-button-action-button, .example-block .v-button-action-button:focus { border: 1px solid #${accountTheme.actionbtnborder}; }")
}
/* Option Buttons */
if (accountTheme.optionbtn != null) {
demoExtraStyles.append(".example-block .v-button.v-button-option-button, .example-block .v-button-option-button:focus { background-color: #${accountTheme.optionbtn}; }")
}
if (accountTheme.optionbtntext != null) {
demoExtraStyles.append(".example-block .v-button.v-button-option-button, .example-block .v-button-option-button:focus { color: #${accountTheme.optionbtntext}; }")
}
if (accountTheme.optionbtnborder != null) {
demoExtraStyles.append(".example-block .v-button.v-button-option-button, .example-block .v-button-option-button:focus { border: 1px solid #${accountTheme.optionbtnborder}; }")
}
/* Danger Buttons */
if (accountTheme.dangerbtn != null) {
demoExtraStyles.append(".example-block .v-button.v-button-danger-button, .example-block .v-button-danger-button:focus { background-color: #${accountTheme.dangerbtn}; }")
}
if (accountTheme.dangerbtntext != null) {
demoExtraStyles.append(".example-block .v-button.v-button-danger-button, .example-block .v-button-danger-button:focus { color: #${accountTheme.dangerbtntext}; }")
}
if (accountTheme.dangerbtnborder != null) {
demoExtraStyles.append(".example-block .v-button.v-button-danger-button, .example-block .v-button-danger-button:focus { border: 1px solid #${accountTheme.dangerbtnborder}; }")
}
if (demoExtraStyles.isNotBlank()) {
Page.getCurrent().styles.add(demoExtraStyles.toString())
}
}
}
| agpl-3.0 | 050225358d1f3ed425134e720ace4048 | 60.643333 | 195 | 0.67047 | 3.910552 | false | false | false | false |
nickbutcher/plaid | designernews/src/main/java/io/plaidapp/designernews/domain/GetCommentsWithRepliesAndUsersUseCase.kt | 1 | 2849 | /*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.designernews.domain
import io.plaidapp.core.data.Result
import io.plaidapp.core.designernews.data.users.model.User
import io.plaidapp.core.designernews.domain.model.Comment
import io.plaidapp.core.designernews.domain.model.CommentWithReplies
import io.plaidapp.core.designernews.domain.model.toComment
import io.plaidapp.designernews.data.users.UserRepository
import javax.inject.Inject
/**
* Use case that builds [Comment]s based on comments with replies and users
*/
class GetCommentsWithRepliesAndUsersUseCase @Inject constructor(
private val getCommentsWithReplies: GetCommentsWithRepliesUseCase,
private val userRepository: UserRepository
) {
suspend operator fun invoke(ids: List<Long>): Result<List<Comment>> {
// Get the comments with replies
val commentsWithRepliesResult = getCommentsWithReplies(ids)
if (commentsWithRepliesResult is Result.Error) {
return commentsWithRepliesResult
}
val commentsWithReplies = (commentsWithRepliesResult as? Result.Success)?.data.orEmpty()
// get the ids of the users that posted comments
val userIds = mutableSetOf<Long>()
createUserIds(commentsWithReplies, userIds)
// get the users
val usersResult = userRepository.getUsers(userIds)
val users = if (usersResult is Result.Success) {
usersResult.data
} else {
emptySet()
}
// create the comments based on the comments with replies and users
val comments = createComments(commentsWithReplies, users)
return Result.Success(comments)
}
private fun createUserIds(comments: List<CommentWithReplies>, userIds: MutableSet<Long>) {
comments.forEach {
userIds.add(it.userId)
createUserIds(it.replies, userIds)
}
}
private fun createComments(
commentsWithReplies: List<CommentWithReplies>,
users: Set<User>
): List<Comment> {
val userMapping = users.associateBy(User::id)
return commentsWithReplies.asSequence()
.flatMap(CommentWithReplies::flattenWithReplies)
.map { it.toComment(userMapping[it.userId]) }
.toList()
}
}
| apache-2.0 | a39892064845f6279363bc92d49dc833 | 37.5 | 96 | 0.704458 | 4.493691 | false | false | false | false |
olonho/carkot | translator/src/main/kotlin/org/kotlinnative/translator/llvm/types/LLVMFloatType.kt | 1 | 2790 | package org.kotlinnative.translator.llvm.types
import org.kotlinnative.translator.llvm.LLVMExpression
import org.kotlinnative.translator.llvm.LLVMSingleValue
class LLVMFloatType() : LLVMType() {
override val align = 4
override var size: Int = 4
override val mangle = "Float"
override val typename = "float"
override val defaultValue = "0.0"
override val isPrimitive = true
override fun operatorMinus(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMFloatType(), "fsub float $firstOp, $secondOp")
override fun operatorTimes(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMFloatType(), "fmul float $firstOp, $secondOp")
override fun operatorPlus(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMFloatType(), "fadd float $firstOp, $secondOp")
override fun operatorDiv(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMFloatType(), "fdiv float $firstOp, $secondOp")
override fun operatorInc(firstOp: LLVMSingleValue) =
LLVMExpression(LLVMDoubleType(), "fadd float $firstOp, 1.0")
override fun operatorDec(firstOp: LLVMSingleValue) =
LLVMExpression(LLVMDoubleType(), "fsub float $firstOp, 1.0")
override fun operatorLt(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMBooleanType(), "fcmp olt float $firstOp, $secondOp")
override fun operatorGt(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMBooleanType(), "fcmp ogt float $firstOp, $secondOp")
override fun operatorLeq(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMBooleanType(), "fcmp ole float i32 $firstOp, $secondOp")
override fun operatorGeq(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMBooleanType(), "fcmp oge float i32 $firstOp, $secondOp")
override fun operatorEq(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMBooleanType(), "fcmp oeq float" + (if ((firstOp.pointer > 0) || (secondOp.pointer > 0)) "*" else "") + " $firstOp, $secondOp")
override fun operatorNeq(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMBooleanType(), "fcmp one float" + (if ((firstOp.pointer > 0) || (secondOp.pointer > 0)) "*" else "") + " $firstOp, $secondOp")
override fun operatorMod(firstOp: LLVMSingleValue, secondOp: LLVMSingleValue) =
LLVMExpression(LLVMFloatType(), "frem float $firstOp, $secondOp")
override fun equals(other: Any?) =
other is LLVMFloatType
override fun hashCode() =
typename.hashCode()
} | mit | f1cc30692726e810b111d66cf1289a3f | 44.754098 | 157 | 0.705735 | 4.096916 | false | false | false | false |
nickbutcher/plaid | core/src/main/java/io/plaidapp/core/designernews/data/login/LoginRepository.kt | 1 | 2362 | /*
* 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
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package io.plaidapp.core.designernews.data.login
import io.plaidapp.core.data.Result
import io.plaidapp.core.designernews.data.login.model.LoggedInUser
/**
* Repository that handles Designer News login data. It knows what data sources need to be
* triggered to login and where to store the data, once the user was logged in.
*/
class LoginRepository(
private val localDataSource: LoginLocalDataSource,
private val remoteDataSource: LoginRemoteDataSource
) {
// local cache of the user object, so we don't retrieve it from the local storage every time
// we need it
var user: LoggedInUser? = null
private set
val isLoggedIn: Boolean
get() = user != null
init {
user = localDataSource.user
}
fun logout() {
user = null
localDataSource.logout()
remoteDataSource.logout()
}
suspend fun login(username: String, password: String): Result<LoggedInUser> {
val result = remoteDataSource.login(username, password)
if (result is Result.Success) {
setLoggedInUser(result.data)
}
return result
}
private fun setLoggedInUser(loggedInUser: LoggedInUser) {
user = loggedInUser
localDataSource.user = user
}
companion object {
@Volatile
private var INSTANCE: LoginRepository? = null
fun getInstance(
localDataSource: LoginLocalDataSource,
remoteDataSource: LoginRemoteDataSource
): LoginRepository {
return INSTANCE ?: synchronized(this) {
INSTANCE ?: LoginRepository(
localDataSource,
remoteDataSource
).also { INSTANCE = it }
}
}
}
}
| apache-2.0 | 5f934aecb809dedf8368cf29a1a5320e | 28.525 | 96 | 0.658764 | 4.840164 | false | false | false | false |
soywiz/korge | korge-dragonbones/src/commonMain/kotlin/com/dragonbones/parser/DataParser.kt | 1 | 10028 | /**
* The MIT License (MIT)
*
* Copyright (c) 2012-2018 DragonBones team and other contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
package com.dragonbones.parser
import com.dragonbones.core.*
import com.dragonbones.model.*
import com.soywiz.korio.serialization.json.*
/**
* @private
*/
@Suppress("unused", "MayBeConstant", "MemberVisibilityCanBePrivate", "FunctionName")
abstract class DataParser(val pool: BaseObjectPool) {
companion object {
val DATA_VERSION_2_3: String = "2.3"
val DATA_VERSION_3_0: String = "3.0"
val DATA_VERSION_4_0: String = "4.0"
val DATA_VERSION_4_5: String = "4.5"
val DATA_VERSION_5_0: String = "5.0"
val DATA_VERSION_5_5: String = "5.5"
val DATA_VERSION_5_6: String = "5.6"
val DATA_VERSION: String = DataParser.DATA_VERSION_5_6
val DATA_VERSIONS: Array<String> = arrayOf(
DataParser.DATA_VERSION_4_0,
DataParser.DATA_VERSION_4_5,
DataParser.DATA_VERSION_5_0,
DataParser.DATA_VERSION_5_5,
DataParser.DATA_VERSION_5_6
)
val TEXTURE_ATLAS: String = "textureAtlas"
val SUB_TEXTURE: String = "SubTexture"
val FORMAT: String = "format"
val IMAGE_PATH: String = "imagePath"
val WIDTH: String = "width"
val HEIGHT: String = "height"
val ROTATED: String = "rotated"
val FRAME_X: String = "frameX"
val FRAME_Y: String = "frameY"
val FRAME_WIDTH: String = "frameWidth"
val FRAME_HEIGHT: String = "frameHeight"
val DRADON_BONES: String = "dragonBones"
val USER_DATA: String = "userData"
val ARMATURE: String = "armature"
val CANVAS: String = "canvas"
val BONE: String = "bone"
val SURFACE: String = "surface"
val SLOT: String = "slot"
val CONSTRAINT: String = "constraint"
val SKIN: String = "skin"
val DISPLAY: String = "display"
val FRAME: String = "frame"
val IK: String = "ik"
val PATH_CONSTRAINT: String = "path"
val ANIMATION: String = "animation"
val TIMELINE: String = "timeline"
val FFD: String = "ffd"
val TRANSLATE_FRAME: String = "translateFrame"
val ROTATE_FRAME: String = "rotateFrame"
val SCALE_FRAME: String = "scaleFrame"
val DISPLAY_FRAME: String = "displayFrame"
val COLOR_FRAME: String = "colorFrame"
val DEFAULT_ACTIONS: String = "defaultActions"
val ACTIONS: String = "actions"
val EVENTS: String = "events"
val INTS: String = "ints"
val FLOATS: String = "floats"
val STRINGS: String = "strings"
val TRANSFORM: String = "transform"
val PIVOT: String = "pivot"
val AABB: String = "aabb"
val COLOR: String = "color"
val VERSION: String = "version"
val COMPATIBLE_VERSION: String = "compatibleVersion"
val FRAME_RATE: String = "frameRate"
val TYPE: String = "type"
val SUB_TYPE: String = "subType"
val NAME: String = "name"
val PARENT: String = "parent"
val TARGET: String = "target"
val STAGE: String = "stage"
val SHARE: String = "share"
val PATH: String = "path"
val LENGTH: String = "length"
val DISPLAY_INDEX: String = "displayIndex"
val Z_ORDER: String = "zOrder"
val Z_INDEX: String = "zIndex"
val BLEND_MODE: String = "blendMode"
val INHERIT_TRANSLATION: String = "inheritTranslation"
val INHERIT_ROTATION: String = "inheritRotation"
val INHERIT_SCALE: String = "inheritScale"
val INHERIT_REFLECTION: String = "inheritReflection"
val INHERIT_ANIMATION: String = "inheritAnimation"
val INHERIT_DEFORM: String = "inheritDeform"
val SEGMENT_X: String = "segmentX"
val SEGMENT_Y: String = "segmentY"
val BEND_POSITIVE: String = "bendPositive"
val CHAIN: String = "chain"
val WEIGHT: String = "weight"
val BLEND_TYPE: String = "blendType"
val FADE_IN_TIME: String = "fadeInTime"
val PLAY_TIMES: String = "playTimes"
val SCALE: String = "scale"
val OFFSET: String = "offset"
val POSITION: String = "position"
val DURATION: String = "duration"
val TWEEN_EASING: String = "tweenEasing"
val TWEEN_ROTATE: String = "tweenRotate"
val TWEEN_SCALE: String = "tweenScale"
val CLOCK_WISE: String = "clockwise"
val CURVE: String = "curve"
val SOUND: String = "sound"
val EVENT: String = "event"
val ACTION: String = "action"
val X: String = "x"
val Y: String = "y"
val SKEW_X: String = "skX"
val SKEW_Y: String = "skY"
val SCALE_X: String = "scX"
val SCALE_Y: String = "scY"
val VALUE: String = "value"
val ROTATE: String = "rotate"
val SKEW: String = "skew"
val ALPHA: String = "alpha"
val ALPHA_OFFSET: String = "aO"
val RED_OFFSET: String = "rO"
val GREEN_OFFSET: String = "gO"
val BLUE_OFFSET: String = "bO"
val ALPHA_MULTIPLIER: String = "aM"
val RED_MULTIPLIER: String = "rM"
val GREEN_MULTIPLIER: String = "gM"
val BLUE_MULTIPLIER: String = "bM"
val UVS: String = "uvs"
val VERTICES: String = "vertices"
val TRIANGLES: String = "triangles"
val WEIGHTS: String = "weights"
val SLOT_POSE: String = "slotPose"
val BONE_POSE: String = "bonePose"
val BONES: String = "bones"
val POSITION_MODE: String = "positionMode"
val SPACING_MODE: String = "spacingMode"
val ROTATE_MODE: String = "rotateMode"
val SPACING: String = "spacing"
val ROTATE_OFFSET: String = "rotateOffset"
val ROTATE_MIX: String = "rotateMix"
val TRANSLATE_MIX: String = "translateMix"
val TARGET_DISPLAY: String = "targetDisplay"
val CLOSED: String = "closed"
val CONSTANT_SPEED: String = "constantSpeed"
val VERTEX_COUNT: String = "vertexCount"
val LENGTHS: String = "lengths"
val GOTO_AND_PLAY: String = "gotoAndPlay"
val DEFAULT_NAME: String = "default"
fun _getArmatureType(value: String?): ArmatureType {
return when (value?.toLowerCase()) {
null -> ArmatureType.Armature
"stage" -> ArmatureType.Stage
"armature" -> ArmatureType.Armature
"movieclip" -> ArmatureType.MovieClip
else -> ArmatureType.Armature
}
}
fun _getBoneTypeIsSurface(value: String?): Boolean {
return when (value?.toLowerCase()) {
null -> false
"bone" -> false
"surface" -> true
else -> false
}
}
fun _getPositionMode(value: String?): PositionMode {
return when (value?.toLowerCase()) {
null -> PositionMode.Percent
"percent" -> PositionMode.Percent
"fixed" -> PositionMode.Fixed
else -> PositionMode.Percent
}
}
fun _getSpacingMode(value: String?): SpacingMode {
return when (value?.toLowerCase()) {
null -> SpacingMode.Length
"length" -> SpacingMode.Length
"percent" -> SpacingMode.Percent
"fixed" -> SpacingMode.Fixed
else -> SpacingMode.Length
}
}
fun _getRotateMode(value: String?): RotateMode {
return when (value?.toLowerCase()) {
null -> RotateMode.Tangent
"tangent" -> RotateMode.Tangent
"chain" -> RotateMode.Chain
"chainscale" -> RotateMode.ChainScale
else -> RotateMode.Tangent
}
}
fun _getDisplayType(value: String?): DisplayType {
return when (value?.toLowerCase()) {
null -> DisplayType.Image
"image" -> DisplayType.Image
"mesh" -> DisplayType.Mesh
"armature" -> DisplayType.Armature
"boundingbox" -> DisplayType.BoundingBox
"path" -> DisplayType.Path
else -> DisplayType.Image
}
}
fun _getBoundingBoxType(value: String?): BoundingBoxType {
return when (value?.toLowerCase()) {
null -> BoundingBoxType.Rectangle
"rectangle" -> BoundingBoxType.Rectangle
"ellipse" -> BoundingBoxType.Ellipse
"polygon" -> BoundingBoxType.Polygon
else -> BoundingBoxType.Rectangle
}
}
fun _getBlendMode(value: String?): BlendMode {
return when (value?.toLowerCase()) {
null -> BlendMode.Normal
"normal" -> BlendMode.Normal
"add" -> BlendMode.Add
"alpha" -> BlendMode.Alpha
"darken" -> BlendMode.Darken
"difference" -> BlendMode.Difference
"erase" -> BlendMode.Erase
"hardlight" -> BlendMode.HardLight
"invert" -> BlendMode.Invert
"layer" -> BlendMode.Layer
"lighten" -> BlendMode.Lighten
"multiply" -> BlendMode.Multiply
"overlay" -> BlendMode.Overlay
"screen" -> BlendMode.Screen
"subtract" -> BlendMode.Subtract
else -> BlendMode.Normal
}
}
fun _getAnimationBlendType(value: String?): AnimationBlendType {
return when (value?.toLowerCase()) {
null -> AnimationBlendType.None
"none" -> AnimationBlendType.None
"1d" -> AnimationBlendType.E1D
else -> AnimationBlendType.None
}
}
fun _getActionType(value: String?): ActionType {
return when (value?.toLowerCase()) {
null -> ActionType.Play
"play" -> ActionType.Play
"frame" -> ActionType.Frame
"sound" -> ActionType.Sound
else -> ActionType.Play
}
}
fun parseDragonBonesDataJson(data: String, scale: Double = 1.0, pool: BaseObjectPool = BaseObjectPool()): DragonBonesData? {
return ObjectDataParser(pool).parseDragonBonesData(Json.parse(data, Json.Context(optimizedNumericLists = true)), scale)
}
}
abstract fun parseDragonBonesData(rawData: Any?, scale: Double = 1.0): DragonBonesData?
abstract fun parseTextureAtlasData(rawData: Any?, textureAtlasData: TextureAtlasData, scale: Double = 1.0): Boolean
}
| apache-2.0 | 1f07a09ccb90ac5fc72337643a12632c | 31.771242 | 126 | 0.687974 | 3.359464 | false | false | false | false |
apixandru/intellij-community | update-server-mock/src/main/java/com/intellij/updater/mock/Server.kt | 15 | 3657 | /*
* Copyright 2000-2016 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.updater.mock
import com.sun.net.httpserver.HttpServer
import org.apache.logging.log4j.LogManager
import java.net.HttpURLConnection.*
import java.net.InetSocketAddress
import java.net.URI
import java.time.ZonedDateTime
import java.time.format.DateTimeFormatter
class Server(private val port: Int, private val generator: Generator) {
private val server = HttpServer.create()
private val log = LogManager.getLogger(Server::class.java)
private val buildFormat = "([A-Z]+)-([0-9.]+)".toRegex()
private val tsFormat = DateTimeFormatter.ofPattern("dd/MMM/yyyy:kk:mm:ss ZZ")
fun start() {
server.bind(InetSocketAddress(port), 0)
server.createContext("/") { ex ->
val response = try {
process(ex.requestMethod, ex.requestURI)
}
catch(e: Exception) {
log.error(e)
Response(HTTP_INTERNAL_ERROR, "Internal error")
}
try {
val contentType = if (response.type.startsWith("text/")) "${response.type}; charset=utf-8" else response.type
ex.responseHeaders.add("Content-Type", contentType)
ex.sendResponseHeaders(response.code, response.bytes.size.toLong())
ex.responseBody.write(response.bytes)
ex.close()
log.info("${ex.remoteAddress.address.hostAddress} - - [${tsFormat.format(ZonedDateTime.now())}]" +
" \"${ex.requestMethod} ${ex.requestURI}\" ${ex.responseCode} ${response.bytes.size}")
}
catch(e: Exception) {
log.error(e)
}
}
server.start()
}
private fun process(method: String, uri: URI): Response {
val path = uri.path
return when {
method != "GET" -> Response(HTTP_BAD_REQUEST, "Didn't get")
path == "/" -> Response(HTTP_OK, "Mock Update Server")
path == "/updates/updates.xml" -> xml(uri.query ?: "")
path.startsWith("/patches/") -> patch(path)
else -> Response(HTTP_NOT_FOUND, "Miss")
}
}
private fun xml(query: String): Response {
val parameters = query.splitToSequence('&')
.filter { it.startsWith("build") || it.startsWith("eap") }
.map { it.split('=', limit = 2) }
.map { it[0] to if (it.size > 1) it[1] else "" }
.toMap()
val build = parameters["build"]
if (build != null) {
val match = buildFormat.find(build)
val productCode = match?.groups?.get(1)?.value
val buildId = match?.groups?.get(2)?.value
if (productCode != null && buildId != null) {
val xml = generator.generateXml(productCode, buildId, "eap" in parameters)
return Response(HTTP_OK, "text/xml", xml.toByteArray())
}
}
return Response(HTTP_BAD_REQUEST, "Bad parameters")
}
private fun patch(path: String): Response = when {
path.endsWith(".jar") -> Response(HTTP_OK, "binary/octet-stream", generator.generatePatch())
else -> Response(HTTP_BAD_REQUEST, "Bad path")
}
private class Response(val code: Int, val type: String, val bytes: ByteArray) {
constructor(code: Int, text: String) : this(code, "text/plain", text.toByteArray())
}
} | apache-2.0 | 92c3da9030f10ba43fe97da363612463 | 34.862745 | 117 | 0.656276 | 3.845426 | false | false | false | false |
edvin/tornadofx | src/main/java/tornadofx/LayoutDebugger.kt | 1 | 17337 | package tornadofx
import javafx.application.Platform
import javafx.beans.property.DoubleProperty
import javafx.beans.property.Property
import javafx.beans.property.SimpleObjectProperty
import javafx.beans.property.StringProperty
import javafx.event.EventHandler
import javafx.geometry.Bounds
import javafx.geometry.Insets
import javafx.geometry.Pos
import javafx.scene.Node
import javafx.scene.Parent
import javafx.scene.Scene
import javafx.scene.canvas.Canvas
import javafx.scene.control.*
import javafx.scene.input.MouseEvent
import javafx.scene.layout.*
import javafx.scene.paint.Color
import javafx.scene.shape.Shape
import javafx.stage.Modality
import javafx.util.StringConverter
import javafx.util.converter.DoubleStringConverter
@Suppress("UNCHECKED_CAST")
class LayoutDebugger : Fragment() {
override val root = BorderPane()
lateinit var debuggingScene: Scene
private lateinit var debuggingRoot: Parent
val hoveredNode = SimpleObjectProperty<Node>()
val selectedNode = SimpleObjectProperty<Node>()
var nodeTree: TreeView<NodeContainer> by singleAssign()
val propertyContainer = ScrollPane()
val stackpane = StackPane()
val overlay = Canvas()
val gc = overlay.graphicsContext2D
init {
overlay.isMouseTransparent = true
stackpane += overlay
gc.fill = c("#99bbbb", 0.4)
with(root) {
setPrefSize(800.0, 600.0)
center {
splitpane {
setDividerPosition(0, 0.3)
treeview<NodeContainer> {
nodeTree = this
}
this += propertyContainer.apply {
paddingAll = 10
}
}
}
}
hookListeners()
}
private fun hookListeners() {
nodeTree.selectionModel.selectedItemProperty().onChange {
if (it?.value != null) setSelectedNode(it.value.node)
}
// Position overlay over hovered node
hoveredNode.addListener { observableValue, oldNode, newNode ->
if (oldNode != newNode && newNode != null)
positionOverlayOver(newNode)
else if (newNode == null && oldNode != null)
clearOverlay()
}
}
private fun positionOverlayOver(node: Node) {
val p = node.localToScene(node.boundsInLocal)
clearOverlay()
gc.fillRect(p.minX, p.minY, p.width, p.height)
}
private fun clearOverlay() {
gc.clearRect(0.0, 0.0, overlay.width, overlay.height)
}
val hoverHandler = EventHandler<MouseEvent> { event ->
val newHover = event.target
if (newHover is Node && hoveredNode.value != newHover)
hoveredNode.value = newHover
}
val sceneExitedHandler = EventHandler<MouseEvent> { event ->
hoveredNode.value = null
}
val clickHandler = EventHandler<MouseEvent> { event ->
val clickedTarget = event.target
if (clickedTarget is Node) setSelectedNode(clickedTarget)
event.consume()
}
private fun setSelectedNode(node: Node) {
selectedNode.value = node
val treeItem = selectedNode.value.properties["tornadofx.layoutdebugger.treeitem"]
if (treeItem is NodeTreeItem) {
nodeTree.selectionModel.select(treeItem)
propertyContainer.nodePropertyView(treeItem.value.node)
}
}
override fun onDock() {
// Prevent the debugger from being reloaded
Platform.runLater {
modalStage!!.scene.properties["tornadofx.layoutdebugger"] = this
}
title = "Layout Debugger [%s]".format(debuggingScene)
with(debuggingScene) {
// Prevent the scene from being reloaded while the debugger is running
properties["tornadofx.layoutdebugger"] = this@LayoutDebugger
addEventFilter(MouseEvent.MOUSE_EXITED, sceneExitedHandler)
addEventFilter(MouseEvent.MOUSE_MOVED, hoverHandler)
addEventFilter(MouseEvent.MOUSE_CLICKED, clickHandler)
}
// Overlay has same size as scene
overlay.widthProperty().cleanBind(debuggingScene.widthProperty())
overlay.heightProperty().cleanBind(debuggingScene.heightProperty())
// Stackpane becomes the new scene root and contains the currentScene.root and our overlay
debuggingRoot = debuggingScene.root
stackpane += debuggingRoot
stackpane += debuggingRoot
debuggingScene.root = stackpane
overlay.toFront()
// Populate the node tree
with(nodeTree) {
root = NodeTreeItem(NodeContainer(debuggingRoot))
populate(
itemFactory = { NodeTreeItem(it) },
childFactory = { it.value.node.getChildList()?.map(::NodeContainer) }
)
// Hover on a node in the tree should visualize in the scene graph
setCellFactory {
object : TreeCell<NodeContainer>() {
init {
addEventFilter(MouseEvent.MOUSE_ENTERED) {
item?.apply {
hoveredNode.value = node
style {
backgroundColor += gc.fill
}
}
}
addEventFilter(MouseEvent.MOUSE_EXITED) {
hoveredNode.value = null
style {
backgroundColor = multi()
}
}
}
override fun updateItem(item: NodeContainer?, empty: Boolean) {
super.updateItem(item, empty)
graphic = null
text = null
if (!empty && item != null)
text = item.node.javaClass.name.substringAfterLast("\\$").substringAfterLast(".")
}
}
}
}
}
override fun onUndock() {
debuggingRoot.removeFromParent()
debuggingScene.root = debuggingRoot
debuggingScene.properties["tornadofx.layoutdebugger"] = null
debuggingScene.removeEventFilter(MouseEvent.MOUSE_MOVED, hoverHandler)
debuggingScene.removeEventFilter(MouseEvent.MOUSE_CLICKED, clickHandler)
}
companion object {
fun debug(scene: Scene) = with(find<LayoutDebugger>()) {
debuggingScene = scene
openModal(modality = Modality.NONE)
}
}
class NodeContainer(val node: Node)
inner class NodeTreeItem(container: NodeContainer) : TreeItem<NodeContainer>(container) {
init {
container.node.properties["tornadofx.layoutdebugger.treeitem"] = this
}
}
/**
* Property editor for node. We can't bind directly to these properties as
* they might have app bindings already, so we have to jump through some hoops
* to synchronize values between this editor and the Node properties.
*/
fun ScrollPane.nodePropertyView(node: Node) = form {
fieldset("Node info") {
field("ClassName") {
text(node.javaClass.name)
}
field("StyleClass") {
text(node.styleClass.joinToString(", ") { ".$it" })
}
field("Id") {
text(node.id ?: "")
}
}
fieldset("Dimensions") {
fun Bounds.describe() = "(${minX.toInt()}, ${width.toInt()}), (${minY.toInt()}, ${height.toInt()})"
field("Layout bounds") {
label(node.layoutBounds.describe())
}
field("Bounds in parent") {
label(node.boundsInParent.describe())
}
field("Bounds in local") {
label(node.boundsInLocal.describe())
}
}
fieldset("Properties") {
if (node is Labeled) {
field("Text") {
textfield() {
textProperty().shadowBindTo(node.textProperty())
prefColumnCount = 30
}
}
}
if (node is TextInputControl) {
field("Text") {
textfield(node.text) {
prefColumnCount = 30
textProperty().shadowBindTo(node.textProperty())
}
}
}
if (node is Shape) {
field("Fill") {
colorpicker(node.fill as? Color) {
valueProperty().onChange { newValue ->
node.fillProperty().unbind()
node.fill = newValue
}
}
}
}
if (node.parent is HBox) {
field("HBox Grow") {
combobox<Priority> {
items = observableListOf(Priority.SOMETIMES, Priority.ALWAYS, Priority.NEVER)
value = HBox.getHgrow(node) ?: Priority.NEVER
valueProperty().onChange {
HBox.setHgrow(node, it)
}
}
}
field("HBox Margin") {
textfield(InsetsConverter().toString(HBox.getMargin(node))) {
textProperty().onChange {
HBox.setMargin(node, InsetsConverter().fromString(it))
}
prefColumnCount = 10
}
}
}
if (node.parent is VBox) {
field("VBox Grow") {
combobox<Priority> {
items = observableListOf(Priority.SOMETIMES, Priority.ALWAYS, Priority.NEVER)
value = VBox.getVgrow(node) ?: Priority.NEVER
valueProperty().onChange {
VBox.setVgrow(node, it)
}
}
}
field("VBox Margin") {
textfield(InsetsConverter().toString(VBox.getMargin(node))) {
textProperty().onChange {
VBox.setMargin(node, InsetsConverter().fromString(it))
}
prefColumnCount = 10
}
}
}
if (node is HBox) {
alignmentCombo(node.alignmentProperty())
spacingEditor(node.spacingProperty())
}
if (node is VBox) {
alignmentCombo(node.alignmentProperty())
spacingEditor(node.spacingProperty())
}
if (node is StackPane) alignmentCombo(node.alignmentProperty())
if (node is FlowPane) alignmentCombo(node.alignmentProperty())
if (node is TitledPane) alignmentCombo(node.alignmentProperty())
if (node is GridPane) alignmentCombo(node.alignmentProperty())
if (node is Region) {
// Background/fills is immutable, so a new background object must be created with the augmented fill
if (!node.background?.fills.isNullOrEmpty()) {
field("Background fill") {
vbox(3.0) {
node.background.fills.forEachIndexed { i, backgroundFill ->
val initialColor: Color? = backgroundFill.fill as? Color
colorpicker(initialColor) {
isEditable = true
valueProperty().onChange { newColor ->
val newFills = node.background.fills.mapIndexed { ix, fill ->
if (ix == i) BackgroundFill(newColor, fill.radii, fill.insets)
else fill
}
node.backgroundProperty().unbind()
node.background = Background(newFills, node.background.images)
}
}
}
}
}
} else {
// Add one background color if none present
field("Background fill") {
colorpicker() {
isEditable = true
valueProperty().addListener { observableValue, oldColor, newColor ->
node.background = Background(BackgroundFill(newColor, null, null))
}
}
}
}
// Padding
field("Padding") {
textfield() {
textProperty().shadowBindTo(node.paddingProperty(), InsetsConverter())
prefColumnCount = 10
}
}
field("Pref/min/max width") {
textfield() {
textProperty().shadowBindTo(node.prefWidthProperty(), DoubleStringConverter())
prefColumnCount = 10
}
textfield() {
textProperty().shadowBindTo(node.minWidthProperty(), DoubleStringConverter())
prefColumnCount = 10
}
textfield() {
textProperty().shadowBindTo(node.maxWidthProperty(), DoubleStringConverter())
prefColumnCount = 10
}
}
field("Pref/min/max height") {
textfield {
textProperty().shadowBindTo(node.prefHeightProperty(), DoubleStringConverter())
prefColumnCount = 10
}
textfield {
textProperty().shadowBindTo(node.minHeightProperty(), DoubleStringConverter())
prefColumnCount = 10
}
textfield {
textProperty().shadowBindTo(node.maxHeightProperty(), DoubleStringConverter())
prefColumnCount = 10
}
}
}
}
}
private fun Fieldset.spacingEditor(spacingProperty: DoubleProperty) {
field("Spacing") {
textfield {
textProperty().shadowBindTo(spacingProperty, DoubleStringConverter())
prefColumnCount = 10
}
}
}
fun Fieldset.alignmentCombo(property: Property<Pos>) {
field("Alignment") {
combobox<Pos> {
items = observableListOf(Pos.TOP_LEFT, Pos.TOP_CENTER, Pos.TOP_RIGHT, Pos.CENTER_LEFT, Pos.CENTER, Pos.CENTER_RIGHT, Pos.BOTTOM_LEFT,
Pos.BOTTOM_CENTER, Pos.BOTTOM_RIGHT, Pos.BASELINE_LEFT, Pos.BASELINE_CENTER, Pos.BASELINE_RIGHT)
valueProperty().shadowBindTo(property)
}
}
}
class InsetsConverter : StringConverter<Insets>() {
override fun toString(v: Insets?) = if (v == null) "" else "${v.top.s()} ${v.right.s()} ${v.bottom.s()} ${v.left.s()}"
override fun fromString(s: String?): Insets {
try {
if (s.isNullOrBlank()) return Insets.EMPTY
val parts = s.split(" ")
if (parts.size == 1) return Insets(s.toDouble())
if (parts.size == 2) return Insets(parts[0].toDouble(), parts[1].toDouble(), parts[0].toDouble(), parts[1].toDouble())
if (parts.size == 4) return Insets(parts[0].toDouble(), parts[1].toDouble(), parts[2].toDouble(), parts[3].toDouble())
} catch (ignored: Exception) {
}
return Insets.EMPTY
}
private fun Double.s(): String {
if (this == 0.0) return "0"
val s = toString()
if (s.endsWith(".0")) return s.substringBefore(".")
return s
}
}
fun <T> Property<T>.shadowBindTo(nodeProperty: Property<T>) {
bindBidirectional(object : SimpleObjectProperty<T>(nodeProperty.value) {
override fun set(newValue: T?) {
super.set(newValue)
nodeProperty.unbind()
nodeProperty.value = newValue
}
})
}
inline fun <reified T, reified C : StringConverter<out T>> StringProperty.shadowBindTo(nodeProperty: Property<T>, converter: C) {
bindBidirectional(object : SimpleObjectProperty<T>(nodeProperty.value) {
override fun set(newValue: T?) {
super.set(newValue)
nodeProperty.unbind()
nodeProperty.value = newValue
}
}, converter as StringConverter<T>)
}
} | apache-2.0 | 5a880d985e3d5adc4a9fbac28705d661 | 37.700893 | 149 | 0.507989 | 5.495087 | false | false | false | false |
AromaTech/banana-data-operations | src/main/java/tech/aroma/data/sql/SQLActivityRepository.kt | 3 | 6180 | /*
* Copyright 2017 RedRoma, 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 tech.aroma.data.sql
import org.slf4j.LoggerFactory
import org.springframework.dao.EmptyResultDataAccessException
import org.springframework.jdbc.core.JdbcOperations
import tech.aroma.data.ActivityRepository
import tech.aroma.data.sql.SQLStatements.*
import tech.aroma.thrift.LengthOfTime
import tech.aroma.thrift.User
import tech.aroma.thrift.events.Event
import tech.aroma.thrift.exceptions.DoesNotExistException
import tech.aroma.thrift.exceptions.InvalidArgumentException
import tech.sirwellington.alchemy.arguments.AlchemyAssertion
import tech.sirwellington.alchemy.arguments.Arguments.checkThat
import tech.sirwellington.alchemy.arguments.assertions.*
import tech.sirwellington.alchemy.thrift.ThriftObjects
import javax.inject.Inject
/**
*
* @author SirWellington
*/
internal class SQLActivityRepository
@Inject constructor(val database: JdbcOperations, val serializer: DatabaseSerializer<Event>) : ActivityRepository
{
private companion object
{
@JvmStatic private val LOG = LoggerFactory.getLogger(this::class.java)!!
}
override fun saveEvent(event: Event, forUser: User, lifetime: LengthOfTime?)
{
checkEventId(event.eventId)
val user = forUser
checkUser(user)
val recepientId = user.userId.toUUID()
val eventId = event.eventId.toUUID()
val appId = event.applicationId.toUUID()
val actorId = event.userIdOfActor.toUUID()
val serialized = try
{
ThriftObjects.toJson(event)
}
catch (ex: Exception)
{
val message = "Failed to serialize event [$event]"
failWithMessage(message, ex)
}
val eventType = event.eventType?.toString()
val timestamp = if (event.timestamp > 0) event.timestamp.toTimestamp() else Timestamps.now()
val sql = Inserts.ACTIVITY_EVENT
try
{
database.update(sql,
recepientId,
eventId,
appId,
actorId,
timestamp,
eventType,
serialized)
}
catch(ex: Exception)
{
val message = "Failed to save event [$event] for user [$recepientId]"
failWithMessage(message, ex)
}
}
override fun containsEvent(eventId: String, user: User): Boolean
{
checkEventId(eventId)
checkUser(user)
val eventId = eventId.toUUID()
val userId = user.userId.toUUID()
val sql = Queries.CHECK_ACTIVITY_EVENT
return try
{
database.queryForObject(sql, Boolean::class.java, userId, eventId)
}
catch(ex: Exception)
{
val message = "Failed to check if event exists: [$userId/$eventId]"
failWithMessage(message, ex)
}
}
override fun getEvent(eventId: String, user: User): Event
{
checkEventId(eventId)
checkUser(user)
val sql = Queries.SELECT_ACTIVITY_EVENT
val eventId = eventId.toUUID()
val userId = user.userId.toUUID()
return try
{
database.queryForObject(sql, serializer, userId, eventId)
}
catch (ex: EmptyResultDataAccessException)
{
val message = "Activity Event does not exist: [$userId/$eventId]"
LOG.warn(message, ex)
throw DoesNotExistException(message)
}
catch (ex: Exception)
{
val message = "Failed to get event [$userId/$eventId]"
failWithMessage(message, ex)
}
}
override fun getAllEventsFor(user: User): MutableList<Event>
{
checkUser(user)
val userId = user.userId.toUUID()
val sql = Queries.SELECT_ALL_ACTIVITY_FOR_USER
return try
{
database.query(sql, serializer, userId) ?: mutableListOf()
}
catch(ex: Exception)
{
val message = "Failed to get all events for user [$userId]"
failWithMessage(message, ex)
}
}
override fun deleteEvent(eventId: String, user: User)
{
checkEventId(eventId)
checkUser(user)
val userId = user.userId.toUUID()
val eventId = eventId.toUUID()
val sql = Deletes.ACTIVITY_EVENT
try
{
val deleted = database.update(sql, userId, eventId)
LOG.debug("Operation to delete activity [$userId/$eventId] affected $deleted rows")
}
catch(ex: Exception)
{
val message = "Failed to delete Activity Event [$userId/$eventId]"
failWithMessage(message, ex)
}
}
override fun deleteAllEventsFor(user: User)
{
checkUser(user)
val userId = user.userId.toUUID()
val sql = Deletes.ACTIVITY_ALL_EVENTS
try
{
val deleted = database.update(sql, userId)
LOG.debug("Operation to clear Activity for user [$userId] affected $deleted rows")
}
catch (ex: Exception)
{
val message = "Failed to delete all messages for user [$user]"
failWithMessage(message, ex)
}
}
private fun checkEventId(eventId: String?)
{
checkThat(eventId)
.throwing(InvalidArgumentException::class.java)
.usingMessage("Invalid Event ID : $eventId")
.isA(validUUID() as AlchemyAssertion<String?>)
}
} | apache-2.0 | 3f19dc015985eb837066b94cf1c50c7b | 28.716346 | 113 | 0.611165 | 4.706778 | false | false | false | false |
Xenoage/Zong | core/src/com/xenoage/zong/core/music/time/TimeType.kt | 1 | 3510 | package com.xenoage.zong.core.music.time
import com.xenoage.utils.annotations.Optimized
import com.xenoage.utils.annotations.Reason.MemorySaving
import com.xenoage.utils.math.Fraction
import com.xenoage.utils.math.Fraction.Companion.fr
/**
* Type of a time signature, e.g. a 4/4, alla breve or senza misura time.
*
* This class includes some common instances which may be reused.
*
* A senza-misura element time indicates that there is no time signature.
* Thus as many beats as needed are allowed for each measure.
*/
class TimeType private constructor(
/** The time fraction (numerator and denominator).
* The beats per measure this time signature allows, e.g. (4/4) or (3/4).
* 0 means: Undefined, so as many beats as needed are allowed. */
val numerator: Int,
val denominator: Int,
/** The symbol of this time signature. For example, a (2/2) time may be represented
* by a normal fraction or by a alla breve symbol. */
val symbol: Symbol,
/** The accentuation of each beat. For example, usually a 4/4 time has `[x . . .]`
* and 6/8 has `[x . . x . .]`. `x` means accentuated (true in the array),
* `.` means unaccentuated (false in the array).
* If there are no beats (senza misura), the array is empty. */
val beatsAccentuation: BooleanArray
) {
/** The beats of a measure in this time, or null for senza misura. */
val measureBeats: Fraction? =
if (numerator == 0 || denominator == 0) null else fr(numerator, denominator)
companion object {
/** 2/2 time. */
val time_2_2 = TimeType(2, 2,
Symbol.Fractional, booleanArrayOf(true, false))
/** 2/4 time. */
val time_2_4 = TimeType(2, 4,
Symbol.Fractional, booleanArrayOf(true, false))
/** 3/4 time. */
val time_3_4 = TimeType(3, 4,
Symbol.Fractional, booleanArrayOf(true, false, false))
/** 4/4 time. */
val time_4_4 = TimeType(4, 4,
Symbol.Fractional, booleanArrayOf(true, false, false, false))
/** 6/8 time. */
val time_6_8 = TimeType(6, 8,
Symbol.Fractional, booleanArrayOf(true, false, false, true, false, false))
/** Common time. */
val timeCommon = TimeType(4, 4,
Symbol.Common, booleanArrayOf(true, false, false, false))
/** Alla breve time. */
val timeAllaBreve = TimeType(2, 2,
Symbol.AllaBreve, booleanArrayOf(true, false))
/** Senza misura. */
val timeSenzaMisura = TimeType(0, 0,
Symbol.None, BooleanArray(0))
//list of known time types with numerator/denominator
private val knownTypes = arrayOf(time_2_2, time_2_4, time_3_4, time_4_4, time_6_8)
/**
* Returns a [TimeType] with the given numerator and denominator.
* When possible, shared instances are returned.
*/
@Optimized(MemorySaving)
operator fun invoke(numerator: Int, denominator: Int): TimeType {
//look for existing instance
for (t in knownTypes)
if (t.numerator == numerator && t.denominator == denominator)
return t
//create new TimeType. only the first beat is accentuated.
val beatsAccentuation = BooleanArray(numerator)
if (denominator > 0)
beatsAccentuation[0] = true
return TimeType(numerator, denominator, Symbol.Fractional, beatsAccentuation)
}
}
/**
* Symbols for time signatures.
*/
enum class Symbol {
/** No symbol (for senza misura). */
None,
/** Common time symbol ("C") for a 4/4 time signature. */
Common,
/** Alla breve symbol (also known as "cut" symbol) for a 2/2 time signature. */
AllaBreve,
/** TimeSignature signature shown by numbers, e.g. 3/4 or 7/8. */
Fractional
}
}
| agpl-3.0 | 165efca7feaafd6ef3778e09df955e68 | 34.1 | 85 | 0.683191 | 3.240997 | false | false | false | false |
Senspark/ee-x | src/android/facebook_ads/src/main/java/com/ee/internal/FacebookInterstitialAd.kt | 1 | 5107 | package com.ee.internal
import android.app.Activity
import androidx.annotation.AnyThread
import androidx.annotation.UiThread
import com.ee.IFullScreenAd
import com.ee.ILogger
import com.ee.IMessageBridge
import com.ee.Thread
import com.facebook.ads.Ad
import com.facebook.ads.AdError
import com.facebook.ads.InterstitialAd
import com.facebook.ads.InterstitialAdListener
import kotlinx.serialization.Serializable
import java.util.concurrent.atomic.AtomicBoolean
/**
* Created by Zinge on 10/11/17.
*/
internal class FacebookInterstitialAd(
private val _bridge: IMessageBridge,
private val _logger: ILogger,
private var _activity: Activity?,
private val _adId: String)
: IFullScreenAd, InterstitialAdListener {
@Serializable
@Suppress("unused")
private class ErrorResponse(
val code: Int,
val message: String
)
companion object {
private val kTag = FacebookInterstitialAd::class.java.name
}
private val _messageHelper = MessageHelper("FacebookInterstitialAd", _adId)
private val _helper = FullScreenAdHelper(_bridge, this, _messageHelper)
private val _isLoaded = AtomicBoolean(false)
private var _displaying = false
private var _ad: InterstitialAd? = null
init {
_logger.info("$kTag: constructor: adId = $_adId")
registerHandlers()
}
override fun onCreate(activity: Activity) {
_activity = activity
}
override fun onResume() {
}
override fun onPause() {
}
override fun onDestroy() {
_activity = null
}
override fun destroy() {
_logger.info("$kTag: ${this::destroy.name}: adId = $_adId")
deregisterHandlers()
destroyInternalAd()
}
@AnyThread
private fun registerHandlers() {
_helper.registerHandlers()
}
@AnyThread
private fun deregisterHandlers() {
_helper.deregisterHandlers()
}
@UiThread
private fun createInternalAd(): InterstitialAd {
_ad?.let {
return@createInternalAd it
}
val ad = InterstitialAd(_activity, _adId)
_ad = ad
return ad
}
@AnyThread
private fun destroyInternalAd() {
Thread.runOnMainThread {
val ad = _ad ?: return@runOnMainThread
ad.destroy()
_ad = null
}
}
override val isLoaded: Boolean
@AnyThread get() = _isLoaded.get()
@AnyThread
override fun load() {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::load.name}: id = $_adId")
val ad = createInternalAd()
ad.loadAd(ad.buildLoadAdConfig()
.withAdListener(this)
.build())
}
}
@AnyThread
override fun show() {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::show.name}: id = $_adId")
val ad = createInternalAd()
_displaying = true
val result = ad.show(ad.buildShowAdConfig().build())
if (result) {
// OK.
} else {
_isLoaded.set(false)
destroyInternalAd()
_bridge.callCpp(_messageHelper.onFailedToShow, ErrorResponse(-1, "Failed to show ad").serialize())
}
}
}
override fun onAdLoaded(ad: Ad) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onAdLoaded.name} id = $_adId")
_isLoaded.set(true)
_bridge.callCpp(_messageHelper.onLoaded)
}
}
override fun onError(ad: Ad, error: AdError) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onError.name}: id = $_adId message = ${error.errorMessage}")
destroyInternalAd()
if (_displaying) {
_displaying = false
_isLoaded.set(false)
_bridge.callCpp(_messageHelper.onFailedToShow, ErrorResponse(error.errorCode, error.errorMessage).serialize())
} else {
_bridge.callCpp(_messageHelper.onFailedToLoad, ErrorResponse(error.errorCode, error.errorMessage).serialize())
}
}
}
override fun onInterstitialDisplayed(ad: Ad) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onInterstitialDisplayed.name}: id = $_adId")
}
}
override fun onLoggingImpression(ad: Ad) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onLoggingImpression.name}: id = $_adId")
}
}
override fun onAdClicked(ad: Ad) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onAdClicked.name}: id = $_adId")
_bridge.callCpp(_messageHelper.onClicked)
}
}
override fun onInterstitialDismissed(ad: Ad) {
Thread.runOnMainThread {
_logger.debug("$kTag: ${this::onInterstitialDismissed.name}: id = $_adId")
_displaying = false
_isLoaded.set(false)
destroyInternalAd()
_bridge.callCpp(_messageHelper.onClosed)
}
}
} | mit | cc8516cf1e6954c956c91b69b9757a44 | 27.696629 | 126 | 0.596045 | 4.519469 | false | false | false | false |
charleskorn/batect | app/src/unitTest/kotlin/batect/logging/ApplicationInfoLoggerSpec.kt | 1 | 3782 | /*
Copyright 2017-2020 Charles Korn.
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 batect.logging
import batect.VersionInfo
import batect.docker.client.DockerSystemInfoClient
import batect.docker.client.DockerVersionInfoRetrievalResult
import batect.os.OperatingSystem
import batect.os.SystemInfo
import batect.testutils.InMemoryLogSink
import batect.testutils.hasMessage
import batect.testutils.on
import batect.testutils.withAdditionalData
import batect.testutils.withLogMessage
import batect.testutils.withSeverity
import com.google.common.jimfs.Configuration
import com.google.common.jimfs.Jimfs
import com.natpryce.hamkrest.assertion.assertThat
import com.natpryce.hamkrest.equalTo
import com.natpryce.hamkrest.hasSize
import com.nhaarman.mockitokotlin2.doReturn
import com.nhaarman.mockitokotlin2.mock
import org.spekframework.spek2.Spek
import org.spekframework.spek2.style.specification.describe
object ApplicationInfoLoggerSpec : Spek({
describe("an application info logger") {
val logSink = InMemoryLogSink()
val logger = Logger("applicationInfo", logSink)
val versionInfo = VersionInfo()
val fileSystem = Jimfs.newFileSystem(Configuration.unix())
val systemInfo = SystemInfo(OperatingSystem.Linux, "1.2.3", "line-separator", "4.5.6", "me", fileSystem.getPath("/home"), fileSystem.getPath("/tmp"))
val environmentVariables = mapOf("PATH" to "/bin:/usr/bin:/usr/local/bin")
val dockerSystemInfoClient = mock<DockerSystemInfoClient> {
on { getDockerVersionInfo() } doReturn DockerVersionInfoRetrievalResult.Failed("Docker version 1.2.3.4")
}
val infoLogger = ApplicationInfoLogger(logger, versionInfo, systemInfo, dockerSystemInfoClient, environmentVariables)
on("logging application information") {
val commandLineArgs = listOf("some", "values")
infoLogger.logApplicationInfo(commandLineArgs)
it("writes a single message to the logger") {
assertThat(logSink.loggedMessages, hasSize(equalTo(1)))
}
it("writes the message at info severity") {
assertThat(logSink, hasMessage(withSeverity(Severity.Info)))
}
it("writes the message with an explanatory message") {
assertThat(logSink, hasMessage(withLogMessage("Application started.")))
}
it("includes the application command line") {
assertThat(logSink, hasMessage(withAdditionalData("commandLine", commandLineArgs)))
}
it("includes application version information") {
assertThat(logSink, hasMessage(withAdditionalData("versionInfo", versionInfo)))
}
it("includes system information") {
assertThat(logSink, hasMessage(withAdditionalData("systemInfo", systemInfo)))
}
it("includes the Docker version") {
assertThat(logSink, hasMessage(withAdditionalData("dockerVersionInfo", "(Docker version 1.2.3.4)")))
}
it("includes environment variables") {
assertThat(logSink, hasMessage(withAdditionalData("environment", environmentVariables)))
}
}
}
})
| apache-2.0 | a8d7e9493ca781a7d8872b1a41cf2251 | 40.56044 | 157 | 0.703332 | 4.963255 | false | true | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/ui/menu/BottomSheetMenu.kt | 1 | 1550 | package com.habitrpg.android.habitica.ui.menu
import android.content.Context
import android.view.View
import com.google.android.material.bottomsheet.BottomSheetBehavior
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.habitrpg.android.habitica.databinding.MenuBottomSheetBinding
class BottomSheetMenu(context: Context) : BottomSheetDialog(context), View.OnClickListener {
private var binding = MenuBottomSheetBinding.inflate(layoutInflater)
private var runnable: ((Int) -> Unit)? = null
init {
setContentView(binding.root)
binding.titleView.visibility = View.GONE
val behavior = BottomSheetBehavior.from(binding.root.parent as View)
behavior.state = BottomSheetBehavior.STATE_EXPANDED
behavior.peekHeight = 0
}
fun setSelectionRunnable(runnable: (Int) -> Unit) {
this.runnable = runnable
}
override fun setTitle(title: CharSequence?) {
binding.titleView.text = title
binding.titleView.visibility = View.VISIBLE
}
fun addMenuItem(menuItem: BottomSheetMenuItem) {
val item = menuItem.inflate(this.context, layoutInflater, this.binding.menuItems)
item.setOnClickListener(this)
this.binding.menuItems.addView(item)
}
override fun onClick(v: View) {
if (this.runnable != null) {
val index = this.binding.menuItems.indexOfChild(v)
if (index != -1) {
runnable?.let { it(index) }
this.dismiss()
}
}
}
}
| gpl-3.0 | 9bf9451531410d31b89c903ab35e67d3 | 32.695652 | 92 | 0.683871 | 4.572271 | false | false | false | false |
HabitRPG/habitrpg-android | Habitica/src/main/java/com/habitrpg/android/habitica/helpers/notifications/GuildInviteLocalNotification.kt | 2 | 2105 | package com.habitrpg.android.habitica.helpers.notifications
import android.app.PendingIntent
import android.content.Context
import android.content.Intent
import com.habitrpg.android.habitica.R
import com.habitrpg.android.habitica.extensions.withImmutableFlag
import com.habitrpg.android.habitica.receivers.LocalNotificationActionReceiver
/**
* Created by keithholliday on 7/1/16.
*/
class GuildInviteLocalNotification(context: Context, identifier: String?) : HabiticaLocalNotification(context, identifier) {
override fun configureMainIntent(intent: Intent) {
super.configureMainIntent(intent)
intent.putExtra("groupID", data?.get("groupID"))
}
override fun setNotificationActions(notificationId: Int, data: Map<String, String>) {
super.setNotificationActions(notificationId, data)
val res = context.resources
val acceptInviteIntent = Intent(context, LocalNotificationActionReceiver::class.java)
acceptInviteIntent.action = res.getString(R.string.accept_guild_invite)
val groupID = data.get("groupID")
acceptInviteIntent.putExtra("groupID", groupID)
acceptInviteIntent.putExtra("NOTIFICATION_ID", notificationId)
val pendingIntentAccept = PendingIntent.getBroadcast(
context,
groupID.hashCode(),
acceptInviteIntent,
withImmutableFlag(PendingIntent.FLAG_UPDATE_CURRENT)
)
notificationBuilder.addAction(0, "Accept", pendingIntentAccept)
val rejectInviteIntent = Intent(context, LocalNotificationActionReceiver::class.java)
rejectInviteIntent.action = res.getString(R.string.reject_guild_invite)
rejectInviteIntent.putExtra("groupID", groupID)
acceptInviteIntent.putExtra("NOTIFICATION_ID", notificationId)
val pendingIntentReject = PendingIntent.getBroadcast(
context,
groupID.hashCode() + 1,
rejectInviteIntent,
withImmutableFlag(PendingIntent.FLAG_UPDATE_CURRENT)
)
notificationBuilder.addAction(0, "Reject", pendingIntentReject)
}
}
| gpl-3.0 | 18c374b79e98b3b20259e0e30751cf89 | 41.959184 | 124 | 0.727791 | 4.827982 | false | false | false | false |
androidx/androidx | compose/compiler/compiler-hosted/src/main/java/androidx/compose/compiler/plugins/kotlin/lower/ClassStabilityFieldSerializationPlugin.kt | 3 | 2905 | /*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package androidx.compose.compiler.plugins.kotlin.lower
import org.jetbrains.kotlin.descriptors.ClassDescriptor
import org.jetbrains.kotlin.descriptors.ClassKind
import org.jetbrains.kotlin.descriptors.DescriptorVisibilities
import org.jetbrains.kotlin.metadata.ProtoBuf
import org.jetbrains.kotlin.metadata.deserialization.Flags.HAS_ANNOTATIONS
import org.jetbrains.kotlin.metadata.serialization.MutableVersionRequirementTable
import org.jetbrains.kotlin.serialization.DescriptorSerializer
import org.jetbrains.kotlin.serialization.DescriptorSerializerPlugin
import org.jetbrains.kotlin.serialization.SerializerExtension
/**
* A static final int is synthesized onto all classes in order to allow for stability to be
* determined at runtime. We need to know from other modules whether or not this field got
* synthesized or not though, and to do that, we also synthesize an annotation on the class.
*
* The kotlin metadata has a flag to indicate whether or not there are any annotations on the
* class or not. If the flag is false, then a synthesized annotation will never be seen from
* another module, so we have to use this plugin to flip the flag for all classes that we
* synthesize the annotation on, even if the source of the class didn't have any annotations.
*/
class ClassStabilityFieldSerializationPlugin : DescriptorSerializerPlugin {
private val hasAnnotationFlag = HAS_ANNOTATIONS.toFlags(true)
override fun afterClass(
descriptor: ClassDescriptor,
proto: ProtoBuf.Class.Builder,
versionRequirementTable: MutableVersionRequirementTable,
childSerializer: DescriptorSerializer,
extension: SerializerExtension
) {
if (
descriptor.visibility != DescriptorVisibilities.PUBLIC ||
descriptor.kind == ClassKind.ENUM_CLASS ||
descriptor.kind == ClassKind.ENUM_ENTRY ||
descriptor.kind == ClassKind.INTERFACE ||
descriptor.kind == ClassKind.ANNOTATION_CLASS ||
descriptor.isExpect ||
descriptor.isInner ||
descriptor.isCompanionObject ||
descriptor.isInline
) return
if (proto.flags and hasAnnotationFlag == 0) {
proto.flags = proto.flags or hasAnnotationFlag
}
}
} | apache-2.0 | aaf7c7898756acbbc41884f12ddbe022 | 44.40625 | 93 | 0.744234 | 4.882353 | false | false | false | false |
klazuka/intellij-elm | src/main/kotlin/org/elm/lang/core/completion/ElmRecordFieldSuggestor.kt | 1 | 2364 | package org.elm.lang.core.completion
import com.intellij.codeInsight.completion.CompletionParameters
import com.intellij.codeInsight.completion.CompletionResultSet
import com.intellij.codeInsight.lookup.LookupElementBuilder
import org.elm.lang.core.psi.ELM_IDENTIFIERS
import org.elm.lang.core.psi.ElmFieldAccessTargetTag
import org.elm.lang.core.psi.elementType
import org.elm.lang.core.psi.elements.ElmFieldAccessExpr
import org.elm.lang.core.psi.elements.ElmValueExpr
import org.elm.lang.core.types.Ty
import org.elm.lang.core.types.TyRecord
import org.elm.lang.core.types.findTy
import org.elm.lang.core.types.renderedText
object ElmRecordFieldSuggestor : Suggestor {
override fun addCompletions(parameters: CompletionParameters, result: CompletionResultSet) {
val pos = parameters.position
val parent = pos.parent
if (pos.elementType in ELM_IDENTIFIERS && parent is ElmFieldAccessExpr) {
// Infer the type of the record whose fields are being accessed
// and suggest that record's fields as completion results.
val targetExpr = parent.targetExpr
val ty = targetExpr.findTy() as? TyRecord ?: resolveTarget(targetExpr) ?: return
// provide each field as a completion result
ty.fields.forEach { (fieldName, fieldTy) ->
result.add(fieldName, fieldTy)
}
}
}
/**
* In partial programs, a function body might not be inferred. But it's common to complete
* fields on parameters, and in many cases the function's parameters are still inferred even if
* the body isn't.
*/
private fun resolveTarget(targetExpr: ElmFieldAccessTargetTag): TyRecord? {
return when (targetExpr) {
is ElmValueExpr -> {
val ref = targetExpr.reference.resolve() ?: return null
ref.findTy() as? TyRecord
}
is ElmFieldAccessExpr -> {
val field = targetExpr.lowerCaseIdentifier.text
val base = resolveTarget(targetExpr.targetExpr) ?: return null
base.fields[field] as? TyRecord
}
else -> null
}
}
}
private fun CompletionResultSet.add(str: String, field: Ty) {
addElement(LookupElementBuilder.create(str)
.withTypeText(field.renderedText()))
}
| mit | a2d8ba7315890843303df8d074cbf06e | 38.4 | 99 | 0.67978 | 4.435272 | false | false | false | false |
andstatus/andstatus | app/src/main/kotlin/org/andstatus/app/note/BaseNoteAdapter.kt | 1 | 11544 | /*
* Copyright (c) 2016 yvolk (Yuri Volkov), http://yurivolkov.com
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.andstatus.app.note
import android.text.SpannableString
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.RelativeLayout
import android.widget.TextView
import org.andstatus.app.R
import org.andstatus.app.context.MyPreferences
import org.andstatus.app.data.AttachedMediaFile
import org.andstatus.app.data.DownloadStatus
import org.andstatus.app.graphics.IdentifiableImageView
import org.andstatus.app.net.social.SpanUtil
import org.andstatus.app.timeline.BaseTimelineAdapter
import org.andstatus.app.timeline.TimelineData
import org.andstatus.app.util.I18n
import org.andstatus.app.util.MyStringBuilder
import org.andstatus.app.util.MyUrlSpan
import org.andstatus.app.util.SharedPreferencesUtil
import java.util.*
import java.util.function.Consumer
/**
* @author [email protected]
*/
abstract class BaseNoteAdapter<T : BaseNoteViewItem<T>>(contextMenu: NoteContextMenu, listData: TimelineData<T>) :
BaseTimelineAdapter<T>(contextMenu.getMyContext(), listData) {
protected val showButtonsBelowNotes = SharedPreferencesUtil.getBoolean(MyPreferences.KEY_SHOW_BUTTONS_BELOW_NOTE, true)
protected val contextMenu: NoteContextMenu
protected var preloadedImages: MutableSet<Long> = HashSet(100)
override fun getView(position: Int, convertView: View?, parent: ViewGroup?): View? {
val view = getEmptyView(convertView)
view.setOnCreateContextMenuListener(contextMenu)
view.setOnClickListener(this)
setPosition(view, position)
val item = getItem(position)
populateView(view, item, false, position)
return view
}
fun populateView(view: ViewGroup, item: T, showReceivedTime: Boolean, position: Int) {
showRebloggers(view, item)
MyUrlSpan.showText(view, R.id.note_author, item.author.actor.getActorNameInTimelineWithOrigin(), false, false)
showNoteName(view, item)
showNoteSummary(view, item)
showNoteContent(view, item)
MyUrlSpan.showText(view, R.id.note_details, item.getDetails(contextMenu.getActivity(), showReceivedTime)
.toString(), false, false)
showAvatarEtc(view, item)
if (showAttachedImages) {
showAttachedImages(view, item)
}
if (markRepliesToMe) {
removeReplyToMeMarkerView(view)
showMarkRepliesToMe(view, item)
}
if (showButtonsBelowNotes) {
showButtonsBelowNote(view, item)
} else {
showFavorited(view, item)
}
showNoteNumberEtc(view, item, position)
}
protected abstract fun showAvatarEtc(view: ViewGroup, item: T)
protected abstract fun showNoteNumberEtc(view: ViewGroup, item: T, position: Int)
protected fun getEmptyView(convertView: View?): ViewGroup {
if (convertView == null) return newView()
convertView.setBackgroundResource(0)
val noteIndented = convertView.findViewById<View?>(R.id.note_indented)
noteIndented.setBackgroundResource(0)
return convertView as ViewGroup
}
override fun getItemId(position: Int): Long {
return getItem(position).getNoteId()
}
protected fun newView(): ViewGroup {
val view = LayoutInflater.from(contextMenu.getActivity()).inflate(R.layout.note, null) as ViewGroup
setupButtons(view)
return view
}
protected fun showRebloggers(view: View, item: T) {
val viewGroup = view.findViewById<View?>(R.id.reblogged)
if (viewGroup == null) {
return
} else if (item.isReblogged()) {
viewGroup.visibility = View.VISIBLE
val rebloggers = MyStringBuilder()
item.rebloggers.values.forEach(Consumer { text: String? -> rebloggers.withComma(text) })
MyUrlSpan.showText(viewGroup, R.id.rebloggers, rebloggers.toString(), false, false)
} else {
viewGroup.visibility = View.GONE
}
}
protected fun showNoteName(view: View, item: T) {
MyUrlSpan.showSpannable(view.findViewById<TextView?>(R.id.note_name),
if (item.isSensitive() && !MyPreferences.isShowSensitiveContent()) SpanUtil.EMPTY else item.getName(), false)
}
protected fun showNoteSummary(view: View, item: T) {
MyUrlSpan.showSpannable(view.findViewById<TextView?>(R.id.note_summary), item.getSummary(), false)
}
protected fun showNoteContent(view: View, item: T) {
MyUrlSpan.showSpannable(view.findViewById<TextView?>(R.id.note_body),
if (item.isSensitive() && !MyPreferences.isShowSensitiveContent()) SpannableString.valueOf("(" + myContext.context.getText(R.string.sensitive) + ")") else item.getContent(),
false)
}
protected fun showAvatar(view: View, item: T) {
item.author.showAvatar(contextMenu.getActivity(), view.findViewById(R.id.avatar_image))
}
private fun showAttachedImages(view: View, item: T) {
val attachmentsList = view.findViewById<LinearLayout?>(R.id.attachments_wrapper) ?: return
if (!contextMenu.getActivity().isMyResumed() || item.isSensitive() && !MyPreferences.isShowSensitiveContent() ||
!item.attachedImageFiles.imageOrLinkMayBeShown()) {
attachmentsList.visibility = View.GONE
return
}
attachmentsList.removeAllViewsInLayout()
for (mediaFile in item.attachedImageFiles.list) {
if (!mediaFile.imageOrLinkMayBeShown()) continue
val attachmentLayout = if (mediaFile.imageMayBeShown()) if (mediaFile.isTargetVideo()) R.layout.attachment_video_preview else R.layout.attachment_image else R.layout.attachment_link
val attachmentView = LayoutInflater.from(contextMenu.getActivity())
.inflate(attachmentLayout, attachmentsList, false)
if (mediaFile.imageMayBeShown()) {
val imageView: IdentifiableImageView = attachmentView.findViewById(R.id.attachment_image)
preloadedImages.add(item.getNoteId())
mediaFile.showImage(contextMenu.getActivity(), imageView)
setOnImageClick(imageView, mediaFile)
} else {
MyUrlSpan.showText(attachmentView, R.id.attachment_link,
mediaFile.getTargetUri().toString(), true, false)
}
attachmentsList.addView(attachmentView)
}
attachmentsList.visibility = View.VISIBLE
}
private fun setOnImageClick(imageView: View, mediaFile: AttachedMediaFile) {
imageView.setOnClickListener { view: View? -> contextMenu.menuContainer.getActivity().startActivity(mediaFile.intentToView()) }
}
fun removeReplyToMeMarkerView(view: ViewGroup) {
val oldView = view.findViewById<View?>(R.id.reply_timeline_marker)
if (oldView != null) {
view.removeView(oldView)
}
}
private fun showMarkRepliesToMe(view: ViewGroup, item: T) {
if (myContext.users.isMe(item.inReplyToActor.actor) &&
!myContext.users.isMe(item.author.actor)) {
val referencedView = view.findViewById<View?>(R.id.note_indented)
val replyToMeMarkerView: ImageView = ConversationIndentImageView(myContext.context, referencedView, dpToPixes(6),
R.drawable.reply_timeline_marker_light, R.drawable.reply_timeline_marker)
replyToMeMarkerView.id = R.id.reply_timeline_marker
view.addView(replyToMeMarkerView, 1)
val layoutParams = replyToMeMarkerView.layoutParams as RelativeLayout.LayoutParams
layoutParams.leftMargin = dpToPixes(3)
}
}
fun setupButtons(view: View) {
if (showButtonsBelowNotes) {
val buttons = view.findViewById<View?>(R.id.note_buttons)
if (buttons != null) {
buttons.visibility = View.VISIBLE
setOnButtonClick(buttons, R.id.reply_button, NoteContextMenuItem.REPLY)
setOnButtonClick(buttons, R.id.reblog_button, NoteContextMenuItem.ANNOUNCE)
setOnButtonClick(buttons, R.id.reblog_button_tinted, NoteContextMenuItem.UNDO_ANNOUNCE)
setOnButtonClick(buttons, R.id.favorite_button, NoteContextMenuItem.LIKE)
setOnButtonClick(buttons, R.id.favorite_button_tinted, NoteContextMenuItem.UNDO_LIKE)
setOnClickShowContextMenu(buttons, R.id.more_button)
}
}
}
private fun setOnButtonClick(viewGroup: View, buttonId: Int, menuItem: NoteContextMenuItem) {
viewGroup.findViewById<View?>(buttonId).setOnClickListener { view: View ->
val item = getItem(view)
if (item.nonEmpty && (item.noteStatus == DownloadStatus.LOADED || menuItem.appliedToUnsentNotesAlso)) {
contextMenu.onViewSelected(view) { contextMenu: NoteContextMenu ->
contextMenu.onContextItemSelected(menuItem, item.getNoteId())
}
}
}
}
private fun setOnClickShowContextMenu(viewGroup: View, buttonId: Int) {
viewGroup.findViewById<View?>(buttonId).setOnClickListener { view: View? -> viewGroup.showContextMenu() }
}
protected fun showButtonsBelowNote(view: View, item: T) {
val viewGroup = view.findViewById<View?>(R.id.note_buttons)
if (viewGroup == null) {
return
} else if (showButtonsBelowNotes && item.noteStatus == DownloadStatus.LOADED) {
viewGroup.visibility = View.VISIBLE
tintIcon(viewGroup, item.reblogged, R.id.reblog_button, R.id.reblog_button_tinted)
tintIcon(viewGroup, item.favorited, R.id.favorite_button, R.id.favorite_button_tinted)
MyUrlSpan.showText(viewGroup, R.id.likes_count, I18n.notZero(item.likesCount), false, true)
MyUrlSpan.showText(viewGroup, R.id.reblogs_count, I18n.notZero(item.reblogsCount), false, true)
MyUrlSpan.showText(viewGroup, R.id.replies_count, I18n.notZero(item.repliesCount), false, true)
} else {
viewGroup.visibility = View.GONE
}
}
private fun tintIcon(viewGroup: View, colored: Boolean, viewId: Int, viewIdColored: Int) {
val imageView = viewGroup.findViewById<ImageView?>(viewId)
val imageViewTinted = viewGroup.findViewById<ImageView?>(viewIdColored)
imageView.visibility = if (colored) View.GONE else View.VISIBLE
imageViewTinted.visibility = if (colored) View.VISIBLE else View.GONE
}
protected fun showFavorited(view: View, item: T) {
val favorited = view.findViewById<View?>(R.id.note_favorited)
favorited.visibility = if (item.favorited) View.VISIBLE else View.GONE
}
init {
this.contextMenu = contextMenu
}
}
| apache-2.0 | 3e7d06760b87981ddfb4b2c442f927e9 | 45.176 | 193 | 0.681306 | 4.412844 | false | false | false | false |
rosenpin/QuickDrawEverywhere | app/src/main/java/com/tomer/draw/gallery/Item.kt | 1 | 1243 | package com.tomer.draw.gallery
import android.graphics.Bitmap
import android.graphics.drawable.Drawable
import android.support.v7.widget.RecyclerView
import android.view.View
import android.widget.ImageView
import com.mikepenz.fastadapter.items.AbstractItem
import com.tomer.draw.R
import kotlinx.android.synthetic.main.gallery_item.view.*
import java.io.File
/**
* DrawEverywhere
* Created by Tomer Rosenfeld on 7/29/17.
*/
class Item : AbstractItem<Item, Item.ViewHolder>() {
override fun getType(): Int = 12
override fun getLayoutRes(): Int = R.layout.gallery_item
var bitmapImage: Bitmap? = null
var file: File? = null
internal fun withBitmap(bitmap: Bitmap): Item {
this.bitmapImage = bitmap
return this
}
internal fun withFile(file: File?): Item {
this.file = file
return this
}
override fun bindView(viewHolder: ViewHolder, payloads: List<Any>) {
super.bindView(viewHolder, payloads)
viewHolder.image.setImageBitmap(bitmapImage)
}
override fun unbindView(holder: ViewHolder) {
super.unbindView(holder)
}
override fun getViewHolder(v: View): ViewHolder {
return ViewHolder(v)
}
class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
var image: ImageView = view.image
}
}
| gpl-3.0 | 6f6d625c7acac30590becc41d00905eb | 22.45283 | 69 | 0.748994 | 3.53125 | false | false | false | false |
wordpress-mobile/AztecEditor-Android | app/src/androidTest/kotlin/org/wordpress/aztec/demo/tests/HistoryMixedTests.kt | 1 | 3585 | package org.wordpress.aztec.demo.tests
import org.junit.Ignore
import org.junit.Test
import org.wordpress.aztec.demo.BaseHistoryTest
import org.wordpress.aztec.demo.pages.EditorPage
class HistoryMixedTests : BaseHistoryTest() {
private val HTML =
"[caption align=\"alignright\"]<img src=\"https://examplebloge.files.wordpress.com/2017/02/3def4804-d9b5-11e6-88e6-d7d8864392e0.png\">Caption[/caption]\n" +
"\n" +
"<h1>Heading 1</h1>\n" +
"<h2>Heading 2</h2>\n" +
"<h3>Heading 3</h3>\n" +
"<h4>Heading 4</h4>\n" +
"<h5>Heading 5</h5>\n" +
"<h6>Heading 6</h6>\n" +
"<b>Bold</b>\n" +
"<i>Italic</i>\n" +
"<u>Underline</u>\n" +
"<s class=\"test\">Strikethrough</s>\n" +
"<ol>\n" +
"\t<li>Ordered</li>\n" +
"\t<li></li>\n" +
"</ol>\n" +
"\n" +
"<hr />\n" +
"\n" +
"<ul>\n" +
"\t<li>Unordered</li>\n" +
"\t<li></li>\n" +
"</ul>\n" +
"<blockquote>Quote</blockquote>\n" +
"<pre>when (person) {\n" +
" MOCTEZUMA -> {\n" +
" print (\"friend\")\n" +
" }\n" +
" CORTES -> {\n" +
" print (\"foe\")\n" +
" }\n" +
"}</pre><a href=\"https://github.com/wordpress-mobile/WordPress-Aztec-Android\">Link</a>\n" +
"<div class=\"first\">\n" +
"<div class=\"second\">\n" +
"<div class=\"third\">Div\n" +
"<span><b>Span</b></span>\n" +
"Hidden</div>\n" +
"<div class=\"fourth\"></div>\n" +
"<div class=\"fifth\"></div>\n" +
"</div>\n" +
"</div>\n" +
"<!--Comment-->\n" +
"\n" +
"<!--more-->\n" +
"\n" +
"<!--nextpage-->\n" +
"\n" +
"<code>if (value == 5) printf(value)</code>\n" +
"<iframe class=\"classic\">Menu</iframe>\n" +
"\uD83D\uDC4D测试一个\n" +
"\n" +
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. [video src=\"https://examplebloge.files.wordpress.com/2017/06/d7d88643-88e6-d9b5-11e6-92e03def4804.mp4\"][audio src=\"https://upload.wikimedia.org/wikipedia/commons/9/94/H-Moll.ogg\"]"
@Ignore("Until this issue is fixed: https://github.com/wordpress-mobile/AztecEditor-Android/issues/676")
@Test
fun testSelectAllDeleteUndoRedo() {
// Add demo html text to editor
EditorPage()
.toggleHtml()
.replaceHTML(HTML)
.toggleHtml()
.threadSleep(throttleTime)
// Select all text and delete, verify
EditorPage()
.tapTop()
.clearText()
.threadSleep(throttleTime)
.toggleHtml()
.verifyHTML("")
.toggleHtml()
// Undo select all and delete, verify
EditorPage()
.undoChange()
.threadSleep(throttleTime)
.toggleHtml()
.verifyHTMLNoStripping(HTML)
.toggleHtml()
// Redo select all and delete, verify
EditorPage()
.redoChange()
.threadSleep(throttleTime)
.toggleHtml()
.verifyHTML("")
}
} | mpl-2.0 | aab4c9059c0d05962dd2c07c4e6fab5f | 35.510204 | 321 | 0.457646 | 3.729927 | false | true | false | false |
CruGlobal/android-gto-support | gto-support-db/src/main/java/org/ccci/gto/android/common/db/Expression.kt | 1 | 11744 | package org.ccci.gto.android.common.db
import android.os.Parcelable
import kotlinx.parcelize.IgnoredOnParcel
import kotlinx.parcelize.Parcelize
import org.ccci.gto.android.common.db.AbstractDao.Companion.bindValues
sealed class Expression : Parcelable {
companion object {
@JvmField
val NULL = Literal(isConstant = true)
@JvmStatic
fun bind() = Literal(isConstant = false)
@JvmStatic
fun bind(value: Any) = Literal(bindValues(value)[0], false)
@JvmStatic
fun bind(value: Number) = Literal(value, false)
@JvmStatic
fun bind(value: String) = Literal(value, false)
@JvmStatic
fun constant(value: Any) = Literal(bindValues(value)[0], true)
@JvmStatic
fun constant(value: Number) = Literal(value, true)
@JvmStatic
fun constant(value: String) = Literal(value, true)
@JvmStatic
fun constants(vararg values: Any) = constants(*bindValues(*values))
@JvmStatic
fun constants(vararg values: Number) = Array(values.size) { constant(values[it]) }
@JvmStatic
fun constants(vararg values: String) = Array(values.size) { constant(values[it]) }
@JvmStatic
fun field(name: String) = Field(name = name)
@JvmStatic
fun not(expression: Expression) = expression.not()
fun raw(expr: String): Expression = Raw(expr, emptyList())
fun raw(expr: String, vararg args: Any): Expression = Raw(expr, bindValues(*args).toList())
fun raw(expr: String, vararg args: String): Expression = Raw(expr, args.toList())
}
/**
* The number of "dynamic" arguments in this expression. This may not be the same as the actual number of arguments
* returned from buildSql
*/
internal open val numOfArgs = 0
fun args(vararg args: Any) = args(*bindValues(*args))
open fun args(vararg args: String): Expression {
require(args.isEmpty()) { "invalid number of arguments specified" }
return this
}
infix fun and(expression: Expression): Expression = binaryExpr(Binary.AND, expression)
infix fun or(expression: Expression): Expression = binaryExpr(Binary.OR, expression)
open operator fun not(): Expression = Unary(Unary.NOT, this)
infix fun eq(constant: Number): Expression = eq(constant(constant))
infix fun eq(constant: String): Expression = eq(constant(constant))
infix fun eq(constant: Any): Expression = eq(constant(constant))
infix fun eq(expression: Expression): Expression = Binary(Binary.EQ, this, expression)
infix fun lt(constant: Number): Expression = lt(constant(constant))
infix fun lt(constant: Any): Expression = lt(constant(constant))
infix fun lt(expression: Expression): Expression = Binary(Binary.LT, this, expression)
infix fun lte(constant: Number): Expression = lte(constant(constant))
infix fun lte(constant: Any): Expression = lte(constant(constant))
infix fun lte(expression: Expression): Expression = Binary(Binary.LTE, this, expression)
infix fun gt(constant: Number): Expression = gt(constant(constant))
infix fun gt(constant: Any): Expression = gt(constant(constant))
infix fun gt(expression: Expression): Expression = Binary(Binary.GT, this, expression)
infix fun gte(constant: Number): Expression = gte(constant(constant))
infix fun gte(constant: Any): Expression = gte(constant(constant))
infix fun gte(expression: Expression): Expression = Binary(Binary.GTE, this, expression)
fun `in`(vararg expressions: Expression): Expression = Binary(Binary.IN, this, *expressions)
fun oneOf(vararg expressions: Expression): Expression = Binary(Binary.IN, this, *expressions)
fun oneOf(literals: List<Expression>): Expression = Binary(Binary.IN, this, *literals.toTypedArray())
fun notIn(vararg expressions: Expression): Expression = Binary(Binary.NOTIN, this, *expressions)
fun `is`(expression: Expression): Expression = Binary(Binary.IS, this, expression)
fun isNull(): Expression = Binary(Binary.IS, this, NULL)
fun isNot(expression: Expression): Expression = Binary(Binary.ISNOT, this, expression)
infix fun ne(constant: Number): Expression = ne(constant(constant))
infix fun ne(constant: String): Expression = ne(constant(constant))
infix fun ne(constant: Any): Expression = ne(constant(constant))
infix fun ne(expression: Expression): Expression = Binary(Binary.NE, this, expression)
internal open fun binaryExpr(op: String, expression: Expression): Expression = Binary(op, this, expression)
internal abstract fun buildSql(dao: AbstractDao): QueryComponent
@Parcelize
data class Field internal constructor(
private val table: Table<*>? = null,
private val name: String
) : Expression() {
@JvmOverloads
fun count(isDistinct: Boolean = false) = Aggregate(Aggregate.COUNT, isDistinct, this)
@JvmOverloads
fun max(isDistinct: Boolean = false) = Aggregate(Aggregate.MAX, isDistinct, this)
@JvmOverloads
fun min(isDistinct: Boolean = false) = Aggregate(Aggregate.MIN, isDistinct, this)
@JvmOverloads
fun sum(isDistinct: Boolean = false) = Aggregate(Aggregate.SUM, isDistinct, this)
@Transient
@IgnoredOnParcel
private var _sql: QueryComponent? = null
override fun buildSql(dao: AbstractDao) =
_sql ?: QueryComponent(if (table != null) "${table.sqlPrefix(dao)}$name" else name).also { _sql = it }
}
@Parcelize
data class Literal internal constructor(
private val strValue: String? = null,
private val numValue: Number? = null,
private val isConstant: Boolean
) : Expression() {
internal constructor(value: Number, constant: Boolean) : this(null, value, constant)
internal constructor(value: String, constant: Boolean) : this(value, null, constant)
override val numOfArgs get() = if (isConstant) 0 else 1
override fun args(vararg args: String): Literal {
require(args.size == numOfArgs) { "incorrect number of args specified" }
return if (isConstant) this else Literal(args[0], false)
}
@IgnoredOnParcel
private val _sql by lazy {
when {
isConstant -> when {
numValue != null -> QueryComponent(numValue.toString())
strValue != null -> QueryComponent("?", strValue)
else -> QueryComponent("NULL")
}
numValue != null -> QueryComponent("?", numValue.toString())
else -> QueryComponent("?", strValue.orEmpty())
}
}
override fun buildSql(dao: AbstractDao) = _sql
}
@Parcelize
private data class Raw(private val expr: String, private val args: List<String>) : Expression() {
override val numOfArgs get() = args.size
override fun args(vararg args: String) = copy(args = args.toList())
override fun buildSql(dao: AbstractDao) = QueryComponent(expr, *args.toTypedArray())
}
@Parcelize
private data class Binary(private val op: String, private val exprs: List<Expression>) : Expression() {
companion object {
internal const val LT = "<"
internal const val LTE = "<="
internal const val GT = ">"
internal const val GTE = ">="
internal const val EQ = "=="
internal const val NE = "!="
internal const val IS = "IS"
internal const val ISNOT = "IS NOT"
internal const val IN = "IN"
internal const val NOTIN = "NOT IN"
internal const val AND = "AND"
internal const val OR = "OR"
}
constructor(op: String, vararg exprs: Expression) : this(op, exprs.toList())
@Transient
@IgnoredOnParcel
override val numOfArgs = exprs.sumOf { it.numOfArgs }
override fun args(vararg args: String): Expression {
require(args.size == numOfArgs) { "incorrect number of args specified" }
if (args.isEmpty()) return this
var pos = 0
val exprs = exprs.map {
when (it.numOfArgs) {
0 -> it
else -> it.args(*args.sliceArray(pos until pos + it.numOfArgs)).also { pos += it.numOfArgs }
}
}
return Binary(op, *exprs.toTypedArray())
}
override fun not() = when (op) {
EQ -> Binary(NE, *exprs.toTypedArray())
NE -> Binary(EQ, *exprs.toTypedArray())
IS -> Binary(ISNOT, *exprs.toTypedArray())
ISNOT -> Binary(IS, *exprs.toTypedArray())
IN -> Binary(NOTIN, *exprs.toTypedArray())
NOTIN -> Binary(IN, *exprs.toTypedArray())
else -> super.not()
}
override fun binaryExpr(op: String, expression: Expression) = when {
this.op != op -> super.binaryExpr(op, expression)
// chain binary expressions together when possible
op == AND || op == OR -> Binary(op, *exprs.toTypedArray(), expression)
else -> super.binaryExpr(op, expression)
}
@Transient
@IgnoredOnParcel
private var _sql: QueryComponent? = null
private fun generateSql(dao: AbstractDao): QueryComponent {
val query = QueryComponent("(") + when (op) {
IN, NOTIN -> {
exprs[0].buildSql(dao) + " $op (" + exprs.subList(1, exprs.size)
.joinToQueryComponent(",") { it.buildSql(dao) } + ")"
}
else -> exprs.joinToQueryComponent(" $op ") { it.buildSql(dao) }
} + ")"
_sql = query
return query
}
override fun buildSql(dao: AbstractDao) = _sql ?: generateSql(dao)
}
@Parcelize
private data class Unary(private val op: String, private val expr: Expression) : Expression() {
companion object {
internal const val NOT = "NOT"
}
override val numOfArgs get() = expr.numOfArgs
override fun args(vararg args: String) = copy(expr = expr.args(*args))
override fun not() = when (op) {
NOT -> expr
else -> super.not()
}
@Transient
@IgnoredOnParcel
private var _sql: QueryComponent? = null
private fun generateSql(dao: AbstractDao) =
(QueryComponent("$op (") + expr.buildSql(dao) + ")").also { _sql = it }
override fun buildSql(dao: AbstractDao) = _sql ?: generateSql(dao)
}
@Parcelize
data class Aggregate internal constructor(
private val op: String,
private val isDistinct: Boolean,
private val expr: Field
) : Expression() {
companion object {
internal const val COUNT = "COUNT"
internal const val MAX = "MAX"
internal const val MIN = "MIN"
internal const val SUM = "SUM"
}
override val numOfArgs get() = expr.numOfArgs
override fun args(vararg args: String) = copy(expr = expr.args(*args) as Field)
fun distinct(isDistinct: Boolean) = copy(isDistinct = isDistinct)
@Transient
@IgnoredOnParcel
private var _sql: QueryComponent? = null
private fun generateSql(dao: AbstractDao) =
// {mOp} (DISTINCT {expr})
(QueryComponent("$op (${if (isDistinct) "DISTINCT " else ""}") + expr.buildSql(dao) + ")")
.also { _sql = it }
override fun buildSql(dao: AbstractDao) = _sql ?: generateSql(dao)
}
}
| mit | d31bdb572b5041c59b63097d56027cdb | 39.496552 | 119 | 0.614271 | 4.438398 | false | false | false | false |
Etik-Tak/backend | src/main/kotlin/dk/etiktak/backend/model/user/ClientDevice.kt | 1 | 2845 | // Copyright (c) 2017, Daniel Andersen ([email protected])
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
// 3. The name of the author may not be used to endorse or promote products derived
// from this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
/**
* A client device; each client can have one or more devices attached.
**/
package dk.etiktak.backend.model.user
import org.springframework.format.annotation.DateTimeFormat
import java.util.*
import javax.persistence.*
@Entity(name = "client_devices")
class ClientDevice {
enum class DeviceType {
Android,
iOS,
Unknown
}
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
@Column(name = "client_device_id")
var id: Long = 0
@Column(name = "uuid", nullable = false, unique = true)
var uuid: String = ""
@Column(name = "id_hashed", nullable = false, unique = true)
var idHashed: String = ""
@Column(name = "type", nullable = false)
var type = DeviceType.Unknown
@Column(name = "enabled", nullable = false)
var enabled: Boolean = true
@ManyToOne(optional = false)
@JoinColumn(name = "client_id")
var client = Client()
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
var creationTime = Date()
@DateTimeFormat(pattern = "yyyy-MM-dd HH:mm:ss")
var modificationTime = Date()
@PreUpdate
fun preUpdate() {
modificationTime = Date()
}
@PrePersist
fun prePersist() {
val now = Date()
creationTime = now
modificationTime = now
}
} | bsd-3-clause | 5fd9f06abe94f70e6ec7a93512a14448 | 32.880952 | 83 | 0.706151 | 4.350153 | false | false | false | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.