text:
\documentclass[a4paper,twocolumn]{article}

\usepackage[english]{babel}
\usepackage[utf8]{inputenc}
\usepackage{graphicx}
\usepackage{fullpage}

\usepackage[small]{titlesec}
% patch titlesec bug of not showing (sub)title numbering http://tex.stackexchange.com/a/300259
\usepackage{etoolbox}
\makeatletter
\patchcmd{\ttlh@hang}{\parindent\z@}{\parindent\z@\leavevmode}{}{}
\patchcmd{\ttlh@hang}{\noindent}{}{}{}
\makeatother

\makeatletter
\newcommand{\thickhline}{%
    \noalign {\ifnum 0=`}\fi \hrule height 1pt
    \futurelet \reserved@a \@xhline
}
\makeatother

\newcommand*\mean[1]{\overline{#1}}

\title{Convolutional Neural Fabrics $-$ summary}
\author{Matěj Nikl}

\begin{document}
\maketitle
\noindent
Convolutional Neural Fabrics (CNFs) is a architecture for embedding an exponentially large number of CNN architectures (via massive parameter sharing). It is intended as a step aside from the conventional CNN model architecture selection problem $-$  it is not trying to solve it, instead it offers the opportunity for the fabrics to learn/select the most appropriate model (or even ensemble of models) within itself by standard back-propagation algorithm, leaving only the hyper-parameters of number of layers and channels up to us.
Other hyper-parameters, which are being ``set'' automatically by embedding in the fabrics are:
\begin{itemize}
    \item filter size per layer
    \item stride per layer
    \item number of pooling vs. convolutional layers
    \item type of pooling operator per layer
    \item size of the pooling regions
    \item ordering of pooling and convolutional layers
    \item channel connectivity pattern between layers
    \item type of activation (ReLU vs MaxOut)
\end{itemize}

% \section{Defining the Fabric}

\begin{figure}[!h]
    \includegraphics[width=\columnwidth]{fabrics1.png}
    \caption{Trellis embedding of two seven-layer CNNs. Trellis nodes receiving the input and producing output are encircled. All edges are oriented to the right, down in the first layer, and towards the output in the last layer. The channel dimension of the 3D trellis is omitted for clarity.}
\end{figure}

\section{Making sense of the Fabrics}
The Fabrics consist of a 3D trellis that connects response maps at different layers, scales, and channels with a sparse homogeneous local connectivity pattern.
Each node in the trellis represents a response map with the same number of dimensions as the input signal.

\subsection{The trellis structure}
It is spanned by three axes:
\begin{enumerate}
    \item a \textbf{layer} axis $-$ along which all edges advance, is analogous to the depth axis of a CNN
    \item a \textbf{scale} axis $-$ along which response maps of different resolutions are organized from fine to coarse
    \item a \textbf{channel} axis $-$ along which different response maps of the same scale and layer are organized
\end{enumerate}

Each node is connected to a 3 x 3 scale-channel neighborhood in the previous layer, i.e. channel $c$ at scale $s$ receives input from channels $\{c-1, c, c+1\}$ at scales $\{s-1, s, s+1\}$. Input from a finer scale is obtained via strided convolution, and input from a coarser scale by convolution, after upsampling by padding zeros around the activations at the coarser level.

\subsection{Embedded architectures}
\paragraph{Re-sampling operators}
Fine-to-coarse change of the resolution of response maps is done using stride-two convolutions. Larger strides can be obtained by following multiple such edges.

\textit{Average pooling} across small regions is also a strided convolution with uniform filter weights, thus available in the trellis. Average pooling over larger areas is also available.

\textit{Bi-linear interpolation} is commonly used in deconvolutional networks. Factor-two interpolation can be represented on coarse-to-fine edges by using a filter with $1$ in the center, $1/4$ on corners, and $1/2$ elsewhere. Larger powers of two can be obtained by repetition.

\begin{figure*}[t]
    \centering
    \includegraphics[width=0.375\textwidth]{fabrics2.png}
    \hskip 1cm
    \includegraphics[width=0.5\textwidth]{fabrics3.png}
    \caption{Visualization of mean-squared filter weights (mean along weights and channels) in models learned for Part Labels (left) and MNIST (right). Layers are laid out horizontally, and scales vertically.}
\end{figure*}

{
\renewcommand{\arraystretch}{1.25}
\begin{table*}[ht]
\centering
    \begin{tabular}{l c c r c}
        \thickhline
                                          & Year & Augmentation & \# Params. & Error (\%) \\
        \hline

        Chang et al.                      & 2015 & N            & 447 K      & 0.24 \\
        Lee et al.                        & 2015 & N            &            & 0.31 \\
        Grid LSTM                         & 2016 & T            &            & 0.32 \\
        Dropconnect                       & 2013 & T+F          & 379 K      & 0.32 \\
        CKN                               & 2014 & N            &  43 K      & 0.39 \\
        Maxout                            & 2013 & N            & 420 K      & 0.45 \\
        Network in Network                & 2013 & N            &            & 0.47 \\
        \hline
        Ours: CNF-sparse (L = 16, C = 32) &      & T            & 249 K      & 0.48 \\
        Ours: CNF-dense (L = 8, C = 64)   &      & T            & 5.3 M      & 0.33 \\
        \thickhline
    \end{tabular}
    \caption{Comparison of results with the state of the art on MNIST. Data augmentation with translation and flipping is denoted by T and F respectively, N denotes no data augmentation.}
\end{table*}
}

\paragraph{Filter sizes}
A 5 x 5 filter can be implemented by computing nine intermediate channels to obtain a vectorized version of the 3 x 3 neighborhood at each pixel. A second 3 x 3 convolution can then aggregate values across the original 5 x 5 patch, and output the desired convolution. Repetition allows to implement every filter of any desired size.

\paragraph{Ordering convolution and re-sampling}
It is up to the back-propagation algorithm to choose the desired path(s) to use $-$ by setting all, except one paths weights to zero, a particular sequence of convolutions and re-sampling operators is obtained.

\paragraph{Channel connectivity pattern}
This sparsely connected among the channel axis trellis suffices to emulate densely connected convolutional layers by copying channels, convolving them, and locally aggregating them.

\section{Principles of modularization}
The CNF architecture does not contain any standalone modules. The network itself can utilize some of its parts more, and by weight visualization it can be seen as modules being instationed, maybe even for certain purposes, however they still make up a integral, inseparable part of the network.

\section{Principles of growing}
The CNF architecture does not allow for any more growing as a conventional (C)NN does. Its purpose is not in growing, but in dynamically utilizing its trellis structure, whilst hiding away multiple hyper-parameters.

\end{document}


text:
// #include "Minuit/MnUserParametersPrint.h"

FunctionMinimum ModularFunctionMinimizer::minimize(const FCNBase& fcn, const std::vector<double>& par, const std::vector<double>& err, unsigned int stra, unsigned int maxfcn, double toler) const {

  MnUserParameterState st(par, err);
  MnFcn mfcn(fcn);
  MnStrategy strategy(stra);
  Numerical2PGradientCalculator gc(mfcn, st.trafo(), strategy);

  if(maxfcn == 0) {
	  unsigned int size = static_cast < unsigned int > ( par.size() );
//	  maxfcn = 200 + 100*par.size() + 5*par.size()*par.size();
	  maxfcn = 200 + 100*size + 5*size*size;
  }

  MinimumSeed mnseeds = seedGenerator()(mfcn, gc, st, strategy);
  return minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler);
}

FunctionMinimum ModularFunctionMinimizer::minimize(const FCNGradientBase& fcn, const std::vector<double>& par, const std::vector<double>& err, unsigned int stra, unsigned int maxfcn, double toler) const {

  MnUserParameterState st(par, err);
  MnFcn mfcn(fcn);
  MnStrategy strategy(stra);
  AnalyticalGradientCalculator gc(fcn, st.trafo());

  if(maxfcn == 0) {
	  unsigned int size = static_cast< unsigned int > ( par.size() );
//	  maxfcn = 200 + 100*par.size() + 5*par.size()*par.size();
	  maxfcn = 200 + 100*size + 5*size*size;
  }

  MinimumSeed mnseeds = seedGenerator()(mfcn, gc, st, strategy);
  return minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler);
}

FunctionMinimum ModularFunctionMinimizer::minimize(const FCNBase& fcn, const std::vector<double>& par, const std::vector<double>& cov, unsigned int nrow, unsigned int stra, unsigned int maxfcn, double toler) const {

  MnUserParameterState st(par, cov, nrow);
  MnFcn mfcn(fcn);
  MnStrategy strategy(stra);
  Numerical2PGradientCalculator gc(mfcn, st.trafo(), strategy);

  if(maxfcn == 0) {
//	  maxfcn = 200 + 100*par.size() + 5*par.size()*par.size();
	  unsigned int size = static_cast < unsigned int > ( par.size() );
	  maxfcn = 200 + 100*size + 5*size*size;
  }

  MinimumSeed mnseeds = seedGenerator()(mfcn, gc, st, strategy);
  return minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler);
}

FunctionMinimum ModularFunctionMinimizer::minimize(const FCNGradientBase& fcn, const std::vector<double>& par, const std::vector<double>& cov, unsigned int nrow, unsigned int stra, unsigned int maxfcn, double toler) const {

  MnUserParameterState st(par, cov, nrow);
  MnFcn mfcn(fcn);
  MnStrategy strategy(stra);
  AnalyticalGradientCalculator gc(fcn, st.trafo());

  if(maxfcn == 0) {
//	  maxfcn = 200 + 100*par.size() + 5*par.size()*par.size();
      unsigned int size = static_cast < unsigned int > ( par.size() );
      maxfcn = 200 + 100*size + 5*size*size;
  }

  MinimumSeed mnseeds = seedGenerator()(mfcn, gc, st, strategy);
  return minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler);
}

FunctionMinimum ModularFunctionMinimizer::minimize(const FCNBase& fcn, const MnUserParameters& upar, const MnStrategy& strategy, unsigned int maxfcn, double toler) const {

  MnUserParameterState st(upar);
  MnUserFcn mfcn(fcn, st.trafo());
  Numerical2PGradientCalculator gc(mfcn, st.trafo(), strategy);

  unsigned int npar = st.variableParameters();
  if(maxfcn == 0) maxfcn = 200 + 100*npar + 5*npar*npar;

  MinimumSeed mnseeds = seedGenerator()(mfcn, gc, st, strategy);
  return minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler);
}

FunctionMinimum ModularFunctionMinimizer::minimize(const FCNBase& fcn, const MnUserParameters& upar, const MnUserCovariance& cov, const MnStrategy& strategy, unsigned int maxfcn, double toler) const {

  MnUserParameterState st(upar, cov);
  MnUserFcn mfcn(fcn, st.trafo());
  Numerical2PGradientCalculator gc(mfcn, st.trafo(), strategy);

  unsigned int npar = st.variableParameters();
  if(maxfcn == 0) maxfcn = 200 + 100*npar + 5*npar*npar;

  MinimumSeed mnseeds = seedGenerator()(mfcn, gc, st, strategy);
  return minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler);
}

FunctionMinimum ModularFunctionMinimizer::minimize(const FCNBase& fcn, const MnUserParameterState& st, const MnStrategy& strategy, unsigned int maxfcn, double toler) const {

  MnUserFcn mfcn(fcn, st.trafo());
  Numerical2PGradientCalculator gc(mfcn, st.trafo(), strategy);

  unsigned int npar = st.variableParameters();
  if(maxfcn == 0) maxfcn = 200 + 100*npar + 5*npar*npar;
  MinimumSeed mnseeds = seedGenerator()(mfcn, gc, st, strategy);

  return minimize(mfcn, gc, mnseeds, strategy, maxfcn, toler);
}

FunctionMinimum ModularFunctionMinimizer::minimize(const MnFcn& mfcn, const GradientCalculator& gc, const MinimumSeed& seed, const MnStrategy& strategy, unsigned int maxfcn, double toler) const {

  return builder().minimum(mfcn, gc, seed, strategy, maxfcn, toler*mfcn.up());
}

redpajama_set_name: RedPajamaGithub


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

namespace iSynaptic.Modeling.Domain
{
    public interface IAggregate
    {
        object Id { get; }
        int Version { get; }

        IEnumerable<IAggregateEvent> GetUncommittedEvents();
        IEnumerable<IAggregateEvent> GetEvents();

        IAggregateSnapshot TakeSnapshot();
    }

    public interface IAggregate<out TIdentifier> : IAggregate
        where TIdentifier : IEquatable<TIdentifier>
    {
        new TIdentifier Id { get; }

        new IEnumerable<IAggregateEvent<TIdentifier>> GetUncommittedEvents();
    }
}


text:
import java.awt.Font;
import java.util.Random;

import ui.Stage;
import ui.elem.Choice;
import ui.elem.Element;
import ui.elem.Sprite;
import ui.elem.Text;
import util.Assassin;
import util.BattleHandler;
import util.EntityCreature;
import util.Item;
import util.Mother;
import util.Tank;
import util.Zombie;

public class StageBattle extends Stage {

	private DataHandler data;

	public StageBattle(DataHandler dataVar) {
		data = dataVar;
	}

    private Choice fightButton;
    private Choice ability0;
    private Choice ability1;
    private Choice ability2;
    private Choice ability3;
    private Choice runButton;

    private Text playerStat;
    private Text opponentStat;

    private Text mainDialog;

    private int scheduleCode = 0;

    private int selectedAbility = -1;

    private Item itemVar2;

    private Sprite opponentSprite;

    @Override
    public void init() {
        if(data.player == null) { this.setStage(1); return; } //if there is no player, then just start stage prologue for character creation
        itemVar2 = null; //sets the Item to null
        int abilityWidth = 150;
        ability0 = new Choice(data.player.getAbilitiesName(0)); //gets the abilities' name using a method that does just that and adds it as a new choice
        ability0.setWidth(abilityWidth);
        ability0.setDock(Choice.CENTER_SOUTH);
        ability0.setX((int) (getWidth() / 2 - ability0.getWidth() - 5));
        ability0.setY(this.getHeight() - 100 - ability0.getHeight()*2 - 10*2);
        ability1 = new Choice(data.player.getAbilitiesName(1));
        ability1.setWidth(abilityWidth);
        ability1.setDock(Choice.CENTER_SOUTH);
        ability1.setX((int) (getWidth() / 2 + 5));
        ability1.setY(this.getHeight() - 100 - ability1.getHeight()*2 - 10*2);
        ability2 = new Choice(data.player.getAbilitiesName(2));
        ability2.setWidth(abilityWidth);
        ability2.setDock(Choice.CENTER_SOUTH);
        ability2.setX((int) (getWidth() / 2 + 5));
        ability2.setY(this.getHeight() - 100 - ability2.getHeight() - 10);
        ability3 = new Choice(data.player.getAbilitiesName(3));
        ability3.setWidth(abilityWidth);
        ability3.setDock(Choice.CENTER_SOUTH);
        ability3.setX((int) (getWidth() / 2 - ability3.getWidth() - 5));
        ability3.setY(this.getHeight() - 100 - ability3.getHeight() - 10);
        fightButton = new Choice("Attack"); //creates the important attack button
        fightButton.setDock(Choice.CENTER_SOUTH);
        fightButton.setWidth(ability0.getWidth() * 2 + 5*2);
        fightButton.setX((int) (getWidth() / 2 - fightButton.getWidth() / 2));
        fightButton.setY(this.getHeight() - 100 - ability0.getHeight()*3 - 10*3);
        runButton = new Choice("Run!"); //the all powerful run method that never works
        runButton.setDock(Choice.CENTER_SOUTH);
        runButton.setWidth(ability0.getWidth() * 2 + 5*2);
        runButton.setX((int) (getWidth() / 2 - runButton.getWidth() / 2));
        runButton.setY(this.getHeight() - 100);
        playerStat = new Text("", 0, 0); //creates the stat. The player's are on the top right and the opponent's are on the bottom right
        opponentStat = new Text("", 0, 0);
        mainDialog = new Text("", 0, 100);
    	mainDialog.setFont(new Font("Arial", Font.PLAIN, 12));
    	mainDialog.setDock(Text.TRUE_CENTER);
		this.add(fightButton, ability0, ability1, ability2, ability3, runButton, playerStat, opponentStat, mainDialog);

		//the following methods check what picture should be put on the rightmost pane
		if(data.player instanceof Tank) this.add(new Sprite(data.getEntityImage(0, 0), getWidth() / 2 - 100 - 150, getHeight() / 2 - 150, 200, 200).setAnchor(Sprite.CENTER));
		else if(data.player instanceof Assassin) this.add(new Sprite(data.getEntityImage(1, 0), getWidth() / 2 - 100 - 150, getHeight() / 2 - 150, 200, 200).setAnchor(Sprite.CENTER));
		else this.add(new Sprite(data.getEntityImage(2, 0), getWidth() / 2 - 100 - 150, getHeight() / 2 - 150, 200, 200).setAnchor(Sprite.CENTER));
		playerStat.setX(getWidth() / 2 - 100 - 150);
		playerStat.setY(getHeight() / 2 + 50);
		playerStat.setDock(Text.CENTER);

		opponentSprite = new Sprite(getWidth() / 2 - 100 + 150, getHeight() / 2 - 150, 200, 200).setAnchor(Sprite.CENTER);
		if(data.opponent instanceof Zombie) {
			if(new Random().nextInt(2) == 0) opponentSprite.setImage(data.getEntityImage(4, 0)); //a random conditional to determine which one will be added
			else opponentSprite.setImage(data.getEntityImage(0, 1));
		} else if(data.source instanceof StageMotherZombie) {
			if(data.opponent instanceof Mother) opponentSprite.setImage(data.getEntityImage(4, 1));
			else {
				switch(new Random().nextInt(3)) {
					case 0: opponentSprite.setImage(data.getEntityImage(1, 1)); break;
					case 1: opponentSprite.setImage(data.getEntityImage(2, 1)); break;
					case 2: opponentSprite.setImage(data.getEntityImage(3, 1)); break;
					default: opponentSprite.setImage(data.getEntityImage(3, 0)); break;
				}
			}
		} else if(data.opponent instanceof EntityCreature) opponentSprite.setImage(data.getEntityImage(3, 0));
		this.add(opponentSprite);
		opponentStat.setX(getWidth() / 2 - 100 + 150);
		opponentStat.setY(getHeight() / 2 + 50);
		opponentStat.setDock(Text.CENTER);
		fightButton.setEnabled(false);
		runButton.setEnabled(false);
		playerTurn();
	}

    @Override
    public void choiceClicked(Element elementVar) {
        if(itemVar2 == null) {
            fightButton.setEnabled(false);
            runButton.setEnabled(false);
            ability0.setEnabled(false);
            ability1.setEnabled(false);
            ability2.setEnabled(false);
            ability3.setEnabled(false);
            Choice choiceObject = (Choice)elementVar;
            if(choiceObject == fightButton) {
                boolean flag = BattleHandler.playerTurn(data.player, selectedAbility, data.opponent);
                updateStats();//a method to update the stats
                if(flag) mainDialog.appendText("\nYou dealt damage!");
                else mainDialog.appendText("\nYour attack missed!");
                scheduleCode = 2;
                this.scheduleTask(30);
            } else if(choiceObject == runButton){
                if(BattleHandler.run(data.player, data.opponent) && !(data.source instanceof StageMotherZombie)) {
                    scheduleCode = 1;
                    mainDialog.appendText("\nYou got away safely..");
                    this.scheduleTask(30);
                } else {
                    scheduleCode = 2;
                    mainDialog.appendText("\nCan't escape!");
                    this.scheduleTask(30);
                }
            } else if(choiceObject == ability0) {
                fightButton.setEnabled(true);
                runButton.setEnabled(true);
                selectedAbility = 0;
            } else if(choiceObject == ability1) {
                fightButton.setEnabled(true);
                runButton.setEnabled(true);
                selectedAbility = 1;
            } else if(choiceObject == ability2) {
                fightButton.setEnabled(true);
                runButton.setEnabled(true);
                selectedAbility = 2;
            } else if(choiceObject == ability3) {
                fightButton.setEnabled(true);
                runButton.setEnabled(true);
                selectedAbility = 3;
            }
        } else {
            if(elementVar == fightButton) {
                data.player.addItem(itemVar2);
                endBattle();
            }
            endBattle();
        }
    }

    @Override
    public void taskPerformed() {
        if(scheduleCode == 1) {
            exitBattle();
        } else if(scheduleCode == 2) {
            opponentTurn();
        } else if(scheduleCode == 3) {
            playerTurn();
        }
    }

    private void playerTurn() {
        if(data.opponent.getHealth() <= 0 || data.player.getHealth() <= 0){
            exitBattle();
            return;
        }
        updateStats();
        fightButton.setEnabled(true);
        runButton.setEnabled(true);
        ability0.setEnabled(true);
        ability0.setToolTip(data.player.getAbilitiesDesc(0));
        ability1.setEnabled(true);
        ability1.setToolTip(data.player.getAbilitiesDesc(1));
        ability2.setEnabled(true);
        ability2.setToolTip(data.player.getAbilitiesDesc(2));
        ability3.setEnabled(true);
        ability3.setToolTip(data.player.getAbilitiesDesc(3));
        selectedAbility = -1;
        mainDialog.setText("What will you do next?");
    }

    private void opponentTurn() {
        if(data.opponent.getHealth() <= 0 || data.player.getHealth() <= 0){
            exitBattle();
            return;
        }
        updateStats();
        boolean flag = BattleHandler.creatureTurn(data.player, data.opponent);
        updateStats();
        if(flag) mainDialog.setText("Your opponent dealt damage!");
        else mainDialog.setText("Your opponent's attack missed!");
        scheduleCode = 3;
        this.scheduleTask(20);
    }

    private void updateStats(){
        playerStat.setText("Health: " + ((int)(data.player.getHealth()*10))/10.0D);
        opponentStat.setText("Health: " + ((int)(data.opponent.getHealth()*10))/10.0D);
    }

    private void exitBattle() {
        data.battleCompleted = true;
        if(data.opponent.getHealth() <= 0){
        	opponentSprite.setImage(data.getEntityImage(0, 2));
            data.player.leveling(data.opponent);
            giveItem(data.opponent.randomDrop());
            return;
        }
        endBattle();
    }

    private void endBattle() {
        if(data.player.getHealth() <= 0) this.setStage(9);
        else this.setStage(data.source.getID());
    }

    private void giveItem(Item itemVar) {
        this.remove(ability0, ability1, ability2, ability3, playerStat, opponentStat);
        mainDialog.setText("YOU GOT A " + itemVar.getName().toUpperCase(), "Do you want it?");
        itemVar2 = itemVar;
        fightButton.setLabel("Accept Item", true);
        runButton.setY(this.getHeight() - 100 - ability0.getHeight()*2 - 10*2);
        runButton.setLabel("Reject Item", true);
    }
}


text:
require "google/cloud/service_usage/v1/service_usage"
require "google/cloud/service_usage/v1/version"

module Google
  module Cloud
    module ServiceUsage
      ##
      # To load this package, including all its services, and instantiate a client:
      #
      # @example
      #
      #     require "google/cloud/service_usage/v1"
      #     client = ::Google::Cloud::ServiceUsage::V1::ServiceUsage::Client.new
      #
      module V1
      end
    end
  end
end

helper_path = ::File.join __dir__, "v1", "_helpers.rb"
require "google/cloud/service_usage/v1/_helpers" if ::File.file? helper_path


text:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Data;
using System.Text;
using System.Windows.Forms;

namespace MVImportTool
{
    public partial class FileControl : UserControl
    {
        public string FileName
        {
            get { return FileBrowser.FileName; }
            set
            {
                if( !String.IsNullOrEmpty( value ) )
                {
                    FileBrowser.FileName = value;
                    FileNameTextBox.Text = value;
                }
            }
        }

        public string[] FileNames
        {
            get { return FileBrowser.FileNames; }
        }

        public bool Multiselect
        {
            get { return FileBrowser.Multiselect; }
            set { FileBrowser.Multiselect = value; }
        }

        public string InitialDirectory
        {
            get { return FileBrowser.InitialDirectory; }
            set { FileBrowser.InitialDirectory = value; }
        }

        public string Filter
        {
            get { return FileBrowser.Filter; }
            set { FileBrowser.Filter = value; }
        }

        public string Title
        {
            get { return FileBrowser.Title; }
            set { FileBrowser.Title = value; }
        }

        /// <summary>
        /// ToolTip displayed for the browser button
        /// </summary>
        public string ButtonToolTip
        {
            get { return BrowserToolTip.GetToolTip( this.BrowseButton ); }
            set { BrowserToolTip.SetToolTip( this.BrowseButton, value ); }
        }

        /// <summary>
        /// This is the label displayed above the text-box that shows the
        /// selected directory. You'd typically use it to explain what the
        /// selection represents.
        /// </summary>
        public string Label
        {
            get { return ControlLabel.Text; }
            set { ControlLabel.Text = value; }
        }

        #region Custom Events

        public class StringEventArgs : EventArgs
        {
            public StringEventArgs( string value )
            {
                Value = value;
            }
            public readonly string Value;
        }

        public delegate void StringEventHandler( object sender, StringEventArgs args );

        /// <summary>
        /// This event fires after the selected file name changes. The event
        /// arguments contain the new file. If Multiselect is enabled, only
        /// the first selected file is sent.
        /// </summary>
        public event StringEventHandler FileNameChangedEvent;

        private void FireFileNameChanged()
        {
            if( null != FileNameChangedEvent )
            {
                FileNameChangedEvent.Invoke( this, new StringEventArgs( FileName ) );
            }
        }

        #endregion Custom Events

        public FileControl()
        {
            InitializeComponent();
        }

        private void BrowseButton_Click( object sender, EventArgs e )
        {
            string oldFile = FileName;

            if( DialogResult.OK == FileBrowser.ShowDialog() )
            {
                string newName = this.Multiselect
                            ? FileBrowser.FileNames[ 0 ]
                            : FileBrowser.FileName;

                if( oldFile != newName )
                {
                    FileName = newName;

                    FireFileNameChanged();
                }
            }
        }
    }
}


text:
<?php

namespace Phalcon\Image {

    /**
     * Phalcon\Image\AdapterInterface initializer
     */
    interface AdapterInterface
        {

        /**
         * Resize the image to the given size. Either the width or the height can
         * be omitted and the image will be resized proportionally.
         *
         * @param int $width   new width
         * @param int $height  new height
         * @param int $master  master dimension
         * @return \Phalcon\Image\Adapter
         */
        public function resize($width=null, $height=null, $master=null);

        public function liquidRescale($width, $height, $delta_x=null, $rigidity=null);

        /**
         * Crop an image to the given size. Either the width or the height can be
         * omitted and the current width or height will be used.
         *
         * @param int $width new width
         * @param int $height new height
         * @param int $offset_x  offset from the left
         * @param int $offset_y  offset from the top
         * @return \Phalcon\Image\Adapter
         */
        public function crop($width, $height, $offset_x=null, $offset_y=null);

        /**
         * Rotate the image by a given amount.
         *
         * @param int $degrees  degrees to rotate: -360-360
         * @return \Phalcon\Image\Adapter
         */
        public function rotate($degrees);

        /**
         * Flip the image along the horizontal or vertical axis.
         *
         * @param $int $direction  direction: Image::HORIZONTAL, Image::VERTICAL
         * @return \Phalcon\Image\Adapter
         */
        public function flip($direction);

        /**
         * Sharpen the image by a given amount.
         *
         * @param int $amount  amount to sharpen: 1-100
         * @return \Phalcon\Image\Adapter
         */
        public function sharpen($amount);

        /**
         * Add a reflection to an image. The most opaque part of the reflection
         * will be equal to the opacity setting and fade out to full transparent.
         * Alpha transparency is preserved.
         *
         * @param int $height reflection height
         * @param int $opacity reflection opacity: 0-100
         * @param boolean $fade_in TRUE to fade in, FALSE to fade out
         * @return \Phalcon\Image\Adapter
         */
        public function reflection($height=null, $opacity=null, $fade_in=null);

        /**
         * Add a watermark to an image with a specified opacity. Alpha transparency
         * will be preserved.
         *
         * @param \Phalcon\Image\Adapter $watermark  watermark Image instance
         * @param int $offset_x offset from the left
         * @param int $offset_y offset from the top
         * @param int $opacity opacity of watermark: 1-100
         * @return \Phalcon\Image\Adapter
         */
        public function watermark($watermark, $offset_x=null, $offset_y=null, $opacity=null);

        public function text($text, $offset_x=null, $offset_y=null, $opacity=null, $color=null, $size=null, $fontfile=null);

        public function mask($mask);

        /**
         * Set the background color of an image. This is only useful for images
         * with alpha transparency.
         *
         * @param string $color hexadecimal color value
         * @param int $opacity background opacity: 0-100
         * @return \Phalcon\Image\Adapter
         */
        public function background($color, $quality=null);

        public function blur($radius=null);

        public function pixelate($amount=null);

        /**
         * Save the image. If the filename is omitted, the original image will
         * be overwritten.
         *
         * @param string $file new image path
         * @param int $quality quality of image: 1-100
         * @return \Phalcon\Image\Adapter
         */
        public function save($file=null, $quality=null);

        /**
         * Render the image and return the binary string.
         *
         * @param string $type image type to return: png, jpg, gif, etc
         * @param int $quality quality of image: 1-100
         * @return \Phalcon\Image\Adapter
         */
        public function render($type=null, $quality=null);

    }
}


text:
class ProvidersController < ApplicationController
  def index
    public_action
    @filter = params[:filter]
    @providers = Provider.visible_to(subject).filter(@filter).order(:name)
                         .paginate(page: params[:page])
  end

  def new
    check_access!('providers:create')
    @provider = Provider.new
  end

  def create
    check_access!('providers:create')
    Provider.transaction do
      @provider = create_provider
      unless @provider.persisted?
        return form_error('new', 'Unable to create the Provider', @provider)
      end
    end

    flash[:success] = "Created provider: #{@provider.name}"
    redirect_to @provider
  end

  def show
    check_access!("providers:#{params[:id]}:read")
    @provider = Provider.find(params[:id])
    @request_count = RequestedEnhancement.where(provider_id: @provider.id)
                                         .pending.count
  end

  def edit
    check_access!("providers:#{params[:id]}:update")
    @provider = Provider.find(params[:id])
  end

  def update
    check_access!("providers:#{params[:id]}:update")

    @provider = Provider.find(params[:id])
    unless update_provider(@provider)
      return form_error('edit', 'Unable to save the Provider', @provider)
    end

    flash[:success] = "Updated provider: #{@provider.name}"
    redirect_to @provider
  end

  def destroy
    check_access!('providers:delete')
    @provider = Provider.find(params[:id])
    @provider.audit_comment = 'Destroyed provider from admin interface'
    @provider.destroy!

    flash[:success] = "Deleted provider: #{@provider.name}"

    redirect_to providers_path
  end

  private

  def provider_params
    params.require(:provider).permit(:name, :description, :identifier, :public)
  end

  def create_provider
    audit_attrs = { audit_comment: 'Created new provider from admin interface' }
    provider = Provider.new(provider_params.merge(audit_attrs))

    provider.save && provider.create_default_roles
    provider
  end

  def update_provider(provider)
    audit_attrs = { audit_comment: 'Updated provider from admin interface' }
    provider.update_attributes(provider_params.merge(audit_attrs))
  end
end


text:
commit_regex='^Merge.+|[+*-] \[(android|ios|jsfm|html5|component|doc|website|example|test|all)\] [^\n]{1,50}'

if ! grep -iqE "$commit_regex" "$1"; then
    echo "ERROR: commit log format is not correct!"
    echo "See https://github.com/alibaba/weex/blob/dev/CONTRIBUTING.md#commit-log"
    exit 1
fi
# FIXME no effect after editor (like vim) exits
# ISSUE merge or conflict


text:
import threading
import time

import mailpile.util
from mailpile.i18n import gettext as _
from mailpile.i18n import ngettext as _n
from mailpile.util import *

##[ Specialized threads ]######################################################

class Cron(threading.Thread):
    """
    An instance of this class represents a cron-like worker thread
    that manages and executes tasks in regular intervals
    """

    def __init__(self, name=None, session=None):
        """
        Initializes a new Cron instance.
        Note that the thread will not be started automatically, so
        you need to call start() manually.

        Keyword arguments:
        name -- The name of the Cron instance
        session -- Currently unused
        """
        threading.Thread.__init__(self)
        self.ALIVE = False
        self.daemon = mailpile.util.TESTING
        self.name = name
        self.session = session
        self.last_run = time.time()
        self.running = 'Idle'
        self.schedule = {}
        self.sleep = 10
        # This lock is used to synchronize
        self.lock = WorkerLock()

    def __str__(self):
        return '%s: %s (%ds)' % (threading.Thread.__str__(self),
                                 self.running, time.time() - self.last_run)

    def add_task(self, name, interval, task):
        """
        Add a task to the cron worker queue

        Keyword arguments:
        name -- The name of the task to add
        interval -- The interval (in seconds) of the task
        task    -- A task function
        """
        with self.lock:
            self.schedule[name] = [name, interval, task, time.time()]
            self.sleep = 1
            self.__recalculateSleep()

    def __recalculateSleep(self):
        """
        Recalculate the maximum sleep delay.
        This shall be called from a lock zone only
        """
        # (Re)alculate how long we can sleep between tasks
        #    (sleep min. 1 sec, max. 61 sec)
        # --> Calculate the GCD of the task intervals
        for i in range(2, 61):  # i = second
            # Check if any scheduled task intervals are != 0 mod i
            filteredTasks = [True for task in self.schedule.values()
                             if int(task[1]) % i != 0]
            # We can sleep for i seconds if i divides all intervals
            if (len(filteredTasks) == 0):
                self.sleep = i

    def cancel_task(self, name):
        """
        Cancel a task in the current Cron instance.
        If a task with the given name does not exist,
        ignore the request.

        Keyword arguments:
        name -- The name of the task to cancel
        """
        if name in self.schedule:
            with self.lock:
                del self.schedule[name]
                self.__recalculateSleep()

    def run(self):
        """
        Thread main function for a Cron instance.

        """
        # Main thread loop
        with self.session.config.index_check:
            self.ALIVE = True
        while self.ALIVE and not mailpile.util.QUITTING:
            tasksToBeExecuted = []  # Contains tuples (name, func)
            now = time.time()
            # Check if any of the task is (over)due
            with self.lock:
                for task_spec in self.schedule.values():
                    name, interval, task, last = task_spec
                    if last + interval <= now:
                        tasksToBeExecuted.append((name, task))

            # Execute the tasks
            for name, task in tasksToBeExecuted:
                # Set last_executed
                self.schedule[name][3] = time.time()
                try:
                    self.last_run = time.time()
                    self.running = name
                    task()
                except Exception, e:
                    self.session.ui.error(('%s failed in %s: %s'
                                           ) % (name, self.name, e))
                finally:
                    self.last_run = time.time()
                    self.running = 'Finished %s' % self.running

            # Some tasks take longer than others, so use the time before
            # executing tasks as reference for the delay
            sleepTime = self.sleep
            delay = time.time() - now + sleepTime

            # Sleep for max. 1 sec to react to the quit signal in time
            while delay > 0 and self.ALIVE:
                # self.sleep might change during loop (if tasks are modified)
                # In that case, just wake up and check if any tasks need
                # to be executed
                if self.sleep != sleepTime:
                    delay = 0
                else:
                    # Sleep for max 1 second to check self.ALIVE
                    time.sleep(max(0, min(1, delay)))
                    delay -= 1

    def quit(self, session=None, join=True):
        """
        Send a signal to the current Cron instance
        to stop operation.

        Keyword arguments:
        join -- If this is True, this method will wait until
                        the Cron thread exits.
        """
        self.ALIVE = False
        if join:
            try:
                self.join()
            except RuntimeError:
                pass

class Worker(threading.Thread):

    def __init__(self, name, session, daemon=False):
        threading.Thread.__init__(self)
        self.daemon = mailpile.util.TESTING or daemon
        self.name = name or 'Worker'
        self.ALIVE = False
        self.JOBS = []
        self.JOBS_LATER = []
        self.LOCK = threading.Condition(WorkerRLock())
        self.last_run = time.time()
        self.running = 'Idle'
        self.pauses = 0
        self.session = session
        self.important = False

    def __str__(self):
        return ('%s: %s (%ds, jobs=%s, jobs_after=%s)'
                % (threading.Thread.__str__(self),
                   self.running,
                   time.time() - self.last_run,
                   len(self.JOBS), len(self.JOBS_LATER)))

    def add_task(self, session, name, task,
                 after=None, unique=False, first=False):
        with self.LOCK:
            if unique:
                for s, n, t in self.JOBS:
                    if n == name:
                        return
            if unique and after:
                for ts, (s, n, t) in self.JOBS_LATER:
                    if n == name:
                        return

            snt = (session, name, task)
            if first:
                self.JOBS[:0] = [snt]
            elif after:
                self.JOBS_LATER.append((after, snt))
            else:
                self.JOBS.append(snt)

            self.LOCK.notify()

    def add_unique_task(self, session, name, task, **kwargs):
        return self.add_task(session, name, task, unique=True, **kwargs)

    def do(self, session, name, task, unique=False):
        if session and session.main:
            # We run this in the foreground on the main interactive session,
            # so CTRL-C has a chance to work.
            try:
                self.pause(session)
                rv = task()
            finally:
                self.unpause(session)
        else:
            self.add_task(session, name, task, unique=unique)
            if session:
                rv = session.wait_for_task(name)
            else:
                rv = True
        return rv

    def _keep_running(self, **ignored_kwargs):
        return (self.ALIVE and not mailpile.util.QUITTING)

    def _failed(self, session, name, task, e):
        self.session.ui.error(('%s failed in %s: %s'
                               ) % (name, self.name, e))
        if session:
            session.report_task_failed(name)

    def _play_nice_with_threads(self):
        play_nice_with_threads()

    def run(self):
        self.ALIVE = True
        while self._keep_running():
            with self.LOCK:
                while len(self.JOBS) < 1:
                    if not self._keep_running(locked=True):
                        return
                    self.LOCK.wait()

            self._play_nice_with_threads()
            with self.LOCK:
                session, name, task = self.JOBS.pop(0)
                if len(self.JOBS) < 0:
                    now = time.time()
                    self.JOBS.extend(snt for ts, snt
                                     in self.JOBS_LATER if ts <= now)
                    self.JOBS_LATER = [(ts, snt) for ts, snt
                                       in self.JOBS_LATER if ts > now]
            try:
                self.last_run = time.time()
                self.running = name
                if session:
                    session.ui.mark('Starting: %s' % name)
                    session.report_task_completed(name, task())
                else:
                    task()
            except (IOError, OSError), e:
                self._failed(session, name, task, e)
                time.sleep(1)
            except Exception, e:
                self._failed(session, name, task, e)
            finally:
                self.last_run = time.time()
                self.running = 'Finished %s' % self.running

    def pause(self, session):
        with self.LOCK:
            self.pauses += 1
            first = (self.pauses == 1)

        if first:
            def pause_task():
                session.report_task_completed('Pause', True)
                session.wait_for_task('Unpause', quiet=True)

            self.add_task(None, 'Pause', pause_task)
            session.wait_for_task('Pause', quiet=True)

    def unpause(self, session):
        with self.LOCK:
            self.pauses -= 1
            if self.pauses == 0:
                session.report_task_completed('Unpause', True)

    def die_soon(self, session=None):
        def die():
            self.ALIVE = False
        self.add_task(session, '%s shutdown' % self.name, die)

    def quit(self, session=None, join=True):
        self.die_soon(session=session)
        if join:
            try:
                self.join()
            except RuntimeError:
                pass

class ImportantWorker(Worker):
    def _keep_running(self, _pass=1, locked=False):
        # This is a much more careful shutdown test, that refuses to
        # stop with jobs queued up and tries to compensate for potential
        # race conditions in our quitting code by waiting a bit and
        # then re-checking if it looks like it is time to die.
        if len(self.JOBS) > 0:
            return True
        else:
             if _pass == 2:
                 return Worker._keep_running(self)
             if self.ALIVE and not mailpile.util.QUITTING:
                 return True
             else:
                 if locked:
                     try:
                         self.LOCK.release()
                         time.sleep(1)
                     finally:
                         self.LOCK.acquire()
                 else:
                     time.sleep(1)
                 return self._keep_running(_pass=2, locked=locked)

    def _failed(self, session, name, task, e):
        # Important jobs!  Re-queue if they fail, it might be transient
        Worker._failed(self, session, name, task, e)
        self.add_unique_task(session, name, task)

    def _play_nice_with_threads(self):
        # Our jobs are important, if we have too many we stop playing nice
        if len(self.JOBS) < 10:
            play_nice_with_threads()

class DumbWorker(Worker):
    def add_task(self, session, name, task, unique=False):
        with self.LOCK:
            return task()

    def add_unique_task(self, session, name, task):
        return self.add_task(session, name, task)

    def do(self, session, name, task, unique=False):
        return self.add_task(session, name, task)

    def run(self):
        pass

if __name__ == "__main__":
    import doctest
    import sys
    result = doctest.testmod(optionflags=doctest.ELLIPSIS,
                             extraglobs={'junk': {}})
    print '%s' % (result, )
    if result.failed:
        sys.exit(1)


text:
from networkx.algorithms.link_analysis.pagerank_alg import *
from networkx.algorithms.link_analysis.hits_alg import *


text:
package main

// HTTP server for accessing weather station data.

import (
	"encoding/json"
	"fmt"
	"net"
	"net/http"
	//_ "net/http/pprof"
	"strconv"
	"time"
)

type httpCtx serverCtx

type httpLogWrapper struct {
	http.Flusher
	http.ResponseWriter
	status int
}

func (l *httpLogWrapper) Write(p []byte) (int, error) {
	return l.ResponseWriter.Write(p)
}

func (l *httpLogWrapper) WriteHeader(status int) {
	l.status = status
	l.ResponseWriter.WriteHeader(status)
}

func (httpCtx) logHandler(h http.Handler) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		record := &httpLogWrapper{
			Flusher:        w.(http.Flusher),
			ResponseWriter: w,
			status:         http.StatusOK,
		}

		h.ServeHTTP(record, r)

		msg := fmt.Sprintf("HTTP connection from %s request %s %s response %d", r.RemoteAddr, r.Method, r.URL, record.status)
		if record.status < 299 {
			Debug.Println(msg)
		} else {
			Warn.Println(msg)
		}
	}
}

// archive is the endpoint for serving out archive records.
// GET /archive[?begin=2016-08-03T00:00:00Z][&end=2016-09-03T00:00:00Z]
func (c httpCtx) archive(w http.ResponseWriter, r *http.Request) {
	// Parse and validate begin and end parameters
	var begin, end time.Time
	var err error

	if r.URL.Query().Get("end") != "" {
		end, err = time.Parse(time.RFC3339, r.URL.Query().Get("end"))
		if err != nil {
			w.Header().Set("Warning", "Unable to parse end timestamp")
			w.WriteHeader(http.StatusBadRequest)
			return
		}
	} else {
		end = time.Now()
	}

	if r.URL.Query().Get("begin") != "" {
		begin, err = time.Parse(time.RFC3339, r.URL.Query().Get("begin"))
		if err != nil {
			w.Header().Set("Warning", "Unable to parse begin timestamp")
			w.WriteHeader(http.StatusBadRequest)
			return
		}
	} else {
		begin = end.AddDate(0, 0, -1)
	}

	if end.Before(begin) {
		w.Header().Set("Warning", "End timestamp precedes begin timestamp")
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// Large durations can be very resource intensive to marshal so
	// cap at 30 days.
	if end.Sub(begin) > (30 * (24 * time.Hour)) {
		w.Header().Set("Warning", "Duration exceeds maximum allowed")
		w.WriteHeader(http.StatusRequestEntityTooLarge)
		return
	}

	// Query archive from database and return
	archive := c.ar.Get(begin, end)
	if len(archive) < 1 {
		w.WriteHeader(http.StatusNoContent)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	json.NewEncoder(w).Encode(archive)
}

// loop is the endpoint for serving out loop samples.
// GET /loop[?lastSequence=#]
func (c httpCtx) loop(w http.ResponseWriter, r *http.Request) {
	numLoops, lastLoop := c.lb.last()

	// If there aren't enough samples (the server just started) or
	// there were no recent updates then send a HTTP service temporarily
	// unavailable response.
	if numLoops < loopsMin {
		w.Header().Set("Warning", errLoopsMin.Error())
		w.WriteHeader(http.StatusServiceUnavailable)
		return
	}

	if time.Since(lastLoop.Timestamp) > loopStaleAge {
		w.Header().Set("Warning", errLoopsAge.Error())
		w.WriteHeader(http.StatusServiceUnavailable)
		return
	}

	// Figure out if request is for loops since a sequence or just for
	// most recent loop.
	j := json.NewEncoder(w)
	if r.URL.Query().Get("lastSequence") != "" {
		seq, _ := strconv.ParseInt(r.URL.Query().Get("lastSequence"), 10, 64)

		// There are no sequence gaps so it's simple subtraction to
		// determine the end index.  A few safeguards have to be added
		// though:
		//
		// If the requested sequence is ahead of the server then return
		// nothing.
		//
		// If the request sequence is so far back that it's been purged
		// then return everything.
		endIndex := int(lastLoop.Seq - seq)
		if endIndex < 1 {
			w.WriteHeader(http.StatusNoContent)
		} else {
			if endIndex > numLoops {
				endIndex = numLoops
			}
			w.Header().Set("Content-Type", "application/json")
			j.Encode(c.lb.loops()[0:endIndex])
		}
	} else {
		w.Header().Set("Content-Type", "application/json")
		j.Encode(lastLoop)
	}
}

// events is the endpoint for streaming loop samples using the Server-sent
// events.
// GET /events
func (c httpCtx) events(w http.ResponseWriter, r *http.Request) {
	// See Server-sent-event specification:
	// https://en.wikipedia.org/wiki/Server-sent_events

	w.Header().Set("Content-Type", "text/event-stream")
	w.Header().Set("Cache-Control", "no-cache")
	w.Header().Set("Connection", "keep-alive")

	events := c.eb.Subscribe(r.RemoteAddr)
	defer c.eb.Unsubscribe(events)

	for {
		select {
		case <-r.Context().Done():
			// Client closed the connection
			return
		case e := <-events:
			fmt.Fprintf(w, "event: %s\n", e.Name)
			r, _ := json.Marshal(e.Data)
			fmt.Fprintf(w, "data: %s\n\n", r)
			w.(http.Flusher).Flush()
		}
	}
}

// httpServer starts the HTTP server.
func httpServer(sc serverCtx, cfg config) {
	// Inherit generic server context so we have access to things like
	// archive records and loop packets.
	c := httpCtx(sc)

	// Register routes
	http.HandleFunc("/archive", c.archive)
	http.HandleFunc("/loop", c.loop)
	http.HandleFunc("/events", c.events)

	// Listen and accept new connections
	s := http.Server{
		Addr:    net.JoinHostPort(cfg.addr, "8080"),
		Handler: c.logHandler(http.DefaultServeMux),
	}
	Info.Printf("HTTP server started on %s", s.Addr)
	err := s.ListenAndServe()
	if err != nil {
		Error.Fatalf("HTTP server error: %s", err.Error())
	}
}


text:
#import "COSequenceEdit.h"
#import "COSequenceDeletion.h"
#import "COSequenceInsertion.h"
#import <EtoileFoundation/Macros.h>

static BOOL COOverlappingRanges(NSRange r1, NSRange r2)
{
    return (r1.location >= r2.location && r1.location < (r2.location + r2.length) && r1.length > 0)
           || (r2.location >= r1.location && r2.location < (r1.location + r1.length) && r2.length > 0);
}

@implementation COSequenceEdit

@synthesize range;

- (instancetype)initWithUUID: (ETUUID *)aUUID
                   attribute: (NSString *)anAttribute
            sourceIdentifier: (id)aSourceIdentifier
                       range: (NSRange)aRange
{
    NILARG_EXCEPTION_TEST(aUUID);
    NILARG_EXCEPTION_TEST(anAttribute);

    self = [super initWithUUID: aUUID attribute: anAttribute sourceIdentifier: aSourceIdentifier];
    if (self == nil)
        return nil;

    range = aRange;
    return self;
}

- (instancetype)initWithUUID: (ETUUID *)aUUID
                   attribute: (NSString *)anAttribute
            sourceIdentifier: (id)aSourceIdentifier
{
    return [self initWithUUID: nil
                    attribute: nil
             sourceIdentifier: nil
                        range: NSMakeRange(0, 0)];
}

- (instancetype)init
{
    return [self initWithUUID: nil
                    attribute: nil
             sourceIdentifier: nil
                        range: NSMakeRange(0, 0)];
}

static NSDictionary *classSortOrder;

+ (void)initialize
{
    if (self == [COSequenceEdit class])
    {
        classSortOrder = @{NSStringFromClass([COSequenceDeletion class]): @0,
                           NSStringFromClass([COSequenceModification class]): @0,
                           NSStringFromClass([COSequenceInsertion class]): @1};
    }
}

- (NSComparisonResult)compare: (COSequenceEdit *)other
{
    if (other.range.location > self.range.location)
    {
        return NSOrderedAscending;
    }
    if (other.range.location == self.range.location)
    {
        NSNumber *selfOrder = classSortOrder[NSStringFromClass([self class])];
        NSNumber *otherOrder = classSortOrder[NSStringFromClass([other class])];

        assert(selfOrder != nil);
        assert(otherOrder != nil);

        if (selfOrder.intValue > otherOrder.intValue)
        {
            return NSOrderedDescending;
        }
        else if (selfOrder.intValue < otherOrder.intValue)
        {
            return NSOrderedAscending;
        }
        else
        {
            return NSOrderedSame;
        }
    }
    else
    {
        return NSOrderedDescending;
    }
}

- (BOOL)overlaps: (COSequenceEdit *)other
{
    return COOverlappingRanges(range, other.range);
}

- (BOOL)touches: (COSequenceEdit *)other
{
    if (COOverlappingRanges(range, other.range))
    {
        return YES;
    }

    if (range.location == NSMaxRange(other.range))
        return YES;

    if (range.location == other.range.location)
        return YES;

    if (NSMaxRange(range) == NSMaxRange(other.range))
        return YES;

    if (NSMaxRange(range) == other.range.location)
        return YES;

    return NO;
}

- (BOOL)isEqualIgnoringSourceIdentifier: (id)other
{
    return [super isEqualIgnoringSourceIdentifier: other]
           && NSEqualRanges(range, ((COSequenceEdit *)other).range);
}

- (NSUInteger)hash
{
    return 9723954873297612448ULL ^ super.hash ^ range.location ^ range.length;
}

- (BOOL)isSameKindOfEdit: (COItemGraphEdit *)anEdit
{
    return [anEdit isKindOfClass: [COSequenceEdit class]];
}

@end


text:
<?php

namespace Vladimino\Geo\Provider;

/**
 * Interface GeoProviderInterface
 * Common Interface for all GeoProviders to be used in GeoProviderFactory
 *
 * @package Vladimino\Geo\Provider
 * @author vladimino
 */
interface GeoProviderInterface
{
    /**
     * @param string $sLocation String to geocode.
     *
     * @return \Vladimino\Geo\Entity\ResultCollection
     * @throws \InvalidArgumentException if string is invalid
     */
    public function getResultsByLocation($sLocation);
}


text:
phosphor-command
================

[![Build Status](https://travis-ci.org/phosphorjs/phosphor-command.svg)](https://travis-ci.org/phosphorjs/phosphor-command?branch=master)
[![Coverage Status](https://coveralls.io/repos/phosphorjs/phosphor-command/badge.svg?branch=master&service=github)](https://coveralls.io/github/phosphorjs/phosphor-command?branch=master)

A module for expressing the command pattern.

[API Docs](http://phosphorjs.github.io/phosphor-command/api/)

Package Install
---------------

**Prerequisites**
- [node](https://nodejs.org/)

```bash
npm install --save phosphor-command
```

Source Build
------------

**Prerequisites**
- [git](http://git-scm.com/)
- [node](http://nodejs.org/)

```bash
git clone https://github.com/phosphorjs/phosphor-command.git
cd phosphor-command
npm install
```

**Rebuild**
```bash
npm run clean
npm run build
```

Run Tests
---------

Follow the source build instructions first.

```bash
npm test
```

Build Docs
----------

Follow the source build instructions first.

```bash
npm run docs
```

Navigate to `docs/index.html`.

Supported Runtimes
------------------

The runtime versions which are currently *known to work* are listed below.
Earlier versions may also work, but come with no guarantees.

- Node 0.12.7+
- IE 11+
- Firefox 32+
- Chrome 38+

Bundle for the Browser
----------------------

Follow the package install instructions first.

```bash
npm install --save-dev browserify
browserify myapp.js -o mybundle.js
```

Usage Examples
--------------

**Note:** This module is fully compatible with Node/Babel/ES6/ES5. Simply
omit the type declarations when using a language other than TypeScript.


text:
var searchData=
[
  ['hasobjective_0',['HasObjective',['../classoperations__research_1_1sat_1_1_cp_model_builder.html#a81c8f76d39ff0529fe40e70f8319d5d2',1,'operations_research::sat::CpModelBuilder']]]
];


text:
<?php
/**
* MySMS - Simple SMS Component for Joomla
*
* Axel Sauerhoefer < mysms[at]quelloffen.com >
*
* http://www.willcodejoomlaforfood.de
*
* $Author: axel $
* $Rev: 184 $
* $HeadURL: svn://willcodejoomlaforfood.de/mysms/trunk/administrator/components/com_mysms/provider/mysms.provider.smsviainternet.php $
*
* $Id: mysms.provider.smsviainternet.php 184 2009-12-11 17:06:40Z axel $
*
* All rights reserved.
*
* @license http://www.gnu.org/copyleft/gpl.html GNU/GPL, see LICENSE.php
* MySMS! is free software. This version may have been modified pursuant
* to the GNU General Public License, and as distributed it includes or
* is derivative of works licensed under the GNU General Public License or
* other free or open source software licenses.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
**/
//check if joomla call us
defined( '_JEXEC' ) or die( 'Restricted access' );

if( defined( 'MYSMS_PROVIDER_SMSVIAINTERNET_PHP' ) == true )
{
  return;
}

/**
 * Define our class constant to precent multipe definition
 */
define( 'MYSMS_PROVIDER_SMSVIAINTERNET_PHP', 1 );

/**
 * require our base class
 */
require_once('provider.php');

/**
*  SMSVIAINTERNET is a sms gateway connection implementation (https://www.SMSVIAINTERNET.it)
*
* @package MySMS
* @subpackage Provider
**/

class SMSVIAINTERNET extends Provider
{

   /**
   *  Constructor, setting up name, file and parameters
   */
      function SMSVIAINTERNET()
      {
        Provider::Provider();   //call base class constructor
        $this->_name = 'SMSVIAINTERNET';
        $this->_file = basename( __FILE__ );

        $this->_params['smstype']		=  'file.sms';            //default params
        $this->_params['smsgateway'] 	=  'H';            		//default params
		$this->_params['smsuser'] 		=  'user';            	//default params
		$this->_params['smspassword']	=  'password';            //default params
      }

   /**
   *  The sendSMS is for sending a sms, this function must be reimplemented in all dirved classes
   *  @param string $text
   *  @param string $from
   *  @param string $to
   */
      function sendSms( $text, $from, $to, &$errMsg )
      {
        $user 		=  &$this->_params['smsuser'];
        $pw 		=  &$this->_params['smspassword'];
        $gw   		=  &$this->_params['smsgateway'];
        $type	 	=  &$this->_params['smstype'];

       // http://77.93.254.105/post/multisms/send.php

        $host = '77.93.254.105';
        $fp = fsockopen( $host, 80 );

        if( $fp == false )
        {
        	$errMsg = JText::_( 'MYSMS_ERROR' ) . ':  Network';
        	return false;
        }

        // we cannot use the buildQuery method because the server side does not understand & :/
        $payload = "smsTEXT=$text&smsNUMBER=$to&smsSENDER=$from&smsTYPE$type&smsGATEWAY&$gw&smsUSER=$user&smsPASSWORD=$pw";

        //do it the old way because the server send 2 http status codes

        /*
         * Array
(
    [0] => HTTP/1.1 100 Continue
    [1] => Server: SMSDriver POST/1.0
    [2] => Date: mar, 31 mar 2009 18:52:30  GMT
    [3] =>
    [4] => HTTP/1.1 200 OK
    [5] => Server: SMSDriver POST/1.0
    [6] => Date: mar, 31 mar 2009 18:52:30  GMT
    [7] => Content-Length: 130
    [8] => Content-Type: text/html
    [9] => Set-Cookie: ASPSESSIONIDACCSTDCT=MDKLNEGAJIIHAMFJIDBLNBIM; path=/
    [10] => Cache-control: private
    [11] =>
    [12] =>
    [13] =>
    [14] =>
    [15] =>
    [16] => [17] =>
    [18] => -Err 007 Message not enabled
    [19] => [20] => [21] =>
)
         */
        fputs($fp, "POST /post/multisms/send.php HTTP/1.1\n");
        fputs($fp, "Host: $host\n");
        fputs($fp, "Content-type: application/x-www-form-urlencoded\n");
        fputs($fp, "Content-length: ".strlen($payload)."\n");
        fputs($fp, "Connection: close\n\n");
        fputs($fp, "$payload\n");

         while( !feof( $fp ) )
         {
         	$res .= fgets($fp, 128);
         }

         fclose($fp);

         $data = strip_tags( $res );

         if( eregi( '-Err', $data ) )
         {
         	$data = explode( "\r\n", $data );

         	foreach ( $data as $line )
         	{

         		if( eregi( '-Err', $line ) )
         		{
         			$errMsg = JText::_( 'MYSMS_ERROR' ) . $line;
         			return false;
         		}
         	}

         	 $errMsg = JText::_( 'MYSMS_ERROR' ) . ':  Provider';
         	 return false;
         }

		return true;
  }//end send sms
} //end class AGILETELECOM
?>


text:
require 'spec_helper'

describe Spree::AlipayForexController, type: :controller do

  # Regression tests for #55
  context "when current_order is nil" do

    context "partner_trade" do
      it "raises ActiveRecord::RecordNotFound" do

        expect(lambda { get :partner_trade, :use_route => :spree}).to raise_error(ActiveRecord::RecordNotFound)
      end
    end

  end
end