text:
#include "ork/ork.hpp"
#define ORK_STL_INC_FILE <string>
#include "ork/core/stl_include.inl"
#define ORK_STL_INC_FILE <sstream>
#include "ork/core/stl_include.inl"

#include "ork/glm.hpp"
#include "ork/orientation.hpp"
#include "ork/string_utils.hpp"

namespace ork {

orientation operator-(const orientation o)
{
    switch(o) {
        case orientation::pos_x:
            return orientation::neg_x;
        case orientation::neg_x:
            return orientation::pos_x;
        case orientation::pos_y:
            return orientation::neg_y;
        case orientation::neg_y:
            return orientation::pos_y;
        case orientation::pos_z:
            return orientation::neg_z;
        case orientation::neg_z:
            return orientation::pos_z;
    }
    ORK_THROW(ORK("Unreachable"));
}

// These must be in the same order as the enum
static const char_t* const oriention_strings[] =
    {ORK("+X"), ORK("-X"), ORK("+Y"), ORK("-Y"), ORK("+Z"), ORK("-Z")};

o_stream& operator<<(o_stream& strm, const orientation o)
{
    strm << orientation2string(o);
    return strm;
}

i_stream& operator>>(i_stream& strm, orientation& o)
{
    string val;
    strm >> val;
    o = string2orientation(val);
    return strm;
}

const char_t* orientation2string(const orientation o)
{
    const size_t index = static_cast<size_t>(o);
    if(index < sizeof(oriention_strings) / sizeof(*oriention_strings))
        return oriention_strings[index];
    else
        ORK_THROW(ORK("Attempt to convert invalid orientation"));
}

orientation string2orientation(const string& val)
{
    string upper = val;
    to_upper(upper);

    const size_t num_strings = sizeof(oriention_strings) / sizeof(*oriention_strings);
    LOOPI(num_strings)
    {
        if(upper == oriention_strings[i]) {
            return static_cast<orientation>(i);
        }
    }
    ORK_THROW(ORK("Attempt to convert invalid orientation: ") << val);
}

// Crappy little parser to get _boost_ out of this compile unit
using iter_t = string::const_iterator;
void skip_whitespace(iter_t& it, const iter_t& end)
{
    while(it != end && (*it == ' ' || *it == '\t')) { // Whitespace can be space or tab
        ++it;
    }
}
iter_t consume_token(iter_t begin, const iter_t& end)
{
    while(begin != end && *begin != ' ' && *begin != '\t') { // Whitespace can be space or tab
        ++begin;
    }
    return begin;
}
std::vector<string> parse_orientation_strings(const string& str)
{
    std::vector<string> retval;
    iter_t curr_pos{str.begin()};
    const iter_t end{str.end()};
    while(curr_pos != end) {
        skip_whitespace(curr_pos, end);
        const iter_t new_pos = consume_token(curr_pos, end);
        if(new_pos != curr_pos) {
            retval.emplace_back(curr_pos, new_pos);
        }
        curr_pos = new_pos;
    }
    return std::move(retval);
}

std::vector<orientation> parse_orientations(const string& line)
{
    const std::vector<string> strings = parse_orientation_strings(line);
    std::vector<orientation> retval;
    for(const string& orient : strings) {
        retval.push_back(string2orientation(orient));
    }
    return std::move(retval);
}

double to_wcs(const double val, const orientation o)
{
    switch(o) {
        case orientation::pos_x:
        case orientation::pos_y:
        case orientation::pos_z:
            return val;
        case orientation::neg_x:
        case orientation::neg_y:
        case orientation::neg_z:
            return -val;
    }
    ORK_THROW(ORK("Unreachable"));
}

orientation to_positive(const orientation o)
{
    switch(o) {
        case orientation::pos_x:
            return orientation::pos_x;
        case orientation::neg_x:
            return orientation::pos_x;
        case orientation::pos_y:
            return orientation::pos_y;
        case orientation::neg_y:
            return orientation::pos_y;
        case orientation::pos_z:
            return orientation::pos_z;
        case orientation::neg_z:
            return orientation::pos_z;
    }
    ORK_THROW(ORK("Unreachable"));
}

bool is_positive(const orientation o)
{
    switch(o) {
        case orientation::pos_x:
        case orientation::pos_y:
        case orientation::pos_z:
            return true;
        case orientation::neg_x:
        case orientation::neg_y:
        case orientation::neg_z:
            return false;
    }
    ORK_THROW(ORK("Unreachable"));
}

} // namespace ork


text:
"""
==========================================
Outlier detection with several methods.
==========================================

When the amount of contamination is known, this example illustrates three
different ways of performing :ref:`outlier_detection`:

- based on a robust estimator of covariance, which is assuming that the
  data are Gaussian distributed and performs better than the One-Class SVM
  in that case.

- using the One-Class SVM and its ability to capture the shape of the
  data set, hence performing better when the data is strongly
  non-Gaussian, i.e. with two well-separated clusters;

- using the Isolation Forest algorithm, which is based on random forests and
  hence more adapted to large-dimensional settings, even if it performs
  quite well in the examples below.

- using the Local Outlier Factor to measure the local deviation of a given
  data point with respect to its neighbors by comparing their local density.

The ground truth about inliers and outliers is given by the points colors
while the orange-filled area indicates which points are reported as inliers
by each method.

Here, we assume that we know the fraction of outliers in the datasets.
Thus rather than using the 'predict' method of the objects, we set the
threshold on the decision_function to separate out the corresponding
fraction.
"""

import numpy as np
from scipy import stats
import matplotlib.pyplot as plt
import matplotlib.font_manager

from sklearn import svm
from sklearn.covariance import EllipticEnvelope
from sklearn.ensemble import IsolationForest
from sklearn.neighbors import LocalOutlierFactor

print(__doc__)

SEED = 42
GRID_PRECISION = 100

rng = np.random.RandomState(SEED)

# Example settings
n_samples = 200
outliers_fraction = 0.25
clusters_separation = (0, 1, 2)

# define two outlier detection tools to be compared
classifiers = {
    "One-Class SVM": svm.OneClassSVM(nu=0.95 * outliers_fraction + 0.05,
                                     kernel="rbf", gamma=0.1),
    "Robust covariance": EllipticEnvelope(contamination=outliers_fraction),
    "Isolation Forest": IsolationForest(max_samples=n_samples,
                                        contamination=outliers_fraction,
                                        random_state=rng),
    "Local Outlier Factor": LocalOutlierFactor(
        n_neighbors=35,
        contamination=outliers_fraction)}

# Compare given classifiers under given settings
xx, yy = np.meshgrid(np.linspace(-7, 7, GRID_PRECISION),
                     np.linspace(-7, 7, GRID_PRECISION))
n_outliers = int(outliers_fraction * n_samples)
n_inliers = n_samples - n_outliers
ground_truth = np.ones(n_samples, dtype=int)
ground_truth[-n_outliers:] = -1

# Fit the problem with varying cluster separation
for _, offset in enumerate(clusters_separation):
    np.random.seed(SEED)
    # Data generation
    X1 = 0.3 * np.random.randn(n_inliers // 2, 2) - offset
    X2 = 0.3 * np.random.randn(n_inliers // 2, 2) + offset
    X = np.concatenate([X1, X2], axis=0)
    # Add outliers
    X = np.concatenate([X, np.random.uniform(low=-6, high=6,
                       size=(n_outliers, 2))], axis=0)

    # Fit the model
    plt.figure(figsize=(9, 7))
    for i, (clf_name, clf) in enumerate(classifiers.items()):
        # fit the data and tag outliers
        if clf_name == "Local Outlier Factor":
            y_pred = clf.fit_predict(X)
            scores_pred = clf.negative_outlier_factor_
        else:
            clf.fit(X)
            scores_pred = clf.decision_function(X)
            y_pred = clf.predict(X)
        n_errors = (y_pred != ground_truth).sum()
        # plot the levels lines and the points
        if clf_name == "Local Outlier Factor":
            # decision_function is private for LOF
            Z = clf._decision_function(np.c_[xx.ravel(), yy.ravel()])
        else:
            Z = clf.decision_function(np.c_[xx.ravel(), yy.ravel()])
        Z = Z.reshape(xx.shape)
        subplot = plt.subplot(2, 2, i + 1)
        subplot.contourf(xx, yy, Z, levels=np.linspace(Z.min(), 0, 7),
                         cmap=plt.cm.Blues_r)
        a = subplot.contour(xx, yy, Z, levels=[0],
                            linewidths=2, colors='red')
        subplot.contourf(xx, yy, Z, levels=[0, Z.max()],
                         colors='orange')
        b = subplot.scatter(X[:-n_outliers, 0], X[:-n_outliers, 1], c='white',
                            s=20, edgecolor='k')
        c = subplot.scatter(X[-n_outliers:, 0], X[-n_outliers:, 1], c='black',
                            s=20, edgecolor='k')
        subplot.axis('tight')
        subplot.legend(
            [a.collections[0], b, c],
            ['learned decision function', 'true inliers', 'true outliers'],
            prop=matplotlib.font_manager.FontProperties(size=10),
            loc='lower right')
        subplot.set_xlabel("%d. %s (errors: %d)" % (i + 1, clf_name, n_errors))
        subplot.set_xlim((-7, 7))
        subplot.set_ylim((-7, 7))
    plt.subplots_adjust(0.04, 0.1, 0.96, 0.94, 0.1, 0.26)
    plt.suptitle("Outlier detection")

plt.show()

redpajama_set_name: RedPajamaGithub


text:
using System;
using System.Reflection;
using System.Diagnostics;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Reflection.Runtime.General;
using System.Reflection.Runtime.TypeInfos;

using Internal.LowLevelLinq;
using Internal.Reflection.Core;
using Internal.Metadata.NativeFormat;

namespace System.Reflection.Runtime.CustomAttributes
{
    //
    // The Runtime's implementation of a pseudo-CustomAttributeData.
    //
    internal sealed class RuntimePseudoCustomAttributeData : RuntimeCustomAttributeData
    {
        public RuntimePseudoCustomAttributeData(RuntimeTypeInfo attributeType, IList<CustomAttributeTypedArgument> constructorArguments, IList<CustomAttributeNamedArgument> namedArguments)
        {
            _attributeType = attributeType;
            if (constructorArguments == null)
                constructorArguments = Array.Empty<CustomAttributeTypedArgument>();
            _constructorArguments = new ReadOnlyCollection<CustomAttributeTypedArgument>(constructorArguments);
            if (namedArguments == null)
                namedArguments = Array.Empty<CustomAttributeNamedArgument>();
            _namedArguments = new ReadOnlyCollection<CustomAttributeNamedArgument>(namedArguments);
            return;
        }

        public sealed override Type AttributeType
        {
            get
            {
                return _attributeType;
            }
        }

        internal sealed override String AttributeTypeString
        {
            get
            {
                return _attributeType.FormatTypeName();
            }
        }

        internal sealed override IList<CustomAttributeTypedArgument> GetConstructorArguments(bool throwIfMissingMetadata)
        {
            return _constructorArguments;
        }

        internal sealed override IList<CustomAttributeNamedArgument> GetNamedArguments(bool throwIfMissingMetadata)
        {
            return _namedArguments;
        }

        // Equals/GetHashCode no need to override (they just implement reference equality but desktop never unified these things.)

        private readonly RuntimeTypeInfo _attributeType;
        private readonly ReadOnlyCollection<CustomAttributeTypedArgument> _constructorArguments;
        private readonly ReadOnlyCollection<CustomAttributeNamedArgument> _namedArguments;
    }
}


text:
package org.vaadin.alump.picker.gwt.client;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.google.gwt.dom.client.Document;
import com.google.gwt.dom.client.Element;
import com.google.gwt.dom.client.NativeEvent;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.MouseDownEvent;
import com.google.gwt.event.dom.client.MouseDownHandler;
import com.google.gwt.event.dom.client.MouseMoveEvent;
import com.google.gwt.event.dom.client.MouseMoveHandler;
import com.google.gwt.event.dom.client.MouseUpEvent;
import com.google.gwt.event.dom.client.MouseUpHandler;
import com.google.gwt.event.dom.client.TouchEndEvent;
import com.google.gwt.event.dom.client.TouchEndHandler;
import com.google.gwt.event.dom.client.TouchMoveEvent;
import com.google.gwt.event.dom.client.TouchMoveHandler;
import com.google.gwt.event.dom.client.TouchStartEvent;
import com.google.gwt.event.dom.client.TouchStartHandler;
import com.google.gwt.event.logical.shared.HasValueChangeHandlers;
import com.google.gwt.event.logical.shared.ValueChangeEvent;
import com.google.gwt.event.logical.shared.ValueChangeHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.DOM;
import com.google.gwt.user.client.Event;
import com.google.gwt.user.client.EventListener;
import com.google.gwt.user.client.ui.Widget;
import com.vaadin.client.BrowserInfo;
import com.vaadin.client.Util;
import com.vaadin.client.VConsole;

public class GwtPicker extends Widget implements
        HasValueChangeHandlers<Integer> {

    public final static String CLASSNAME = "alump-picker";
    public final static String CLASSNAME_BUTTONS = CLASSNAME + "-buttons";
    public final static String CLASSNAME_BUTTON = CLASSNAME + "-button";
    public final static String CLASSNAME_UP = CLASSNAME + "-up";
    public final static String CLASSNAME_DOWN = CLASSNAME + "-down";
    public final static String CLASSNAME_LINE = CLASSNAME + "-line";
    public final static String CLASSNAME_CURRENT = CLASSNAME + "-current";
    public final static String CLASSNAME_OUTER = CLASSNAME + "-outer";
    public final static String CLASSNAME_INNER = CLASSNAME + "-inner";
    public final static String CLASSNAME_OVERLAY = CLASSNAME + "-overlay";

    public final static String CLASSNAME_STEPPING = CLASSNAME + "-stepping";
    public final static String CLASSNAME_DRAGGING = CLASSNAME + "-dragging";

    protected final static int DRAG_TRESSHOLD_Y = 10;
    protected final static long IGNORE_CLICK_AFTER_DRAG_MS = 200;

    protected Element upButtonElement;
    protected Element downButtonElement;
    protected Element outerScrollElement;
    protected Element innerScrollElement;
    protected Element overlayElement;

    protected List<Element> valueElements = new ArrayList<Element>();
    protected Integer currentValue = null;
    protected PickerEventHandler eventHandler = new PickerEventHandler();

    protected TransitionMode currentTransitionMode = TransitionMode.NONE;

    protected int scrollTopValue = 0;

    public GwtPicker() {
        setElement(Document.get().createDivElement());

        upButtonElement = Document.get().createDivElement();
        upButtonElement.addClassName(CLASSNAME_BUTTON);
        upButtonElement.addClassName(CLASSNAME_UP);
        upButtonElement.setInnerHTML("⇧");
        getElement().appendChild(upButtonElement);

        downButtonElement = Document.get().createDivElement();
        downButtonElement.addClassName(CLASSNAME_BUTTON);
        downButtonElement.addClassName(CLASSNAME_DOWN);
        downButtonElement.setInnerHTML("⇩");
        getElement().appendChild(downButtonElement);

        outerScrollElement = Document.get().createDivElement();
        outerScrollElement.addClassName(CLASSNAME_OUTER);
        getElement().appendChild(outerScrollElement);

        innerScrollElement = Document.get().createDivElement();
        innerScrollElement.addClassName(CLASSNAME_INNER);
        outerScrollElement.appendChild(innerScrollElement);

        overlayElement = Document.get().createDivElement();
        overlayElement.addClassName(CLASSNAME_OVERLAY);
        overlayElement.setAttribute("unselectable", "on");
        getElement().appendChild(overlayElement);
        eventHandler.setCaptureElement(overlayElement);

        setStylePrimaryName(CLASSNAME);
    }

    @Override
    public void onAttach() {
        super.onAttach();

        if (BrowserInfo.get().isTouchDevice()) {
            // VConsole.log("Connect picker events in touch mode");
            addHandler(eventHandler, ClickEvent.getType());

            DOM.sinkEvents((com.google.gwt.user.client.Element) overlayElement,
                    Event.TOUCHEVENTS);
            DOM.setEventListener(
                    (com.google.gwt.user.client.Element) overlayElement,
                    eventHandler);
        } else {
            // VConsole.log("Connect picker events in mouse mode");
            addHandler(eventHandler, ClickEvent.getType());

            DOM.sinkEvents((com.google.gwt.user.client.Element) overlayElement,
                    Event.MOUSEEVENTS);
            DOM.setEventListener(
                    (com.google.gwt.user.client.Element) overlayElement,
                    eventHandler);
        }

    }

    /**
     * Event handler class
     */
    protected class PickerEventHandler implements ClickHandler,
            MouseDownHandler, MouseMoveHandler, MouseUpHandler,
            TouchStartHandler, TouchMoveHandler, TouchEndHandler, EventListener {

        private boolean dragged = false;
        private int dragStartY = -1;
        private int dragStartIndex = -1;
        private Element captureElement = null;
        private long dragEnded = 0;

        public void setCaptureElement(Element element) {
            captureElement = element;
        }

        @Override
        public void onClick(ClickEvent event) {

            Element element = Element.as(event.getNativeEvent()
                    .getEventTarget());

            if (upButtonElement.isOrHasChild(element)) {
                event.preventDefault();
                event.stopPropagation();
                setPrevValue();
            } else if (downButtonElement.isOrHasChild(element)) {
                event.preventDefault();
                event.stopPropagation();
                setNextValue();
            } else if (overlayElement != null
                    && overlayElement.isOrHasChild(element)) {
                if (new Date().getTime() - dragEnded < IGNORE_CLICK_AFTER_DRAG_MS) {
                    return;
                }
                // VConsole.log("onClick");
                GwtPicker.this.setValueAtPosition(
                        Util.getTouchOrMouseClientX(event.getNativeEvent()),
                        Util.getTouchOrMouseClientY(event.getNativeEvent()),
                        true, null);
            }

            Event.releaseCapture(captureElement);
        }

        @Override
        public void onTouchStart(TouchStartEvent event) {
            onDragStart(event.getNativeEvent());
        }

        protected void onDragStart(NativeEvent event) {
            if (dragStartY >= 0) {
                // VConsole.log("Ignore onDragStart");
                return;
            }

            Element element = Element.as(event.getEventTarget());
            if (!overlayElement.isOrHasChild(element)) {
                // VConsole.log("onDragStart not at overlay");
                return;
            }

            // VConsole.log("onDragStart");

            dragStartY = Util.getTouchOrMouseClientY(event);
            dragStartIndex = GwtPicker.this.currentValue;
            setTransitionMode(TransitionMode.DRAGGING);
            event.stopPropagation();

        }

        @Override
        public void onTouchMove(TouchMoveEvent event) {
            onDragMove(event.getNativeEvent());
        }

        protected void onDragMove(NativeEvent event) {
            if (dragStartY < 0) {
                return;
            }

            int dragDist = Math.round(dragStartY
                    - Util.getTouchOrMouseClientY(event));

            if (!dragged) {
                if (Math.abs(dragDist) < DRAG_TRESSHOLD_Y) {
                    dragged = true;
                    Event.setCapture(captureElement);
                    event.preventDefault();
                    event.stopPropagation();
                }
            } else {
                int top = GwtPicker.this.scrollTopValue - dragDist;
                setScrollTop(top, false);
                GwtPicker.this.setValueAtMiddle(false, false);
                event.preventDefault();
                event.stopPropagation();
            }

        }

        @Override
        public void onTouchEnd(TouchEndEvent event) {
            onDragEnd(event.getNativeEvent());
        }

        public void onDragEnd(NativeEvent event) {
            dragStartY = -1;

            if (!dragged) {
                return;
            }

            dragEnded = new Date().getTime();
            // VConsole.log("onDragEnd");

            Event.releaseCapture(captureElement);
            dragged = false;
            event.preventDefault();
            event.stopPropagation();

            GwtPicker.this.setValue(currentValue, true,
                    dragStartIndex != currentValue);
        }

        @Override
        public void onBrowserEvent(Event event) {
            switch (event.getTypeInt()) {
            case Event.ONMOUSEDOWN:
                if (event.getButton() != NativeEvent.BUTTON_LEFT) {
                    // VConsole.log("Ignoring button: " + event.getButton());
                    return;
                }
                event.preventDefault();
            case Event.ONTOUCHSTART:
                onDragStart(event);
                break;
            case Event.ONTOUCHMOVE:
            case Event.ONMOUSEMOVE:
                onDragMove(event);
                break;
            case Event.ONMOUSEUP:
                if (event.getButton() != NativeEvent.BUTTON_LEFT) {
                    // VConsole.log("Ignoring button: " + event.getButton());
                    return;
                }
            case Event.ONTOUCHEND:
                onDragEnd(event);
                break;
            }
        }

        @Override
        public void onMouseDown(MouseDownEvent event) {
            onDragMove(event.getNativeEvent());
        }

        @Override
        public void onMouseMove(MouseMoveEvent event) {
            onDragMove(event.getNativeEvent());
        }

        @Override
        public void onMouseUp(MouseUpEvent event) {
            onDragEnd(event.getNativeEvent());
        }

    }

    /**
     * Select value at middle
     */
    protected void setValueAtMiddle(boolean move, Boolean fire) {

        int y = (int) Math.round(overlayElement.getAbsoluteTop()
                + overlayElement.getClientHeight() / 2.0);
        Integer index = findValue(y);
        if (index != null) {
            setValue(index, move, fire);
        }
    }

    protected void setValueAtPosition(int clientX, int clientY, boolean move,
            Boolean fire) {

        Integer index = findValue(clientY);
        if (index != null) {
            setValue(index, move, fire);
        }
    }

    /**
     * Find index of value at given client Y value
     *
     * @param clientY
     * @return Index of value or null if out of bounds
     */
    protected Integer findValue(int clientY) {
        for (Element value : valueElements) {
            int valY = value.getAbsoluteTop();
            if (clientY > valY) {
                int valB = valY + value.getClientHeight();
                if (clientY < valB) {
                    return valueElements.indexOf(value);
                }
            }
        }

        return null;
    }

    /**
     * Show or hide browse buttons
     *
     * @param visible
     *            true to show, false to hide
     */
    public void setButtonsVisible(boolean visible) {
        if (visible) {
            addStyleName(CLASSNAME_BUTTONS);
        } else {
            removeStyleName(CLASSNAME_BUTTONS);
        }
    }

    /**
     * How many values there are in Picker
     *
     * @param amount
     *            Amount of values
     */
    public void setValueAmount(int amount) {
        if (amount < 0) {
            amount = 0;
        }

        while (valueElements.size() > amount) {
            Element element = valueElements.get(valueElements.size() - 1);
            valueElements.remove(element);
            element.removeFromParent();
        }

        while (valueElements.size() < amount) {
            Element element = createValueElement();
            valueElements.add(element);
            innerScrollElement.appendChild(element);
        }
    }

    protected Element createValueElement() {
        Element element = Document.get().createDivElement();
        element.addClassName(CLASSNAME_LINE);
        return element;
    }

    /**
     * Define presentation for given value
     *
     * @param index
     *            Index of value
     * @param presentation
     *            Presentation of value
     * @param isHTML
     *            Is content safe HTML (true), or plain text (false)
     */
    public void setValuePresentation(int index, String presentation,
            boolean isHTML) {

        try {
            Element element = valueElements.get(index);
            if (presentation == null || presentation.isEmpty()) {
                element.setInnerHTML(" ");
            } else {
                if (isHTML) {
                    element.setInnerHTML(presentation);
                } else {
                    element.setInnerText(presentation);
                }
            }
        } catch (IndexOutOfBoundsException e) {
            VConsole.error("Failed to get value presentation");
        }
    }

    /**
     * Set previous value active
     */
    public void setPrevValue() {
        setPrevValue(1);
    }

    /**
     * Set previous value active
     *
     * @param steps
     *            How many steps to previous
     */
    public void setPrevValue(int steps) {
        if (currentValue != null) {
            int newIndex = currentValue - steps;
            if (newIndex < 0) {
                newIndex = 0;
            }
            setValue(newIndex, true, true);
        }
    }

    /**
     * Set next value active
     */
    public void setNextValue() {
        setNextValue(1);
    }

    /**
     * Set next value active
     *
     * @param steps
     *            How many steps to next
     */
    public void setNextValue(int steps) {
        if (currentValue != null) {
            int newIndex = currentValue + steps;
            if (newIndex >= valueElements.size()) {
                newIndex = valueElements.size() - 1;
            }
            setValue(newIndex, true, true);
        }
    }

    /**
     * Set value with given index active
     *
     * @param index
     *            Index of value
     */
    public void setValue(int index) {
        setValue(index, true, false);
    }

    /**
     * Change value of picker
     *
     * @param index
     *            New index to be selected
     * @param move
     *            If picker should scroll to given position
     * @param fire
     *            If value change should be fired. If null it will be fired if
     *            value has changed.
     */
    protected void setValue(int index, boolean move, Boolean fire) {
        try {

            boolean doFire = (currentValue == null || currentValue != index);
            if (fire != null) {
                doFire = fire;
            }
            currentValue = index;

            if (move) {
                Element element = valueElements.get(currentValue);
                double elementTop = element.getOffsetTop();
                double elementHeight = element.getClientHeight();
                double scrollerHeight = outerScrollElement.getClientHeight();
                int scrollTop = (int) Math.round(scrollerHeight / 2
                        - elementHeight / 2 - elementTop);
                setTransitionMode(TransitionMode.STEPPING);
                setScrollTop(scrollTop, true);
            }

            updateCurrentValueStyles();

            if (doFire) {
                ValueChangeEvent.fire(this, currentValue);
            }

        } catch (IndexOutOfBoundsException e) {
            VConsole.error("Failed to set value");
        }
    }

    /**
     * Set scroll top value to style
     *
     * @param topValue
     *            New top value
     * @param updateValue
     *            If value should be stored to scrollTopValue
     */
    protected void setScrollTop(int topValue, boolean updateValue) {
        innerScrollElement.getStyle().setTop(topValue, Unit.PX);
        if (updateValue) {
            scrollTopValue = topValue;
        }
    }

    /**
     * Makes sure only current value has current value style name
     */
    protected void updateCurrentValueStyles() {
        if (currentValue == null) {
            for (Element element : valueElements) {
                element.removeClassName(CLASSNAME_CURRENT);
            }
        } else {
            for (int i = 0; i < valueElements.size(); ++i) {
                if (i == currentValue) {
                    valueElements.get(i).addClassName(CLASSNAME_CURRENT);
                } else {
                    valueElements.get(i).removeClassName(CLASSNAME_CURRENT);
                }
            }
        }
    }

    @Override
    public HandlerRegistration addValueChangeHandler(
            ValueChangeHandler<Integer> handler) {
        HandlerRegistration registration = this.addHandler(handler,
                ValueChangeEvent.getType());
        return registration;
    }

    protected enum TransitionMode {
        NONE(null), STEPPING(CLASSNAME_STEPPING), DRAGGING(CLASSNAME_DRAGGING);

        private final String className;

        private TransitionMode(String className) {
            this.className = className;
        }

        public String getClassName() {
            return className;
        }

        public boolean hasClassName() {
            return className != null;
        }
    }

    protected void setTransitionMode(TransitionMode mode) {
        if (currentTransitionMode != mode) {
            if (currentTransitionMode.hasClassName()) {
                innerScrollElement.removeClassName(currentTransitionMode
                        .getClassName());
            }
            currentTransitionMode = mode;
            if (currentTransitionMode.hasClassName()) {
                innerScrollElement.addClassName(currentTransitionMode
                        .getClassName());
            }
        }
    }
}


text:
package com.voxelwind.server.game.level.manager;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import com.spotify.futures.CompletableFutures;
import com.voxelwind.api.game.entities.Entity;
import com.voxelwind.api.game.level.Chunk;
import com.voxelwind.server.VoxelwindServer;
import com.voxelwind.server.game.level.VoxelwindLevel;
import com.voxelwind.server.game.level.chunk.SectionedChunk;
import com.voxelwind.server.game.level.chunk.generator.ChunkGenerator;
import com.voxelwind.server.game.level.chunk.provider.ChunkProvider;
import com.voxelwind.server.network.session.PlayerSession;
import gnu.trove.TCollections;
import gnu.trove.map.TLongLongMap;
import gnu.trove.map.TLongObjectMap;
import gnu.trove.map.hash.TLongLongHashMap;
import gnu.trove.map.hash.TLongObjectHashMap;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import javax.annotation.Nonnull;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.concurrent.*;
import java.util.concurrent.atomic.AtomicReference;

/**
 * Handles chunk management, including loading and unloading chunks.
 *
 * This class keeps all loaded chunks in memory and cleans chunks that are no longer required to be loaded. Chunks are
 * loaded asynchronously and only one attempt to load the same chunk is made, even with concurrent callers.
 */
public class LevelChunkManager {
    private static final Logger LOGGER = LogManager.getLogger(LevelChunkManager.class);

    private final TLongObjectMap<Chunk> chunksLoaded = TCollections.synchronizedMap(new TLongObjectHashMap<Chunk>());
    private final TLongObjectMap<LoadingTask> chunksToLoad = TCollections.synchronizedMap(new TLongObjectHashMap<LoadingTask>());
    private final TLongLongMap loadedTimes = TCollections.synchronizedMap(new TLongLongHashMap());
    private final TLongLongMap lastAccessTimes = TCollections.synchronizedMap(new TLongLongHashMap());
    private final ExecutorService loadService;

    private final VoxelwindLevel level;
    private final ChunkProvider backingChunkProvider;
    private final ChunkGenerator backingChunkGenerator;
    private final VoxelwindServer server;

    public LevelChunkManager(@Nonnull VoxelwindServer server, @Nonnull VoxelwindLevel level, @Nonnull ChunkProvider backingChunkProvider, @Nonnull ChunkGenerator backingChunkGenerator) {
        this.server = server;
        this.level = level;
        this.backingChunkProvider = backingChunkProvider;
        this.backingChunkGenerator = backingChunkGenerator;
        this.loadService = Executors.newFixedThreadPool(Math.max(1, server.getConfiguration().getFineTuning().getChunkLoadThreads()),
                new ThreadFactoryBuilder()
                        .setNameFormat("Voxelwind Chunk Load Handler for " + level.getName() + " - #%d")
                        .setDaemon(true)
                        .build());
    }

    public CompletableFuture<Chunk> getChunk(int x, int z) {
        Optional<Chunk> alreadyLoaded = getChunkIfLoaded(x, z);
        if (alreadyLoaded.isPresent()) {
            return CompletableFuture.completedFuture(alreadyLoaded.get());
        }

        // Not already loaded, so we need to ask the chunk provider.
        long chunkKey = toLong(x, z);
        LoadingTask loadingTask = chunksToLoad.get(chunkKey);
        if (loadingTask == null) {
            loadingTask = new LoadingTask(x, z);
            chunksToLoad.put(chunkKey, loadingTask);
        }

        CompletableFuture<Chunk> resultFuture = loadingTask.createCompletableFuture();
        if (!loadingTask.isInitiated()) {
            loadingTask.execute();
        }

        return resultFuture;
    }

    public Optional<Chunk> getChunkIfLoaded(int x, int z) {
        long chunkKey = toLong(x, z);
        Chunk chunk = chunksLoaded.get(chunkKey);
        if (chunk != null) {
            lastAccessTimes.put(chunkKey, System.currentTimeMillis());
        }

        return Optional.ofNullable(chunk);
    }

    public void onTick() {
        long current = System.currentTimeMillis();

        int spawnChunkX = level.getSpawnLocation().getFloorX() >> 4;
        int spawnChunkZ = level.getSpawnLocation().getFloorZ() >> 4;

        if (server.getConfiguration().getChunkGC().isEnabled()) {
            // Create a copy of all chunk indexes
            chunkGc: for (long chunkKey : chunksLoaded.keys()) {
                // Check for spawnchunk
                int x = (int) (chunkKey >> 32);
                int z = (int) chunkKey + Integer.MIN_VALUE;

                if (Math.abs(x - spawnChunkX) <= server.getConfiguration().getChunkGC().getSpawnRadiusToKeep() ||
                        Math.abs(z - spawnChunkZ) <= server.getConfiguration().getChunkGC().getSpawnRadiusToKeep()) {
                    // Chunk is part of the spawn, skip it
                    continue;
                }

                // Get the loaded times
                long loadedTime = loadedTimes.get(chunkKey);
                if (current - loadedTime <= TimeUnit.SECONDS.toMillis(server.getConfiguration().getChunkGC().getReleaseAfterLoadSeconds())) {
                    // This chunk has been loaded recently, skip it
                    continue;
                }

                // Check for last access
                long lastAccessTime = lastAccessTimes.get(chunkKey);
                if (current - lastAccessTime <= TimeUnit.SECONDS.toMillis(server.getConfiguration().getChunkGC().getReleaseAfterLastAccess())) {
                    // There was a access recently, skip it
                    continue;
                }

                // Check if a player has loaded the chunk
                for (PlayerSession session : level.getEntityManager().getPlayers()) {
                    if (session.isChunkInView(x, z)) {
                        // Chunk has been loaded by a player, skip it
                        continue chunkGc;
                    }
                }

                // Unload the chunk
                chunksLoaded.remove(chunkKey);
                lastAccessTimes.remove(chunkKey);
                loadedTimes.remove(chunkKey);
                level.getEntityManager().getEntitiesInChunk(x, z).forEach(Entity::remove);

                LOGGER.debug("Chunk GC cleared chunk @ " + level.getName() + " x" + x + " z" + z);
            }
        }
    }

    private class LoadingTask {
        private final int x;
        private final int z;
        private final List<CompletableFuture<Chunk>> futuresToComplete = new CopyOnWriteArrayList<>();
        private final AtomicReference<LoadState> state = new AtomicReference<>();
        private final AtomicReference<Chunk> loaded = new AtomicReference<>();
        private final AtomicReference<Throwable> loadException = new AtomicReference<>();

        private LoadingTask(int x, int z) {
            this.x = x;
            this.z = z;
        }

        boolean isInitiated() {
            return state.get() != null;
        }

        void execute() {
            // Don't run more than once!
            if (!state.compareAndSet(null, LoadState.INITIATED)) return;

            // Load the chunk.
            backingChunkProvider.createChunk(level, x, z, loadService).thenAcceptAsync(chunk -> {
                long chunkKey = toLong(x, z);

                if (chunk == null) {
                    long seed = chunkSeed(x, z);
                    if (LOGGER.isDebugEnabled()) {
                        LOGGER.debug("Generating chunk ({},{}) using {} and seed {}", x, z, backingChunkGenerator.getClass().getName(), seed);
                    }
                    SectionedChunk generated = new SectionedChunk(x, z, level);
                    backingChunkGenerator.generate(level, generated, new Random(seed));
                    generated.recalculateLight();
                    chunk = generated;
                }

                chunksLoaded.put(chunkKey, chunk);
                long current = System.currentTimeMillis();
                loadedTimes.put(chunkKey, current);
                lastAccessTimes.put(chunkKey, current);
                loaded.set(chunk);
                state.set(LoadState.COMPLETED);

                for (CompletableFuture<Chunk> future : futuresToComplete) {
                    future.complete(chunk);
                }
            }, loadService).exceptionally(throwable -> {
                long chunkKey = toLong(x, z);
                loadException.set(throwable);
                state.set(LoadState.EXCEPTIONAL);
                chunksToLoad.remove(chunkKey);
                for (CompletableFuture<Chunk> future : futuresToComplete) {
                    future.completeExceptionally(throwable);
                }
                return null;
            });
        }

        CompletableFuture<Chunk> createCompletableFuture() {
            LoadState currentState = state.get();
            if (currentState == LoadState.COMPLETED) {
                return CompletableFuture.completedFuture(loaded.get());
            } else if (currentState == LoadState.EXCEPTIONAL) {
                return CompletableFutures.exceptionallyCompletedFuture(loadException.get());
            }

            CompletableFuture<Chunk> completableFuture = new CompletableFuture<>();
            futuresToComplete.add(completableFuture);
            return completableFuture;
        }
    }

    private enum LoadState {
        INITIATED,
        COMPLETED,
        EXCEPTIONAL
    }

    /**
     * Shift two int's together to form a compound key
     *
     * @param x value of key
     * @param z value of key
     * @return long compound of the two int's
     */
    private static long toLong(int x, int z) {
        return ((long) x << 32) + z - Integer.MIN_VALUE;
    }

    /**
     * Creates a chunk and level-specific random seed.
     * @param x chunk X value
     * @param z chunk Z value
     * @return random seed
     */
    private long chunkSeed(int x, int z) {
        // simple XOR of toLong() and the level seed
        return toLong(x, z) ^ level.getSeed();
    }
}


text:
from pyvisdk.thirdparty import Enum

HostActiveDirectoryInfoDomainMembershipStatus = Enum(
    'clientTrustBroken',
    'inconsistentTrust',
    'noServers',
    'ok',
    'otherProblem',
    'serverTrustBroken',
    'unknown',

)


text:
            <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>

<?php echo Yii::t('UserModule.user', 'User has been invited.'); ?>

            <button type="button" class="btn btn-primary"
                    data-dismiss="modal"><?php echo Yii::t('base', 'Ok'); ?></button>


text:
cfar::cfar(float pfa, int numCells, int numGuardBins, int buffLen, int freqSlip, int sampleRate):m_numCells(numCells),
                                                                m_numGuardBins(numGuardBins),m_buffLen(buffLen),
                                                                m_freqSlip(freqSlip),
                                                                m_sampleRate(sampleRate)
{
    m_freqReso = (m_sampleRate/m_buffLen);
    m_freqSlipHz = m_freqSlip * m_freqReso;

    //calculate alpha
    m_alpha = numCells*(std::pow(pfa,-1.0/numCells) - 1.0);
    console::info(__FILENAME__,__LINE__,"CFAR alpha: %f",m_alpha);

    time = new timer();
    std::pair<uint,uint> timeVal = time->getTime();
    console::info(__FILENAME__,__LINE__,"CFAR Starting at time: %llu",timeVal.first);

    dbgFile.open("cfar_noise_estimate.bin",std::ios::binary);

}

cfar::~cfar(){
    dbgFile.close();
    delete time;
};

void cfar::InitTrainingCells(float* input){
    m_forwardNoiseEstimate = 0; m_forwardStart = m_numGuardBins; m_forwardEnd = m_numCells + m_numGuardBins - 1;
    m_reverseNoiseEstimate = 0; m_reverseStart = m_buffLen - m_numCells - m_numGuardBins; m_reverseEnd = m_buffLen - m_numGuardBins - 1;

    size_t idx1,idx2;
    for(idx1 = m_forwardStart,idx2 = m_reverseStart; idx1 <= m_forwardEnd; ++idx1,++idx2){
        m_forwardNoiseEstimate += input[idx1];
        m_reverseNoiseEstimate += input[idx2];
    }
}

std::vector<radar::target> cfar::getDetections(radar::floatIQ* fftIn){
    //CFAR processing
    int bin             = 0;
    int binCheck        = m_buffLen>>1;
    int detBin          = 0;
    float mean          = 0;
    float noiseEsti     = 0;
    radar::cfarDet tmpDet;

    std::vector<radar::cfarDet> dets;
    std::vector<radar::target>  targets;
    dets.reserve(m_buffLen);

    InitTrainingCells(fftIn->iq);

    //loop through buffer
    for(bin = 0;bin<m_buffLen;++bin){
        mean = std::abs(m_forwardNoiseEstimate + m_reverseNoiseEstimate);
        //compare to signal level
        noiseEsti = mean*m_alpha/(2*m_numCells);

        dbgFile.write((char*)&noiseEsti,sizeof(float));

        if(fftIn->iq[bin] > noiseEsti){
            std::pair<uint,uint> timeVal = time->getTime();
            //FFT shift
            bin > binCheck ? detBin = bin - m_buffLen : detBin = bin;

            uint64_t freqOffset = fftIn->metaData.freqHz + (bin)*m_freqReso;

            tmpDet.power           = fftIn->iq[bin];
            tmpDet.freqHz          = freqOffset;
            tmpDet.timeOn          = timeVal.first;
            tmpDet.timeOnMicroSec  = timeVal.second;

            //store detection
            dets.push_back(tmpDet);
        }

        //recalculate noise estimate
        m_forwardNoiseEstimate -= fftIn->iq[m_forwardStart];
        m_reverseNoiseEstimate -= fftIn->iq[m_reverseStart];

        m_forwardStart = (m_forwardStart + 1) % m_buffLen;
        m_reverseStart = (m_reverseStart + 1) % m_buffLen;

        m_forwardNoiseEstimate += fftIn->iq[++m_forwardEnd % m_buffLen];
        m_reverseNoiseEstimate += fftIn->iq[++m_reverseEnd % m_buffLen];

    }

    //run compaction
    targets = compaction(dets);

    return targets;
};

std::vector<radar::target> cfar::compaction(std::vector<radar::cfarDet> dets){
    //assuming no frequency slip, the maximum number of dets we can have is the same size dets
    std::vector<radar::target> targets; targets.reserve(dets.size());

    for(auto& det : dets){
        //check if the frequecny ranges overlap
        if(targets.size() == 0){
            targets.push_back(newTarget(det));
        }

        radar::target& currTarget = targets.back();

        //check if the detection overlaps with the current target
        uint64_t low  = currTarget.freqHz.first - (currTarget.freqHz.second>>1);
        uint64_t high = currTarget.freqHz.first + (currTarget.freqHz.second>>1);

        if((high + m_freqSlipHz) > det.freqHz && (low - m_freqSlipHz) < det.freqHz){
            currTarget = addDetToTarget(currTarget, det);
        }else{
            targets.push_back(newTarget(det));
        }
    }

    return targets;
}

radar::target cfar::newTarget(radar::cfarDet det){
    radar::target tmp;
    tmp.freqHz.first   = det.freqHz;
    tmp.freqHz.second  = 0;
    tmp.power          = det.power;
    tmp.timeOn         = det.timeOn;
    tmp.timeOnMicroSec = det.timeOnMicroSec;
    return tmp;
}

radar::target cfar::addDetToTarget(radar::target target, radar::cfarDet det){
    uint64_t low  = std::min(target.freqHz.first - (target.freqHz.second>>1),det.freqHz);
    uint64_t high = std::max(target.freqHz.first + (target.freqHz.second>>1),det.freqHz);

    target.freqHz.first   = (high+low)>>1;
    target.freqHz.second  = (high-low);
    target.power          += det.power;
    target.timeOn         = std::max(det.timeOn,target.timeOn);
    target.timeOnMicroSec = std::min(det.timeOnMicroSec,target.timeOnMicroSec);

    return target;
}


text:
using System.Threading.Tasks;
using Firestorm.AspNetCore2.HttpContext;
using Firestorm.Host;
using JetBrains.Annotations;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;

namespace Firestorm.AspNetCore2
{
    [UsedImplicitly]
    public class FirestormMiddleware
    {
        private readonly IRequestInvoker _invoker;
        private readonly RequestDelegate _next;

        public FirestormMiddleware(RequestDelegate next, IRequestInvoker invoker)
        {
            _next = next;
            _invoker = invoker;

            // middlewares are singletons constructed during WebHostBuilder.Build(), we can initialize here
            invoker.Initialize();
        }

        [UsedImplicitly]
        public async Task Invoke(Microsoft.AspNetCore.Http.HttpContext httpContext)
        {
            var reader = new HttpContextReader(httpContext);
            var responder = new HttpContextResponder(httpContext);
            var context = new HttpContextRequestContext(httpContext);

            await _invoker.InvokeAsync(reader, responder, context);

            //await _next.Invoke(httpContext);
        }
    }
}


text:
#include <aws/iam/model/PutRolePolicyRequest.h>
#include <aws/core/utils/StringUtils.h>
#include <aws/core/utils/memory/stl/AWSStringStream.h>

using namespace Aws::IAM::Model;
using namespace Aws::Utils;

PutRolePolicyRequest::PutRolePolicyRequest() :
    m_roleNameHasBeenSet(false),
    m_policyNameHasBeenSet(false),
    m_policyDocumentHasBeenSet(false)
{
}

Aws::String PutRolePolicyRequest::SerializePayload() const
{
  Aws::StringStream ss;
  ss << "Action=PutRolePolicy&";
  if(m_roleNameHasBeenSet)
  {
    ss << "RoleName=" << StringUtils::URLEncode(m_roleName.c_str()) << "&";
  }

  if(m_policyNameHasBeenSet)
  {
    ss << "PolicyName=" << StringUtils::URLEncode(m_policyName.c_str()) << "&";
  }

  if(m_policyDocumentHasBeenSet)
  {
    ss << "PolicyDocument=" << StringUtils::URLEncode(m_policyDocument.c_str()) << "&";
  }

  ss << "Version=2010-05-08";
  return ss.str();
}

void  PutRolePolicyRequest::DumpBodyToUrl(Aws::Http::URI& uri ) const
{
  uri.SetQueryString(SerializePayload());
}


text:
import * as types from '../constants/actionTypes';
let getDefaultState=function () {
  return {
    isLoading:false,
    isLoaded:false,
    meetingTypes:{},
    selectBox:{
      isPopulated:false,
      isFresh:false,
      selectedId:"",
      meetingTypes:{},
      alreadySelected:{},
    }
  };
};

export default function meetingTypeReducer(state=getDefaultState(), action) {
  let newState,
    meetingTypes,
    alreadySelected,
    selectBox;
  switch(action.type){
    case types.GET_MEETING_TYPES:
      newState={...state,isLoading:true};
      break;
    case types.GET_MEETING_TYPES_RETURNED:
      newState={...state,isLoading:false,isLoaded:true,meetingTypes:action.meetingTypes};
      break;
    case types.POPULATE_SELECT_BOX:
      selectBox={...state.selectBox,isPopulated:true,isFresh:true,meetingTypes:state.meetingTypes,alreadySelected:{}};
      newState={...state,selectBox};
      break;
    case types.CHANGE_SELECTED:
      meetingTypes={...state.selectBox.meetingTypes};
      alreadySelected={...state.selectBox.alreadySelected};
      newState={...state,meetingTypes,alreadySelected};
      break;
    default:
      newState=state;
  }
  return newState;
}


text:
#include "battery.h"
#include "battery_smart.h"
#include "charger.h"
#include "timer.h"

#ifndef __CROS_EC_CHARGE_STATE_V2_H
#define __CROS_EC_CHARGE_STATE_V2_H

#if defined(CONFIG_I2C_VIRTUAL_BATTERY) && defined(CONFIG_BATTERY_SMART)
#define VIRTUAL_BATTERY_ADDR BATTERY_ADDR
#endif
/*
 * The values exported by charge_get_state() and charge_get_flags() are used
 * only to control the LEDs (with one not-quite-correct exception). For V2
 * we use a different set of states internally.
 */
enum charge_state_v2 {
	ST_IDLE = 0,
	ST_DISCHARGE,
	ST_CHARGE,
	ST_PRECHARGE,

	NUM_STATES_V2
};

struct charge_state_data {
	timestamp_t ts;
	int ac;
	int batt_is_charging;
	struct charger_params chg;
	struct batt_params batt;
	enum charge_state_v2 state;
	int requested_voltage;
	int requested_current;
	int desired_input_current;
};

/*
 * Optional customization.
 *
 * On input, the struct reflects the default behavior. The function can make
 * changes to the state, requested_voltage, or requested_current.
 *
 * Return value:
 *   >0    Desired time in usec for this poll period.
 *   0     Use the default poll period (which varies with the state).
 *  <0     An error occurred. The poll time will be shorter than usual. Too
 *           many errors in a row may trigger some corrective action.
 */
int charger_profile_override(struct charge_state_data *);

/*
 * Access to custom profile params through host commands.
 * What this does is up to the implementation.
 */
enum ec_status charger_profile_override_get_param(uint32_t param,
						  uint32_t *value);
enum ec_status charger_profile_override_set_param(uint32_t param,
						  uint32_t value);

/**
 * Set the charge input current limit. This value is stored and sent every
 * time AC is applied.
 *
 * @param ma New input current limit in mA
 * @return EC_SUCCESS or error
 */
int charge_set_input_current_limit(int ma);

/**
 * Get value of battery parameter from charge state.
 *
 * @param batt_param	battery parameter
 * @param dest		Destination buffer for data
 * @param read_len	Number of bytes to write to buffer
 * @return EC_SUCCESS if successful, non-zero if error.
 *
 */
int virtual_battery_read(uint8_t batt_param, uint8_t *dest, int read_len);
#endif /* __CROS_EC_CHARGE_STATE_V2_H */


text:
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Example from './containers/Example';

export default (
	<Route path="/" component={Example}>
		<IndexRoute component={Example} />
		{/* <Route path="/about" component={About} /> */}
	</Route>
);


text:
<?php

namespace PhpGitHooks\Module\Configuration\Tests\Behaviour;

use PhpGitHooks\Module\Configuration\Contract\Query\ConfigurationDataFinder;
use PhpGitHooks\Module\Configuration\Contract\Query\ConfigurationDataFinderHandler;
use PhpGitHooks\Module\Configuration\Contract\Response\ConfigurationDataResponse;
use PhpGitHooks\Module\Configuration\Tests\Infrastructure\ConfigurationUnitTestCase;
use PhpGitHooks\Module\Configuration\Tests\Stub\CommitMsgStub;
use PhpGitHooks\Module\Configuration\Tests\Stub\ConfigStub;
use PhpGitHooks\Module\Configuration\Tests\Stub\PreCommitStub;
use PhpGitHooks\Module\Configuration\Tests\Stub\PrePushStub;

class ConfigurationDataFinderHandlerTest extends ConfigurationUnitTestCase
{
    /**
     * @var ConfigurationDataFinderHandler
     */
    private $configurationDataFinderQueryHandler;

    protected function setUp(): void
    {
        $this->configurationDataFinderQueryHandler = new ConfigurationDataFinderHandler(
            $this->getConfigurationFileReader()
        );
    }

    /**
     * @test
     */
    public function itShouldReturnEnabledTools()
    {
        $this->shouldReadConfigurationData(
            ConfigStub::create(
                PreCommitStub::createAllEnabled(),
                CommitMsgStub::createEnabled(),
                PrePushStub::createAllEnabled()
            )
        );

        /** @var ConfigurationDataResponse $data */
        $data = $this->configurationDataFinderQueryHandler->handle(new ConfigurationDataFinder());

        $this->assertTrue($data->getPreCommit()->isPreCommit());
        $this->assertNotNull($data->getPreCommit()->getRightMessage());
        $this->assertNotNull($data->getPreCommit()->getErrorMessage());
        $this->assertTrue($data->getPreCommit()->isComposer());
        $this->assertTrue($data->getPreCommit()->isJsonLint());
        $this->assertTrue($data->getPreCommit()->isPhpLint());
        $this->assertTrue($data->getPreCommit()->getPhpMd()->isPhpMd());
        $this->assertTrue($data->getPreCommit()->getPhpCs()->isPhpCs());
        $this->assertNotNull($data->getPreCommit()->getPhpCs()->getPhpCsStandard());
        $this->assertTrue($data->getPreCommit()->getPhpCsFixer()->isPhpCsFixer());
        $this->assertTrue($data->getPreCommit()->getPhpCsFixer()->isPhpCsFixerPsr0());
        $this->assertTrue($data->getPreCommit()->getPhpCsFixer()->isPhpCsFixerPsr1());
        $this->assertTrue($data->getPreCommit()->getPhpCsFixer()->isPhpCsFixerPsr2());
        $this->assertTrue($data->getPreCommit()->getPhpCsFixer()->isPhpCsFixerSymfony());
        $this->assertTrue($data->getPreCommit()->getPhpUnit()->isPhpunit());
        $this->assertTrue($data->getPreCommit()->getPhpUnit()->isPhpunitRandomMode());
        $this->assertTrue($data->getPreCommit()->getPhpUnitGuardCoverage()->isEnabled());
        $this->assertNotNull($data->getPreCommit()->getPhpUnitGuardCoverage()->getWarningMessage());
        $this->assertNotNull($data->getPreCommit()->getPhpUnit()->getPhpunitOptions());
        $this->assertTrue($data->getCommitMsg()->isCommitMsg());
        $this->assertNotNull($data->getPrePush()->getPhpUnitGuardCoverage()->getWarningMessage());
    }
}


text:
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB)
// Reference Implementation, v2.2.4-2
// See http://java.sun.com/xml/jaxb
// Any modifications to this file will be lost upon recompilation of the source
// schema.
// Generated on: 2013.07.10 at 12:45:26 PM CEST
//
// TOSCA version: TOSCA-v1.0-cs02.xsd
//

package org.opentosca.model.tosca;

import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlType;

/**
 *

 * Java class for tExtensions complex type.
 *
 *

 * The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType name="tExtensions">
 *   <complexContent>
 *     <extension base="{http://docs.oasis-open.org/tosca/ns/2011/12}tExtensibleElements">
 *       <sequence>
 *         <element name="Extension" type="{http://docs.oasis-open.org/tosca/ns/2011/12}tExtension" maxOccurs="unbounded"/>
 *       </sequence>
 *       <anyAttribute processContents='lax' namespace='##other'/>
 *     </extension>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "tExtensions", propOrder = { "extension" })
public class TExtensions extends TExtensibleElements {

	@XmlElement(name = "Extension", required = true)
	protected List<TExtension> extension;

	/**
	 * Gets the value of the extension property.
	 *
	 *

	 * This accessor method returns a reference to the live list, not a snapshot. Therefore any modification you make to the returned list
	 * will be present inside the JAXB object. This is why there is not a set method for the extension property.
	 *
	 *

	 * For example, to add a new item, do as follows:
	 *
	 *

	 * getExtension().add(newItem);
	 *

	 *
	 *
	 *

	 * Objects of the following type(s) are allowed in the list {@link TExtension }
	 *
	 *
	 */
	public List<TExtension> getExtension() {
		if (this.extension == null) {
			this.extension = new ArrayList<TExtension>();
		}
		return this.extension;
	}

}


text:
/**
 * Connection Manager implementation. Connection Managers architecture is composed of two parties.
 *

 *
Connection Managers that accept client connections. Not implemented here.

 *
The Main server that handles Connection Manager connections. Implemented here.

 *

 */
package org.jivesoftware.openfire.multiplex;


text:
<?xml version="1.0" encoding="iso-8859-1"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
          "DTD/xhtml1-transitional.dtd">

  <title>svnmailer.notifier._multimail.URLDecorator</title>
  <link rel="stylesheet" href="epydoc.css" type="text/css"></link>

       Home
       Trees
       Index
       Help

        Package svnmailer ::
        Package notifier ::
        Module _multimail ::
        Class URLDecorator

[show private | hide private]

[frames | no frames]

Class URLDecorator

object --+
         |
        URLDecorator

Shows only the urls, if the mail gets too long

  Method Summary

  __init__(self,
          settings,
          groupset,
          maxsize,
          drop)

Initialization

  _getMailWriter(self,
          fp)

Returns a "urling" mail writer

<tt class="literal">list</tt> of <tt class="literal">_MultiMail</tt>
  _getMultiMails(self)

Returns the multipart mail(s)

  writeContentDiff(self,
          change)

Writes the content diff for a particular change

      Inherited from object

  __delattr__(...)

x.__delattr__('name') <==> del x.name...

  __getattribute__(...)

x.__getattribute__('name') <==> x.name...

  __hash__(x)

x.__hash__() <==> hash(x)...

  __reduce__(...)

helper for pickle...

  __reduce_ex__(...)

helper for pickle...

  __repr__(x)

x.__repr__() <==> repr(x)...

  __setattr__(...)

x.__setattr__('name', value) <==> x.name = value...

  __str__(x)

x.__str__() <==> str(x)...

      Inherited from type

  __new__(T,
          S,
          ...)

T.__new__(S, ...) -> a new object with type S, a subtype of T...

  Instance Variable Summary

<tt class="literal">bool</tt>
do_truncate: truncating mode?

<tt class="literal">int</tt>
max_notification_size: Maximum size of one mail content

<tt class="literal">file</tt>
url_fp: The alternative stream

  Method Details

__init__(self,
          settings,
          groupset,
          maxsize,
          drop)

(Constructor)

Initialization

Parameters:

maxsize -
 The maximum number of bytes that should be written
into one mail

        (type=<tt class="literal">int</tt>)

drop -
 maximum number of mails

        (type=<tt class="literal">int</tt>)

Overrides:

__builtin__.object.__init__

_getMailWriter(self,
          fp)

Returns a "urling" mail writer

_getMultiMails(self)

Returns the multipart mail(s)

Returns:

The mail(s)

        (type=<tt class="literal">list</tt> of <tt class="literal">_MultiMail</tt>)

writeContentDiff(self,
          change)

Writes the content diff for a particular change

  Instance Variable Details

do_truncate

truncating mode?

Type:

<tt class="literal">bool</tt>

max_notification_size

Maximum size of one mail content

Type:

<tt class="literal">int</tt>

url_fp

The alternative stream

Type:

<tt class="literal">file</tt>

       Home
       Trees
       Index
       Help

    Generated by Epydoc 2.0 on Sun Sep 25 20:49:10 2005
    http://epydoc.sf.net


text:
'use strict';

require('should');

const sinon = require('sinon');

const TypeWrapper = require('../../src/typeWrapper');
const MapInstance = require('../../src/mapInstances/base');

const testData = require('./data/mapInstance');

function checkInitialState(mapInstance, convention) {
  (mapInstance.sourceType instanceof TypeWrapper).should.be.eql(true);
  (mapInstance.destType instanceof TypeWrapper).should.be.eql(true);
  mapInstance.mapInfo.should.have.property('size', 0);
  mapInstance.should.have.property('convention', convention);
  (mapInstance.convertCb === null).should.be.eql(true);
}

describe('Base Map Instance', () => {
  describe('Initial state', () => {
    it('should set correct initial state with passed callback', () => {
      const { sourceType, destType, convention } = testData;
      const configCb = sinon.mock().once();
      const mapInstance = new MapInstance(convention, sourceType, destType, configCb);

      checkInitialState(mapInstance, convention);
      configCb.verify();
    });

    it('should set correct initial state without passed callback', () => {
      const { sourceType, destType, convention } = testData;
      const mapInstance = new MapInstance(convention, sourceType, destType);

      checkInitialState(mapInstance, convention);
    });
  });

  describe('#mapField', () => {
    it('should set mapping for field', () => {
      const {
        convention, sourceType, destType, configCb, mapFieldName, mapFieldValue
      } = testData;
      const mapInstance = new MapInstance(convention, sourceType, destType, configCb);

      mapInstance.mapField(mapFieldName, mapFieldValue);
      mapInstance.mapInfo.get(mapFieldName).should.be.eql(mapFieldValue);
    });
  });

  describe('#ignoreField', () => {
    it('should set mapping to ignore the field', () => {
      const { convention, sourceType, destType, configCb, fieldToIgnore } = testData;
      const mapInstance = new MapInstance(convention, sourceType, destType, configCb);

      mapInstance.ignoreField(fieldToIgnore);
      (mapInstance.mapInfo.get(fieldToIgnore) === null).should.be.eql(true);
    });
  });

  describe('#mapFieldByPath', () => {
    it('should set field mapping by path', () => {
      const {
        convention, sourceType, destType, configCb, mapFieldName, fieldPath
      } = testData;
      const mapInstance = new MapInstance(convention, sourceType, destType, configCb);

      mapInstance.mapFieldByPath(mapFieldName, fieldPath);
      (typeof mapInstance.mapInfo.get(mapFieldName)).should.be.eql('function');
    });
  });

  describe('#convert', () => {
    it('should set convert function for map instance', () => {
      const { convention, sourceType, destType, configCb, convertCb } = testData;
      const mapInstance = new MapInstance(convention, sourceType, destType, configCb);

      mapInstance.convert(convertCb);
      mapInstance.convertCb.should.be.eql(convertCb);
    });
  });
});


text:
if ($CopyFromUser -like "*@*") { #If the input has an @ sign in it, its probrably an email.
    $CopyFromUser = get-aduser -Filter {Mail -like $CopyFromUser}
}
else {
    if ($CopyFromUser -like "* *") { #If the input has a space in it,its probrably a name.
        $CopyFromUser = get-aduser -Filter {Name -like $CopyFromUser}
    }
    else {
        if ($CopyFromUser -ne $null) { #if it doesnt have an at sign or a space in it, it may be a first name.
            $copyfromusermaybe = get-aduser -Filter {Givenname -like $CopyFromUser} #search for the people it might be
            if (($copyfromusermaybe).Count -ge 1) { #if it returns more than 1 person, give me a selection window.
                $SelectionMade = $copyfromusermaybe | Out-GridView -Title 'Select $CopyFromUser to use' -passthru
                $CopyFromUser = $SelectionMade
            }
            else {$CopyFromUser = $copyfromusermaybe}
        }
        else {
            "CopyFromField was empty."
            $CopyFromUser = Read-Host "Write the name of  the user we need to copy from"
            $CopyFromUser = get-aduser -Filter {Name -like $CopyFromUser}
        }
    }
}
$CopyFromUserManager = get-aduser $CopyFromUser -Properties Manager | Select-Object -ExpandProperty Manager
Write-host -ForegroundColor Cyan "---- Copy from user is $CopyFromUser ----"


text:
package org.apereo.cas.support.events.dao;

import org.apereo.cas.support.events.CasEventRepository;
import org.apereo.cas.support.events.CasEventRepositoryFilter;

import java.util.ArrayList;
import java.util.Collection;

/**
 * This is {@link NoOpCasEventRepository}.
 *
 * @author Misagh Moayyed
 * @since 5.1.0
 */
public class NoOpCasEventRepository extends AbstractCasEventRepository {

    /**
     * Static instance.
     */
    public static final CasEventRepository INSTANCE = new NoOpCasEventRepository();

    public NoOpCasEventRepository() {
        this(CasEventRepositoryFilter.noOp());
    }

    public NoOpCasEventRepository(final CasEventRepositoryFilter eventRepositoryFilter) {
        super(eventRepositoryFilter);
    }

    @Override
    public CasEvent saveInternal(final CasEvent event) {
        /*
         * A no-op event repository
         * does not save events.
         */
        return event;
    }

    @Override
    public Collection<CasEvent> load() {
        return new ArrayList<>(0);
    }
}


text:
package net.firejack.platform.core.model.registry;

public interface IUrlPathContainer {

    /**
     * @return
     */
    public String getUrlPath();

    /**
     * @param urlPath
     */
    public void setUrlPath(String urlPath);

}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<plugin-artifact xmlns:ns2="http://geronimo.apache.org/xml/ns/attributes-1.2" xmlns="http://geronimo.apache.org/xml/ns/plugins-1.3">
    <module-id>
        <groupId>org.apache.geronimo.configs</groupId>
        <artifactId>wadi-clustering</artifactId>
        <version>3.0-SNAPSHOT</version>
        <type>car</type>
    </module-id>
    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib-nodep</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.bundles</groupId>
        <artifactId>wadi-aop</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.bundles</groupId>
        <artifactId>wadi-core</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.bundles</groupId>
        <artifactId>wadi-group</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.bundles</groupId>
        <artifactId>wadi-tribes</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.configs</groupId>
        <artifactId>aspectj</artifactId>
        <type>car</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.configs</groupId>
        <artifactId>clustering</artifactId>
        <type>car</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.ext.tomcat</groupId>
        <artifactId>shared</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.ext.tomcat</groupId>
        <artifactId>tribes</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.ext.tomcat</groupId>
        <artifactId>util</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.modules</groupId>
        <artifactId>geronimo-clustering-wadi</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.apache.geronimo.specs</groupId>
        <artifactId>geronimo-servlet_3.0_spec</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.codehaus.wadi</groupId>
        <artifactId>wadi-aop</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.codehaus.wadi</groupId>
        <artifactId>wadi-core</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.codehaus.wadi</groupId>
        <artifactId>wadi-group</artifactId>
        <type>jar</type>
    </dependency>
    <dependency>
        <groupId>org.codehaus.wadi</groupId>
        <artifactId>wadi-tribes</artifactId>
        <type>jar</type>
    </dependency>
</plugin-artifact>


text:
from django.contrib import admin
from polls.models import Choice, Poll

class ChoiceInline(admin.TabularInline): #allows stacking from another field
	model = Choice		#choice objects are to be edited in the Poll admin page
	extra = 3

class PollAdmin(admin.ModelAdmin):
	fieldsets = [
        (None,               {'fields': ['question']}),
        ('Date information', {'fields': ['pub_date'], 'classes': ['collapse']}),
	]
	inlines = [ChoiceInline]
	list_display = ('question', 'pub_date', 'was_published_recently')
	list_filter = ['pub_date']
	search_fields = ['question']
	date_hierarchy = 'pub_date'

admin.site.register(Poll, PollAdmin)  #register both Poll and PollAdmin


text:
/**
 * STUFF DOWNLOADED FROM http://wiki.unity3d.com/index.php/Hermite_Spline_Controller
 * AUTHOR: F. Montorsi
 */

using UnityEngine;
using System.Collections;

public class SplineNodeProperties : MonoBehaviour
{
	// this is just a simple placeholder for properties of a spline node
	// (additional to those of the Transform object associated to it!)
	// these properties get copied by the SplineController into SplineNode structures
	// (along with other properties)

	public float BreakTime = 0f;
	public string Name;
}


text:
package org.brunocvcunha.instagram4j.requests.payload;

import lombok.Getter;
import lombok.Setter;

/**
 * InstagramConfigureStoryResult
 * @author Justin Vo
 *
 */
@Getter
@Setter
public class InstagramConfigureStoryResult extends StatusResult {
    private InstagramStoryItem media;
    private String upload_id;
}


text:
import builder from 'bodybuilder'
import config from '../lib/config'

/**
 * Create slugify -> "create-slugify" permalink  of text
 * @param {String} text
 */
export function slugify (text) {
  return text.toString().toLowerCase()
    .replace(/\s+/g, '-') // Replace spaces with -
    .replace(/&/g, '-and-') // Replace & with 'and'
    .replace(/[^\w-]+/g, '') // Remove all non-word chars
    .replace(/--+/g, '-') // Replace multiple - with single -
}

/**
 * Re-format category path to be suitable for breadcrumb
 * @param {Array} categoryPath
 */
export function breadCrumbRoutes (categoryPath) {
  const tmpRts = []
  for (let sc of categoryPath) {
    tmpRts.push({
      name: sc.name,
      route_link: '/c/' + sc.slug
    })
  }

  return tmpRts
}

/**
 * Return configurable product thumbnail depending on the configurable_children
 * @param {object} product
 * @param {bool} ignoreConfig
 */
export function productThumbnailPath (product, ignoreConfig = false) {
  let thumbnail = product.image
  if ((product.type_id && product.type_id === 'configurable') && product.hasOwnProperty('configurable_children') &&
    product.configurable_children.length && (ignoreConfig || !product.is_configured) &&
    ('image' in product.configurable_children[0])
  ) {
    thumbnail = product.configurable_children[0].image
  }
  return thumbnail
}

export function buildFilterProductsQuery (currentCategory, chosenFilters, defaultFilters = null) {
  let filterQr = baseFilterProductsQuery(currentCategory, defaultFilters == null ? config.products.defaultFilters : defaultFilters)
  let attrFilterBuilder = (filterQr, attrPostfix = '') => {
    for (let code of Object.keys(chosenFilters)) {
      const filter = chosenFilters[code]

      if (filter.attribute_code !== 'price') {
        filterQr = filterQr.andFilter('match', filter.attribute_code + attrPostfix, filter.id)
      } else { // multi should be possible filter here?
        const rangeqr = {}
        if (filter.from) {
          rangeqr['gte'] = filter.from
        }
        if (filter.to) {
          rangeqr['lte'] = filter.to
        }
        filterQr = filterQr.andFilter('range', filter.attribute_code, rangeqr)
      }
    }
    return filterQr
  }
  filterQr = filterQr.orFilter('bool', (b) => attrFilterBuilder(b).filter('match', 'type_id', 'simple'))
    .orFilter('bool', (b) => attrFilterBuilder(b, '_options').filter('match', 'type_id', 'configurable'))
  return filterQr
}

export function baseFilterProductsQuery (parentCategory, filters = []) { // TODO add aggregation of color_options and size_options fields
  let searchProductQuery = builder().query('range', 'price', { 'gt': 0 }).andFilter('range', 'visibility', { 'gte': 2, 'lte': 4 }/** Magento visibility in search & categories */)

  // add filters to query
  for (let attrToFilter of filters) {
    if (attrToFilter !== 'price') {
      searchProductQuery = searchProductQuery.aggregation('terms', attrToFilter)
      searchProductQuery = searchProductQuery.aggregation('terms', attrToFilter + '_options')
    } else {
      searchProductQuery = searchProductQuery.aggregation('terms', attrToFilter)
      searchProductQuery.aggregation('range', 'price', {
        ranges: [
          { from: 0, to: 50 },
          { from: 50, to: 100 },
          { from: 100, to: 150 },
          { from: 150 }
        ]
      })
    }
  }

  let childCats = [parentCategory.id]
  if (parentCategory.children_data) {
    let recurCatFinderBuilder = (category) => {
      if (!category) {
        return
      }

      if (!category.children_data) {
        return
      }

      for (let sc of category.children_data) {
        if (sc && sc.id) {
          childCats.push(sc.id)
        }
        recurCatFinderBuilder(sc)
      }
    }
    recurCatFinderBuilder(parentCategory)
  }
  searchProductQuery = searchProductQuery.filter('terms', 'category.category_id', childCats)
  return searchProductQuery
}


text:
package stack

import "jvmgo/instructions/base"
import "jvmgo/rtda"

type DUP struct {
	base.NoOperandsInstruction
}

type DUP_X1 struct {
	base.NoOperandsInstruction
}

type DUP_X2 struct {
	base.NoOperandsInstruction
}

type DUP2 struct {
	base.NoOperandsInstruction
}

type DUP2_X1 struct {
	base.NoOperandsInstruction
}

type DUP2_X2 struct {
	base.NoOperandsInstruction
}

func (self *DUP) Execute(frame *rtda.Frame) {
	stack := frame.OperandStack()
	slot := stack.PopSlot()
	stack.PushSlot(slot)
	stack.PushSlot(slot)
}


text:
var demand = require('must');
var proxyquire = require('proxyquire');
var sinon = require('sinon');

describe('Email', function () {
	/**
	 * SETUP
	 */
	var keystoneEmail;
	var Email;

	beforeEach(function () {
		// Make the tests work no matter if keystone-email is installed or not, spying on the mocked
		// keystone-email
		keystoneEmail = sinon.spy();
		Email = proxyquire('../../../lib/email', { 'keystone-email': keystoneEmail });
	});

	/**
	 * TESTS
	 */
	it('should require options to be passed in', function () {
		demand(Email).throw(/requires a templateName or options argument/);
	});

	it('should require keystone-email to be installed', function () {
		// Pretend keystone-email isn't installed for this test
		var Email = proxyquire('../../../lib/email', { 'keystone-email': null });
		try {
			Email({});
		} catch (err) {
			demand(err.message).contain('keystone-email');
		}
	});

	it('should return an instance of keystone-email', function () {
		demand(Email({})).instanceof(keystoneEmail);
	});

	it('should allow a string to be passed in as the template name', function () {
		var templateName = 'templatename';
		Email(templateName);
		demand(keystoneEmail.calledOnce).true();
		demand(keystoneEmail.getCall(0).args[0]).eql(templateName);
	});

	it('should pass on the options passed in', function () {
		var options = { some: 'options' };
		Email(options);
		demand(keystoneEmail.calledOnce).true();
		demand(keystoneEmail.getCall(0).args[1]).eql(options);
	});
});


text:
using System;
using System.Collections.Generic;
using System.Text;

namespace Angora
{
    static class CustomBufferReaderExtensions
    {
        static List<object> ReadArray(this ref CustomBufferReader reader)
        {
            var result = new List<object>();

            var arrayLength = reader.ReadUInt32();
            var initialBytesConsumed = reader.ConsumedBytes;

            while (reader.ConsumedBytes < arrayLength + initialBytesConsumed)
            {
                var fieldValue = reader.ReadFieldValue();

                result.Add(fieldValue);
            }

            return result;
        }

        public static Dictionary<string, object> ReadTable(this ref CustomBufferReader reader)
        {
            var result = new Dictionary<string, object>();

            var tableLength = reader.ReadUInt32();
            var initialBytesConsumed = reader.ConsumedBytes;

            while (reader.ConsumedBytes < tableLength + initialBytesConsumed)
            {
                var fieldName = reader.ReadShortString();
                var fieldValue = reader.ReadFieldValue();

                result.Add(fieldName, fieldValue);
            }

            return result;
        }

        static object ReadFieldValue(this ref CustomBufferReader reader)
        {
            var fieldValueType = reader.ReadByte();

            switch ((char)fieldValueType)
            {
                case 't':
                    return Convert.ToBoolean(reader.ReadByte());
                case 'b':
                    return reader.ReadSByte();
                case 'B':
                    return reader.ReadByte();
                case 's':
                    return reader.ReadInt16();
                case 'u':
                    return reader.ReadUInt16();
                case 'I':
                    return reader.ReadInt32();
                case 'i':
                    return reader.ReadUInt32();
                case 'l':
                    return reader.ReadInt64();
                case 'f':
                    return reader.ReadFloat();
                case 'd':
                    return reader.ReadDouble();
                case 'D':
                    return reader.ReadDecimal();
                case 'S':
                    return reader.ReadLongString();
                case 'A':
                    return reader.ReadArray();
                case 'T':
                    return reader.ReadTimestamp();
                case 'F':
                    return reader.ReadTable();
                case 'V':
                    return null;
                case 'x':
                    return reader.ReadBytes();
                default:
                    throw new Exception($"Unknown field value type: '{fieldValueType}'.");
            }
        }

        public static string ReadShortString(this ref CustomBufferReader reader)
        {
            var length = reader.ReadByte();
            var bytes = reader.ReadBytes(length);

            return Encoding.UTF8.GetString(bytes.ToArray());
        }

        public static string ReadLongString(this ref CustomBufferReader reader)
        {
            var length = reader.ReadUInt32();
            var bytes = reader.ReadBytes((int)length); // TODO check cast

            return Encoding.UTF8.GetString(bytes.ToArray());
        }

        static byte[] ReadBytes(this ref CustomBufferReader reader)
        {
            var length = reader.ReadUInt32();
            var bytes = reader.ReadBytes((int)length); // TODO check cast

            return bytes.ToArray();
        }

        static decimal ReadDecimal(this ref CustomBufferReader reader)
        {
            var scale = reader.ReadByte();
            var value = reader.ReadUInt32();

            return default; //TODO return real value
        }

        static DateTime ReadTimestamp(this ref CustomBufferReader reader)
        {
            var time = reader.ReadUInt64();

            return DateTimeOffset.FromUnixTimeSeconds((long)time).DateTime; //TODO check the cast
        }

        public static MessageProperties ReadBasicProperties(this ref CustomBufferReader reader)
        {
            var properties = new MessageProperties();

            var flags = reader.ReadUInt16();

            if ((flags & 1 << 15) != 0)
            {
                properties.ContentType = reader.ReadShortString();
            }

            if ((flags & 1 << 14) != 0)
            {
                properties.ContentEncoding = reader.ReadShortString();
            }

            if ((flags & 1 << 13) != 0)
            {
                properties.Headers = reader.ReadTable();
            }

            if ((flags & 1 << 12) != 0)
            {
                properties.DeliveryMode = reader.ReadByte();
            }

            if ((flags & 1 << 11) != 0)
            {
                properties.Priority = reader.ReadByte();
            }

            if ((flags & 1 << 10) != 0)
            {
                properties.CorrelationId = reader.ReadShortString();
            }

            if ((flags & 1 << 9) != 0)
            {
                properties.ReplyTo = reader.ReadShortString();
            }

            if ((flags & 1 << 8) != 0)
            {
                properties.Expiration = reader.ReadShortString();
            }

            if ((flags & 1 << 7) != 0)
            {
                properties.MessageId = reader.ReadShortString();
            }

            if ((flags & 1 << 6) != 0)
            {
                properties.Timestamp = reader.ReadTimestamp();
            }

            if ((flags & 1 << 5) != 0)
            {
                properties.Type = reader.ReadShortString();
            }

            if ((flags & 1 << 4) != 0)
            {
                properties.UserId = reader.ReadShortString();
            }

            if ((flags & 1 << 3) != 0)
            {
                properties.AppId = reader.ReadShortString();
            }

            return properties;
        }
    }
}


text:
using NUnit.Framework;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Game.Overlays;
using osu.Game.Screens.Edit.Timing;
using osuTK;
using osuTK.Input;

namespace osu.Game.Tests.Visual.Editing
{
    public class TestSceneTapButton : OsuManualInputManagerTestScene
    {
        private TapButton tapButton;

        [Cached]
        private readonly OverlayColourProvider overlayColour = new OverlayColourProvider(OverlayColourScheme.Aquamarine);

        [Test]
        public void TestBasic()
        {
            AddStep("create button", () =>
            {
                Child = tapButton = new TapButton
                {
                    Anchor = Anchor.Centre,
                    Origin = Anchor.Centre,
                    Scale = new Vector2(4),
                };
            });

            bool pressed = false;

            AddRepeatStep("Press button", () =>
            {
                InputManager.MoveMouseTo(tapButton);
                if (!pressed)
                    InputManager.PressButton(MouseButton.Left);
                else
                    InputManager.ReleaseButton(MouseButton.Left);

                pressed = !pressed;
            }, 100);
        }
    }
}