text:
#ifndef AddicoreRFID_h
#define AddicoreRFID_h

#include <Arduino.h>
#include <SPI.h>
#include <inttypes.h>

//#define	uchar	unsigned char
#define	uint	unsigned int

//AddicoreRFID Primary Coupling Device (PCD according to the ISO14443) Commands
#define PCD_IDLE                0x00  // no action, cancels current command execution
#define PCD_MEM                 0x01  // stores 25 bytes into the internal buffer
#define PCD_GENRANDOMID         0x02  // generates a 10-byte random ID number
#define PCD_CALCCRC             0x03  // activates the CRC calculation or performs a self test
#define PCD_TRANSMIT            0x04  // Transmit data
#define PCD_NOCMDCHANGE         0x07  // no command change, can be used to modify the CommandReg register bits without affecting the command, for example, the PowerDown bit
#define PCD_RECEIVE             0x08  // activates the receiver circuits (receive data)
#define PCD_TRANSCEIVE          0x0C  // transmits data from FIFO buffer to antenna and automatically activates the receiver after transmission (transmit and receive data)
#define PCD_MFAUTHENT           0x0E  // performs the MIFARE standard authentication as a reader (authentication)
#define PCD_SOFTRESET           0x0F  // resets the MFRC522

// AddicoreRFID Proximity Integrated Circuit Card (PICC) Commands
#define PICC_REQIDL             0x26  // search the antenna area. PCD does not enter hibernation
#define PICC_REQALL             0x52  // find all the cards in antenna area
#define PICC_ANTICOLL           0x93  // anti-collision
#define PICC_SElECTTAG          0x93  // Select card
#define PICC_AUTHENT1A          0x60  // authentication with key A
#define PICC_AUTHENT1B          0x61  // authentication with key B
#define PICC_READ               0x30  // reads one memory block
#define PICC_WRITE              0xA0  // writes one memory block
#define PICC_DECREMENT          0xC0  // decrements the contents of a block and stores the result in the internal data register
#define PICC_INCREMENT          0xC1  // increments the contents of a block and stores the result in the internal data register
#define PICC_RESTORE            0xC2  // reads the contents of a block into the internal data register
#define PICC_TRANSFER           0xB0  // writes the contents of the internal data register to a block
#define PICC_HALT               0x50  // Sleep the card

// AddicoreRFID PICC Responses
#define MI_ACK                  0xA   // The 4-bit acknowledgement returned from a MIFARE Classic PICC
#define MI_ATQA                 0x04 //The 16-bit ATQA (Answer To Request acc. to ISO/IEC 14443-4) response from PICC
#define MI_SAK                  0x08  // The 8-bit SAK (Select Acknowledge, Type A) response from PICC

// AddicoreRFID Default Definable Pins
#define DEFAULT_CHIP_SELECT_PIN         10
#define DEFAULT_RESET_PIN               5

//AddicoreRFID error codes
#define MI_OK                   0
#define MI_NO_TAG_ERR           1
#define MI_ERR                  2

//Maximum length of the array
#define MAX_LEN 16

////////////////////////////////////////////////////////////////
// AddicoreRFID Registers
////////////////////////////////////////////////////////////////
/* The information below regarding the MFRC522 registers is from
   the MFRC522 Manufacturer's Datasheet (Rev. 3.6 — 14 December 2011), Table 20
*/
//Page 0: Command and Status
#define     Reserved00          0x00  // reserved for future use
#define     CommandReg          0x01  // starts and stops command execution
#define     ComIEnReg           0x02  // enable and disable the passing of interrupt requests to IRq pin
#define     DivlEnReg           0x03  // enable and disable interrupt request control bits
#define     ComIrqReg           0x04  // interrupt request bits
#define     DivIrqReg           0x05  // interrupt request bits
#define     ErrorReg            0x06  // error bits showing the error status of the last command executed
#define     Status1Reg          0x07  // communication status bits
#define     Status2Reg          0x08  // receiver and transmitter status bits
#define     FIFODataReg         0x09  // input and output of 64 byte FIFO buffer
#define     FIFOLevelReg        0x0A  // number of bytes stored in the FIFO buffer
#define     WaterLevelReg       0x0B  // level for FIFO underflow and overflow warning
#define     ControlReg          0x0C  // miscellaneous control registers
#define     BitFramingReg       0x0D  // adjustments for bit-oriented frames
#define     CollReg             0x0E  // bit position of the first bit-collision detected on the RF interface
#define     Reserved01          0x0F  // reserved for future use
//Page 1: Command
#define     Reserved10          0x10  // reserved for future use
#define     ModeReg             0x11  // defines general modes for transmitting and receiving
#define     TxModeReg           0x12  // defines transmission data rate and framing
#define     RxModeReg           0x13  // defines reception data rate and framing
#define     TxControlReg        0x14  // controls the logical behavior of the antenna driver pins TX1 and TX2
#define     TxAutoReg           0x15  // controls the setting of the transmission modulation
#define     TxSelReg            0x16  // selects the internal sources for the antenna driver
#define     RxSelReg            0x17  // selects internal receiver settings
#define     RxThresholdReg      0x18  // selects thresholds for the bit decoder
#define     DemodReg            0x19  // defines demodulator settings
#define     Reserved11          0x1A  // reserved for future use
#define     Reserved12          0x1B  // reserved for future use
#define     MfTxReg             0x1C  // controls some MIFARE communication transmit parameters
#define     MfRxReg             0x1D  // controls some MIFARE communication receive parameters
#define     Reserved13          0x1E  // reserved for future use
#define     SerialSpeedReg      0x1F  // selects the speed of the serial UART interface
//Page 2: Configuration
#define     Reserved20          0x20  // reserved for future use
#define     CRCResultRegM       0x21  // shows the MSB values of the CRC calculation
#define     CRCResultRegL       0x22  // shows the LSB values of the CRC calculation
#define     Reserved21          0x23  // reserved for future use
#define     ModWidthReg         0x24  // controls the ModWidth setting
#define     Reserved22          0x25  // reserved for future use
#define     RFCfgReg            0x26  // configures the receiver gain
#define     GsNReg              0x27  // selects the conductance of the antenna driver pins TX1 and TX2 for modulation
#define     CWGsPReg	        0x28  // defines the conductance of the p-driver output during periods of no modulation
#define     ModGsPReg           0x29  // defines the conductance of the p-driver output during periods of modulation
#define     TModeReg            0x2A  // defines settings for the internal timer
#define     TPrescalerReg       0x2B  // defines settings for the internal timer
#define     TReloadRegH         0x2C  // defines the higher 8 bits of the 16-bit timer reload value
#define     TReloadRegL         0x2D  // defines the lower 8 bits of the 16-bit timer reload value
#define     TCounterValueRegH   0x2E  // shows the higher 8 bits of the 16-bit timer value
#define     TCounterValueRegL   0x2F  // shows the lower 8 bits of the 16-bit timer value
//Page 3: Test Registers
#define     Reserved30          0x30  // reserved for future use
#define     TestSel1Reg         0x31  // general test signal configuration
#define     TestSel2Reg         0x32  // general test signal configuration and PRBS control
#define     TestPinEnReg        0x33  // enables pin output driver on pins D1 to D7
#define     TestPinValueReg     0x34  // defines the values for D1 to D7 when it is used as an I/O bus
#define     TestBusReg          0x35  // shows the status of the internal test bus
#define     AutoTestReg         0x36  // controls the digital self test
#define     VersionReg          0x37  // shows the software version
#define     AnalogTestReg       0x38  // controls the pins AUX1 and AUX2
#define     TestDAC1Reg         0x39  // defines the test value for TestDAC1
#define     TestDAC2Reg         0x3A  // defines the test value for TestDAC2
#define     TestADCReg          0x3B  // shows the value of ADC I and Q channels
#define     Reserved31          0x3C  // reserved for production tests
#define     Reserved32          0x3D  // reserved for production tests
#define     Reserved33          0x3E  // reserved for production tests
#define     Reserved34		    0x3F  // reserved for production tests

class AddicoreRFID
{
public:
	AddicoreRFID();
	AddicoreRFID( byte chipSelectPin, byte resetPin);
	void Setup_AddicoreRFID(void);
	void Advanced_Setup_AddicoreRFID(byte chipSelectPin, byte resetPin);
	void AddicoreRFID_Init(void);						// Initialize the AddicoreRFID Module
	void Write_AddicoreRFID(byte addr, byte val);		// To a certain AddicoreRFID register to write a byte of data
	byte Read_AddicoreRFID(byte addr);				// From a certain AddicoreRFID read a byte of data register
	void SetBitMask(byte reg, byte mask);				// Set RC522 register bit
	void ClearBitMask(byte reg, byte mask);			// clear RC522 register bit
	void AntennaOn(void);								// Open antennas, each time you start or shut down the natural barrier between the transmitter should be at least 1ms interval
	void AntennaOff(void);								// Close antennas, each time you start or shut down the natural barrier between the transmitter should be at least 1ms interval
	void AddicoreRFID_Reset(void);						// Soft reset of AddicoreRFID module
	byte AddicoreRFID_Request(byte reqMode, byte *TagType);	// Find cards, read the card type number
	byte AddicoreRFID_ToCard(byte command, byte *sendData, byte sendLen, byte *backData, uint *backLen);	// RC522 and ISO14443 card communication
	byte AddicoreRFID_Anticoll(byte *serNum);			// Anti-collision detection, reading selected card serial number card
	void CalulateCRC(byte *pIndata, byte len, byte *pOutData);	// CRC calculation with MF522
	uint AddicoreRFID_SelectTag(byte *serNum);			// Selection card, read the card memory capacity
	byte AddicoreRFID_Auth(byte authMode, byte BlockAddr, byte *Sectorkey, byte *serNum);	// Verify card password
	byte AddicoreRFID_Read(byte blockAddr, byte *recvData);	// Read block data
	byte AddicoreRFID_Write(byte blockAddr, byte *_writeData);	// Write block data
	void AddicoreRFID_Halt(void);						// Command card into hibernation
	byte serNum[];
	byte getNumRxBits(void);                                //Returns the number of received data bits
private:
	byte _chipSelectPin;								// Arduino pin connected to AddicoreRFID SDA pin (active low)
	byte _resetPin;                                     // Arduino pin connected to AddicoreRFID RST (reset) pin (active low)
	uint _RxBits;			                            // The number of received data bits
};

#endif


text:
package edu.neu.ccs.pyramid.eval;

import edu.neu.ccs.pyramid.classification.Classifier;
import edu.neu.ccs.pyramid.classification.logistic_regression.LogisticRegression;
import edu.neu.ccs.pyramid.classification.logistic_regression.Weights;
import edu.neu.ccs.pyramid.dataset.DataSet;
import edu.neu.ccs.pyramid.dataset.MultiLabel;
import edu.neu.ccs.pyramid.dataset.MultiLabelClfDataSet;
import edu.neu.ccs.pyramid.multilabel_classification.MultiLabelClassifier;
import edu.neu.ccs.pyramid.multilabel_classification.cbm.CBM;
import edu.neu.ccs.pyramid.util.ArgSort;
import edu.neu.ccs.pyramid.util.Pair;
import org.apache.commons.math3.util.FastMath;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.mahout.math.Vector;
import org.apache.xpath.operations.Bool;

import java.util.Arrays;
import java.util.List;
import java.util.stream.IntStream;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by chengli on 11/11/14.
 */
public class KLDivergence {
    private static final Logger logger = LogManager.getLogger();

    public static double kl(double[] trueDistribution, double[] estimatedDistribution){
        double r = 0;
        for (int i=0;i<trueDistribution.length;i++){
            if (trueDistribution[i]==0){
                r += 0;
            } else if (estimatedDistribution[i]==0){
                r = Double.POSITIVE_INFINITY;
                break;
            } else {
                r += trueDistribution[i]* (Math.log(trueDistribution[i])-Math.log(estimatedDistribution[i]));
            }
        }
        if (Double.isInfinite(r)&&logger.isDebugEnabled()){
            logger.debug("true distribution = "+ Arrays.toString(trueDistribution));
            logger.debug("estimated distribution = "+ Arrays.toString(estimatedDistribution));
        }

        if (Double.isNaN(r)){
            throw new RuntimeException("KL divergence between "+Arrays.toString(trueDistribution)+" and "+Arrays.toString(estimatedDistribution)+" is NaN");
        }
        return r;
    }

    public static double klGivenPLogQ(double[] targetDistribution, double[] logEstimatedDistribution){
        double r = 0;
        for (int i=0;i<targetDistribution.length;i++){
            // if ==0, don't change sum
            if (targetDistribution[i]!=0){
                r += targetDistribution[i]* (Math.log(targetDistribution[i])-logEstimatedDistribution[i]);
            }
        }
        return r;
    }

    public static double kl(Classifier.ProbabilityEstimator estimator, Vector vector, double[] targetDistribution){
        double[] logEstimation = estimator.predictLogClassProbs(vector);
        return KLDivergence.klGivenPLogQ(targetDistribution,logEstimation);
    }

    public static double kl(Classifier.ProbabilityEstimator estimator, DataSet dataSet,
                     double[][] targetDistributions, double[] weights) {
        double sum = 0.0;
        for(int n=0; n<dataSet.getNumDataPoints(); n++) {
            sum += weights[n] * kl(estimator, dataSet.getRow(n), targetDistributions[n]);
        }
        return sum;
    }

    public static double kl(Classifier.ProbabilityEstimator estimator, DataSet dataSet,
                     double[][] targetDistributions) {
        double[] weights = new double[dataSet.getNumDataPoints()];
        Arrays.fill(weights,1.0);
        return kl(estimator,dataSet,targetDistributions,weights);
    }

    // total KL
    public static double kl(MultiLabelClassifier.AssignmentProbEstimator multiLabelClassifier, MultiLabelClfDataSet dataSet){
        return IntStream.range(0, dataSet.getNumDataPoints())
                .mapToDouble(i-> multiLabelClassifier.predictLogAssignmentProb(dataSet.getRow(i), dataSet.getMultiLabels()[i]))
                .sum()*(-1);
    }

    // empirical KL
    public static double kl_conditional(MultiLabelClassifier.AssignmentProbEstimator multiLabelClassifier, MultiLabelClfDataSet dataSet){
        Map<MultiLabel, Integer> q_z = new HashMap<MultiLabel, Integer>();
        Map<MultiLabel, HashMap<MultiLabel, Integer>> q_yz = new HashMap<MultiLabel, HashMap<MultiLabel, Integer>>();

        // get overall empirical distribution
        for (int i = 0; i < dataSet.getNumDataPoints(); ++i) {
            MultiLabel z = new MultiLabel(dataSet.getRow(i));
            MultiLabel y = dataSet.getMultiLabels()[i];
            if (q_z.containsKey(z)) {
                q_z.put(z, q_z.get(z) + 1);
            } else {
                q_z.put(z, 1);
            }

            if (!q_yz.containsKey(z)) {
                q_yz.put(z, new HashMap<MultiLabel, Integer>());
            }
            if (q_yz.get(z).containsKey(y)) {
                q_yz.get(z).put(y, q_yz.get(z).get(y) + 1);
            } else {
                q_yz.get(z).put(y, 1);
            }
        }

        // compute kl divergence
        double kl = 0.0;
        for (Map.Entry<MultiLabel, Integer> e1 : q_z.entrySet()) {
            double kl_y = 0.0;
            for (Map.Entry<MultiLabel, Integer> e2 : q_yz.get(e1.getKey()).entrySet()) {
                double empirical_prob_yz = (double)e2.getValue() / (double)e1.getValue();
                double log_estimated_prob_yz = multiLabelClassifier.predictLogAssignmentProb(e1.getKey().toVector(dataSet.getNumFeatures()), e2.getKey());
                kl_y += empirical_prob_yz * (Math.log(empirical_prob_yz) - log_estimated_prob_yz);
            }
            double empirical_prob_z = (double)e1.getValue() / (double)dataSet.getNumDataPoints();
            kl += empirical_prob_z * kl_y;
        }

        // Printing information if needed
        int occur_threshold = 10;
        double marginal_threshold = 0.01;
        for (Map.Entry<MultiLabel, Integer> e1 : q_z.entrySet()) {
            double[] marginals1 = new double[dataSet.getNumFeatures()];
            for (Map.Entry<MultiLabel, Integer> e2 : q_yz.get(e1.getKey()).entrySet()) {
                double estimated_prob_yz = multiLabelClassifier.predictAssignmentProb(e1.getKey().toVector(dataSet.getNumFeatures()), e2.getKey());
                double empirical_prob_yz = (double)e2.getValue() / (double)e1.getValue();
                if (e1.getValue() >= occur_threshold) {
                    System.out.println("#z:" + e1.getValue()+ ",z=" +
                            e1.getKey().toStringWithExtLabels(dataSet.getLabelTranslator()) + "->{" +
                            e2.getKey().toStringWithExtLabels(dataSet.getLabelTranslator()) + "},#y:" +
                            e2.getValue() + ",p_y|z_empirical:" + empirical_prob_yz +
                            ",p_y|z_estimated:" + estimated_prob_yz);
                }
                for (int i = 0; i < dataSet.getNumFeatures(); i++) {
                    if (e2.getKey().matchClass(i)) {
                        marginals1[i] += e2.getValue();
                    }
                }
            }
            if (e1.getValue() >= occur_threshold) {
                double estimated_prob_zz = multiLabelClassifier.predictAssignmentProb(e1.getKey().toVector(dataSet.getNumFeatures()), e1.getKey());
                System.out.println("p(y=z|z)=" + estimated_prob_zz);
                CBM cbm = (CBM) multiLabelClassifier;
//                List<MultiLabel> sampled = cbm.samples(e1.getKey().toVector(dataSet.getNumFeatures()), 10);
//                for (int i = 0; i < sampled.size(); ++i) {
//                    double prob = multiLabelClassifier.predictAssignmentProb(e1.getKey().toVector(dataSet.getNumFeatures()), sampled.get(i));
//                    System.out.println(sampled.get(i).toStringWithExtLabels(dataSet.getLabelTranslator()) + ":" + prob);
//                }
                System.out.println("p_y|z_estimated marginals are: ");
                double[] marginals = cbm.predictClassProbs(e1.getKey().toVector(dataSet.getNumFeatures()));
                int[] order = ArgSort.argSortDescending(marginals);
                for (int i = 0; i < order.length; ++i) {
                    if (marginals[order[i]] > marginal_threshold) {
                        System.out.println(dataSet.getLabelTranslator().toExtLabel(order[i]) + ":" + marginals[order[i]]);
                    }
                }

                System.out.println("p_y|z_empirical marginals are: ");
                for (int i = 0; i < dataSet.getNumFeatures(); i++) {
                    marginals1[i] /= (double)e1.getValue();
                }
                int[] order1 = ArgSort.argSortDescending(marginals1);
                for (int i = 0; i < order1.length; ++i) {
                    if (marginals1[order1[i]] > marginal_threshold) {
                        System.out.println(dataSet.getLabelTranslator().toExtLabel(order1[i]) + ":" + marginals1[order1[i]]);
                    }
                }
            }
        }

        System.out.println("LRs for each label:");
        CBM cbm = (CBM) multiLabelClassifier;
        Classifier.ProbabilityEstimator[] estimators = cbm.getBinaryClassifiers()[0];
        for (int i = 0; i < estimators.length; i++) {
            System.out.println("LR:" + dataSet.getLabelTranslator().toExtLabel(i));
            LogisticRegression lr = (LogisticRegression)estimators[i];
            Vector weight_vec = lr.getWeights().getWeightsWithoutBiasForClass(1);
            double[] weights = new double[weight_vec.size()];
            for (int j = 0; j < weight_vec.size(); j++) {
                weights[j] = weight_vec.get(j);
            }

            System.out.println("bias:" + lr.getWeights().getBiasForClass(1));
            int[] order2 = ArgSort.argSortDescending(weights);
            for (int j = 0; j < order2.length; ++j) {
                System.out.println(dataSet.getLabelTranslator().toExtLabel(order2[j]) + ":" + weights[order2[j]]);
            }
        }
        System.out.println("---");

        return kl;
    }
}

redpajama_set_name: RedPajamaGithub


text:
package org.om.core.api.annotation;

import java.util.*;

/**
 * Defines how to create the keys for {@link Map}s.
 *
 * @author Jakob Külzer
 */
public enum MapKeyStrategy {
	/**
	 * Use the name of the node as the key.
	 */
	Name,
	/**
	 * Use a property under each entry's node. This only works for complex target types.
	 */
	Property,
	/**
	 * Use a zero based index as key. This is hardly useful, but I just felt there might be
	 * situations where this is handy.
	 */
	Index
}


text:
package io.github.rcarlosdasilva.weixin.core.exception;

public class OpenPlatformTicketNotFoundException extends RuntimeException {

  private static final long serialVersionUID = 789236695987149410L;

}


text:
#pragma once
#include <vector>
#include "Phrase.hpp"
#include "UnitBezier.h"
#include "TimeType.h"

namespace choreograph
{

enum class Interpolate {
    BEZIER,
    HOLD,
    LINEAR
};

class Curve
{
public:
  enum Type {
    Bezier,
    Hold,
    Linear
  };

  Curve() = default;
  Curve(Type t):
    _type(t)
  {}
  Curve(const BezierInterpolant &bezier):
    _type(Bezier),
    _bezier(bezier)
  {}

  float              solve(float t) const;
  void               setType(Type type) { _type = type; }
  void               hold() { _type = Hold; }
  BezierInterpolant& bezier() { _type = Bezier; return _bezier; }
  const BezierInterpolant& bezier() const { assert(_type == Bezier); return _bezier; }
  Type               type() const { return _type; }
private:
  Type              _type = Linear;
  BezierInterpolant _bezier;
};

inline float Curve::solve(float t) const
{
  switch (_type) {
    case Bezier:
      return _bezier.solve(t);
    break;
    case Hold:
      return 0.0f;
    break;
    case Linear:
      return t;
    break;
    default:
      return t;
    break;
  }
}

///
/// Simple channel concept with bezier interpolation between keys.
/// Goals:
/// - Easy serialization
/// - Easy to create graphical manipulation tools.
///   - Support direct manipulation of animation data.
///   - Avoid deeply nested information. Flat hierarchy.
/// - Flexible enough to create an AfterEffects-style timeline.
///   - Separate motion path with bezier interpolation for full effect.
///   - Get time along section with channel, calculate value using path.
///   - Channel for timing, with key values corresponding to control points on spatial curve.
///
/// Good for animating single values, like floats or quaternions.
/// For vector types, use a channel per component (and maybe add a group type to associate them).
/// Grouping type could be a manipulator/animator type class that reads/writes multiple channels.
///
template <typename T>
class Channel
{
public:
  struct Key {
    Key(T value, Time time):
      value(value),
      time(time)
    {}
    T    value;
    Time time;
  };

  class KeyInfo
  {
  public:
    KeyInfo(Key &current, Key *previous, Key *next, Curve *c1, Curve *c2):
      _current(current),
      _previous(previous),
      _next(next),
      _curve_in(c1),
      _curve_out(c2)
    {}

    T    value() const {
      return _current.value;
    }
    T    previousValue() const {
      return _previous ? _previous->value : value();
    }
    T    nextValue() const {
      return _next ? _next->value : value();
    }
    Time time() const {
      return _current.time;
    }
    Time nextTime() const {
      return _next ? _next->time : std::numeric_limits<Time>::max();
    }
    Time previousTime() const {
      return _previous ? _previous->time : 0;
    }

    bool isFirst() const { return _previous == nullptr; }
    bool isLast() const { return _next == nullptr; }

    const Curve* curveOut() const { return _curve_out; }
    const Curve* curveIn() const { return _curve_in; }

  protected:
    Key   &_current;
    Curve *_curve_in = nullptr;
    Curve *_curve_out = nullptr;
  private:
    Key   *_previous = nullptr;
    Key   *_next = nullptr;
  };

  class KeyManipulator : public KeyInfo
  {
  public:
    KeyManipulator(Key &current, Key *previous, Key *next, Curve *c1, Curve *c2):
      KeyInfo(current, previous, next, c1, c2)
    {}

    void setValue(const T &value) {
      this->_current.value = value;
    }

    void setTime(Time t) {
      this->_current.time = std::min(std::max(t, this->previousTime()), this->nextTime());
    }

    Curve* curveOut() { return this->_curve_out; }
    Curve* curveIn() { return this->_curve_in; }
  };

  Channel() = default;
  template <typename ... Keys>
  Channel(T value, Time at_time, Curve::Type curve_type, Keys&&... keys) {
    insertKey(value, at_time, curve_type, std::forward<Keys>(keys)...);
  }
  template <typename ... Keys>
  Channel(T value, Seconds at_time, Curve::Type curve_type, Keys&&... keys) {
    insertKey(value, at_time, curve_type, std::forward<Keys>(keys)...);
  }

  /// Return the value of the channel at a given time.
  T value(Time at_time) const;
  /// Return the interpolated value between two keys.
  /// If you keep track of keys yourself, this is faster.
  T interpolatedValue(size_t curve_index, Time at_time) const;

  /// Returns the index of the starting key for the current time.
  /// The curve lies between two keys.
  size_t index(Time at_time) const;
  size_t lastIndex() const { return _keys.empty() ? 0 : _keys.size() - 1; }

  /// Append a key to the list of keys, positioned at \offset time after the previous key.
  Channel& appendKeyAfter(T value, Time offset, Curve::Type curve_type = Curve::Linear) {
    _keys.emplace_back(value, duration() + offset);
    _curves.emplace_back(curve_type);
    return *this;
  }
  /// Insert a key at the given time.
  Channel& insertKey(T value, Time at_time, Curve curve = Curve(Curve::Linear));
  /// Insert multiple keys.
  template <typename ... Keys>
  Channel& insertKey(T value, Time at_time, Curve curve, Keys&&... keys);

  /// Insert a key at the given time using chrono::seconds.
  Channel& insertKey(T value, Seconds at_time, Curve curve = Curve(Curve::Linear)) { return insertKey(value, at_time.count(), curve); }
  /// Insert multiple keys using chrono::seconds.
  template <typename ... Keys>
  Channel& insertKey(T value, Seconds at_time, Curve curve, Keys&&... keys);

  bool     empty() const { return _keys.empty(); }
  Time     duration() const { return empty() ? 0 : _keys.back().time; }
  const std::vector<Key>&   keys() const { return _keys; }
  const std::vector<Curve>& curves() const { return _curves; }

  /// Returns a manipulator to adjust properties of the requested key.
  KeyManipulator keyControl(size_t key_index);
  /// Returns an object allowing easier observation of a key and its neighbors.
  const KeyInfo  keyInfo(size_t key_index) const;

  // TODO: remove general mutability from keys/curves in favor of KeyManipulators.
  std::vector<Key>&   mutableKeys() { return _keys; }
  std::vector<Curve>& mutableCurves() { return _curves; }

private:
  std::vector<Key>   _keys;
  // may make polymorphic in future (like phrases are). Basically just an ease fn.
  // Compare std::function<float (float)> for max flexibility against custom class.
  std::vector<Curve> _curves;
};

#pragma mark - Channel Template Implementation

template <typename T>
size_t Channel<T>::index(Time at_time) const {

  if( at_time <= 0 ) {
    return 0;
  }
  else if ( at_time >= this->duration() ) {
    return lastIndex();
  }

  for (auto i = 0; i < _keys.size() - 1; i += 1) {
    auto &a = _keys[i], &b = _keys[i + 1];
    if (a.time <= at_time && b.time > at_time) {
      return i;
    }
  }
  return lastIndex();
}

template <typename T>
T Channel<T>::value(Time at_time) const {
  if (at_time >= duration()) {
    return _keys.back().value;
  }
  else if (at_time <= 0.0) {
    return _keys.front().value;
  }

  return interpolatedValue(index(at_time), at_time);
}

template <typename T>
T Channel<T>::interpolatedValue(size_t curve_index, Time at_time) const {
  auto &a = _keys[curve_index];
  auto &b = _keys[curve_index + 1];
  auto &c = _curves[curve_index];

  auto x = (at_time - a.time) / (b.time - a.time);
  auto t = c.solve(x);
  return lerpT(a.value, b.value, t);
}

template <typename T>
Channel<T>& Channel<T>::insertKey(T value, Time at_time, Curve curve) {
  auto i = index(at_time);
  if (_keys.empty()) {
    _keys.emplace_back(value, at_time);
  }
  else {
    _keys.insert(_keys.begin() + i + 1, {value, at_time});
  }

  if (_curves.empty()) {
    _curves.emplace_back(curve);
  }
  else {
    _curves.insert(_curves.begin() + i + 1, curve);
  }

  return *this;
}

template <typename T>
template <typename ... Keys>
Channel<T>& Channel<T>::insertKey(T value, Time at_time, Curve curve, Keys&&... keys)
{
    insertKey(value, at_time, curve);
    insertKey(std::forward<Keys>(keys)...);
    return *this;
}

template <typename T>
template <typename ... Keys>
Channel<T>& Channel<T>::insertKey(T value, Seconds at_time, Curve curve, Keys&&... keys)
{
    insertKey(value, at_time, curve);
    insertKey(std::forward<Keys>(keys)...);
    return *this;
}

template <typename T>
typename Channel<T>::KeyManipulator Channel<T>::keyControl(size_t desired_index) {
  auto index = std::min(desired_index, _keys.size() - 1);
  auto &current = _keys[index];
  auto *previous = (index > 0) ? &_keys[index - 1] : nullptr;
  auto *next = (index < _keys.size() - 1) ? &_keys[index + 1] : nullptr;
  auto *c1 = (index > 0) ? &_curves[index - 1] : nullptr;
  auto *c2 = (index < _curves.size()) ? &_curves[index] : nullptr;
  return KeyManipulator(current, previous, next, c1, c2);
}

template <typename T>
const typename Channel<T>::KeyInfo Channel<T>::keyInfo(size_t desired_index) const
{
  auto index = std::min(desired_index, _keys.size() - 1);
  auto &current = const_cast<Key&>(_keys[index]);
  auto *previous = (index > 0) ? &const_cast<Key&>(_keys[index - 1]) : nullptr;
  auto *next = (index < _keys.size() - 1) ? &const_cast<Key&>(_keys[index + 1]) : nullptr;
  auto *c1 = (index > 0) ? &const_cast<Curve&>(_curves[index - 1]) : nullptr;
  auto *c2 = (index < _curves.size()) ? &const_cast<Curve&>(_curves[index]) : nullptr;
  return KeyInfo(current, previous, next, c1, c2);
}

} // namepsace choreograph


text:
'use strict';

import Event from 'vs/base/common/event';
import {IDisposable} from 'vs/base/common/lifecycle';
import {TPromise} from 'vs/base/common/winjs.base';
import {ServiceIdentifier, createDecorator} from 'vs/platform/instantiation/common/instantiation';
import * as modes from 'vs/editor/common/modes';
import {ILanguage} from 'vs/editor/common/modes/monarch/monarchTypes';
import {IRichLanguageConfiguration} from 'vs/editor/common/modes/supports/richEditSupport';
import {IEditorWorkerService} from 'vs/editor/common/services/editorWorkerService';
import {IModelService} from 'vs/editor/common/services/modelService';

export var IModeService = createDecorator<IModeService>('modeService');

export interface IModeLookupResult {
	modeId: string;
	isInstantiated: boolean;
}

export interface ILanguageExtensionPoint {
	id: string;
	extensions?: string[];
	filenames?: string[];
	filenamePatterns?: string[];
	firstLine?: string;
	aliases?: string[];
	mimetypes?: string[];
	configuration?: string;
}

export interface IValidLanguageExtensionPoint {
	id: string;
	extensions: string[];
	filenames: string[];
	filenamePatterns: string[];
	firstLine: string;
	aliases: string[];
	mimetypes: string[];
	configuration: string;
}

export interface IModeService {
	serviceId: ServiceIdentifier<any>;

	onDidAddModes: Event<string[]>;
	onDidCreateMode: Event<modes.IMode>;

	configureMode(modeName: string, options: any): void;
	configureModeById(modeId: string, options: any): void;
	configureAllModes(config:any): void;
	getConfigurationForMode(modeId:string): any;

	// --- reading
	isRegisteredMode(mimetypeOrModeId: string): boolean;
	isCompatMode(modeId: string): boolean;
	getRegisteredModes(): string[];
	getRegisteredLanguageNames(): string[];
	getExtensions(alias: string): string[];
	getMimeForMode(modeId: string): string;
	getLanguageName(modeId:string): string;
	getModeIdForLanguageName(alias:string): string;
	getModeId(commaSeparatedMimetypesOrCommaSeparatedIds: string): string;
	getConfigurationFiles(modeId: string): string[];

	// --- instantiation
	lookup(commaSeparatedMimetypesOrCommaSeparatedIds: string): IModeLookupResult[];
	getMode(commaSeparatedMimetypesOrCommaSeparatedIds: string): modes.IMode;
	getOrCreateMode(commaSeparatedMimetypesOrCommaSeparatedIds: string): TPromise<modes.IMode>;
	getOrCreateModeByLanguageName(languageName: string): TPromise<modes.IMode>;
	getOrCreateModeByFilenameOrFirstLine(filename: string, firstLine?:string): TPromise<modes.IMode>;

	registerRichEditSupport(modeId: string, support: IRichLanguageConfiguration): IDisposable;
	registerTokenizationSupport(modeId: string, callback: (mode: modes.IMode) => modes.ITokenizationSupport): IDisposable;
	registerTokenizationSupport2(modeId: string, support: modes.TokensProvider): IDisposable;
	registerMonarchDefinition(modelService: IModelService, editorWorkerService: IEditorWorkerService, modeId:string, language:ILanguage): IDisposable;
}


text:
const Sequelize = require('sequelize')

function AniONDB(dbconfig) {
  this.seq = new Sequelize(dbconfig.url, {
    omitNull: true, // http://stackoverflow.com/a/14333057
    dialectOptions: {
      ssl: !!dbconfig.ssl, // http://stackoverflow.com/a/27688357
    },
  })
  this.seq.authenticate().catch(err => {
    console.error('Error on connection db: %s', err)
  })
  this.Ani = this.seq.define(
    'Ani',
    {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
      },
      index: {
        type: Sequelize.INTEGER,
        allowNull: true,
      },
      weekday: {
        type: Sequelize.INTEGER,
        allowNull: true, // for ended ani
      },
      title: {
        type: Sequelize.STRING,
        allowNull: false,
      },
      time: {
        type: Sequelize.STRING(4),
        defaultValue: '0000',
      },
      ended: {
        type: Sequelize.BOOLEAN,
        defaultValue: false,
      },
      homepage: Sequelize.STRING,
      genre: Sequelize.STRING,
      broaded: Sequelize.BOOLEAN,
      startdate: {
        type: Sequelize.STRING(8),
        defaultValue: '00000000',
      },
      enddate: {
        type: Sequelize.STRING(8),
        defaultValue: '00000000',
      },
    },
    {
      freezeTableName: true,
      tableName: 'ani',
      createdAt: false,
      updatedAt: false,
    }
  )

  this.Genre = this.seq.define(
    'Genre',
    {
      id: {
        type: Sequelize.INTEGER,
        primaryKey: true,
        autoIncrement: true,
      },
      ani_id: {
        type: Sequelize.INTEGER,
        allowNull: false,
      },
      genre: {
        type: Sequelize.STRING(30),
        allowNull: false,
      },
    },
    {
      freezeTableName: true,
      tableName: 'ani_genres',
      createdAt: false,
      updatedAt: false,
    }
  )
}

AniONDB.Sequelize = Sequelize

module.exports = AniONDB


text:
from gettext import gettext

#------------------------------------------------------------------------------
def _(message, *args, **kw):
  if args or kw:
    return gettext(message).format(*args, **kw)
  return gettext(message)

#------------------------------------------------------------------------------
# end of $Id$
#------------------------------------------------------------------------------


text:
#include "detect_board.hpp"

#include <iostream>
#include <string>
#include <math.h>
#include <algorithm>
#include <numeric>

namespace Go_Scanner {

    const char* thresh_window = "Thresh";
    const char* morph_window = "Morph";
    bool asked_for_board_contour = false;

    using namespace cv;
    using namespace std;

    //point coordinates
    int boardCornerX[]={80, 443, 460, 157};
    int boardCornerY[]={80, 87, 430, 325};
    Mat img0, selectedImg, temp;
    string windowName = "Manual Selection Window";

    int board_selection_cancel_key = 27;

    // split a string at each char that is contained in delimiters and return the tokens
    vector<string> split(const string& str, const string& delimiters)
    {
        // Skip delimiters at beginning.
        string::size_type lastPos = str.find_first_not_of(delimiters, 0);
        // Find first "non-delimiter".
        string::size_type pos     = str.find_first_of(delimiters, lastPos);

        vector<string> tokens;
        while (string::npos != pos || string::npos != lastPos)
        {
            // Found a token, add it to the vector.
            tokens.push_back(str.substr(lastPos, pos - lastPos));
            // Skip delimiters.  Note the "not_of"
            lastPos = str.find_first_not_of(delimiters, pos);
            // Find next "non-delimiter"
            pos = str.find_first_of(delimiters, lastPos);
        }

        return tokens;
    }

    // renders a text in img with text at position
    // automatically handels newlines
    void putText(Mat img, string text, Point position) {
        // text appearence
        int fontFace     = 1;
        double fontScale = 1.2;
        int thickness    = 1;
        int baseline     = 0;
        int offset_x = 1, offset_y = 3;

        // text size of one line
        Size textSize = getTextSize(text, fontFace, fontScale, thickness, &baseline);
        baseline += thickness;

        auto total_height = textSize.height + baseline + 1;

        auto lines = split(text, "\n");

        // recurse if we got more than one line
        // and put each line directly under the preceding
        if (lines.size() > 1) {
            int i = 0;
            for (const auto& line : lines) {
                putText(img, line, position + Point(0, i*total_height));
                ++i;
            }
            return;
        }

        // buffer for the transparent box under the text (achieved through blending the images)
        Mat box_buf = img.clone();

        // draw the solid box
        rectangle(box_buf, position + Point(0, baseline),
            position + Point(textSize.width, -textSize.height),
            Scalar(0, 0, 0),
            CV_FILLED);

        // blend the box to make it transparent
        auto alpha = .3f;
        addWeighted(box_buf, alpha, img, 1.0 - alpha, 0.0, img);

        // draw the baseline
        line(img, position + Point(0, thickness + offset_y),
            position + Point(textSize.width, thickness + offset_y),
            Scalar(0, 0, 255));

        // draw the actual text
        putText(img, text,
                    position + Point(offset_x, offset_y),            // position
                    fontFace,            // font face
                    fontScale,           // font scale
                    Scalar(64, 64, 255), // color
                    thickness,           // thickness
                    CV_AA);              // line type
    }

     /**
     * @brief   Calls the manual board detection and shows the result in a new window.
     */
    void ask_for_board_contour() {
        namedWindow(windowName, CV_WINDOW_AUTOSIZE);
        setMouseCallback(windowName, mouseHandler, NULL);
        putText(img0,
            "Mark the Go board with the blue rectangle\n"
            "Press ESC to cancel or any other key to accept.",
            cvPoint(10, 20));

        showImage();
        auto key = waitKey(0);
        destroyWindow(windowName);

        // only accept board selection if the ESCAPE key was NOT pressed!
        if (key != board_selection_cancel_key)
            asked_for_board_contour = true;
    }

    /**
     * @brief   Calls the automatic board detection and shows the result in a new window.
     *          Prints an error to the console if the automatic detection couldn't find anything.
     */
    void do_auto_board_detection() {
        Point2f p0, p1, p2, p3;
        automatic_warp(img0, p0, p1, p2, p3);

        // automatic_warp failed and board wasn't found
        // if one of the points wasn't set
        if (p0 == Point2f()) {
            cout << "!!ERROR >> Failed to automatically detect the go board!" << endl;
            ask_for_board_contour();
            return;
        }

        // HACK: adjust the coordinates a bit to snap them closer to the board grid
        const auto gap = .5f;
        p0 += Point2f(gap, gap);
        p1 += Point2f(-gap, gap);
        p2 += Point2f(-gap, -gap);
        p3 += Point2f(gap, -gap);

        // create data suitable for showImage()
        int board_corners_X[] = { (int)p0.x, (int)p1.x, (int)p2.x, (int)p3.x };
        int board_corners_Y[] = { (int)p0.y, (int)p1.y, (int)p2.y, (int)p3.y };

        namedWindow(windowName, CV_WINDOW_AUTOSIZE);
        putText(img0,
            "Result of automatically detecting the Go board.\n"
            "Press ESC to cancel or any other key to accept.",
            cvPoint(10, 20));

        showImage(board_corners_X, board_corners_Y);
        auto key = waitKey(0);
        destroyWindow(windowName);

        // only accept board selection if the ESCAPE key was NOT pressed!
        if (key != board_selection_cancel_key) {
            asked_for_board_contour = true;

            // actually commmit the selection to the internal used variables
            boardCornerX[0] = cvRound(p0.x);
            boardCornerX[1] = cvRound(p1.x);
            boardCornerX[2] = cvRound(p2.x);
            boardCornerX[3] = cvRound(p3.x);

            boardCornerY[0] = cvRound(p0.y);
            boardCornerY[1] = cvRound(p1.y);
            boardCornerY[2] = cvRound(p2.y);
            boardCornerY[3] = cvRound(p3.y);
        }
    }

    Mat warpImage(Mat img, Point2f p0, Point2f p1, Point2f p2, Point2f p3)
    {
        /*
        Rectangle Order:
        0-------1
        |        |
        |        |
        2-------3
        */
        Point2f selCorners[4];
        selCorners[0] = p0;
        selCorners[1] = p1;
        selCorners[2] = p2;
        selCorners[3] = p3;

        Point2f dstCorners[4];
        dstCorners[0] = Point2f(0.0, 0.0);
        dstCorners[1] = Point2f((float)img.cols, 0.0);
        dstCorners[2] = Point2f(0.0, (float)img.rows);
        dstCorners[3] = Point2f((float)img.cols, (float)img.rows);

        Mat transformationMatrix;
        transformationMatrix = getPerspectiveTransform(selCorners, dstCorners);

        Mat warpedImg;
        warpPerspective(img, warpedImg, transformationMatrix, warpedImg.size(), 1, 0 ,0);

        return warpedImg;
    }

    RNG rng(12345);

    // Tries to automatically detect the corner points of the go board
    // This function simply returns without modifying p0, .., p3 if the board couldn't be found
    void automatic_warp(const Mat& input, Point2f& p0, Point2f& p1, Point2f& p2, Point2f& p3)
    {
        // CONVERT TO HSV
        Mat imgHSV;
        cvtColor( input, imgHSV, CV_BGR2HSV );

        // SPLITTING CHANNELS
        vector<Mat> v_channel;
        split(imgHSV, v_channel);          //split into three channels

        // SELECT CHANNEL FOR FURTHER PROCEEDING: SATURATION
        auto& source_channel = v_channel[1];

        // SMOOTHING IMAGE
        medianBlur(source_channel, source_channel, 3);

        // BINARY THRESH THE IMAGE
        const auto threshold = cv::threshold(source_channel, source_channel, 0, 255, THRESH_BINARY | THRESH_OTSU);

        // FINDING CONTOURS
        Mat clone = source_channel.clone();
        vector<vector<Point> > contours;
        vector<Vec4i> hierarchy;
        findContours(clone, contours, hierarchy, RETR_LIST, CHAIN_APPROX_SIMPLE, Point(0, 0));

        // STOP IF THERE AREN'T ANY CONTOURS
        if (contours.size() == 0)
            return;

        // APPROX. CONTOURS TO RECTANGLES
        const auto factor = .065f; // found through testing!
        for (auto& contour : contours) {
            // approximating each contour to get a rectangle with 4 points!
            approxPolyDP(Mat(contour), contour, arcLength(Mat(contour), true)*factor, true);
        }

        // CALCULATING BBOXES
        vector<Rect> bboxes;
        for (const auto& contour : contours)
            bboxes.push_back(boundingRect(contour));

        // CALCULATING MEAN BBOX AREA
        int bbox_area_sum = accumulate(begin(bboxes), end(bboxes), 0, [](int base, const Rect& r) { return base + r.area(); });
        int mean_area = bbox_area_sum/contours.size();

        // DELETING IMPROPER CONTOURS/BBOXES
        // that are smaller than the mean area
        // or almost as big as the whole image
        // or don't have exactly 4 corner points after approximation ( == rectangle)
        assert(bboxes.size() == contours.size());

        // for discarding contours that contain the complete image
        const float edge_factor = .99f;
        const float max_width   = input.cols * edge_factor;
        const float max_height  = input.rows * edge_factor;

        // DEBUG: DRAWING ALL LEFTOVER CONTOURS
        Mat drawing = input.clone();
        for (size_t i = 0; i < contours.size(); ++i) {
            Scalar color = Scalar( rng.uniform(0, 255), rng.uniform(0,255), rng.uniform(0,255));
            drawContours(drawing, contours, (int)i, color, 2, 8, hierarchy, 0, Point());
        }

        // DEBUG: DRAWING BBOXES FOR ALL CONTOURS
        for(auto& rect : bboxes) {
            rectangle(drawing, rect.tl(), rect.br(), Scalar(255, 255, 255), 2, 8);
        }

        auto cont_it = begin(contours);
        auto bbox_it = begin(bboxes);
        while (cont_it != end(contours) && bbox_it != end(bboxes)) {
            auto& contour = *cont_it;
            auto& bbox = *bbox_it;
            const auto ar = bbox.area();

            // delete bboxes and its corresponding contour if the bbox is almost as large as the window
            if (bbox.width >= max_width && bbox.height >= max_height) {
                cont_it = contours.erase(cont_it);
                bbox_it = bboxes.erase(bbox_it);
            }
            // or if the bbox area is smaller than the mean area
            else if (bbox.area() <= mean_area) {
                cont_it = contours.erase(cont_it);
                bbox_it = bboxes.erase(bbox_it);
            }
            else if (contour.size() != 4) {
                cont_it = contours.erase(cont_it);
                bbox_it = bboxes.erase(bbox_it);
            }
            else {
                ++cont_it;
                ++bbox_it;
            }
        }

        // STOP IF WE DON'T HAVE ANY CONTOURS LEFT -> NO BOARD FOUND
        if (contours.size() == 0)
            return;

        // SELECTING SUITABLE CONTOUR
        // sort contours and bboxes by area
        // that means we're selecting biggest contour for further processing
        if (contours.size() > 1) {
            sort(begin(contours), end(contours),
                [](const vector<Point>& cont1, const vector<Point>& cont2) { return contourArea(cont1) > contourArea(cont2); }
            );
            sort(begin(bboxes), end(bboxes),
                [](const Rect& r1, const Rect& r2) { return r1.area() > r2.area(); }
            );
        }

        auto board_contour = contours.front();
        auto board_bbox    = bboxes.front();

        // GETTING CORNER POINTS OF CONTOUR

        // stop if the contour has left only 4 points after approximating
        if (board_contour.size() != 4)
            return;

        // Rectangle Order for warping:
        // 0--------1
        // |        |
        // |        |
        // 2--------3

        auto center = Point(board_bbox.x + board_bbox.width/2, board_bbox.y + board_bbox.height/2);

        // splitting points in upper and lower half
        vector<Point> uppers, lowers;
        for (auto& point : board_contour) {
            if (point.y < center.y)
                uppers.emplace_back(point);
            else
                lowers.emplace_back(point);
        }

        // stop if we couldn't classify two uppers and lowers
        if (uppers.size() != 2 || lowers.size() != 2)
            return;

        // deciding which point is left/right
        // upper side
        p0 = uppers[0];
        p1 = uppers[1];
        if (p0.x > p1.x)
            swap(p0, p1);

        // lower side
        p2 = lowers[0];
        p3 = lowers[1];
        if (p2.x < p3.x)
            swap(p2, p3);
    }

//Manual detection

    /*

    Rectangle Order:
    0-------1
    |        |
    |        |
    3-------2

    */

    int point=-1;            //currently selected point
    int nop=4;               //number of points

    void mouseHandler(int event, int x, int y, int flags, void *param)
    {

        switch(event)
        {
        case CV_EVENT_LBUTTONDOWN:
            selectedImg = holdImg(x, y);
            break;

        case CV_EVENT_LBUTTONUP:
            if((selectedImg.empty()!= true)&& point!=-1)
            {
                releaseImg(selectedImg,x,y);
                selectedImg=Mat();
            }
            break;

        //Draws the lines while navigating with the mouse
        case CV_EVENT_MOUSEMOVE:
            /* draw a rectangle*/
            if(point!=-1)
            {
                if(selectedImg.empty()!= true)
                {
                    temp = selectedImg.clone();
                    rectangle(temp,
                        Point(x - 10, y - 10),
                        Point(x + 10, y + 10),
                        //BGR not RGB!!
                        Scalar(0, 255, 0, 0), 2, 8, 0);

                    //adjust the lines
                    for(int i=0;i<nop;i++)
                    {
                        if(i!=point)
                        {
                            line(temp,
                                Point(x, y),
                                Point(boardCornerX[i] , boardCornerY[i] ),
                                Scalar(0, 255, 0 ,0), 1,8,0);
                        }
                    }
                    imshow(windowName, temp);
                }
                break;
            }
            temp = Mat();
        }
    }

    //draws the lines and points while holding left mouse button down
    Mat holdImg(int x, int y)
    {
        Mat img = img0;

        int radius = 4;
        //find what point is selected
        for(int i=0;i<nop;i++){
            if((x>=(boardCornerX[i]-radius)) && (x<=(boardCornerX[i]+radius ))&& (y<=(boardCornerY[i]+radius ))&& (y<=(boardCornerY[i]+radius ))){
                point=i;
                break;
            }

        }
        //draw points
        for(int j=0;j<nop;j++)
        {
            //if this is not the selected point
            if(j!=point)
            {
                img = img.clone();
                rectangle(img,
                    Point(boardCornerX[j] - 1, boardCornerY[j] - 1),
                    Point(boardCornerX[j] + 1, boardCornerY[j] + 1),
                    Scalar(255, 0,  0, 0), 2, 8, 0);
            }
        }

        //draw lines
        for(int i=0;i<nop;i++)
        {
            if(i!=point)
            {
                for(int k=i+1;k<nop;k++)
                {
                    if(k!=point)
                    {
                        img = img.clone();
                        line(img,
                            Point(boardCornerX[i] , boardCornerY[i] ),
                            Point(boardCornerX[k] , boardCornerY[k] ),
                            Scalar(255, 0, 0, 0), 1,8,0);

                    }
                }
            }
        }
        return img;
    }

    //set new coordinates and redraw the scene if the left mouse button is released
    void releaseImg(Mat a, int x, int y)
    {
        boardCornerX[point]=x;
        boardCornerY[point]=y;
        showImage();
    }

    /**
     * @brief   Shows the points given through the two passed parameters on a clone of the img0 in a new window.
     *          Both pointers have to point to memory containing 4 variables
     */
    void showImage(int* board_corner_X, int* board_corner_Y)
    {
        Mat img1 = img0.clone();

        //draw the points
        for(int j=0;j<nop;j++)
        {
            rectangle(img1,
                Point(board_corner_X[j] - 1, board_corner_Y[j] - 1),
                Point(board_corner_X[j] + 1, board_corner_Y[j] + 1),
                Scalar(255, 0,  0, 0), 2, 8, 0);

            //draw the lines
            for(int k=j+1;k<nop;k++)
            {
                line(img1,
                    Point(board_corner_X[j] , board_corner_Y[j] ),
                    Point(board_corner_X[k] , board_corner_Y[k] ),
                    Scalar(255, 0,  0, 0), 1,8,0);
            }
        }
        imshow(windowName, img1);
    }

    /**
     * @brief   Shows the selected points (through manual or automatic board detection) on a clone of the img0 in a new window.
     */
    void showImage()
    {
        showImage(boardCornerX, boardCornerY);
    }

    bool getWarpedImg(Mat& warpedImg)
    {
        img0 = warpedImg.clone();

        // only process the image if the user  selected the board with "ask_for_board_contour" or "do_auto_board_detection" once.
        // this is triggered through the GUI (and the Scanners selectBoardManually() and selectBoardAutomatically() methods)
        if (!asked_for_board_contour) {
            return false;
        }

            warpedImg = warpImage(img0,
            Point2i(boardCornerX[0], boardCornerY[0]),
            Point2i(boardCornerX[1], boardCornerY[1]),
            Point2i(boardCornerX[3], boardCornerY[3]),
            Point2i(boardCornerX[2], boardCornerY[2]));

        return true;

    }
}


text:
resque-nofork
====

Just like resque-jobs-per-fork, but without forking at all. Perform the job in the worker, and exit after a fixed number of jobs.

Designed to work with [resque-pool](https://github.com/nevans/resque-pool) which will maintain the worker count from a master process.


text:
package com.google.gwt.debugpanel.models;

import junit.framework.TestCase;

/**
 * Tests the {@link GwtDebugStatisticsValue}.
 */
public class GwtDebugStatisticsValueTest extends TestCase {
  public void testRpcMethodTranslation() {
    GwtDebugStatisticsValue value = new GwtDebugStatisticsValue("label", "module", 0, 1);
    value.setRpcMethod("SomeService_Proxy.method");
    assertTrue(value.hasRpcMethod());
    assertEquals("SomeService.method", value.getRpcMethod());
  }

  public void testWithChildTime() {
    GwtDebugStatisticsValue value = new GwtDebugStatisticsValue("label", "module", 2, 4);
    assertTiming(value.withChildTime(1), 1, 4);
    assertTiming(value.withChildTime(2), 2, 4);
    assertTiming(value.withChildTime(3), 2, 4);
    assertTiming(value.withChildTime(4), 2, 4);
    assertTiming(value.withChildTime(5), 2, 5);
  }

  public void testWithEndTime() {
    GwtDebugStatisticsValue value = new GwtDebugStatisticsValue("label", "module", 2, 4);
    assertTiming(value.withEndTime(1), 2, 4);
    assertTiming(value.withEndTime(2), 2, 4);
    assertTiming(value.withEndTime(3), 2, 4);
    assertTiming(value.withEndTime(4), 2, 4);
    assertTiming(value.withEndTime(5), 2, 5);
  }

  private void assertTiming(GwtDebugStatisticsValue value, double start, double end) {
    assertEquals(start, value.getStartTime());
    assertEquals(end, value.getEndTime());
  }

  public void testResponse() {
    GwtDebugStatisticsValue value = new GwtDebugStatisticsValue("label", "module", 2, 4);
    assertFalse(value.hasResponse());
    value.setResponse("response");
    assertTrue(value.hasResponse());
    assertEquals("response", value.getResponse());
  }
}


text:
<ion-modal-view>
  <ion-content ng-controller="bitpayCardConfirmationController">

Are you sure you would like to log out of your DigiByte Foundation Card account?

You will need to log back for fill in your DigiByte Foundation Card.

          <button class="button button-block button-stable" ng-click="cancel()" translate>
            Cancel
          </button>

          <button class="button button-block button-assertive" ng-click="ok()">
            Log out
          </button>

  </ion-content>
</ion-modal-view>


text:
""" MsgTypesCMU module: defines the various message type codes as used
by the CMU ServerRepository/ClientRepository code in this directory.
It replaces the MsgTypes module, which is not used by the CMU
implementation. """

from direct.showbase.PythonUtil import invertDictLossless

MsgName2Id = {
    'SET_DOID_RANGE_CMU'                      : 9001,
    'CLIENT_OBJECT_GENERATE_CMU'              : 9002,
    'OBJECT_GENERATE_CMU'                     : 9003,
    'OBJECT_UPDATE_FIELD_CMU'                 : 9004,
    'OBJECT_DISABLE_CMU'                      : 9005,
    'OBJECT_DELETE_CMU'                       : 9006,
    'REQUEST_GENERATES_CMU'                   : 9007,
    'CLIENT_DISCONNECT_CMU'                   : 9008,
    'CLIENT_SET_INTEREST_CMU'                 : 9009,
    'OBJECT_SET_ZONE_CMU'                     : 9010,
    'CLIENT_HEARTBEAT_CMU'                    : 9011,
    'CLIENT_OBJECT_UPDATE_FIELD_TARGETED_CMU'  : 9011,

    'CLIENT_OBJECT_UPDATE_FIELD' : 24,  # Matches MsgTypes.CLIENT_OBJECT_UPDATE_FIELD
    }

# create id->name table for debugging
MsgId2Names = invertDictLossless(MsgName2Id)

# put msg names in module scope, assigned to msg value
globals().update(MsgName2Id)


text:
angular.module('NutrifApp').controller('cadastrarRefeicaoCtrl', function ($scope, $mdToast, $state, refeicaoService) {

    // Enviar para o serviço de cadastro de refeição.
    this.cadastrar = function (refeicao) {

        refeicao.horaInicio = Date.parse(refeicao.horaInicio);
        refeicao.horaFinal = Date.parse(refeicao.horaFinal);
        refeicao.horaPrevisaoPretensao = Date.parse(refeicao.horaPrevisaoPretensao);

        refeicaoService.cadastrarRefeicao(refeicao)
            .success(onSuccessCallback)
            .error(onErrorCallback);
    }

    function onSuccessCallback(data, status) {
        // Mensagem
        $mdToast.show(
            $mdToast.simple()
            .textContent('Refeição cadastrada com sucesso!')
            .position('top right')
            .action('OK')
            .hideDelay(6000)
        );

        // Redirecionamento
        $state.transitionTo('home.listar-refeicoes');
    }

    function onErrorCallback(data, status) {
        var _message = '';

        if (!data) {
            _message = 'Ocorreu um erro na comunicação com o servidor, favor chamar o suporte.'
        } else {
            _message = data.mensagem
        }

        // Mensagem
        $mdToast.show(
            $mdToast.simple()
            .textContent(_message)
            .position('top right')
            .action('OK')
            .hideDelay(6000)
        );
    }
});


text:
$LOAD_PATH.unshift File.expand_path("../../lib", __FILE__)
require "rack/multiplexer"

RSpec.configure do |config|
  config.treat_symbols_as_metadata_keys_with_true_values = true
  config.run_all_when_everything_filtered = true
  config.filter_run :focus
end


text:
class Metric(object):
    """
    Metric object contains:
        - the metric sub prefix,
        - metrics mapping (response JSON key to metric name and metric type)
        - tags mapping (response JSON key to tag name)
        - field_to_name (response JSON key to metric name)
    """

    def __init__(self, prefix, metrics, tags=None, field_to_name=None):
        self.prefix = prefix
        for key, name_method in metrics.items():
            if isinstance(name_method, tuple):
                continue
            else:
                metrics[key] = (name_method, 'gauge')

        self.metrics = metrics
        self.tags = tags if tags else {}
        self.field_to_name = field_to_name if field_to_name else {}

METRICS = {
    'hosts': Metric(prefix='system', metrics={'views_count': 'views_count', 'volumes_count': 'volumes_count'}),
    'volumes': Metric(
        prefix='volume',
        metrics={
            'avg_compressed_ratio': 'compressed_ratio.avg',
            'logical_capacity': 'logical_capacity',
            'no_dedup': 'no_dedup',
            'size': 'size',
            'snapshots_logical_capacity': 'snapshots_logical_capacity',
            'stream_avg_compressed_size_in_bytes': 'stream_average_compressed_bytes',
        },
        tags={
            'name': 'volume_raw_name',
            'node_id': 'node_id',
        },
    ),
    'stats/system': Metric(
        prefix='system',
        metrics={
            'iops_avg': 'io_ops.avg',
            'iops_max': 'io_ops.max',
            'latency_inner': 'latency.inner',
            'latency_outer': 'latency.outer',
            'throughput_avg': 'throughput.avg',
            'throughput_max': 'throughput.max',
        },
        tags={
            'resolution': 'resolution',
        },
    ),
    'stats/volumes': Metric(
        prefix='volume',
        metrics={
            'iops_avg': ('io_ops.avg', 'gauge'),
            'iops_max': 'io_ops.max',
            'latency_inner': 'latency.inner',
            'latency_outer': 'latency.outer',
            'throughput_avg': 'throughput.avg',
            'throughput_max': 'throughput.max',
        },
        tags={
            'peer_k2_name': 'peer_name',
            'volume_name': 'volume_name',
            'resolution': 'resolution',
        },
    ),
    'system/capacity': Metric(
        prefix='system.capacity',
        metrics={
            'allocated': 'allocated',
            'allocated_snapshots_and_views': 'allocated_snapshots_and_views',
            'allocated_volumes': 'allocated_volumes',
            'curr_dt_chunk': 'curr_dt_chunk',
            'free': 'free',
            'logical': 'logical',
            'physical': 'physical',
            'provisioned': 'provisioned',
            'provisioned_snapshots': 'provisioned_snapshots',
            'provisioned_views': 'provisioned_views',
            'provisioned_volumes': 'provisioned_volumes',
            'reserved': 'reserved',
            'total': 'total',
        },
        tags={
            'state': 'capacity_state',
        },
    ),
    'replication/stats/system': Metric(
        prefix='replication.system',
        metrics={
            "logical_in": "logical_in",
            "logical_out": "logical_out",
            "physical_in": "physical_in",
            "physical_out": "physical_out",
        },
        tags={
            'resolution': 'resolution',
        },
    ),
    'replication/stats/volumes': Metric(
        prefix='replication.volume',
        metrics={
            "logical_in": "logical_in",
            "logical_out": "logical_out",
            "physical_in": "physical_in",
            "physical_out": "physical_out",
        },
        tags={
            'peer_k2_name': 'peer_name',
            'volume_name': 'volume_name',
            'resolution': 'resolution',
        },
    ),
}

BLOCKSIZE_METRICS = {
    'stats/system?__bs_breakdown=True': Metric(
        prefix='system.block_size',
        metrics={
            'iops_avg': 'io_ops.avg',
            'latency_inner': 'latency.inner',
            'latency_outer': 'latency.outer',
            'throughput_avg': 'throughput.avg',
        },
        tags={
            'resolution': 'resolution',
            'bs': 'block_size',
        },
    ),
    'stats/volumes?__bs_breakdown=True': Metric(
        prefix='volume.block_size',
        metrics={
            'iops_avg': ('io_ops.avg', 'gauge'),
            'latency_inner': 'latency.inner',
            'latency_outer': 'latency.outer',
            'throughput_avg': 'throughput.avg',
        },
        tags={
            'peer_k2_name': 'peer_name',
            'volume_name': 'volume_name',
            'resolution': 'resolution',
            'bs': 'block_size',
        },
    ),
}

READ_WRITE_METRICS = {
    'stats/volumes?__rw_breakdown=True': Metric(
        prefix='volume',
        metrics={
            'iops_avg': ('io_ops.avg', 'gauge'),
            'latency_inner': 'latency.inner',
            'latency_outer': 'latency.outer',
            'throughput_avg': 'throughput.avg',
        },
        tags={
            'peer_k2_name': 'peer_name',
            'volume_name': 'volume_name',
            'resolution': 'resolution',
        },
        field_to_name={
            'rw': {
                'r': 'read',
                'w': 'write',
            }
        },
    ),
    'stats/system?__rw_breakdown=True': Metric(
        prefix='system',
        metrics={
            'iops_avg': 'io_ops.avg',
            'latency_inner': 'latency.inner',
            'latency_outer': 'latency.outer',
            'throughput_avg': 'throughput.avg',
        },
        tags={
            'resolution': 'resolution',
        },
        field_to_name={
            'rw': {
                'r': 'read',
                'w': 'write',
            }
        },
    ),
}


text:
package org.ovirt.engine.core.bll.validator;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.bll.ImagesHandler;
import org.ovirt.engine.core.bll.ValidationResult;
import org.ovirt.engine.core.bll.interfaces.BackendInternal;
import org.ovirt.engine.core.bll.scheduling.SchedulingManager;
import org.ovirt.engine.core.bll.snapshots.SnapshotsValidator;
import org.ovirt.engine.core.bll.validator.storage.DiskImagesValidator;
import org.ovirt.engine.core.bll.validator.storage.MultipleStorageDomainsValidator;
import org.ovirt.engine.core.bll.validator.storage.StoragePoolValidator;
import org.ovirt.engine.core.common.FeatureSupported;
import org.ovirt.engine.core.common.VdcActionUtils;
import org.ovirt.engine.core.common.action.RunVmParams;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.businessentities.ArchitectureType;
import org.ovirt.engine.core.common.businessentities.BootSequence;
import org.ovirt.engine.core.common.businessentities.Entities;
import org.ovirt.engine.core.common.businessentities.GraphicsType;
import org.ovirt.engine.core.common.businessentities.StoragePool;
import org.ovirt.engine.core.common.businessentities.VDSGroup;
import org.ovirt.engine.core.common.businessentities.VDSStatus;
import org.ovirt.engine.core.common.businessentities.VM;
import org.ovirt.engine.core.common.businessentities.VMStatus;
import org.ovirt.engine.core.common.businessentities.VdsDynamic;
import org.ovirt.engine.core.common.businessentities.VmDevice;
import org.ovirt.engine.core.common.businessentities.VmDeviceGeneralType;
import org.ovirt.engine.core.common.businessentities.network.Network;
import org.ovirt.engine.core.common.businessentities.network.VmNetworkInterface;
import org.ovirt.engine.core.common.businessentities.storage.Disk;
import org.ovirt.engine.core.common.businessentities.storage.DiskImage;
import org.ovirt.engine.core.common.businessentities.storage.ImageFileType;
import org.ovirt.engine.core.common.businessentities.storage.RepoImage;
import org.ovirt.engine.core.common.businessentities.storage.VolumeType;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.errors.EngineMessage;
import org.ovirt.engine.core.common.osinfo.OsRepository;
import org.ovirt.engine.core.common.queries.GetImagesListParameters;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.common.utils.SimpleDependecyInjector;
import org.ovirt.engine.core.common.utils.customprop.VmPropertiesUtils;
import org.ovirt.engine.core.common.vdscommands.IsVmDuringInitiatingVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSCommandType;
import org.ovirt.engine.core.compat.Guid;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.dao.DiskDao;
import org.ovirt.engine.core.dao.StorageDomainDao;
import org.ovirt.engine.core.dao.VdsDynamicDao;
import org.ovirt.engine.core.dao.network.NetworkDao;
import org.ovirt.engine.core.dao.network.VmNicDao;
import org.ovirt.engine.core.di.Injector;
import org.ovirt.engine.core.utils.NetworkUtils;

public class RunVmValidator {

    private VM vm;
    private RunVmParams runVmParam;
    private boolean isInternalExecution;
    private Guid activeIsoDomainId;
    private OsRepository osRepository;

    private List<Disk> cachedVmDisks;
    private List<DiskImage> cachedVmImageDisks;
    private Set<String> cachedInterfaceNetworkNames;
    private List<Network> cachedClusterNetworks;
    private Set<String> cachedClusterNetworksNames;

    public RunVmValidator(VM vm, RunVmParams rumVmParam, boolean isInternalExecution, Guid activeIsoDomainId) {
        this.vm = vm;
        this.runVmParam = rumVmParam;
        this.isInternalExecution = isInternalExecution;
        this.activeIsoDomainId = activeIsoDomainId;
        this.osRepository = SimpleDependecyInjector.getInstance().get(OsRepository.class);
    }

    /**
     * Used for testings
     */
    protected RunVmValidator() {
    }

    /**
     * A general method for run vm validations. used in runVmCommand and in VmPoolCommandBase
     *
     * @param messages
     * @param storagePool
     * @param vdsBlackList
     *            - hosts that we already tried to run on
     * @param vdsWhiteList
     *            - initial host list, mainly runOnSpecificHost (runOnce/migrateToHost)
     * @param destVdsList
     * @param vdsGroup
     * @return
     */
    public boolean canRunVm(List<String> messages, StoragePool storagePool, List<Guid> vdsBlackList,
            List<Guid> vdsWhiteList, List<Guid> destVdsList, VDSGroup vdsGroup) {

        if (vm.getStatus() == VMStatus.Paused) {
            // if the VM is paused, we should only check the VDS status
            // as the rest of the checks were already checked before
            return validate(validateVdsStatus(vm), messages);
        } else if (vm.getStatus() == VMStatus.Suspended) {
            return validate(new VmValidator(vm).vmNotLocked(), messages) &&
                   validate(getSnapshotValidator().vmNotDuringSnapshot(vm.getId()), messages) &&
                   validate(validateVmStatusUsingMatrix(vm), messages) &&
                   validate(validateStoragePoolUp(vm, storagePool, getVmImageDisks()), messages) &&
                   validate(vmDuringInitialization(vm), messages) &&
                    validate(validateStorageDomains(vm,
                            isInternalExecution,
                            filterReadOnlyAndPreallocatedDisks(getVmImageDisks())), messages)
                    &&
                   validate(validateImagesForRunVm(vm, getVmImageDisks()), messages) &&
                   getSchedulingManager().canSchedule(
                           vdsGroup, vm, vdsBlackList, vdsWhiteList, destVdsList, messages);
        }

        return
                validateVmProperties(vm, runVmParam.getCustomProperties(), messages) &&
                validate(validateBootSequence(vm, runVmParam.getBootSequence(), getVmDisks(), activeIsoDomainId), messages) &&
                validate(validateDisplayType(), messages) &&
                validate(new VmValidator(vm).vmNotLocked(), messages) &&
                validate(getSnapshotValidator().vmNotDuringSnapshot(vm.getId()), messages) &&
                validate(validateVmStatusUsingMatrix(vm), messages) &&
                validate(validateStoragePoolUp(vm, storagePool, getVmImageDisks()), messages) &&
                validate(validateIsoPath(vm, runVmParam.getDiskPath(), runVmParam.getFloppyPath(), activeIsoDomainId), messages)  &&
                validate(vmDuringInitialization(vm), messages) &&
                validate(validateStatelessVm(vm, runVmParam.getRunAsStateless()), messages) &&
                validate(validateFloppy(), messages) &&
                validate(validateStorageDomains(vm,
                        isInternalExecution,
                        filterReadOnlyAndPreallocatedDisks(getVmImageDisks())), messages)
                &&
                validate(validateImagesForRunVm(vm, getVmImageDisks()), messages) &&
                validate(validateMemorySize(vm), messages) &&
                getSchedulingManager().canSchedule(
                        vdsGroup, vm, vdsBlackList, vdsWhiteList, destVdsList, messages);
    }

    private List<DiskImage> filterReadOnlyAndPreallocatedDisks(List<DiskImage> vmImageDisks) {
        List<DiskImage> retVal = new ArrayList<>();
        for (DiskImage disk : vmImageDisks) {
            if (!(disk.getVolumeType() == VolumeType.Preallocated || disk.getReadOnly())) {
                retVal.add(disk);
            }
        }
        return retVal;
    }

    private SchedulingManager getSchedulingManager() {
        return Injector.get(SchedulingManager.class);
    }

    protected ValidationResult validateMemorySize(VM vm) {
        int maxSize;
        if (getOsRepository().get64bitOss().contains(vm.getOs())) {
            ConfigValues config = vm.getClusterArch() == ArchitectureType.ppc64 ?
                    ConfigValues.VMPpc64BitMaxMemorySizeInMB :
                    ConfigValues.VM64BitMaxMemorySizeInMB;
            maxSize = Config.getValue(config, vm.getVdsGroupCompatibilityVersion().getValue());
        } else {
            maxSize = Config.getValue(ConfigValues.VM32BitMaxMemorySizeInMB);
        }

        if (vm.getMemSizeMb() > maxSize) {
            return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_MEMORY_EXCEEDS_SUPPORTED_LIMIT);
        }

        return ValidationResult.VALID;
    }

    public ValidationResult validateFloppy() {

        if (StringUtils.isNotEmpty(runVmParam.getFloppyPath()) && !VmValidationUtils.isFloppySupported(vm.getOs(),
                vm.getVdsGroupCompatibilityVersion())) {
            return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_FLOPPY_IS_NOT_SUPPORTED_BY_OS);
        }

        return ValidationResult.VALID;
    }

    /**
     * @return true if all VM network interfaces are valid
     */
    public ValidationResult validateNetworkInterfaces() {
        ValidationResult validationResult = validateInterfacesConfigured(vm);
        if (!validationResult.isValid()) {
            return validationResult;
        }

        validationResult = validateInterfacesAttachedToClusterNetworks(vm, getClusterNetworksNames(), getInterfaceNetworkNames());
        if (!validationResult.isValid()) {
            return validationResult;
        }

        validationResult = validateInterfacesAttachedToVmNetworks(getClusterNetworks(), getInterfaceNetworkNames());
        if (!validationResult.isValid()) {
            return validationResult;
        }

        return ValidationResult.VALID;
    }

    protected ValidationResult validateDisplayType() {
        if (!VmValidationUtils.isGraphicsAndDisplaySupported(vm.getOs(),
                vm.getVdsGroupCompatibilityVersion(),
                getVmActiveGraphics(),
                vm.getDefaultDisplayType())) {
            return new ValidationResult(
                    EngineMessage.ACTION_TYPE_FAILED_ILLEGAL_VM_DISPLAY_TYPE_IS_NOT_SUPPORTED_BY_OS);
        }

        return ValidationResult.VALID;
    }

    private Set<GraphicsType> getVmActiveGraphics() {
        if (vm.getGraphicsInfos() != null && !vm.getGraphicsInfos().isEmpty()) { // graphics overriden in runonce
            return vm.getGraphicsInfos().keySet();
        } else {
            List<VmDevice> graphicDevices =
                    DbFacade.getInstance().getVmDeviceDao().getVmDeviceByVmIdAndType(vm.getId(), VmDeviceGeneralType.GRAPHICS);

            Set<GraphicsType> graphicsTypes = new HashSet<>();

            for (VmDevice graphicDevice : graphicDevices) {
                GraphicsType type = GraphicsType.fromString(graphicDevice.getDevice());
                graphicsTypes.add(type);
            }

            return graphicsTypes;
        }
    }

    protected boolean validateVmProperties(VM vm, String runOnceCustomProperties, List<String> messages) {
        String customProperties = runOnceCustomProperties != null ?
                runOnceCustomProperties : vm.getCustomProperties();
        return getVmPropertiesUtils().validateVmProperties(
                        vm.getVdsGroupCompatibilityVersion(),
                        customProperties,
                        messages);
    }

    protected ValidationResult validateBootSequence(VM vm, BootSequence runOnceBootSequence,
            List<Disk> vmDisks, Guid activeIsoDomainId) {
        BootSequence bootSequence = runOnceBootSequence != null ?
                runOnceBootSequence : vm.getDefaultBootSequence();
        // Block from running a VM with no HDD when its first boot device is
        // HD and no other boot devices are configured
        if (bootSequence == BootSequence.C && vmDisks.isEmpty()) {
            return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_DISK_WITHOUT_DISK);
        }

        // If CD appears as first and there is no ISO in storage
        // pool/ISO inactive - you cannot run this VM
        if (bootSequence == BootSequence.CD && activeIsoDomainId == null) {
            return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_CD_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO);
        }

        // if there is network in the boot sequence, check that the
        // vm has network, otherwise the vm cannot be run in vdsm
        if (bootSequence == BootSequence.N
                && getVmNicDao().getAllForVm(vm.getId()).isEmpty()) {
            return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_NETWORK_WITHOUT_NETWORK);
        }

        return ValidationResult.VALID;
    }

    /**
     * Check storage domains. Storage domain status and disk space are checked only for non-HA VMs.
     *
     * @param vm
     *            The VM to run
     * @param isInternalExecution
     *            Command is internal?
     * @param vmImages
     *            The VM's image disks
     * @return true if the VM can be run, false if not
     */
    protected ValidationResult validateStorageDomains(VM vm, boolean isInternalExecution,
            List<DiskImage> vmImages) {
        if (vmImages.isEmpty()) {
            return ValidationResult.VALID;
        }

        if (!vm.isAutoStartup() || !isInternalExecution) {
            Set<Guid> storageDomainIds = ImagesHandler.getAllStorageIdsForImageIds(vmImages);
            MultipleStorageDomainsValidator storageDomainValidator =
                    new MultipleStorageDomainsValidator(vm.getStoragePoolId(), storageDomainIds);

            ValidationResult result = storageDomainValidator.allDomainsExistAndActive();
            if (!result.isValid()) {
                return result;
            }

            result = !vm.isAutoStartup() ? storageDomainValidator.allDomainsWithinThresholds()
                    : ValidationResult.VALID;
            if (!result.isValid()) {
                return result;
            }
        }

        return ValidationResult.VALID;
    }

    /**
     * Check isValid only if VM is not HA VM
     */
    protected ValidationResult validateImagesForRunVm(VM vm, List<DiskImage> vmDisks) {
        if (vmDisks.isEmpty()) {
            return ValidationResult.VALID;
        }

        return !vm.isAutoStartup() ?
                new DiskImagesValidator(vmDisks).diskImagesNotLocked() : ValidationResult.VALID;
    }

    protected ValidationResult validateIsoPath(VM vm, String diskPath, String floppyPath, Guid activeIsoDomainId) {
        if (vm.isAutoStartup()) {
            return ValidationResult.VALID;
        }

        if (StringUtils.isEmpty(vm.getIsoPath()) && StringUtils.isEmpty(diskPath) && StringUtils.isEmpty(floppyPath)) {
            return ValidationResult.VALID;
        }

        if (activeIsoDomainId == null) {
            return new ValidationResult(EngineMessage.VM_CANNOT_RUN_FROM_CD_WITHOUT_ACTIVE_STORAGE_DOMAIN_ISO);
        }

        if (!StringUtils.isEmpty(diskPath) && !isRepoImageExists(diskPath, activeIsoDomainId, ImageFileType.ISO)) {
            return new ValidationResult(EngineMessage.ERROR_CANNOT_FIND_ISO_IMAGE_PATH);
        }

        if (!StringUtils.isEmpty(floppyPath) && !isRepoImageExists(floppyPath, activeIsoDomainId, ImageFileType.Floppy)) {
            return new ValidationResult(EngineMessage.ERROR_CANNOT_FIND_FLOPPY_IMAGE_PATH);
        }

        return ValidationResult.VALID;
    }

    protected ValidationResult vmDuringInitialization(VM vm) {
        if (vm.isRunning() || vm.getStatus() == VMStatus.NotResponding ||
                isVmDuringInitiating(vm)) {
            return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_IS_RUNNING);
        }

        return ValidationResult.VALID;
    }

    protected ValidationResult validateVdsStatus(VM vm) {
        if (vm.getStatus() == VMStatus.Paused && vm.getRunOnVds() != null &&
                getVdsDynamic(vm.getRunOnVds()).getStatus() != VDSStatus.Up) {
            return new ValidationResult(
                    EngineMessage.ACTION_TYPE_FAILED_VDS_STATUS_ILLEGAL,
                    EngineMessage.VAR__HOST_STATUS__UP.toString());
        }

        return ValidationResult.VALID;
    }

    protected ValidationResult validateStatelessVm(VM vm, Boolean stateless) {
        // if the VM is not stateless, there is nothing to check
        if (stateless != null ? !stateless : !vm.isStateless()) {
            return ValidationResult.VALID;
        }

        ValidationResult previewValidation = getSnapshotValidator().vmNotInPreview(vm.getId());
        if (!previewValidation.isValid()) {
            return previewValidation;
        }

        // if the VM itself is stateless or run once as stateless
        if (vm.isAutoStartup()) {
            return new ValidationResult(EngineMessage.VM_CANNOT_RUN_STATELESS_HA);
        }

        ValidationResult hasSpaceValidation = hasSpaceForSnapshots();
        if (!hasSpaceValidation.isValid()) {
            return hasSpaceValidation;
        }

        return ValidationResult.VALID;
    }

    protected ValidationResult validateVmStatusUsingMatrix(VM vm) {
        if (!VdcActionUtils.canExecute(Arrays.asList(vm), VM.class,
                VdcActionType.RunVm)) {
            return new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_VM_STATUS_ILLEGAL, LocalizedVmStatus.from(vm.getStatus()));
        }

        return ValidationResult.VALID;
    }

    /**
     * check that we can create snapshots for all disks
     * return true if all storage domains have enough space to create snapshots for this VM plugged disks
     */
    protected ValidationResult hasSpaceForSnapshots() {
        List<Disk> disks = DbFacade.getInstance().getDiskDao().getAllForVm(vm.getId());
        List<DiskImage> allDisks = ImagesHandler.filterImageDisks(disks, false, true, false);

        Set<Guid> sdIds = ImagesHandler.getAllStorageIdsForImageIds(allDisks);

        MultipleStorageDomainsValidator msdValidator = getStorageDomainsValidator(sdIds);
        ValidationResult retVal = msdValidator.allDomainsWithinThresholds();
        if (retVal == ValidationResult.VALID) {
            return msdValidator.allDomainsHaveSpaceForNewDisks(allDisks);
        }
        return retVal;
    }

    protected MultipleStorageDomainsValidator getStorageDomainsValidator(Collection<Guid> sdIds) {
        Guid spId = vm.getStoragePoolId();
        return new MultipleStorageDomainsValidator(spId, sdIds);
    }

    protected ValidationResult validateStoragePoolUp(VM vm, StoragePool storagePool, List<DiskImage> vmImages) {
        if (vmImages.isEmpty() || vm.isAutoStartup()) {
            return ValidationResult.VALID;
        }

        return new StoragePoolValidator(storagePool).isUp();
    }

    /**
     * Checking that the interfaces are all configured, interfaces with no network are allowed only if network linking
     * is supported.
     *
     * @return true if all VM network interfaces are attached to existing cluster networks, or to no network (when
     *         network linking is supported).
     */
    protected ValidationResult validateInterfacesConfigured(VM vm) {
        for (VmNetworkInterface nic : vm.getInterfaces()) {
            if (nic.getVnicProfileId() == null) {
                return FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion()) ?
                        ValidationResult.VALID:
                            new ValidationResult(EngineMessage.ACTION_TYPE_FAILED_INTERFACE_NETWORK_NOT_CONFIGURED);
            }
        }

        return ValidationResult.VALID;
    }

    /**
     * @param vm The VM to be run
     * @param clusterNetworkNames cluster logical networks names
     * @param interfaceNetworkNames VM interface network names
     * @return true if all VM network interfaces are attached to existing cluster networks
     */
    protected ValidationResult validateInterfacesAttachedToClusterNetworks(VM vm,
            final Set<String> clusterNetworkNames, final Set<String> interfaceNetworkNames) {

        Set<String> result = new HashSet<>(interfaceNetworkNames);
        result.removeAll(clusterNetworkNames);
        if (FeatureSupported.networkLinking(vm.getVdsGroupCompatibilityVersion())) {
            result.remove(null);
        }

        // If after removing the cluster network names we still have objects, then we have interface on networks that
        // aren't attached to the cluster
        return result.isEmpty() ?
                ValidationResult.VALID
                : new ValidationResult(
                        EngineMessage.ACTION_TYPE_FAILED_NETWORK_NOT_IN_CLUSTER,
                        String.format("$networks %1$s", StringUtils.join(result, ",")));
    }

    /**
     * @param clusterNetworks
     *            cluster logical networks
     * @param interfaceNetworkNames
     *            VM interface network names
     * @return true if all VM network interfaces are attached to VM networks
     */
    protected ValidationResult validateInterfacesAttachedToVmNetworks(final List<Network> clusterNetworks,
            Set<String> interfaceNetworkNames) {
        List<String> nonVmNetworkNames =
                NetworkUtils.filterNonVmNetworkNames(clusterNetworks, interfaceNetworkNames);

        return nonVmNetworkNames.isEmpty() ?
                ValidationResult.VALID
                : new ValidationResult(
                        EngineMessage.ACTION_TYPE_FAILED_NOT_A_VM_NETWORK,
                        String.format("$networks %1$s", StringUtils.join(nonVmNetworkNames, ",")));
    }

    ///////////////////////
    /// Utility methods ///
    ///////////////////////

    protected boolean validate(ValidationResult validationResult, List<String> message) {
        if (!validationResult.isValid()) {
            message.add(validationResult.getMessage().name());

            for (String variableReplacement : validationResult.getVariableReplacements()) {
                message.add(variableReplacement);
            }

        }
        return validationResult.isValid();
    }

    protected NetworkDao getNetworkDao() {
        return DbFacade.getInstance().getNetworkDao();
    }

    protected VdsDynamicDao getVdsDynamicDao() {
        return DbFacade.getInstance().getVdsDynamicDao();
    }

    protected BackendInternal getBackend() {
        return Backend.getInstance();
    }

    protected VmNicDao getVmNicDao() {
        return DbFacade.getInstance().getVmNicDao();
    }

    protected StorageDomainDao getStorageDomainDao() {
        return DbFacade.getInstance().getStorageDomainDao();
    }

    protected VmPropertiesUtils getVmPropertiesUtils() {
        return VmPropertiesUtils.getInstance();
    }

    protected DiskDao getDiskDao() {
        return DbFacade.getInstance().getDiskDao();
    }

    private boolean isRepoImageExists(String repoImagePath, Guid storageDomainId, ImageFileType imageFileType) {
        VdcQueryReturnValue ret = getBackend().runInternalQuery(
                VdcQueryType.GetImagesList,
                new GetImagesListParameters(storageDomainId, imageFileType));

        if (ret != null && ret.getReturnValue() != null && ret.getSucceeded()) {
            for (RepoImage isoFileMetaData : ret.<List<RepoImage>>getReturnValue()) {
                if (repoImagePath.equals(isoFileMetaData.getRepoImageId())) {
                    return true;
                }
            }
        }
        return false;
    }

    protected boolean isVmDuringInitiating(VM vm) {
        return (Boolean) getBackend()
                .getResourceManager()
                .RunVdsCommand(VDSCommandType.IsVmDuringInitiating,
                        new IsVmDuringInitiatingVDSCommandParameters(vm.getId()))
                .getReturnValue();
    }

    protected SnapshotsValidator getSnapshotValidator() {
        return new SnapshotsValidator();
    }

    private VdsDynamic getVdsDynamic(Guid vdsId) {
        return getVdsDynamicDao().get(vdsId);
    }

    private List<Disk> getVmDisks() {
        if (cachedVmDisks == null) {
            cachedVmDisks = getDiskDao().getAllForVm(vm.getId(), true);
        }

        return cachedVmDisks;
    }

    private List<DiskImage> getVmImageDisks() {
        if (cachedVmImageDisks == null) {
            cachedVmImageDisks = ImagesHandler.filterImageDisks(getVmDisks(), true, false, false);
            cachedVmImageDisks.addAll(ImagesHandler.filterDisksBasedOnCinder(getVmDisks(), true));
        }

        return cachedVmImageDisks;
    }

    private Set<String> getInterfaceNetworkNames() {
        if (cachedInterfaceNetworkNames == null) {
            cachedInterfaceNetworkNames = Entities.vmInterfacesByNetworkName(vm.getInterfaces()).keySet();
        }

        return cachedInterfaceNetworkNames;
    }

    private List<Network> getClusterNetworks() {
        if (cachedClusterNetworks == null) {
            cachedClusterNetworks = getNetworkDao().getAllForCluster(vm.getVdsGroupId());
        }

        return cachedClusterNetworks;
    }

    private Set<String> getClusterNetworksNames() {
        if (cachedClusterNetworksNames == null) {
            cachedClusterNetworksNames = Entities.objectNames(getClusterNetworks());
        }

        return cachedClusterNetworksNames;
    }

    public OsRepository getOsRepository() {
        return osRepository;
    }
}


text:
@interface SCActionSheetProxy : NSObject <UIActionSheetDelegate> {
    SCActionSheetProxy* _keepAlive; // we are a free roaming delegate, need a reference to ourself to avoid death
    NSArray* _actions;
    void (^_dismiss)();
}

@end

@implementation SCActionSheetProxy

-(id)initWithActions:(NSArray*)actions andDismiss:(void(^)())dismiss {
    if((self = [super init])) {
        _keepAlive = self;
        _actions = actions;
        _dismiss = dismiss;
    }
    return self;
}

-(void)actionSheet:(UIActionSheet *)actionSheet didDismissWithButtonIndex:(NSInteger)buttonIndex {
    if ((buttonIndex >= 0) && (buttonIndex < [_actions count])) {
        void(^action)() = [_actions objectAtIndex:buttonIndex];
        action();
    }
    _dismiss();
    _keepAlive = nil;
}

@end

@implementation UIActionSheet (SCBlockAditions)

+(UIActionSheet*) actionSheetWithTitle:(NSString*) title
                               dismiss:(void(^)())dismiss
           buttonsAndActions:(NSObject*) buttonsAndActions, ... {

    NSMutableArray* actions = [NSMutableArray new];

    UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:title
                                                             delegate:nil
                                                    cancelButtonTitle:nil
                                               destructiveButtonTitle:nil
                                                    otherButtonTitles:nil];
    va_list args;
    va_start(args, buttonsAndActions);

    NSObject* buttonTitle = (NSString*)buttonsAndActions;

    while(buttonTitle) {
        NSObject* action =  va_arg(args, NSObject*);

        if(buttonTitle != [NSNull null]) {
            [actionSheet addButtonWithTitle:(NSString*)buttonTitle];
            [actions addObject:[action copy]];
        }

        buttonTitle = va_arg(args, NSObject*);
    }
    va_end(args);

    SCActionSheetProxy* proxy = [[SCActionSheetProxy alloc] initWithActions:actions andDismiss:[dismiss copy]];
    actionSheet.delegate = proxy;

    return actionSheet;
}

@end


text:
// The MIT License (MIT)
//
// Copyright (c) 2014-2016, Institute for Software & Systems Engineering
//
// 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.

namespace Tests.Serialization.Ranges
{
	using System;
	using SafetySharp.Modeling;
	using SafetySharp.Runtime;
	using SafetySharp.Runtime.Serialization;
	using Shouldly;

	internal class UInt8 : SerializationObject
	{
		protected override void Check()
		{
			var c = new C { F = 1, G = 2, H = 3 };

			GenerateCode(SerializationMode.Optimized, c);

			Serialize();
			c.F = 31;
			c.G = 99;
			c.H = 77;
			Deserialize();
			c.F.ShouldBe((byte)1);
			c.G.ShouldBe((byte)2);
			c.H.ShouldBe((byte)3);

			c.F = 99;
			Should.Throw<RangeViolationException>(() => Serialize());

			c.F = 1;
			c.G = 0;
			c.H = 0;

			Serialize();
			Deserialize();

			c.F.ShouldBe((byte)1);
			c.G.ShouldBe((byte)1);
			c.H.ShouldBe((byte)6);

			c.G = 1;
			c.H = 2;

			Serialize();
			Deserialize();

			c.G.ShouldBe((byte)1);
			c.H.ShouldBe((byte)2);

			c.G = 2;
			c.H = 3;

			Serialize();
			Deserialize();

			c.G.ShouldBe((byte)2);
			c.H.ShouldBe((byte)3);

			c.G = 3;
			c.H = 6;

			Serialize();
			Deserialize();

			c.G.ShouldBe((byte)3);
			c.H.ShouldBe((byte)6);

			c.G = 4;
			c.H = 7;

			Serialize();
			Deserialize();

			c.G.ShouldBe((byte)3);
			c.H.ShouldBe((byte)2);

			c.G = 5;
			c.H = 8;

			Serialize();
			Deserialize();

			c.G.ShouldBe((byte)3);
			c.H.ShouldBe((byte)2);

			c.G = Byte.MaxValue;
			c.H = Byte.MaxValue;
			c.Q = Byte.MaxValue;

			Serialize();
			Deserialize();

			c.G.ShouldBe((byte)3);
			c.H.ShouldBe((byte)2);
			c.Q.ShouldBe(Byte.MaxValue);

			c.G = Byte.MinValue;
			c.H = Byte.MinValue;
			c.Q = Byte.MinValue;

			Serialize();
			Deserialize();

			c.G.ShouldBe((byte)1);
			c.H.ShouldBe((byte)6);
			c.Q.ShouldBe(Byte.MinValue);
		}

		internal class C
		{
			[Range(1, 5, OverflowBehavior.Error)]
			public byte F;

			public byte G;
			public byte H;
			public byte Q;

			public C()
			{
				Range.Restrict(G, 1, 3, OverflowBehavior.Clamp);
				Range.Restrict(H, 2, 6, OverflowBehavior.WrapClamp);
			}
		}
	}
}