text:
package org.apache.hadoop.yarn.sls;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Reader;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Set;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;

import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.GnuParser;
import org.apache.commons.cli.Options;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.tools.rumen.JobTraceReader;
import org.apache.hadoop.tools.rumen.LoggedJob;
import org.apache.hadoop.tools.rumen.LoggedTask;
import org.apache.hadoop.tools.rumen.LoggedTaskAttempt;
import org.apache.hadoop.util.ReflectionUtils;
import org.apache.hadoop.yarn.api.records.NodeId;
import org.apache.hadoop.yarn.api.records.NodeState;
import org.apache.hadoop.yarn.api.records.Resource;
import org.apache.hadoop.yarn.conf.YarnConfiguration;
import org.apache.hadoop.yarn.exceptions.YarnException;
import org.apache.hadoop.yarn.server.resourcemanager.ResourceManager;
import org.apache.hadoop.yarn.server.resourcemanager.rmnode.RMNode;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.custom.SchedulerCustomUtils.NodeSelection;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.CustomYLocSimFairScheduler;
import org.apache.hadoop.yarn.server.resourcemanager.scheduler.fair.FairSchedulerConfiguration;
import org.apache.hadoop.yarn.server.utils.BuilderUtils;
import org.apache.hadoop.yarn.sls.appmaster.AMSimulator;
import org.apache.hadoop.yarn.sls.appmaster.MRAMSimulator;
import org.apache.hadoop.yarn.sls.conf.SLSConfiguration;
import org.apache.hadoop.yarn.sls.nodemanager.NMSimulator;
import org.apache.hadoop.yarn.sls.scheduler.ContainerSimulator;
import org.apache.hadoop.yarn.sls.scheduler.ResourceSchedulerWrapper;
import org.apache.hadoop.yarn.sls.scheduler.TaskRunner;
import org.apache.hadoop.yarn.sls.types.TopologyLocation;
import org.apache.hadoop.yarn.sls.utils.SLSUtils;
import org.apache.log4j.Level;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.codehaus.jackson.JsonFactory;
import org.codehaus.jackson.map.ObjectMapper;

import com.typesafe.config.Config;
import com.typesafe.config.ConfigFactory;

public class SLSRunner {
  // RM, Runner
  private ResourceManager rm;
  private static TaskRunner runner = new TaskRunner();
  private String[] inputTraces;
  private Configuration conf;
  private Map<String, Integer> queueAppNumMap;

  // NM simulator
  private HashMap<NodeId, NMSimulator> nmMap;
  private int nmMemoryMB, nmVCores;
  private String nodeFile;

  // AM simulator
  private int AM_ID;
  private Map<String, AMSimulator> amMap;
  private Set<String> trackedApps;
  private Map<String, Class> amClassMap;
  private static int remainingApps = 0;

  // metrics
  private String metricsOutputDir;
  private boolean printSimulation;

  // other simulation information
  private int numNMs, numRacks, numAMs, numTasks;
  private long maxRuntime;
  public final static Map<String, Object> simulateInfoMap =
          new HashMap<String, Object>();

  // logger
  public final static Logger LOG = Logger.getLogger(SLSRunner.class);

  // input traces, input-rumen or input-sls
  private boolean isSLS;

  private int MAX_BLOCK_BUDGET = 0;
  private double SCORE_THRESHOLD = 0;
  private NodeSelection nodeSelectionPolicy = NodeSelection.RANDOM;
  private String []inputFilesTraces = new String [10];
  private int t1 ; //Fair Scheduler Node Locality Threshold
  private int t2 ; //Fair Scheduler Rack Locality Threshold

  private int cpuCores ;
  private int memory ;

  private boolean isDistributeDataEnabled = true;

  public SLSRunner() {

  }
  public SLSRunner(boolean isSLS, String inputTraces[], String nodeFile,
                   String outputDir, Set<String> trackedApps,
                   boolean printsimulation)
          throws IOException, ClassNotFoundException {
    this.isSLS = isSLS;
    this.inputTraces = inputTraces.clone();
    this.nodeFile = nodeFile;
    this.trackedApps = trackedApps;
    this.printSimulation = printsimulation;
    metricsOutputDir = outputDir;

    nmMap = new HashMap<NodeId, NMSimulator>();
    queueAppNumMap = new HashMap<String, Integer>();
    amMap = new HashMap<String, AMSimulator>();
    amClassMap = new HashMap<String, Class>();

    // runner configuration
    conf = new Configuration(false);
    conf.addResource(new FileInputStream(new File("src/main/resources/sls-runner.xml")));
    // runner
    int poolSize = conf.getInt(SLSConfiguration.RUNNER_POOL_SIZE,
                                SLSConfiguration.RUNNER_POOL_SIZE_DEFAULT);
    SLSRunner.runner.setQueueSize(poolSize);
    // <AMType, Class> map
    for (Map.Entry e : conf) {
      String key = e.getKey().toString();
      if (key.startsWith(SLSConfiguration.AM_TYPE)) {
        String amType = key.substring(SLSConfiguration.AM_TYPE.length());
        amClassMap.put(amType, Class.forName(conf.get(key)));
      }
    }
  }

  public SLSRunner (boolean isSLS, String inputTraces[], String nodeFile,
          String outputDir, Set<String> trackedApps,
          boolean printsimulation , int maxBlockBudget , double scoreThreshold , NodeSelection ns , int t1 , int t2 , boolean isDistributeDataEnabled , int cpu , int memory) throws IOException, ClassNotFoundException{
	  this(isSLS, inputTraces, nodeFile, outputDir, trackedApps, printsimulation);
	  MAX_BLOCK_BUDGET = maxBlockBudget;
	  SCORE_THRESHOLD = scoreThreshold;
	  nodeSelectionPolicy = ns;
	  inputFilesTraces = inputTraces;
	  this.t1 = t1;
	  this.t2 = t2;
	  this.isDistributeDataEnabled = isDistributeDataEnabled;
	  this.cpuCores = cpu;
	  this.memory = memory;
  }

  public void start() throws Exception {

	LogManager.getRootLogger().setLevel(Level.ERROR);
    // start resource manager
	startRM();

    // start node managers
	startNM();

    // start application masters
    startAM();
    // set queue & tracked apps information
    ((ResourceSchedulerWrapper) rm.getResourceScheduler())
                            .setQueueSet(this.queueAppNumMap.keySet());
    ((ResourceSchedulerWrapper) rm.getResourceScheduler())
                            .setTrackedAppSet(this.trackedApps);
    // print out simulation info
    printSimulationInfo();
    // blocked until all nodes RUNNING
    waitForNodesRunning();
    // starting the runner once everything is ready to go,
    runner.start();
  }

  private void startRM() throws IOException, ClassNotFoundException {
    Configuration rmConf = new YarnConfiguration();
    //String schedulerClass = rmConf.get(YarnConfiguration.RM_SCHEDULER);
    //String schedulerClass = CapacityScheduler.class.getCanonicalName();
    //String schedulerClass = CustomFairScheduler.class.getCanonicalName();
    String schedulerClass = CustomYLocSimFairScheduler.class.getCanonicalName();
    //CustomFairScheduler
    rmConf.set(SLSConfiguration.RM_SCHEDULER, schedulerClass);
    rmConf.set(YarnConfiguration.RM_SCHEDULER,
            ResourceSchedulerWrapper.class.getName());
    rmConf.set(SLSConfiguration.METRICS_OUTPUT_DIR, metricsOutputDir);
    //rmConf.set(FairSchedulerConfiguration.ALLOCATION_FILE , "src/test/resources/fair-scheduler-allocation.xml");
    rmConf.set(FairSchedulerConfiguration.ALLOCATION_FILE , "src/main/resources/fair-scheduler-allocation.xml");

    //rmConf.set(CommonConfigurationKeys.NET_TOPOLOGY_SCRIPT_FILE_NAME_KEY, "src/main/resources/topology.py");
    rmConf.addResource(new FileInputStream(new File("src/main/resources/yarn-site.xml")));

    rmConf.setInt("yarn.scheduler.fair.locality-delay-node-ms", t1);
    rmConf.setInt("yarn.scheduler.fair.locality-delay-rack-ms", t2);
    rmConf.setBoolean(CustomYLocSimFairScheduler.IS_DISTRIBUTE_DATA_ENABLED, isDistributeDataEnabled);
    rmConf.setInt(CustomYLocSimFairScheduler.CPU, cpuCores);
    rmConf.setInt(CustomYLocSimFairScheduler.MEMORY, memory);

    rmConf.setInt(CustomYLocSimFairScheduler.MAX_BLOCK_BUDGET_KEY, MAX_BLOCK_BUDGET);
    rmConf.setDouble(CustomYLocSimFairScheduler.SCORE_THRESHOLD_KEY, SCORE_THRESHOLD);
    rmConf.setEnum(CustomYLocSimFairScheduler.NODE_SELECTION_KEY, nodeSelectionPolicy);
    rmConf.set(CustomYLocSimFairScheduler.TOPOLOGY_FILE_PATH, nodeFile);
    rmConf.set(CustomYLocSimFairScheduler.INPUT_FILE_TRACE, inputFilesTraces[0].substring(inputFilesTraces[0].lastIndexOf("/")+1,inputFilesTraces[0].length()));

    List<TopologyLocation> nodeRackTopologyList = SLSUtils.getTopologyLocationsFromFile(nodeFile);
    String []rackNodes = new String[nodeRackTopologyList.size()];
    int i = 0;
    for (TopologyLocation tl : nodeRackTopologyList) {
    	rackNodes[i++] = tl.getNodeName() + "-" + tl.getRackName();
    }

    rmConf.setStrings(CustomYLocSimFairScheduler.TOPOLOGY_INFO, rackNodes);

    rm = new ResourceManager();
    rm.init(rmConf);
    rm.start();

  }

  private void startNM() throws YarnException, IOException {
    // nm configuration
	nmMemoryMB = memory;
	nmVCores = cpuCores;
	if (memory ==0 )
		nmMemoryMB = conf.getInt(SLSConfiguration.NM_MEMORY_MB,
				SLSConfiguration.NM_MEMORY_MB_DEFAULT);
	if (cpuCores == 0)
		nmVCores = conf.getInt(SLSConfiguration.NM_VCORES,
				SLSConfiguration.NM_VCORES_DEFAULT);
    System.out.println("vmcores " + nmVCores + " nmMemoryMB " + nmMemoryMB);
    int heartbeatInterval = conf.getInt(
            SLSConfiguration.NM_HEARTBEAT_INTERVAL_MS,
            SLSConfiguration.NM_HEARTBEAT_INTERVAL_MS_DEFAULT);
    // nm information (fetch from topology file, or from sls/rumen json file)
    Set<String> nodeSet = new HashSet<String>();
    if (nodeFile.isEmpty()) {
      if (isSLS) {
        for (String inputTrace : inputTraces) {
          nodeSet.addAll(SLSUtils.parseNodesFromSLSTrace(inputTrace));
        }
      } else {
        for (String inputTrace : inputTraces) {
          nodeSet.addAll(SLSUtils.parseNodesFromRumenTrace(inputTrace));
        }
      }

    } else {
      nodeSet.addAll(SLSUtils.parseNodesFromNodeFile(nodeFile));
    }
    // create NM simulators
    Random random = new Random();
    Set<String> rackSet = new HashSet<String>();
    for (String hostName : nodeSet) {
      // we randomize the heartbeat start time from zero to 1 interval
      NMSimulator nm = new NMSimulator();
      nm.init(hostName, nmMemoryMB, nmVCores,
          random.nextInt(heartbeatInterval), heartbeatInterval, rm);
      nm.setMaxBudget(MAX_BLOCK_BUDGET);
      nm.setZScoreThreshold(SCORE_THRESHOLD);
      nm.setReplicaPlacementPolicy(nodeSelectionPolicy.name());

      nmMap.put(nm.getNode().getNodeID(), nm);
      runner.schedule(nm);
      rackSet.add(nm.getNode().getRackName());
    }
    numRacks = rackSet.size();
    numNMs = nmMap.size();
  }

  private void waitForNodesRunning() throws InterruptedException {
    long startTimeMS = System.currentTimeMillis();
    while (true) {
      int numRunningNodes = 0;
      for (RMNode node : rm.getRMContext().getRMNodes().values()) {
        if (node.getState() == NodeState.RUNNING) {
          numRunningNodes ++;
        }
      }
      if (numRunningNodes == numNMs) {
        break;
      }
      LOG.info(MessageFormat.format("SLSRunner is waiting for all " +
              "nodes RUNNING. {0} of {1} NMs initialized.",
              numRunningNodes, numNMs));
      Thread.sleep(1000);
    }
    LOG.info(MessageFormat.format("SLSRunner takes {0} ms to launch all nodes.",
            (System.currentTimeMillis() - startTimeMS)));
  }

  @SuppressWarnings("unchecked")
  private void startAM() throws YarnException, IOException {
    // application/container configuration
	//conf.set(YARN_APP_MAPREDUCE_AM_COMMAND_OPTS, conf.get(YARN_APP_MAPREDUCE_AM_COMMAND_OPTS) + " -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:8888,server=n,suspend=n");
    int heartbeatInterval = conf.getInt(
            SLSConfiguration.AM_HEARTBEAT_INTERVAL_MS,
            SLSConfiguration.AM_HEARTBEAT_INTERVAL_MS_DEFAULT);
    int containerMemoryMB = conf.getInt(SLSConfiguration.CONTAINER_MEMORY_MB,
            SLSConfiguration.CONTAINER_MEMORY_MB_DEFAULT);
    int containerVCores = conf.getInt(SLSConfiguration.CONTAINER_VCORES,
            SLSConfiguration.CONTAINER_VCORES_DEFAULT);
    Resource containerResource =
            BuilderUtils.newResource(containerMemoryMB, containerVCores);

    // application workload
    queueAppNumMap.clear();
    trackedApps.clear();
    if (isSLS) {
      startAMFromSLSTraces(containerResource, heartbeatInterval);
    } else {
      startAMFromRumenTraces(containerResource, heartbeatInterval);
    }
    numAMs = amMap.size();
    remainingApps = numAMs;
  }

  /**
   * parse workload information from sls trace files
   */
  static Map<String,Integer> accessCounts = new HashMap<>();
  static Map<String,Double> jobsRuntime = new HashMap<>();

  @SuppressWarnings("unchecked")
  private void startAMFromSLSTraces(Resource containerResource,
                                    int heartbeatInterval) throws IOException {
    // parse from sls traces
    JsonFactory jsonF = new JsonFactory();
    ObjectMapper mapper = new ObjectMapper();
    for (String inputTrace : inputTraces) {
      Reader input = new FileReader(inputTrace);
      try {
        Iterator<Map> i = mapper.readValues(jsonF.createJsonParser(input),
                Map.class);
        while (i.hasNext()) {
          Map jsonJob = i.next();

          // load job information
          long jobStartTime = Long.parseLong(
                  jsonJob.get("job.start.ms").toString());
          long jobFinishTime = Long.parseLong(
                  jsonJob.get("job.end.ms").toString());

          double jobLifeTime = (jobFinishTime - jobStartTime) / 1000;

          String user = (String) jsonJob.get("job.user");
          if (user == null)  user = "default";
          String queue = jsonJob.get("job.queue.name").toString();
          String jobName = jsonJob.get("job.name").toString();

          String oldAppId = jsonJob.get("job.id").toString();

          jobsRuntime.put(oldAppId, jobLifeTime);

          BufferedWriter tasksDurationsFile = new BufferedWriter(new FileWriter(new File("src/test/resources/tasks_durations.csv"),true));

          boolean isTracked = trackedApps.contains(oldAppId);
          int queueSize = queueAppNumMap.containsKey(queue) ?
                  queueAppNumMap.get(queue) : 0;
          queueSize ++;
          queueAppNumMap.put(queue, queueSize);
          // tasks
          List tasks = (List) jsonJob.get("job.tasks");
          if (tasks == null || tasks.size() == 0) {
            continue;
          }
          List<ContainerSimulator> containerList =
                  new ArrayList<ContainerSimulator>();
          for (Object o : tasks) {
            Map jsonTask = (Map) o;
            String hostname = jsonTask.get("container.host").toString();
            long taskStart = Long.parseLong(
                    jsonTask.get("container.start.ms").toString());
            long taskFinish = Long.parseLong(
                    jsonTask.get("container.end.ms").toString());
            long lifeTime = taskFinish - taskStart;
            int priority = Integer.parseInt(
                    jsonTask.get("container.priority").toString());
            String type = jsonTask.get("container.type").toString();
            HashMap<String,String> preferredLocations = (HashMap<String,String>)jsonTask.get(RumenToSLSConverter.MAP_PREFERRED_LOCATIONS);
            if (preferredLocations != null) {
	            //all the rack names should start with "/"
	            for (Map.Entry<String, String> nodeRack : preferredLocations.entrySet()) {
	            	if (!nodeRack.getValue().startsWith("/")) {
	            		preferredLocations.put(nodeRack.getKey(), "/" + nodeRack.getValue());
	            	}

	            }
            }
            String jobId = jsonTask.get(RumenToSLSConverter.TASK_JOB_JOBID).toString();
            String taskId = jsonTask.get(RumenToSLSConverter.TASK_TASKID).toString();
            String taskAttemtId = jsonTask.get(RumenToSLSConverter.TASK_ATTEMPTID).toString();
            String originalLocality = jsonTask.get(RumenToSLSConverter.CONTAINER_ORIGINAL_LOCALITY).toString();
            String fileSplitName = jsonTask.get(RumenToSLSConverter.FILE_SPLIT_ID).toString();
            String splitId ="";
            if (jsonTask.get("splitId") !=null)
            	splitId = jsonTask.get("splitId").toString();
            ContainerSimulator cs = new ContainerSimulator(containerResource,
                    lifeTime, hostname, priority, type,preferredLocations,jobId,taskId , taskAttemtId,originalLocality);
            cs.setFileName(fileSplitName);
            cs.setSplitId(splitId);
            containerList.add(cs);

            tasksDurationsFile.write(oldAppId + "," + taskId + "," + type + "," + lifeTime/1000 + "," + jobName + ","+ jobLifeTime + "\n");
          }

          tasksDurationsFile.close();

          //calculating the access counts
          BufferedWriter bw = new BufferedWriter(new FileWriter(new File("src/test/resources/access_counts.csv")));

          //System.out.println("Start writing access counts for job " + oldAppId);

          for (ContainerSimulator cs : containerList) {
        	  synchronized (accessCounts) {
        		  if (accessCounts.containsKey(cs.getFileName())) {
        			  int newCount = accessCounts.get(cs.getFileName()) + 1;
        			  accessCounts.put(cs.getFileName(), newCount);
        		  }
        		  else {
        			  accessCounts.put(cs.getFileName(), 1);
        		  }
			}
          }
          for(Map.Entry<String, Integer> e : accessCounts.entrySet()) {
        	  bw.write(e.getKey() + "," + e.getValue() + "\n");
          }
          bw.close();

          // create a new AM
          String amType = jsonJob.get("am.type").toString();
          String amContainerNode = jsonJob.get("am.container.node").toString();
          Configuration amConf = new Configuration();
          //amConf.set(YARN_APP_MAPREDUCE_AM_COMMAND_OPTS, amConf.get(YARN_APP_MAPREDUCE_AM_COMMAND_OPTS) + " -agentlib:jdwp=transport=dt_socket,address=127.0.0.1:8888,server=n,suspend=n");
          AMSimulator amSim = (AMSimulator) ReflectionUtils.newInstance(
                  amClassMap.get(amType), amConf);
          if (amSim != null) {
        	amSim.setToplogyFilePath(nodeFile);
            amSim.init(AM_ID++, heartbeatInterval, containerList, rm,
                    this, jobStartTime, jobFinishTime, user, queue,
                    isTracked, oldAppId,amContainerNode);
            runner.schedule(amSim);
            maxRuntime = Math.max(maxRuntime, jobFinishTime);
            numTasks += containerList.size();
            amMap.put(oldAppId, amSim);
          }
        }

        BufferedWriter bw = new BufferedWriter(new FileWriter(new File ("src/test/resources/jobs_runtime.csv")));
        for (Map.Entry<String, Double> e : jobsRuntime.entrySet()) {
        	bw.write(e.getKey() + "," + e.getValue() + "\n");
        }
        bw.close();
      } finally {
        input.close();
      }
    }
  }

  /**
   * parse workload information from rumen trace files
   */
  //private static final String YARN_APP_MAPREDUCE_AM_COMMAND_OPTS = "yarn.app.mapreduce.am.command-opts";
  @SuppressWarnings("unchecked")
  private void startAMFromRumenTraces(Resource containerResource,
                                      int heartbeatInterval)
          throws IOException {
    Configuration conf = new Configuration();
    conf.set("fs.defaultFS", "file:///");
    long baselineTimeMS = 0;
    for (String inputTrace : inputTraces) {
      File fin = new File(inputTrace);
      JobTraceReader reader = new JobTraceReader(
              new Path(fin.getAbsolutePath()), conf);
      try {
        LoggedJob job = null;
        while ((job = reader.getNext()) != null) {
          // only support MapReduce currently
          String jobType = "mapreduce";
          String user = job.getUser() == null ?
                  "default" : job.getUser().getValue();
          String jobQueue = job.getQueue().getValue();
          String oldJobId = job.getJobID().toString();
          long jobStartTimeMS = job.getSubmitTime();
          long jobFinishTimeMS = job.getFinishTime();
          if (baselineTimeMS == 0) {
            baselineTimeMS = jobStartTimeMS;
          }
          jobStartTimeMS -= baselineTimeMS;
          jobFinishTimeMS -= baselineTimeMS;
          if (jobStartTimeMS < 0) {
            LOG.warn("Warning: reset job " + oldJobId + " start time to 0.");
            jobFinishTimeMS = jobFinishTimeMS - jobStartTimeMS;
            jobStartTimeMS = 0;
          }

          boolean isTracked = trackedApps.contains(oldJobId);
          int queueSize = queueAppNumMap.containsKey(jobQueue) ?
                  queueAppNumMap.get(jobQueue) : 0;
          queueSize ++;
          queueAppNumMap.put(jobQueue, queueSize);

          List<ContainerSimulator> containerList =
                  new ArrayList<ContainerSimulator>();
          // map tasks
          for(LoggedTask mapTask : job.getMapTasks()) {
            LoggedTaskAttempt taskAttempt = mapTask.getAttempts()
                    .get(mapTask.getAttempts().size() - 1);
            String hostname = taskAttempt.getHostName().getValue();
            long containerLifeTime = taskAttempt.getFinishTime()
                    - taskAttempt.getStartTime();
            containerList.add(new ContainerSimulator(containerResource,
                    containerLifeTime, hostname,MRAMSimulator.PRIORITY_MAP, "map"));
          }

          // reduce tasks
          for(LoggedTask reduceTask : job.getReduceTasks()) {
            LoggedTaskAttempt taskAttempt = reduceTask.getAttempts()
                    .get(reduceTask.getAttempts().size() - 1);
            String hostname = taskAttempt.getHostName().getValue();
            long containerLifeTime = taskAttempt.getFinishTime()
                    - taskAttempt.getStartTime();
            containerList.add(new ContainerSimulator(containerResource,
                    containerLifeTime, hostname, MRAMSimulator.PRIORITY_REDUCE, "reduce"));
          }

          // create a new AM
          AMSimulator amSim = (AMSimulator) ReflectionUtils.newInstance(
                  amClassMap.get(jobType), conf);
          if (amSim != null) {
            amSim.init(AM_ID ++, heartbeatInterval, containerList,
                    rm, this, jobStartTimeMS, jobFinishTimeMS, user, jobQueue,
                    isTracked, oldJobId);
            runner.schedule(amSim);
            maxRuntime = Math.max(maxRuntime, jobFinishTimeMS);
            numTasks += containerList.size();
            amMap.put(oldJobId, amSim);
          }
        }
      } finally {
        reader.close();
      }
    }
  }

  private void printSimulationInfo() {
    if (printSimulation) {
      // node
      LOG.info("------------------------------------");
      LOG.info(MessageFormat.format("# nodes = {0}, # racks = {1}, capacity " +
              "of each node {2} MB memory and {3} vcores.",
              numNMs, numRacks, nmMemoryMB, nmVCores));
      LOG.info("------------------------------------");
      // job
      LOG.info(MessageFormat.format("# applications = {0}, # total " +
              "tasks = {1}, average # tasks per application = {2}",
              numAMs, numTasks, (int)(Math.ceil((numTasks + 0.0) / numAMs))));
      LOG.info("JobId\tQueue\tAMType\tDuration\t#Tasks");
      for (Map.Entry<String, AMSimulator> entry : amMap.entrySet()) {
        AMSimulator am = entry.getValue();
        LOG.info(entry.getKey() + "\t" + am.getQueue() + "\t" + am.getAMType()
            + "\t" + am.getDuration() + "\t" + am.getNumTasks());
      }
      LOG.info("------------------------------------");
      // queue
      LOG.info(MessageFormat.format("number of queues = {0}  average " +
              "number of apps = {1}", queueAppNumMap.size(),
              (int)(Math.ceil((numAMs + 0.0) / queueAppNumMap.size()))));
      LOG.info("------------------------------------");
      // runtime
      LOG.info(MessageFormat.format("estimated simulation time is {0}" +
              " seconds", (long)(Math.ceil(maxRuntime / 1000.0))));
      LOG.info("------------------------------------");
    }
    // package these information in the simulateInfoMap used by other places
    simulateInfoMap.put("Number of racks", numRacks);
    simulateInfoMap.put("Number of nodes", numNMs);
    simulateInfoMap.put("Node memory (MB)", nmMemoryMB);
    simulateInfoMap.put("Node VCores", nmVCores);
    simulateInfoMap.put("Number of applications", numAMs);
    simulateInfoMap.put("Number of tasks", numTasks);
    simulateInfoMap.put("Average tasks per applicaion",
            (int)(Math.ceil((numTasks + 0.0) / numAMs)));
    simulateInfoMap.put("Number of queues", queueAppNumMap.size());
    simulateInfoMap.put("Average applications per queue",
            (int)(Math.ceil((numAMs + 0.0) / queueAppNumMap.size())));
    simulateInfoMap.put("Estimated simulate time (s)",
            (long)(Math.ceil(maxRuntime / 1000.0)));
  }

  public HashMap<NodeId, NMSimulator> getNmMap() {
    return nmMap;
  }

  public static TaskRunner getRunner() {
    return runner;
  }

  public static void decreaseRemainingApps() {
	remainingApps --;
    if (remainingApps == 0) {
      LOG.info("SLSRunner tears down.");
      System.out.println("SLSRunner tears down.");
      //TODO: Just commented this temporarily to test multiple runs.
      System.exit(0);
    }
  }

  public static int getRemainingApps () {
	  return remainingApps;
  }

  public static void main(String args[]) throws Exception {
    Options options = new Options();
    options.addOption("inputrumen", true, "input rumen files");
    options.addOption("inputsls", true, "input sls files");
    options.addOption("nodes", true, "input topology");
    options.addOption("output", true, "output directory");
    options.addOption("trackjobs", true,
            "jobs to be tracked during simulating");
    options.addOption("printsimulation", false,
            "print out simulation information");

    CommandLineParser parser = new GnuParser();
    CommandLine cmd = parser.parse(options, args);

    String inputRumen = cmd.getOptionValue("inputrumen");
    String inputSLS = cmd.getOptionValue("inputsls");
    String output = cmd.getOptionValue("output");

    if ((inputRumen == null && inputSLS == null) || output == null) {
      System.err.println();
      System.err.println("ERROR: Missing input or output file");
      System.err.println();
      System.err.println("Options: -inputrumen|-inputsls FILE,FILE... " +
              "-output FILE [-nodes FILE] [-trackjobs JobId,JobId...] " +
              "[-printsimulation]");
      System.err.println();
      System.exit(1);
    }

    File outputFile = new File(output);
    if (! outputFile.exists()
            && ! outputFile.mkdirs()) {
      System.err.println("ERROR: Cannot create output directory "
              + outputFile.getAbsolutePath());
      System.exit(1);
    }

    Set<String> trackedJobSet = new HashSet<String>();
    if (cmd.hasOption("trackjobs")) {
      String trackjobs = cmd.getOptionValue("trackjobs");
      String jobIds[] = trackjobs.split(",");
      trackedJobSet.addAll(Arrays.asList(jobIds));
    }

    String nodeFile = cmd.hasOption("nodes") ? cmd.getOptionValue("nodes") : "";

    boolean isSLS = inputSLS != null;
    String inputFiles[] = isSLS ? inputSLS.split(",") : inputRumen.split(",");
    SLSRunner sls = new SLSRunner(isSLS, inputFiles, nodeFile, output,
        trackedJobSet, cmd.hasOption("printsimulation"));
    sls.start();
  }
 public static void startSLSRunner(String args[]) throws Exception {
	  Options options = new Options();
	    options.addOption("inputrumen", true, "input rumen files");
	    options.addOption("inputsls", true, "input sls files");
	    options.addOption("nodes", true, "input topology");
	    options.addOption("output", true, "output directory");
	    options.addOption("trackjobs", true,
	            "jobs to be tracked during simulating");
	    options.addOption("printsimulation", false,
	            "print out simulation information");
	    options.addOption("maxbudgetperblock", true,"The maximum budget per data block");
	    options.addOption("scorethreshold", true,"The Z-Score Threshold");
	    options.addOption("selection", true,"The Node Selection Policy");
	    options.addOption("config_file_path" , true , "YLocSim configuration files");

	    options.addOption("t1" , true , "Fair Scheduler Node Locality Threshold");
	    options.addOption("t2" , true , "Fair Scheduler Rack Locality Threshold");
	    options.addOption("distribute" , true , "True if it is required to redistribute the data blocks over the new topology");

	    options.addOption("cpu" , true , "CPU Cores");
	    options.addOption("memory" , true , "Memory");

	    CommandLineParser parser = new GnuParser();
	    CommandLine cmd = parser.parse(options, args);

	    String inputRumen = cmd.getOptionValue("inputrumen");
	    String inputSLS = cmd.getOptionValue("inputsls");
	    String nodeFile = cmd.hasOption("nodes") ? cmd.getOptionValue("nodes") : "";
	    String output = cmd.getOptionValue("output");

	    int MAX_BUDGET_BLOCK = Integer.parseInt(cmd.getOptionValue("maxbudgetperblock"));
	    double SCORE_THRESHOLD = Double.parseDouble(cmd.getOptionValue("scorethreshold"));

	    int t1MS = Integer.parseInt(cmd.getOptionValue("t1"));
	    int t2MS = Integer.parseInt(cmd.getOptionValue("t2"));

	    int cpuCores = Integer.parseInt(cmd.getOptionValue("cpu"));
	    int memory = Integer.parseInt(cmd.getOptionValue("memory"));

	    NodeSelection ns = NodeSelection.RANDOM;
	    if (cmd.getOptionValue("selection").equalsIgnoreCase(NodeSelection.MIN.name())) {
	    	ns = NodeSelection.MIN;
	    }

	    System.out.println(MAX_BUDGET_BLOCK + " " + SCORE_THRESHOLD + " " + ns);
	    Config ylocSimConfig = null;
	    if (cmd.hasOption("config_file_path")) {
	       ylocSimConfig = ConfigFactory.parseFile(new File(cmd.getOptionValue("config_file_path")));
	       inputSLS = ylocSimConfig
					.getConfig(SLSConfiguration.YLOC_SIM_ROOT)
					.getString(SLSConfiguration.NEW_SLS_TRACE_FILE);
	       output =  ylocSimConfig
					.getConfig(SLSConfiguration.YLOC_SIM_ROOT)
					.getConfig(SLSConfiguration.SLS_CONF_ROOT)
					.getString(SLSConfiguration.SLS_OUTPUT_FOLDER);

	    }

	    boolean isDistributeDataEnabled = cmd.getOptionValue("distribute").equalsIgnoreCase("true") ? true : false;

	    if (!isDistributeDataEnabled) {
	    	inputSLS = cmd.getOptionValue("inputsls");
	    }

	    System.out.println("output : " + output);
	    System.out.println("inputsls : " + inputSLS);
	    System.out.println("nodeFile : " + nodeFile);

	    if ((inputRumen == null && inputSLS == null) || output == null) {
	      System.err.println();
	      System.err.println("ERROR: Missing input or output file");
	      System.err.println();
	      System.err.println("Options: -inputrumen|-inputsls FILE,FILE... " +
	              "-output FILE [-nodes FILE] [-trackjobs JobId,JobId...] " +
	              "[-printsimulation]");
	      System.err.println();
	      System.exit(1);
	    }

	    File outputFile = new File(output);
	    if (! outputFile.exists()
	            && ! outputFile.mkdirs()) {
	      System.err.println("ERROR: Cannot create output directory "
	              + outputFile.getAbsolutePath());
	      System.exit(1);
	    }

	    Set<String> trackedJobSet = new HashSet<String>();
	    if (cmd.hasOption("trackjobs")) {
	      String trackjobs = cmd.getOptionValue("trackjobs");
	      String jobIds[] = trackjobs.split(",");
	      trackedJobSet.addAll(Arrays.asList(jobIds));
	    }

	    boolean isSLS = inputSLS != null;
	    String inputFiles[] = isSLS ? inputSLS.split(",") : inputRumen.split(",");
	    SLSRunner sls = new SLSRunner(isSLS, inputFiles, nodeFile, output,
	        trackedJobSet, cmd.hasOption("printsimulation"),MAX_BUDGET_BLOCK,SCORE_THRESHOLD, ns, t1MS , t2MS, isDistributeDataEnabled, cpuCores , memory);
	    /*SLSRunner sls = new SLSRunner(isSLS, inputFiles, nodeFile, output,
		        trackedJobSet, cmd.hasOption("printsimulation"));*/
	    sls.start();
  }
}


text:
/**
 * @author Luciano Graziani @lgraziani2712
 * @license {@link http://www.opensource.org/licenses/mit-license.php|MIT License}
 *
 * @flow
 */
import {
  MOVE_RIGHT_TITLE,
  MOVE_RIGHT_TOOLTIP,
} from 'core/constants/localize/es/blocklyTextsBlocks';

import rightArrowURL from './images/right_arrow.svg';
import moveBuilder from './moveBuilder';

export default moveBuilder(MOVE_RIGHT_TITLE, MOVE_RIGHT_TOOLTIP, rightArrowURL);

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Knp\Bundle\MenuBundle\Tests\DependencyInjection\Compiler;

use Knp\Bundle\MenuBundle\DependencyInjection\Compiler\AddProvidersPass;
use PHPUnit\Framework\TestCase;
use Symfony\Component\DependencyInjection\Argument\IteratorArgument;
use Symfony\Component\DependencyInjection\Reference;

class AddProvidersPassTest extends TestCase
{
    public function testProcessWithoutProviderDefinition()
    {
        $containerBuilder = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->getMock();
        $containerBuilder->expects($this->once())
            ->method('hasDefinition')
            ->will($this->returnValue(false));
        $containerBuilder->expects($this->never())
            ->method('findTaggedServiceIds');

        $providersPass = new AddProvidersPass();

        $providersPass->process($containerBuilder);
    }

    public function testProcessForOneProvider()
    {
        $containerBuilderMock = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->getMock();
        $containerBuilderMock->expects($this->once())
            ->method('hasDefinition')
            ->will($this->returnValue(true));
        $containerBuilderMock->expects($this->once())
            ->method('findTaggedServiceIds')
            ->with($this->equalTo('knp_menu.provider'))
            ->will($this->returnValue(array('id' => array('provider_tag1'))));
        $containerBuilderMock->expects($this->once())
            ->method('setAlias')
            ->with(
                $this->equalTo('knp_menu.menu_provider'),
                $this->equalTo('id')
            );

        $providersPass = new AddProvidersPass();
        $providersPass->process($containerBuilderMock);
    }

    public function testProcessForManyProviders()
    {
        $expectedProviders = array(new Reference('id'), new Reference('id2'));

        if (class_exists(IteratorArgument::class)) {
            $expectedProviders = new IteratorArgument($expectedProviders);
        }

        $definitionMock = $this->getMockBuilder('Symfony\Component\DependencyInjection\Definition')
            ->disableOriginalConstructor()
            ->getMock();
        $definitionMock->expects($this->once())
            ->method('replaceArgument')
            ->with($this->equalTo(0), $expectedProviders);

        $containerBuilderMock = $this->getMockBuilder('Symfony\Component\DependencyInjection\ContainerBuilder')->getMock();
        $containerBuilderMock->expects($this->once())
            ->method('hasDefinition')
            ->will($this->returnValue(true));
        $containerBuilderMock->expects($this->once())
            ->method('findTaggedServiceIds')
            ->with($this->equalTo('knp_menu.provider'))
            ->will($this->returnValue(array(
                'id' => array('provider_tag1'),
                'id2' => array('provider_tag2')
            )));
        $containerBuilderMock->expects($this->once())
            ->method('setAlias')
            ->with(
                $this->equalTo('knp_menu.menu_provider'),
                $this->equalTo('knp_menu.menu_provider.chain')
            );
        $containerBuilderMock->expects($this->once())
            ->method('getDefinition')
            ->with($this->equalTo('knp_menu.menu_provider.chain'))
            ->will($this->returnValue($definitionMock));

        $providersPass = new AddProvidersPass();
        $providersPass->process($containerBuilderMock);
    }
}


text:
namespace PetStore.Data
{
    using System;
    using System.Collections.Generic;

    public partial class Pet
    {
        public int PetId { get; set; }
        public int SpeciesId { get; set; }
        public System.DateTime BirthDate { get; set; }
        public decimal Price { get; set; }
        public int ColorId { get; set; }
        public string Breed { get; set; }

        public virtual Color Color { get; set; }
        public virtual Species Species { get; set; }
    }
}


text:
package linprogMPC;

import linprogMPC.helper.ConsumptionProfiles;
import topology.ActorTopology;

/**
 *
 * Topology for example with 5 buildings with Linear Programming
 *
 * @author andreas.thut
 *
 */
public class Topology {

	private static String simulationName = "LinProg";
	public static final int NR_OF_CONSUMERS = 5;

	// Efficiencies
	private static final double EFFICIENCY_CHP_H = .6;
	private static final double EFFICIENCY_CHP_EL = .25;
	private static final double EFFICIENCY_THERMALSTORAGE = 1.;
	private static final double EFFICIENCY_GASBOILER = .65;
	private static final double EFFICIENCY_OILBOILER = .65;
	private static final double EFFICIENCY_HEATPUMP = 3.8;
	private static final double EFFICIENCY_BAT = 1.;

	// Capacities
	private static final double QDOT_MAX_THERMALSTORAGE_IN = 5.;
	private static final double QDOT_MAX_THERMALSTORAGE_OUT = 5.;
	private static final double QDOT_MAX_GASBOILER = 40.;
	private static final double QDOT_MAX_OILBOILER = 40.;
	private static final double P_MAX_BATTERY_IN = 5.;
	private static final double P_MAX_BATTERY_OUT = 5.;
	private static final double QDOT_MAX_CHP = 80.;
	//private static final double QDOT_MAX_SOLARTHERMIC = 3.;
	private static final double P_MAX_HEATPUMP = 20.;
	private static final double CAPACITY_THERMALSTORAGE = 100000.;
	private static final double CAPACITY_BATTERY = 40000.;
	private static final int PORT_UNDEFINED = 0;

	public static ActorTopology createTopology(){
		int port = 8081;
		ActorTopology top = new ActorTopology(simulationName);
		top.addActor(simulationName, ActorFactory.createLinProgBehavior());
		ConsumptionProfiles consumptionProfiles = new ConsumptionProfiles(NR_OF_CONSUMERS);

		//Aggregated Consumption
//		top.addActorAsChild(simulationName + "/Consumption", ActorFactory.createConsumer("/Consumption", port++));

		String building1Name = "Building1";
		Boolean LDHeatingB1 = true;
		Integer heatTransportLengthB1 = 50;
		ActorTopology building1 = new ActorTopology(building1Name);
		building1.addActor(building1Name, ActorFactory.createBuilding(port++, LDHeatingB1, heatTransportLengthB1));
		building1.addActorAsChild(building1Name + "/OilBoiler", ActorFactory.createOilBoiler(QDOT_MAX_OILBOILER, EFFICIENCY_OILBOILER, PORT_UNDEFINED));
		building1.addActorAsChild(building1Name + "/Consumption", ActorFactory.createConsumer(consumptionProfiles, 0, PORT_UNDEFINED));

		String building2Name = "Building2";
		Boolean LDHeatingB2 = false;
		Integer heatTransportLengthB2 = 150;
		ActorTopology building2 = new ActorTopology(building2Name);
		building2.addActor(building2Name, ActorFactory.createBuilding(port++, LDHeatingB2, heatTransportLengthB2));
		building2.addActorAsChild(building2Name + "/Consumption", ActorFactory.createConsumer(consumptionProfiles, 1, PORT_UNDEFINED));
		building2.addActorAsChild(building2Name + "/PV", ActorFactory.createPV(10, PORT_UNDEFINED));
		building2.addActorAsChild(building2Name + "/HeatPump", ActorFactory.createHeatPump(P_MAX_HEATPUMP, EFFICIENCY_HEATPUMP, PORT_UNDEFINED));
		building2.addActorAsChild(building2Name + "/ThermalStorage", ActorFactory.createThermalStorage(QDOT_MAX_THERMALSTORAGE_IN, QDOT_MAX_THERMALSTORAGE_OUT, CAPACITY_THERMALSTORAGE, EFFICIENCY_THERMALSTORAGE, PORT_UNDEFINED));

		String building3Name = "Building3";
		Boolean LDHeatingB3 = false;
		Integer heatTransportLengthB3 = 250;
		ActorTopology building3 = new ActorTopology(building3Name);
		building3.addActor(building3Name, ActorFactory.createBuilding(port++, LDHeatingB3, heatTransportLengthB3));
		building3.addActorAsChild(building3Name + "/Consumption", ActorFactory.createConsumer(consumptionProfiles, 2, PORT_UNDEFINED));
		building3.addActorAsChild(building3Name + "/PV", ActorFactory.createPV(10, PORT_UNDEFINED));
		building3.addActorAsChild(building3Name + "/Battery", ActorFactory.createBattery(P_MAX_BATTERY_IN, P_MAX_BATTERY_OUT, EFFICIENCY_BAT, EFFICIENCY_BAT, CAPACITY_BATTERY, PORT_UNDEFINED));
		building3.addActorAsChild(building3Name + "/GasBoiler", ActorFactory.createGasBoiler(QDOT_MAX_GASBOILER, EFFICIENCY_GASBOILER, PORT_UNDEFINED));

		String building4Name = "Building4";
		Boolean LDHeatingB4 = false;
		Integer heatTransportLengthB4 = 350;
		ActorTopology building4 = new ActorTopology(building4Name);
		building4.addActor(building4Name, ActorFactory.createBuilding(port++, LDHeatingB4, heatTransportLengthB4));
		building4.addActorAsChild(building4Name + "/Consumption", ActorFactory.createConsumer(consumptionProfiles, 3, port++));
		building4.addActorAsChild(building4Name + "/CHP", ActorFactory.createCHP(QDOT_MAX_CHP, EFFICIENCY_CHP_EL, EFFICIENCY_CHP_H, port++));
		building4.addActorAsChild(building4Name + "/ThermalStorage", ActorFactory.createThermalStorage(QDOT_MAX_THERMALSTORAGE_IN, QDOT_MAX_THERMALSTORAGE_OUT, CAPACITY_THERMALSTORAGE, EFFICIENCY_THERMALSTORAGE, port++));

		String building5Name = "Building5";
		Boolean LDHeatingB5 = false;
		Integer heatTransportLengthB5 = 450;
		ActorTopology building5 = new ActorTopology(building5Name);
		building5.addActor(building5Name, ActorFactory.createBuilding(port++, LDHeatingB5, heatTransportLengthB5));
		building5.addActorAsChild(building5Name + "/Consumption", ActorFactory.createConsumer(consumptionProfiles, 4, port++));
		building5.addActorAsChild(building5Name + "/CHP", ActorFactory.createCHP(QDOT_MAX_CHP, EFFICIENCY_CHP_EL, EFFICIENCY_CHP_H, port++));
		building5.addActorAsChild(building5Name + "/SolarThermic", ActorFactory.createSolarThermic(10, port++));
		building5.addActorAsChild(building5Name + "/ThermalStorage", ActorFactory.createThermalStorage(QDOT_MAX_THERMALSTORAGE_IN, QDOT_MAX_THERMALSTORAGE_OUT, CAPACITY_THERMALSTORAGE, EFFICIENCY_THERMALSTORAGE, port++));

//		String building6Name = "Building6";
//		Boolean LDHeatingB6 = false;
//		Integer heatTransportLengthB6 = 550;
//		ActorTopology building6 = new ActorTopology(building6Name);
//		building6.addActor(building6Name, ActorFactory.createBuilding(building6Name, port++, LDHeatingB6, heatTransportLengthB6));
//		building6.addActorAsChild(building6Name + "/Consumption", ActorFactory.createConsumer("Consumption", consumptionProfiles, 4, port++));
//		building6.addActorAsChild(building6Name + "/SolarThermic", ActorFactory.createSolarThermic("SolarThermic", AREA_SOLARTHERMIC, EFFICIENCY_SOLARTHERMIC, port++));
//		building6.addActorAsChild(building6Name + "/HeatPump", ActorFactory.createHeatPump("HeatPump", P_MAX_HEATPUMP, EFFICIENCY_HEATPUMP, PORT_UNDEFINED));
//		building6.addActorAsChild(building6Name + "/OilBoiler", ActorFactory.createOilBoiler("OilBoiler", QDOT_MAX_OILBOILER, EFFICIENCY_OILBOILER, PORT_UNDEFINED));

//		String districtStorageName = "DistrictStorage";
//		ActorTopology districtStorage = new ActorTopology(districtStorageName);
//		districtStorage.addActor(districtStorageName, ActorFactory.createBattery("Battery", 10*P_MAX_BATTERY_IN, 10*P_MAX_BATTERY_OUT, EFFICIENCY_BAT, 10*CAPACITY_BATTERY, PORT_UNDEFINED));

		top.addSubTopology(simulationName, building3);
		top.addSubTopology(simulationName, building2);
		top.addSubTopology(simulationName, building1);
		top.addSubTopology(simulationName, building4);
		top.addSubTopology(simulationName, building5);
//		top.addSubTopology(simulationName, building6);
//		top.addSubTopology(simulationName, districtStorage);

		return top;
	}

}


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

  <meta content="text/html; charset=utf-8" http-equiv="Content-Type"/>
  <title>
   Scala Documentation — Akka Documentation
  </title>
  <link href="_static/style.css" rel="stylesheet" type="text/css"/>
  <link href="_static/pygments.css" rel="stylesheet" type="text/css"/>
  <link href="_static/prettify.css" rel="stylesheet" type="text/css"/>
  <link href="_static/base.css" rel="stylesheet" type="text/css"/>
  <link href="_static/docs.css" rel="stylesheet" type="text/css"/>
  <link href="http://fonts.googleapis.com/css?family=Exo:300,400,600,700" rel="stylesheet" type="text/css"/>

  <link href="_static/favicon.ico" rel="shortcut icon"/>
  <link href="index.html" rel="top" title="Akka Documentation"/>
  <link href="intro/index-scala.html" rel="next" title="Introduction"/>
  <link href="additional/http.html" rel="prev" title="Incomplete List of HTTP Frameworks"/>

        Documentation

        FAQ

        Download

        Mailing List

        Code

        Commercial Support

     Scala Documentation

          |

          Introduction

          »

          Contents

          «

          Incomplete List of HTTP Frameworks

          |

         Version 2.2.3

         Scala Documentation

            Introduction

              What is Akka?

              Why Akka?

              Getting Started

              The Obligatory Hello World

              Use-case and Deployment Scenarios

              Examples of use-cases for Akka

            General

              Terminology, Concepts

              Actor Systems

              What is an Actor?

              Supervision and Monitoring

              Actor References, Paths and Addresses

              Location Transparency

              Akka and the Java Memory Model

              Message Delivery Guarantees

              Configuration

            Actors

              Actors

              Typed Channels (EXPERIMENTAL)

              Typed Actors

              Fault Tolerance

              Dispatchers

              Mailboxes

              Routing

              FSM

              Testing Actor Systems

            Futures and Agents

              Futures

              Dataflow Concurrency

              Software Transactional Memory

              Agents

              Transactors

            Networking

              Cluster Specification

              Cluster Usage

              Remoting

              Serialization

              I/O

              Encoding and decoding binary data

              Using TCP

              Using UDP

              ZeroMQ

              Camel

            Utilities

              Event Bus

              Logging

              Scheduler

              Duration

              Circuit Breaker

              Akka Extensions

              Durable Mailboxes

              Microkernel

            HowTo: Common Patterns

              Throttling Messages

              Balancing Workload Across Nodes

              Work Pulling Pattern to throttle and distribute work, and prevent mailbox overflow

              Ordered Termination

              Akka AMQP Proxies

              Shutdown Patterns in Akka 2

              Distributed (in-memory) graph processing with Akka

              Case Study: An Auto-Updating Cache Using Actors

              Discovering message flows in actor systems with the Spider Pattern

              Scheduling Periodic Messages

              Template Pattern

            Experimental Modules

              Multi Node Testing

              External Contributions

            Information for Akka Developers

              Building Akka

              Multi JVM Testing

              I/O Layer Design

              Developer Guidelines

              Documentation Guidelines

              Team

            Project Information

              Migration Guides

              Issue Tracking

              Licenses

              Sponsors

              Project

            Additional Information

              Books

              Here is a list of recipes for all things Akka

              Other Language Bindings

              Akka in OSGi

              Incomplete List of HTTP Frameworks

        Contents

       Akka

       Documentation

       FAQ

       Downloads

       News

       Blog

       Contribute

       Community Projects

       Source Code

       Mailing List

       Report a Bug

       Company

       Commercial Support

       Team

       Contact

     © 2013

      Typesafe Inc.

      Akka is Open Source and available under the Apache 2 License.

     Last updated: Feb 22, 2014


text:
'''A wrapper around riscv32-unknown-elf-ld for OTBN

This just adds the OTBN linker script and calls the underlying
linker.'''

import os
import subprocess
import sys
import tempfile
from contextlib import contextmanager
from typing import Iterator, List, Optional

from mako import exceptions  # type: ignore
from mako.template import Template  # type: ignore

from shared.mem_layout import get_memory_layout
from shared.toolchain import find_tool

def interpolate_linker_script(in_path: str, out_path: str) -> None:
    mems = get_memory_layout()
    try:
        template = Template(filename=in_path)
        rendered = template.render(imem_lma=mems.imem_address,
                                   imem_length=mems.imem_size_bytes,
                                   dmem_lma=mems.dmem_address,
                                   dmem_length=mems.dmem_size_bytes,
                                   dmem_bus_length=mems.dmem_bus_size_bytes)
    except OSError as err:
        raise RuntimeError(str(err)) from None
    except:  # noqa: 722
        raise RuntimeError(exceptions.text_error_template().render()) from None

    try:
        with open(out_path, 'w') as out_file:
            out_file.write(rendered)
    except FileNotFoundError:
        raise RuntimeError(
            'Failed to open output file at {!r}.'.format(out_path)) from None

@contextmanager
def mk_linker_script() -> Iterator[str]:
    ld_in = os.path.abspath(
        os.path.join(os.path.dirname(__file__), '..', 'data', 'otbn.ld.tpl'))
    with tempfile.TemporaryDirectory(prefix='otbn-ld-') as tmpdir:
        ld_out = os.path.join(tmpdir, 'otbn.ld')
        try:
            interpolate_linker_script(ld_in, ld_out)
        except RuntimeError as err:
            sys.stderr.write(
                'Failed to interpolate linker script: {}\n'.format(err))
            return 1

        yield ld_out

def run_ld(ld_script: Optional[str], args: List[str]) -> int:
    '''Run the underlying linker and return the status code'''
    ld_name = find_tool('ld')
    # The --no-check-sections argument tells ld not to complain when we have
    # more than one section with the same VMA. Since we have a Harvard
    # architecture where data and instructions both start at zero, we expect
    # that to happen.
    cmd = [ld_name, '--no-check-sections']
    if ld_script is not None:
        cmd.append('--script={}'.format(ld_script))
    cmd += args

    try:
        return subprocess.run(cmd).returncode
    except FileNotFoundError:
        sys.stderr.write(
            'Unknown command: {!r}. '
            '(is it installed and on your PATH?)\n'.format(ld_name))
        return 127

def main(argv: List[str]) -> int:
    # Only add the --script argument if the caller isn't supplying one
    # themselves. This argument accumulates (so -T foo -T bar is like
    # concatenating foo and bar), so we mustn't supply our own if the user
    # has one.
    needs_script = True
    for arg in argv[1:]:
        if arg == '-T' or arg.startswith('--script='):
            needs_script = False
            break

    if needs_script:
        with mk_linker_script() as script_path:
            return run_ld(script_path, argv[1:])
    else:
        return run_ld(None, argv[1:])

if __name__ == '__main__':
    sys.exit(main(sys.argv))


text:
<?php

use yii\db\Schema;
use yii\db\Migration;

class m150718_235340_create_status_table extends Migration
{
    public function up()
    {
        $tableOptions = null;
        if ($this->db->driverName === 'mysql') {
            // http://stackoverflow.com/questions/766809/whats-the-difference-between-utf8-general-ci-and-utf8-unicode-ci
            $tableOptions = 'CHARACTER SET utf8 COLLATE utf8_unicode_ci ENGINE=InnoDB';
        }

        $this->createTable('{{%status}}', [
            'id' => $this->primaryKey(),
            // 'category' => $this->string(15)->notNull(),
            // 'level' => $this->text(),
            'status' => $this->String(40)->notNull(),
            //'status' => $this->String(20)->notNull(),
            'description' => $this->text(),
           //'previous' => $this->integer()->notNull(),
            //'next' => $this->integer()->notNull(),
            // 'created_dt' => $this->datetime()->notNull(),
            // 'updated_dt' => $this->datetime()->notNull(),
        ], $tableOptions);

       // $this->addForeignKey('status_ibfk_1', '{{%status}}', 'previous', '{{%status}}', 'id', 'RESTRICT', 'RESTRICT');
       // $this->addForeignKey('status_ibfk_2', '{{%activity}}', 'next', '{{%status}}', 'id', 'RESTRICT', 'RESTRICT');
    }

    public function down()
    {
      //  $this->dropForeignKey('status_ibfk_1', '{{%status}}');
      //  $this->dropForeignKey('status_ibfk_2', '{{%status}}');

        $this->dropTable('{{%status}}');
    }
}


text:
//
//  AFNetworkStream.h
//  Amber
//
//  Created by Keith Duncan on 02/03/2010.
//  Copyright 2010. All rights reserved.
//

#import <Foundation/Foundation.h>

#import "CoreNetworking/AFNetwork-Macros.h"

@class AFNetworkPacketQueue;
@class AFNetworkPacket;

@class AFNetworkStreamQueue;

@class AFNetworkSchedule;

@protocol AFNetworkStreamQueueDelegate <NSObject>

 @required

/*!
	\brief
	Only the following events are forwarded before being processed internally:

	- NSStreamEventOpenCompleted
	- NSStreamEventHasBytesAvailable
	- NSStreamEventHasSpaceAvailable
	- NSStreamEventEndEncountered

	all other events are captured and processed.
 */
- (void)networkStream:(AFNetworkStreamQueue *)networkStream didReceiveEvent:(NSStreamEvent)event;

/*!
	\brief
	You must implement this method to handle any errors; errors must be handled.
 */
- (void)networkStream:(AFNetworkStreamQueue *)networkStream didReceiveError:(NSError *)error;

 @optional

/*!
	\brief
	Implement to know when a packet has been removed from the stream's queue.
 */
- (void)networkStream:(AFNetworkStreamQueue *)networkStream didDequeuePacket:(AFNetworkPacket *)packet;

/*!
	\brief
	Implement this method to be informed of packet progress.
 */
- (void)networkStream:(AFNetworkStreamQueue *)networkStream didTransfer:(AFNetworkPacket *)packet bytesTransferred:(NSInteger)bytesTransferred totalBytesTransferred:(NSInteger)totalBytesTransferred totalBytesExpectedToTransfer:(NSInteger)totalBytesExpectedToTransfer;

@end

#pragma mark -

/*!
	\brief
	Asynchronously read/write data from/to an NSStream.
 */
@interface AFNetworkStreamQueue : NSObject {
 @private
	id <AFNetworkStreamQueueDelegate> _delegate;

	NSStream *_stream;
	SEL _performSelector;

	NSUInteger _streamFlags;

	AFNetworkSchedule *_schedule;

	NSUInteger _queueSuspendCount;
	AFNetworkPacketQueue *_packetQueue;
	BOOL _dequeuing;
}

/*
	Creation
 */

/*!
	\brief
	The stream MUST be unopened, this is asserted.
 */
- (id)initWithStream:(NSStream *)stream;

@property (assign, nonatomic) id <AFNetworkStreamQueueDelegate> delegate;

/*
	Scheduling

	Used to schedule the underlying stream and timeout timer.
 */

- (void)scheduleInRunLoop:(NSRunLoop *)runLoop forMode:(NSString *)mode;

- (void)scheduleInQueue:(dispatch_queue_t)queue;

/*
	State
 */

- (void)open;
- (BOOL)isOpen;

- (void)close;
- (BOOL)isClosed;

- (id)streamPropertyForKey:(NSString *)key;
- (BOOL)setStreamProperty:(id)property forKey:(NSString *)key;

/*
	Queue
 */

- (void)enqueuePacket:(AFNetworkPacket *)packet;
- (NSUInteger)countOfEnqueuedPackets;

- (void)suspendPacketQueue;
- (void)resumePacketQueue;

@end


text:
For learning typescript, this project describes the application, loma testing system.

Patterns and Principles in this project:

- Generic Repository Pattern
- Singleton Pattern
- Multi-layer Architecture Pattern

Tools:
- NodeJS
- TypeScript
- ExpressJS
- MongoDB
- Mongoose
- GulpJS
- VSCode Task Runners


text:
/*
 * This file is part of EconomyLite, licensed under the MIT License (MIT). See the LICENSE file at the root of this project for more information.
 */
package io.github.flibio.economylite.impl.economy.registry;

import org.spongepowered.api.registry.CatalogRegistryModule;
import org.spongepowered.api.service.economy.Currency;

import io.github.flibio.economylite.EconomyLite;

import java.util.Collection;
import java.util.Optional;

public class CurrencyRegistryModule implements CatalogRegistryModule<Currency> {

    @Override
    public Optional<Currency> getById(String id) {
        for (Currency cur : EconomyLite.getCurrencyService().getCurrencies()) {
            if (cur.getId().equals(id)) {
                return Optional.of(cur);
            }
        }
        return Optional.empty();
    }

    @Override
    public Collection<Currency> getAll() {
        return EconomyLite.getCurrencyService().getCurrencies();
    }
}


text:
import warnings

import numpy as np

from ..qt import qt_api

try:
    import matplotlib as mpl
    from matplotlib.figure import Figure
    from matplotlib import _pylab_helpers
    from matplotlib.colors import LinearSegmentedColormap
    if qt_api is None:
        raise ImportError
    else:
        from matplotlib.backends.backend_qt4 import FigureManagerQT
        from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg
except ImportError:
    FigureCanvasQTAgg = object  # hack to prevent nosetest and autodoc errors
    LinearSegmentedColormap = object
    print("Could not import matplotlib -- skimage.viewer not available.")

from ..qt import QtGui

__all__ = ['init_qtapp', 'start_qtapp', 'RequiredAttr', 'figimage',
           'LinearColormap', 'ClearColormap', 'FigureCanvas', 'new_plot',
           'update_axes_image']

QApp = None

def init_qtapp():
    """Initialize QAppliction.

    The QApplication needs to be initialized before creating any QWidgets
    """
    global QApp
    QApp = QtGui.QApplication.instance()
    if QApp is None:
        QApp = QtGui.QApplication([])
    return QApp

def is_event_loop_running(app=None):
    """Return True if event loop is running."""
    if app is None:
        app = init_qtapp()
    if hasattr(app, '_in_event_loop'):
        return app._in_event_loop
    else:
        return False

def start_qtapp(app=None):
    """Start Qt mainloop"""
    if app is None:
        app = init_qtapp()
    if not is_event_loop_running(app):
        app._in_event_loop = True
        app.exec_()
        app._in_event_loop = False
    else:
        app._in_event_loop = True

class RequiredAttr(object):
    """A class attribute that must be set before use."""

    instances = dict()

    def __init__(self, msg='Required attribute not set', init_val=None):
        self.instances[self, None] = init_val
        self.msg = msg

    def __get__(self, obj, objtype):
        value = self.instances[self, obj]
        if value is None:
            # Should raise an error but that causes issues with the buildbot.
            warnings.warn(self.msg)
            self.__set__(obj, self.init_val)
        return value

    def __set__(self, obj, value):
        self.instances[self, obj] = value

class LinearColormap(LinearSegmentedColormap):
    """LinearSegmentedColormap in which color varies smoothly.

    This class is a simplification of LinearSegmentedColormap, which doesn't
    support jumps in color intensities.

    Parameters
    ----------
    name : str
        Name of colormap.

    segmented_data : dict
        Dictionary of 'red', 'green', 'blue', and (optionally) 'alpha' values.
        Each color key contains a list of `x`, `y` tuples. `x` must increase
        monotonically from 0 to 1 and corresponds to input values for a
        mappable object (e.g. an image). `y` corresponds to the color
        intensity.

    """
    def __init__(self, name, segmented_data, **kwargs):
        segmented_data = dict((key, [(x, y, y) for x, y in value])
                              for key, value in segmented_data.items())
        LinearSegmentedColormap.__init__(self, name, segmented_data, **kwargs)

class ClearColormap(LinearColormap):
    """Color map that varies linearly from alpha = 0 to 1
    """
    def __init__(self, rgb, max_alpha=1, name='clear_color'):
        r, g, b = rgb
        cg_speq = {'blue':  [(0.0, b), (1.0, b)],
                   'green': [(0.0, g), (1.0, g)],
                   'red':   [(0.0, r), (1.0, r)],
                   'alpha': [(0.0, 0.0), (1.0, max_alpha)]}
        LinearColormap.__init__(self, name, cg_speq)

class FigureCanvas(FigureCanvasQTAgg):
    """Canvas for displaying images."""
    def __init__(self, figure, **kwargs):
        self.fig = figure
        FigureCanvasQTAgg.__init__(self, self.fig)
        FigureCanvasQTAgg.setSizePolicy(self,
                                        QtGui.QSizePolicy.Expanding,
                                        QtGui.QSizePolicy.Expanding)
        FigureCanvasQTAgg.updateGeometry(self)

    def resizeEvent(self, event):
        FigureCanvasQTAgg.resizeEvent(self, event)
        # Call to `resize_event` missing in FigureManagerQT.
        # See https://github.com/matplotlib/matplotlib/pull/1585
        self.resize_event()

def new_canvas(*args, **kwargs):
    """Return a new figure canvas."""
    allnums = _pylab_helpers.Gcf.figs.keys()
    num = max(allnums) + 1 if allnums else 1

    FigureClass = kwargs.pop('FigureClass', Figure)
    figure = FigureClass(*args, **kwargs)
    canvas = FigureCanvas(figure)
    fig_manager = FigureManagerQT(canvas, num)
    return fig_manager.canvas

def new_plot(parent=None, subplot_kw=None, **fig_kw):
    """Return new figure and axes.

    Parameters
    ----------
    parent : QtWidget
        Qt widget that displays the plot objects. If None, you must manually
        call ``canvas.setParent`` and pass the parent widget.
    subplot_kw : dict
        Keyword arguments passed ``matplotlib.figure.Figure.add_subplot``.
    fig_kw : dict
        Keyword arguments passed ``matplotlib.figure.Figure``.
    """
    if subplot_kw is None:
        subplot_kw = {}
    canvas = new_canvas(**fig_kw)
    canvas.setParent(parent)

    fig = canvas.figure
    ax = fig.add_subplot(1, 1, 1, **subplot_kw)
    return fig, ax

def figimage(image, scale=1, dpi=None, **kwargs):
    """Return figure and axes with figure tightly surrounding image.

    Unlike pyplot.figimage, this actually plots onto an axes object, which
    fills the figure. Plotting the image onto an axes allows for subsequent
    overlays of axes artists.

    Parameters
    ----------
    image : array
        image to plot
    scale : float
        If scale is 1, the figure and axes have the same dimension as the
        image.  Smaller values of `scale` will shrink the figure.
    dpi : int
        Dots per inch for figure. If None, use the default rcParam.
    """
    dpi = dpi if dpi is not None else mpl.rcParams['figure.dpi']
    kwargs.setdefault('interpolation', 'nearest')
    kwargs.setdefault('cmap', 'gray')

    h, w, d = np.atleast_3d(image).shape
    figsize = np.array((w, h), dtype=float) / dpi * scale

    fig, ax = new_plot(figsize=figsize, dpi=dpi)
    fig.subplots_adjust(left=0, bottom=0, right=1, top=1)

    ax.set_axis_off()
    ax.imshow(image, **kwargs)
    return fig, ax

def update_axes_image(image_axes, image):
    """Update the image displayed by an image plot.

    This sets the image plot's array and updates its shape appropriately

    Parameters
    ----------
    image_axes : `matplotlib.image.AxesImage`
        Image axes to update.
    image : array
        Image array.
    """
    image_axes.set_array(image)

    # Adjust size if new image shape doesn't match the original
    h, w = image.shape[:2]
    image_axes.set_extent((0, w, h, 0))


text:
package kiwi.exception;

/**
 * Thrown if an expected revision does not exists
 *
 * @author Stephanie Stroka
 *			(stephanie.stroka@salzburgresearch.at)
 *
 */
public class RevisionDoesNotExistException extends Exception {

	/**
	 *
	 */
	private static final long serialVersionUID = 2796740006245929519L;

	/**
	 * Default constructor
	 */
	public RevisionDoesNotExistException() {
		super();
	}

	/**
	 * Constructor with param message
	 * @param msg
	 */
	public RevisionDoesNotExistException(String msg) {
		super(msg);
	}
}


text:
#import "FBRequestConnectionTests.h"
#import "FBTestSession.h"
#import "FBTestSession+Internal.h"
#import "FBRequestConnection.h"
#import "FBRequestConnection+Internal.h"
#import "FBRequest.h"
#import "FBTestBlocker.h"
#import "FBError.h"

#if defined(FACEBOOKSDK_SKIP_REQUEST_CONNECTION_TESTS)

#pragma message ("warning: Skipping FBRequestConnectionTests")

#else

@implementation FBRequestConnectionTests

- (void)testCancelInvokesHandler {
    FBRequest *request = [[[FBRequest alloc] initWithSession:self.defaultTestSession graphPath:@"me"] autorelease];
    FBRequestConnection *connection = [[FBRequestConnection alloc] init];
    __block int count = 0;
    __block FBTestBlocker *blocker = [[FBTestBlocker alloc] init];

    [connection addRequest:request completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        STAssertEqualObjects(FBErrorOperationCancelled, error.code, @"Expected FBErrorOperationCancelled code for error:%@", error);
        STAssertEquals(++count, 1, @"Expected handler to only be called once");
        [blocker signal];
    }];
    [connection start];
    [connection cancel];

    STAssertTrue([blocker waitWithTimeout:10], @" handler was not invoked");

    [connection release];
}

- (void)testConcurrentRequests
{
    __block FBTestBlocker *blocker1 = [[FBTestBlocker alloc] init];
    __block FBTestBlocker *blocker2 = [[FBTestBlocker alloc] init];
    __block FBTestBlocker *blocker3 = [[FBTestBlocker alloc] init];
    [[[[FBRequest alloc] initWithSession:self.defaultTestSession graphPath:@"me"] autorelease] startWithCompletionHandler:[self handlerExpectingSuccessSignaling:blocker1]];
    [[[[FBRequest alloc] initWithSession:self.defaultTestSession graphPath:@"me"] autorelease] startWithCompletionHandler:[self handlerExpectingSuccessSignaling:blocker2]];
    [[[[FBRequest alloc] initWithSession:self.defaultTestSession graphPath:@"me"] autorelease] startWithCompletionHandler:[self handlerExpectingSuccessSignaling:blocker3]];

    [blocker1 wait];
    [blocker2 wait];
    [blocker3 wait];

    [blocker1 release];
    [blocker2 release];
    [blocker3 release];
}

- (void)testWillPiggybackTokenExtensionIfNeeded
{
    FBTestSession *session = [self getSessionWithSharedUserWithPermissions:nil];
    session.forceAccessTokenRefresh = YES;

    FBRequest *request = [[[FBRequest alloc] initWithSession:session graphPath:@"me"] autorelease];

    FBTestBlocker *blocker = [[FBTestBlocker alloc] init];
    FBRequestConnection *connection = [[FBRequestConnection alloc] init];
    [connection addRequest:request completionHandler:[self handlerExpectingSuccessSignaling:blocker]];
    [connection start];

    [blocker wait];
    [blocker release];

    NSArray *requests = [connection performSelector:@selector(requests)];
    STAssertTrue(requests.count == 2, @"didn't piggyback");

    [connection release];
}

- (void)testWillNotPiggybackIfWouldExceedBatchSize
{
    FBTestSession *session = [self getSessionWithSharedUserWithPermissions:nil];
    session.forceAccessTokenRefresh = YES;

    FBRequestConnection *connection = [[FBRequestConnection alloc] init];

    const int batchSize = 50;
    for (int i = 0; i < batchSize; ++i) {
        FBRequest *request = [[[FBRequest alloc] initWithSession:session graphPath:@"me"] autorelease];

        // Minimize traffic by just getting our id.
        [request.parameters setObject:@"id" forKey:@"fields"];

        [connection addRequest:request completionHandler:[self handlerExpectingSuccessSignaling:nil]];
    }
    [connection start];
    // We don't need to wait for the requests to complete to determine success.

    NSArray *requests = [connection performSelector:@selector(requests)];
    STAssertTrue(requests.count == batchSize, @"piggybacked but shouldn't have");
    [connection release];
}

- (void)testNoRequests
{
    FBRequestConnection *connection = [[FBRequestConnection alloc] init];
    STAssertThrows([connection start], @"should throw");
    [connection release];
}

- (void)testCachedRequests
{
    FBTestBlocker *blocker = [[FBTestBlocker alloc] init];

    FBTestSession *session = [self getSessionWithSharedUserWithPermissions:nil];

    // here we just want to seed the cache, by identifying the cache, and by choosing not to consult the cache
    FBRequestConnection *connection = [[FBRequestConnection alloc] init];
    FBRequest *request = [[[FBRequest alloc] initWithSession:session graphPath:@"me"] autorelease];
    [request.parameters setObject:@"id,first_name" forKey:@"fields"];
    [connection addRequest:request completionHandler:[self handlerExpectingSuccessSignaling:blocker]];
    [connection startWithCacheIdentity:@"FBUnitTests"
                 skipRoundtripIfCached:NO];

    [blocker wait];

    STAssertFalse(connection.isResultFromCache, @"Should not have cached, and should have fetched from server");

    [connection release];
    [blocker release];

    __block BOOL completedWithoutBlocking = NO;

    // here we expect to complete on the cache, so we will confirm that
    connection = [[FBRequestConnection alloc] init];
    request = [[[FBRequest alloc] initWithSession:session graphPath:@"me"] autorelease];
    [request.parameters setObject:@"id,first_name" forKey:@"fields"];
    [connection addRequest:request completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        STAssertNotNil(result, @"Expected a successful result");
        completedWithoutBlocking = YES;
    }];
    [connection startWithCacheIdentity:@"FBUnitTests"
                 skipRoundtripIfCached:YES];

    // should have completed successfully by here
    STAssertTrue(completedWithoutBlocking, @"Should have called the handler, due to cache hit");
    STAssertTrue(connection.isResultFromCache, @"Should not have fetched from server");
    [connection release];
}

- (void)testDelete
{
    // this is a longish test, here is the breakdown:
    // 1) three objects are created in one batch
    // 2) two objects are deleted with different approaches, and one object created in the next batch
    // 3) one object is deleted
    // 4) another object is deleted
    FBTestBlocker *blocker = [[[FBTestBlocker alloc] initWithExpectedSignalCount:3] autorelease];

    FBTestSession *session = [self getSessionWithSharedUserWithPermissions:nil];

    FBRequest *request = [[[FBRequest alloc] initWithSession:session
                                                   graphPath:@"me/feed"]
                          autorelease];

    [request.parameters setObject:@"dummy status"
                           forKey:@"name"];
    [request.parameters setObject:@"http://www.facebook.com"
                           forKey:@"link"];
    [request.parameters setObject:@"dummy description"
                           forKey:@"description"];
    [request.parameters setObject:@"post"
                           forKey:@"method"];

    NSMutableArray *fbids = [NSMutableArray array];

    FBRequestHandler handler = ^(FBRequestConnection *connection, id<FBGraphObject> result, NSError *error) {
        // There's a lot going on in this test. To make failures easier to understand, giving each
        // of the handlers a number so we can tell what failed.
        STAssertNotNil(result, @"should have a result here: Handler 1");
        STAssertNil(error, @"should not have an error here: Handler 1");
        [fbids addObject: [[result objectForKey:@"id"] description]];
        [blocker signal];
    };

    // this creates three objects
    FBRequestConnection *connection = [[[FBRequestConnection alloc] init] autorelease];
    [connection addRequest:request completionHandler:handler];
    [connection addRequest:request completionHandler:handler];
    [connection addRequest:request completionHandler:handler];
    [connection start];

    [blocker wait];

    if (fbids.count != 3) {
        STAssertTrue(fbids.count == 3, @"wrong number of fbids, aborting test");
        // Things are bad. Continuing isn't going to make them better, and might throw exceptions.
        return;
    }

    blocker = [[FBTestBlocker alloc] initWithExpectedSignalCount:3];

    connection = [[[FBRequestConnection alloc] init] autorelease];
    FBRequest *deleteRequest = [[FBRequest alloc] initWithSession:session
                                                        graphPath:[fbids objectAtIndex:fbids.count-1]
                                                       parameters:nil
                                                       HTTPMethod:@"delete"];
    [connection addRequest:deleteRequest
         completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
             STAssertNotNil(result, @"should have a result here: Handler 2");
             STAssertNil(error, @"should not have an error here: Handler 2");
             STAssertTrue(0 != fbids.count, @"not enough fbids: Handler 2");
             [fbids removeObjectAtIndex:fbids.count-1];
             [blocker signal];
         }];

    deleteRequest = [[FBRequest alloc] initWithSession:session
                                             graphPath:[fbids objectAtIndex:fbids.count-1]
                                            parameters:[NSDictionary dictionaryWithObjectsAndKeys:
                                                        @"delete", @"method",
                                                        nil]
                                            HTTPMethod:nil];
    [connection addRequest:deleteRequest
         completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
             STAssertNotNil(result, @"should have a result here: Handler 3");
             STAssertNil(error, @"should not have an error here: Handler 3");
             STAssertTrue(0 != fbids.count, @"not enough fbids: Handler 3");
             [fbids removeObjectAtIndex:fbids.count-1];
             [blocker signal];
         }];

    [connection addRequest:request completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        STAssertNotNil(result, @"should have a result here: Handler 4");
        STAssertNil(error, @"should not have an error here: Handler 4");
        if (result) {
            [fbids addObject: [[result objectForKey:@"id"] description]];
        }
        [blocker signal];
    }];

    // these deletes two and adds one
    [connection start];

    [blocker wait];
    if (fbids.count != 2) {
        STAssertTrue(fbids.count == 2, @"wrong number of fbids, aborting test");
        // Things are bad. Continuing isn't going to make them better, and might throw exceptions.
        return;
    }

    blocker = [[[FBTestBlocker alloc] initWithExpectedSignalCount:2] autorelease];

    // delete
    request = [[[FBRequest alloc] initWithSession:session
                                        graphPath:[fbids objectAtIndex:fbids.count-1]
                                       parameters:[NSDictionary dictionaryWithObjectsAndKeys:
                                                   @"delete", @"method",
                                                   nil]
                                       HTTPMethod:nil] autorelease];
    [request startWithCompletionHandler:
     ^(FBRequestConnection *connection, id result, NSError *error) {
         STAssertNotNil(result, @"should have a result here: Handler 5");
         STAssertNil(error, @"should not have an error here: Handler 5");
         STAssertTrue(0 != fbids.count, @"not enough fbids: Handler 5");
         [fbids removeObjectAtIndex:fbids.count-1];
         [blocker signal];
     }];
    // delete
    request = [[[FBRequest alloc] initWithSession:session
                                        graphPath:[fbids objectAtIndex:fbids.count-1]
                                       parameters:nil
                                       HTTPMethod:@"delete"] autorelease];
    [request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
        STAssertNotNil(result, @"should have a result here: Handler 6");
        STAssertNil(error, @"should not have an error here: Handler 6");
        STAssertTrue(0 != fbids.count, @"not enough fbids: Handler 6");
        [fbids removeObjectAtIndex:fbids.count-1];
        [blocker signal];
    }];

    [blocker wait];

    STAssertTrue(fbids.count == 0, @"Our fbid collection should be empty here");
}

@end

#endif


text:
package android.support.v4.view;

import android.os.Build;
import android.view.ViewGroup;

/**
 * Helper for accessing API features in
 * {@link android.view.ViewGroup.MarginLayoutParams MarginLayoutParams} added after API 4.
 */
public class MarginLayoutParamsCompat {
    interface MarginLayoutParamsCompatImpl {
        int getMarginStart(ViewGroup.MarginLayoutParams lp);
        int getMarginEnd(ViewGroup.MarginLayoutParams lp);
        void setMarginStart(ViewGroup.MarginLayoutParams lp, int marginStart);
        void setMarginEnd(ViewGroup.MarginLayoutParams lp, int marginEnd);
        boolean isMarginRelative(ViewGroup.MarginLayoutParams lp);
        int getLayoutDirection(ViewGroup.MarginLayoutParams lp);
        void setLayoutDirection(ViewGroup.MarginLayoutParams lp, int layoutDirection);
        void resolveLayoutDirection(ViewGroup.MarginLayoutParams lp, int layoutDirection);
    }

    static class MarginLayoutParamsCompatImplBase implements MarginLayoutParamsCompatImpl {

        @Override
        public int getMarginStart(ViewGroup.MarginLayoutParams lp) {
            return lp.leftMargin;
        }

        @Override
        public int getMarginEnd(ViewGroup.MarginLayoutParams lp) {
            return lp.rightMargin;
        }

        @Override
        public void setMarginStart(ViewGroup.MarginLayoutParams lp, int marginStart) {
            lp.leftMargin = marginStart;
        }

        @Override
        public void setMarginEnd(ViewGroup.MarginLayoutParams lp, int marginEnd) {
            lp.rightMargin = marginEnd;
        }

        @Override
        public boolean isMarginRelative(ViewGroup.MarginLayoutParams lp) {
            return false;
        }

        @Override
        public int getLayoutDirection(ViewGroup.MarginLayoutParams lp) {
            return ViewCompat.LAYOUT_DIRECTION_LTR;
        }

        @Override
        public void setLayoutDirection(ViewGroup.MarginLayoutParams lp, int layoutDirection) {
            // No-op
        }

        @Override
        public void resolveLayoutDirection(ViewGroup.MarginLayoutParams lp, int layoutDirection) {
            // No-op
        }
    }

    static class MarginLayoutParamsCompatImplJbMr1 implements MarginLayoutParamsCompatImpl {

        @Override
        public int getMarginStart(ViewGroup.MarginLayoutParams lp) {
            return MarginLayoutParamsCompatJellybeanMr1.getMarginStart(lp);
        }

        @Override
        public int getMarginEnd(ViewGroup.MarginLayoutParams lp) {
            return MarginLayoutParamsCompatJellybeanMr1.getMarginEnd(lp);
        }

        @Override
        public void setMarginStart(ViewGroup.MarginLayoutParams lp, int marginStart) {
            MarginLayoutParamsCompatJellybeanMr1.setMarginStart(lp, marginStart);
        }

        @Override
        public void setMarginEnd(ViewGroup.MarginLayoutParams lp, int marginEnd) {
            MarginLayoutParamsCompatJellybeanMr1.setMarginEnd(lp, marginEnd);
        }

        @Override
        public boolean isMarginRelative(ViewGroup.MarginLayoutParams lp) {
            return MarginLayoutParamsCompatJellybeanMr1.isMarginRelative(lp);
        }

        @Override
        public int getLayoutDirection(ViewGroup.MarginLayoutParams lp) {
            return MarginLayoutParamsCompatJellybeanMr1.getLayoutDirection(lp);
        }

        @Override
        public void setLayoutDirection(ViewGroup.MarginLayoutParams lp, int layoutDirection) {
            MarginLayoutParamsCompatJellybeanMr1.setLayoutDirection(lp, layoutDirection);
        }

        @Override
        public void resolveLayoutDirection(ViewGroup.MarginLayoutParams lp, int layoutDirection) {
            MarginLayoutParamsCompatJellybeanMr1.resolveLayoutDirection(lp, layoutDirection);
        }
    }

    static final MarginLayoutParamsCompatImpl IMPL;
    static {
        final int version = Build.VERSION.SDK_INT;
        if (version >= 17) { // jb-mr1
            IMPL = new MarginLayoutParamsCompatImplJbMr1();
        } else {
            IMPL = new MarginLayoutParamsCompatImplBase();
        }
    }

    /**
     * Get the relative starting margin that was set.
     *
     *
On platform versions supporting bidirectional text and layouts
     * this value will be resolved into the LayoutParams object's left or right
     * margin as appropriate when the associated View is attached to a window
     * or when the layout direction of that view changes.

     *
     * @param lp LayoutParams to query
     * @return the margin along the starting edge in pixels
     */
    public static int getMarginStart(ViewGroup.MarginLayoutParams lp) {
        return IMPL.getMarginStart(lp);
    }

    /**
     * Get the relative ending margin that was set.
     *
     *
On platform versions supporting bidirectional text and layouts
     * this value will be resolved into the LayoutParams object's left or right
     * margin as appropriate when the associated View is attached to a window
     * or when the layout direction of that view changes.

     *
     * @param lp LayoutParams to query
     * @return the margin along the ending edge in pixels
     */
    public static int getMarginEnd(ViewGroup.MarginLayoutParams lp) {
        return IMPL.getMarginEnd(lp);
    }

    /**
     * Set the relative start margin.
     *
     *
On platform versions supporting bidirectional text and layouts
     * this value will be resolved into the LayoutParams object's left or right
     * margin as appropriate when the associated View is attached to a window
     * or when the layout direction of that view changes.

     *
     * @param lp LayoutParams to query
     * @param marginStart the desired start margin in pixels
     */
    public static void setMarginStart(ViewGroup.MarginLayoutParams lp, int marginStart) {
        IMPL.setMarginStart(lp, marginStart);
    }

    /**
     * Set the relative end margin.
     *
     *
On platform versions supporting bidirectional text and layouts
     * this value will be resolved into the LayoutParams object's left or right
     * margin as appropriate when the associated View is attached to a window
     * or when the layout direction of that view changes.

     *
     * @param lp LayoutParams to query
     * @param marginEnd the desired end margin in pixels
     */
    public static void setMarginEnd(ViewGroup.MarginLayoutParams lp, int marginEnd) {
        IMPL.setMarginEnd(lp, marginEnd);
    }

    /**
     * Check if margins are relative.
     *
     * @return true if either marginStart or marginEnd has been set.
     */
    public static boolean isMarginRelative(ViewGroup.MarginLayoutParams lp) {
        return IMPL.isMarginRelative(lp);
    }

    /**
     * Retuns the layout direction. Can be either {@link ViewCompat#LAYOUT_DIRECTION_LTR} or
     * {@link ViewCompat#LAYOUT_DIRECTION_RTL}.
     *
     * @return the layout direction.
     */
    public static int getLayoutDirection(ViewGroup.MarginLayoutParams lp) {
        return IMPL.getLayoutDirection(lp);
    }

    /**
     * Set the layout direction.
     *
     * @param layoutDirection the layout direction.
     *        Should be either {@link ViewCompat#LAYOUT_DIRECTION_LTR}
     *                     or {@link ViewCompat#LAYOUT_DIRECTION_RTL}.
     */
    public static void setLayoutDirection(ViewGroup.MarginLayoutParams lp, int layoutDirection) {
        IMPL.setLayoutDirection(lp, layoutDirection);
    }

    /**
     * This will be called by {@link android.view.View#requestLayout()}. Left and Right margins
     * may be overridden depending on layout direction.
     */
    public static void resolveLayoutDirection(ViewGroup.MarginLayoutParams lp,
            int layoutDirection) {
        IMPL.resolveLayoutDirection(lp, layoutDirection);
    }
}


text:
@(title: String,  court: Court, reviews: List[Review], reviewForm: Form[forms.CourtReviewForm], isLoggedIn: Boolean)

@import helper._
@import utils.Tags._

@Main(title, isLoggedIn) {

@court.getName

            @form(routes.Courts.postReview(court.getId, slugify(court.getName)), 'class -> "form-horizontal") {

                @bootstrap3.textarea(reviewForm("review"),
                    rows = "12",
                    label = "Review",
                    placeholder = "Your review for the court",
                    help = "")

                        <button id="submitButton" type="submit" class="btn btn-primary pull-right">
                            Submit
                        </button>

            }

        @if(reviews.isEmpty) {

No Reviews

        }else {

Recent Reviews

            @for(review <- reviews) {

                                @review.getAuthor.getName

                        @review.getTimestamp.getMonthOfYear/@review.getTimestamp.getDayOfWeek/@review.getTimestamp.getYear

                    @review.getReview

            }
        }

}


text:
(function () {
  'use strict';

  angular.module('ngMicrosoftGraph').controller('ngMicrosoftGraph.contactsController',
      ['$http', contactsController]);

  function contactsController($http) {
    var vm = this;

    // collection of contacts
    vm.contacts = {};

    // activate the controller
    getContacts();

function getContacts() {
  $http({
    method:'GET',
    url: 'https://graph.microsoft.com/v1.0/me/contacts',
    headers: {
      'ACCEPT': 'application/json'
    }
  }).success(function (response){
    vm.contacts = response.value;
  });
}
  }

})();


text:
package com.tom.transport.tileentity;

import net.minecraft.block.state.IBlockState;
import net.minecraft.nbt.NBTTagCompound;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.util.EnumFacing;

import net.minecraftforge.items.IItemHandler;

import com.tom.transport.block.ConveyorBeltOmniBase;
import com.tom.util.TomsModUtils;

public abstract class TileEntityConveyorOmniBase extends TileEntityConveyorBase {
	public EnumFacing facing = EnumFacing.DOWN;

	@Override
	public int[] getSlotsForFace(EnumFacing side) {
		return facing == side ? FRONT : facing.getOpposite() == side ? SLOT : SIDE;
	}

	@Override
	public boolean pushItemOut(IBlockState currentState) {
		boolean sync = false;
		IItemHandler h = TomsModUtils.getItemHandler(world, pos.offset(facing), facing.getOpposite(), true);
		if (h != null) {
			inv.setInventorySlotContents(0, TomsModUtils.putStackInInventoryAllSlots(h, inv.getStackInSlot(0)));
			if (inv.getStackInSlot(0).isEmpty()) {
				sync = true;
				itemPos = 0;
			}
		} else {
			TileEntity t = world.getTileEntity(pos.offset(facing).down());
			if (t instanceof IConveyorSlope) {
				IConveyorSlope c = (IConveyorSlope) t;
				if (c.isValid()) {
					inv.setInventorySlotContents(0, c.insert(inv.getStackInSlot(0), facing.getOpposite()));
					if (inv.getStackInSlot(0).isEmpty()) {
						sync = true;
						itemPos = 0;
					}
				}
			}
		}
		return sync;
	}

	@Override
	public NBTTagCompound writeToNBT(NBTTagCompound compound) {
		compound.setInteger("facing", facing.ordinal());
		return super.writeToNBT(compound);
	}

	@Override
	public void readFromNBT(NBTTagCompound compound) {
		super.readFromNBT(compound);
		facing = EnumFacing.getFront(compound.getInteger("facing"));
	}

	@Override
	public void writeToPacket(NBTTagCompound tag) {
		super.writeToPacket(tag);
		tag.setInteger("f", facing.ordinal());
	}

	@Override
	public void readFromPacket(NBTTagCompound tag) {
		super.readFromPacket(tag);
		facing = EnumFacing.getFront(tag.getInteger("f"));
	}

	@Override
	public EnumFacing getFacing() {
		return world.getBlockState(pos).getValue(ConveyorBeltOmniBase.POSITION);
	}
}


text:
<?php

namespace PagueVeloz\Api\v1;

use TestCase;
use PagueVeloz\PagueVeloz;
use PagueVeloz\Api\v1\Dto\ExtratoDTOTest;

class ExtratoTest extends TestCase
{
    protected $extrato;

    public function setUp()
    {
        parent::setUp();
        $this->extrato = PagueVeloz::Extrato('v2');
    }

    public function testGet()
    {
        $this->extrato->auth = $this->auth();

        $response = $this->extrato->Get();

        $this->assertInstanceOf('PagueVeloz\Service\Context\HttpResponse', $response);
        $this->assertEquals(200, $response->status);
        $this->assertJson($response->body);
        $response = json_decode($response->body, true);
        $this->assertGreaterThan(0, count($response));
    }

    public function testGetByPeriodo()
    {
        $this->extrato->auth = $this->auth();

        $interval = new \DateInterval('P1D');
        $today = new \DateTime;
        $yesterday = clone $today;
        $yesterday->sub($interval);

        $response = $this->extrato->GetByPeriodo($yesterday->format('Y-m-d'), $today->format('Y-m-d'));

        $this->assertInstanceOf('PagueVeloz\Service\Context\HttpResponse', $response);
        $this->assertEquals(200, $response->status);
        $this->assertJson($response->body);
        $response = json_decode($response->body, true);
        $this->assertGreaterThan(0, count($response));
    }

    /**
     * @expectedException PagueVeloz\Exception\NotImplementedException
     */
    public function testPost()
    {
        $this->extrato->Post(1);
    }

    /**
     * @expectedException PagueVeloz\Exception\NotImplementedException
     */
    public function testPut()
    {
        $this->extrato->Put(1);
    }

    /**
     * @expectedException PagueVeloz\Exception\NotImplementedException
     */
    public function testDelete()
    {
        $this->extrato->Delete(1);
    }
}


text:
#include "yggdrasil_decision_forests/learner/gradient_boosted_trees/loss/loss_library.h"

#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "yggdrasil_decision_forests/model/abstract_model.pb.h"
#include "yggdrasil_decision_forests/model/gradient_boosted_trees/gradient_boosted_trees.pb.h"
#include "yggdrasil_decision_forests/utils/test.h"

namespace yggdrasil_decision_forests {
namespace model {
namespace gradient_boosted_trees {
namespace {

TEST(LossLibrary, CanonicalLosses) {
  proto::GradientBoostedTreesTrainingConfig config;
  dataset::proto::Column binary_categorical_label_column =
      PARSE_TEST_PROTO(R"pb(
        type: CATEGORICAL
        categorical { number_of_unique_values: 3 is_already_integerized: true }
      )pb");

  dataset::proto::Column numerical_label_column = PARSE_TEST_PROTO(R"pb(
    type: NUMERICAL
  )pb");
  dataset::proto::Column multiclass_categorical_label_column =
      PARSE_TEST_PROTO(R"pb(
        type: CATEGORICAL
        categorical { number_of_unique_values: 20 is_already_integerized: true }
      )pb");

  EXPECT_OK(CreateLoss(proto::Loss::BINOMIAL_LOG_LIKELIHOOD,
                       model::proto::Task::CLASSIFICATION,
                       binary_categorical_label_column, config));

  EXPECT_OK(CreateLoss(proto::Loss::SQUARED_ERROR,
                       model::proto::Task::REGRESSION, numerical_label_column,
                       config));

  EXPECT_OK(CreateLoss(proto::Loss::MULTINOMIAL_LOG_LIKELIHOOD,
                       model::proto::Task::CLASSIFICATION,
                       multiclass_categorical_label_column, config));

  EXPECT_OK(CreateLoss(proto::Loss::LAMBDA_MART_NDCG5,
                       model::proto::Task::RANKING, numerical_label_column,
                       config));

  EXPECT_OK(CreateLoss(proto::Loss::XE_NDCG_MART, model::proto::Task::RANKING,
                       numerical_label_column, config));

  EXPECT_OK(CreateLoss(proto::Loss::BINARY_FOCAL_LOSS,
                       model::proto::Task::CLASSIFICATION,
                       binary_categorical_label_column, config));
}

}  // namespace
}  // namespace gradient_boosted_trees
}  // namespace model
}  // namespace yggdrasil_decision_forests