text:
*This tutorial requires that you first well understand how
`Commands <Commands.html>`_ work.*

Cooldowns
=========

Some types of games want to limit how often a command can be run. If a
character casts the spell *Firestorm*, you might not want them to spam
that command over and over. Or in an advanced combat system, a massive
swing may offer a chance of lots of damage at the cost of not being able
to re-do it for a while. Such effects are called *cooldowns*.

Evennia allows for many ways to implement cooldowns. Here are some
ideas.

Simplest way - single-command, non-persistent cooldown
------------------------------------------------------

This little recipe will limit how often a particular command can be run.
Since Commands are class instances, and those are cached in memory, a
command instance will remember things you store on it. So just store the
current time of execution! Next time the command is run, it just needs
to check if it has that time stored, and compare it with the current
time to see if a desired delay has passed.

::

    import time
    from ev import default_cmds

    class CmdSpellFirestorm(default_cmds.MuxCommand):
        """
        Spell - Firestorm

        Usage:
          cast firestorm <target>

        This will unleash a storm of flame. You can only release one
        firestorm every five minutes (assuming you have the mana).
        """
        key = "cast firestorm"
        locks = "cmd:isFireMage()"

        def func(self):
            "Implement the spell"

            # check cooldown (5 minute cooldown)
            if hasattr(self, "lastcast") and time.time()-self.lastcast < 5*60:
                self.caller.msg("You need to wait before casting this spell again.")
                return

            #[the spell effect is implemented]

            # if the spell was successfully cast, store the casting time
            self.lastcast = time.time()

We just check the ``lastcast`` flag, and update it if everything works
out. Simple and very effective since everything is just stored in
memory. The drawback of this simple scheme is that it's non-persistent.
If you do ``@reload``, the cache is cleaned and all such ongoing
cooldowns will be forgotten. It is also limited only to this one
command, other commands cannot (easily) check for this value.

Persistent cooldown
-------------------

This is essentially the same mechanism as the simple one above, except
we use the database to store the information which means the cooldown
will survive a server reload/reboot. Since commands themselves have no
representation in the database, you need to use the caster for the
storage.

::

            #[...]
            # check cooldown (5 minute cooldown)
            lastcall = self.caller.db.firestorm_lastcast # returns None if not exist yet
            if lastcast and time.time() - lastcast < 5*60:
                self.caller.msg("You need to wait before casting this spell again.")
                return

            #[the spell effect is implemented]

            # if the spell was successfully cast, store the casting time
            self.caller.db.firestorm_lastcast = time.time()

Since we are storing as an `Attribute <Attributes.html>`_, we need to
identify the variable as ``firestorm_lastcast`` so we are sure we get
the right one (we'll likely have other skills with cooldowns after all).
But this method of using cooldowns also has the advantage of working
*between* commands - you can for example let all fire-related spells
check the same cooldown to make sure the casting of *Firestorm* blocks
all fire-related spells for a while. Or, in the case of taking that big
swing with the sword, this could now block all other types of attacks
for a while before the warrior can recover.


text:
/* global input */

import { extend } from 'src/client/lang/utils.js';

extend(self, {

  get ctrlRight() { lively.warn('ControlRight not defined in window'); },
  get shiftRight() { lively.warn('ShiftRight not defined in window'); },
  get altRight() { lively.warn('AltRight not defined in window'); },
  get f1() { lively.warn('F1 not defined in window'); },
  get f2() { lively.warn('F2 not defined in window'); },
  get f3() { lively.warn('F3 not defined in window'); },
  get f4() { lively.warn('F4 not defined in window'); },
  get f5() { lively.warn('F5 not defined in window'); },
  get f6() { lively.warn('F6 not defined in window'); },
  get f7() { lively.warn('F7 not defined in window'); },
  get f8() { lively.warn('F8 not defined in window'); },
  get f9() { lively.warn('F9 not defined in window'); },
  get f10() { lively.warn('F10 not defined in window'); },
  get f11() { lively.warn('F11 not defined in window'); },
  get f12() { lively.warn('F12 not defined in window'); },
  get f13() { lively.warn('F13 not defined in window'); },
  get f14() { lively.warn('F14 not defined in window'); },
  get f15() { lively.warn('F15 not defined in window'); },
  get f16() { lively.warn('F16 not defined in window'); },
  get f17() { lively.warn('F17 not defined in window'); },
  get f18() { lively.warn('F18 not defined in window'); },
  get f19() { lively.warn('F19 not defined in window'); },
  get f20() { lively.warn('F20 not defined in window'); },
  get f21() { lively.warn('F21 not defined in window'); },
  get f22() { lively.warn('F22 not defined in window'); },
  get f23() { lively.warn('F23 not defined in window'); },
  get f24() { lively.warn('F24 not defined in window'); },
});

extend(KeyboardEvent.prototype, {

  get ctrlRight() { return !!self.input.key('ControlRight'); },
  get shiftRight() { return !!self.input.key('ShiftRight'); },
  get altRight() { return !!self.input.key('AltRight'); },

  get f1() { return !!self.input.key('F1'); },
  get f2() { return !!self.input.key('F2'); },
  get f3() { return !!self.input.key('F3'); },
  get f4() { return !!self.input.key('F4'); },
  get f5() { return !!self.input.key('F5'); },
  get f6() { return !!self.input.key('F6'); },
  get f7() { return !!self.input.key('F7'); },
  get f8() { return !!self.input.key('F8'); },
  get f9() { return !!self.input.key('F9'); },
  get f10() { return !!self.input.key('F10'); },
  get f11() { return !!self.input.key('F11'); },
  get f12() { return !!self.input.key('F12'); },
  get f13() { return !!self.input.key('F13'); },
  get f14() { return !!self.input.key('F14'); },
  get f15() { return !!self.input.key('F15'); },
  get f16() { return !!self.input.key('F16'); },
  get f17() { return !!self.input.key('F17'); },
  get f18() { return !!self.input.key('F18'); },
  get f19() { return !!self.input.key('F19'); },
  get f20() { return !!self.input.key('F20'); },
  get f21() { return !!self.input.key('F21'); },
  get f22() { return !!self.input.key('F22'); },
  get f23() { return !!self.input.key('F23'); },
  get f24() { return !!self.input.key('F24'); },

});

class KeyInput {

  constructor() {
    this._resetStates()
  }

  /*MD ## querying state key MD*/
  // #TODO: not yet implemented
  // #TODO: bind actions to keys
  state(action) {
    throw new Error('not yet implemented')
  }

  key(code) {
    return !!this._keys[code]
  }

  allKeys() {
    return Object.keys(input._keys)
  }

  /*MD ## writing key state MD*/
  _setKey(code, state) {
    if (state) {
      this._keys[code] = true
    } else {
      delete this._keys[code]
    }
  }

  _resetStates() {
    this._keys = {}
  }

  /*MD ## hooks MD*/
  static setKeyState(e, state) {
    self.input._setKey(e.code, state)
  }

  static onKeydown(e) {
    this.setKeyState(e, true);
  }

  static onKeyup(e) {
    this.setKeyState(e, false);
  }

  static onFocus(e) {
    self.input._resetStates();
  }

  // #important
  static load() {
    self.input = new this();

    const options = {
      capture: true,
      passive: true
    };

    const context = 'key-state';
    lively.removeEventListener(context);
    lively.addEventListener(context, document, "keydown", ::this.onKeydown, options);
    lively.addEventListener(context, document, "keyup", ::this.onKeyup, options);
    lively.addEventListener(context, window, 'focus', ::this.onFocus, options);

    lively.addEventListener(context, document, "keydown", evt => {
      // debug output?
      // lively.notify(input.allKeys())
    }, options);
  }
}

KeyInput.load();

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="UTF-8"?>
<generator_policy>

    <generator name="generator1">

    </generator>

</generator_policy>


text:
<?php

namespace Oro\Bundle\FeatureToggleBundle\DependencyInjection\CompilerPass;

use Symfony\Component\DependencyInjection\Compiler\CompilerPassInterface;
use Symfony\Component\DependencyInjection\ContainerBuilder;
use Symfony\Component\DependencyInjection\Reference;

class FeatureToggleVotersPass implements CompilerPassInterface
{
    /**
     * {@inheritdoc}
     */
    public function process(ContainerBuilder $container)
    {
        if (!$container->hasDefinition('oro_featuretoggle.checker.feature_checker')) {
            return;
        }

        $voters = new \SplPriorityQueue();
        foreach ($container->findTaggedServiceIds('oro_featuretogle.voter') as $id => $attributes) {
            $priority = isset($attributes[0]['priority']) ? $attributes[0]['priority'] : 0;
            $voters->insert(new Reference($id), $priority);
        }

        $voters = iterator_to_array($voters);
        ksort($voters);

        $container->getDefinition('oro_featuretoggle.checker.feature_checker')
            ->addMethodCall('setVoters', [array_values($voters)]);
    }
}


text:
package org.apache.lucene.store;

import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.Checksum;

/** Writes bytes through to a primary IndexOutput, computing
 *  checksum as it goes. Note that you cannot use seek(). */
public class ChecksumIndexInput extends IndexInput {
  IndexInput main;
  Checksum digest;

  public ChecksumIndexInput(IndexInput main) {
    this.main = main;
    digest = new CRC32();
  }

  @Override
  public byte readByte() throws IOException {
    final byte b = main.readByte();
    digest.update(b);
    return b;
  }

  @Override
  public void readBytes(byte[] b, int offset, int len)
    throws IOException {
    main.readBytes(b, offset, len);
    digest.update(b, offset, len);
  }

  public long getChecksum() {
    return digest.getValue();
  }

  @Override
  public void close() throws IOException {
    main.close();
  }

  @Override
  public long getFilePointer() {
    return main.getFilePointer();
  }

  @Override
  public void seek(long pos) {
    throw new RuntimeException("not allowed");
  }

  @Override
  public long length() {
    return main.length();
  }
}


text:
package net.runelite.client.plugins.screenmarkers;

import com.google.common.base.Strings;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import javax.inject.Inject;
import lombok.AccessLevel;
import lombok.Getter;
import lombok.Setter;
import net.runelite.client.config.ConfigManager;
import net.runelite.client.eventbus.Subscribe;
import net.runelite.client.events.ConfigChanged;
import net.runelite.client.input.MouseManager;
import net.runelite.client.plugins.Plugin;
import net.runelite.client.plugins.PluginDescriptor;
import net.runelite.client.plugins.screenmarkers.ui.ScreenMarkerPluginPanel;
import net.runelite.client.ui.ClientToolbar;
import net.runelite.client.ui.NavigationButton;
import net.runelite.client.ui.components.colorpicker.ColorPickerManager;
import net.runelite.client.ui.overlay.OverlayManager;
import net.runelite.client.util.ImageUtil;

@PluginDescriptor(
	name = "Screen Markers",
	description = "Enable drawing of screen markers on top of the client",
	tags = {"boxes", "overlay", "panel"}
)
public class ScreenMarkerPlugin extends Plugin
{
	private static final String PLUGIN_NAME = "Screen Markers";
	private static final String CONFIG_GROUP = "screenmarkers";
	private static final String CONFIG_KEY = "markers";
	private static final String ICON_FILE = "panel_icon.png";
	private static final String DEFAULT_MARKER_NAME = "Marker";
	private static final Dimension DEFAULT_SIZE = new Dimension(2, 2);

	@Getter
	private final List<ScreenMarkerOverlay> screenMarkers = new ArrayList<>();

	@Inject
	private ConfigManager configManager;

	@Inject
	private MouseManager mouseManager;

	@Inject
	private ClientToolbar clientToolbar;

	@Inject
	private OverlayManager overlayManager;

	@Inject
	private ScreenMarkerCreationOverlay overlay;

	@Getter
	@Inject
	private ColorPickerManager colorPickerManager;

	@Inject
	private ScreenMarkerWidgetHighlightOverlay widgetHighlight;

	private ScreenMarkerMouseListener mouseListener;
	private ScreenMarkerPluginPanel pluginPanel;
	private NavigationButton navigationButton;

	@Getter(AccessLevel.PACKAGE)
	private ScreenMarker currentMarker;

	@Getter
	@Setter
	private boolean creatingScreenMarker = false;

	@Getter
	private boolean drawingScreenMarker = false;

	@Getter
	@Setter
	private Rectangle selectedWidgetBounds = null;
	private Point startLocation = null;

	@Override
	protected void startUp() throws Exception
	{
		overlayManager.add(overlay);
		overlayManager.add(widgetHighlight);
		loadConfig(configManager.getConfiguration(CONFIG_GROUP, CONFIG_KEY)).forEach(screenMarkers::add);
		screenMarkers.forEach(overlayManager::add);

		pluginPanel = new ScreenMarkerPluginPanel(this);
		pluginPanel.rebuild();

		final BufferedImage icon = ImageUtil.getResourceStreamFromClass(getClass(), ICON_FILE);

		navigationButton = NavigationButton.builder()
			.tooltip(PLUGIN_NAME)
			.icon(icon)
			.priority(5)
			.panel(pluginPanel)
			.build();

		clientToolbar.addNavigation(navigationButton);

		mouseListener = new ScreenMarkerMouseListener(this);
	}

	@Override
	protected void shutDown() throws Exception
	{
		overlayManager.remove(overlay);
		overlayManager.remove(widgetHighlight);
		overlayManager.removeIf(ScreenMarkerOverlay.class::isInstance);
		screenMarkers.clear();
		clientToolbar.removeNavigation(navigationButton);
		setMouseListenerEnabled(false);
		creatingScreenMarker = false;
		drawingScreenMarker = false;

		pluginPanel = null;
		currentMarker = null;
		mouseListener = null;
		navigationButton = null;
		selectedWidgetBounds = null;
	}

	@Subscribe
	public void onConfigChanged(ConfigChanged event)
	{
		if (screenMarkers.isEmpty() && event.getGroup().equals(CONFIG_GROUP) && event.getKey().equals(CONFIG_KEY))
		{
			loadConfig(event.getNewValue()).forEach(screenMarkers::add);
			overlayManager.removeIf(ScreenMarkerOverlay.class::isInstance);
			screenMarkers.forEach(overlayManager::add);
		}
	}

	public void setMouseListenerEnabled(boolean enabled)
	{
		if (enabled)
		{
			mouseManager.registerMouseListener(mouseListener);
		}
		else
		{
			mouseManager.unregisterMouseListener(mouseListener);
		}
	}

	public void startCreation(Point location)
	{
		startCreation(location, DEFAULT_SIZE);

		// Stop the highlighting so we don't get rectangles around widgets while trying to make normal screen markers
		if (selectedWidgetBounds == null)
		{
			drawingScreenMarker = true;
		}
	}

	public void startCreation(Point location, Dimension size)
	{
		currentMarker = new ScreenMarker(
			Instant.now().toEpochMilli(),
			DEFAULT_MARKER_NAME + " " + (screenMarkers.size() + 1),
			pluginPanel.getSelectedBorderThickness(),
			pluginPanel.getSelectedColor(),
			pluginPanel.getSelectedFillColor(),
			true
		);

		// Set overlay creator bounds to current position and default size
		startLocation = location;
		overlay.setPreferredLocation(location);
		overlay.setPreferredSize(size);
	}

	public void finishCreation(boolean aborted)
	{
		ScreenMarker marker = currentMarker;
		if (!aborted && marker != null)
		{
			final ScreenMarkerOverlay screenMarkerOverlay = new ScreenMarkerOverlay(marker);
			screenMarkerOverlay.setPreferredLocation(overlay.getBounds().getLocation());
			screenMarkerOverlay.setPreferredSize(overlay.getBounds().getSize());

			screenMarkers.add(screenMarkerOverlay);
			overlayManager.saveOverlay(screenMarkerOverlay);
			overlayManager.add(screenMarkerOverlay);
			pluginPanel.rebuild();
			updateConfig();
		}

		creatingScreenMarker = false;
		drawingScreenMarker = false;
		selectedWidgetBounds = null;
		startLocation = null;
		currentMarker = null;
		setMouseListenerEnabled(false);

		pluginPanel.setCreation(false);
	}

	public void completeSelection()
	{
		pluginPanel.getCreationPanel().unlockConfirm();
	}

	public void deleteMarker(final ScreenMarkerOverlay marker)
	{
		screenMarkers.remove(marker);
		overlayManager.remove(marker);
		overlayManager.resetOverlay(marker);
		pluginPanel.rebuild();
		updateConfig();
	}

	void resizeMarker(Point point)
	{
		drawingScreenMarker = true;
		Rectangle bounds = new Rectangle(startLocation);
		bounds.add(point);
		overlay.setPreferredLocation(bounds.getLocation());
		overlay.setPreferredSize(bounds.getSize());
	}

	public void updateConfig()
	{
		if (screenMarkers.isEmpty())
		{
			configManager.unsetConfiguration(CONFIG_GROUP, CONFIG_KEY);
			return;
		}

		final Gson gson = new Gson();
		final String json = gson
			.toJson(screenMarkers.stream().map(ScreenMarkerOverlay::getMarker).collect(Collectors.toList()));
		configManager.setConfiguration(CONFIG_GROUP, CONFIG_KEY, json);
	}

	private Stream<ScreenMarkerOverlay> loadConfig(String json)
	{
		if (Strings.isNullOrEmpty(json))
		{
			return Stream.empty();
		}

		final Gson gson = new Gson();
		final List<ScreenMarker> screenMarkerData = gson.fromJson(json, new TypeToken<ArrayList<ScreenMarker>>()
		{
		}.getType());

		return screenMarkerData.stream().filter(Objects::nonNull).map(ScreenMarkerOverlay::new);
	}
}


text:
namespace Obvs.Types
{
    public interface IResponse : IMessage
    {
        string RequestId { get; set; }
        string RequesterId { get; set; }
    }
}


text:
typedef khronos_uint64_t EGLuint64NV;
#ifdef EGL_EGLEXT_PROTOTYPES
EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeFrequencyNV(void);
EGLAPI EGLuint64NV EGLAPIENTRY eglGetSystemTimeNV(void);
#endif
typedef EGLuint64NV (EGLAPIENTRYP PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC)(void);
typedef EGLuint64NV (EGLAPIENTRYP PFNEGLGETSYSTEMTIMENVPROC)(void);
#endif

class NvEGLWinUtil : public NvAndroidWinUtil {
public:
    // typedef for a function pointer that can be used by the app to find their own
    // EGL configuration.  This function, if supplied to construction, must return the
    // app's desired EGL config for the on-screen context
    // API support is a vector of the EGL_<API>_BIT flags supported by all configs ORed
    // Returns false if no useful configs are found
    typedef bool (*ConfigChooser)(EGLDisplay disp, EGLint apiSupport, EGLConfig& bestConfig,
        EGLint& api, EGLint& apiMajVer, EGLint& apiMinVer);

    // The default config chooser function, which returns a 565 RGB config with a 16 bit depth buffer
    // and an ES2 context
    static bool defaultEGLChooser(EGLDisplay disp, EGLint apiSupport, EGLConfig& bestConfig,
        EGLint& api, EGLint& apiMajVer, EGLint& apiMinVer);

    // returns a wrapper with a valid config on success.
    // no surface is created yet
    // A context is created but is not bound
	static NvEGLWinUtil* create(ConfigChooser chooser = &defaultEGLChooser);

    // Shuts down any active EGL resources and deletes
	~NvEGLWinUtil();

	// valid only when getWindow()!=NULL
	int32_t getWidth() { return m_width; }
	int32_t getHeight() { return m_height; }

	// used to set or update the native window given to us by Android
	// Must be called with NULL when the window is destroyed
	bool setWindow(ANativeWindow* window);

	// Returns true if the app has an allocated surface (bound or not)
	// returns false otherwise
	bool hasSurface() { return m_status >= NV_HAS_SURFACE; }

	// Returns true if the window size has changed since the last call to this
	// function, and indicates that the app needs to re-set its viewport, etc
	bool checkWindowResized();

	// Returns true if the rendering surface and context are bound
	// false otherwise
	bool isBound() { return m_status == NV_IS_BOUND; }

	// Binds the rendering context and on-screen surface;
	// fails if there is no rendering surface available
	bool bind();

	// Unbinds the current rendering context and surface
	bool unbind();

	// Preps a new thread for use with EGL/GL[ES]
	bool prepareThread();

	// Swaps the current on-screen surface.  Fails if the surface and context
	// are not already bounds
	bool swap();

	bool requestResetContext();

	// Returns true if there is a bound surface and context.
	// If allocateIfNeeded is true, then the function will
	// attempt to allocate the rendering surface and bind the
	// surface and context if possible.  Otherwise, the app
	// takes no actions and only returns whether or not the
	// system was already ready for rendering
	bool isReadyToRender(bool allocateIfNeeded = false);

	bool hasContext() { return m_context != EGL_NO_CONTEXT; }

	// Accessors for the low-level EGL/Android objects
	virtual void*  getDisplay() { return (void*)m_display; }
	virtual void*  getContext() { return (void*)m_context; }

	NvGLExtensionsAPI::GLproc getProcAddress(const char* procname);

	void getConfiguration(NvGLConfiguration& config);

protected:
    enum {
        // Numbering matters here, as we use >/< for state hierarchy
        NV_UNINITIALIZED = 0,
        NV_INITIALIZED = 1,
        NV_HAS_SURFACE = 2,
        NV_IS_BOUND = 3
    };

    enum {
        // the clock timing mode
        NV_TIME_MODE_INIT,
        NV_TIME_MODE_SYSTEM,
        NV_TIME_MODE_EGL
    };

	NvEGLWinUtil()
    {
        m_display = EGL_NO_DISPLAY;
        m_config = NULL;
        m_context = EGL_NO_CONTEXT;
        m_surface = EGL_NO_SURFACE;
        m_window = NULL;
        m_status = NV_UNINITIALIZED;
        m_width = 0;
        m_height = 0;
        mNewWindow = true;
        m_lastQueriedTime = 0;
        m_accumulatedTime = 0;
        gettimeofday(&m_startTime, 0);
        m_eglGetSystemTimeFrequencyNVProc = NULL;
        m_eglGetSystemTimeNVProc = NULL;
        m_eglSystemTimeFrequency = 0;
        m_nvTimeExtensionQueried = false;
        m_timeMode = NV_TIME_MODE_INIT;
    }

    bool queryNVTimeSupport();

    bool createContext();

	// This clock will use the NV time extension if available, allowing the
	// time to be slowed, accelerated or stopped.  This function may return
	// the same time from multiple calls, specifically if PerfHUD ES is active
	// Units are miliseconds
	uint32_t getSystemTime();

	// Create the rendering surface.  Will fail if no valid window has been
	// passed using setWindow
	bool createSurface();

	// Unbinds and destroys the rendering surface
	bool destroySurface();

	EGLDisplay m_display;
    EGLConfig m_config;
    EGLContext m_context;
    EGLSurface m_surface;
    EGLint m_format;
    EGLint m_api;
    EGLint m_majVer;
    EGLint m_minVer;
    int32_t m_width;
    int32_t m_height;

    ANativeWindow* m_window;
    bool mNewWindow;

    uint32_t m_status;

    uint32_t m_lastQueriedTime;
    uint32_t m_accumulatedTime;
    PFNEGLGETSYSTEMTIMEFREQUENCYNVPROC m_eglGetSystemTimeFrequencyNVProc;
    PFNEGLGETSYSTEMTIMENVPROC m_eglGetSystemTimeNVProc;
    EGLuint64NV m_eglSystemTimeFrequency;
    struct timeval m_startTime;
    bool m_nvTimeExtensionQueried;
    int32_t m_timeMode;
};

#endif


text:
import logging
import os

from ..utilities.execution_id import gen_execution_id

from ..status import status_mgr
from ..status.pipeline_status import PipelineStatus

from .dependency_manager import DependencyManager
from .celery_common import get_celery_app
from ..specs import pipelines, PipelineSpec
from ..manager.tasks import execute_pipeline

celery_app = get_celery_app()

executed_hashes = {}
# dependencies = {}
# dependents = {}
already_init = False
dep_mgr = None

def get_dep_mgr() -> DependencyManager:
    global dep_mgr
    if dep_mgr is None:
        dep_mgr = DependencyManager()
    return dep_mgr

def build_dependents():
    dm = get_dep_mgr()
    for spec in pipelines():  # type: PipelineSpec
        dm.update(spec)

def collect_dependencies(pipeline_ids):
    if pipeline_ids is None:
        return None
    dm = get_dep_mgr()
    ret = set()
    for pipeline_id in pipeline_ids:
        ret.add(pipeline_id)
        deps = dm.get_dependencies(pipeline_id)
        if deps is not None:
            ret.update(collect_dependencies(deps))
    return ret

def queue_pipeline(ps: PipelineStatus, spec: PipelineSpec, trigger):
    eid = gen_execution_id()
    logging.info('%s QUEUEING %s task %s', eid[:8], trigger.upper(), spec.pipeline_id)
    if ps.queue_execution(eid, trigger):
        execute_pipeline_task.delay(spec.pipeline_id,
                                    spec.pipeline_details,
                                    spec.path,
                                    trigger,
                                    eid)
        return True
    return False

def execute_update_pipelines():
    update_pipelines.delay('update', None, None)

@celery_app.task
def update_pipelines(action, completed_pipeline_id, completed_trigger):
    # action=scheduled: start a scheduled pipeline
    # action=update: iterate over all pipelines, register new ones, trigger dirty ones
    # action=complete: iterate over all pipelines, trigger dependencies
    # completed_pipeline_id: pipeline id that had just completed (or scheduled pipeline)
    # completed_trigger: the trigger for the pipeline that had just completed (when applicable)

    logging.info("Update Pipelines (%s)", action)
    status_all_pipeline_ids = set(status_mgr().all_pipeline_ids())
    executed_count = 0
    all_pipeline_ids = set()
    dm = get_dep_mgr()

    if action == 'complete':
        filter = collect_dependencies(dm.get_dependents(completed_pipeline_id))
        logging.info("DEPENDENTS Pipeline: %s <- %s", completed_pipeline_id, filter)
    else:
        filter = ('',)

    for spec in pipelines(filter):  # type: PipelineSpec
        all_pipeline_ids.add(spec.pipeline_id)
        ps = status_mgr().get(spec.pipeline_id)
        ps.init(spec.pipeline_details,
                spec.source_details,
                spec.validation_errors,
                spec.cache_hash)

        if action == 'init':
            psle = ps.get_last_execution()
            if psle is not None and not psle.finish_time:
                psle.invalidate()
                psle.finish_execution(False, {}, ['Cancelled'])

        elif action == 'update':
            if spec.pipeline_id not in status_all_pipeline_ids:
                dm.update(spec)
                logging.info("NEW Pipeline: %s", spec)
                ps.save()
            logging.debug('Pipeline: %s (dirty: %s, #ex=%s, ch=%s ex0-cache=%s)',
                          spec.pipeline_id, ps.dirty(), len(ps.executions), ps.cache_hash,
                          ps.executions[0].cache_hash if len(ps.executions) > 0 else None)

        elif action == 'complete':
            if completed_pipeline_id in spec.dependencies:
                logging.info("DEPENDENT Pipeline: %s (%d errors) (from ...%s), trigger=%s",
                             spec.pipeline_id, len(spec.validation_errors),
                             os.path.basename(completed_pipeline_id),
                             completed_trigger)
                ps.save()
            else:
                continue

        elif action == 'scheduled':
            if completed_pipeline_id != spec.pipeline_id:
                continue

        last_successful = ps.state() == 'SUCCEEDED'
        if ps.runnable() and \
                (ps.dirty() or
                 completed_trigger or
                 (action == 'init' and not last_successful)):
            queued = queue_pipeline(ps, spec,
                                    'dirty-task-%s' % action
                                    if completed_trigger is None
                                    else completed_trigger)
            if queued:
                executed_count += 1
                if executed_count == 4 and action == 'update':
                    # Limit ops on update only
                    break

    if executed_count == 0 and action == 'update':
        extra_pipelines = status_all_pipeline_ids.difference(all_pipeline_ids)
        for pipeline_id in extra_pipelines:
            logging.info("Removing Pipeline: %s", pipeline_id)
            status_mgr().deregister(pipeline_id)
            dm.remove(pipeline_id)

@celery_app.task
def execute_scheduled_pipeline(pipeline_id):
    for spec in pipelines([pipeline_id]):
        if spec.pipeline_id == pipeline_id:
            logging.info('Running scheduled pipeline %s, with schedule %s (%r)',
                         pipeline_id, spec.schedule,
                         spec.pipeline_details.get('schedule'))
            update_pipelines.delay('scheduled', pipeline_id, 'scheduled')

@celery_app.task
def execute_pipeline_task(pipeline_id,
                          pipeline_details,
                          pipeline_cwd,
                          trigger,
                          execution_id):

    spec = PipelineSpec(pipeline_id=pipeline_id,
                        pipeline_details=pipeline_details,
                        path=pipeline_cwd)
    success, _, _ = \
        execute_pipeline(spec,
                         execution_id,
                         trigger,
                         False)

    if success:
        has_dependents = len(get_dep_mgr().get_dependents(spec.pipeline_id)) > 0
        logging.info('HAS DEPENDENTS %s: %s', pipeline_id, has_dependents)
        if has_dependents:
            update_pipelines.delay('complete', pipeline_id, trigger)


text:
namespace SQLServerSearcher.DAL.Contracts
{
    using System.Collections.Generic;

    using Model;

    public interface ITables
    {
        List<Table> FindTables(string database, string query = null);
        List<TableExtendedProperty> FindTableExtendedProperties(string database, string query);
        long FindTableRowCount(string database, string table);
        string GetFindTablesSql(string database, string query);
        string GetFindTableExtendedPropertiesSql(string database, string query);
        string GetFindTableRowCountSql(string database, string table);
    }
}


text:
layout: post
title:  XAP Community
categories: FAQ
weight: 200
parent: none
---

{% wbr %}

{%panel%}
- [What is GigaSpaces XAP-Community?](#1)

- [Why was it launched?](#2)

- [How does the XAP-Community compare to other freeware JavaSpaces implementations?](#3)

- [Can I use the XAP-Community in production?](#4)

- [I am an ISV, Can I embed the XAP-Community in a commercial product?](#5)

- [What is the difference between the XAP-Community and XAP?](#6)

- [What are the terms for using the XAP-Community?](#7)

- [What if I need support for the XAP-Community?](#8)

- [What are my upgrade options from the XAP-Community?](#9)
{%endpanel%}

{%anchor 1%}

### What is GigaSpaces XAP-Community?

The GigaSpaces eXtreme Application Platform - Community enables application developers to use a full, mature implementation of GigaSpaces XAP free of charge, both in development and in production environments. While GigaSpaces XAP-Community is limited to a single server node, it allows unlimited number of clients with local caches (Master/Local cache) which makes it ideal for small-scale applications that are not data-intensive.(read more at: [www.gigaspaces.com](http://www.gigaspaces.com).

{%anchor 2%}

### Why was it launched?

We hope that this initiative will help accelerate the adoption of JavaSpaces as the de-facto programming model for building grid-based applications, as well as offer developers a simple yet powerful tool to develop distributed, grid-based applications quickly.

{%anchor 3%}

### How does the XAP-Community compare to other freeware JavaSpaces implementations?

GigaSpaces users will benefit from the enhanced capabilities provided by the XAP-Community such as caching, indexing, SQL and RegExp query support, support for FIFO as well as superior performance.

{%anchor 4%}

### Can I use the XAP-Community in production?

Yes. The XAP-Community is available for use in production environments. (Please refer to the XAP-Community Licensing agreement for more information)

{%anchor 5%}

### I am an ISV, Can I embed the XAP-Community in a commercial product?

Yes. The XAP-Community is available for embedding within a commercial product. (Please refer to the XAP-Community Licensing agreement for more information)

{%anchor 6%}

### What is the difference between the XAP-Community and XAP?

GigaSpaces XAP offers a complete middleware platform (read more at: [http://www.gigaspaces.com](http://www.gigaspaces.com)) and is not free. The XAP-Community enables application developers to use a full, mature implementation of GigaSpaces XAP free of charge, both in development and in production environments. While GigaSpaces XAP-Community is limited to a single server node, it allows unlimited number of clients with local caches (Master/Local cache) which makes it ideal for small-scale applications that are not data-intensive. For more information about GigaSpaces XAP please contact sales at: [sales@gigaspaces.com](mailto:sales@gigaspaces.com)

{%anchor 7%}

### What are the terms for using the XAP-Community?

You can use the XAP-Community free of charge in both development and production environments. (Please refer to the XAP-Community Licensing agreement for more information)

{%anchor 8%}

### What if I need support for the XAP-Community?

Support for production environments or OEM is available at an annual flat-fee of $5,000.
Please contact sales@gigaspace.com for further details.

{%anchor 9%}

### What are my upgrade options from the XAP-Community?

If your needs necessitate more than what the XAP-Community has to offer, please contact [support@gigaspace.com](mailto:support@gigaspace.com) and we will provide you with the key that will enable you to upgrade to the complete XAP solution for a free 30 day trial period.

Please note that upgrading involves only a simple license change, there is no need to reinstall or change your existing XAP-Community version.


text:
**E**ndangered **S**oaring **A**frican **L**ynx-**P**idgeon is a **work in progress** OS by Calvin Lee and JJ Garzella

It is an implimentation of Phillipp Oppermann's [Blog OS](https://github.com/phil-opp/blog_os), go check out that repository and [his blog](http://os.phil-opp.com/) for more details.

## Project Goals
+ No C environment
  + ESALP will be written in Rust (and some Assembler of course)
+ Flexibility
+ **More to come**

## Features
Right now it doesn't do much, but more is added every day!

Current features:
+ Interaction
  + Can print to the VGA text buffer (in 255 different colors!)
  + Simple PS/2 keyboard driver
    + with multiple keyboard maps
  + Can print to the serial bus
+ Memory
  + Simple paging
    + With physical frame allocation _and_ deallocation
  + Kernel space heap
+ Text-based unit tests powered by [TAP](https://testanything.org/)
+ Multitasking
  + Basic kernel threads
+ **More to come**

## How to Compile
1. Install packages, ESALP requires `xargo`, `nasm`, `grub-mkrescue`, `ld`, and a unix environment to build. To run, use `qemu`.
2. Use `make all` to build ESALP
3. `make run` and you're done!

If you want to run regressions, use `make test`

### Compilation on macOS
ESALP also supports compilation on macOS. As macOS uses mostly Apple's infrastructure rather than linux's, it requires a bit more setup.
#### Compile Assembly on macOS
1. Homebrew
	- gcc
	- autoconf
	- xorriso
	- nasm
2. MacPorts
	- libmpc
	- gmp
	- mpfr
* 2.5. Optional: Compile libiconv
3. Cross-compile Binutils
	- use phil's page: http://os.phil-opp.com/cross-compile-binutils.html
	- include option --program-prefix
4. Cross-compile GCC
	- use OSDev page: http://wiki.osdev.org/GCC_Cross-Compiler
	- include option --program-prefix
5. Compile grub
	- use OSDev page on grub: http://wiki.osdev.org/GRUB#Installing_GRUB2_on_Mac_OS_X
	- put in platform-specific tools
#### Set up Rust on macOS
1. Install rustup
2. Get the proper nightly build in your folder
3. Homebrew
	- cmake
	- openssl
4. put a symlink to openssl in /usr/local/include
	- https://solitum.net/openssl-os-x-el-capitan-and-brew/
5. Install xargo
	- "cargo install xargo"
#### Running on macOS
+ Because we cross-compiled binutils earlier, we need to use `make all cross=yes` and `make run cross=yes`

### Notes:
+ If your system binutils is not x86_64-elf format, for example in macOS (see above), you need to cross-compile binutils. By adding `cross=yes` to both make commands, the prefix `x86_64-elf-` will be added to all binutils commands.
+ `int=yes` prints out the registers on an interrupt and `reboot=no` stops qemu from rebooting. If you're stuck in an infinite reboot loop, `make run int=yes reboot=no` could be helpful
+ If kvm is your thing, run with `kvm=yes`

## Licensing
This code is licensed under the MIT license. See LICENSE for more details.


text:
<!DOCTYPE html>

  <title>goog.ui.SubMenu</title>

  <link rel="stylesheet" href="css/demo.css">
  <link rel="stylesheet" href="../css/menu.css">
  <link rel="stylesheet" href="../css/menuitem.css">
  <link rel="stylesheet" href="../css/menuseparator.css">
  <link rel="stylesheet" href="../css/submenu.css">

goog.ui.SubMenu

Demonstration of different hierarchical menus which share its submenus.
  A flyweight pattern demonstration for submenus.

<button id="button">Open menu</button>

Google

Yahoo

MSN

Bla...


text:
@@echo off

SHIFT

IF "%1"=="--help"  (
    goto Help
) ELSE (
	IF NOT "%1"=="" (
		echo unrecogized argument^(s^), try using the "--help" switch
        goto End
	) ELSE (
		goto listInstalled
	)
)

:Help
echo --installed
echo     Lists the installed versions of Python
goto End

:listInstalled
for /d %%X in (%PYWE_HOME%\versions\*) do echo %%~nxX
goto End

:End
rem ends this script


text:
<?php

declare(strict_types=1);

namespace WoohooLabs\Worm\Model\Relationship;

use WoohooLabs\Larva\Query\Condition\ConditionBuilderInterface;

interface RelationshipBuilderInterface
{
    public function distinct(bool $isDistinct = true): RelationshipBuilderInterface;

    public function where(ConditionBuilderInterface $where): RelationshipBuilderInterface;

    public function addWhereGroup(ConditionBuilderInterface $where, string $operator = "AND"): RelationshipBuilderInterface;

    public function groupBy(string $attribute): RelationshipBuilderInterface;

    public function groupByAttributes(array $attributes): RelationshipBuilderInterface;

    public function having(ConditionBuilderInterface $having): RelationshipBuilderInterface;

    public function orderBy(string $attribute, string $direction = "ASC"): RelationshipBuilderInterface;

    public function limit(?int $limit): RelationshipBuilderInterface;

    public function offset(?int $offset): RelationshipBuilderInterface;

    public function toRelationship(): RelationshipInterface;
}


text:
package org.tinymediamanager.scraper;

import java.io.IOException;
import java.io.InvalidObjectException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamException;
import java.lang.reflect.Array;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * The class DynaEnum is used to create a "dynamic" enum - an enum which is extensible at runtime
 *
 * @param <E>
 *          the element type
 * @author Manuel Laggner
 * @since 1.0
 */
public class DynaEnum<E extends DynaEnum<E>> {
  private static Map<Class<? extends DynaEnum<?>>, Map<String, DynaEnum<?>>>   elements  = new LinkedHashMap<>();
  private static Map<Class<? extends DynaEnum<?>>, Set<DynaEnumEventListener>> listeners = new LinkedHashMap<>();
  private final String                                                         name;
  protected final int                                                          ordinal;

  public final String name() {
    return name;
  }

  /**
   * Ordinal.
   *
   * @return the int
   */
  public final int ordinal() {
    return ordinal;
  }

  /**
   * Instantiates a new dyna enum.
   *
   * @param name
   *          the name
   * @param ordinal
   *          the ordinal
   */
  protected DynaEnum(String name, int ordinal) {
    this.name = name;
    this.ordinal = ordinal;
    Map<String, DynaEnum<?>> typeElements = elements.get(getClass());
    if (typeElements == null) {
      typeElements = new LinkedHashMap<>();
      elements.put(getDynaEnumClass(), typeElements);
    }
    typeElements.put(name, this);

    valueAdded(getClass(), this);
  }

  /**
   * Gets the dyna enum class.
   *
   * @return the dyna enum class
   */
  @SuppressWarnings("unchecked")
  private Class<? extends DynaEnum<?>> getDynaEnumClass() {
    return (Class<? extends DynaEnum<?>>) getClass();
  }

  @Override
  public String toString() {
    return name;
  }

  @Override
  public final boolean equals(Object other) {
    return this == other;
  }

  @Override
  public final int hashCode() {
    return super.hashCode();
  }

  @Override
  protected final Object clone() throws CloneNotSupportedException {
    throw new CloneNotSupportedException();
  }

  public final int compareTo(E other) {
    DynaEnum<?> self = this;
    if (self.getClass() != other.getClass() && // optimization
        self.getDeclaringClass() != other.getDeclaringClass()) {
      throw new ClassCastException();
    }
    return self.ordinal - other.ordinal;
  }

  @SuppressWarnings({ "unchecked", "rawtypes" })
  public final Class<E> getDeclaringClass() {
    Class clazz = getClass();
    Class zuper = clazz.getSuperclass();
    return (zuper == DynaEnum.class) ? clazz : zuper;
  }

  /**
   * Value of.
   *
   * @param <T>
   *          the generic type
   * @param enumType
   *          the enum type
   * @param name
   *          the name
   * @return the t
   */
  @SuppressWarnings("unchecked")
  public static <T extends DynaEnum<T>> T valueOf(Class<T> enumType, String name) {
    return (T) elements.get(enumType).get(name);
  }

  /**
   * Read object.
   *
   * @param in
   *          the in
   * @throws IOException
   *           Signals that an I/O exception has occurred.
   * @throws ClassNotFoundException
   *           the class not found exception
   */
  private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException {
    throw new InvalidObjectException("can't deserialize enum");
  }

  /**
   * Read object no data.
   *
   * @throws ObjectStreamException
   *           the object stream exception
   */
  @SuppressWarnings("unused")
  private void readObjectNoData() throws ObjectStreamException {
    throw new InvalidObjectException("can't deserialize enum");
  }

  /**
   * Values.
   *
   * @param <E>
   *          the element type
   * @return the dyna enum<? extends dyna enum<?>>[]
   */
  public static <E> DynaEnum<? extends DynaEnum<?>>[] values() {
    throw new IllegalStateException("Sub class of DynaEnum must implement method values()");
  }

  /**
   * Values.
   *
   * @param <E>
   *          the element type
   * @param enumType
   *          the enum type
   * @return the e[]
   */
  @SuppressWarnings("unchecked")
  public static <E> E[] values(Class<E> enumType) {
    Collection<DynaEnum<?>> values = elements.get(enumType).values();
    int n = values.size();
    E[] typedValues = (E[]) Array.newInstance(enumType, n);
    int i = 0;
    for (DynaEnum<?> value : values) {
      Array.set(typedValues, i, value);
      i++;
    }

    return typedValues;
  }

  /**
   * add a new DynaEnumEventListener. This listener will be informed if any new value has been added
   *
   * @param clazz
   *          the class to register the listener for
   * @param listener
   *          the new listener to be added
   */
  protected static void addListener(Class<? extends DynaEnum<?>> clazz, DynaEnumEventListener listener) {
    Set<DynaEnumEventListener> listenerSet = listeners.get(clazz);
    if (listenerSet == null) {
      listenerSet = new HashSet<>();
      listeners.put(clazz, listenerSet);
    }
    listenerSet.add(listener);
  }

  /**
   * remove the given DynaEnumEventListener
   *
   * @param clazz
   *          the class to de-register the listener for
   * @param listener
   *          the listener to be removed
   */
  protected static void removeListener(Class<? extends DynaEnum<?>> clazz, DynaEnumEventListener listener) {
    Set<DynaEnumEventListener> listenerSet = listeners.get(clazz);
    if (listenerSet != null) {
      listenerSet.remove(listener);
    }
  }

  protected static void valueAdded(Class<? extends DynaEnum> clazz, DynaEnum<?> value) {
    Set<DynaEnumEventListener> listenerSet = listeners.get(clazz);
    if (listenerSet != null) {
      try {
        for (DynaEnumEventListener listener : listenerSet) {
          listener.valueAdded(value);
        }
      }
      catch (Exception ignored) {
      }
    }
  }

  /**
   * DynaEnumEventListener is the interface for getting informed if any new items are added
   *
   * @param <E>
   *          the type of the enum
   */
  public interface DynaEnumEventListener<E> {
    void valueAdded(E value);
  }
}


text:
def call0():
    for x in 1: print x

for x in range(1, 1001):
    exec("def call%s(): call%s()" % (x, x - 1))

import unittest

class TypeErrorRegression(unittest.TestCase):
    pass

  # This is a negative test that tested the UI error msg -- should be ported to JS
  #def test_typeerror_thrown_for_iterating(self):
  #  try:
  #    call100()
  #  except TypeError, e:
  #    # TODO verify that the exception matches these conditions:
  #    exp = {
  #        'type': 'TypeError',
  #        'exp.error_message': "TypeError: iteration over non-sequence of type int",
  #        'exp.error_source_file': "test.py",
  #        'exp.error_source_line': 4,
  #        'exp.error_stack': [
  #            'at call0 in test.py, line 4'] + [
  #            'at call%d in <string>, line 1' % x for x in range(1, 100)
  #        ]
  #    }
  #    self.fail()


text:
Timers
======

Djangular Demonstration App for the Seattle AngularJS Meetup:
* [Deployed app](http://ec2-54-148-78-141.us-west-2.compute.amazonaws.com/)
* [Presentation slides](https://docs.google.com/presentation/d/1XFPEjhNFhTunOpFZ2ueJxDNBnUyti1fvoaiS-QIAebg/)

Single Page Angular App is served by a SimpleHTTPServer.

Django Rest Framework backend provides API endpoints for the Angular app to communicate with.


text:
package com.polidea.rxandroidble.internal.operations;

import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattDescriptor;

import com.polidea.rxandroidble.exceptions.BleGattCannotStartException;
import com.polidea.rxandroidble.exceptions.BleGattOperationType;
import com.polidea.rxandroidble.internal.RxBleRadioOperation;
import com.polidea.rxandroidble.internal.connection.RxBleGattCallback;

import rx.Subscription;

public class RxBleRadioOperationDescriptorWrite extends RxBleRadioOperation<byte[]> {

    private final RxBleGattCallback rxBleGattCallback;

    private final BluetoothGatt bluetoothGatt;

    private final BluetoothGattDescriptor bluetoothGattDescriptor;

    private final byte[] data;

    public RxBleRadioOperationDescriptorWrite(RxBleGattCallback rxBleGattCallback, BluetoothGatt bluetoothGatt,
                                              BluetoothGattDescriptor bluetoothGattDescriptor, byte[] data) {
        this.rxBleGattCallback = rxBleGattCallback;
        this.bluetoothGatt = bluetoothGatt;
        this.bluetoothGattDescriptor = bluetoothGattDescriptor;
        this.data = data;
    }

    @Override
    public void run() {
        //noinspection Convert2MethodRef
        final Subscription subscription = rxBleGattCallback
                .getOnDescriptorWrite()
                .filter(uuidPair -> uuidPair.first.equals(bluetoothGattDescriptor))
                .first()
                .map(uuidPair -> uuidPair.second)
                .doOnCompleted(() -> releaseRadio())
                .subscribe(getSubscriber());

        bluetoothGattDescriptor.setValue(data);
        final boolean success = bluetoothGatt.writeDescriptor(bluetoothGattDescriptor);
        if (!success) {
            subscription.unsubscribe();
            onError(new BleGattCannotStartException(BleGattOperationType.DESCRIPTOR_WRITE));
        }
    }
}


text:
SmppWizard 1.0.0

A RESTful based smpp client which is hosted as a service.
Its uses the "dropwizard" (http://dropwizard.codahale.com/) to add REST support
and "cloudhopper" (https://github.com/twitter/cloudhopper-smpp) to handle the SMPP boilerplate.


text:
layout: page
title: Larson - Walters Wedding
date: 2016-05-24
author: Keith Rasmussen
tags: weekly links, java
status: published
summary: Nunc a ex hendrerit, ultrices justo.
banner: images/banner/wedding.jpg
booking:
  startDate: 04/22/2019
  endDate: 04/24/2019
  ctyhocn: COVLAHX
  groupCode: LWW
published: true
---
Etiam sit amet mi lectus. Ut fringilla dui a nisi fringilla viverra. Sed orci turpis, rutrum vel dui varius, molestie sollicitudin justo. Cras sagittis accumsan odio, et porta ex sagittis a. Cras dictum nibh sed aliquet rhoncus. Quisque congue sit amet magna eget pretium. Etiam pharetra sem id dignissim fermentum. Fusce semper, turpis ut interdum luctus, lectus nisl tempor diam, quis hendrerit turpis purus in sem.
Cras egestas metus quis purus volutpat, non maximus ex commodo. Curabitur euismod tellus ante, non varius sapien dapibus id. Cras tincidunt hendrerit quam. Cras vel metus tristique diam viverra eleifend a ut ipsum. Proin et dolor a arcu consequat rutrum. Cras eu lobortis metus. Praesent convallis non sem in ultricies. Curabitur laoreet, velit ut faucibus interdum, ante ipsum egestas urna, ut aliquam diam erat vitae nunc. Praesent sit amet sapien leo. Mauris eu orci tellus. Pellentesque faucibus nibh orci, at tempor tellus mattis ac. Ut vestibulum non lectus rhoncus vestibulum.

1 Praesent molestie nunc sed porttitor dictum.

Suspendisse potenti. Praesent dignissim, magna at suscipit porta, mauris ante consequat tortor, eu venenatis risus nulla at arcu. Maecenas a euismod turpis, euismod ornare ex. Sed volutpat consectetur commodo. Morbi arcu metus, luctus id gravida cursus, fermentum nec libero. Sed rutrum non tortor quis semper. Sed ante mauris, bibendum id mauris ac, blandit dapibus odio. Nulla ut mollis dolor, commodo suscipit ipsum. Praesent porta euismod magna, id facilisis odio mattis vel.


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Scott. Natural. 6: 106 (1881)

#### Original name
Usnea oncodes Stirt.

### Remarks
null


text:
using Arragro.Core.Common.BusinessRules;
using System;

namespace ArragroCMS.BusinessLayer.Data.Entities
{
    public class Setting : Auditable<Guid>
    {
        public int SettingId { get; set; }
        public string Name { get; set; }
        public string Value { get; set; }
    }
}


text:
package org.hisp.dhis.option;

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.databind.annotation.JsonSerialize;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlRootElement;
import org.hisp.dhis.common.BaseIdentifiableObject;
import org.hisp.dhis.common.DxfNamespaces;
import org.hisp.dhis.schema.PropertyType;
import org.hisp.dhis.schema.annotation.Property;

/**
 * @author Chau Thu Tran
 */
@JacksonXmlRootElement( localName = "option", namespace = DxfNamespaces.DXF_2_0 )
public class Option
    extends BaseIdentifiableObject
{
    private OptionSet optionSet;

    public Option()
    {
        setAutoFields();
    }

    public Option( String name, String code )
    {
        this();
        this.name = name;
        this.code = code;
    }

    @Override
    public boolean haveUniqueNames()
    {
        return false;
    }

    @Override
    public boolean haveUniqueCode()
    {
        return false;
    }

    @Override
    @JsonProperty
    @JacksonXmlProperty( isAttribute = true )
    @Property( PropertyType.TEXT )
    public String getCode()
    {
        return super.getCode();
    }

    @JsonProperty
    @JsonSerialize( as = BaseIdentifiableObject.class )
    @JacksonXmlProperty( namespace = DxfNamespaces.DXF_2_0 )
    public OptionSet getOptionSet()
    {
        return optionSet;
    }

    public void setOptionSet( OptionSet optionSet )
    {
        this.optionSet = optionSet;
    }
}


text:
import Component from 'flarum/Component';
import LoadingIndicator from 'flarum/components/LoadingIndicator';
import icon from 'flarum/helpers/icon';

/**
 * The `Checkbox` component defines a checkbox input.
 *
 * ### Props
 *
 * - `state` Whether or not the checkbox is checked.
 * - `className` The class name for the root element.
 * - `disabled` Whether or not the checkbox is disabled.
 * - `onchange` A callback to run when the checkbox is checked/unchecked.
 * - `children` A text label to display next to the checkbox.
 */
export default class Checkbox extends Component {
  constructor(...args) {
    super(...args);

    /**
     * Whether or not the checkbox's value is in the process of being saved.
     *
     * @type {Boolean}
     * @public
     */
    this.loading = false;
  }

  view() {
    let className = 'Checkbox ' + (this.props.state ? 'on' : 'off') + ' ' + (this.props.className || '');
    if (this.loading) className += ' loading';
    if (this.props.disabled) className += ' disabled';

    return (
      <label className={className}>
        <input type="checkbox"
          checked={this.props.state}
          disabled={this.props.disabled}
          onchange={m.withAttr('checked', this.onchange.bind(this))}/>
        <div className="Checkbox-display">
          {this.getDisplay()}
        </div>
        {this.props.children}
      </label>
    );
  }

  /**
   * Get the template for the checkbox's display (tick/cross icon).
   *
   * @return {*}
   * @protected
   */
  getDisplay() {
    return this.loading
      ? LoadingIndicator.component({size: 'tiny'})
      : icon(this.props.state ? 'check' : 'times');
  }

  /**
   * Run a callback when the state of the checkbox is changed.
   *
   * @param {Boolean} checked
   * @protected
   */
  onchange(checked) {
    if (this.props.onchange) this.props.onchange(checked, this);
  }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<doctrine-mapping xmlns="http://doctrine-project.org/schemas/orm/doctrine-mapping" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://doctrine-project.org/schemas/orm/doctrine-mapping http://doctrine-project.org/schemas/orm/doctrine-mapping.xsd">
  <entity name="Proyecto\PrincipalBundle\Entity\D100tProdU4rgp" table="d100t_prod_u4rgp">
    <change-tracking-policy>DEFERRED_IMPLICIT</change-tracking-policy>
    <id name="d100pkProdU4rgp" type="integer" column="d100pk_prod_u4rgp">
      <generator strategy="IDENTITY"/>
    </id>
    <field name="feFecha" type="datetime" column="fe_fecha" precision="0" scale="0"/>
    <field name="txTipodesal" type="text" column="tx_tipodesal" precision="0" scale="0"/>
    <field name="nuNdematiz" type="integer" column="nu_ndematiz" precision="0" scale="0"/>
    <field name="nuPorcentaje" type="integer" column="nu_porcentaje" precision="0" scale="0"/>
    <field name="nuPan" type="integer" column="nu_pan" precision="0" scale="0"/>
    <many-to-one field="i100fkUsuario" target-entity="Proyecto\PrincipalBundle\Entity\I100tUsuario" orphan-removal="">
      <join-columns>
        <join-column name="i100fk_usuario" referenced-column-name="i100pk_usuario" nullable="1"/>
      </join-columns>
    </many-to-one>
    <lifecycle-callbacks/>
  </entity>
</doctrine-mapping>


text:
from __future__ import print_function
from acq4.util import Qt
from collections import OrderedDict

import six

class DictView(Qt.QTreeWidget):
    def __init__(self, data, parent=None):
        Qt.QTreeWidget.__init__(self, parent)
        self.setData(data)
        self.setColumnCount(2)
        self.setHeaderLabels(['key', 'value'])
        self.setVerticalScrollMode(self.ScrollPerPixel)

    def setData(self, data):
        """data should be a dictionary."""
        self.clear()
        node = self.mkNode('', data)
        while node.childCount() > 0:
            c = node.child(0)
            node.removeChild(c)
            self.invisibleRootItem().addChild(c)
        self.expandToDepth(3)
        self.resizeColumnToContents(0)

    def mkNode(self, name, v):
        if type(v) is list and len(v) > 0 and isinstance(v[0], dict):
            inds = list(map(six.text_type, range(len(v))))
            v = OrderedDict(zip(inds, v))
        if isinstance(v, dict):
            #print "\nadd tree", k, v
            node = Qt.QTreeWidgetItem([name])
            for k in v:
                newNode = self.mkNode(k, v[k])
                node.addChild(newNode)
        else:
            #print "\nadd value", k, str(v)
            node = Qt.QTreeWidgetItem([six.text_type(name), six.text_type(v)])
        return node

    def close(self):
        self.clear()
        self.setParent(None)


text:
#ifndef DelphesLCIOConverter_h
#define DelphesLCIOConverter_h

#include <string>
#include <map>
#include <functional>

#include "DelphesLCIOConfig.h"

class TTree;
class TClonesArray;
class TObject;

namespace IO{ class LCWriter ; }
namespace EVENT{
  class LCEvent ;
  class MCParticle;
  class ReconstructedParticle;
  class LCCollection;
}
namespace IMPL{
  class LCEventImpl ;
  class LCCollectionVec;
}

namespace UTIL{
  class LCRelationNavigator;
}

/** \class DelphesLCIOConverter
 *
 *  Class handling output of ROOT tree in LCIO
 *
 *  \author F.Gaede, DESY
 *  \date June 2020
 *
 */
class DelphesLCIOConverter {
public:

  ///c'tor intializes an LCWriter if valid non-empty file name given
  DelphesLCIOConverter(const char* fileName = "" );

  /// d'tor
  ~DelphesLCIOConverter();

  /// read the configuration file with parameter maps containing collection and branch names etc.
  void readConfigFile( const char* fileName ) ;

  /// convert the Delphes tree to LCIO collections and add them to the event
  void convertTree2LCIO( TTree *tree , IMPL::LCEventImpl* evt ) ;

  /// create a new LCIO event and write it to the writer (if valid)
  void writeEvent( TTree* tree ) ;

  /** Helper function to convert convert a (isolated) particle reference collection. Assumes that the referenced
   *  ReconstructedParticles (PFOs) have been created and are in the relation nafigator. If pdg is given the PFO
   *  type is set to pdg*charge.
   */
  bool convertPFORefCollection( TClonesArray* tca, EVENT::LCCollection* col, UTIL::LCRelationNavigator& mcrecNav,
			       std::function<unsigned(TObject*)> uid, int pdg=-99 ) ;

  /** Helper function to convert convert a jet collection. Assumes that the referenced
   *  ReconstructedParticles (PFOs) have been created beforehand. If useDelphes4Vec != 0  the four vector from
   *  the Delphes jet is used otherwise it is computed from the constituent PFOs.
   */
  bool convertJetCollection( TClonesArray* tca, EVENT::LCCollection* col, int useDelphes4Vec, int storeYMerge ) ;

  /** Helper function to convert extra charged (Track) particles to ReconstructedParticles (PFOs).
   *  The new elements are added to the LCIO collection. They will not be linked to the MCParticles as is done
   *  for the standard PFOs.
   */
  int convertExtraPFOsCharged(  TClonesArray* tca, EVENT::LCCollection* col, int pdg, double mass );

  /** Helper function to convert extra neutral (Tower) particles to ReconstructedParticles (PFOs).
   *  The new elements are added to the LCIO collection. They will not be linked to the MCParticles as is done
   *  for the standard PFOs.
   */
  int convertExtraPFOsNeutral(  TClonesArray* tca, EVENT::LCCollection* col, int pdg, double mass );

private:
  IO::LCWriter *_writer=nullptr;
  IMPL::LCCollectionVec *_evtSumCol=nullptr;

  std::map< unsigned, EVENT::MCParticle*> _mcpd2lmap ;
  std::map< unsigned, EVENT::ReconstructedParticle*> _recd2lmap ;

  DelphesLCIOConfig* _cfg ;
  DelphesLCIOConfig::FloatMap  _evtParF ; /// optional float event parameters
  DelphesLCIOConfig::IntMap    _evtParI ; /// optional int event parameters
  DelphesLCIOConfig::StringMap _evtParS ; /// optional string event parameters
};

#endif /* DelphesLCIOConverter */


text:
CREATE TABLE `business_company` (
`id_company`  int NOT NULL ,
`company_name`  varchar(255) NOT NULL ,
`company_slogan`  varchar(255) NULL ,
`company_address`  varchar(255) NOT NULL ,
`city`  varchar(255) NOT NULL ,
`state`  varchar(255) NOT NULL ,
`zip`  varchar(255) NOT NULL ,
`phone`  varchar(255) NOT NULL ,
`fax`  varchar(255) NULL ,
PRIMARY KEY (`id_company`)
)
ENGINE=InnoDB
DEFAULT CHARACTER SET=utf8 COLLATE=utf8_general_ci
ROW_FORMAT=DYNAMIC
;


text:
module UDDFactor
include GenFactor
include MortalityTable

  ##
  # Calculates the present value of each unit payment and sums them to create a factor.
  # This method lacks the validation of generate_factor.  {#generate_factor} should be called instead.
  #
  # @return [float] Present Value Factor
  #
  # @todo protect this method
  #
  # @since version 1.0.0
  ##
  def calculate_present_value()
    returnValue = singlePV = spousePV = jointPV = time = payment = 0.0
    age = @immediate_age
    dAge = @commencement_age
    lxZero = lxZeroSpouse = LX_ZERO
    sAge = @secondary_age
    jointCalc = @joint_survivor_type

    mortalityDiscount = mortalityDiscountSpouse = mortalityDiscountJoint = 1.0

    lX = lxZero
    lXSpouse = lxZeroSpouse

    dX = calculate_dx(0.0,lX,age.truncate,@primary_mortality)
    dXSpouse = calculate_dx(0.0,lXSpouse,sAge.truncate,@secondary_mortality)

    lX = calculate_initial_lx(lX,dX,age)
    lxZero = lX

    lXSpouse = calculate_initial_lx(lXSpouse,dXSpouse,sAge)
    lxZeroSpouse = lXSpouse

    if 0.0 == lX
      retVal = 0.0 #everyone is already dead yo.
    else
      jointCalculationValid = false
      if jointCalc > 0.0 and lXSpouse > 0.0
        jointCalculationValid = true
      end
      while (lX > 0.0) or (jointCalculationValid)
        monthlyTime = time / 12.0
        if SEGMENT_TWO > monthlyTime
          interestRate = @interest_segment_a
        elsif SEGMENT_THREE > monthlyTime
          interestRate = @interest_segment_b
        else
          interestRate = @interest_segment_c
        end

        if age < dAge
          payment = 0.0
        else
          payment = (1.0/12.0)
        end

        if @temporary_period > 0.0
          if age >= (@temporary_period + dAge)
            payment = 0.0
          end
        end

        singlePV += GenFactor::unit_payment(mortalityDiscount,interestRate,time,payment)
        if jointCalc > 0.0
          sAge = add_month(sAge)
          if lXSpouse > 0.0
            spousePV += GenFactor::unit_payment(mortalityDiscountSpouse,interestRate,time,payment)
            jointPV += GenFactor::unit_payment(mortalityDiscountJoint,interestRate,time,payment)
          else
            jointCalculationValid = false
          end
        end

        time += 1.0
        age = add_month(age)

        lX = lX - dX
        lXSpouse = lXSpouse - dXSpouse

        dX = calculate_dx(dX,lX,age,@primary_mortality)
        dXSpouse = calculate_dx(dXSpouse,lXSpouse,sAge,@secondary_mortality)
        if ((nil != @certain_period) and age >= (dAge + @certain_period) || age <= dAge) or (nil == @certain_period)
            mortalityDiscount = GenFactor::calculate_discount(lX, lxZero)
            mortalityDiscountSpouse = GenFactor::calculate_discount(lXSpouse,lxZeroSpouse)
            mortalityDiscountJoint = mortalityDiscount * mortalityDiscountSpouse
        end

      end #end while 0.0 < lX
    end #end if lx = 0.0

    returnValue = calculate_joint_factor(singlePV,spousePV,jointPV,@joint_survivor_type,@joint_survivor_percent)
    round_factor(returnValue,@rounding)
  end
  module_function :calculate_present_value

  ##
  # Validates input parameters then generates a Present Value Factor.
  #
  # @raise [InvalidFloat] if any input parameter cannot be converted to a float, it will produce an error.
  # @raise [DefTemp] if immediateAge < commencementAge and tempPeriod > 0, will throw an error.
  # @raise [ImmComm] if immediateAge > commencementAge, will throw an error.
  #
  # @todo Add in verbose mode.
  #
  # @return [float,string,true] If outputType = 0, outputs a present value factor or an error message.
  #                             If outputType =1 , outputs true or an error message.
  #
  # @since version 1.0.0
  ##
  def generate_factor()
	  #set default blank input items
    self.default_values

	  #check to make sure we can do the calculation first
    self.validation
  	#now check for logical errors
  	self.validate_logic_errors

	  if @errors.empty?
		  if 0 == @output_type
			  calculate_present_value
		  else
			  true
		  end #if outputType is 0

	  else #errors is not empty
      @errors
	  end #if errors.empty?
  end

  ##
  # Validates a single field and adds to the error messages if it is invalid.
  #
  # @param [float] age - The value to be validated
  # @param [String] errorMessage - Error messages to be added if an error is raised
  # @param [float] radix - 1.0 for ages, 2.0 for interests, 3.0 for js_type, 4.0 for js_pct, 5 for rounding validation
  #
  # @since 2.0.0
  ##
  def validate_single_field(age,errorMessage,radix)
    begin
      case radix
        when 1.0
	        GenFactor::sanitize_age(Float(age))
	      when 2.0
	        GenFactor::sanitize_interest(Float(age))
	      when 3.0
	        GenFactor::sanitize_js_type(Float(age))
        when 4.0
          jsPct = GenFactor::sanitize_js_pct(Float(age))
       else
        Float(age)
      end
	  rescue
      self.append_error(errorMessage)
	  end
  end

  ##
  # Validates the mortality tables for potential errors
  #
  # @raise [Non-Array] - If the Mortality table isn't an array
  # @raise [InvalidFloat] - If the table has non-numeric fields
  # @raise [InvalidEnd] - If the last row does not have a q(x) = 1.0
  #
  # @since version 2.0.0
  ##
  def validate_mortality(mortality,type)
		unless mortality.is_a? Array
		  errorString = type + " Mortality: Mortality Table must be an array"
		  self.append_error(errorString)
		else
		  cErrorCount = 0.0
		  mortality.each do |ii|
		    begin
		      tempy = ii
		      tempo = Float(tempy[0])
		      tempsan = Float(tempy[1])
		    rescue
	          cErrorCount += 1.0
		    end
	    end
	    if cErrorCount > 0.0
	      errorString = type + " Mortality: Invalid mortality table format: cannot convert all elements to numbers"
        self.append_error(errorString)
      else
        unless (mortality[0][0] == 0.0) and (mortality[0][1] == 0.0)
          errorString = type + " Mortality: Invalid mortality table format: first row is not 0.0,0.0"
          self.append_error(errorString)
        end
        unless mortality[-1][1] == 1.0
          errorString = type + " Mortality: Invalid mortality table format: last row does not have a q(x) of 1.0"
         self.append_error(errorString)
        end
      end
		end
  end

  ##
  # Sets all the instance variables to default values
  #
  # @since version 2.0.0
  ##
  def default_values()
	  @immediate_age = GenFactor::set_default(@immediate_age,@commencement_age)
	  @secondary_age = GenFactor::set_default(@secondary_age,0.0)
	  @joint_survivor_type = GenFactor::set_default(@joint_survivor_type,0.0)
	  @joint_survivor_percent = GenFactor::set_default(@joint_survivor_percent,0.0)
	  @primary_mortality = GenFactor::set_default(@primary_mortality,MortalityTable::PPA2009)
	  @secondary_mortality = GenFactor::set_default(@secondary_mortality,@primary_mortality)
	  @interest_segment_b = GenFactor::set_default(@interest_segment_b,@interest_segment_a)
	  @interest_segment_c = GenFactor::set_default(@interest_segment_c,@interest_segment_a)
	  @certain_period = GenFactor::set_default(@certain_period,0.0)
	  @temporary_period = GenFactor::set_default(@temporary_period,0.0)
	  @rounding = GenFactor::set_default(@rounding,12.0)
	  @output_type = GenFactor::set_default(@output_type,0.0)
  end

  ##
  # Validates all the instance variables to ensure a calculation can be run
  #
  # @since version 2.0.0
  ##
  def validation()
	  @immediate_age = validate_single_field(@immediate_age,"Immediate age cannot be converted into a number",1.0)
	  @commencement_age = validate_single_field(@commencement_age,"Commencement age cannot be converted into a number",1.0)
	  @secondary_age = validate_single_field(@secondary_age,"Spousal age cannot be converted into a number",1.0)
	  @joint_survivor_type = validate_single_field(@joint_survivor_type,"JS Type cannot be converted into a number",3.0)
    @joint_survivor_percent = validate_single_field(@joint_survivor_percent,"JS percent cannot be converted into a number",4.0)
    validate_mortality(@primary_mortality,"Primary")
    validate_mortality(@secondary_mortality,"Secondary")
		@interest_segment_a = validate_single_field(@interest_segment_a,"Interest segment A cannot be converted into a number",2.0)
    @interest_segment_b = validate_single_field(@interest_segment_b,"Interest segment B cannot be converted into a number",2.0)
    @interest_segment_c = validate_single_field(@interest_segment_c,"Interest segment C cannot be converted into a number",2.0)
    @certain_period = validate_single_field(@certain_period,"Certain period cannot be converted into a number",1.0)
    @temporary_period = validate_single_field(@temporary_period,"Temporary period cannot be converted into a number",1.0)
    @rounding = validate_single_field(@rounding,"Rounding cannot be converted into a number",5.0)
  end

  ##
  # Validates the logic errors that can occur and a calculation shouldn't take place.
  #
  # @since version 2.0.0
  ##
  def validate_logic_errors
    if @errors.empty?
		  if (@immediate_age < @commencement_age) && (@temporary_period > 0.0)
			  self.append_error("Error: Deferred Calculation with a Temporary Period")
		  end
		  if (@immediate_age > @commencement_age)
        self.append_error("Error: Commencement age must be greater than or equal to immediate age")
		  end
	  end #if errors.empty?
	end
end


text:
"""@package tools
@brief   Utility tool sets
@author  Marcel H
@date    2017

@parblock
@b Classes
@li Traceable           Base class for adding traceability and debuggability.

@b Functions
@li typename                   Retrieve type name of an object.
@li fullobjname                Retrieve full name (incl. module) of an object.
@li str_current_time           Retrieve current time in string format.
@li join_recursive             Join string list or tuples recursively.
@li getobj                     Get an object from a module.
@li is_iterable                Returns true if its an iterable.
@li split                      Split an array according to the indices given.
@li find_uniques_consecutive   Find consecutive duplicates within the array.
@li get_uniques                Get elements that are duplicated within the array.
@li is_file                    Determine whether a string refers to a file.
@li is_dir                     Determine whether a string refers to a directory.
@li resolve                    Resolve directory.
@li check_dir                  Raises an exception if directory is invalid.
@li assert_cond                Assert that a condition is true.
@li assert_type                Type checking w/ assertion.
@li swap_inarray               Swaps 2 elements inside an array.
@li geo_seq                    Geometric sequence

@b Exceptions
@li N/A
@endparblock

@copyright Copyright (c) 2017 Marcel H

 MIT License

 Copyright (c) 2017 mh0401

 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.

"""
from pathlib import Path
from typing import Iterable
from operator import xor
from time import strftime, gmtime, process_time
from importlib import import_module
from enum import IntEnum, unique
from . import TypeCheckError

######################################################
## @publicsection

def typename(obj):
    """Get the qual name of an object.
    @param  obj   Object in question.
    @return       The type of the object.
    """
    return obj.__name__ if hasattr(obj, '__name__') else type(obj).__qualname__

def fullobjname(obj):
    """Get the full name of an object (including its module).
    @param  obj   Object in question.
    @return       Module name <.> object name.
    """
    return obj.__module__ + '.' + typename(obj)

def str_current_time():
    """Returns the current time string format for suffix to a string.
    @return     Current time string format of yy_mm_dd_hr_min_sec_timezone
    """
    return strftime("%Y_%m_%d_%H_%M_%S_%Z", gmtime())

def join_recursive(lst, sep):
    """Utility function for joining string tuples recursively.
    @param  lst  List or tuple to be joined which contain list/tuples within.
    @return      Joined string
    """
    msg = ''
    for i in lst:
        if isinstance(i, tuple) or isinstance(i, list):
            msg += join_recursive(i, sep)
        else:
            msg += (i + sep)
    return msg

def getobj(modulename, objname):
    """Get sorting function associated with the function name.
    @param  modulename  Module name of the given object.
    @param  objname     Name of the desired object.
    @return             Desired object.
    """
    return getattr(import_module(modulename), objname)

def is_iterable(obj, isStrIterable=False):
    """Returns true if an object is iterable.
    @param  obj            Object in question.
    @param  isStrIterable  String is an iterable (default: False).
    """
    if not isinstance(obj, Iterable):
        return False
    else:
        # XNOR is an iff statement A XNOR B = A iff B
        return not xor(isStrIterable, isinstance(obj, str))

def split(array, indexes):
    """Split an array according to the indexes given.
    @param   array    Array to be split
    @param   indexes  Index as integer or list.
    @return           Array split
    """
    if isinstance(indexes, int):
        return list(array[0:indexes], array[indexes:])

    newarray = []
    offset = 0
    for idx in indexes:
        newarray.append(array[offset:idx])
        offset += idx
    if indexes[-1] < len(array):
        newarray.append(array[indexes[-1]:])
    return newarray

def find_uniques_consecutive(array):
    """Find unique elements within the array consecutively.
    @param   array   Array to look into.
    @return          The indices of the unique elements.
    """
    val = array[0]
    indices = []
    for idx, element in enumerate(array):
        if element != val:
            indices.append(idx)
            val = element
    return indices

def get_uniques(array):
    """Get unique elements within an array.
    i.e. All other elements in the array are duplicates of the unique elements.
    @param   array   Array to look into.
    @return          The list of unique elements
    """
    uniques = []
    for element in array:
        if element not in uniques:
            uniques.append(element)
    return uniques

def is_file(argstr):
    """Platform independent method for determining whether a string
    refers to a file.
    @param  argstr  Any string argument
    @return         Returns true if it is a file, false otherwise.
    """
    argf = Path(argstr)
    return argf.exists() and argf.is_file()

def is_dir(argstr):
    """Platform independent method for determining whether a string
    refers to a directory.
    @param  argstr  Any string argument
    @return         Returns true if it is a directory, false otherwise.
    """
    arg = Path(argstr)
    return arg.exists() and arg.is_dir()

def resolve(name):
    """Platform independent method for resolving a directory.
    @param  name    Directory name (absolute/relative)
    @return         String representation of the directory
    """
    arg = Path(name)
    return str(arg.resolve())

def check_dir(dirname):
    """Check if the directory is valid.
    @param  dirname     Directory to be checked
    @throw  FileNotFoundError
    """
    print('Checking directory...{}'.format(dirname))
    if dirname is not None and not is_dir(dirname):
        raise FileNotFoundError('{} is not a valid directory'.format(dirname))

def get_full_filename(dirname, name, ext, tmstamp=False):
    """Returns full file name given all necessary information.
    Checks and resolves directory and formats the get_full_filename.

    @param  dirname  Directory of where the log file should be.
    @param  name     File name
    @param  ext      File extension
    @param  tmstamp  Whether to add timestamp or not.
    @return          Full log file name.
    """
    fill = '_' + str_current_time() if tmstamp else ''
    fmt = '/{}{}{}' if ext.startswith('.') else '/{}{}.{}'
    return resolve(dirname) + fmt.format(name, fill, ext)

def assert_cond(cond, exc):
    """Assert a condition. Raise an error if the condition is not true.
    @param  cond  Condition that the assertion evaluates.
    @throw  exc   Exception that will be thrown when not quiet.
    """
    if not cond:
        raise exc

def assert_type(instance, classtype):
    """Type checking with assertion.
    @param  instance    Any object or instance.
    @param  classtype   Expected or desired type of the object.
    @throw  TypeCheckError
    """
    assert_cond(isinstance(instance, classtype), TypeCheckError(type(instance), classtype))

def swap_inarray(array, idx1, idx2):
    """ Swap two elements in an array.

    @param  array    Input array
    @param  idx1     Index of first element
    @param  idx2     Index of second element
    @retval array    Array after swapping
    """
    if idx1 != idx2:
        temp = array[idx1]
        array[idx1] = array[idx2]
        array[idx2] = temp
    return array

#pylint: disable=anomalous-backslash-in-string
def geo_seq(val, ratio, length):
    """Returns an array of geometric sequence.

    @n @f$ a , \hspace{1 mm} a r , \hspace{1 mm} a r^2 ,
    \hspace{1 mm} \dots \hspace{1 mm}, \hspace{1 mm}
    a_{n-1} \hspace{1 mm} r^{n-1} @f$ @n

    @param val      Start value of the geometric sequence (a)
    @param ratio    Ratio (r)
    @param length   Sequence length (n)

    @return Array of geometric sequence
    """
    return [val * pow(ratio, i) for i in range(length)]
#pylint: enable=anomalous-backslash-in-string

@unique
class Verbosity(IntEnum):
    """Enumeration for verbosity level"""
    ERROR = 0
    WARNING = 1
    NONE = 2
    INFO = 3
    DEBUG = 4

class Traceable(object):
    """Base class with verbosity and debug flag as default attribute."""

    ## Static variables
    verbosity = Verbosity.NONE
    debug = 0
    DEBUG_ENABLE = 0

    def __init__(self):
        super().__init__()

    @classmethod
    def is_debug(cls):
        """Returns whether this object is in debug mode."""
        return Traceable.debug & cls.DEBUG_ENABLE

    @classmethod
    def print_tr(cls, msg, threshold):
        """Print only if the verbosity is above the threshold.
        @param  msg          Message to be printed out.
        @param  threshold    Verbosity threshold level.
        """
        if Traceable.verbosity >= threshold:
            print('{:.6f} sec: [{}] {}'.format(process_time(), cls.__qualname__, msg)) #pylint: disable=no-member

class ListIterator: #pylint: disable=too-few-public-methods
    """Iterator class for a list."""

    def __init__(self, lst):
        """Constructor"""
        self.__idx = 0
        self.__lst = lst
        self.__n = len(lst)

    def __iter__(self):
        return self

    def __next__(self):
        if self.__idx < self.__n:
            self.__idx += 1
            return self.__lst[self.__idx - 1]
        else:
            raise StopIteration()


text:
import React, { FC } from 'react';

import { Button, FilterInput } from '@grafana/ui';

interface Props {
  searchQuery: string;
  disabled: boolean;
  onAddClick: () => void;
  onSearchChange: (value: string) => void;
}

export const ApiKeysActionBar: FC<Props> = ({ searchQuery, disabled, onAddClick, onSearchChange }) => {
  return (

        <FilterInput placeholder="Search keys" value={searchQuery} onChange={onSearchChange} />

      <Button className="pull-right" onClick={onAddClick} disabled={disabled}>
        Add API key
      </Button>

  );
};


text:
package org.terracotta.persistence.sanskrit;

import org.terracotta.persistence.sanskrit.change.SanskritChange;

import java.io.IOException;

import static org.terracotta.persistence.sanskrit.Owner.own;

public class LockReleasingSanskrit implements Sanskrit {
  private final Sanskrit underlying;
  private final DirectoryLock lock;

  public LockReleasingSanskrit(Sanskrit underlying, DirectoryLock lock) {
    this.underlying = underlying;
    this.lock = lock;
  }

  @Override
  @SuppressWarnings("try")
  public void close() throws SanskritException {
    try (
        Owner<DirectoryLock, IOException> lockOwner = own(lock, IOException.class);
        Owner<Sanskrit, SanskritException> sanskritOwner = own(underlying, SanskritException.class)
    ) {
      // Do nothing - the Java try-with-resources will correctly close both objects.
    } catch (IOException e) {
      throw new SanskritException(e);
    }
  }

  @Override
  public String getString(String key) throws SanskritException {
    return underlying.getString(key);
  }

  @Override
  public Long getLong(String key) throws SanskritException {
    return underlying.getLong(key);
  }

  @Override
  public SanskritObject getObject(String key) throws SanskritException {
    return underlying.getObject(key);
  }

  @Override
  public void applyChange(SanskritChange change) throws SanskritException {
    underlying.applyChange(change);
  }

  @Override
  public MutableSanskritObject newMutableSanskritObject() {
    return underlying.newMutableSanskritObject();
  }

  @Override
  public void reset() throws SanskritException {
    underlying.reset();
  }
}