text:
Development Guide
#################

*******************************
Optional fast start with docker
*******************************

Docker-compose installation
===========================
In case of Ubuntu 14.04::

    sudo apt-get update
    sudo apt-get install apt-transport-https ca-certificates apparmor
    sudo apt-key adv --keyserver hkp://p80.pool.sks-keyservers.net:80 --recv-keys 58118E89F3A912897C070ADBF76221572C52609D
    echo 'deb https://apt.dockerproject.org/repo ubuntu-trusty main' | sudo tee /etc/apt/sources.list.d/docker.list
    sudo apt-get update
    sudo apt-get install -y docker-engine
    sudo bash -c "curl -L https://github.com/docker/compose/releases/download/1.6.2/docker-compose-`uname -s`-`uname -m` > /usr/local/bin/docker-compose"
    sudo chmod +x /usr/local/bin/docker-compose

More detailed info available at `Docker page <https://docs.docker.com/compose/install/>`_.

Available make commands (requires sudo)
=======================================
``docker-up`` -> run local development server at localhost:8000
``docker-tests`` -> run all tests in docker environment
``docker-bash`` -> attach to docker environment command line

********
Starting
********

System dependencies
===================

In case of Ubuntu::

  sudo apt-get install python-dev libpq-dev libfreetype6-dev libblas-dev liblapack-dev gfortran postgresql postgresql-contrib libpng-dev

In case of Fedora::

  sudo yum install python-devel freetype-devel libblas-devel lapack-devel gcc-fortran postgresql-server postgresql-contrib postgresql-devel postgresql-libs

PIP and Virtual Environment
===========================

You need to have `PIP <https://pypi.python.org/pypi/pip>`_ installed. Now, we try to install `virtualenvwrapper <http://virtualenvwrapper.readthedocs.org/en/latest/>`_::

  sudo pip install virtualenvwrapper

and add the following to your ``~/.bashrc`` file::

  export WORKON_HOME=$HOME/.virtualenvs
  source /usr/local/bin/virtualenvwrapper.sh

Using ``whereis python`` find your installation of Python 3.x. We will reference it as ``PYTHON_PATH``. Now, crate a virtual environment::

  mkvirtualenv -p $PYTHON_PATH proso-apps

If you want to use the environment in the future, just type::

  workon proso-apps

PostgreSQL
==========

Create a development user and database on your localhost::

  sudo -i -u postgres
  psql

You are in PostgreSQL shell. Execute::

  CREATE DATABASE proso_apps;
  CREATE USER proso_apps WITH PASSWORD 'proso_apps';
  GRANT ALL PRIVILEGES ON DATABASE "proso_apps" to proso_apps;

GIT repository
==============

Firstly, you need to clone our GIT repository::

  git clone git@github.com:adaptive-learning/proso-apps.git

or in case, you have no access::

  git clone https://github.com/adaptive-learning/proso-apps.git

Since now, we will work inside the cloned repository::

  cd proso-apps

After you clone the repository, install ``proso-apps``::

  make install

After successful installation, migrate database::

  ./manage.py migrate

Finally, we can run the test server::

  ./manage.py runserver

Sample database
===============

You can download a dump from PostgreSQL used by `www.slepemapy.cz <http://www.slepemapy.cz>`_ from
`data-private.slepemapy.cz/dump <http://data-private.slepemapy.cz/dump>`_ (the file is referenced as ``DUMP_FILE``) and
load it to your database::

  export PGPASSWORD=proso_apps
  psql -Uproso_apps --set ON_ERROR_STOP=on proso_apps < $DUMP_FILE

If you want to create a new dump file, just run::

  export PGPASSWORD=...
  pg_dump -h db.fi.muni.cz -Uweb_slepemapy -nweb_slepemapy_prod --exclude-table=proso_models_audit "dbname=pgdb sslmode=require" > $DUMP_FILE


text:
var conf = require('./conf');
var util = require('./util');
var rpc = require('./rpc');
var fs = require('fs');
var getCrc32 = require('crc32');
var url = require('url');
var mime = require('mime');
var formstream = require('formstream');

exports.UNDEFINED_KEY = '?'
exports.PutExtra = PutExtra;
exports.PutRet = PutRet;
exports.put = put;
exports.putWithoutKey = putWithoutKey;
exports.putFile = putFile;
exports.putFileWithoutKey = putFileWithoutKey;

// @gist PutExtra
function PutExtra(params, mimeType, crc32, checkCrc) {
  this.paras = params || {};
  this.mimeType = mimeType || null;
  this.crc32 = crc32 || null;
  this.checkCrc = checkCrc || 0;
}
// @endgist

function PutRet(hash, key) {
  this.hash = hash || null;
  this.key = key || null;
}

// onret: callback function instead of ret
function put(uptoken, key, body, extra, onret) {
  if(!extra) {
    extra = new PutExtra();
  }
  if (!extra.mimeType) {
    extra.mimeType = 'application/octet-stream';
  }

  if(!key) {
    key = exports.UNDEFINED_KEY;
  }

  var form = getMultipart(uptoken, key, body, extra);

  rpc.postMultipart(conf.UP_HOST, form, onret);
}

function putWithoutKey(uptoken, body, extra, onret) {
  put(uptoken, null, body, extra, onret);
}

function getMultipart(uptoken, key, body, extra) {

  var form = formstream();

  form.field('token', uptoken);
  if(key != exports.UNDEFINED_KEY) {
    form.field('key', key);
  }
  var buf = Buffer.isBuffer(body) ? body : new Buffer(body);
  form.buffer('file', buf, key, extra.mimeType);

  //extra['checkcrc']
  if (extra.checkCrc == 1) {
    var bodyCrc32 = getCrc32(body);
    extra.crc32 = '' + parseInt(bodyCrc32, 16);
  }

  if(extra.checkCrc) {
    form.field('crc32', extra.crc32);
  }

  for (var k in extra.params) {
    form.field(k, extra.params[k]);
  }

  return form;
}

function putFile(uptoken, key, loadFile, extra, onret) {
  fs.readFile(loadFile, function(err, data) {
    if(err) {
      onret({code: -1, error: err.toString()}, {});
      return;
    }

    if(!extra) {
      extra = new PutExtra();
    }

    if(!extra.mimeType) {
      extra.mimeType = mime.lookup(loadFile);
    }
    put(uptoken, key, data, extra, onret);
  });
}

function putFileWithoutKey(uptoken, loadFile, extra, onret) {
  putFile(uptoken, null, loadFile, extra, onret);
}

redpajama_set_name: RedPajamaGithub


text:
package org.wso2.msf4j;

import java.nio.ByteBuffer;

/**
 * HttpHandler would extend this abstract class and implement methods to stream the body directly.
 * chunk method would receive the http-chunks of the body and finished would be called
 * on receipt of the last chunk.
 */
public interface HttpStreamHandler {

    /**
     * Initialize the stream handler.
     *
     * @param response response object that should be used to send response
     */
    void init(Response response);

    /**
     * Http request content will be streamed directly to this method.
     *
     * @param content content of chunks
     */
    void chunk(ByteBuffer content) throws Exception;

    /**
     * This method will be called when all chunks
     * have been completely streamed.
     *
     * @throws Exception
     */
    void end() throws Exception;

    /**
     * When there is exception on netty while streaming, it will be propagated to handler
     * so the handler can do the cleanup.
     *
     * @param cause Cause of the Exception
     */
    void error(Throwable cause);
}


text:
class Rational < Numeric

  private_class_method :new

  def self.convert(num, den)
    if num.equal? nil or den.equal? nil
      raise TypeError, "cannot convert nil into Rational"
    end

    case num
    when Integer
      # nothing
    when Float, String, Complex
      num = num.to_r
    end

    case den
    when Integer
      # nothing
    when Float, String, Complex
      den = den.to_r
    end

    if num.kind_of? Integer and den.kind_of? Integer
      return new(num, den)
    end

    if den.equal? 1 and !num.kind_of? Integer
      return Rubinius::Type.coerce_to num, Rational, :to_r
    else
      if num.kind_of? Numeric and den.kind_of? Numeric and
         !(num.kind_of? Integer and den.kind_of? Integer)
        return num / den
      end
    end

    new num, den
  end

  private_class_method :convert

  #
  # This method is actually private.
  #
  def initialize(num, den)
    case num
    when Integer
      # nothing
    when Numeric
      num = num.to_i
    else
      raise TypeError, "numerator is not an Integer"
    end

    case den
    when Integer
      if den == 0
        raise ZeroDivisionError, "divided by 0"
      elsif den < 0
        num = -num
        den = -den
      end

      if den == 1
        @numerator = num
        @denominator = den
        return
      end
    when Numeric
      den = den.to_i
    else
      raise TypeError, "denominator is not an Integer"
    end

    gcd = num.gcd den
    @numerator = num.div gcd
    @denominator = den.div gcd
  end

  def + (a)
    if a.kind_of?(Rational)
      num = @numerator * a.denominator
      num_a = a.numerator * @denominator
      Rational(num + num_a, @denominator * a.denominator)
    elsif a.kind_of?(Integer)
      self + Rational(a, 1)
    elsif a.kind_of?(Float)
      Float(self) + a
    else
      x, y = a.coerce(self)
      x + y
    end
  end

  def - (a)
    if a.kind_of?(Rational)
      num = @numerator * a.denominator
      num_a = a.numerator * @denominator
      Rational(num - num_a, @denominator*a.denominator)
    elsif a.kind_of?(Integer)
      self - Rational(a, 1)
    elsif a.kind_of?(Float)
      Float(self) - a
    else
      x, y = a.coerce(self)
      x - y
    end
  end

  def * (a)
    if a.kind_of?(Rational)
      num = @numerator * a.numerator
      den = @denominator * a.denominator
      Rational(num, den)
    elsif a.kind_of?(Integer)
      self * Rational(a, 1)
    elsif a.kind_of?(Float)
      Float(self) * a
    else
      x, y = a.coerce(self)
      x * y
    end
  end

  def divide (a)
    if a.kind_of?(Rational)
      num = @numerator * a.denominator
      den = @denominator * a.numerator
      Rational(num, den)
    elsif a.kind_of?(Integer)
      raise ZeroDivisionError, "division by zero" if a == 0
      self / Rational(a, 1)
    elsif a.kind_of?(Float)
      Float(self) / a
    else
      redo_coerced :/, a
    end
  end

  alias_method :/, :divide

  def ** (other)
    if other.kind_of?(Rational) && other.denominator == 1
      other = other.numerator
    end

    if other.kind_of?(Fixnum)
      if self == 0 && other < 0
        raise ZeroDivisionError, "divided by 0"
      end
      if other > 0
        num = @numerator ** other
        den = @denominator ** other
      elsif other < 0
        num = @denominator ** -other
        den = @numerator ** -other
      elsif other == 0
        num = 1
        den = 1
      end
      Rational(num, den)
    elsif other.kind_of?(Bignum)
      if self == 0
        if other < 0
          raise ZeroDivisionError, "divided by 0"
        elsif other > 0
          return Rational(0)
        end
      elsif self == 1
        return Rational(1)
      elsif self == -1
        return Rational(other.even? ? 1 : -1)
      end
      Float(self) ** other
    elsif other.kind_of?(Float) || other.kind_of?(Rational)
      Float(self) ** other
    else
      x, y = other.coerce(self)
      x ** y
    end
  end

  def div(other)
    (self / other).floor
  end

  def % (other)
    if other == 0.0
      raise ZeroDivisionError, "division by zero"
    end
    value = (self / other).floor
    return self - other * value
  end

  def divmod(other)
    if other.is_a?(Float) && other == 0.0
      raise ZeroDivisionError, "division by zero"
    end
    value = (self / other).floor
    return value, self - other * value
  end

  def abs
    if @numerator > 0
      self
    else
      Rational(-@numerator, @denominator)
    end
  end

  def == (other)
    if other.kind_of?(Rational)
      @numerator == other.numerator and (@denominator == other.denominator or @numerator.zero?)
    elsif other.kind_of?(Integer)
      self == Rational(other, 1)
    elsif other.kind_of?(Float)
      Float(self) == other
    else
      other == self
    end
  end

  def <=> (other)
    if other.kind_of?(Rational)
      num = @numerator * other.denominator
      num_a = other.numerator * @denominator
      v = num - num_a
      if v > 0
        return 1
      elsif v < 0
        return  -1
      else
        return 0
      end
    elsif other.kind_of?(Integer)
      return self <=> Rational(other, 1)
    elsif other.kind_of?(Float)
      return Float(self) <=> other
    elsif defined? other.coerce
      x, y = other.coerce(self)
      return x <=> y
    else
      return nil
    end
  end

  def coerce(other)
    if other.kind_of?(Float)
      return other, self.to_f
    elsif other.kind_of?(Integer)
      return Rational(other, 1), self
    else
      super
    end
  end

  def floor
    @numerator.div(@denominator)
  end

  def ceil
    -((-@numerator).div(@denominator))
  end

  def truncate
    if @numerator < 0
      return -((-@numerator).div(@denominator))
    end
    @numerator.div(@denominator)
  end

  alias_method :to_i, :truncate

  def round
    if @numerator < 0
      num = -@numerator
      num = num * 2 + @denominator
      den = @denominator * 2
      -(num.div(den))
    else
      num = @numerator * 2 + @denominator
      den = @denominator * 2
      num.div(den)
    end
  end

  def to_f
    @numerator.to_f/@denominator.to_f
  end

  def to_s
    @numerator.to_s+"/"+@denominator.to_s
  end

  def to_r
    self
  end

  def inspect
    "(#{to_s})"
  end

  def hash
    @numerator.hash ^ @denominator.hash
  end

  attr_reader :numerator
  attr_reader :denominator

  private :initialize

  def rationalize(eps=undefined)
    if eps.equal?(undefined)
      self
    else
      e = eps.abs
      a = self - e
      b = self + e

      p0 = 0
      p1 = 1
      q0 = 1
      q1 = 0

      while true
        c = a.ceil
        break if c < b
        k = c - 1
        p2 = k * p1 + p0
        q2 = k * q1 + q0
        t = 1 / (b - k)
        b = 1 / (a - k)
        a = t
        p0 = p1
        q0 = q1
        p1 = p2
        q1 = q2
      end

      Rational(c * p1 + p0, c * q1 + q0)
    end
  end

  def marshal_dump
    ary = [numerator, denominator]
    instance_variables.each do |ivar|
      ary.instance_variable_set(ivar, instance_variable_get(ivar))
    end
    ary
  end

  def marshal_load(ary)
    @numerator, @denominator = ary
    ary.instance_variables.each do |ivar|
      instance_variable_set(ivar, ary.instance_variable_get(ivar))
    end
    self
  end

  #
  # Returns the truncated value, toward the nearest unit, based on the
  # precision.
  #
  # eg:
  #
  # Rational(1,2).round    #=> 1
  # Rational(-1,2).round   #=> -1
  # Rational(1,4).round(1) #=> Rational(3,10)
  #
  def round(precision = 0)
    return 0 if @numerator == 0
    return @numerator if @denominator == 1

    adj = (10 ** precision.abs).to_i
    adj = Rational(1, adj) if precision < 0

    value = self * adj

    value = if self > 0
      (value + Rational(1,2)).floor
    else
      (value - Rational(1,2)).ceil
    end

    result = Rational(value, adj)

    return result.numerator if result.denominator == 1
    result
  end
end


text:
"""
Global Equities Momentum (GEM)¶

Gary Antonacci's Dual Momentum approach is simple: by combining both
relative momentum and absolute momentum (i.e. trend following),
Dual Momentum seeks to rotate into areas of relative strength while
preserving the flexibility to shift entirely to safety assets
(e.g. short-term U.S. Treasury bills) during periods of pervasive,
negative trends.

Antonacci's Global Equities Momentum (GEM) portfolio builds a portfolio
with three assets: U.S. stocks, international stocks and U.S. bonds.
For the retail investor he recommends using low-cost ETFs: for example,
VOO for U.S. stocks; VEU for non-U.S. stocks and AGG for U.S. aggregate
bonds.

Antonacci named his system "Dual Momentum" because he uses both
relative momentum (the measure of the performance of an asset relative
to another asset) and absolute momentum ( the measure of performance
relative to the risk-free rate – absolute excess return.) To keep the
process very simple to implement, he used a 12-month look-back period
and an easy to execute buy and sell system.

Every month the investor places all funds in the equity ETF that has
the best 12-month performance relative to the other equity ETFs,
unless the absolute performance is worse than the return of
six-month U.S. Treasuries (as measured by BIL ETF). If absolute
performance is below the BIL ETF, then the investor places all funds
in AGG, the aggregate bond index.
"""

import random

import pinkfish as pf

default_options = {
    'use_adj' : True,
    'use_cache' : True,
    'lookback': None,
    'margin': 1,
}

class Strategy:

    def __init__(self, symbols, capital, start, end, options=default_options):

        self.symbols = symbols
        self.capital = capital
        self.start = start
        self.end = end
        self.options = options.copy()

        self.ts = None
        self.rlog = None
        self.tlog = None
        self.dbal = None
        self.stats = None

    def _algo(self):

        pf.TradeLog.cash = self.capital
        pf.TradeLog.margin = self.options['margin']

        # These dicts are used to track close, mom, and weights for
        # each symbol in portfolio
        prices = {}
        mom = {}
        weights = {}

        # These variables are assigned to the actual ETFs
        US_STOCKS   = self.symbols['US STOCKS']
        US_BONDS    = self.symbols['US BONDS']
        EXUS_STOCKS = self.symbols['EX-US STOCKS']
        TBILL       = self.symbols['T-BILL']

        # A counter to countdown the number of months a lookback has
        # been in place
        month_count = 0

        for i, row in enumerate(self.ts.itertuples()):

            date = row.Index.to_pydatetime()
            end_flag = pf.is_last_row(self.ts, i)

            if month_count == 0:
                # if period is None, then select a random trading period of
                # 6,7,8,...,or 12 months
                if self.options['lookback'] is None:
                    lookback = random.choice(range(6, 12+1))
                else:
                    lookback = self.options['lookback']
                month_count = lookback

            # If first day of the month or last row
            if row.first_dotm or end_flag:

                month_count -= 1

                # Get prices for current row
                mom_field = 'mom' + str(lookback)
                p = self.portfolio.get_prices(row, fields=['close', mom_field])

                # Copy data from `p` into prices and mom dicts for
                # convenience, also zero out weights dict.
                for symbol in self.portfolio.symbols:
                    prices[symbol] = p[symbol]['close']
                    mom[symbol] = p[symbol][mom_field]
                    weights[symbol] = 0

                # Rebalance logic:
                #   Check absolute momenteum first, i.e. US_STOCKS > TBILL.
                #   Check relative momentrum, i.e. US_STOCKS > EXUS_STOCKS.
                #   (see complete description at top of this file)
                #   Finally rebalance

                # GEM strategy
                if end_flag:
                    # Since weights dict is zeroed out, all positions
                    # will be closed out below with adjust_percent()
                    pass
                elif mom[US_STOCKS] > mom[TBILL]:
                    if mom[US_STOCKS] > mom[EXUS_STOCKS]:
                        weights[US_STOCKS] = 1
                    else:
                        weights[EXUS_STOCKS] = 1
                else:
                    weights[US_BONDS] = 1

                # Rebalance portfolio
                self.portfolio.adjust_percents(date, prices, weights, row)

            # record daily balance
            self.portfolio.record_daily_balance(date, row)

    def run(self):
        self.portfolio = pf.Portfolio()
        self.ts = self.portfolio.fetch_timeseries(self.symbols.values(), self.start, self.end,
                    fields=['close'],
                    use_cache=self.options['use_cache'],
                    use_adj=self.options['use_adj'])

        # Add calendar columns
        self.ts = self.portfolio.calendar(self.ts)

        # Add technical indicator Momenteum for all symbols in portfolio.
        lookbacks = range(3, 18+1)
        for lookback in lookbacks:
            @pf.technical_indicator(self.symbols.values(), 'mom'+str(lookback), 'close')
            def _momentum(ts, input_column=None):
                return pf.MOMENTUM(ts, lookback=lookback, time_frame='monthly',
                                   price=input_column, prevday=False)
            self.ts = _momentum(self.ts)

        self.ts, self.start = self.portfolio.finalize_timeseries(self.ts, self.start)
        self.portfolio.init_trade_logs(self.ts)

        self._algo()
        self._get_logs()
        self._get_stats()

    def _get_logs(self):
        self.rlog, self.tlog, self.dbal = self.portfolio.get_logs()

    def _get_stats(self):
        self.stats = pf.stats(self.ts, self.tlog, self.dbal, self.capital)


text:
using Orleans.Concurrency;
using System;

namespace Sample.Grains.Models
{
    [Immutable]
    public class WeatherInfo
    {
        public WeatherInfo(DateTime date, int temperatureC, string summary, int temperatureF)
        {
            Date = date;
            TemperatureC = temperatureC;
            Summary = summary;
            TemperatureF = temperatureF;
        }

        public DateTime Date { get; }
        public int TemperatureC { get; }
        public string Summary { get; }
        public int TemperatureF { get; }
    }
}


text:
EW_ENTER

class DLLIMPEXP_EWC_BASE WndManager;

class DLLIMPEXP_EWC_BASE PluginManager
{
public:

	friend class WndManager;

	void Register(Plugin* p);

	static PluginManager& current();

	indexer_map<String,DataPtrT<Plugin> > plugin_map;
	ObjectGroupT<PluginCommon> plugin_common;
	ObjectGroupT<PluginEditor> plugin_editor;
	ObjectGroupT<IEditorPlugin> plugin_plugin;

	PluginManager();

protected:

	bool AttachPlugin(Plugin* p);

};

EW_LEAVE
#endif


text:
      <button class="btn" ng-disabled="!anySelectionHasState(['stop', 'suspend'])" ng-click="start()"> Start</button>
      <button class="btn" ng-disabled="!anySelectionHasState('start')" ng-click="pause()"> Pause</button>
      <button class="btn" ng-disabled="!anySelectionHasState(['start', 'suspend'])" ng-click="stop()"> Stop</button>
      <button class="btn" ng-disabled="!everySelectionHasState('stop')" ng-click="delete()"> Delete</button>

      <input type="text" class="span12 search-query" ng-model="$parent.gridOptions.filterOptions.filterText" placeholder="Filter...">


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ObjectComparer
{
    interface IComparer
    {
        bool Compare(object A, object B);
    }
}


text:
/*
	Channels that can go through external I/O devices for Clive.

	The protocol used in the device permits muxing of multiple
	channels within a single connection.

	In the connection, messages exchanged use the format:

	size[4] tag[2] type[2] data[size]

	Here, a tag identifies a channel and type identifies the type
	of data exchanged.
*/
package ch

import (
	"bytes"
	"encoding/binary"
	"errors"
	"fmt"
	"io"
	"sync"
	"time"
)

// Message types.
// It is ok for the user to define new types.
// By convention, unknown message types are to be forwarded as-is
// by processes piping data along with actual data being processed.
// For any unknown type, Bytes(), WriteTo(), and String() are used
// if they exist, if they don't, the type is discarded.
// In this case, the type is Tign unless a TypeId() method exists to
// return the type id to be sent.
const (
	Tnone  uint16 = iota
	Tbytes        // byte[], used as data
	Tign          // byte[], ignored as data
	Tstr          // string
	Terr          // error string
	Taddr         // file address (name, ln, ch)
	Tdir          // map[string]string, directory entry
	Tzx           // zx protocol msg
	Tusr          // first user defined type value
)

const (
	hdrSz = 4 + 4 + 2

	// Maximum supported msg sz
	MaxMsgSz = 64 * 1024
	// Maximum supported len(Dir)
	MaxDirSz = 1024
)

// byte[] messages ignored as data.
struct Ign {
	Typ uint16
	Dat []byte
}

interface Byteser {
	Bytes() []byte
}

interface Typer {
	TypeId() uint16
}

// For user defined types, implementors of this interface
// use their own make function to make values of the message type
// upon reception.
interface Unpacker {
	Typer
	Unpack([]byte) (face{}, error)
}

var (
	ErrTooLarge  = errors.New("message size is too large")
	ErrTooSmall  = errors.New("truncated message")
	ErrAlready   = errors.New("type already defined")
	ErrDiscarded = errors.New("msg write discarded")
	ErrIO        = errors.New("i/o error")

	// Msg size for []byte readers
	MsgSz = 16 * 1024

	empty = []byte{} // it must be a slice

	unpackers = map[uint16]Unpacker{}
)

// Define a user type to be sent through chans
// Should be used only at init time.
func DefType(x Unpacker) {
	unpackers[x.TypeId()] = x
}

func WriteStringTo(w io.Writer, s string) (n int64, err error) {
	if err := binary.Write(w, binary.LittleEndian, uint32(len(s))); err != nil {
		return 0, fmt.Errorf("%s: %s", ErrIO, err)
	}
	n = 4
	nw, err := io.WriteString(w, s)
	n += int64(nw)
	return n, err
}

func UnpackString(b []byte) ([]byte, string, error) {
	if len(b) < 4 {
		return nil, "", ErrTooSmall
	}
	sz := int(binary.LittleEndian.Uint32(b[0:]))
	b = b[4:]
	if len(b) < sz {
		return nil, "", ErrTooSmall
	}
	return b[sz:], string(b[:sz]), nil
}

func writeBytes(w io.Writer, tag uint32, typ uint16, b []byte) (int64, error) {
	var hdr [hdrSz]byte

	if b == nil {
		b = empty[:]
	}
	n := len(b)
	// do a single write, at the cost of an extra copy
	var buf bytes.Buffer
	binary.LittleEndian.PutUint32(hdr[0:], uint32(n))
	binary.LittleEndian.PutUint32(hdr[4:], tag)
	binary.LittleEndian.PutUint16(hdr[8:], typ)
	buf.Write(hdr[:])
	buf.Write(b)
	tot, err := w.Write(buf.Bytes())
	if err != nil {
		err = fmt.Errorf("%s: %s", ErrIO, err)
	}
	return int64(tot), err
}

// Write []byte, or Ign, string, error, Stringer, Byteser or discard the write.
// If the write is discarded, ErrDiscarded is returned.
func WriteMsg(w io.Writer, tag uint32, m face{}) (int64, error) {
	switch m := m.(type) {
	case []byte:
		return writeBytes(w, tag, Tbytes, m)
	case Ign:
		return writeBytes(w, tag, m.Typ, m.Dat)
	case string:
		return writeBytes(w, tag, Tstr, []byte(m))
	case error:
		if m == nil {
			return writeBytes(w, tag, Terr, nil)
		}
		return writeBytes(w, tag, Terr, []byte(m.Error()))
	case io.WriterTo:
		var buf bytes.Buffer
		n, err := m.WriteTo(&buf)
		if err != nil {
			return n, fmt.Errorf("%s: %s", ErrIO, err)
		}
		typ := Tign
		if ti, ok := m.(Typer); ok {
			typ = ti.TypeId()
		}
		return writeBytes(w, tag, typ, buf.Bytes())
	case fmt.Stringer:
		typ := Tign
		if ti, ok := m.(Typer); ok {
			typ = ti.TypeId()
		}
		return writeBytes(w, tag, typ, []byte(m.String()))
	}
	return 0, ErrDiscarded
}

func decHdr(hdr []byte) (int, uint32, uint16) {
	return int(binary.LittleEndian.Uint32(hdr[0:])),
		binary.LittleEndian.Uint32(hdr[4:]),
		binary.LittleEndian.Uint16(hdr[8:])
}

func readBytes(r io.Reader, sz int) (d []byte, err error) {
	dat := make([]byte, sz, sz)
	nr, err := io.ReadFull(r, dat)
	if err != nil && nr != sz {
		return nil, err
	}
	return dat, nil
}

// Read a message and return the number of bytes, the msg, and its tag.
// If the message is an error, it is returned in in the interface.
// Errors while reading from r are returned using the error instead.
// EOF is reported using io.EOF; but it's not an error.
func ReadMsg(r io.Reader) (n int, tag uint32, m face{}, err error) {
	var hdr [hdrSz]byte

	nr, err := io.ReadFull(r, hdr[:])
	if err != nil {
		if err != io.EOF {
			err = fmt.Errorf("%s: %s", ErrIO, err)
		}
		return nr, 0, nil, err
	}
	sz, tag, typ := decHdr(hdr[:])
	if sz < 0 || sz > MaxMsgSz {
		return nr, tag, nil, ErrTooLarge
	}
	var b []byte
	if sz > 0 {
		b, err = readBytes(r, sz)
		sz += hdrSz
		if err != nil {
			return sz, tag, nil, fmt.Errorf("%s: %s", ErrIO, err)
		}
	} else {
		sz += hdrSz
	}
	switch typ {
	case Tbytes:
		return sz, tag, b, nil
	case Tstr:
		return sz, tag, string(b), nil
	case Terr:
		err := errors.New(string(b))
		return sz, tag, err, nil
	default:
		if mk := unpackers[typ]; mk != nil {
			m, err = mk.Unpack(b)
			return sz, tag, m, err
		}
		return sz, tag, Ign{typ, b}, nil
	}
}

// Read messages from a external reader and send them through c
// Error messages are forwarded.
// The chan is not closed, the caller may close(c, err) upon return.
func ReadMsgs(r io.Reader, c chan<- face{}) (nbytes int64, nmsgs int, err error) {
	for {
		n, _, m, rerr := ReadMsg(r)
		err = rerr
		if err != nil {
			if err == io.EOF {
				err = nil
			}
			return
		}
		nbytes += int64(n)
		nmsgs++
		if ok := c <- m; !ok {
			err = cerror(c)
			return
		}
	}
}

// Write messages received from c through an external writer with the given tag.
// The chan is not closed, the caller may close(c, err) upon return.
// Error messages are also propagated.
// The cerror of c, if not nil, is also written as an error message.
func WriteMsgs(w io.Writer, tag uint32, c <-chan face{}) (nbytes int64, nmsgs int, err error) {
	fl, _ := w.(flusher)
	for m := range c {
		n, rerr := WriteMsg(w, tag, m)
		if rerr == ErrDiscarded {
			rerr = nil
		}
		err = rerr
		if err == nil && fl != nil {
			err = fl.Flush()
		}
		if err != nil {
			return
		}
		nbytes += int64(n)
		nmsgs++
	}
	err = cerror(c)
	if err != nil {
		n, _ := WriteMsg(w, tag, err)
		nbytes += int64(n)
	}
	return
}

// Read bytes from a external reader and send them as messages through c
// The chan is not closed, the caller may close(c, err) upon return.
func ReadBytes(r io.Reader, c chan<- face{}) (nbytes int64, nmsgs int, err error) {
	err = nil
	buf := make([]byte, MsgSz)
	for {
		n, rerr := r.Read(buf[0:])
		if rerr != nil {
			if rerr != io.EOF && err == nil {
				err = fmt.Errorf("%s: %s", ErrIO, rerr)
			}
			return
		}
		nbytes += int64(n)
		nmsgs++
		m := make([]byte, n)
		copy(m, buf[:n])
		if ok := c <- m; !ok {
			if err == nil {
				err = cerror(c)
			}
			return
		}
	}

}

// Write []byte messages to an external writer, ignoring everything else.
// Error messages are ignored (the first one is used as the return sts).
func WriteBytes(w io.Writer, c <-chan face{}) (nbytes int64, nmsgs int, err error) {
	err = nil
	for {
		m, ok := <-c
		if !ok {
			break
		}
		if e, ok := m.(error); ok {
			if err == nil {
				err = e
			}
			continue
		}
		b, ok := m.([]byte)
		if !ok {
			continue
		}
		n, werr := w.Write(b)
		nbytes += int64(n)
		nmsgs++
		if werr != nil {
			if err == nil {
				err = fmt.Errorf("%s: %s", ErrIO, werr)
			}
			return
		}
	}
	if err == nil {
		err = cerror(c)
	}
	return
}

// Merge input channels: msgs received from in are sent to a single channel
func Merge(in ...<-chan face{}) <-chan face{} {
	var wg sync.WaitGroup
	outc := make(chan face{})
	for _, inc := range in {
		wg.Add(1)
		inc := inc
		go func() {
			for m := range inc {
				if ok := outc <- m; !ok {
					close(inc, cerror(outc))
				}
			}
			wg.Done()
		}()
	}
	go func() {
		wg.Wait()
		for _, i := range in {
			if err := cerror(i); err != nil {
				close(outc, err)
				return
			}
		}
		close(outc)
	}()
	return outc
}

// Group bytes from the input channel so data is sent at most every
// ival or when the given size is reached.
// Useful to collect command output and display it for the user without
// issuing a single write for each msg in the input.
func GroupBytes(in <-chan face{}, ival time.Duration, size int) <-chan face{} {
	var buf bytes.Buffer
	var t time.Time
	outc := make(chan face{})
	send := func() {
		m := make([]byte, buf.Len())
		copy(m, buf.Bytes())
		buf.Reset()
		if ok := outc <- m; !ok {
			close(in, cerror(outc))
		}
		t = time.Now()
	}
	go func() {
		doselect {
		case x, ok := <-in:
			if !ok {
				break
			}
			switch m := x.(type) {
			case []byte:
				buf.Write(m)
				if buf.Len() > size || time.Since(t) > ival {
					send()
				}
			default:
				if ok := outc <- m; !ok {
					close(in, cerror(outc))
				}
			}
		case <-time.After(ival):
			if buf.Len() > size {
				send()
			}
			t = time.Now()
		}
		if buf.Len() > 0 {
			outc <- buf.Bytes()
		}
		close(outc, cerror(in))
	}()
	return outc
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>kr.lerad.netronics.mobile.android</groupId>
    <artifactId>NetronicsMobile</artifactId>
    <version>1.0-SNAPSHOT</version>

    <dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty</artifactId>
            <version>3.5.8.Final</version>
            <scope>compile</scope>
        </dependency>
        <dependency>
            <groupId>de.undercouch</groupId>
            <artifactId>bson4jackson</artifactId>
            <version>2.0.0</version>
        </dependency>
    </dependencies>
</project>


text:
{% extends 'base.html' %}
{% load humanize %}
{% load sekizai_tags %}
{% load staticfiles %}
{% load i18n %}

{% block breadcrumb %}

{% trans 'PROJECTS' %}

{{ object.stage.project.name }}

{{ object.stage.name }}

Deployment started {{ object.date_created|naturaltime }}

{% endblock breadcrumb %}

{% block content %}

Deployment started {{ object.date_created|naturaltime }}

Comments

{{ object.comments }}

Date Started

{{ object.date_created }}

{% trans 'PROJECT' %}

{{ object.stage.project.name }}

{% trans 'STAGE' %}

{{ object.stage.name }}

Task

{{ object.task.name }}

Remote Host

{{ object.task.remote_host }}

Task Description

{{ object.task.description|linebreaksbr }}

                <fieldset style="text-align: center;margin-bottom:10px;" id="status_section">
                    {% if object.status == object.PENDING %}
                        <legend>Status: Working</legend>

                    {% elif object.status == object.SUCCESS %}
                        <legend>Status: Success!</legend>

                    {% else %}
                        <legend>Status: Failed!</legend>

                    {% endif %}
                </fieldset>

        {% block output %}
            {% if object.status == object.PENDING %}

            {% else %}

{{ object.output|safe }}

            {% endif %}
        {% endblock %}

    {% addtoblock "js" %}

        {% block deployment_scripts %}

        {% endblock %}
    {% endaddtoblock %}

{% endblock content %}


text:
package devices

import (
	"context"
	"crypto/rand"
	"database/sql"
	"encoding/base64"

	"github.com/matrix-org/dendrite/clientapi/auth/authtypes"
	"github.com/matrix-org/dendrite/common"
	"github.com/matrix-org/gomatrixserverlib"
)

// The length of generated device IDs
var deviceIDByteLength = 6

// Database represents a device database.
type Database struct {
	db      *sql.DB
	devices devicesStatements
}

// NewDatabase creates a new device database
func NewDatabase(dataSourceName string, serverName gomatrixserverlib.ServerName) (*Database, error) {
	var db *sql.DB
	var err error
	if db, err = sql.Open("postgres", dataSourceName); err != nil {
		return nil, err
	}
	d := devicesStatements{}
	if err = d.prepare(db, serverName); err != nil {
		return nil, err
	}
	return &Database{db, d}, nil
}

// GetDeviceByAccessToken returns the device matching the given access token.
// Returns sql.ErrNoRows if no matching device was found.
func (d *Database) GetDeviceByAccessToken(
	ctx context.Context, token string,
) (*authtypes.Device, error) {
	return d.devices.selectDeviceByToken(ctx, token)
}

// GetDeviceByID returns the device matching the given ID.
// Returns sql.ErrNoRows if no matching device was found.
func (d *Database) GetDeviceByID(
	ctx context.Context, localpart, deviceID string,
) (*authtypes.Device, error) {
	return d.devices.selectDeviceByID(ctx, localpart, deviceID)
}

// GetDevicesByLocalpart returns the devices matching the given localpart.
func (d *Database) GetDevicesByLocalpart(
	ctx context.Context, localpart string,
) ([]authtypes.Device, error) {
	return d.devices.selectDevicesByLocalpart(ctx, localpart)
}

// CreateDevice makes a new device associated with the given user ID localpart.
// If there is already a device with the same device ID for this user, that access token will be revoked
// and replaced with the given accessToken. If the given accessToken is already in use for another device,
// an error will be returned.
// If no device ID is given one is generated.
// Returns the device on success.
func (d *Database) CreateDevice(
	ctx context.Context, localpart string, deviceID *string, accessToken string,
	displayName *string,
) (dev *authtypes.Device, returnErr error) {
	if deviceID != nil {
		returnErr = common.WithTransaction(d.db, func(txn *sql.Tx) error {
			var err error
			// Revoke existing token for this device
			if err = d.devices.deleteDevice(ctx, txn, *deviceID, localpart); err != nil {
				return err
			}

			dev, err = d.devices.insertDevice(ctx, txn, *deviceID, localpart, accessToken, displayName)
			return err
		})
	} else {
		// We generate device IDs in a loop in case its already taken.
		// We cap this at going round 5 times to ensure we don't spin forever
		var newDeviceID string
		for i := 1; i <= 5; i++ {
			newDeviceID, returnErr = generateDeviceID()
			if returnErr != nil {
				return
			}

			returnErr = common.WithTransaction(d.db, func(txn *sql.Tx) error {
				var err error
				dev, err = d.devices.insertDevice(ctx, txn, newDeviceID, localpart, accessToken, displayName)
				return err
			})
			if returnErr == nil {
				return
			}
		}
	}
	return
}

// generateDeviceID creates a new device id. Returns an error if failed to generate
// random bytes.
func generateDeviceID() (string, error) {
	b := make([]byte, deviceIDByteLength)
	_, err := rand.Read(b)
	if err != nil {
		return "", err
	}
	// url-safe no padding
	return base64.RawURLEncoding.EncodeToString(b), nil
}

// UpdateDevice updates the given device with the display name.
// Returns SQL error if there are problems and nil on success.
func (d *Database) UpdateDevice(
	ctx context.Context, localpart, deviceID string, displayName *string,
) error {
	return common.WithTransaction(d.db, func(txn *sql.Tx) error {
		return d.devices.updateDeviceName(ctx, txn, localpart, deviceID, displayName)
	})
}

// RemoveDevice revokes a device by deleting the entry in the database
// matching with the given device ID and user ID localpart.
// If the device doesn't exist, it will not return an error
// If something went wrong during the deletion, it will return the SQL error.
func (d *Database) RemoveDevice(
	ctx context.Context, deviceID, localpart string,
) error {
	return common.WithTransaction(d.db, func(txn *sql.Tx) error {
		if err := d.devices.deleteDevice(ctx, txn, deviceID, localpart); err != sql.ErrNoRows {
			return err
		}
		return nil
	})
}

// RemoveAllDevices revokes devices by deleting the entry in the
// database matching the given user ID localpart.
// If something went wrong during the deletion, it will return the SQL error.
func (d *Database) RemoveAllDevices(
	ctx context.Context, localpart string,
) error {
	return common.WithTransaction(d.db, func(txn *sql.Tx) error {
		if err := d.devices.deleteDevicesByLocalpart(ctx, txn, localpart); err != sql.ErrNoRows {
			return err
		}
		return nil
	})
}


text:
"""
FILE: hello_world_advanced_sample.py
DESCRIPTION:
    This sample demos more advanced scenarios including add/set with label/list operations for app configuration
USAGE: python hello_world_advanced_sample.py
"""

from azure.appconfiguration import AzureAppConfigurationClient, ConfigurationSetting
from util import print_configuration_setting, get_connection_string

def main():
    CONNECTION_STRING = get_connection_string()

    # Create app config client
    client = AzureAppConfigurationClient.from_connection_string(CONNECTION_STRING)

    print("Add new configuration setting")
    config_setting = ConfigurationSetting(
        key="MyKey",
        label="MyLabel",
        value="my value",
        content_type="my content type",
        tags={"my tag": "my tag value"}
    )
    added_config_setting = client.add_configuration_setting(config_setting)
    print("New configuration setting:")
    print_configuration_setting(added_config_setting)
    print("")

    print("Set configuration setting")
    added_config_setting.value = "new value"
    added_config_setting.content_type = "new content type"
    updated_config_setting = client.set_configuration_setting(config_setting)
    print_configuration_setting(updated_config_setting)
    print("")

    print("List configuration settings")
    config_settings = client.list_configuration_settings(label_filter="MyLabel")
    for item in config_settings:
        print_configuration_setting(item)

    print("Delete configuration setting")
    client.delete_configuration_setting(
        key="MyKey",
        label="MyLabel",
    )

if __name__ == "__main__":
    main()


text:
import { randomColor } from 'utils/colors'

export default function defaultPlayer(player) {
  if (!player.name) player.name = 'clu'
  if (!player.color) player.color = randomColor()
  return player
}


text:
package server

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io"
	"net/http"
	"reflect"
	"strconv"
	"strings"

	"github.com/moov-io/base"
	moovhttp "github.com/moov-io/base/http"
	"github.com/moov-io/base/log"

	"github.com/go-kit/kit/endpoint"
	httptransport "github.com/go-kit/kit/transport/http"
	gokitlog "github.com/go-kit/log"
	"github.com/gorilla/mux"
)

var (
	bugReportHelp = "please report this as a bug -- https://github.com/moov-io/ach/issues/new"

	// ErrBadRouting is returned when an expected path variable is missing, which is always programmer error.
	ErrBadRouting = fmt.Errorf("inconsistent mapping between route and handler, %s", bugReportHelp)
	ErrFoundABug  = fmt.Errorf("snuck into encodeError with err == nil, %s", bugReportHelp)

	errInvalidFile = errors.New("invalid ACH file")
)

// contextKey is a unique (and compariable) type we use
// to store and retrieve additional information in the
// go-kit context.
var contextKey struct{}

// saveCORSHeadersIntoContext saves CORS headers into the go-kit context.
//
// This is designed to be added as a ServerOption in our main http handler.
func saveCORSHeadersIntoContext() httptransport.RequestFunc {
	return func(ctx context.Context, r *http.Request) context.Context {
		origin := r.Header.Get("Origin")
		return context.WithValue(ctx, contextKey, origin)
	}
}

// respondWithSavedCORSHeaders looks in the go-kit request context
// for our own CORS headers. (Stored with our context key in
// saveCORSHeadersIntoContext.)
//
// This is designed to be added as a ServerOption in our main http handler.
func respondWithSavedCORSHeaders() httptransport.ServerResponseFunc {
	return func(ctx context.Context, w http.ResponseWriter) context.Context {
		v, ok := ctx.Value(contextKey).(string)
		if ok && v != "" {
			moovhttp.SetAccessControlAllowHeaders(w, v) // set CORS headers
		}
		return ctx
	}
}

// preflightHandler captures Corss Origin Resource Sharing (CORS) requests
// by looking at all OPTIONS requests for the Origin header, parsing that
// and responding back with the other Access-Control-Allow-* headers.
//
// Docs: https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS
func preflightHandler(options []httptransport.ServerOption) http.Handler {
	return httptransport.NewServer(
		endpoint.Nop,
		httptransport.NopRequestDecoder,
		func(_ context.Context, w http.ResponseWriter, _ interface{}) error {
			if v := w.Header().Get("Content-Type"); v == "" {
				w.Header().Set("Content-Type", "text/plain")
			}
			return nil
		},
		options...,
	)
}

func MakeHTTPHandler(s Service, repo Repository, kitlog gokitlog.Logger) http.Handler {
	logger := log.NewLogger(kitlog)

	r := mux.NewRouter()
	options := []httptransport.ServerOption{
		httptransport.ServerErrorLogger(kitlog),
		httptransport.ServerErrorEncoder(encodeError),
		httptransport.ServerBefore(saveCORSHeadersIntoContext()),
		httptransport.ServerAfter(respondWithSavedCORSHeaders()),
	}

	// HTTP Methods
	r.Methods("OPTIONS").Handler(preflightHandler(options)) // CORS pre-flight handler
	r.Methods("GET").Path("/ping").HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		moovhttp.SetAccessControlAllowHeaders(w, r.Header.Get("Origin"))
		w.Header().Set("Content-Type", "text/plain")
		w.Write([]byte("PONG"))
	})
	r.Methods("GET").Path("/files").Handler(httptransport.NewServer(
		getFilesEndpoint(s),
		decodeGetFilesRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/files/{id}/build").Handler(httptransport.NewServer(
		buildFileEndpoint(s, repo, logger),
		decodeBuildFileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/files/{fileID}").Handler(httptransport.NewServer(
		createFileEndpoint(s, repo, logger),
		decodeCreateFileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/files/{id}").Handler(httptransport.NewServer(
		getFileEndpoint(s, logger),
		decodeGetFileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/files/{id}/contents").Handler(httptransport.NewServer(
		getFileContentsEndpoint(s, logger),
		decodeGetFileContentsRequest,
		encodeTextResponse,
		options...,
	))
	r.Methods("GET").Path("/files/{id}/validate").Handler(httptransport.NewServer(
		validateFileEndpoint(s, logger),
		decodeValidateFileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/files/{id}/validate").Handler(httptransport.NewServer(
		validateFileEndpoint(s, logger),
		decodeValidateFileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/files/{id}").Handler(httptransport.NewServer(
		deleteFileEndpoint(s, logger),
		decodeDeleteFileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/files/{fileID}/batches").Handler(httptransport.NewServer(
		createBatchEndpoint(s, logger),
		decodeCreateBatchRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/files/{fileID}/batches").Handler(httptransport.NewServer(
		getBatchesEndpoint(s, logger),
		decodeGetBatchesRequest,
		encodeResponse,
		options...,
	))
	r.Methods("GET").Path("/files/{fileID}/batches/{batchID}").Handler(httptransport.NewServer(
		getBatchEndpoint(s, logger),
		decodeGetBatchRequest,
		encodeResponse,
		options...,
	))
	r.Methods("DELETE").Path("/files/{fileID}/batches/{batchID}").Handler(httptransport.NewServer(
		deleteBatchEndpoint(s, logger),
		decodeDeleteBatchRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/files/{fileID}/balance").Handler(httptransport.NewServer(
		balanceFileEndpoint(s, repo, logger),
		decodeBalanceFileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/files/{fileID}/segment").Handler(httptransport.NewServer(
		segmentFileIDEndpoint(s, repo, logger),
		decodeSegmentFileIDRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/segment").Handler(httptransport.NewServer(
		segmentFileEndpoint(s, repo, logger),
		decodeSegmentFileRequest,
		encodeResponse,
		options...,
	))
	r.Methods("POST").Path("/files/{fileID}/flatten").Handler(httptransport.NewServer(
		flattenBatchesEndpoint(s, repo, logger),
		decodeFlattenBatchesRequest,
		encodeResponse,
		options...,
	))
	return r
}

// errorer is implemented by all concrete response types that may contain
// errors. There are a few well-known values which are used to change the
// HTTP response code without needing to trigger an endpoint (transport-level)
// error.
type errorer interface {
	error() error
}

// counter is implemented by any concrete response types that may contain
// some arbitrary count information.
type counter interface {
	count() int
}

// marshalStructWithError converts a struct into a JSON response with all fields of the struct
// with our expected error formats.
//
// There are a few reasons we need to do this.
//  1. base.ErrorList marshals to an object which breaks the string format our API declares
//     and isn't caught when we pass around interface{} values.
//  2. We want to return additional fields of structs (such as in createFileEndpoint)
func marshalStructWithError(in interface{}, w http.ResponseWriter) error {
	v := reflect.ValueOf(in)
	out := make(map[string]interface{}, v.NumField())

	for i := 0; i < v.NumField(); i++ {
		name := v.Type().Field(i).Name
		value := v.Field(i).Interface()

		if err, ok := value.(error); ok {
			out["error"] = err.Error()
		} else {
			out[name] = value
		}
	}

	return json.NewEncoder(w).Encode(out)
}

// encodeResponse is the common method to encode all response types to the
// client. I chose to do it this way because, since we're using JSON, there's no
// reason to provide anything more specific. It's certainly possible to
// specialize on a per-response (per-method) basis.
func encodeResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
	if e, ok := response.(errorer); ok && e.error() != nil {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		w.WriteHeader(codeFrom(e.error()))
		return marshalStructWithError(response, w)
	}

	// Used for pagination
	if e, ok := response.(counter); ok {
		w.Header().Set("X-Total-Count", strconv.Itoa(e.count()))
	}

	// Don't overwrite a header (i.e. called from encodeTextResponse)
	if v := w.Header().Get("Content-Type"); v == "" {
		w.Header().Set("Content-Type", "application/json; charset=utf-8")
		// Only write json body if we're setting response as json
		return json.NewEncoder(w).Encode(response)
	}
	return nil
}

// encodeTextResponse will marshal response into the HTTP Response
// This method is designed text/plain content-types and expects response
// to be an io.Reader.
func encodeTextResponse(ctx context.Context, w http.ResponseWriter, response interface{}) error {
	if r, ok := response.(io.Reader); ok {
		w.Header().Set("Content-Type", "text/plain")
		w.WriteHeader(http.StatusOK)
		_, err := io.Copy(w, r)
		return err
	}
	return nil
}

// encodeError JSON encodes the supplied error
func encodeError(_ context.Context, err error, w http.ResponseWriter) {
	if err == nil {
		err = ErrFoundABug
	}
	w.Header().Set("Content-Type", "application/json; charset=utf-8")
	w.WriteHeader(codeFrom(err))
	json.NewEncoder(w).Encode(map[string]interface{}{
		"error": err.Error(),
	})
}

func codeFrom(err error) int {
	if err == nil {
		return http.StatusOK
	}

	errString := fmt.Sprintf("%#v", err)
	if el, ok := err.(base.ErrorList); ok {
		errString = el.Error()
	}
	switch {
	case
		strings.Contains(errString, errInvalidFile.Error()), // This branch comes from validateFileEndpoint
		strings.Contains(errString, "*ach.FieldError"),
		strings.Contains(errString, "*ach.BatchError"),
		strings.Contains(errString, "*ach.ErrFile"),
		strings.Contains(errString, "ach.RecordWrongLengthErr"),
		strings.Contains(errString, "FieldName"): // FileFromJSON
		return http.StatusBadRequest
	}

	switch err {
	case ErrNotFound:
		return http.StatusNotFound
	case ErrAlreadyExists:
		return http.StatusBadRequest
	default:
		return http.StatusInternalServerError
	}
}


text:
#include "set/hdr_intrusive_cuckoo_set.h"
#include <cds/intrusive/cuckoo_set.h>

#include "set/intrusive_cuckoo_set_common.h"
#include "../unit/print_cuckoo_stat.h"

namespace set {

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_basehook_equal()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::list, 0 > >  item_type;
        struct set_traits : public ci::cuckoo::traits {
            typedef co::hash_tuple< hash1, hash2 > hash;
            typedef set::equal_to<item_type> equal_to;
        };
        typedef ci::CuckooSet< item_type, set_traits > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_basehook_equal()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::vector<4>, 0 > >  item_type;

        struct set_traits : public ci::cuckoo::traits {
            typedef ci::cuckoo::base_hook< ci::cuckoo::probeset_type< item_type::probeset_type >> hook;
            typedef co::hash_tuple< hash1, hash2 > hash;
            typedef set::equal_to<item_type> equal_to;
        };
        typedef ci::CuckooSet< item_type, set_traits > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_basehook_sort_cmp()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::list, 0 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_basehook_sort_cmp()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::vector<4>, 0 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_basehook_sort_less()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::list, 0 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_basehook_sort_less()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::vector<4>, 0 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_basehook_sort_cmpmix()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::list, 0 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_basehook_sort_cmpmix()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::vector<8>, 0 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_basehook_sort_cmpmix_stat()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::vector<8>, 0 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
                ,co::stat< ci::cuckoo::stat >
            >::type
        > set_type;

        unsigned int nProbesetSize = set_type::node_type::probeset_size ? set_type::node_type::probeset_size : 4;
        set_type s( 256, nProbesetSize, nProbesetSize / 2 );
        test_with( s );
        CPPUNIT_MSG( s.statistics() << s.mutex_policy_statistics() );
    }

    // base hook, store hash
    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_basehook_equal_storehash()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::list, 2 > >  item_type;
        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                    ,ci::cuckoo::store_hash< item_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::equal_to< equal_to<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_basehook_equal_storehash()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::vector<4>, 2 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                    ,ci::cuckoo::store_hash< item_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::equal_to< equal_to<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_basehook_sort_cmp_storehash()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::list, 2 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                    ,ci::cuckoo::store_hash< item_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_basehook_sort_cmp_storehash()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::vector<4>, 2 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                    ,ci::cuckoo::store_hash< item_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_basehook_sort_less_storehash()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::list, 2 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                    ,ci::cuckoo::store_hash< item_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_basehook_sort_less_storehash()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::vector<4>, 2 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                    ,ci::cuckoo::store_hash< item_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_basehook_sort_cmpmix_storehash()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::list, 2 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                    ,ci::cuckoo::store_hash< item_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_basehook_sort_cmpmix_storehash()
    {
        typedef IntrusiveCuckooSetHdrTest::base_item< ci::cuckoo::node< ci::cuckoo::vector<8>, 2 > >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::base_hook<
                    ci::cuckoo::probeset_type< item_type::probeset_type >
                    ,ci::cuckoo::store_hash< item_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    // Member hook
    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_memberhook_equal()
    {
        typedef IntrusiveCuckooSetHdrTest::member_item< ci::cuckoo::node< ci::cuckoo::list, 0 > >  item_type;
        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember)> >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::equal_to< equal_to<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_memberhook_equal()
    {
        typedef ci::cuckoo::node< ci::cuckoo::vector<4>, 0 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::equal_to< equal_to<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_memberhook_sort_cmp()
    {
        typedef ci::cuckoo::node< ci::cuckoo::list, 0 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_memberhook_sort_cmp()
    {
        typedef ci::cuckoo::node< ci::cuckoo::vector<4>, 0 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_memberhook_sort_less()
    {
        typedef ci::cuckoo::node< ci::cuckoo::list, 0 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_memberhook_sort_less()
    {
        typedef ci::cuckoo::node< ci::cuckoo::vector<4>, 0 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_memberhook_sort_cmpmix()
    {
        typedef ci::cuckoo::node< ci::cuckoo::list, 0 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_memberhook_sort_cmpmix()
    {
        typedef ci::cuckoo::node< ci::cuckoo::vector<8>, 0 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    // member hook, store hash
    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_memberhook_equal_storehash()
    {
        typedef ci::cuckoo::node< ci::cuckoo::list, 2 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;
        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                    ,ci::cuckoo::store_hash< node_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::equal_to< equal_to<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_memberhook_equal_storehash()
    {
        typedef ci::cuckoo::node< ci::cuckoo::vector<4>, 2 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                    ,ci::cuckoo::store_hash< node_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::equal_to< equal_to<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_memberhook_sort_cmp_storehash()
    {
        typedef ci::cuckoo::node< ci::cuckoo::list, 2 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                    ,ci::cuckoo::store_hash< node_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_memberhook_sort_cmp_storehash()
    {
        typedef ci::cuckoo::node< ci::cuckoo::vector<4>, 2 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                    ,ci::cuckoo::store_hash< node_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_memberhook_sort_less_storehash()
    {
        typedef ci::cuckoo::node< ci::cuckoo::list, 2 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                    ,ci::cuckoo::store_hash< node_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_memberhook_sort_less_storehash()
    {
        typedef ci::cuckoo::node< ci::cuckoo::vector<4>, 2 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                    ,ci::cuckoo::store_hash< node_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_list_memberhook_sort_cmpmix_storehash()
    {
        typedef ci::cuckoo::node< ci::cuckoo::list, 2 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                    ,ci::cuckoo::store_hash< node_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

    void IntrusiveCuckooSetHdrTest::Cuckoo_striped_vector_memberhook_sort_cmpmix_storehash()
    {
        typedef ci::cuckoo::node< ci::cuckoo::vector<8>, 2 > node_type;
        typedef IntrusiveCuckooSetHdrTest::member_item< node_type >  item_type;

        typedef ci::CuckooSet< item_type
            ,ci::cuckoo::make_traits<
                ci::opt::hook< ci::cuckoo::member_hook< offsetof(item_type, hMember),
                    ci::cuckoo::probeset_type< node_type::probeset_type >
                    ,ci::cuckoo::store_hash< node_type::hash_array_size >
                > >
                ,co::hash< std::tuple< hash1, hash2 > >
                ,co::less< IntrusiveCuckooSetHdrTest::less<item_type> >
                ,co::compare< IntrusiveCuckooSetHdrTest::cmp<item_type> >
            >::type
        > set_type;

        test_cuckoo<set_type>();
    }

}   // namespace set

CPPUNIT_TEST_SUITE_REGISTRATION(set::IntrusiveCuckooSetHdrTest);


text:
select * from users
where name = '{{name}}'
limit 1


text:
<?php

namespace Todays\Libs\ShortUrl;

abstract class Environment {
	abstract public function hostname();
}


text:
title: "Tiistain tunnille"
tags: läksyt rub6.4
---

Ei läksyjä. Jos haluat, kirjallisuussanastoa voi jo täytellä.


text:
const gapi = {
  client: {
    request: () => {
      return Promise.resolve("");
    }
  },
  requestPeople: {}
};

console.log(gapi.client.request());

module.exports = gapi;


text:
package org.apache.camel.component.file.remote.integration;

import java.util.concurrent.TimeUnit;

import org.apache.camel.Exchange;
import org.apache.camel.builder.RouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;

import static org.apache.camel.test.junit5.TestSupport.assertDirectoryEquals;
import static org.awaitility.Awaitility.await;

public class FtpConsumerRelativeFileNameIT extends FtpServerTestSupport {

    private String getFtpUrl() {
        return "ftp://admin@localhost:{{ftp.server.port}}"
               + "/out/filename-consumer?password=admin&recursive=true&sortBy=file:name";
    }

    @Override
    @BeforeEach
    public void setUp() throws Exception {
        super.setUp();
        sendFile(getFtpUrl(), "Hello World", "out/filename-consumer-hello.txt");
        sendFile(getFtpUrl(), "Bye World", "out/filename-consumer-bye.txt");
    }

    @Override
    protected RouteBuilder createRouteBuilder() {
        return new RouteBuilder() {
            @Override
            public void configure() {
                from(getFtpUrl()).to("mock:result");
            }
        };
    }

    @Test
    public void testValidFilenameOnExchange() throws Exception {
        MockEndpoint mock = getMockEndpoint("mock:result");
        mock.expectedMessageCount(2);
        // should have file name header set
        mock.allMessages().header(Exchange.FILE_NAME).isNotNull();

        MockEndpoint.assertIsSatisfied(context);

        // give time for ftp consumer to disconnect
        // and expect name to contain target/filename-consumer-XXX.txt
        await().atMost(2, TimeUnit.SECONDS)
                .untilAsserted(() -> isExpectedFile(mock, "out/filename-consumer-bye.txt", 0));
        isExpectedFile(mock, "out/filename-consumer-hello.txt", 1);
    }

    private void isExpectedFile(MockEndpoint mock, String s, int exchangeNumber) {
        assertDirectoryEquals(s,
                mock.getReceivedExchanges().get(exchangeNumber).getIn().getHeader(Exchange.FILE_NAME, String.class));
    }

}


text:
<!DOCTYPE html>

        <meta charset="UTF-8">
        <title>Zalora Capture</title>

        <link rel="stylesheet" type="text/css" href="../bower_components/bootstrap/dist/css/bootstrap.min.css">
        <link rel="stylesheet" type="text/css" href="../bower_components/font-awesome/css/font-awesome.min.css">
        <link rel="stylesheet" type="text/css" href="../bower_components/angular/angular-csp.css">
        <link rel="stylesheet" type="text/css" href="css/common.css">
        <link rel="stylesheet" type="text/css" href="css/report.css">

                                Clear

                                Export

                    <svg id="draw-canvas" zc-canvas class="{{dvm.activeTool.params.id}}"></svg>
                    <div type="text"
                        ng-show="dvm.textLayer.isShow"
                        ng-cloak
                        name="text-layer"
                        id="text-layer"
                        style="color: {{dvm.activeColor}}; border-color: {{dvm.activeColor}}; top: {{dvm.textLayer.top - 23}}px; left: {{dvm.textLayer.left - 17}}px"
                        ng-model="dvm.textlayerData"
                        zc-text-layer
                        zc-focus="dvm.textLayer.focus"
                        ng-blur="dvm.textLayer.focus = false"
                        contenteditable
                        zc-contenteditable>

                <form id="create-new-issue" method="POST" role="form" ng-show="!vm.loading" ng-cloak ng-submit="vm.saveIssue()">
                    <legend>Create new issue</legend>

                          {{vm.newIssue.key}} created!
                        <button ng-click="vm.newIssue = false;" type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

                        Errors:

                             - {{err}}

                        <button ng-click="vm.issueError = false;" type="button" class="close" data-dismiss="alert" aria-label="Close">×</button>

                        Project *
                        <select name="project" id="project" class="form-control" required="required" ng-model="vm.selected['projects']" ng-options="project.id as project.name for project in vm.info['projects']" ng-show="vm.info['projects'].length">
                        </select>

No available projects! Please create your own project to continue!

                        Issue Type *
                        <select name="type" id="type" class="form-control" required="required" ng-model="vm.selected['issueTypes']" ng-options="type.id as type.name for type in vm.info['issueTypes']">
                        </select>

                        Priority *
                        <select name="priority" id="priority" class="form-control" required="required" ng-model="vm.selected['priorities']" ng-options="priority.id as priority.name for priority in vm.info['priorities']">
                        </select>

                        Template *
                        <select name="priority" id="priority" class="form-control" required="required" ng-model="vm.selected['template']" ng-options="template.id as template.name for template in vm.templates" ng-change="vm.onTemplateChange()"></select>

                        Summary *
                        <textarea ng-model="vm.summary" name="summary" id="summary" class="form-control" required="required" rows="2"></textarea>

                        Description *
                        <textarea ng-model="vm.description" name="description" id="description" class="form-control" required="required" rows="10"></textarea>

                        Attach files *
                        <input type="file" nv-file-select="" uploader="vm.uploader" multiple>

                                    {{item.file.name}}

                                     remove

                        User actions
                        <textarea ng-model="actions" name="actions" id="actions" class="form-control" rows="6" ></textarea>

                                <input type="checkbox" value="" checked="checked" ng-model="vm.includeEnv">
                                Include environment data

                                <input type="checkbox" value="" checked="checked" ng-model="vm.includeConsoleLogs">
                                Include console logs

                    <button type="submit" class="btn btn-primary">Create</button>
                </form>

                    {{vm.loading}}


text:
@interface Note : NSObject

@property (strong, nonatomic) NSString * title;
@property (strong, nonatomic) NSString * content;

- (id) initWithTitle:(NSString *) title content:(NSString *) content;
@end


text:
<?php
/**
 * Requests for service those are not intent in login protection, will be placed here. This is the other way to call backend service except ajax.php.
 * - Process login, save userId, wxAccountId, cred in session, append to reuqest automatically.
 * - Create and destory session in this page.
 * - Process register.
 */
session_start();
require_once ("config.php");
require_once (__DIR__ . "/bootstrap.php");
use \Httpful\Request;

if (isset($_GET["logout"])) {
	session_destroy();
	if (isset($_GET["ctx"])) {
	    $url = $_GET["ctx"]."/Login.html";
	} else {
	    $url = "../Login.html";
	}
	header("Location: ".$url);
} else if (isset($_GET["register"])) {
	// user register.
	$data = json_encode($_POST);
	//TODO:J implement signature generation, will resolve the security issue.
	$url = SERVICEURL . "/user";
	$response = Request::post($url, $data) -> sendsJson() -> send();
} else {
	// handle normal login case.
	$email = $_POST["email"];
	$password = $_POST["password"];

	//TODO:J implement signature generation, will resolve the security issue.
	$url = SERVICEURL . "/credential?email=" . $email . "&password=" . $password;

	// send out request.
	$response = Request::get($url) -> send();
	// save sessions.
	if ($response -> body -> success) {
		$_SESSION["userId"] = $response -> body -> data -> userId;
		$_SESSION["cred"] = $response -> body -> data -> cred;
		$_SESSION["modules"] = $response -> body -> data -> modules;
	}
}
// send response to client.
header("Content-Type:application/json;charset=utf-8");
echo json_encode($response -> body);
?>


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>nl.esciencecenter.xenon.adaptors.torque (Xenon 1.2.2 API for Xenon developers)</title>
<meta name="date" content="2017-05-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

nl.esciencecenter.xenon.adaptors.torque

Classes

TorqueAdaptor

TorqueJobScriptGenerator

TorqueSchedulerConnection

TorqueSchedulerConnectionFactory

TorqueXmlParser


text:
/*

 Ionize main menu intialization

*/

var Ionize = (Ionize || {});

Ionize.initializeDesktop = function(){

	MUI.create({
		'control':'MUI.Desktop',
		'id':'desktop',
		'taskbar':true,
		'content':[
			{name:'header', url: admin_url + 'desktop/get_header'},
			{name:'taskbar'},
			{name:'content',columns:[
				{id: 'sideColumn', placement: 'left', width: 280, resizeLimit: [222, 600],
					panels:[
						{
							id: 'structurePanel',
							title: '',
							cssClass: 'panelAlt',
							content: [
								{url: admin_url + 'tree'},
								{
									name: 'toolbox',
									position: 'header',
									cssClass: 'left',
									divider: false,
									url: admin_url + 'desktop/get/toolboxes/structure_toolbox'
								}
							]
						}
					]
				},
				{id: 'mainColumn',	placement: 'main', resizeLimit: [100, 300],
					panels:[
					{
						id: 'mainPanel',
						title: Lang.get('ionize_title_welcome'),
						content: [
							{url: admin_url + 'dashboard'},
							{
								name: 'toolbox',
								position: 'header',
								url: admin_url + 'desktop/get/toolboxes/empty_toolbox'
							}
						],
						collapsible: false,
						onLoaded: function()
						{
						}
	//					,onResize: Ionize.updateResizeElements
					}]
				}
			]}
		]
	});
};

// Initialize MochaUI when the DOM is ready
window.addEvent('load', function()
{
	MUI.initialize({path:{root:theme_url + 'javascript/mochaui/'}});
	MUI.register('MUI.Windows', MUI.Windows);

	Ionize.initializeDesktop();

	Ionize.User.initialize();

//	console.log(Ionize.User.getUser());
//	console.log(Ionize.User.getGroupLevel());

});


text:
<?php

namespace Socks;

use React\Dns\Resolver\Resolver;
use React\EventLoop\LoopInterface;
use React\SocketClient\Connector;

class Factory
{
    public function __construct(LoopInterface $loop, Resolver $resolver)
    {
        $this->loop = $loop;
        $this->resolver = $resolver;
    }

    public function createClient($socksHost, $socksPort)
    {
        $connector = $this->createConnector();
        return new Client($this->loop, $connector, $this->resolver, $socksHost, $socksPort);
    }

    public function createServer($socket)
    {
        $connector = $this->createConnector();
        return new Server($socket, $this->loop, $connector);
    }

    protected function createConnector()
    {
        return new Connector($this->loop, $this->resolver);
    }
}


text:
	<title>Nassim Khadem's panel show appearances</title>

	<link rel="stylesheet" media="all" href="../style.css" type="text/css"/>

Nassim Khadem's panel show appearances

Nassim Khadem has appeared in 3 episodes between 2017-2018. Note that these appearances may be for more than one person if multiple people have the same name.

2017

2018

2018-05-29 / The Drum

2018-04-09 / The Drum

2017-08-10 / The Drum


text:
using YAF.Lucene.Net.Support;
using System;
using System.Runtime.CompilerServices;

namespace YAF.Lucene.Net.Store
{

    /// <summary>
    /// Base implementation class for buffered <see cref="IndexOutput"/>. </summary>
    public abstract class BufferedIndexOutput : IndexOutput
    {
        /// <summary>
        /// The default buffer size in bytes (<see cref="DEFAULT_BUFFER_SIZE"/>). </summary>
        public const int DEFAULT_BUFFER_SIZE = 16384;

        private readonly int bufferSize;
        private byte[] buffer;
        private long bufferStart = 0; // position in file of buffer
        private int bufferPosition = 0; // position in buffer
        private readonly CRC32 crc;

        /// <summary>
        /// Creates a new <see cref="BufferedIndexOutput"/> with the default buffer size
        /// (<see cref="DEFAULT_BUFFER_SIZE"/> bytes see <see cref="DEFAULT_BUFFER_SIZE"/>)
        /// </summary>
        protected BufferedIndexOutput() // LUCENENET: CA1012: Abstract types should not have constructors (marked protected)
            : this(DEFAULT_BUFFER_SIZE)
        {
        }

        /// <summary>
        /// Creates a new <see cref="BufferedIndexOutput"/> with the given buffer size. </summary>
        /// <param name="bufferSize"> the buffer size in bytes used to buffer writes internally. </param>
        /// <exception cref="ArgumentException"> if the given buffer size is less or equal to <c>0</c> </exception>
        protected BufferedIndexOutput(int bufferSize) // LUCENENET: CA1012: Abstract types should not have constructors (marked protected)
            : this(bufferSize, new CRC32())
        { }

        // LUCENENET specific - added constructor overload so FSDirectory can still subclass BufferedIndexOutput, but
        // utilize its own buffer, since FileStream is already buffered in .NET.
        private protected BufferedIndexOutput(int bufferSize, CRC32 crc)
        {
            if (bufferSize <= 0)
            {
                throw new ArgumentOutOfRangeException(nameof(bufferSize), "bufferSize must be greater than 0 (got " + bufferSize + ")"); // LUCENENET specific - changed from IllegalArgumentException to ArgumentOutOfRangeException (.NET convention)
            }
            this.bufferSize = bufferSize;
            // LUCENENET: We lazy-load the buffer, so we don't force all subclasses to allocate it
            this.crc = crc;
        }

        public override void WriteByte(byte b)
        {
            if (buffer is null) buffer = new byte[bufferSize]; // LUCENENET: Lazy-load the buffer, so we don't force all subclasses to allocate it
            if (bufferPosition >= bufferSize)
            {
                Flush();
            }
            buffer[bufferPosition++] = b;
        }

        public override void WriteBytes(byte[] b, int offset, int length)
        {
            if (buffer is null) buffer = new byte[bufferSize]; // LUCENENET: Lazy-load the buffer, so we don't force all subclasses to allocate it
            int bytesLeft = bufferSize - bufferPosition;
            // is there enough space in the buffer?
            if (bytesLeft >= length)
            {
                // we add the data to the end of the buffer
                Arrays.Copy(b, offset, buffer, bufferPosition, length);
                bufferPosition += length;
                // if the buffer is full, flush it
                if (bufferSize - bufferPosition == 0)
                {
                    Flush();
                }
            }
            else
            {
                // is data larger then buffer?
                if (length > bufferSize)
                {
                    // we flush the buffer
                    if (bufferPosition > 0)
                    {
                        Flush();
                    }
                    // and write data at once
                    crc.Update(b, offset, length);
                    FlushBuffer(b, offset, length);
                    bufferStart += length;
                }
                else
                {
                    // we fill/flush the buffer (until the input is written)
                    int pos = 0; // position in the input data
                    int pieceLength;
                    while (pos < length)
                    {
                        pieceLength = (length - pos < bytesLeft) ? length - pos : bytesLeft;
                        Arrays.Copy(b, pos + offset, buffer, bufferPosition, pieceLength);
                        pos += pieceLength;
                        bufferPosition += pieceLength;
                        // if the buffer is full, flush it
                        bytesLeft = bufferSize - bufferPosition;
                        if (bytesLeft == 0)
                        {
                            Flush();
                            bytesLeft = bufferSize;
                        }
                    }
                }
            }
        }

        /// <inheritdoc/>
        [MethodImpl(MethodImplOptions.NoInlining)]
        public override void Flush()
        {
            if (buffer is null) return; // LUCENENET: Lazy-load the buffer, so we don't force all subclasses to allocate it
            crc.Update(buffer, 0, bufferPosition);
            FlushBuffer(buffer, bufferPosition);
            bufferStart += bufferPosition;
            bufferPosition = 0;
        }

        /// <summary>
        /// Expert: implements buffer write.  Writes bytes at the current position in
        /// the output. </summary>
        /// <param name="b"> the bytes to write </param>
        /// <param name="len"> the number of bytes to write </param>
        private void FlushBuffer(byte[] b, int len)
        {
            FlushBuffer(b, 0, len);
        }

        /// <summary>
        /// Expert: implements buffer write.  Writes bytes at the current position in
        /// the output. </summary>
        /// <param name="b"> the bytes to write </param>
        /// <param name="offset"> the offset in the byte array </param>
        /// <param name="len"> the number of bytes to write </param>
        protected internal abstract void FlushBuffer(byte[] b, int offset, int len);

        /// <inheritdoc/>
        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                Flush();
            }
        }

        public override long Position => bufferStart + bufferPosition; // LUCENENET specific: Renamed from getFilePointer() to match FileStream

        [Obsolete("(4.1) this method will be removed in Lucene 5.0")]
        public override void Seek(long pos)
        {
            Flush();
            bufferStart = pos;
        }

        public override abstract long Length { get; }

        /// <summary>
        /// Returns size of the used output buffer in bytes.
        /// </summary>
        public int BufferSize => bufferSize;

        public override long Checksum
        {
            get
            {
                Flush();
                return crc.Value;
            }
        }
    }
}


text:
package ru.job4j.monitore_synchronizy.list;

import java.util.Arrays;
import java.util.Iterator;
import java.util.NoSuchElementException;

/**
 * SynchronizedArrayContainer.
 *
 * @param <E> type of elements.
 * @author Ayuzyak
 * @version 1.0
 * @since 11.09.2017
 */
public class SynchronizedArrayContainer<E> implements Iterable<E> {

    /**
     * Array of objects.
     */
    private Object[] arr;

    /**
     * Number of array elements.
     */
    private int size = 0;

    /**
     * Load capacity.
     */
    private int capacity;

    /**
     * Class constructor.
     */
    public SynchronizedArrayContainer() {
        capacity = 10;
        this.arr = new Object[capacity];
    }

    /**
     * method for increase array's capacity.
     *
     * @return true if array is increased.
     */
    private boolean increaseCapacity() {
        if (size > capacity * 0.7) {
            Object[] newArr = new Object[capacity * 2];
            System.arraycopy(arr, 0, newArr, 0, size);
            this.arr = newArr;
            capacity *= 2;
            return true;
        } else {
            return false;
        }
    }

    /**
     * Getting element from array.
     *
     * @param index of element for getting.
     * @return element.
     */
    @SuppressWarnings(value = "unchecked")
    public synchronized E get(int index) {
        if (index >= this.size || index < 0) {
            throw new IndexOutOfBoundsException();
        }
        return (E) arr[index];
    }

    /**
     * Update reference by index to new element.
     *
     * @param index   for updating.
     * @param element for setting.
     */
    public synchronized void update(int index, E element) {
        if (index >= this.size || index < 0) {
            throw new IndexOutOfBoundsException();
        }
        arr[index] = element;
    }

    /**
     * Getter for size.
     *
     * @return size.
     */
    public synchronized int getSize() {
        return size;
    }

    /**
     * Add element.
     *
     * @param element element for adding.
     */
    public synchronized void add(E element) {
        increaseCapacity();
        arr[size++] = element;
    }

    /**
     * delete element.
     *
     * @param index of element for delete it.
     * @return deleted element.
     */
    @SuppressWarnings(value = "unchecked")
    public synchronized E delete(int index) {
        if (index >= this.size || index < 0) {
            throw new IndexOutOfBoundsException();
        }
        E delElement = (E) arr[index];
        System.arraycopy(arr, index + 1, arr, index, this.size - index - 1);
        arr[--size] = null;
        return delElement;
    }

    /**
     * Check array for contain element.
     *
     * @param elem for check.
     * @return true if array contains element.
     */
    public synchronized boolean contains(E elem) {
        boolean isE = false;
        for (int i = 0; i < getSize(); i++) {
            if (elem.equals(get(i))) {
                isE = true;
                i = getSize();
            }
        }
        return isE;
    }

    /**
     * Get iterator for passing container.
     *
     * @return iterator.
     */
    @Override
    public synchronized Iterator<E> iterator() {
        return new ArrayIterator();
    }

    /**
     * Inner class implements Iterator.
     */
    private class ArrayIterator implements Iterator<E> {
        /**
         * Copy of arr.
         */
        private Object[] copyArray;

        /**
         * Constructor for ArrayIterator.
         * Copy array for iterate.
         */
        ArrayIterator() {
            copyArray = Arrays.copyOf(arr, arr.length);
        }

        /**
         * Cursor for passing.
         */
        private int cursor = 0;

        /**
         * Check next element.
         *
         * @return true if iterator has next number.
         */
        @Override
        public boolean hasNext() {
            return cursor < copyArray.length;
        }

        /**
         * Get next element.
         *
         * @return next element.
         */
        @Override
        @SuppressWarnings(value = "unchecked")
        public E next() {
            E elem;
            if (hasNext()) {
                elem = (E) copyArray[cursor++];
            } else {
                throw new NoSuchElementException();
            }
            return elem;
        }
    }
}