text:
/**
 *
 * Process Editor
 *
 * (C) 2009, 2010 inubit AG
 * (C) 2014 the authors
 *
 */
package com.inubit.research.layouter.gridLayouter;

import java.awt.Dimension;
import java.awt.Point;
import java.awt.Rectangle;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;

import com.inubit.research.layouter.LayoutHelper;
import com.inubit.research.layouter.interfaces.BPMNEdgeInterface;
import com.inubit.research.layouter.interfaces.BPMNNodeInterface;
import com.inubit.research.layouter.interfaces.EdgeInterface;
import com.inubit.research.layouter.interfaces.AbstractModelAdapter;
import com.inubit.research.layouter.interfaces.NodeInterface;
import com.inubit.research.layouter.interfaces.TWFModelInterface;
import com.inubit.research.layouter.preprocessor.DummyEdge;

/**
 * determines routing points for the edges between the nodes.
 * also contains an A* implementation for the routing of message flows.
 * But due to the penalties and constraints the state space quite easily explodes and layouting
 * of several message flows then easily takes several seconds. Thus it can be disables in the
 * properties.
 * @author ff
 *
 */
public class GridLayouterEdgeRouter {

	private GridLayouter f_layouter;
	private AbstractModelAdapter f_model;

	/**
	 * needed for A* Message Flow Routing
	 */
	private static final int JUMPDISTANCE = 20; //pixels
	private static final int BOUNDINGBOX_EXTENSION = 14;
	private static final int BEND_PENALTY = 5;
	private static final int NODE_CROSSING_PENALTY = 100;
	private static final int POOL_CROSSING_PENALTY = 10;

	private HashSet<ANode> f_open = new HashSet<ANode>();
	private HashSet<ANode> f_closed = new HashSet<ANode>();
	private NodeInterface f_source;
	private NodeInterface f_target;
	private List<EdgeInterface> f_routedEdges = new ArrayList<EdgeInterface>();

	/**
	 *
	 */
	public GridLayouterEdgeRouter(GridLayouter layouter,AbstractModelAdapter model) {
		f_layouter = layouter;
		f_model = model;
	}

	public void routeEdges() {
		Hypergrid _grids = f_layouter.getGrids();
		for(int g = 0; g < _grids.getNumOfGrids();g++) {
			Grid _grid = _grids.getGrid(g);
			for(int col=0;col<_grid.getColCount();col++) {
				for(int row=0;row<_grid.getRowCount();row++) {
					FlowObjectWrapper _obj = _grid.getObject(row, col);
					if(_obj != null) {
						if(_obj.getWrappedObject() instanceof BPMNNodeInterface) {
							if(isGateway(_obj) || isDataObject(_obj)) {
								route(_grid,row,col,_obj);
							}
						}
					}
				}
			}
		}
	}

	public void routeMessageFlows() {
		//long start = System.currentTimeMillis();
		for(EdgeInterface e:f_model.getEdges()) {
			if(e instanceof BPMNEdgeInterface) {
				if(((BPMNEdgeInterface)e).isMessageFlow()){
					routeMessageFlow(e);
				}
			}
		}
		//System.out.println("MSF Routing: "+(System.currentTimeMillis()-start)+" ms");
	}

	/**
	 * @param obj
	 * @return
	 */
	private boolean isDataObject(FlowObjectWrapper obj) {
		return obj.isDataObject() &&
			(obj.getPredecessorEdges().size()==1);
	}

	/**
	 * @param e
	 */
	private void routeMessageFlow(EdgeInterface e) {
		f_open.clear();
		f_closed.clear();
		f_source = (NodeInterface) e.getSource();
		f_target = (NodeInterface)e.getTarget();
		Point _start = f_source.getPos();
		Point _end = f_target.getPos();
		ANode _node = new ANode(_start,_end,null);
		_node.setG(0);
		f_open.add(_node);
		Rectangle _source = getBounds((NodeInterface) e.getSource(),-20);
		Rectangle _target = getBounds((NodeInterface)e.getTarget(),-20);
		ANode _goal = routeMSF(_source,_target);
		_source = getBounds((NodeInterface) e.getSource(),BOUNDINGBOX_EXTENSION);
		_target = getBounds((NodeInterface)e.getTarget(),BOUNDINGBOX_EXTENSION);
		List<Point> _rps = new ArrayList<Point>();
		while(_goal != null) {
			if(!(_source.contains(_goal.getPoint()) || _target.contains(_goal.getPoint()))) {
				_rps.add(0,_goal.getPoint());
			}
			_goal = _goal.getCameFrom();
		}
		LayoutHelper.removeUnneccesaryPoints(_rps);
		e.clearRoutingPoints();
		e.setRoutingPoints(_rps);
	}
	/**
	 * @param _target
	 * @param _source
	 *
	 */
	private ANode routeMSF(Rectangle _source, Rectangle _target) {
		int max = 0;
		ANode _a = null;
		//some edges are quite long and need lots of steps
		while(f_open.size() > 0 && max < 2000) {
			_a = getNodeWithLowestF();
			f_open.remove(_a);
			f_closed.add(_a);
			for(ANode neighbor:getNeighbors(_a)) {
				if(_target.contains(neighbor.getPoint())) {
					return neighbor;
				}
				if(f_closed.contains(neighbor)) {
					continue;
				}
				int _g = 0;
				if(!_source.contains(neighbor.getPoint())) {
				 _g = _a.getG() + JUMPDISTANCE + getPenalty(neighbor,f_model);
				}
				if(f_open.contains(neighbor)) {
					ANode _other = getClone(f_open,neighbor);
					if(_other.getG() > _g) {
						_other.setG(_g);
						_other.setCameFrom(_a);
					}
				}else {
					neighbor.setG(_g);
					f_open.add(neighbor);
				}
			}
			max++;
		}
		return getNodeWithLowestH();
	}

	/**
	 * @return
	 */
	private ANode getNodeWithLowestH() {
		ANode _result = null;
		for(ANode a:f_open) {
			if(_result == null) {
				_result=a;
			}
			if(_result.getH() > a.getH()) {
				_result = a;
			}
		}
		return _result;
	}

	/**
	 * @param f_open2
	 * @param neighbor
	 * @return
	 */
	private ANode getClone(HashSet<ANode> set, ANode neighbor) {
		for(ANode n:set) {
			if(n.hashCode() == neighbor.hashCode()) {
				return n;
			}
		}
		return null;
	}

	/**
	 * @param point
	 * @param f_model2
	 * @return
	 */
	private int getPenalty(ANode node, AbstractModelAdapter model) {
		int _result = 0;
		for(NodeInterface n : model.getNodes()) {
			if((n.equals(f_source)) || (n.equals(f_target))) continue; //those are okay!
			Rectangle bounds = getBounds(n,BOUNDINGBOX_EXTENSION);
			if(bounds.contains(node.getPoint())) {
				BPMNNodeInterface _n = (BPMNNodeInterface) n;
				if(_n.isPool() || _n.isSubProcess()) {
					_result += POOL_CROSSING_PENALTY;
				}else
				if(_n.isLane()) {
					//nothing already handled by pool
				}else {
					_result += NODE_CROSSING_PENALTY; //we do not want to cross other nodes!
				}
			}
		}
		if(node.getCameFrom() != null && node.getCameFrom().getCameFrom() != null) {
			Point _p1 = node.getCameFrom().getPoint();
			Point _p2 = node.getCameFrom().getCameFrom().getPoint();
			if(!LayoutHelper.isStraight(node.getPoint(),_p1,_p2)) {
				_result += BEND_PENALTY;
			}

		}
		return _result;
	}

	/**
	 * @param n
	 * @return
	 */
	private Rectangle getBounds(NodeInterface n,int offset) {
		Point _p = n.getPos();
		Dimension _d = n.getSize();
		_p.translate(-_d.width/2-offset/2, -_d.height/2-offset/2);
		_d.width += offset;
		_d.height += offset;
		return new Rectangle(_p,_d);
	}

	/**
	 * @param _a
	 * @return
	 */
	private List<ANode> getNeighbors(ANode _a) {
		LinkedList<ANode> _result = new LinkedList<ANode>();

		Point p = new Point(_a.getPoint());
		p.translate(JUMPDISTANCE, 0);
		_result.add(new ANode(p,_a.getTarget(),_a));

		p = new Point(_a.getPoint());
		p.translate(-JUMPDISTANCE, 0);
		_result.add(new ANode(p,_a.getTarget(),_a));

		p = new Point(_a.getPoint());
		p.translate(0, JUMPDISTANCE);
		_result.add(new ANode(p,_a.getTarget(),_a));

		p = new Point(_a.getPoint());
		p.translate(0, -JUMPDISTANCE);
		_result.add(new ANode(p,_a.getTarget(),_a));

		return _result;
	}

	/**
	 * @return
	 */
	private ANode getNodeWithLowestF() {
		ANode _result = null;
		for(ANode a:f_open) {
			if(_result == null) {
				_result=a;
			}
			if(_result.getF() > a.getF()) {
				_result = a;
			}
		}
		return _result;
	}

	/**
	 * @param _grid
	 * @param row
	 * @param col
	 * @param _o
	 */
	private void route(Grid _grid, int row, int col, FlowObjectWrapper _o) {
		ArrayList<FlowObjectWrapper> f_succ = _o.getSuccessors();
		if(!_o.isDataObject()) {
			for(int s = 0;s<f_succ.size();s++) {
				if(!(_o.getSuccessorEdges().get(s) instanceof DummyEdge)) {
					if(!isGateway(f_succ.get(s)) &&
							(!((BPMNEdgeInterface)_o.getSuccessorEdges().get(s)).isMessageFlow())) {
						if(routeDown(_o, f_succ, s)) {
							//routing downwards
							int _row = row+1;
							if(_row < _grid.getRowCount()) {
								FlowObjectWrapper _cell = _grid.getObject(_row, col);
								ArrayList<Point> _newrps = new ArrayList<Point>();
								while((_cell == null) && (_row <=  f_succ.get(s).getPosition().y)) {
									//add routing point
									Point p = new Point(_grid.getX(col),_grid.getY(_row));
									if(f_model instanceof TWFModelInterface) {
										p.x += _grid.getColSize(col)/2;
									}
									_newrps.add(p);
									_row++;
									if(_row < _grid.getRowCount())
										_cell = _grid.getObject(_row, col);
									else
										break;
								}
								LayoutHelper.removeUnneccesaryPoints(_newrps);
								if(_newrps.size()>0) {
									_o.getSuccessorEdges().get(s).setRoutingPoints(_newrps);
									f_routedEdges.add(_o.getSuccessorEdges().get(s));
								}
							}

						}else if(routeUp(_o, f_succ, s)) {
							//routing upwards
							int _row = row-1;
							if(_row >= 0) {
								FlowObjectWrapper _cell = _grid.getObject(_row, col);
								ArrayList<Point> _newrps = new ArrayList<Point>();
								while((_cell == null) && (_row >=  f_succ.get(s).getPosition().y)) {
									//add routing point
									Point p = new Point(_grid.getX(col),_grid.getY(_row));
									if(f_model instanceof TWFModelInterface) {
										p.x += _grid.getColSize(col)/2;
									}
									_newrps.add(p);
									_row--;
									if(_row >= 0)
										_cell = _grid.getObject(_row, col);
									else
										break;
								}
								LayoutHelper.removeUnneccesaryPoints(_newrps);
								if(_newrps.size()>0) {
									_o.getSuccessorEdges().get(s).setRoutingPoints(_newrps);
									f_routedEdges.add(_o.getSuccessorEdges().get(s));
								}
							}
						}
					}
				}
			}
		}

		ArrayList<FlowObjectWrapper> f_pred = _o.getPredecessors();
		if(f_pred.size() == 1) {
			//x direction first
			if(_o.getPosition().y != f_pred.get(0).getPosition().y) {
				int _col = col-1;
				if(_col >= 0) {
					FlowObjectWrapper _cell = _grid.getObject(row, _col);
					ArrayList<Point> _newrps = new ArrayList<Point>();
					while((_cell == null) && (_col >=  f_pred.get(0).getPosition().x)) {
						//add routing point
						Point p = new Point(_grid.getX(_col),_grid.getY(row));
						_newrps.add(0,p);
						_col--;
					}
					LayoutHelper.removeUnneccesaryPoints(_newrps);
					_o.getPredecessorEdges().get(0).setRoutingPoints(_newrps);
					//checking if the way down/up is entirely free
					if(routeDown(_o, f_pred, 0)) {
						//routing downwards
						int _row = row+1;
						if(_row < _grid.getRowCount()) {
							_cell = _grid.getObject(_row, col);
							while(_row <=  f_pred.get(0).getPosition().y) {
								if(_cell == null) {
									_row++;
									continue;
								}
								//not free!
								_o.getPredecessorEdges().get(0).clearRoutingPoints();
								break;
							}
						}
					}else if(routeUp(_o, f_pred, 0)) {
						//routing upwards
						int _row = row-1;
						if(_row >= 0) {
							_cell = _grid.getObject(_row, col);
							while((_row >=  f_pred.get(0).getPosition().y)) {
								if(_cell == null) {
									_row--;
									continue;
								}
								//not free!
								_o.getPredecessorEdges().get(0).clearRoutingPoints();
								break;
							}
						}
					}
				}
			}
		}else {
			for(int pID = 0;pID<f_pred.size();pID++) {
				if(_o.getPredecessorEdges().get(pID) instanceof BPMNEdgeInterface) {
					if(!((BPMNEdgeInterface)_o.getPredecessorEdges().get(pID)).isMessageFlow()) {
						if(routeDown(_o, f_pred, pID)) {
							//routing downwards
							int _row = row+1;
							if(_row < _grid.getRowCount()) {
								FlowObjectWrapper _cell = _grid.getObject(_row, col);
								ArrayList<Point> _newrps = new ArrayList<Point>();
								while((_cell == null) && (_row <=  f_pred.get(pID).getPosition().y)) {
									//add routing point
									Point p = new Point(_grid.getX(col),_grid.getY(_row));
									if(f_model instanceof TWFModelInterface) {
										p.x -= _grid.getColSize(col)/2;
									}
									_newrps.add(0,p);
									_row++;
									if(_row < _grid.getRowCount())
										_cell = _grid.getObject(_row, col);
								}
								LayoutHelper.removeUnneccesaryPoints(_newrps);
								if(_newrps.size()>0) {
									_o.getPredecessorEdges().get(pID).setRoutingPoints(_newrps);
									f_routedEdges.add(_o.getPredecessorEdges().get(pID));
								}
							}

						}else if(routeUp(_o, f_pred, pID)) {
							//routing upwards
							int _row = row-1;
							if(_row >= 0) {
								FlowObjectWrapper _cell = _grid.getObject(_row, col);
								ArrayList<Point> _newrps = new ArrayList<Point>();
								while((_cell == null) && (_row >=  f_pred.get(pID).getPosition().y)) {
									//add routing point
									Point p = new Point(_grid.getX(col),_grid.getY(_row));
									if(f_model instanceof TWFModelInterface) {
										p.x -= _grid.getColSize(col)/2;
									}
									_newrps.add(0,p);
									_row--;
									if(_row >= 0)
										_cell = _grid.getObject(_row, col);
								}
								LayoutHelper.removeUnneccesaryPoints(_newrps);
								if(_newrps.size()>0) {
									_o.getPredecessorEdges().get(pID).setRoutingPoints(_newrps);
									f_routedEdges.add(_o.getPredecessorEdges().get(pID));
								}
							}
						}
					}
			}
			}
		}
	}

	private boolean routeUp(FlowObjectWrapper _o,ArrayList<FlowObjectWrapper> list, int s) {
		FlowObjectWrapper _o2 = list.get(s);
		return _o2.getGrid() < _o.getGrid() || ( _o2.getGrid() == _o.getGrid() && (_o.getPosition().y > _o2.getPosition().y));
	}

	private boolean routeDown(FlowObjectWrapper _o,ArrayList<FlowObjectWrapper> list, int s) {
		FlowObjectWrapper _o2 = list.get(s);
		return (_o2.getGrid() > _o.getGrid()) || ( _o2.getGrid() == _o.getGrid() && (_o.getPosition().y < _o2.getPosition().y));
	}

	private boolean isGateway(FlowObjectWrapper fow) {
		//general case
		return (fow.isSplit() || fow.isJoin()) && !fow.isDataObject() ;
		//node dependent case
		//return ((BPMNNodeInterface)fow.getWrappedObject()).isGateway();
	}

	protected List<EdgeInterface> getRoutedEdges(){
		return f_routedEdges;
	}

}


text:
josh-library
============

Maintain Josh Library

redpajama_set_name: RedPajamaGithub


text:
"""
Try out different partition assignment algorithms on a simulation trace, and
evaluate their performance.
"""

import argparse
import math
import matplotlib.pyplot as plt
import numpy as np
import os
import pickle

from assign_partitions import AssignmentAlgorithm

def ParseArguments():
    parser = argparse.ArgumentParser(description="Plot times")
    parser.add_argument('--input', type=str, required=True,
                        help="Directory for input files")
    parser.add_argument('--output', type=str, required=True,
                        help="Directory for output files")
    parser.add_argument('--workers', type=int, required=True,
                        help="Number of workers")
    parser.add_argument('--cores', type=int, required=True,
                        help="Number of cores per worker")
    parser.add_argument('--window', type=int, default=10,
                        help="Window (horizon) for analysis")
    return parser.parse_args()

class DynamicGreedyForWindow(object):
    def __init__(self, data, start_iter, end_iter):
        # Initialize data.
        self.partition_time = data.partition_time[:, start_iter:end_iter]
        self.num_workers = data.num_workers
        self.num_cores_per_worker = data.num_cores_per_worker
        self.num_partitions = data.num_partitions
        self.start_iter = start_iter
        self.end_iter = end_iter
        self.window = end_iter - start_iter
        # Assignment for this window.
        self.assignment = np.zeros((self.num_partitions), dtype=int) - 1
        # Maximum and minimum for each partition
        self.max_load = self.partition_time.max(axis=1).flatten()
        self.max_load_time = np.argmax(self.partition_time, axis=1).flatten()
        self.min_load = self.partition_time.min(axis=1).flatten()
        # Store work assigned so far, and other variables to compute assignment.
        self.work_assigned = np.zeros(
          shape=(self.num_workers,  self.window), dtype=float)
        self.work_average = self.partition_time.sum(axis=0)/self.num_workers
        self.next_worker = 0

    def ComputeAssignment(self):
        # Sort them by average amount of load.
        partition_load = self.partition_time.mean(axis=1).flatten()
        order = np.argsort(partition_load)
        order = np.flip(order, axis=0)
        # Assign each partition to least loaded worker.
        for p in order:
            partition_work = self.partition_time[p,:]
            cost_worker = np.zeros((self.num_workers))
            for w in range(self.num_workers):
                worker_assignment = self.work_assigned.copy()
                worker_assignment[w,:] += partition_work
                cost_worker[w] = worker_assignment.max(axis=0).sum()
            #cost_worker = self.work_assigned.mean(axis=1)
            assignment = np.argmin(cost_worker)
            self.assignment[p] = assignment
            self.work_assigned[assignment, :] += self.partition_time[p, :]

    def AssignPartitions(self):
        self.ComputeAssignment()

"""
Perform dynamic greedy assignment from scratch for every window.
"""
class AssignDynamicGreedyFromScratch(AssignmentAlgorithm):
    def __init__(self, num_workers, num_cores_per_worker, partition_time,
                 assignment_window):
        super(AssignDynamicGreedyFromScratch, self).__init__(
          num_workers, num_cores_per_worker, partition_time, -1)
        self.assignment_window = assignment_window

    """
    Compute partition_to_worker for every partition and iteration.
    """
    def AssignPartitions(self):
        print("Applying assignments using dynamic greedy from scratch ...")
        num_windows = int(math.ceil(float(self.num_iterations)/self.assignment_window))
        for i in range(num_windows):
            start_iter = i*self.assignment_window
            end_iter = min(start_iter + self.assignment_window, self.num_iterations)
            helper = DynamicGreedyForWindow(self, start_iter, end_iter)
            helper.AssignPartitions()
            self.partition_to_worker[:,start_iter:end_iter] = helper.assignment.reshape((-1,1))

if __name__ == '__main__':
    args = ParseArguments()
    # Load data.
    partition_time = np.load(os.path.join(args.input, 'partition_time.npy'))
    # Evaluate dynamic greedy partitioning.
    dynamic_greedy_scratch = AssignDynamicGreedyFromScratch(
      args.workers, args.cores, partition_time[:,1:], args.window)
    dynamic_greedy_scratch.RunEvaluation(
      os.path.join(args.output, 'dynamic_greedy_scratch_assignment'))


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

namespace Iodine.Compiler
{
    public class CodeBuilder : CodeObject
    {
        static int nextLabelID = 0;

        readonly Dictionary<int, Label> labelReferences = new Dictionary<int, Label> ();

        protected List<Instruction> instructions = new List<Instruction> ();

        public void EmitInstruction (Opcode opcode)
        {
            instructions.Add (new Instruction (null, opcode));
        }

        public void EmitInstruction (Opcode opcode, int arg)
        {
            instructions.Add (new Instruction (null, opcode, arg));
        }

        public void EmitInstruction (Opcode opcode, IodineObject arg)
        {
            instructions.Add (new Instruction (null, opcode, arg));
        }

        public void EmitInstruction (Opcode opcode, Label label)
        {
            labelReferences [instructions.Count] = label;
            instructions.Add (new Instruction (null, opcode, 0));
        }

        public void EmitInstruction (SourceLocation loc, Opcode opcode)
        {
            instructions.Add (new Instruction (loc, opcode));
        }

        public void EmitInstruction (SourceLocation loc, Opcode opcode, int arg)
        {
            instructions.Add (new Instruction (loc, opcode, arg));
        }

        public void EmitInstruction (SourceLocation loc, Opcode opcode, int arg, IodineObject obj)
        {
            instructions.Add (new Instruction (loc, opcode, arg, obj));
        }

        public void EmitInstruction (SourceLocation loc, Opcode opcode, IodineObject arg)
        {
            instructions.Add (new Instruction (loc, opcode, arg));
        }

        public void EmitInstruction (SourceLocation loc, Opcode opcode, Label label)
        {
            labelReferences [instructions.Count] = label;
            instructions.Add (new Instruction (loc, opcode, 0));
        }

        public Label CreateLabel ()
        {
            return new Label (nextLabelID++);
        }

        public void MarkLabelPosition (Label label)
        {
            label._Position = instructions.Count;
        }

        public void FinalizeMethod ()
        {
            foreach (int position in labelReferences.Keys) {
                instructions [position] = new Instruction (instructions [position].Location,
                    instructions [position].OperationCode,
                    labelReferences [position]._Position
                );
            }
            Instructions = instructions.ToArray ();
        }
    }
}


text:
namespace Merchello.Plugin.Taxation.Taxjar.Services
{
    using System.IO;
    using System.Net;
    using Models;
    using Newtonsoft.Json.Linq;

    internal class TaxJarTaxService : ITaxJarTaxService
    {
        #region Fields

        /// <summary>
        /// The API version.
        /// </summary>
        private readonly string _apiVersion;

        /// <summary>
        /// The api token used in API authentication.
        /// </summary>
        private readonly string _apiToken;

        #endregion
        public TaxJarTaxService(TaxJarProviderSettings settings)
        {
            _apiToken = settings.ApiToken;
            _apiVersion = settings.ApiVersion;
        }

        public TaxResult GetTax(TaxRequest request)
        {
            string url = "https://api.taxjar.com/sales_tax?amount=" + request.Amount
                + "&shipping=" + request.Shipping
                + "&to_country=" + request.ToCountry
                + "&to_state=" + request.ToState
                + "&to_city=" + request.ToCity
                + "&to_zip=" + request.ToZip;
            JObject response = MakeTaxJarApiRequest(url);

            var result = new TaxResult();
            try
            {
                result.TotalTax = (decimal) response["amount_to_collect"];
                result.Rate = (decimal) response["rate"];
                result.HasNexus = (bool) response["has_nexus"];
                if (response["freight_taxable"].HasValues)
                    result.FreightTaxable = (bool) response["freight_taxable"];
                if (response["tax_source"].HasValues)
                    result.TaxSource = (string) response["tax_source"];
                result.Success = true;
            }
            catch
            {
                result.Success = false;
            }

            return result;
        }

        private JObject MakeTaxJarApiRequest(string url)
        {
            var request = (HttpWebRequest)WebRequest.Create(url);
            request.Method = "GET";
            request.Headers.Add("Authorization", "Token token=\"" + this._apiToken + "\"");
            request.UserAgent = "Merchello (https://github.com/Merchello/Merchello)";
            HttpWebResponse response = (HttpWebResponse)request.GetResponse();
            string apiResponse = null;
            using (var reader = new StreamReader(response.GetResponseStream()))
            {
                apiResponse = reader.ReadToEnd();
            }
            return JObject.Parse(apiResponse);
        }
    }
}


text:
<?php

namespace MS\Sentry\Monitor\Command;

use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputArgument;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Symfony\Component\Console\Style\SymfonyStyle;
use Symfony\Component\Process\ProcessBuilder;

class RunCommand extends Command
{
    /**
     * @inheritdoc
     */
    protected function configure()
    {
        $this
            ->setName('run')
            ->setDescription('run sentry monitor server')
            ->addArgument('address', InputArgument::OPTIONAL, 'Address:port', 'localhost:8006')
        ;
    }

    /**
     * @param InputInterface  $input
     * @param OutputInterface $output
     *
     * @return void
     */
    protected function execute(InputInterface $input, OutputInterface $output)
    {
        $io = new SymfonyStyle($input, $output);
        $io->title('Start and run sentry monitor');

        $address = $input->getArgument('address');
        $webPath = __DIR__ . '/../../web';

        $processBuilder = new ProcessBuilder([PHP_BINARY, '-S', $address, $webPath . '/index.php']);
        $processBuilder
            ->setWorkingDirectory($webPath . '/scripts')
            ->setTimeout(null);

        $io->success(sprintf('Server running on "%s"', $address));
        $io->comment('Quit the server with CONTROL-C.');

        $process = $processBuilder->getProcess();
        $process->run();
    }
}


text:
__author__ = 'Matteo Cafasso'
__version__ = '1.0.0'
__license__ = 'BSD-3'

__all__ = ('CLIPSError',
           'Environment',
           'Router',
           'LoggingRouter',
           'ImpliedFact',
           'TemplateFact',
           'Template',
           'Instance',
           'InstanceName',
           'Class',
           'Strategy',
           'SalienceEvaluation',
           'Verbosity',
           'ClassDefaultMode',
           'TemplateSlotDefaultType',
           'Symbol',
           'InstanceName',
           'SaveMode')

from clips.environment import Environment
from clips.classes import Instance, Class
from clips.values import Symbol, InstanceName
from clips.routers import Router, LoggingRouter
from clips.facts import ImpliedFact, TemplateFact, Template
from clips.common import SaveMode, Strategy, SalienceEvaluation, Verbosity
from clips.common import CLIPSError, ClassDefaultMode, TemplateSlotDefaultType


text:
package de.uni_hildesheim.sse.system.fallback;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

import de.uni_hildesheim.sse.system.IThreadDataGatherer;

/**
 * Implements a thread data gatherer for the Java platform (using JMX
 * functionality). Be careful as JMX for CPU time on Java 1.7 pollutes the
 * memory with long arrays.
 *
 * @author Holger Eichelberger
 * @since 1.20
 * @version 1.20
 */
public class ThreadDataGatherer implements IThreadDataGatherer {

    /**
     * Stores the JMX thread bean. [Convenience]
     */
    private static final ThreadMXBean THREAD_MX
        = ManagementFactory.getThreadMXBean();

    /**
     * Stores whether thread CPU ticks are supported by the JMX thread bean.
     */
    private static final boolean THREAD_CPU_TICKS_ENABLED;

    /**
     * Checks JMX capabilities and initializes the threads map.
     */
    static {
        boolean useThreadCpuTicks = false;
        if (THREAD_MX.isThreadCpuTimeSupported()) {
            if (!THREAD_MX.isThreadCpuTimeEnabled()) {
                try {
                    THREAD_MX.setThreadCpuTimeEnabled(true);
                    useThreadCpuTicks = true;
                } catch (UnsupportedOperationException e) {
                } catch (SecurityException e) {
                }
            } else {
                useThreadCpuTicks = true;
            }
        }
        THREAD_CPU_TICKS_ENABLED = useThreadCpuTicks;
    }

    @Override
    public long[] getAllThreadIds() {
        return THREAD_MX.getAllThreadIds();
    }

    @Override
    public long getCpuTime(long threadId) {
        long result = 0;
        if (THREAD_CPU_TICKS_ENABLED) {
            result = THREAD_MX.getThreadCpuTime(threadId);
        }
        return result;
    }

    /**
     * Returns the number of the CPU time consumed by all threads of this JVM.
     *
     * @return the number of all ticks, 0 if not available
     *
     * @since 1.00
     */
    public long getAllTicks() {
        long count = 0;
        if (THREAD_CPU_TICKS_ENABLED) {
            for (Thread t : Thread.getAllStackTraces().keySet()) {
                count += THREAD_MX.getThreadCpuTime(t.getId());
            }
        }
        return count;
    }

    @Override
    public long getAllCpuTime() {
        long count = 0;
        if (THREAD_CPU_TICKS_ENABLED) {
            for (Thread t : Thread.getAllStackTraces().keySet()) {
                count += THREAD_MX.getThreadCpuTime(t.getId());
            }
        }
        return count;
    }

    @Override
    public long getCurrentCpuTime() {
        long result = 0;
        if (THREAD_CPU_TICKS_ENABLED) {
            result = THREAD_MX.getCurrentThreadCpuTime();
        }
        return result;
    }

    @Override
    public long getCurrentId() {
        return Thread.currentThread().getId();
    }

}


text:
<?php

/**
 * @file
 * Contains \Drupal\Tests\Core\Render\Element\MachineNameTest.
 */

namespace Drupal\Tests\Core\Render\Element;

use Drupal\Core\Form\FormStateInterface;
use Drupal\Core\Render\Element\MachineName;
use Drupal\Tests\UnitTestCase;

/**
 * @coversDefaultClass \Drupal\Core\Render\Element\MachineName
 * @group Render
 */
class MachineNameTest extends UnitTestCase {

  /**
   * @covers ::valueCallback
   *
   * @dataProvider providerTestValueCallback
   */
  public function testValueCallback($expected, $input) {
    $element = [];
    $form_state = $this->prophesize(FormStateInterface::class)->reveal();
    $this->assertSame($expected, MachineName::valueCallback($element, $input, $form_state));
  }

  /**
   * Data provider for testValueCallback().
   */
  public function providerTestValueCallback() {
    $data = [];
    $data[] = [NULL, FALSE];
    $data[] = [NULL, NULL];
    $data[] = ['', ['test']];
    $data[] = ['test', 'test'];
    $data[] = ['123', 123];

    return $data;
  }

}


text:
<!DOCTYPE html>
<body id="element0">
</body>


text:
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({ name: 'ngxNumberWithCommas' })
export class NumberWithCommasPipe implements PipeTransform {

  transform(input: number): string {
    return new Intl.NumberFormat().format(input);
  }
}


text:
<?php

namespace Browscap\Generator;

use Browscap\Helper\CollectionCreator;
use Browscap\Writer;

/**
 * Class BuildGenerator
 *
 * @category   Browscap
 * @package    Generator
 * @author     James Titcumb <james@asgrim.com>
 * @author     Thomas Müller <t_mueller_stolzenhain@yahoo.de>
 */
class BuildCustomFileGenerator extends AbstractBuildGenerator
{
    /**@+
     * @var string
     */
    const OUTPUT_FORMAT_PHP  = 'php';
    const OUTPUT_FORMAT_ASP  = 'asp';
    const OUTPUT_FORMAT_CSV  = 'csv';
    const OUTPUT_FORMAT_XML  = 'xml';
    const OUTPUT_FORMAT_JSON = 'json';
    /**@-*/

    /**@+
     * @var string
     */
    const OUTPUT_TYPE_FULL    = 'full';
    const OUTPUT_TYPE_DEFAULT = 'normal';
    const OUTPUT_TYPE_LITE    = 'lite';
    /**@-*/

    /**
     * Entry point for generating builds for a specified version
     *
     * @param string      $version
     * @param array       $fields
     * @param string|null $file
     * @param string      $format
     *
     * @return \Browscap\Generator\BuildCustomFileGenerator
     */
    public function run(
        $version,
        $fields = array(),
        $file = null,
        $format = self::OUTPUT_FORMAT_PHP
    ) {
        return $this
            ->preBuild($fields, $file, $format)
            ->build($version)
            ->postBuild()
        ;
    }

    /**
     * runs before the build
     *
     * @param array       $fields
     * @param string|null $file
     * @param string      $format
     *
     * @return \Browscap\Generator\BuildCustomFileGenerator
     */
    protected function preBuild(
        $fields = array(),
        $file = null,
        $format = self::OUTPUT_FORMAT_PHP
    ) {
        parent::preBuild();

        $this->getLogger()->info('started creating the custom output file');

        if (null === $this->collectionCreator) {
            $this->setCollectionCreator(new CollectionCreator());
        }

        if (null === $this->writerCollection) {
            $factory = new Writer\Factory\CustomWriterFactory();

            $this->setWriterCollection(
                $factory->createCollection(
                    $this->getLogger(),
                    $this->buildFolder,
                    $file,
                    $fields,
                    $format
                )
            );
        }

        return $this;
    }

    /**
     * runs after the build
     *
     * @return \Browscap\Generator\BuildCustomFileGenerator
     */
    protected function postBuild()
    {
        $this->getLogger()->info('finished creating the custom output file');

        return $this;
    }
}


text:
using System.IO;

namespace TS.CodeGenerator
{
    public interface IAssemblyReader
    {
        Stream GenerateTypingsStream();
        string GenerateTypingsString();
    }
}


text:
package org.hibernate.service.jdbc.dialect.internal;

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

import org.hibernate.HibernateException;
import org.hibernate.cfg.AvailableSettings;
import org.hibernate.internal.util.StringHelper;
import org.hibernate.service.classloading.spi.ClassLoaderService;
import org.hibernate.service.jdbc.dialect.spi.DialectResolver;
import org.hibernate.service.spi.BasicServiceInitiator;
import org.hibernate.service.spi.ServiceException;
import org.hibernate.service.spi.ServiceRegistryImplementor;

/**
 * Standard initiator for the standard {@link DialectResolver} service
 *
 * @author Steve Ebersole
 */
public class DialectResolverInitiator implements BasicServiceInitiator<DialectResolver> {
	public static final DialectResolverInitiator INSTANCE = new DialectResolverInitiator();

	@Override
	public Class<DialectResolver> getServiceInitiated() {
		return DialectResolver.class;
	}

	@Override
	public DialectResolver initiateService(Map configurationValues, ServiceRegistryImplementor registry) {
		return new DialectResolverSet( determineResolvers( configurationValues, registry ) );
	}

	private List<DialectResolver> determineResolvers(Map configurationValues, ServiceRegistryImplementor registry) {
		final List<DialectResolver> resolvers = new ArrayList<DialectResolver>();

		final String resolverImplNames = (String) configurationValues.get( AvailableSettings.DIALECT_RESOLVERS );

		if ( StringHelper.isNotEmpty( resolverImplNames ) ) {
			final ClassLoaderService classLoaderService = registry.getService( ClassLoaderService.class );
			for ( String resolverImplName : StringHelper.split( ", \n\r\f\t", resolverImplNames ) ) {
				try {
					resolvers.add( (DialectResolver) classLoaderService.classForName( resolverImplName ).newInstance() );
				}
				catch (HibernateException e) {
					throw e;
				}
				catch (Exception e) {
					throw new ServiceException( "Unable to instantiate named dialect resolver [" + resolverImplName + "]", e );
				}
			}
		}

		resolvers.add( new StandardDialectResolver() );
		return resolvers;
	}
}


text:
static EDFilesystemItem *sRootItem = nil;
static NSMutableArray *sLeafNode = nil;
static NSMutableDictionary *sCache = nil;

@interface EDFilesystemItem ()
- (id)initWithFullPath:(NSString *)path;

@property (nonatomic, copy, readwrite) NSString *fullPath;
@property (nonatomic, copy, readwrite) NSString *relativePath;
@property (nonatomic, retain, readwrite) NSMutableArray *children;
@property (nonatomic, retain, readwrite) NSImage *icon;
@end

@implementation EDFilesystemItem

+ (void)initialize {
    if ([EDFilesystemItem class] == self) {
        sLeafNode = [[NSMutableArray alloc] init];
        [self clearCache];
    }
}

+ (NSString *)pasteboardType {
    return NSStringFromClass(self);
}

+ (EDFilesystemItem *)rootItem {
    EDAssert(0);
    if (sRootItem == nil) {
        sRootItem = [[EDFilesystemItem itemWithFullPath:@"/"] retain];
    }
    return sRootItem;
}

+ (void)clearCache {
//    [sRootItem autorelease];
//    sRootItem = nil;

    [sCache autorelease];
    sCache = [[NSMutableDictionary alloc] init];
}

+ (EDFilesystemItem *)itemWithFullPath:(NSString *)fullPath {

    EDFilesystemItem *item = nil;

    BOOL wantsCache = ![fullPath hasPrefix:EDProjectSettingsURL];
    if (wantsCache) {
        item = [sCache objectForKey:fullPath];
    }

    if (!item) {
        item = [[[EDFilesystemItem alloc] initWithFullPath:fullPath] autorelease];
        if (wantsCache) {
            [sCache setObject:item forKey:fullPath];
        }
    }

    return item;
}

- (id)initWithFullPath:(NSString *)fullPath {
    self = [super init];
    if (self) {
        // unforunately, this is required, or the NSString methods below change exedore:// to exedore:/
        if ([fullPath isEqualToString:EDProjectSettingsURL]) {
            self.fullPath = fullPath;
            self.relativePath = fullPath;
        } else {
            self.fullPath = [fullPath stringByExpandingTildeInPath];
            self.relativePath = [fullPath lastPathComponent];
        }
        EDAssert([_fullPath length]);
        EDAssert([_relativePath length]);
    }
    return self;
}

- (void)dealloc {
    self.fullPath = nil;
    self.relativePath = nil;
    self.children = nil;
    self.icon = nil;
    [super dealloc];
}

- (id)initWithCoder:(NSCoder *)coder {
    self.fullPath = [coder decodeObjectForKey:@"fullPath"];
    EDAssert(_fullPath);

    self.relativePath = [_fullPath lastPathComponent];
//    self.children = [coder decodeObjectForKey:@"children"];

    return self;
}

- (void)encodeWithCoder:(NSCoder *)coder {
    [coder encodeObject:_fullPath forKey:@"fullPath"];
//    [coder encodeObject:_children forKey:@"children"];
}

- (NSString *)description {
    return [NSString stringWithFormat:@"<%@ %p %@>", [self class], self, _fullPath];
}

- (BOOL)isEqual:(id)obj {
    if (![obj isKindOfClass:[EDFilesystemItem class]]) {
        return NO;
    }

    EDFilesystemItem *fsItem = (EDFilesystemItem *)obj;
    return [self.fullPath isEqualToString:fsItem.fullPath];
}

- (void)reloadChildren {
    for (EDFilesystemItem *child in _children) {
        [child reloadChildren];
    }

    self.children = nil;
}

- (BOOL)shouldExclude:(NSString *)filename {
    BOOL exclude = NO;

    NSArray *pats = [[EDUserDefaults instance] excludeFilePatterns];
    for (EDPattern *pat in pats) {
        if ([pat isMatch:filename]) {
            exclude = YES;
            break;
        }
    }

    return exclude;
}

// Creates, caches, and returns the array of children
// Loads children incrementally
- (NSArray *)children {
    EDAssert([_fullPath length]);

    if (!_children) {
        NSFileManager *mgr = [NSFileManager defaultManager];

        BOOL isDir;
        if ([mgr fileExistsAtPath:_fullPath isDirectory:&isDir] && isDir) {
            NSArray *filenames = [mgr contentsOfDirectoryAtPath:_fullPath error:nil];

            NSMutableArray *arr = [NSMutableArray arrayWithCapacity:[filenames count]];

            for (NSString *filename in filenames) {
                if ([filename hasPrefix:@"."] || [self shouldExclude:filename]) continue;

                NSString *childPath = [_fullPath stringByAppendingPathComponent:filename];
                EDFilesystemItem *newChild = [EDFilesystemItem itemWithFullPath:childPath];
                [arr addObject:newChild];
            }

            self.children = arr;
        } else {
            self.children = sLeafNode;
        }
    }

    EDAssert(_children);
    return _children;
}

- (EDFilesystemItem *)childAtIndex:(NSUInteger)n {
    return [self.children objectAtIndex:n];
}

- (EDFilesystemItem *)descendantAtFullPath:(NSString *)targetPath {
    EDFilesystemItem *target = nil;

    if ([targetPath hasPrefix:_fullPath]) {
        if ([targetPath isEqualToString:_fullPath]) return self;

        NSUInteger len = [_fullPath length];
        NSString *childName = [[targetPath substringFromIndex:len] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"/"]];
        NSArray *comps = [childName componentsSeparatedByString:@"/"];
        childName = [comps objectAtIndex:0];

        for (EDFilesystemItem *child in self.children) {
            if ([child.relativePath isEqualToString:childName]) {
                return [child descendantAtFullPath:targetPath];
                break;
            }
        }

    }

    return target;
}

- (BOOL)isLeaf {
    // must go thru getter here
    BOOL result = self.children == sLeafNode;
    return result;
}

- (NSInteger)numberOfChildren {
    NSInteger c = self.isLeaf ? (-1) : [self.children count];
    return c;
}

@end


text:
package momentum.async;

public interface Receiver {
  /*
   * Invoked with the realized value.
   */
  void success(Object val);

  /*
   * Invoked with the aborted error
   */
  void error(Exception err);
}


text:
package io.iteratee.testing

import io.iteratee.{ Enumerator, EnumeratorModule, Iteratee, IterateeModule, Module }
import org.scalacheck.{ Arbitrary, Gen }

trait ArbitraryEnumerators[F[_]] {
  this: ModuleSuite[F] with Module[F] with EnumeratorModule[F] with IterateeModule[F] =>

  case class EnumeratorAndValues[A](enumerator: Enumerator[F, A], values: Vector[A]) {
    def resultWithLeftovers[Z](iteratee: Iteratee[F, A, Z]): F[(Z, Vector[A])] = enumerator.into(
      iteratee.flatMap(result => consume[A].map(leftovers => (result, leftovers))(F))(F)
    )(F)
  }

  private[this] val maxDepth = 4

  private[this] def appendGenerator[A: Arbitrary](depth: Int): List[Gen[EnumeratorAndValues[A]]] =
    if (depth < maxDepth) List(
      for {
        EnumeratorAndValues(enumerator1, list1) <- generate[A](depth + 1)
        EnumeratorAndValues(enumerator2, list2) <- generate[A](depth + 1)
      } yield EnumeratorAndValues(enumerator1.append(enumerator2)(F), list1 ++ list2)
    ) else Nil

  private[this] def generate[A](depth: Int)(implicit A: Arbitrary[A]): Gen[EnumeratorAndValues[A]] =
    Gen.oneOf(
      Gen.const(EnumeratorAndValues[A](empty, Vector.empty)),
      A.arbitrary.map(a => EnumeratorAndValues(enumOne(a), Vector(a))),
      (
        for {
          vals <- Gen.listOf(A.arbitrary)
          enumerator <- Gen.oneOf(
            enumStream(vals.toStream),
            enumList(vals),
            enumVector(vals.toVector)
          )
        } yield EnumeratorAndValues(enumerator, vals.toVector)
      ) :: appendGenerator[A](depth): _*
    )

  implicit def arbitraryEnumeratorAndValues[A: Arbitrary]: Arbitrary[EnumeratorAndValues[A]] =
    Arbitrary(generate(0))
}


text:
using content::BrowserThread;

namespace util = app_notification_test_util;

class AppNotificationStorageTest : public testing::Test {
 public:
  AppNotificationStorageTest() :
      file_thread_(BrowserThread::FILE, &message_loop_) {}
  virtual ~AppNotificationStorageTest() {}

  virtual void SetUp() OVERRIDE {
    ASSERT_TRUE(dir_.CreateUniqueTempDir());
    storage_path_ = dir_.path().AppendASCII("App Notifications");
    storage_.reset(AppNotificationStorage::Create(storage_path_));
    ASSERT_TRUE(storage_.get() != NULL);
  }

 protected:
  // Returns whether the database file(s) exist on disk yet.
  bool DatabaseExistsOnDisk() {
    if (!storage_.get())
      return false;

    return file_util::PathExists(storage_path_);
  }

  MessageLoop message_loop_;
  content::TestBrowserThread file_thread_;
  ScopedTempDir dir_;
  FilePath storage_path_;
  scoped_ptr<AppNotificationStorage> storage_;
};

// Tests simple operations.
TEST_F(AppNotificationStorageTest, Basics) {
  std::set<std::string> tmp_ids;
  AppNotificationList tmp_list;
  std::string id1 = extension_test_util::MakeId("1");

  // Try operations on non-existent keys.
  EXPECT_TRUE(storage_->GetExtensionIds(&tmp_ids));
  EXPECT_TRUE(tmp_ids.empty());
  EXPECT_TRUE(storage_->Get(id1, &tmp_list));
  EXPECT_TRUE(tmp_list.empty());
  EXPECT_TRUE(storage_->Delete(id1));
  EXPECT_FALSE(DatabaseExistsOnDisk());

  // Add some items.
  AppNotificationList list;
  util::AddNotifications(&list, id1, 2, "whatever");
  EXPECT_TRUE(storage_->Set(id1, list));
  EXPECT_TRUE(DatabaseExistsOnDisk());

  // Try getting them back.
  tmp_list.clear();
  EXPECT_TRUE(storage_->Get(id1, &tmp_list));
  util::ExpectListsEqual(list, tmp_list);
  EXPECT_TRUE(storage_->GetExtensionIds(&tmp_ids));
  EXPECT_EQ(tmp_ids.size(), 1U);
  EXPECT_TRUE(ContainsKey(tmp_ids, id1));
}

// Tests with multiple extensions.
TEST_F(AppNotificationStorageTest, MultipleExtensions) {
  std::string id1 = extension_test_util::MakeId("1");
  std::string id2 = extension_test_util::MakeId("2");

  // Add items for id1.
  AppNotificationList list1;
  util::AddNotifications(&list1, id1, 2, "one");
  EXPECT_TRUE(storage_->Set(id1, list1));

  // Add items for id2.
  AppNotificationList list2;
  util::AddNotifications(&list2, id2, 3, "two");
  EXPECT_TRUE(storage_->Set(id2, list2));

  // Verify the items are present
  std::set<std::string> tmp_ids;
  EXPECT_TRUE(storage_->GetExtensionIds(&tmp_ids));
  EXPECT_EQ(tmp_ids.size(), 2U);
  EXPECT_TRUE(ContainsKey(tmp_ids, id1));
  EXPECT_TRUE(ContainsKey(tmp_ids, id2));

  AppNotificationList tmp_list;
  EXPECT_TRUE(storage_->Get(id1, &tmp_list));
  util::ExpectListsEqual(tmp_list, list1);
  tmp_list.clear();
  EXPECT_TRUE(storage_->Get(id2, &tmp_list));
  util::ExpectListsEqual(tmp_list, list2);

  // Delete the id1 items and check the results.
  EXPECT_TRUE(storage_->Delete(id1));
  tmp_ids.clear();
  EXPECT_TRUE(storage_->GetExtensionIds(&tmp_ids));
  EXPECT_EQ(tmp_ids.size(), 1U);
  EXPECT_FALSE(ContainsKey(tmp_ids, id1));
  EXPECT_TRUE(ContainsKey(tmp_ids, id2));
  tmp_list.clear();
  EXPECT_TRUE(storage_->Get(id1, &tmp_list));
  EXPECT_TRUE(tmp_list.empty());
  tmp_list.clear();
  EXPECT_TRUE(storage_->Get(id2, &tmp_list));
  util::ExpectListsEqual(tmp_list, list2);
}

// Tests using Set to replace existing entries.
TEST_F(AppNotificationStorageTest, ReplaceExisting) {
  std::string id = extension_test_util::MakeId("1");
  AppNotificationList list1;
  AppNotificationList list2;
  util::AddNotifications(&list1, id, 5, "one");
  util::AddNotifications(&list2, id, 7, "two");

  // Put list1 in, then replace with list2 and verify we get list2 back.
  EXPECT_TRUE(storage_->Set(id, list1));
  EXPECT_TRUE(storage_->Set(id, list2));
  AppNotificationList tmp_list;
  EXPECT_TRUE(storage_->Get(id, &tmp_list));
  util::ExpectListsEqual(list2, tmp_list);
}


text:
package org.hisp.dhis.interceptor;

import javax.servlet.http.HttpServletResponse;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.interceptor.Interceptor;

/**
 * @author Lars Helge Overland
 */
public class CacheInterceptor
    implements Interceptor
{
    private int seconds = 86400; // One day

    public void setSeconds( int seconds )
    {
        this.seconds = seconds;
    }

    @Override
    public String intercept( ActionInvocation invocation )
        throws Exception
    {
        HttpServletResponse response = ServletActionContext.getResponse();

        response.setHeader( "Cache-Control", "public, max-age=" + seconds );

        return invocation.invoke();
    }

    @Override
    public void destroy()
    {
    }

    @Override
    public void init()
    {
    }
}


text:
<?php

namespace Tests\Fhp\DataElementGroups;

use Fhp\DataElementGroups\HashAlgorithm;

class HashAlgorithmTest extends \PHPUnit_Framework_TestCase
{
    public function test_to_string()
    {
        $e = new HashAlgorithm();
        $this->assertEquals('1:999:1', (string) $e);
        $this->assertEquals('1:999:1', $e->toString());
    }
}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
AASP Contributions Series (Dallas) 39: 193 (2000)

#### Original name
Multicellaesporites pandus Sheffy & Dilcher

### Remarks
null


text:
package ai.h2o.api.proto.frames;

import ai.h2o.api.GrpcUtils;
import ai.h2o.api.proto.core.JobInfo;
import ai.h2o.api.proto.core.JobService;
import hex.createframe.recipes.SimpleCreateFrameRecipe;
import io.grpc.stub.StreamObserver;
import water.Job;
import water.Key;
import water.fvec.Frame;

/**
 */
public class CreateFrameService extends CreateFrameGrpc.CreateFrameImplBase {

  @Override
  public void simple(CreateFrameSimpleSpec request, StreamObserver<JobInfo> responseObserver) {
    try {
      SimpleCreateFrameRecipe cf = new SimpleCreateFrameRecipe();
      cf.dest = Key.make(request.getTargetId());
      cf.seed = request.getSeed();
      cf.nrows = request.getNrows();
      cf.ncols_real = request.getNcolsReal();
      cf.ncols_int = request.getNcolsInt();
      cf.ncols_enum = request.getNcolsEnum();
      cf.ncols_bool = request.getNcolsBool();
      cf.ncols_str = request.getNcolsStr();
      cf.ncols_time = request.getNcolsTime();
      cf.real_lb = request.getRealLb();
      cf.real_ub = request.getRealUb();
      cf.int_lb = request.getIntLb();
      cf.int_ub = request.getIntUb();
      cf.enum_nlevels = request.getEnumNlevels();
      cf.bool_p = request.getBoolP();
      cf.time_lb = request.getTimeLb();
      cf.time_ub = request.getTimeUb();
      cf.str_length = request.getStrLength();
      cf.missing_fraction = request.getMissingFraction();
      cf.response_type = SimpleCreateFrameRecipe.ResponseType.valueOf(request.getResponseType().toString());
      cf.response_lb = request.getResponseLb();
      cf.response_ub = request.getResponseUb();
      cf.response_p = request.getResponseP();
      cf.response_nlevels = request.getResponseNlevels();

      Job<Frame> job = cf.exec();
      responseObserver.onNext(JobService.fillJobInfo(job));
      responseObserver.onCompleted();

    } catch (Throwable ex) {
      GrpcUtils.sendError(ex, responseObserver, JobInfo.class);
    }
  }

}


text:
using namespace std;

bool gzipInflate ( const std::string& compressedBytes, std::string& uncompressedBytes ) {
    if ( compressedBytes.size() == 0 ) {
        uncompressedBytes = compressedBytes ;
        return true ;
    }

    uncompressedBytes.clear() ;
    unsigned full_length = compressedBytes.size() ;
    unsigned half_length = compressedBytes.size() / 2;
    unsigned uncompLength = full_length ;
    char* uncomp = ( char* ) calloc ( sizeof ( char ), uncompLength );
    z_stream strm;
    strm.next_in = ( Bytef* ) compressedBytes.c_str();
    strm.avail_in = compressedBytes.size() ;
    strm.total_out = 0;
    strm.zalloc = Z_NULL;
    strm.zfree = Z_NULL;
    bool done = false ;

    if ( inflateInit2 ( &strm, ( 16 + MAX_WBITS ) ) != Z_OK ) {
        free ( uncomp );
        return false;
    }

    while ( !done ) {
        // If our output buffer is too small
        if ( strm.total_out >= uncompLength ) {
            // Increase size of output buffer
            char* uncomp2 = ( char* ) calloc ( sizeof ( char ), uncompLength + half_length );
            memcpy ( uncomp2, uncomp, uncompLength );
            uncompLength += half_length ;
            free ( uncomp );
            uncomp = uncomp2 ;
        }

        strm.next_out = ( Bytef* ) ( uncomp + strm.total_out );
        strm.avail_out = uncompLength - strm.total_out;
        // Inflate another chunk.
        int err = inflate ( &strm, Z_SYNC_FLUSH );

        if ( err == Z_STREAM_END ) { done = true; }

        else if ( err != Z_OK )  {
            break;
        }
    }

    if ( inflateEnd ( &strm ) != Z_OK ) {
        free ( uncomp );
        return false;
    }

    for ( size_t i = 0; i < strm.total_out; ++i ) {
        uncompressedBytes += uncomp[ i ];
    }

    free ( uncomp );
    return true ;
}


text:
package com.sicdlib.service.pythonService;

import com.sicdlib.dto.entity.KdnetCommentEntity;

/**
 * Created by init on 2017/6/5.
 */
public interface IKDNETCommentService {
    //更新或新增凯迪社区
    boolean saveKDNETComment(KdnetCommentEntity kdnetComment);
}


text:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<servico xsi:schemaLocation="http://servicos.gov.br/v3/schema.../servico.xsd" xmlns="http://servicos.gov.br/v3/schema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
    <id>participar-de-eventos-cientificos-da-fundacao-casa-de-rui-barbosa</id>
    <dbId>2367</dbId>
    <nome>Participar de eventos científicos da Fundação Casa de Rui Barbosa</nome>
    <sigla></sigla>
    <descricao>A Fundação oferece ao público eventos científicos na área da Cultura. Os interessados em participar das atividades oferecidas devem inscrever-se, mediante preenchimento de formulário de inscrição.</descricao>
    <contato></contato>
    <gratuito>true</gratuito>
    <porcentagem-manual>false</porcentagem-manual>
    <servico-digital>false</servico-digital>
    <link-servico-digital></link-servico-digital>
    <solicitantes>
        <solicitante id="2920">
            <tipo>Qualquer pessoa pode se inscrever para participar dos eventos científicos.</tipo>
            <requisitos></requisitos>
        </solicitante>
    </solicitantes>
    <tempo-total-estimado>
        <nao-estimado-ainda/>
        <descricao></descricao>
    </tempo-total-estimado>
    <validade-documento>
        <descricao></descricao>
    </validade-documento>
    <etapas>
        <etapa id="5704">
            <titulo>Inscrever-se</titulo>
            <descricao></descricao>
            <documentos>
                <default>
                    <item id="6696">Documento de identificação oficial com foto</item>
                </default>
            </documentos>
            <custos>
                <default/>
            </custos>
            <canais-de-prestacao>
                <default>
                    <canal-de-prestacao id="5551" tipo="presencial">
                        <descricao>**Fundação Casa de Rui Barbosa** - Rua São Clemente, 134 - Botafogo - CEP: 22260-000 - Rio de Janeiro, RJ</descricao>
                    </canal-de-prestacao>
                </default>
            </canais-de-prestacao>
        </etapa>
    </etapas>
    <orgao id="http://estruturaorganizacional.dados.gov.br/id/unidade-organizacional/261" dbId="34301">
        <nomeOrgao>Fundação Casa de Rui Barbosa (FCRB)</nomeOrgao>
    </orgao>
    <segmentos-da-sociedade>
        <item idSegmento="1" idServicoSegmento="5658">Cidadãos</item>
    </segmentos-da-sociedade>
    <areas-de-interesse>
        <item>Cultura</item>
        <item>Educação</item>
        <item>Pesquisa e Desenvolvimento</item>
        <item>Difusão Cultural</item>
        <item>Difusão</item>
        <item>Pesquisa, Ciência, Inovação e Tecnologia</item>
    </areas-de-interesse>
    <palavras-chave>
        <item id="10811">evento científico</item>
        <item id="10812">palestras</item>
        <item id="10813">casa de rui barbosa</item>
    </palavras-chave>
</servico>


text:
require 'heia_heia'

RSpec.configure do |config|
  config.mock_with :rspec
  config.order = "random"
end


text:
package com.commercehub.clouseau.graph.format;

/**
 * @author pmogren
 */
public class ToString implements ObjectGraphFormatter {
    @Override
    public String formatObjectGraph(Object graph) {
        return graph == null ? null : graph.toString();
    }
}


text:
# compiler
This is an implementation of a Tiger compiler following the book "Modern Compiler Implementation in ML" by Andrew W. Appel and the instructions of Guido Macchi (and assistance from Guillermo Grinblat and Martín Ceresa) for a Computer Science course. Tiger is a simple, statically-typed programming language with nested functions first introduced in the aforementioned book.

Build for x86-64 architecture it uses GCC compiler, tested in Linux.

## Authors
* Aldana Ramirez
* Lautaro Rinaldi
* Martín Villagra

## Extensions
Besides the basic parts of the compiler the following features were implemented:

### includes
Include a file inside the let construction. Example:
```
let
  include "other_definitions.tigd"
in
  0
end
```
This feature was implemented by adding an extra stage just after parsing, where includes are replaced for the contents of the included files. Extra care was taken for detecting include loops. Implementation lives on `tigerinclude.sml`.

We ended up with 164 tests for the tiger compiler.

### extern
Added an `extern` keyword to declarate extern functions, this enables calling C functions from Tiger or to use any external library. Example:
```
let
  type SDL_Window = {}
  type SDL_Surface = {}
  extern function SDL_GetWindowSurface(win:SDL_Window):SDL_Surface
in
  SDL_GetWindowSurface(nil);
  0
end
```
It was implemented by only editing the parser (`tigergrm.y`) as the compiler was already handling `extern` functions.

### gcc flags
All unrecognized flags are passed to gcc, which generates the executable code on the last stage. This enables passing parameters to the linking process, which is specially useful for projects requiring libraries. This is implemented in `tigermain.sml`.

Example:
```
./tiger ../juego/main.tig -lSDL2 -lSDL2_ttf -lSDL2_image -lSDL2_mixer ../juego/lib.c
```

### optimization 1: Representation of sets
During liveness analysis, following the suggestion from the book on page 216, we represent sets as ordered lists which drastically reduced the time of that step. This can be seen on `tigerliveness.sml`.

### optimization 2: Ordering the nodes
During liveness analysis, we implemented the optimization mentioned in the book on page 389. This greatly reduces compilation time by topological sorting the flow graph and use the order to process the nodes, thus reaching the fixed point much faster. Implemented on `tigerliveness.sml`.

### test automatization
We developed a simple script to run and maintain a test suite. Each test was added manually, it consists of a code and the expected output of the compiler and its execution. We do a small parsing of the first line of the code of the test in order to embed what parameters should be passed to the compiler (for example to print intermediate trees). This enables to create and maintain the test suite even when not all stages of the compiler are finished. It has saved us a lot of time by detecing bugs early and to avoid introducing new ones. The script is `tests/test` and is written in Bash.

We ended up with 164 tests for the tiger compiler.

Example test:

> liveness/hello.tig
```
/*TIGER_ARGS=-code -flow*/
(print ("Hello World");0)
```

> liveness/hello.out
```bien!
;;--FRAME--L0__tigermain_0:
LABEL: L3
MOVE: movq %'s0, %'d0 D:T2 S:rbx
MOVE: movq %'s0, %'d0 D:T3 S:r12
...
	n22(LABEL: L2): n23
	n23(OPER:  D:[] S:[rax,rsp,rbp,rbx,r12,r13,r14,r15]):
;;-END-FLOW-:
yes!!
Hello World
Return code: 0
```

Screenshot:

![Screenshot of tests running](https://raw.githubusercontent.com/vmartinv/compiler/master/screenshots/test_script.png)

### sokoban game
By using some of the features implemented small game was programmed. It uses `SDL 2` C library and function wrappers in `juego/lib.c` has been written to call functions with strings (as C strings are diferent from Tiger strings). You can run it by:
1. Installing SDL2 (with image, mixer and TTF libs).

  For Ubuntu:

    follow this link https://gist.github.com/BoredBored/3187339a99f7786c25075d4d9c80fad5

  For Arch Linux:

    sudo pacman -S sdl2 sdl2_image sdl2_mixer sdl2_ttf

2. Run in a terminal:
  > cd juego

  > cd make run

Screenshot:

![Screenshot of first level of the game](https://raw.githubusercontent.com/vmartinv/compiler/master/screenshots/juego.png)

### compiler pipeline
We encapsulated each stage of the compiler in a function and by defining the operator `>>=` we are able to write the entire compiler as a series of steps in a very clear way:

```
fun perFragment fragment =
    fragment >>= instructionSel >>= prntCode >>=
        debugLivenessAnalysis
        >>= coloreo
        >>= prntColor
        >>= procExit3
        >>= formatter

source_filename >>= abreArchivo >>=
   lexer >>= parser >>= (*de ASCII al arbol tigerabs.exp*)
   expIncludes >>=  (*etapa agregada para que funcionen los includes*)
   escap >>= prntArbol >>=
   seman >>= prntIr >>= (*chequeo de tipos y generacion de fragmentos*)
   canonize >>= prntCanon >>=
   (fn (stringList, frags) => (stringList, map perFragment frags)) >>=
   serializer >>= prntAsm >>=
   compileAsm >>=
   prntOk (*si llega hasta aca esta todo ok*)
```

Implemented on `tigermain.sml`.

### compiler diagram
A diagram was created showing the main stages of the compiler.

Original document:

  https://drive.google.com/file/d/0ByI9GfoY63_aTDFaUjVLRjVwM1k/view?usp=sharing

Image preview:

![Diagram of the compiler](https://raw.githubusercontent.com/vmartinv/compiler/master/screenshots/etapas.png)

### file opener
All source files start with `tiger` and there are many files with the same name but different extensions (some come from compilation subproducts). For this reason we found ourselves spending a lot of time looking for the specific files we wanted to open. For this reason we made a small script to list and open the sources files easily. Implementation is in `src/e` and is written in Bash.

Screenshot:

![Screenshot of file opener](https://raw.githubusercontent.com/vmartinv/compiler/master/screenshots/e_script.png)

### open source

Full code of the compiler, tests, game, class notes and presentation are available at:

    https://github.com/vmartinv/tiger-compiler

## Geany extensions (for coloring ML files):
Run in a terminal:
>  mkdir -p ~/.config/geany/colorschemes && wget https://labdcc.fceia.unr.edu.ar/~mvillagra/filetype_extensions.conf -O ~/.config/geany/filetype_extensions.conf && curl -O https://labdcc.fceia.unr.edu.ar/~mvillagra/geany.colors.tar.gz && tar -zxf geany.colors.tar.gz -C ~/.config/geany/colorschemes/ && rm geany.colors.tar.gz

## Requeriments
* mosml (ML compiler)

  For Ubuntu:
    > sudo apt-get install libgmp-dev

    > wget https://github.com/kfl/mosml/archive/ver-2.10.1.tar.gz

    > tar zxf ver-2.10.1.tar.gz

    > cd mosml-ver-2.10.1/src

    > make

    > sudo make install

  For Arch Linux:
    > sudo yaourt -S mosml

## Links útiles
* Pagina para aprender git:
  https://git-scm.com/book/es/v1

* SVN de la materia:
  svn checkout https://svn.dcc.fceia.unr.edu.ar/svn/lcc/T-521-Compiladores/

* Entregas iniciales + cosas:
  git clone https://bitbucket.org/martinceresa/tiger-compiler


text:
#pragma once
#ifndef DISPLAY_H
#define DISPLAY_H

#include <stdint.h>

/**
 * Initialize the resource of the 7-Segment display module
 */
extern void display_init();

/**
 * Enable the refresh of the display.
 */
extern void display_enable();

/**
 * Disable the refresh of the display.
 */
extern void display_disable();

/**
 * Set the value to display.
 *
 * @param value The value to display, range from -99 to 99.
 */
extern void display_set(int8_t value);

#endif


text:
# one-token-please
A cross platform .NET Core CLI app to get an Auth token. Right now it just gets one from Azure Active Directory using an application key.

[![Build Status](https://travis-ci.org/StephenGilboy/one-token-please.svg?branch=master)](https://travis-ci.org/StephenGilboy/one-token-please)

## How to use it

* If you're on OSX you'll need to install the pre-requisites for dotnet core. https://www.microsoft.com/net/core#macos
* Download the latest release for your system https://github.com/StephenGilboy/one-token-please/releases (Note: Its 20MB because it contains the full .NET Framework so you don't need to install it)
* Run it providing the parameters listed below

## Parameters
`-s` Auth Service. Defaults to 'aad' which is Azure Active Directory

`-c` ClientID. This is a GUID that you'll get from the AAD portal

`-k` AppKey. This is the key that is generated when adding an app in the AAD Portal.

`-r` Resource. https://yourcompany.onmicrosoft.com/YourApplication

`-a` Authority. https://login.microsoftonline.com/yourcompany.onmicrosoft.com

Enjoy!


text:
#include <hxcpp.h>

#ifndef INCLUDED_flixel_system_frontEnds_WatchFrontEnd
#include <flixel/system/frontEnds/WatchFrontEnd.h>
#endif
namespace flixel{
namespace _system{
namespace frontEnds{

Void WatchFrontEnd_obj::__construct()
{
HX_STACK_FRAME("flixel.system.frontEnds.WatchFrontEnd","new",0xbd21d019,"flixel.system.frontEnds.WatchFrontEnd.new","flixel/system/frontEnds/WatchFrontEnd.hx",7,0xd7ade198)
HX_STACK_THIS(this)
{
}
;
	return null();
}

//WatchFrontEnd_obj::~WatchFrontEnd_obj() { }

Dynamic WatchFrontEnd_obj::__CreateEmpty() { return  new WatchFrontEnd_obj; }
hx::ObjectPtr< WatchFrontEnd_obj > WatchFrontEnd_obj::__new()
{  hx::ObjectPtr< WatchFrontEnd_obj > _result_ = new WatchFrontEnd_obj();
	_result_->__construct();
	return _result_;}

Dynamic WatchFrontEnd_obj::__Create(hx::DynamicArray inArgs)
{  hx::ObjectPtr< WatchFrontEnd_obj > _result_ = new WatchFrontEnd_obj();
	_result_->__construct();
	return _result_;}

Void WatchFrontEnd_obj::add( Dynamic object,::String field,::String displayName){
{
		HX_STACK_FRAME("flixel.system.frontEnds.WatchFrontEnd","add",0xbd17f1da,"flixel.system.frontEnds.WatchFrontEnd.add","flixel/system/frontEnds/WatchFrontEnd.hx",18,0xd7ade198)
		HX_STACK_THIS(this)
		HX_STACK_ARG(object,"object")
		HX_STACK_ARG(field,"field")
		HX_STACK_ARG(displayName,"displayName")
	}
return null();
}

HX_DEFINE_DYNAMIC_FUNC3(WatchFrontEnd_obj,add,(void))

Void WatchFrontEnd_obj::remove( Dynamic object,::String field){
{
		HX_STACK_FRAME("flixel.system.frontEnds.WatchFrontEnd","remove",0x8d8c762b,"flixel.system.frontEnds.WatchFrontEnd.remove","flixel/system/frontEnds/WatchFrontEnd.hx",31,0xd7ade198)
		HX_STACK_THIS(this)
		HX_STACK_ARG(object,"object")
		HX_STACK_ARG(field,"field")
	}
return null();
}

HX_DEFINE_DYNAMIC_FUNC2(WatchFrontEnd_obj,remove,(void))

Void WatchFrontEnd_obj::addQuick( ::String displayName,Dynamic value){
{
		HX_STACK_FRAME("flixel.system.frontEnds.WatchFrontEnd","addQuick",0x8c660eb3,"flixel.system.frontEnds.WatchFrontEnd.addQuick","flixel/system/frontEnds/WatchFrontEnd.hx",46,0xd7ade198)
		HX_STACK_THIS(this)
		HX_STACK_ARG(displayName,"displayName")
		HX_STACK_ARG(value,"value")
	}
return null();
}

HX_DEFINE_DYNAMIC_FUNC2(WatchFrontEnd_obj,addQuick,(void))

Void WatchFrontEnd_obj::removeQuick( ::String displayName){
{
		HX_STACK_FRAME("flixel.system.frontEnds.WatchFrontEnd","removeQuick",0x15fb44c2,"flixel.system.frontEnds.WatchFrontEnd.removeQuick","flixel/system/frontEnds/WatchFrontEnd.hx",58,0xd7ade198)
		HX_STACK_THIS(this)
		HX_STACK_ARG(displayName,"displayName")
	}
return null();
}

HX_DEFINE_DYNAMIC_FUNC1(WatchFrontEnd_obj,removeQuick,(void))

Void WatchFrontEnd_obj::addExpression( ::String expression,::String displayName){
{
		HX_STACK_FRAME("flixel.system.frontEnds.WatchFrontEnd","addExpression",0xe5869c12,"flixel.system.frontEnds.WatchFrontEnd.addExpression","flixel/system/frontEnds/WatchFrontEnd.hx",73,0xd7ade198)
		HX_STACK_THIS(this)
		HX_STACK_ARG(expression,"expression")
		HX_STACK_ARG(displayName,"displayName")
	}
return null();
}

HX_DEFINE_DYNAMIC_FUNC2(WatchFrontEnd_obj,addExpression,(void))

Void WatchFrontEnd_obj::removeExpression( ::String expression){
{
		HX_STACK_FRAME("flixel.system.frontEnds.WatchFrontEnd","removeExpression",0xc4a80fa3,"flixel.system.frontEnds.WatchFrontEnd.removeExpression","flixel/system/frontEnds/WatchFrontEnd.hx",86,0xd7ade198)
		HX_STACK_THIS(this)
		HX_STACK_ARG(expression,"expression")
	}
return null();
}

HX_DEFINE_DYNAMIC_FUNC1(WatchFrontEnd_obj,removeExpression,(void))

Void WatchFrontEnd_obj::addMouse( ){
{
		HX_STACK_FRAME("flixel.system.frontEnds.WatchFrontEnd","addMouse",0x3add9deb,"flixel.system.frontEnds.WatchFrontEnd.addMouse","flixel/system/frontEnds/WatchFrontEnd.hx",97,0xd7ade198)
		HX_STACK_THIS(this)
	}
return null();
}

HX_DEFINE_DYNAMIC_FUNC0(WatchFrontEnd_obj,addMouse,(void))

Void WatchFrontEnd_obj::removeMouse( ){
{
		HX_STACK_FRAME("flixel.system.frontEnds.WatchFrontEnd","removeMouse",0xc472d3fa,"flixel.system.frontEnds.WatchFrontEnd.removeMouse","flixel/system/frontEnds/WatchFrontEnd.hx",107,0xd7ade198)
		HX_STACK_THIS(this)
	}
return null();
}

HX_DEFINE_DYNAMIC_FUNC0(WatchFrontEnd_obj,removeMouse,(void))

WatchFrontEnd_obj::WatchFrontEnd_obj()
{
}

Dynamic WatchFrontEnd_obj::__Field(const ::String &inName,hx::PropertyAccess inCallProp)
{
	switch(inName.length) {
	case 3:
		if (HX_FIELD_EQ(inName,"add") ) { return add_dyn(); }
		break;
	case 6:
		if (HX_FIELD_EQ(inName,"remove") ) { return remove_dyn(); }
		break;
	case 8:
		if (HX_FIELD_EQ(inName,"addQuick") ) { return addQuick_dyn(); }
		if (HX_FIELD_EQ(inName,"addMouse") ) { return addMouse_dyn(); }
		break;
	case 11:
		if (HX_FIELD_EQ(inName,"removeQuick") ) { return removeQuick_dyn(); }
		if (HX_FIELD_EQ(inName,"removeMouse") ) { return removeMouse_dyn(); }
		break;
	case 13:
		if (HX_FIELD_EQ(inName,"addExpression") ) { return addExpression_dyn(); }
		break;
	case 16:
		if (HX_FIELD_EQ(inName,"removeExpression") ) { return removeExpression_dyn(); }
	}
	return super::__Field(inName,inCallProp);
}

#if HXCPP_SCRIPTABLE
static hx::StorageInfo *sMemberStorageInfo = 0;
static hx::StaticInfo *sStaticStorageInfo = 0;
#endif

static ::String sMemberFields[] = {
	HX_HCSTRING("add","\x21","\xf2","\x49","\x00"),
	HX_HCSTRING("remove","\x44","\x9c","\x88","\x04"),
	HX_HCSTRING("addQuick","\x0c","\xad","\x4a","\xd7"),
	HX_HCSTRING("removeQuick","\x09","\x64","\x21","\x5c"),
	HX_HCSTRING("addExpression","\x19","\x5b","\xe8","\x98"),
	HX_HCSTRING("removeExpression","\xfc","\x2e","\x48","\xe8"),
	HX_HCSTRING("addMouse","\x44","\x3c","\xc2","\x85"),
	HX_HCSTRING("removeMouse","\x41","\xf3","\x98","\x0a"),
	::String(null()) };

static void sMarkStatics(HX_MARK_PARAMS) {
	HX_MARK_MEMBER_NAME(WatchFrontEnd_obj::__mClass,"__mClass");
};

#ifdef HXCPP_VISIT_ALLOCS
static void sVisitStatics(HX_VISIT_PARAMS) {
	HX_VISIT_MEMBER_NAME(WatchFrontEnd_obj::__mClass,"__mClass");
};

#endif

hx::Class WatchFrontEnd_obj::__mClass;

void WatchFrontEnd_obj::__register()
{
	hx::Static(__mClass) = new hx::Class_obj();
	__mClass->mName = HX_HCSTRING("flixel.system.frontEnds.WatchFrontEnd","\xa7","\xcf","\xe7","\x84");
	__mClass->mSuper = &super::__SGetClass();
	__mClass->mConstructEmpty = &__CreateEmpty;
	__mClass->mConstructArgs = &__Create;
	__mClass->mGetStaticField = &hx::Class_obj::GetNoStaticField;
	__mClass->mSetStaticField = &hx::Class_obj::SetNoStaticField;
	__mClass->mMarkFunc = sMarkStatics;
	__mClass->mStatics = hx::Class_obj::dupFunctions(0 /* sStaticFields */);
	__mClass->mMembers = hx::Class_obj::dupFunctions(sMemberFields);
	__mClass->mCanCast = hx::TCanCast< WatchFrontEnd_obj >;
#ifdef HXCPP_VISIT_ALLOCS
	__mClass->mVisitFunc = sVisitStatics;
#endif
#ifdef HXCPP_SCRIPTABLE
	__mClass->mMemberStorageInfo = sMemberStorageInfo;
#endif
#ifdef HXCPP_SCRIPTABLE
	__mClass->mStaticStorageInfo = sStaticStorageInfo;
#endif
	hx::RegisterClass(__mClass->mName, __mClass);
}

} // end namespace flixel
} // end namespace system
} // end namespace frontEnds


text:
// This detects whether we are in a server situation and act accordingly:
if (typeof define !== 'function') {
    var define = require('amdefine')(module);
    var vizapp = { type: 'server'},
    events = require('events'),
    dbs = require('pouch-config');
}

define(function (require) {
    "use strict";

    var abutils = require('app/lib/abutils'),
        btleConnection = require('connections/btle');

    var parser = function (socket) {

        var self = this,
            socket = socket,
            instrumentid = null,
            streaming = true,
            port = null,
            port_close_requested = false,
            port_open_requested = false,
            isopen = false;

        /**
         *   We are redefining the parser here because we need it to work
         * in both client mode and server mode (browser + cordova + node)
         * @param {*} delimiter
         * @param {*} encoding
         */
        var readline = function (delimiter, encoding) {
            if (typeof delimiter === "undefined" || delimiter === null) { delimiter = "\r"; }
            if (typeof encoding  === "undefined" || encoding  === null) { encoding  = "utf8"; }
            // Delimiter buffer saved in closure
            var data = "";
            return function (emitter, buffer) {
              // Collect data
              data += abutils.ab2str(buffer);
              // Split collected data by delimiter
              var parts = data.split(delimiter);
              data = parts.pop();
              parts.forEach(function (part, i, array) {
                emitter.onDataReady(part);
              });
            };
        }

        var parser = readline(','); // Parse line on "comma" character

        var CUSTOM_SERVICE_UUID = '39b31fec-b63a-4ef7-b163-a7317872007f';
        var SERIAL_PORT_UUID = 'd68236af-266f-4486-b42d-80356ed5afb7';

        // This is the CPM to µSv/h conversion coefficient for the tube
        // in the Inspector.
        var conversionCoefficient = 1 / 334;

        // If possible, we want to keep track of the location of the measurement.
        var current_loc = null,
            location_status = '',
            watchid = null;

        /////////////
        // Private methods
        /////////////

        var portSettings = function () {
            return {
                service_uuid: CUSTOM_SERVICE_UUID,
                characteristic_uuid: SERIAL_PORT_UUID
            }
        };

        // Format can act on incoming data from the device, and then
        // forwards the data to the app through a 'data' event.
        var format = function (data) {
            if (!data.value) {
                console.log('No value received');
                return;
            }
            parser(self, data.value);
        };

        // Status returns an object that is concatenated with the
        // global server status
        var status = function (stat) {
            port_open_requested = false;
            console.log('Port status change', stat);
            if (stat.openerror) {
                // We could not open the port: warn through
                // a 'data' messages
                var resp = {
                    openerror: true
                };
                if (stat.reason != undefined)
                    resp.reason = stat.reason;
                if (stat.description != undefined)
                    resp.description = stat.description;
                self.trigger('data', resp);
                // We need to unsubscribe from data/status messages now
                // since the port never opened.
                if (port.off) { // If we're running on NodeJS, then we've gotta use removeListener
                    port.off('status', status);
                    port.off('data', format);
                }  else {
                    port.removeListener('status', status);
                    port.removeListener('data', format);
                }
                return;
            }
            if (stat.reconnecting != undefined) {
                // Forward the message to front-end
                self.trigger('data', {
                    reconnecting: stat.reconnecting
                });
                return;
            }
            isopen = stat.portopen;
            if (isopen && stat.services) {
                // Should run any "onOpen" initialization routine here if
                // necessary.
                console.log('We found those services', stat.services);
                // ToDo: depending on the services we found, we can subscribe
                // to different service/characteristic UUIDs so that we can support
                // multiple versions of the Bluetooth module.
                port.subscribe({
                    service_uuid: CUSTOM_SERVICE_UUID,
                    characteristic_uuid: SERIAL_PORT_UUID
                });

                // Now regularly ask the navigator for current position and refresh map
                if (watchid == null) {
                    current_loc = null;
                    if (typeof navigator == 'undefined') // Note: Node.js requires using typeof
                        return;
                    watchid = navigator.geolocation.watchPosition(newLocation, geolocationError, {
                        maximumAge: 10000,
                        timeout: 20000,
                        enableHighAccuracy: true
                    });
                }

            } else {
                // We remove the listener so that the serial port can be GC'ed
                if (port_close_requested) {
                    if (port.off) // If we're running on NodeJS, then we've gotta use removeListener
                        port.off('status', status);
                    else
                        port.removeListener('status', status);
                    port_close_requested = false;
                    if (typeof navigator == 'undefined') // Note: Node.js requires using typeof
                        return;
                    if (watchid != null) {
                        navigator.geolocation.clearWatch(watchid);
                        watchid = null; // Nullify watchid otherwise we won't re-enable loc tracking at reopen
                    }
                }
            }
        };

        var newLocation = function (loc) {
            location_status = 'OK';
            current_loc = {
                coords: {
                    accuracy: loc.coords.accuracy,
                    altitude: loc.coords.altitude,
                    altitudeAccuracy: loc.coords.altitudeAccuracy,
                    latitude: loc.coords.latitude,
                    longitude: loc.coords.longitude,
                    heading: loc.coords.heading,
                    speed: loc.coords.speed
                }
            };
        }

        var geolocationError = function (err) {
            console.log('Location error', err);
            if (err.code == 3) {
                // It seems that iOS ends up throwing a code 3 when the phone
                // is not moving. This indicates our position has not changed, so this is
                // not really an error as long as current_loc is not empty
                if (current_loc != null)
                    return;
                else
                   location_status = 'no fix (timeout)';
            } else
                location_status = err.message;
        }

        /**
         *   Composite drivers (see envmonitor) pass the instrument port path
         *  directly since the 'ins' reference returned by the instrument manager is the
         *  composite instrument reference, not the one we actually want.
         * @param {*} insid    Instrument ID (string)
         * @param {*} insport  Instrument port path (string)
         */
        var openPort_app = function (insid, insport) {
            var ins = instrumentManager.getInstrument();
            port = new btleConnection(insport ? insport : ins.get('port'), portSettings());
            port.open();
            port.on('data', format);
            port.on('status', status);
        };

        var openPort_server = function(insid) {
            dbs.instruments.get(insid, function(err,item) {
                if (port == null)
                    port = new btleConnection(item.port, portSettings());
                port.on('data', format);
                port.on('status', status);
                port.open();
            });
        };

        /////////////
        // Public methods
        /////////////

        /**
         * insid : ID of the instrument (so that we can fetch its settings)
         * insport: optional, pass the instrument port info for direct opening, used for
         *          composite drivers in Cordova/app mode
         */
        this.openPort = function (insid, insport) {
            port_open_requested = true;
            instrumentid = insid;
            if (vizapp.type == 'server') {
                openPort_server(insid);
            } else {
                openPort_app(insid, insport);
            }

        };

        this.closePort = function (data) {
            // We need to remove all listeners otherwise the serial port
            // will never be GC'ed
            if (port.off)
                port.off('data', format);
            else
                port.removeListener('data', format);
            port_close_requested = true;
            port.close();
        }

        this.isOpen = function () {
            return isopen;
        }

        this.isOpenPending = function () {
            return port_open_requested;
        }

        this.getInstrumentId = function (arg) {
            return instrumentid;
        };

        this.isStreaming = function () {
            return streaming;
        };

        // Called when the app needs a unique identifier.
        // this is a standardized call across all drivers.
        //
        // TODO: Returns the instrument GUID.
        this.sendUniqueID = function () {};

        // period in seconds
        this.startLiveStream = function (period) {};

        this.stopLiveStream = function (args) {};

        // output should return a string, and is used to format
        // the data that is sent on the serial port, coming from the
        // HTML interface.
        this.output = function (data) {
            //console.log('TX', data);
            port.write(data);
        };

        /**
         *This is called by the serial parser (see 'format' above)
         */
        this.onDataReady = function (data) {
            // Remove the comma
            data = data.replace(',', '');
            if (data.length == 0)
                return;

            var cpm = parseInt(data);
            if (cpm != undefined) {
                var response = {
                    cpm: {
                        value: cpm,
                        usv: cpm * 0.00294,
                        name: 'Pancake',
                        valid: true
                    },
                    loc: current_loc,
                    loc_status: location_status
                };
                self.trigger('data', response);
            }
        };

    }

    // On server side, we use the Node eventing system, whereas on the
    // browser/app side, we use Bacbone's API:
    if (vizapp.type != 'server') {
        // Add event management to our parser, from the Backbone.Events class:
        _.extend(parser.prototype, Backbone.Events);
    } else {
        parser.prototype.__proto__ = events.EventEmitter.prototype;
        parser.prototype.trigger = parser.prototype.emit;
    }
    return parser;
});


text:
SPK_NAME = debian-chroot
SPK_VERS = 6.0.6
SPK_REV = 3
SPK_ICON = src/debian.png
DSM_UI_DIR = app

DEPENDS  =
SPK_DEPENDS = "python>2.7.3-3"

MAINTAINER = SynoCommunity
DESCRIPTION = Debian is a free operating system \(OS\) that comes with over 29000 packages, precompiled software bundled up in a nice format for easy installation on your DiskStation. Debian Chroot allows you to benefit from the Debian OS inside your DiskStation, alongside DSM. This package is intended for advanced users only.
DESCRIPTION_FRE = Debian est un système d\\\'exploitation \\\(SE\\\) qui rend disponible plus de 29000 paquets, logiciels précompilés et empaquetés dans un joli format pour rendre son installation facile sur votre DiskStation. Debian Chroot vous permet de bénéficier du SE Debian au sein de votre DiskStation, aux cotés de DSM. Ce paquet est destiné aux utilisateurs avancés uniquement.
RELOAD_UI = yes
DISPLAY_NAME = Debian Chroot

HOMEPAGE   = http://www.debian.org/
LICENSE    =

INSTALLER_SCRIPT = src/installer.sh
SSS_SCRIPT       = src/dsm-control.sh

INSTALL_PREFIX = /usr/local/$(SPK_NAME)

COPY_TARGET = nop
POST_STRIP_TARGET = debian-chroot_extra_install

DEBIAN_ARCH =
ifeq ($(findstring $(ARCH),88f6281),$(ARCH))
DEBIAN_ARCH = armel
endif
ifeq ($(findstring $(ARCH),bromolow cedarview x86),$(ARCH))
DEBIAN_ARCH = i386
endif
ifeq ($(findstring $(ARCH),qoriq),$(ARCH))
DEBIAN_ARCH = powerpc
endif
ifeq ($(strip $(DEBIAN_ARCH)),)
$(error Arch $(ARCH) not supported)
endif

include ../../mk/spksrc.spk.mk

.PHONY: debian-chroot_extra_install
debian-chroot_extra_install: $(STAGING_DIR)/share/requirements.pybundle
	install -m 755 -d $(STAGING_DIR)/var
	debootstrap --foreign --arch $(DEBIAN_ARCH) squeeze $(STAGING_DIR)/var/chroottarget "http://ftp.debian.org/debian"
	install -m 644 src/sources.list $(STAGING_DIR)/var/chroottarget/etc/apt/sources.list.default
	install -m 644 src/preferences $(STAGING_DIR)/var/chroottarget/etc/apt/preferences.default
	install -m 644 src/policy-rc.d $(STAGING_DIR)/var/chroottarget/usr/sbin/policy-rc.d
	install -m 755 -d $(STAGING_DIR)/app
	install -m 644 src/app/config $(STAGING_DIR)/app/config
	install -m 644 src/app/index.conf $(STAGING_DIR)/app/index.conf
	install -m 644 src/app/helptoc.conf $(STAGING_DIR)/app/helptoc.conf
	install -m 644 src/app/style.css $(STAGING_DIR)/app/style.css
	install -m 644 src/app/debian-chroot.js $(STAGING_DIR)/app/debian-chroot.js
	install -m 755 src/app/setup.py $(STAGING_DIR)/app/setup.py
	install -m 755 src/app/start.py $(STAGING_DIR)/app/start.py
	install -m 755 src/app/stop.py $(STAGING_DIR)/app/stop.py
	install -m 755 src/app/debian-chroot.cgi.py $(STAGING_DIR)/app/debian-chroot.cgi
	install -m 755 -d $(STAGING_DIR)/app/application
	install -m 644 src/app/application/* $(STAGING_DIR)/app/application/
	install -m 755 -d $(STAGING_DIR)/app/texts
	install -m 755 -d $(STAGING_DIR)/app/help
	for language in enu fre; do \
		install -m 755 -d $(STAGING_DIR)/app/texts/$${language}; \
		install -m 755 -d $(STAGING_DIR)/app/help/$${language}; \
		install -m 644 src/app/texts/$${language}/strings $(STAGING_DIR)/app/texts/$${language}/strings; \
		install -m 644 src/app/help/$${language}/*.html $(STAGING_DIR)/app/help/$${language}/; \
	done
	install -m 755 -d $(STAGING_DIR)/app/images
	install -m 644 src/app/images/*.png $(STAGING_DIR)/app/images/
	for size in 16 24 32 48; do \
		convert $(SPK_ICON) -thumbnail $${size}x$${size} \
		        $(STAGING_DIR)/app/images/$(SPK_NAME)-$${size}.png ; \
	done

$(STAGING_DIR)/share/requirements.pybundle:
	@$(MSG) "Bundling requirements"
	install -m 755 -d $(STAGING_DIR)/share
	@cd $(WORK_DIR) && $(PIP) bundle $@ pyextdirect==0.3.1 flask


text:
'use strict';

// Declare app level module which depends on views, and components
angular.module('myApp', [
	'ngRoute',
	'myApp.controllers',
	'myApp.services',
	'myApp.directives',
	'myApp.filters',
	'ngCookies',
	'gettext',
	'superCache',
	'ngAnimate',
	'textAngular'
]).
	config(['$routeProvider', '$locationProvider','$provide', function ($routeProvider, $locationProvider, $provide) {

		$locationProvider.html5Mode(true);

		$routeProvider.when('/:lang/matchmaking',
			{
				templateUrl: 'html/controllers/matchmaking.html',
				controller : 'MatchmakingCtrl'
			});

		$routeProvider.when('/:lang/',
			{
				templateUrl: '/html/controllers/home.html',
				controller : 'HomeCtrl',
				reloadOnSearch: false
			});

		$routeProvider.when('/:lang/destiny/',
			{
				templateUrl: '/html/controllers/rdv.html',
				controller : 'RdvCtrl',
				reloadOnSearch: false
			});

		$routeProvider.when('/:lang/destiny/:plateform',
			{
				templateUrl: '/html/controllers/rdv.html',
				controller : 'RdvCtrl',
				reloadOnSearch: false
			});

		$routeProvider.when('/:lang/party/create',
			{
				templateUrl: '/html/controllers/party-create.html',
				controller : 'PartyCreateCtrl'
			});
		$routeProvider.when('/:lang/party/waiting/:partyId',
			{
				templateUrl: '/html/controllers/party-waiting.html',
				controller : 'PartyWaitingCtrl'
			});
		$routeProvider.when('/:lang/matchmaking/waiting/:partyId',
			{
				templateUrl: '/html/controllers/matchmaking-waiting.html',
				controller : 'MatchmakingWaitingCtrl'
			});
		$routeProvider.when('/:lang/register',
			{
				templateUrl: '/html/controllers/register.html',
				controller : 'RegisterCtrl'
			});
		$routeProvider.when('/:lang/login',
			{
				templateUrl: '/html/controllers/login.html',
				controller : 'LoginCtrl'
			});
		$routeProvider.when('/:lang/profile/',
			{
				templateUrl: '/html/controllers/profile.html',
				controller : 'ProfileCtrl'
			});

		$routeProvider.when('/:lang/profile/:gameId/:plateformId/',
			{
				templateUrl: '/html/controllers/profile.html',
				controller : 'ProfileCtrl'
			});

		$routeProvider.when('/:lang/welcome',
			{
				templateUrl: '/html/controllers/rdv.html',
				controller : 'RdvCtrl',
				action     : 'welcome'
			});
		$routeProvider.when('/:lang/home',
			{
				templateUrl: '/html/controllers/home.html',
				controller : 'HomeCtrl'
			});
		$routeProvider.when('/:lang/games',
			{
				templateUrl: '/html/controllers/games-profiles.html',
				controller : 'GamesProfilesCtrl',
				action     : 'games'
			});

		$routeProvider.when('/:lang/404/:msg?',
			{
				templateUrl: '/html/controllers/404.html',
				controller : '404Ctrl'
			});
		$routeProvider.when('/:lang/notification',
			{
				templateUrl: '/html/controllers/notification.html',
				controller : 'NotificationCtrl'
			});

		$routeProvider.when('/:lang/password/forget/:username/:forgetToken',
			{
				templateUrl: '/html/controllers/password-update.html',
				controller : 'PasswordUpdateCtrl',
				action     : 'forget'
			});

		$routeProvider.when('/:lang/password/update',
			{
				templateUrl: '/html/controllers/password-update.html',
				controller : 'PasswordUpdateCtrl',
				action     : 'update'
			});

		$routeProvider.when('/:lang/users/connected',
			{
				templateUrl: '/html/controllers/list-users.html',
				controller : 'ListUsersCtrl',
				reloadOnSearch: false
			});

		$routeProvider.when('/:lang/annonce/create',
			{
				templateUrl: '/html/controllers/annonce-create.html',
				controller : 'AnnonceCreateCtrl'
			});

		$routeProvider.when('/:lang/forum/',
			{
				templateUrl: '/html/controllers/forum.html',
				controller : 'ForumCtrl'
			});

		$routeProvider.when('/:lang/forum/topic/:id/:page/:titre',
			{
				templateUrl: '/html/controllers/topic.html',
				controller : 'TopicCtrl'
			});

		$routeProvider.when('/:lang/destiny/video/all',
			{
				templateUrl: '/html/controllers/videotheque.html',
				controller : 'VideothequeCtrl'
			});

		$routeProvider.when('/:lang/video/:id/:nom',
			{
				templateUrl: '/html/controllers/partenaire.html',
				controller : 'PartenaireCtrl'
			});

		$routeProvider.otherwise({redirectTo: '/fr/'});

		$provide.decorator('taOptions', ['$delegate', function(taOptions){
			// $delegate is the taOptions we are decorating
			// here we override the default toolbars and classes specified in taOptions.
			taOptions.toolbar = [
				['quote','bold', 'italics', 'underline','strikeThrough', 'ul', 'ol', 'redo', 'undo'],
				['h1','justifyLeft','justifyCenter','justifyRight', 'insertImage', 'insertLink', 'insertVideo','html', 'clear']
			];
			taOptions.classes = {
				focussed: 'focussed',
				toolbar: 'btn-toolbar',
				toolbarGroup: 'btn-group',
				toolbarButton: 'btn btn-default',
				toolbarButtonActive: 'active',
				disabled: 'disabled',
				textEditor: 'form-control',
				htmlEditor: 'form-control'
			};
			return taOptions; // whatever you return will be the taOptions
		}]);

	}]);

angular.module('myApp.controllers', []);
angular.module('myApp.services', []);
angular.module('myApp.directives', []);
angular.module('myApp.filters', []);


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

<TITLE>
net.beadsproject.beads.data.buffers
</TITLE>

<META NAME="date" CONTENT="2010-04-18">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

net.beadsproject.beads.data.buffers

Classes

CosineWindow

CurveBuffer

Exp01Buffer

HanningWindow

Log01Buffer

MeanFilter

NoiseBuffer

OneWindow

RampBuffer

SawBuffer

SineBuffer

SquareBuffer

TriangularBuffer


text:
package com.cloud.api.commands;

import javax.inject.Inject;

import org.apache.log4j.Logger;

import org.apache.cloudstack.api.APICommand;
import org.apache.cloudstack.api.ApiConstants;
import org.apache.cloudstack.api.ApiErrorCode;
import org.apache.cloudstack.api.BaseCmd;
import org.apache.cloudstack.api.Parameter;
import org.apache.cloudstack.api.ServerApiException;
import org.apache.cloudstack.api.response.PhysicalNetworkResponse;
import org.apache.cloudstack.context.CallContext;

import com.cloud.api.response.CiscoVnmcResourceResponse;
import com.cloud.exception.ConcurrentOperationException;
import com.cloud.exception.InsufficientCapacityException;
import com.cloud.exception.InvalidParameterValueException;
import com.cloud.exception.ResourceAllocationException;
import com.cloud.exception.ResourceUnavailableException;
import com.cloud.network.cisco.CiscoVnmcController;
import com.cloud.network.element.CiscoVnmcElementService;
import com.cloud.utils.exception.CloudRuntimeException;

@APICommand(name = "addCiscoVnmcResource", responseObject = CiscoVnmcResourceResponse.class, description = "Adds a Cisco Vnmc Controller",
        requestHasSensitiveInfo = false, responseHasSensitiveInfo = false)
public class AddCiscoVnmcResourceCmd extends BaseCmd {
    private static final Logger s_logger = Logger.getLogger(AddCiscoVnmcResourceCmd.class.getName());
    private static final String s_name = "addCiscoVnmcResource";
    @Inject
    CiscoVnmcElementService _ciscoVnmcElementService;

    /////////////////////////////////////////////////////
    //////////////// API parameters /////////////////////
    /////////////////////////////////////////////////////

    @Parameter(name = ApiConstants.PHYSICAL_NETWORK_ID,
               type = CommandType.UUID,
               entityType = PhysicalNetworkResponse.class,
               required = true,
               description = "the Physical Network ID")
    private Long physicalNetworkId;

    @Parameter(name = ApiConstants.HOST_NAME, type = CommandType.STRING, required = true, description = "Hostname or ip address of the Cisco VNMC Controller.")
    private String host;

    @Parameter(name = ApiConstants.USERNAME, type = CommandType.STRING, required = true, description = "Credentials to access the Cisco VNMC Controller API")
    private String username;

    @Parameter(name = ApiConstants.PASSWORD, type = CommandType.STRING, required = true, description = "Credentials to access the Cisco VNMC Controller API")
    private String password;

    /////////////////////////////////////////////////////
    /////////////////// Accessors ///////////////////////
    /////////////////////////////////////////////////////

    public Long getPhysicalNetworkId() {
        return physicalNetworkId;
    }

    public String getHost() {
        return host;
    }

    public String getUsername() {
        return username;
    }

    public String getPassword() {
        return password;
    }

    /////////////////////////////////////////////////////
    /////////////// API Implementation///////////////////
    /////////////////////////////////////////////////////

    @Override
    public void execute() throws ResourceUnavailableException, InsufficientCapacityException, ServerApiException, ConcurrentOperationException,
        ResourceAllocationException {
        try {
            CiscoVnmcController CiscoVnmcResourceVO = _ciscoVnmcElementService.addCiscoVnmcResource(this);
            if (CiscoVnmcResourceVO != null) {
                CiscoVnmcResourceResponse response = _ciscoVnmcElementService.createCiscoVnmcResourceResponse(CiscoVnmcResourceVO);
                response.setObjectName("CiscoVnmcResource");
                response.setResponseName(getCommandName());
                this.setResponseObject(response);
            } else {
                throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, "Failed to add Cisco VNMC controller due to internal error.");
            }
        } catch (InvalidParameterValueException invalidParamExcp) {
            throw new ServerApiException(ApiErrorCode.PARAM_ERROR, invalidParamExcp.getMessage());
        } catch (CloudRuntimeException runtimeExcp) {
            throw new ServerApiException(ApiErrorCode.INTERNAL_ERROR, runtimeExcp.getMessage());
        }
    }

    @Override
    public String getCommandName() {
        return s_name;
    }

    @Override
    public long getEntityOwnerId() {
        return CallContext.current().getCallingAccount().getId();
    }
}


text:
#ifndef _VECTORMATH_VECIDX_AOS_H
#define _VECTORMATH_VECIDX_AOS_H

#include "floatInVec.h"

namespace Vectormath {
namespace Aos {

//-----------------------------------------------------------------------------
// VecIdx
// Used in setting elements of Vector3, Vector4, Point3, or Quat with the
// subscripting operator.
//

VM_ATTRIBUTE_ALIGNED_CLASS16 (class) VecIdx
{
private:
   __m128 &ref;
   int i;
public:
    inline VecIdx( __m128& vec, int idx ): ref(vec) { i = idx; }

    // implicitly casts to float unless _VECTORMATH_NO_SCALAR_CAST defined
    // in which case, implicitly casts to floatInVec, and one must call
    // getAsFloat to convert to float.
    //
#ifdef _VECTORMATH_NO_SCALAR_CAST
    inline operator floatInVec() const;
    inline float getAsFloat() const;
#else
    inline operator float() const;
#endif

    inline float operator =( float scalar );
    inline floatInVec operator =( const floatInVec &scalar );
    inline floatInVec operator =( const VecIdx& scalar );
    inline floatInVec operator *=( float scalar );
    inline floatInVec operator *=( const floatInVec &scalar );
    inline floatInVec operator /=( float scalar );
    inline floatInVec operator /=( const floatInVec &scalar );
    inline floatInVec operator +=( float scalar );
    inline floatInVec operator +=( const floatInVec &scalar );
    inline floatInVec operator -=( float scalar );
    inline floatInVec operator -=( const floatInVec &scalar );
};

} // namespace Aos
} // namespace Vectormath

#endif


text:
var despace = function(input){
  return input.replace(/\n|\t/mg,'').replace(/\s+/mg,' ').trim()
}

var s = require('../lib/sparql.js')
  , r = require('ramda')
  , query = s.query
  , select = s.select
  , Describe = s.describe
  , construct = s.construct
  , where = s.where
  , triple = s.triple
  , graph = s.graph
  , filter = s.filter
  , optional = s.optional
  , union = s.union
  , serialise = r.compose(despace, s.serialiseGGP)

describe("query", function(){
  it("should serialise the query", function(){
    var rq = query(select(['?s'], where(triple('?s','?p','?o'))))
    expect(despace(rq)).toEqual("SELECT ?s WHERE { ?s ?p ?o }")
  })
})
describe("GGP funcs", function(){
  it("filter", function(){
    expect(serialise(filter('?x > ?y'))).toEqual('FILTER(?x > ?y)')
  })
  it("graph", function(){
    expect(serialise(graph('?g', triple('?s', '?p', '?o')))).toEqual('GRAPH ?g { ?s ?p ?o }')
  })
})