text:
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.CommandLineArgs = void 0;
const MeasurementType_1 = require("../runner/config/MeasurementType");
const ExecutionType_1 = require("../runner/config/ExecutionType");
const Converter_1 = require("../utilities/Converter");
class CommandLineArgs {
    constructor(args) {
        this.modules = [];
        this.classes = [];
        this.benchmarks = [];
        this.parameters = {};
        this.reportFile = "BenchmarkReport.txt";
        this.duration = 60;
        this.showHelp = false;
        this.showBenchmarks = false;
        this.showParameters = false;
        this.showReport = false;
        this.measureEnvironment = false;
        this.measurementType = MeasurementType_1.MeasurementType.Peak;
        this.executionType = ExecutionType_1.ExecutionType.Proportional;
        this.nominalRate = 1;
        this.processArguments(args);
    }
    processArguments(args) {
        for (let index = 2; index < args.length; index++) {
            let arg = args[index];
            let moreArgs = index < args.length - 1;
            if ((arg == "-a" || arg == "-j" || arg == "--module") && moreArgs) {
                let module = args[++index];
                this.modules.push(module);
            }
            else if ((arg == "-l" || arg == "--class") && moreArgs) {
                let clazz = args[++index];
                this.classes.push(clazz);
            }
            else if ((arg == "-b" || arg == "--benchmark") && moreArgs) {
                let benchmark = args[++index];
                this.benchmarks.push(benchmark);
            }
            else if ((arg == "-p" || arg == "--param") && moreArgs) {
                let param = args[++index];
                let pos = param.indexOf('=');
                let key = pos > 0 ? param.substring(0, pos - 1) : param;
                let value = pos > 0 ? param.substring(pos + 1) : null;
                this.parameters.put(key, value);
            }
            else if ((arg == "-c" || arg == "--config") && moreArgs) {
                this.configurationFile = args[++index];
            }
            else if ((arg == "-r" || arg == "--report") && moreArgs) {
                this.reportFile = args[++index];
            }
            else if ((arg == "-d" || arg == "--duration") && moreArgs) {
                this.duration = Converter_1.Converter.stringToLong(args[++index], 60);
            }
            else if ((arg == "-m" || arg == "--measure") && moreArgs) {
                let measure = args[++index].toLowerCase();
                this.measurementType = measure.startsWith("nom")
                    ? MeasurementType_1.MeasurementType.Nominal : MeasurementType_1.MeasurementType.Peak;
            }
            else if ((arg == "-x" || arg == "--execute") && moreArgs) {
                let execution = args[++index].toLowerCase();
                this.executionType = execution.startsWith("seq")
                    ? ExecutionType_1.ExecutionType.Sequential : ExecutionType_1.ExecutionType.Proportional;
            }
            else if ((arg == "-n" || arg == "--nominal") && moreArgs) {
                this.nominalRate = Converter_1.Converter.stringToDouble(args[++index], 1);
            }
            else if (arg == "-h" || arg == "--help") {
                this.showHelp = true;
            }
            else if (arg == "-B" || arg == "--show-benchmarks") {
                this.showBenchmarks = true;
            }
            else if (arg == "-P" || arg == "--show-params") {
                this.showParameters = true;
            }
            else if (arg == "-R" || arg == "--show-report") {
                this.showReport = true;
            }
            else if (arg == "-e" || arg == "--environment") {
                this.measureEnvironment = true;
            }
        }
    }
}
exports.CommandLineArgs = CommandLineArgs;
//# sourceMappingURL=CommandLineArgs.js.map


text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package circleland.Monsters;

import circleland.CircleAttack;
import circleland.CircleEntity;
import circleland.CircleLandUtility;
import circleland.CircleMap;
import circleland.CircleMonster;
import circleland.Weapons.BombWeapon;
import circleland.Weapons.BulletWeapon;
import java.awt.Color;
import java.util.Random;

/**
 *
 * @author Jeff
 */
public class FlyMonster extends CircleMonster{
    public static final int BASE_MAXHEALTH= 10;
    public static final int BASE_HEALTHREGEN= 1;
    public static final int BASE_MAXMANA= 10;
    public static final int BASE_MANAREGEN= 10;
    public static final int BASE_ATTACK_DAMAGE= 1;
    public static final int BASE_MAGIC_DAMAGE= 1;
    public static final int BASE_ATTACK_DEFENSE= 2;
    public static final int BASE_MAGIC_DEFENSE= 1;
    public static final int BASE_PRECISION = 1;
    public static final int BASE_ATTACKSPEED= 1000;
    public static final int BASE_CASTSPEED= 1000;
    public static final int BASE_MOVESPEED= 80;

    private static Random rand = new Random();
    private int viewRadius;
    private int moveChangeTimer;
    public FlyMonster()
    {
        super();
        name = "Fly";
        size = 10;
        headRadius = 2;
        headSize = 2;
        color = Color.GRAY;
        viewRadius = 100;
        position.x = 0;
        position.y = 0;

        //initialize stats
        moveChangeTimer = 0;
        team = CircleLandUtility.MONSTER_SIDE;
        level = 5;
        maxHealth = 50;
        health = 50;
        baseAttackSpeed = 1000;
        castSpeed = 100;
        moveSpeed = 100;
        gold = 5;
        equippedWeapon = new BulletWeapon();
    }
    public FlyMonster(int x, int y)
    {
        super();
        name = "Fly";
        size = 10;
        headRadius = 2;
        headSize = 2;
        color = Color.GRAY;
        viewRadius = 100;
        position.x = x;
        position.y = y;

        //initialize stats
        moveChangeTimer = 0;
        team = CircleLandUtility.MONSTER_SIDE;
        level = 5;
        maxHealth = 50;
        health = 50;
        baseAttackSpeed = 1000;
        castSpeed = 100;
        moveSpeed = 100;
        gold = 5;
        equippedWeapon = new BulletWeapon();
    }
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE html>
<html ng-app="app">
  <head>
    <meta charset="utf-8">
    <title>MycroLens</title>
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta http-equiv="x-ua-compatible" content="ie=edge">
    <link rel="shortcut icon" href="./images/logo5.jpg">
    <link rel="manifest" href="./manifest.json">
    <meta name="mobile-web-app-capable" content="yes">
    <meta name=application-name content="MicroLens">
    <meta name=apple-mobile-web-app-capable content=yes>
    <meta name=apple-mobile-web-app-status-bar-style content=black>
    <meta name=apple-mobile-web-app-title content="MicroLens">
    <link rel=apple-touch-icon href=./images/logo.png>
    <meta name=msapplication-TileImage content=./images/logo.png>
    <meta name=msapplication-TileColor content=#536878>
    <meta name=theme-color content=#536878>
    <title>MicroLens</title>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <link rel=stylesheet type="text/css" href="/css/main.css">
    <link rel="stylesheet" type="text/css" href="/css/business-frontpage.css">
    <link href="https://fonts.googleapis.com/css?family=Righteous" rel="stylesheet">
    <base href="/">
    <script src="http://d3js.org/d3.v3.min.js"></script>

  </head>
  <body>
    <main class="row">
      <section class="col-lg-12 center-block">
        <ui-view></ui-view>
      </section>
    </main>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.4/angular.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.0-beta.3/angular-ui-router.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.17.1/moment.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-moment/1.0.1/angular-moment.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://cdn.jsdelivr.net/satellizer/0.15.5/satellizer.min.js"></script>
    <script src="https://d3js.org/d3.v4.min.js"></script>

    <script type="text/javascript">
      window.onload=function(){
       $(function(){
           if(window.location.protocol==="https:")
               window.location.protocol="http";
        });
      }
    </script>

    <script src="/app.module.js"></script>
    <script src="/app.config.js"></script>

    <script src="/components/dashboard/dashboard.module.js"></script>
    <script src="/components/dashboard/dashboard.component.js"></script>
    <script src="/components/dashboard/dashboard.controller.js"></script>
    <script src="/components/dashboard/dashboard.service.js"></script>

    <script src="/components/dashboard/d3/dashboard.d3.bar.component.js"></script>
    <script src="/components/dashboard/d3/dashboard.d3.bar.controller.js"></script>
    <script src="/components/dashboard/d3/dashboard.d3.pie.component.js"></script>
    <script src="/components/dashboard/d3/dashboard.d3.pie.controller.js"></script>

    <script src="/components/about/about.module.js"></script>
    <script src="/components/about/about.component.js"></script>
    <script src="/components/about/about.controller.js"></script>

    <script src="/components/dashboard/addFood/dashboard.addFood.module.js"></script>
    <script src="/components/dashboard/addFood/dashboard.addFood.component.js"></script>
    <script src="/components/dashboard/addFood/dashboard.addFood.controller.js"></script>
    <script src="/components/dashboard/addFood/dashboard.addFood.service.js"></script>
  </body>
</html>


text:
@class NSDate, NSString;

@interface KSCrashReportInfo : NSObject
{
    NSString *_reportID;
    NSDate *_creationDate;
}

+ (id)reportInfoWithID:(id)arg1 creationDate:(id)arg2;
@property(readonly, retain, nonatomic) NSDate *creationDate; // @synthesize creationDate=_creationDate;
@property(readonly, retain, nonatomic) NSString *reportID; // @synthesize reportID=_reportID;
- (void).cxx_destruct;
- (long long)compare:(id)arg1;
- (id)initWithID:(id)arg1 creationDate:(id)arg2;

@end


text:
/**
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * @author Andreas Joelsson (andreas.joelsson@gmail.com)
 */
package io.github.scrier.opus.duke.commander;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

import io.github.scrier.opus.common.Constants;
import io.github.scrier.opus.common.data.BaseDataC;
import io.github.scrier.opus.common.message.BaseMsgC;
import io.github.scrier.opus.common.nuke.CommandState;
import io.github.scrier.opus.common.nuke.NukeExecuteIndMsgC;
import io.github.scrier.opus.common.nuke.NukeExecuteReqMsgC;
import io.github.scrier.opus.common.nuke.NukeExecuteRspMsgC;
import io.github.scrier.opus.common.nuke.NukeMsgFactory;

public class CommandProcedure extends BaseDukeProcedure {

	private static Logger log = LogManager.getLogger(CommandProcedure.class);

	public final int INITIALIZING = CREATED + 1;
	public final int WORKING =      CREATED + 2;
	public final int REMOVING =     CREATED + 3;

	private long destination;
	private String command;
	private boolean repeated;
	private String folder;
	private ICommandCallback callback;
	private CommandState currentState;
	private long processID;
	private long sagaID;

	/**
	 * Constructor
	 * @param destination long with the id of the nuke to call.
	 * @param command String with the command to execute.
	 */
	public CommandProcedure(long destination, String command) {
		this(destination, command, false, null);
	}

	/**
	 * Constructor
	 * @param destination long with the id of the nuke to call.
	 * @param command String with the command to execute.
	 * @param callback interface to callback the result of the handling.
	 */
	public CommandProcedure(long destination, String command, ICommandCallback callback) {
		this(destination, command, false, callback);
	}

	/**
	 * Constructor
	 * @param destination long with the id of the nuke to call.
	 * @param command String with the command to execute.
	 * @param repeated boolean if the command should be repeated or not.
	 */
	public CommandProcedure(long destination, String command, boolean repeated) {
		this(destination, command, repeated, null);
	}

	/**
	 * Constructor
	 * @param destination long with the id of the nuke to call.
	 * @param command String with the command to execute.
	 * @param repeated boolean if the command should be repeated or not.
	 * @param callback interface to callback the result of the handling.
	 */
	public CommandProcedure(long destination, String command, boolean repeated, ICommandCallback callback) {
		this(destination, command, "", repeated, callback);
	}

	/**
	 * Constructor
	 * @param destination long with the id of the nuke to call.
	 * @param command String with the command to execute.
	 * @param folder String with the folder to execute the command from.
	 * @param repeated boolean if the command should be repeated or not.
	 */
	public CommandProcedure(long destination, String command, String folder, boolean repeated) {
		this(destination, command, folder, repeated, null);
	}

	/**
	 * Constructor
	 * @param destination long with the id of the nuke to call.
	 * @param command String with the command to execute.
	 * @param folder String with the folder to execute the command from.
	 * @param repeated boolean if the command should be repeated or not.
	 * @param callback interface to callback the result of the handling.
	 */
	public CommandProcedure(long destination, String command, String folder, boolean repeated, ICommandCallback callback) {
		log.trace("CommandProcedure(" + destination + ", \"" + command + "\", \"" + folder + "\", " + repeated + ", " + callback + ")");
		setDestination(destination);
		setCommand(command);
		setFolder(folder);
		setRepeated(repeated);
		setCallback(callback);
		setProcessID(Constants.HC_UNDEFINED);
		setCurrentState(CommandState.UNDEFINED);
		setSagaID(getNextSagaID());
	}

	@Override
	public void init() throws Exception {
		log.trace("init()");
		NukeExecuteReqMsgC pNukeExecuteReq = new NukeExecuteReqMsgC(getSendIF());
		pNukeExecuteReq.setTxID(getTxID());
		pNukeExecuteReq.setSource(getIdentity());
		pNukeExecuteReq.setDestination(getDestination());
		pNukeExecuteReq.setCommand(getCommand());
		pNukeExecuteReq.setFolder(getFolder());
		pNukeExecuteReq.setRepeated(isRepeated());
		pNukeExecuteReq.send();
		setState(INITIALIZING);
	}

	@Override
	public void shutDown() throws Exception {
		log.trace("shutDown()");
		if( null != getCallback() ) {
			getCallback().finished(getDestination(), getProcessID(),
					getState(), getCommand(), "");
		}
	}

	@Override
	public int handleOnUpdated(BaseDataC data) {
		log.trace("handleOnUpdated(" + data + ")");
		return getState();
	}

	@Override
	public int handleOnEvicted(BaseDataC data) {
		log.trace("handleOnEvicted(" + data + ")");
		return getState();
	}

	@Override
	public int handleOnRemoved(Long key) {
		log.trace("handleOnRemoved(" + key + ")");
		return getState();
	}

	/**
	 * @return the callback
	 */
  public ICommandCallback getCallback() {
	  return callback;
  }

	/**
	 * @param callback the callback to set
	 */
  public void setCallback(ICommandCallback callback) {
	  this.callback = callback;
  }

  /**
   * {@inheritDoc}
   */
  @Override
  public String toString() {
  	String retValue = "CommandProcedure{destination:" + getDestination();
  	retValue += ", command:" + getCommand();
  	retValue += ", repeated:" + isRepeated();
  	retValue += ", folder:" + getFolder();
  	retValue += ", callback:" + getCallback();
  	retValue += ", currentState:" + getCurrentState();
  	retValue += ", processID: " + getProcessID() + "}";
  	return retValue;
  }

  /**
   * {@inheritDoc}
   */
	@Override
  public int handleInMessage(BaseMsgC message) {
		log.trace("handleInMessage(" + message + ")");
	  switch( message.getId() ) {
	  	case NukeMsgFactory.NUKE_EXECUTE_RSP: {
	  		log.debug("[" + getTxID() + "] Received NUKE_EXECUTE_RSP message.");
	  		NukeExecuteRspMsgC pNukeExecuteRsp = new NukeExecuteRspMsgC(message);
	  		handleMessage(pNukeExecuteRsp);
	  		break;
	  	}
	  	case NukeMsgFactory.NUKE_EXECUTE_IND: {
	  		log.debug("[" + getTxID() + "] Received NUKE_EXECUTE_IND message.");
	  		NukeExecuteIndMsgC pNukeExecuteInd = new NukeExecuteIndMsgC(message);
	  		handleMessage(pNukeExecuteInd);
	  		break;
	  	}
	  }
	  return getState();
  }

	/**
	 * @return the destination
	 */
  public long getDestination() {
	  return destination;
  }

	/**
	 * @param destination the destination to set
	 */
  public void setDestination(long destination) {
	  this.destination = destination;
  }

	/**
	 * @return the command
	 */
  public String getCommand() {
	  return command;
  }

	/**
	 * @param command the command to set
	 */
  public void setCommand(String command) {
	  this.command = command;
  }

	/**
	 * @return the repeated
	 */
  public boolean isRepeated() {
	  return repeated;
  }

	/**
	 * @param repeated the repeated to set
	 */
  public void setRepeated(boolean repeated) {
	  this.repeated = repeated;
  }

	/**
	 * @return the folder
	 */
  public String getFolder() {
	  return folder;
  }

	/**
	 * @param folder the folder to set
	 */
  public void setFolder(String folder) {
	  this.folder = folder;
  }

	/**
	 * @return the currentState
	 */
  public CommandState getCurrentState() {
	  return currentState;
  }

	/**
	 * @param currentState the currentState to set
	 */
  public void setCurrentState(CommandState currentState) {
	  this.currentState = currentState;
  }

	/**
	 * @return the processID
	 */
  public long getProcessID() {
	  return processID;
  }

	/**
	 * @param processID the processID to set
	 */
  public void setProcessID(long processID) {
	  this.processID = processID;
  }

	/**
	 * @return the sagaID
	 */
  public long getSagaID() {
	  return sagaID;
  }

	/**
	 * @param sagaID the sagaID to set
	 */
  public void setSagaID(long sagaID) {
	  this.sagaID = sagaID;
  }

  /**
   * Method to handle the NukeExecuteRspMsgC message.
   * @param message NukeExecuteRspMsgC instance
   */
  protected void handleMessage(NukeExecuteRspMsgC message) {
  	log.trace(" handleMessage(" + message + ")");
  	if( getTxID() != message.getTxID() ) {
  		log.debug("[" + getTxID() + "] Wrong txid. expected: " + getTxID() + ", but was: " + message.getTxID() + ".");
  	} else {
  		if( INITIALIZING != getState() ) {
  			log.error("[" + getTxID() + "] Received NukeExecuteRspMsgC in wrong state: " + getState() + ", expected: " + INITIALIZING + ".");
  			setState(ABORTED);
  		} else {
	  		log.debug("[" + getTxID() + "] Received: " + message + ", updating processID to: " + message.getProcessID() + ".");
	  		setProcessID(message.getProcessID());
	  		setState(WORKING);
  		}
  	}
  }

  /**
   * Method to handle the NukeExecuteIndMsgC message.
   * @param message NukeExecuteIndMsgC instance
   */
  protected void handleMessage(NukeExecuteIndMsgC message) {
  	log.trace(" handleMessage(" + message + ")");
  	if( getDestination() == message.getSource() ) {
  		if( getProcessID() != message.getProcessID() ) {
  			log.debug("[" + getTxID() + "] Message not for us, expected: " + getProcessID() + ", received: " + message.getProcessID() + ".");
  		} else {
  			log.debug("[" + getTxID() + "] Received: " + message);
  			if( WORKING != getState() ) {
  				log.error("[" + getTxID() + "] Received NukeExecuteIndMsgC when not in state WORKING.");
  				setState(ABORTED);
  			} else {
  				log.debug("[" + getTxID() + "] Changed status to: " + message.getStatus() + ".");
  				switch( message.getStatus() ) {
  					case ABORTED: {
  						log.error("[" + getTxID() + "] Task reports aborted state.");
  						setState(ABORTED);
  						break;
  					}
  					case DONE: {
  						log.debug("[" + getTxID() + "] Task reports done state.");
  						setState(COMPLETED);
  						break;
  					}
  					default: {
  						// do nothing.
  					}
  				}
  				setCurrentState(message.getStatus());
  			}
  		}
  	}
  }

}


text:
import Ember from 'ember';

const { Route, A } = Ember;

export default Route.extend({
  model() {
    // BEGIN-SNIPPET table-route
    let content = new A([
      { id: 'white',   name: 'Walter White',   route: 'tabs' },
      { id: 'pinkman', name: 'Jesse Pinkman',  route: 'modal' },
      { id: 'freng',   name: 'Gustavo Freng',  route: 'collection' }
    ]);
    // END-SNIPPET

    return content;
  }
});


text:
/*!
{
  "name": "DataView",
  "property": "dataview",
  "authors": ["Addy Osmani"],
  "builderAliases": ["dataview_api"],
  "notes": [{
    "name": "MDN documentation",
    "href": "https://developer.mozilla.org/en/JavaScript_typed_arrays/DataView"
  }],
  "polyfills": ["jdataview"]
}
!*/
/* DOC
Detects support for the DataView interface for reading data from an ArrayBuffer as part of the Typed Array spec.
*/
define(['Modernizr'], function( Modernizr ) {
  Modernizr.addTest('dataview', (typeof DataView !== 'undefined' && 'getFloat64' in DataView.prototype));
});


text:
package tools.sep;

import java.util.*;
import java.lang.reflect.*;
import org.junit.Test;

public class SingleExecutionPreparer {
	private static void usage(){
		System.err.println("Usage: java SingleExecutionPreparer [-Dparam] <ExampleTest>");
		System.exit(0);
	}

	public static Method[] getMethodsSorted(final Class cls) {
		final Method[] methods = cls.getMethods();
		Arrays.sort(methods, new Comparator<Method>() {
			@Override
			public int compare(final Method method1, final Method method2) {
				return method1.getName().compareTo(method2.getName());
			}
		});
		return methods;
	}

	private static void writeOutSingleTestExecution(String cp, String dparam, String className){
		try{
			ClassLoader cl = ClassLoader.getSystemClassLoader();
			Class tc = cl.loadClass(className);
			int counter = 0;
			for(Method method : getMethodsSorted(tc)) {
				if(method.isAnnotationPresent(Test.class)){
					if(counter > 0){
						System.out.println("echo \",\" 1>&2");
					}
					String methodName = method.getName();
					System.out.println("java -XX:-OmitStackTraceInFastThrow -Xmx1024m -cp "+cp + dparam + " tools.SingleMethodRunner " + className + " " + methodName);
					counter++;
				}

			}
		} catch(ClassNotFoundException cnfe) {
			throw new Error("WARNING - test class not found: " + className);
		}
	}

	public static void main(String args[]){
		String className = null;
		String dparam = null;
		String cp = null;
		if(args == null || args.length < 2 || args.length > 3) {
			usage();
		}

		if(args.length == 2) {
			cp = args[0];
			className = args[1];
			dparam = " ";
		} else if (args.length == 3){
			cp = args[0];
			dparam  = " " + args[1] + " ";
			className = args[2];
		}

		writeOutSingleTestExecution(cp, dparam, className);
	}

}


text:
#include "ClientSocket.h"
#include "Reporting.h"
#include "SocketUtils.h"
#include "WdtOptions.h"
#include <glog/logging.h>
#include <sys/socket.h>
#include <poll.h>
#include <fcntl.h>

namespace facebook {
namespace wdt {

using std::string;

ClientSocket::ClientSocket(const string &dest, const string &port,
                           IAbortChecker const *abortChecker)
    : dest_(dest), port_(port), fd_(-1), abortChecker_(abortChecker) {
  memset(&sa_, 0, sizeof(sa_));
  const auto &options = WdtOptions::get();
  if (options.ipv6) {
    sa_.ai_family = AF_INET6;
  }
  if (options.ipv4) {
    sa_.ai_family = AF_INET;
  }
  sa_.ai_socktype = SOCK_STREAM;
}

ErrorCode ClientSocket::connect() {
  WDT_CHECK(fd_ < 0) << "Previous connection not closed " << fd_ << " "
                     << port_;
  // Lookup
  struct addrinfo *infoList = nullptr;
  auto guard = folly::makeGuard([&] {
    if (infoList) {
      freeaddrinfo(infoList);
    }
  });
  int res = getaddrinfo(dest_.c_str(), port_.c_str(), &sa_, &infoList);
  if (res) {
    // not errno, can't use PLOG (perror)
    LOG(ERROR) << "Failed getaddrinfo " << dest_ << " , " << port_ << " : "
               << res << " : " << gai_strerror(res);
    return CONN_ERROR;
  }
  int count = 0;
  for (struct addrinfo *info = infoList; info != nullptr;
       info = info->ai_next) {
    ++count;
    std::string host, port;
    SocketUtils::getNameInfo(info->ai_addr, info->ai_addrlen, host, port);
    VLOG(2) << "will connect to " << host << " " << port;
    fd_ = socket(info->ai_family, info->ai_socktype, info->ai_protocol);
    if (fd_ == -1) {
      PLOG(WARNING) << "Error making socket for port " << port_;
      continue;
    }
    VLOG(1) << "new socket " << fd_ << " for port " << port_;

    // make the socket non blocking
    int sockArg = fcntl(fd_, F_GETFL, nullptr);
    sockArg |= O_NONBLOCK;
    int retValue = fcntl(fd_, F_SETFL, sockArg);
    if (retValue == -1) {
      PLOG(ERROR) << "Could not make the socket non-blocking " << port_;
      this->close();
      continue;
    }

    if (::connect(fd_, info->ai_addr, info->ai_addrlen) != 0) {
      if (errno != EINPROGRESS) {
        PLOG(INFO) << "Error connecting on " << host << " " << port;
        this->close();
        continue;
      }
      auto startTime = Clock::now();
      int connectTimeout = WdtOptions::get().connect_timeout_millis;

      while (true) {
        // check for abort
        if (abortChecker_->shouldAbort()) {
          LOG(ERROR) << "Transfer aborted during connect " << port_ << " "
                     << fd_;
          this->close();
          return ABORT;
        }
        // we need this loop because poll() can return before any file handles
        // have changes or before timing out. In that case, we check whether it
        // is because of EINTR or not. If true, we have to try poll with
        // reduced timeout. Also we set the poll timeout to be at max equal to
        // abort check interval. This allows us to check for abort regularly.
        int timeElapsed = durationMillis(Clock::now() - startTime);
        if (timeElapsed >= connectTimeout) {
          VLOG(1) << "connect() timed out" << host << " " << port;
          this->close();
          return CONN_ERROR_RETRYABLE;
        }
        int pollTimeout =
            std::min(connectTimeout - timeElapsed,
                     WdtOptions::get().abort_check_interval_millis);
        struct pollfd pollFds[] = {{fd_, POLLOUT, 0}};

        int retValue;
        if ((retValue = poll(pollFds, 1, pollTimeout)) <= 0) {
          if (errno == EINTR) {
            VLOG(1) << "poll() call interrupted. retrying... " << port_;
            continue;
          }
          if (retValue == 0) {
            VLOG(1) << "poll() timed out " << host << " " << port;
            continue;
          }
          PLOG(ERROR) << "poll() failed " << host << " " << port << " " << fd_;
          this->close();
          return CONN_ERROR;
        }
        break;
      }

      // have to check whether the connection attempt succeeded
      int connectResult;
      socklen_t len = sizeof(connectResult);
      if (getsockopt(fd_, SOL_SOCKET, SO_ERROR, &connectResult, &len) < 0) {
        PLOG(WARNING) << "getsockopt() failed";
        this->close();
        continue;
      }
      if (connectResult != 0) {
        LOG(WARNING) << "connect did not succeed on " << host << " " << port
                     << " : " << strerrorStr(connectResult);
        this->close();
        continue;
      }
    }

    // Set to blocking mode again
    sockArg = fcntl(fd_, F_GETFL, nullptr);
    sockArg &= (~O_NONBLOCK);
    retValue = fcntl(fd_, F_SETFL, sockArg);
    if (retValue == -1) {
      PLOG(ERROR) << "Could not make the socket blocking " << port_;
      this->close();
      continue;
    }
    VLOG(1) << "Successful connect on " << fd_;
    sa_ = *info;
    break;
  }
  if (fd_ < 0) {
    if (count > 1) {
      // Only log this if not redundant with log above (ie --ipv6=false)
      LOG(INFO) << "Unable to connect to either of the " << count << " addrs";
    }
    return CONN_ERROR_RETRYABLE;
  }
  SocketUtils::setReadTimeout(fd_);
  SocketUtils::setWriteTimeout(fd_);
  return OK;
}

int ClientSocket::getFd() const {
  VLOG(1) << "fd is " << fd_;
  return fd_;
}

std::string ClientSocket::getPort() const {
  return port_;
}

int ClientSocket::read(char *buf, int nbyte, bool tryFull) {
  return SocketUtils::readWithAbortCheck(fd_, buf, nbyte, abortChecker_,
                                         tryFull);
}

int ClientSocket::write(const char *buf, int nbyte, bool tryFull) {
  return SocketUtils::writeWithAbortCheck(fd_, buf, nbyte, abortChecker_,
                                          tryFull);
}

void ClientSocket::close() {
  if (fd_ >= 0) {
    VLOG(1) << "Closing socket : " << fd_;
    if (::close(fd_) < 0) {
      VLOG(1) << "Socket close failed for fd " << fd_;
    }
    fd_ = -1;
  }
}

void ClientSocket::shutdown() {
  if (::shutdown(fd_, SHUT_WR) < 0) {
    VLOG(1) << "Socket shutdown failed for fd " << fd_;
  }
}

ClientSocket::~ClientSocket() {
  this->close();
}
}
}  // end namespace facebook::wtd


text:
<!--

********************************************************************************

WARNING:

    DO NOT EDIT "drupal/README.md"

    IT IS AUTO-GENERATED

    (from the other files in "drupal/" combined with a set of templates)

********************************************************************************

-->

# Supported tags and respective `Dockerfile` links

-	[`8.5.0-apache`, `8.5-apache`, `8-apache`, `apache`, `8.5.0`, `8.5`, `8`, `latest` (*8.5/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/2347af9118cfbc1666cd773579a7ad055e6a2a2e/8.5/apache/Dockerfile)
-	[`8.5.0-fpm`, `8.5-fpm`, `8-fpm`, `fpm` (*8.5/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/2347af9118cfbc1666cd773579a7ad055e6a2a2e/8.5/fpm/Dockerfile)
-	[`8.5.0-fpm-alpine`, `8.5-fpm-alpine`, `8-fpm-alpine`, `fpm-alpine` (*8.5/fpm-alpine/Dockerfile*)](https://github.com/docker-library/drupal/blob/2347af9118cfbc1666cd773579a7ad055e6a2a2e/8.5/fpm-alpine/Dockerfile)
-	[`7.57-apache`, `7-apache`, `7.57`, `7` (*7/apache/Dockerfile*)](https://github.com/docker-library/drupal/blob/c1863d8b12623355b7ca0abdffead4618289e2ee/7/apache/Dockerfile)
-	[`7.57-fpm`, `7-fpm` (*7/fpm/Dockerfile*)](https://github.com/docker-library/drupal/blob/c1863d8b12623355b7ca0abdffead4618289e2ee/7/fpm/Dockerfile)
-	[`7.57-fpm-alpine`, `7-fpm-alpine` (*7/fpm-alpine/Dockerfile*)](https://github.com/docker-library/drupal/blob/c1863d8b12623355b7ca0abdffead4618289e2ee/7/fpm-alpine/Dockerfile)

# Quick reference

-	**Where to get help**:
	[the Docker Community Forums](https://forums.docker.com/), [the Docker Community Slack](https://blog.docker.com/2016/11/introducing-docker-community-directory-docker-community-slack/), or [Stack Overflow](https://stackoverflow.com/search?tab=newest&q=docker)

-	**Where to file issues**:
	[https://github.com/docker-library/drupal/issues](https://github.com/docker-library/drupal/issues)

-	**Maintained by**:
	[the Docker Community](https://github.com/docker-library/drupal) (*not* the Drupal Community or the Drupal Security Team)

-	**Supported architectures**: ([more info](https://github.com/docker-library/official-images#architectures-other-than-amd64))
	[`amd64`](https://hub.docker.com/r/amd64/drupal/), [`arm32v5`](https://hub.docker.com/r/arm32v5/drupal/), [`arm32v6`](https://hub.docker.com/r/arm32v6/drupal/), [`arm32v7`](https://hub.docker.com/r/arm32v7/drupal/), [`arm64v8`](https://hub.docker.com/r/arm64v8/drupal/), [`i386`](https://hub.docker.com/r/i386/drupal/), [`ppc64le`](https://hub.docker.com/r/ppc64le/drupal/), [`s390x`](https://hub.docker.com/r/s390x/drupal/)

-	**Published image artifact details**:
	[repo-info repo's `repos/drupal/` directory](https://github.com/docker-library/repo-info/blob/master/repos/drupal) ([history](https://github.com/docker-library/repo-info/commits/master/repos/drupal))
	(image metadata, transfer size, etc)

-	**Image updates**:
	[official-images PRs with label `library/drupal`](https://github.com/docker-library/official-images/pulls?q=label%3Alibrary%2Fdrupal)
	[official-images repo's `library/drupal` file](https://github.com/docker-library/official-images/blob/master/library/drupal) ([history](https://github.com/docker-library/official-images/commits/master/library/drupal))

-	**Source of this description**:
	[docs repo's `drupal/` directory](https://github.com/docker-library/docs/tree/master/drupal) ([history](https://github.com/docker-library/docs/commits/master/drupal))

-	**Supported Docker versions**:
	[the latest release](https://github.com/docker/docker-ce/releases/latest) (down to 1.6 on a best-effort basis)

# What is Drupal?

Drupal is a free and open-source content-management framework written in PHP and distributed under the GNU General Public License. It is used as a back-end framework for at least 2.1% of all Web sites worldwide ranging from personal blogs to corporate, political, and government sites including WhiteHouse.gov and data.gov.uk. It is also used for knowledge management and business collaboration.

> [wikipedia.org/wiki/Drupal](https://en.wikipedia.org/wiki/Drupal)

![logo](https://raw.githubusercontent.com/docker-library/docs/a0f37ddfd711f858bb968d6c85715f5bc1f7393f/drupal/logo.png)

# How to use this image

The basic pattern for starting a `drupal` instance is:

```console
$ docker run --name some-drupal -d drupal
```

If you'd like to be able to access the instance from the host without the container's IP, standard port mappings can be used:

```console
$ docker run --name some-drupal -p 8080:80 -d drupal
```

Then, access it via `http://localhost:8080` or `http://host-ip:8080` in a browser.

There are multiple database types supported by this image, most easily used via standard container linking. In the default configuration, SQLite can be used to avoid a second container and write to flat-files. More detailed instructions for different (more production-ready) database types follow.

When first accessing the webserver provided by this image, it will go through a brief setup process. The details provided below are specifically for the "Set up database" step of that configuration process.

## MySQL

```console
$ docker run --name some-drupal --link some-mysql:mysql -d drupal
```

-	Database type: `MySQL, MariaDB, or equivalent`
-	Database name/username/password: `<details for accessing your MySQL instance>` (`MYSQL_USER`, `MYSQL_PASSWORD`, `MYSQL_DATABASE`; see environment variables in the description for [`mysql`](https://registry.hub.docker.com/_/mysql/))
-	ADVANCED OPTIONS; Database host: `mysql` (for using the `/etc/hosts` entry added by `--link` to access the linked container's MySQL instance)

## PostgreSQL

```console
$ docker run --name some-drupal --link some-postgres:postgres -d drupal
```

-	Database type: `PostgreSQL`
-	Database name/username/password: `<details for accessing your PostgreSQL instance>` (`POSTGRES_USER`, `POSTGRES_PASSWORD`; see environment variables in the description for [`postgres`](https://registry.hub.docker.com/_/postgres/))
-	ADVANCED OPTIONS; Database host: `postgres` (for using the `/etc/hosts` entry added by `--link` to access the linked container's PostgreSQL instance)

## Volumes

By default, this image does not include any volumes. There is a lot of good discussion on this topic in [docker-library/drupal#3](https://github.com/docker-library/drupal/issues/3), which is definitely recommended reading.

There is consensus that `/var/www/html/modules`, `/var/www/html/profiles`, and `/var/www/html/themes` are things that generally ought to be volumes (and might have an explicit `VOLUME` declaration in a future update to this image), but handling of `/var/www/html/sites` is somewhat more complex, since the contents of that directory *do* need to be initialized with the contents from the image.

If using bind-mounts, one way to accomplish pre-seeding your local `sites` directory would be something like the following:

```console
$ docker run --rm drupal tar -cC /var/www/html/sites . | tar -xC /path/on/host/sites
```

This can then be bind-mounted into a new container:

```console
$ docker run --name some-drupal --link some-postgres:postgres -d \
	-v /path/on/host/modules:/var/www/html/modules \
	-v /path/on/host/profiles:/var/www/html/profiles \
	-v /path/on/host/sites:/var/www/html/sites \
	-v /path/on/host/themes:/var/www/html/themes \
	drupal
```

Another solution using Docker Volumes:

```console
$ docker volume create drupal-sites
$ docker run --rm -v drupal-sites:/temporary/sites drupal cp -aRT /var/www/html/sites /temporary/sites
$ docker run --name some-drupal --link some-postgres:postgres -d \
	-v drupal-modules:/var/www/html/modules \
	-v drupal-profiles:/var/www/html/profiles \
	-v drupal-sites:/var/www/html/sites \
	-v drupal-themes:/var/www/html/themes \
	drupal
```

## ... via [`docker stack deploy`](https://docs.docker.com/engine/reference/commandline/stack_deploy/) or [`docker-compose`](https://github.com/docker/compose)

Example `stack.yml` for `drupal`:

```yaml
# Drupal with PostgreSQL
#
# Access via "http://localhost:8080"
#   (or "http://$(docker-machine ip):8080" if using docker-machine)
#
# During initial Drupal setup,
# Database type: PostgreSQL
# Database name: postgres
# Database username: postgres
# Database password: example
# ADVANCED OPTIONS; Database host: postgres

version: '3.1'

services:

  drupal:
    image: drupal:8.2-apache
    ports:
      - 8080:80
    volumes:
      - /var/www/html/modules
      - /var/www/html/profiles
      - /var/www/html/themes
      # this takes advantage of the feature in Docker that a new anonymous
      # volume (which is what we're creating here) will be initialized with the
      # existing content of the image at the same location
      - /var/www/html/sites
    restart: always

  postgres:
    image: postgres:9.6
    environment:
      POSTGRES_PASSWORD: example
    restart: always
```

[![Try in PWD](https://github.com/play-with-docker/stacks/raw/cff22438cb4195ace27f9b15784bbb497047afa7/assets/images/button.png)](http://play-with-docker.com?stack=https://raw.githubusercontent.com/docker-library/docs/54359bd26c41e63c6e50ccd338b5a18d8b572c60/drupal/stack.yml)

Run `docker stack deploy -c stack.yml drupal` (or `docker-compose -f stack.yml up`), wait for it to initialize completely, and visit `http://swarm-ip:8080`, `http://localhost:8080`, or `http://host-ip:8080` (as appropriate). When installing select `postgres` as database with the following parameters: `dbname=postgres` `user=postgres` `pass=example` `hostname=postgres`

## Adding additional libraries / extensions

This image does not provide any additional PHP extensions or other libraries, even if they are required by popular plugins. There are an infinite number of possible plugins, and they potentially require any extension PHP supports. Including every PHP extension that exists would dramatically increase the image size.

If you need additional PHP extensions, you'll need to create your own image `FROM` this one. The [documentation of the `php` image](https://github.com/docker-library/docs/blob/master/php/README.md#how-to-install-more-php-extensions) explains how to compile additional extensions. Additionally, the [`drupal:7` Dockerfile](https://github.com/docker-library/drupal/blob/bee08efba505b740a14d68254d6e51af7ab2f3ea/7/Dockerfile#L6-9) has an example of doing this.

The following Docker Hub features can help with the task of keeping your dependent images up-to-date:

-	[Automated Builds](https://docs.docker.com/docker-hub/builds/) let Docker Hub automatically build your Dockerfile each time you push changes to it.
-	[Repository Links](https://docs.docker.com/docker-hub/builds/#repository-links) can ensure that your image is also rebuilt any time `drupal` is updated.

# Image Variants

The `drupal` images come in many flavors, each designed for a specific use case.

## `drupal:<version>`

This is the defacto image. If you are unsure about what your needs are, you probably want to use this one. It is designed to be used both as a throw away container (mount your source code and start the container to start your app), as well as the base to build other images off of.

## `drupal:alpine`

This image is based on the popular [Alpine Linux project](http://alpinelinux.org), available in [the `alpine` official image](https://hub.docker.com/_/alpine). Alpine Linux is much smaller than most distribution base images (~5MB), and thus leads to much slimmer images in general.

This variant is highly recommended when final image size being as small as possible is desired. The main caveat to note is that it does use [musl libc](http://www.musl-libc.org) instead of [glibc and friends](http://www.etalabs.net/compare_libcs.html), so certain software might run into issues depending on the depth of their libc requirements. However, most software doesn't have an issue with this, so this variant is usually a very safe choice. See [this Hacker News comment thread](https://news.ycombinator.com/item?id=10782897) for more discussion of the issues that might arise and some pro/con comparisons of using Alpine-based images.

To minimize image size, it's uncommon for additional related tools (such as `git` or `bash`) to be included in Alpine-based images. Using this image as a base, add the things you need in your own Dockerfile (see the [`alpine` image description](https://hub.docker.com/_/alpine/) for examples of how to install packages if you are unfamiliar).

# License

View [license information](https://www.drupal.org/licensing/faq) for the software contained in this image.

As with all Docker images, these likely also contain other software which may be under other licenses (such as Bash, etc from the base distribution, along with any direct or indirect dependencies of the primary software being contained).

Some additional license information which was able to be auto-detected might be found in [the `repo-info` repository's `drupal/` directory](https://github.com/docker-library/repo-info/tree/master/repos/drupal).

As for any pre-built image usage, it is the image user's responsibility to ensure that any use of this image complies with any relevant licenses for all software contained within.


text:
from base import Task
from common import phases
from common.tasks.packages import InstallPackages
from common.exceptions import TaskError

class CheckGuestAdditionsPath(Task):
	description = 'Checking whether the VirtualBox Guest Additions image exists'
	phase = phases.preparation

	@classmethod
	def run(cls, info):
		import os.path
		guest_additions_path = info.manifest.bootstrapper['guest_additions']
		if not os.path.exists(guest_additions_path):
			msg = 'The file {file} does not exist.'.format(file=guest_additions_path)
			raise TaskError(msg)

class AddGuestAdditionsPackages(Task):
	description = 'Adding packages to support Guest Additions installation'
	phase = phases.package_installation
	successors = [InstallPackages]

	@classmethod
	def run(cls, info):
		info.packages.add('bzip2')
		info.packages.add('build-essential')
		info.packages.add('dkms')

		from common.tools import log_check_call
		[kernel_version] = log_check_call(['/usr/sbin/chroot', info.root,
		                                   '/bin/uname', '-r'])
		kernel_headers_pkg = 'linux-headers-{version}'.format(version=kernel_version)
		info.packages.add(kernel_headers_pkg)

class InstallGuestAdditions(Task):
	description = 'Installing the VirtualBox Guest Additions'
	phase = phases.package_installation
	predecessors = [InstallPackages]

	@classmethod
	def run(cls, info):
		import os
		guest_additions_path = info.manifest.bootstrapper['guest_additions']
		mount_dir = 'mnt/guest_additions'
		mount_path = os.path.join(info.root, mount_dir)
		os.mkdir(mount_path)
		root = info.volume.partition_map.root
		root.add_mount(guest_additions_path, mount_path, ['-o', 'loop'])

		install_script = os.path.join('/', mount_dir, 'VBoxLinuxAdditions.run')
		from common.tools import log_call
		status, out, err = log_call(['/usr/sbin/chroot', info.root,
		                            install_script, '--nox11'])
		# Install will exit with $?=1 because X11 isn't installed
		if status != 1:
			msg = ('VBoxLinuxAdditions.run exited with status {status}, '
			       'it should exit with status 1').format(status=status)
			raise TaskError(msg)

		root.remove_mount(mount_path)
		os.rmdir(mount_path)


text:
<!doctype html>

    <title>Code coverage report for cjs/observables/ForkJoinObservable.js</title>
    <meta charset="utf-8">
    <link rel="stylesheet" href="../../prettify.css">
    <link rel="stylesheet" href="../../base.css">

Code coverage report for cjs/observables/ForkJoinObservable.js

        Statements: 96.61% (57 / 59)
        Branches: 66.67% (12 / 18)
        Functions: 100% (13 / 13)
        Lines: 100% (51 / 51)
        Ignored: none

All files » cjs/observables/ » ForkJoinObservable.js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91

1

2

4

2

1

1

1

1

1
1

1
1

1
1

1
1
3

1

1
1
1
1
1
3

1

1

1
1

1
3

3
3
3
3

1
10

1
3
3
3
1
1

1

1
8

1
1
1
3

1

1

'use strict';

exports.__esModule = true;

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { 'default': obj }; }

function _classCallCheck(instance, Constructor) { Iif (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }

function _inherits(subClass, superClass) { Iif (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); Eif (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }

var _Observable2 = require('../Observable');

var _Observable3 = _interopRequireDefault(_Observable2);

var _Subscriber2 = require('../Subscriber');

var _Subscriber3 = _interopRequireDefault(_Subscriber2);

var ForkJoinObservable = (function (_Observable) {
    _inherits(ForkJoinObservable, _Observable);

    function ForkJoinObservable(observables) {
        _classCallCheck(this, ForkJoinObservable);

        _Observable.call(this);
        this.observables = observables;
    }

    ForkJoinObservable.create = function create() {
        for (var _len = arguments.length, observables = Array(_len), _key = 0; _key < _len; _key++) {
            observables[_key] = arguments[_key];
        }

        return new ForkJoinObservable(observables);
    };

    ForkJoinObservable.prototype._subscribe = function _subscribe(subscriber) {
        var observables = this.observables;
        var len = observables.length;
        var context = { complete: 0, total: len, values: emptyArray(len) };
        for (var i = 0; i < len; i++) {
            observables[i].subscribe(new AllSubscriber(subscriber, this, i, context));
        }
    };

    return ForkJoinObservable;
})(_Observable3['default']);

exports['default'] = ForkJoinObservable;

var AllSubscriber = (function (_Subscriber) {
    _inherits(AllSubscriber, _Subscriber);

    function AllSubscriber(destination, parent, index, context) {
        _classCallCheck(this, AllSubscriber);

        _Subscriber.call(this, destination);
        this.parent = parent;
        this.index = index;
        this.context = context;
    }

    AllSubscriber.prototype._next = function _next(value) {
        this._value = value;
    };

    AllSubscriber.prototype._complete = function _complete() {
        var context = this.context;
        context.values[this.index] = this._value;
        if (context.values.every(hasValue)) {
            this.destination.next(context.values);
            this.destination.complete();
        }
    };

    return AllSubscriber;
})(_Subscriber3['default']);

function hasValue(x) {
    return x !== null;
}
function emptyArray(len) {
    var arr = [];
    for (var i = 0; i < len; i++) {
        arr.push(null);
    }
    return arr;
}
//# sourceMappingURL=ForkJoinObservable.js.map
module.exports = exports['default'];
//# sourceMappingURL=ForkJoinObservable.js.map

Generated by istanbul at Mon Oct 26 2015 13:47:29 GMT-0700 (PDT)


text:
using System.IO;

using Aspose.Cells;
using System;

namespace Aspose.Cells.Examples.CSharp.Data.Handling.AccessingCells
{
    public class UsingRowAndColumnIndexOfCell
    {
        public static void Run()
        {
            // ExStart:1
            // The path to the documents directory.
            string dataDir = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

            // Instantiating a Workbook object
            Workbook workbook = new Workbook(dataDir + "book1.xls");

            // Using the Sheet 1 in Workbook
            Worksheet worksheet = workbook.Worksheets[0];

            // Accessing a cell using its row and column
            Cell cell = worksheet.Cells[0,0];

            string value = cell.Value.ToString();

            Console.WriteLine(value);
            // ExEnd:1
        }
    }
}


text:
{-# LANGUAGE NoImplicitPrelude, MagicHash, ScopedTypeVariables, KindSignatures,
             UnboxedTuples, FlexibleContexts, UnliftedFFITypes, TypeOperators,
             AllowAmbiguousTypes, DataKinds, TypeFamilies #-}
-----------------------------------------------------------------------------
-- |
-- Module      :  Java.Utils
-- Copyright   :  (c) Rahul Muttineni 2016
--
-- License     :  BSD-style (see the file libraries/base/LICENSE)
--
-- Maintainer  :  rahulmutt@gmail.com
-- Stability   :  provisional
-- Portability :  portable
--
-- The utility functions for the Java FFI.
--
-----------------------------------------------------------------------------

module Java.Utils
  ( JClass
  , getClass
  , toString
  , equals
  , classObject
  , hashCode
  , Proxy(..)
  , eqObject#
  , toString#
  , safeDowncast
  , Void
  , Comparator
  , Comparable
  , Enum )
where

import GHC.Base
import Data.Proxy
import Java.String

data {-# CLASS "java.lang.Class" #-} JClass a = JClass (Object# (JClass a))
  deriving Class

{-# INLINE getClass #-}
getClass :: forall (a :: *). Proxy a -> JClass a
getClass _ = JClass (getClass# (proxy# :: Proxy# a))

foreign import java unsafe classObject :: (a <: Object) => a -> JClass a
foreign import java unsafe toString    :: (a <: Object) => a -> JString
foreign import java unsafe hashCode    :: (a <: Object) => a -> Int

foreign import java unsafe equals :: (a <: Object, b <: Object)
                                  => a -> b -> Bool

foreign import java unsafe "equals" eqObject# :: Object# a -> Object# b -> Bool
foreign import java unsafe "toString" toString# :: Object# a -> String

foreign import java unsafe "@static eta.base.Utils.convertInstanceOfObject"
  castObject :: (t <: Object, o <: Object) => o -> JClass t -> Maybe t

{-# INLINE safeDowncast #-}
safeDowncast :: forall a b. (Class a, Class b) => a -> Maybe b
safeDowncast x = castObject x (getClass (Proxy :: Proxy b))

-- Start java.lang.Void

data {-# CLASS "java.lang.Void" #-} Void = Void (Object# Void)
  deriving Class

-- End java.lang.Void

-- Start java.util.Comparator

data {-# CLASS "java.util.Comparator" #-} Comparator t = Comparator (Object# (Comparator t))
  deriving Class

foreign import java unsafe "@interface compare"
  compare :: (t <: Object, b <: (Comparator t)) => t -> t -> Java b Int

foreign import java unsafe "@interface equals"
  equalsComparator :: (t <: Object, b <: (Comparator t)) => Object -> Java b Bool

-- End java.util.Comparator

-- Start java.lang.Enum

data {-# CLASS "java.lang.Enum" #-} Enum e = Enum (Object# (Enum e))
  deriving Class

type instance Inherits (Enum e) = '[Object, Comparable e]

foreign import java unsafe getDeclaringClass :: (e <: Enum e) => Java e (JClass e)

foreign import java unsafe name :: (e <: Enum e) => Java e String

foreign import java unsafe ordinal :: (e <: Enum e) => Java e Int

-- End java.lang.Enum


text:
using UnityEngine;
using System.Collections;

public class EndGameRestart : MonoBehaviour {

	// Make the sprite invisible while you're playing
	void Start () {
        GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f, 0f);
	}

	// Checking if you're dead, if you are, make the sprite visible
	void Update () {
        GameObject go = GameObject.Find("Burd");
        Control bird = go.GetComponent<Control>();
        if (bird.isDead)
        {
            GetComponent<SpriteRenderer>().color = new Color(1f, 1f, 1f, 1f);
        }
	}
    void OnMouseDown()
    {
        GameObject go = GameObject.Find("Burd");
        Control bird = go.GetComponent<Control>();
        //AND the sprite becomes clickable
        if(bird.isDead) Application.LoadLevel(Application.loadedLevel);
    }
}


text:
require 'rspec'
require 'converter/cf_portgroup'

describe CFPortGroup do
  describe 'vSphere/Photon PortGroup manipulation' do
    yaml = nil

    context 'in the cf manifest' do
      manifest = <<-END

---
networks:
- name: default
  subnets:
  - range: 10.65.170.0/23
    cloud_properties:
      name: Photon_PCF

END

     before do
       yaml = YAML.load manifest
     end

     it 'should swap the network' do
        CFPortGroup.set_portgroup yaml, 'a-new-network'
        expect(yaml['networks'][0]['subnets'][0]['cloud_properties']['name']).to eql 'a-new-network'
     end

  end
 end
end


text:
<?php

/**
 * Exception thrown when a department is not found
 */
class D2LWS_OrgUnit_Department_Exception_NotFound extends Zend_Exception
{

}


text:
package org.apache.flex.compiler.problems;

import org.apache.flex.compiler.problems.annotations.DefaultSeverity;

/**
 * The SWF Tag length is set longer than need to read all of the data in the tag.
 */
@DefaultSeverity(CompilerProblemSeverity.WARNING)
public class SWFTagLengthTooLongProblem extends CompilerProblem
{
    public static final String DESCRIPTION =
        "A SWF Tag of type ${type} contains ${extraBytes} bytes of unread data at the end of the tag at byte offset ${offset}";

    public static final int warningCode = 5025;

    /**
     * The SWF Tag is longer than it should be.
     *
     * @param type The tag type.
     * @param sourcePath The normalized path of the file
     * in which the problem occurred.
     * @param offset The byte offset of the start of the extra data.
     * @param tagEndOffset The byte offset of the end of the tag.
     */
    public SWFTagLengthTooLongProblem(int type, String sourcePath,
            long offset, long tagEndOffset)
    {
        super(sourcePath);
        this.type = type;
        this.offset = offset;
        this.extraBytes = tagEndOffset - offset;
    }

    public final int type;
    public final long offset;
    public final long extraBytes;

}


text:
Unofficial LESS port of [Pocketgrid](http://arnaudleray.github.io/pocketgrid/), a pure CSS responsive and semantic grid system.

PocketGrid is the smallest responsive grid system having so many features:
- **Lightweight**: about 0.5kB!
- **Pure CSS-only** (no CSS preprocessor needed)
- **Fluid** (by default, but you can set a fixed width or max-width if you want)
- **Responsive**
- **Unlimited number of breakpoints** (you can define your own Media Queries)
- **Mobile-first** compatible (block width is 100% by default)
- **Content-first** compatible (you can **swap columns** and you can define your own breakpoints for each content in your page to fine-tune and optimize your content readability: not only 'tablet' or 'smartphone' breakpoints)
- **Semantic** (as much as a pure CSS grid could be ;) )
- **Very simple** (just have to define blocks and groups of blocks)
- **Unlimited number of columns** (no 12 or 16 columns restrictions: blocks just require a width in percentage)
- **Unlimited nested grids**
- Manage consistent **gutters** (gutters can be defined in pixels or ems, which is better than percentage-based solutions because it allows consistent gutters even in nested grids)
- **Automatic rows** (when a row is full, the next blocks go to a new row without doing anything)
- No dependencies
- Compatible with CSS frameworks such as Twitter Bootstrap or Zurb Foundation (you can use the Bootstrap or Foundation components such as buttons, tabs, etc. and use the Pocket grid for other layout)
- **Compatibility**: **IE6+, Firefox, Chrome, Safari, Opera, and mobile browsers (iPhone, iPad, Android...)**

## Documentation
See http://arnaudleray.github.io/pocketgrid/docs/

## Download
See http://arnaudleray.github.io/pocketgrid/download/

## FAQ
See http://arnaudleray.github.io/pocketgrid/faq/

## Community
You can follow @PocketGrid on Twitter!

## Should I use PocketGrid instead of Twitter Bootstrap or other grids?
Well, first, **you can use both**!
Indeed, PocketGrid is compatible with any other framework such as Twitter Bootstrap or Zurb Foundation (because it does not use 'grid', 'row' or 'col' classes which are used by too many grid systems).
For example, you could use PocketGrid for your layout positioning, and use Twitter Bootstrap for styling, tabs or special components...

Moreover, PocketGrid has many nice features:
- PocketGrid is really lightweight, so you can use it in all your projects at no cost (Twitter Bootstrap is about 200x bigger, even minified!)
- Twitter Bootstrap 2's grid has only 1 breakpoint (like many grid systems), whereas with PocketGrid you can define as many breakpoints as you want!
- Twitter Bootstrap breakpoints are hard-coded and limited, whereas PocketGrid breakpoints are free and unlimited!
- Twitter Bootstrap has only 12 columns, whereas PocketGrid columns are unlimited!
- PocketGrid is one of the very few semantic grids (especially pure CSS grids!): you don't have "span4" or "small-6 large-2 columns" classes everywhere in your HTML: column size should be defined in the stylesheet, not in the HTML! That's the PocketGrid philosophy!
- Percentage sizing is more natural and more precise than using a number of columns
(how can you make 5 columns in a 12 or 16-columns system? It's impossible! With PocketGrid, just put "width:20%", easy!)
- PocketGrid does not require a CSS preprocessor such as LESS or SASS (but you can use one if you want).

Note: If you want to use a complete CSS framework like Twitter Bootstrap, it's dangerous to use it for ALL your site structure because when you upgrade this framework (e.g. upgrading Bootstrap 2 to Bootstrap 3), all your layout will be broken because their grid has evolved and is not backward compatible.
**Using a separate grid for your layout (such as PocketGrid!) allows you to upgrade safely your CSS framework (buttons, tabs, carousel...) without breaking your layout!**

## Author

* **Arnaud Leray**
* **shopware AG *(LESS port)***

## Copyright and license

Copyright 2013 Arnaud Leray.

Licensed under the MIT License:
[http://opensource.org/licenses/MIT](http://opensource.org/licenses/MIT)
Basically, you can do whatever you want as long as you include the original copyright.


text:
$(document).on('click','table.inline-edit a.row-remove', function(event){
    $(event.target).closest('tr').remove();
    return false;
});

$(document).on('click','table.inline-edit a.row-add', function(event){

    var table = $(event.target).closest('table');
    var copy = table.find('tbody tr:first-child').clone();

    // Find a free number
    var highest = 0;
    var num = 0;

    $(table).find('input,select,textarea').each(function(){
            var element = $(this);
            var name = element.attr('name');
            var number = name.replace( /[^\d.]/g, '');
            if(number){
                var num = parseInt(number);
                if(num && num > highest){
                    highest = num;
                }
            }
    });

    if(copy){
        $(copy).find('input,select,textarea').each(function(){
            var element = $(this);
            var name = element.attr('name');
            var id = element.attr('id');
            var number = name.replace( /[^\d.]/g, '');
            var next = highest + 1;
            element.attr('name',name.replace('['+number+']','['+next+']'));
            element.attr('id',id.replace(number,next));
            if(element.attr('name') == 'id'){
                element.attr('value','');
            }
        });
        copy.appendTo(table.find('tbody'));
    }

    return false;
});


text:
package org.dswarm.controller.resources.job.test.utils;

import org.dswarm.persistence.model.job.Function;
import org.dswarm.persistence.model.job.proxy.ProxyFunction;
import org.dswarm.persistence.service.job.FunctionService;
import org.dswarm.persistence.service.job.test.utils.FunctionServiceTestUtils;

public class FunctionsResourceTestUtils extends BasicFunctionsResourceTestUtils<FunctionServiceTestUtils, FunctionService, ProxyFunction, Function> {

	public FunctionsResourceTestUtils() {

		super("functions", Function.class, FunctionService.class, FunctionServiceTestUtils.class);
	}
}


text:
package com.orientechnologies.common.concur.resource;

public interface OResourcePoolListener<K, V> {

	public V createNewResource(K iKey, String... iAdditionalArgs);

	public V reuseResource(K iKey, V iValue);
}


text:
<?php

?>

<?php $form=$this->beginWidget('CActiveForm', array(
	'action'=>Yii::app()->createUrl($this->route),
	'method'=>'get',
)); ?>

			<?php echo $model->getAttributeLabel('course_id'); ?>

			<?php echo $form->textField($model,'course_id', array('size'=>11,'maxlength'=>11)); ?>

			<?php echo $model->getAttributeLabel('course_name'); ?>

			<?php echo $form->textField($model,'course_name', array('size'=>32,'maxlength'=>32)); ?>

			<?php echo $model->getAttributeLabel('course_desc'); ?>

			<?php echo $form->textArea($model,'course_desc', array('rows'=>6, 'cols'=>50)); ?>

			<?php echo $model->getAttributeLabel('creation_date'); ?>

			<?php echo $form->textField($model,'creation_date'); ?>

			<?php echo $model->getAttributeLabel('creation_id'); ?>

			<?php echo $form->textField($model,'creation_id', array('size'=>11,'maxlength'=>11)); ?>

			<?php echo CHtml::submitButton(Yii::t('phrase', 'Search')); ?>

<?php $this->endWidget(); ?>


text:
package play.core.j

import java.lang.annotation.Annotation
import java.lang.reflect.AnnotatedElement;
import java.util.concurrent.CompletionStage
import javax.inject.Inject

import play.api.http.ActionCompositionConfiguration
import play.api.http.HttpConfiguration
import play.api.inject.Injector
import play.api.Logger

import scala.compat.java8.FutureConverters
import scala.language.existentials
import play.core.Execution.Implicits.trampoline
import play.api.mvc._
import play.mvc.FileMimeTypes
import play.mvc.{ Action => JAction }
import play.mvc.{ BodyParser => JBodyParser }
import play.mvc.{ Result => JResult }
import play.i18n.{ Langs => JLangs }
import play.i18n.{ MessagesApi => JMessagesApi }
import play.libs.AnnotationUtils
import play.mvc.Http.{ Request => JRequest }
import play.mvc.Http.{ RequestImpl => JRequestImpl }

import scala.collection.JavaConverters._
import scala.concurrent.ExecutionContext
import scala.concurrent.Future

/**
 * Retains and evaluates what is otherwise expensive reflection work on call by call basis.
 *
 * @param controller The controller to be evaluated
 * @param method     The method to be evaluated
 */
class JavaActionAnnotations(
    val controller: Class[_],
    val method: java.lang.reflect.Method,
    config: ActionCompositionConfiguration
) {
  val parser: Class[_ <: JBodyParser[_]] =
    Seq(
      method.getAnnotation(classOf[play.mvc.BodyParser.Of]),
      controller.getAnnotation(classOf[play.mvc.BodyParser.Of])
    ).filterNot(_ == null)
      .headOption
      .map(_.value)
      .getOrElse(classOf[JBodyParser.Default])

  val controllerAnnotations: Seq[(Annotation, AnnotatedElement)] = play.api.libs.Collections
    .unfoldLeft[Seq[(Annotation, AnnotatedElement)], Option[Class[_]]](Option(controller)) { clazz =>
      clazz.map(c => (Option(c.getSuperclass), c.getDeclaredAnnotations.map((_, c)).toSeq))
    }
    .flatten

  val actionMixins: Seq[(Annotation, Class[_ <: JAction[_]], AnnotatedElement)] = {
    val methodAnnotations = method.getDeclaredAnnotations.map((_, method))
    val allDeclaredAnnotations: Seq[(java.lang.annotation.Annotation, AnnotatedElement)] =
      if (config.controllerAnnotationsFirst) {
        controllerAnnotations ++ methodAnnotations
      } else {
        methodAnnotations ++ controllerAnnotations
      }
    allDeclaredAnnotations
      .collect {
        case (a: play.mvc.With, ae) => a.value.map(c => (a, c, ae)).toSeq
        case (a, ae) if a.annotationType.isAnnotationPresent(classOf[play.mvc.With]) =>
          a.annotationType.getAnnotation(classOf[play.mvc.With]).value.map(c => (a, c, ae)).toSeq
        case (a, ae) if !a.annotationType.isAnnotationPresent(classOf[play.mvc.With]) =>
          AnnotationUtils
            .getIndirectlyPresentAnnotations(a)
            .asScala
            .filter(_.annotationType.isAnnotationPresent(classOf[play.mvc.With]))
            .flatMap(ia => ia.annotationType.getAnnotation(classOf[play.mvc.With]).value.map(c => (ia, c, ae)))
      }
      .flatten
      .map(v => {
        if (v._2.isAnnotationPresent(classOf[javax.inject.Singleton])) {
          // If action singletons would be allowed, it would be very, very likely that concurrent requests interfere with each other
          // when setting the delegate property on that one-and-only singleton instance (see code further below where delegate gets set).
          // If timing is right, it would be possible that, just before calling action.delegate, that the to-be-called delegate was just modified by a concurrent request
          // and points to the next (=delegate) action of that other request (instead of it's own delegate action)
          // As a result (at least) the path/query params of the request would be leaked to the others' request delegate (which eventually will be the action method in the controller).
          // See https://github.com/playframework/playframework/issues/8985#issuecomment-457009162
          throw new RuntimeException(
            s"Singleton action instances are not allowed! Remove the @javax.inject.Singleton annotation from the action class ${v._2.getName}"
          )
        }
        v
      })
      .reverse
  }
}

/*
 * An action that's handling Java requests
 */
abstract class JavaAction(val handlerComponents: JavaHandlerComponents)
    extends Action[play.mvc.Http.RequestBody]
    with JavaHelpers {
  private val logger = Logger(classOf[JAction[_]])

  private def config: ActionCompositionConfiguration = handlerComponents.httpConfiguration.actionComposition

  def invocation(req: JRequest): CompletionStage[JResult]
  val annotations: JavaActionAnnotations

  val executionContext: ExecutionContext = handlerComponents.executionContext

  def apply(req: Request[play.mvc.Http.RequestBody]): Future[Result] = {
    val javaRequest: JRequest = new JRequestImpl(req)

    val rootAction = new JAction[Any] {
      override def call(request: JRequest): CompletionStage[JResult] = invocation(request)
    }

    val baseAction = handlerComponents.actionCreator.createAction(javaRequest, annotations.method)

    val endOfChainAction = if (config.executeActionCreatorActionFirst) {
      rootAction
    } else {
      rootAction.precursor = baseAction
      baseAction.delegate = rootAction
      baseAction
    }

    val firstUserDeclaredAction = annotations.actionMixins.foldLeft[JAction[_ <: Any]](endOfChainAction) {
      case (delegate, (annotation, actionClass, annotatedElement)) =>
        val action = handlerComponents.getAction(actionClass).asInstanceOf[play.mvc.Action[Object]]
        action.configuration = annotation
        delegate.precursor = action
        action.delegate = delegate
        action.annotatedElement = annotatedElement
        action
    }

    val firstAction = if (config.executeActionCreatorActionFirst) {
      firstUserDeclaredAction.precursor = baseAction
      baseAction.delegate = firstUserDeclaredAction
      baseAction
    } else {
      firstUserDeclaredAction
    }

    val trampolineWithContext: ExecutionContext = {
      val javaClassLoader = Thread.currentThread.getContextClassLoader
      new HttpExecutionContext(javaClassLoader, trampoline)
    }
    if (logger.isDebugEnabled) {
      val actionChain = play.api.libs.Collections
        .unfoldLeft[JAction[_], Option[JAction[_]]](Option(firstAction)) { action =>
          action.map(a => (Option(a.delegate), a))
        }
        .reverse
      logger.debug("### Start of action order")
      actionChain
        .zip(Stream.from(1))
        .foreach({
          case (action, index) =>
            logger.debug(
              s"${index}. ${action.getClass.getName}" +
                (if (action.annotatedElement != null) {
                   s" defined on ${action.annotatedElement}"
                 })
            )
        })
      logger.debug("### End of action order")
    }
    val actionFuture: Future[Future[JResult]] = Future {
      FutureConverters.toScala(firstAction.call(javaRequest))
    }(trampolineWithContext)
    val flattenedActionFuture: Future[JResult] = actionFuture.flatMap(identity)(trampoline)
    val resultFuture: Future[Result]           = flattenedActionFuture.map(_.asScala)(trampoline)
    resultFuture
  }
}

/**
 * A Java handler.
 *
 * Java handlers, given that they have to load actions and perform Java specific interception, need extra components
 * that can't be supplied by the controller itself to do so.  So this handler is a factory for handlers that, given
 * the JavaComponents, will return a handler that can be invoked by a Play server.
 */
trait JavaHandler extends Handler {

  /**
   * Return a Handler that has the necessary components supplied to execute it.
   */
  def withComponents(handlerComponents: JavaHandlerComponents): Handler
}

/**
 * Group components that are commonly to serve requests.
 */
@deprecated("Inject MessagesApi, Langs, FileMimeTypes or HttpConfiguration instead", "2.8.0")
trait JavaContextComponents {
  def messagesApi: JMessagesApi
  def langs: JLangs
  def fileMimeTypes: FileMimeTypes
  def httpConfiguration: HttpConfiguration
}

@deprecated("Inject MessagesApi, Langs, FileMimeTypes or HttpConfiguration instead", "2.8.0")
class DefaultJavaContextComponents @Inject() (
    val messagesApi: JMessagesApi,
    val langs: JLangs,
    val fileMimeTypes: FileMimeTypes,
    val httpConfiguration: HttpConfiguration
) extends JavaContextComponents

trait JavaHandlerComponents {
  def getBodyParser[A <: JBodyParser[_]](parserClass: Class[A]): A
  def getAction[A <: JAction[_]](actionClass: Class[A]): A
  def actionCreator: play.http.ActionCreator
  def httpConfiguration: HttpConfiguration
  def executionContext: ExecutionContext
  @deprecated(
    "Use the corresponding methods that provide MessagesApi, Langs, FileMimeTypes or HttpConfiguration",
    "2.8.0"
  )
  def contextComponents: JavaContextComponents
}

/**
 * The components necessary to handle a Java handler.
 */
class DefaultJavaHandlerComponents @Inject() (
    injector: Injector,
    val actionCreator: play.http.ActionCreator,
    val httpConfiguration: HttpConfiguration,
    val executionContext: ExecutionContext,
    @deprecated("Inject MessagesApi, Langs, FileMimeTypes or HttpConfiguration instead", "2.8.0")
    val contextComponents: JavaContextComponents
) extends JavaHandlerComponents {
  def getBodyParser[A <: JBodyParser[_]](parserClass: Class[A]): A = injector.instanceOf(parserClass)
  def getAction[A <: JAction[_]](actionClass: Class[A]): A         = injector.instanceOf(actionClass)
}


text:
<?php
/**
 * The Sidebar containing the main widget areas.
 *
 * @package WordPress
 * @subpackage Bouquet
 */
?>

	<?php if ( is_active_sidebar( 'sidebar-1' ) ) : ?>

			<?php get_search_form(); ?>

			<?php dynamic_sidebar( 'sidebar-1' ); ?>

	<?php endif; // end sidebar widget area ?>


text:
Life as a front-end web developer used to be a continuous cycle of 'change file', 'reload browser', 'change file', etc etc until you got the result you were looking for.

SocketStream breaks this cycle by automatically refreshing the browser whenever you make a change to any file in the `/client` directory. What's more, if you're just tweaking the stylesheets, the CSS will be reloaded in place so your app doesn't lose state.

**Tip**: Open up your text editor on one side of the screen, put the browser on the other, and watch your productivity soar!

Live Reload is automatically enabled unless you call:

   ss.client.packAssets()

As you typically would in `production` mode.

### Known issues

#### VIM

VIM creates a temporary file before replacing the real file. To prevent problems with Live Reload, change the write mode with:

    :set nowritebackup

#### Too many files

Live Reload is built on Node's `fs.watch()` API which works differently on each operating system. For example, on Linux you'll get an `EMFILE` error if you have many files in your `client` directory. Change this limit with:

    sudo vi /etc/sysctl.conf

add the following line

    fs.inotify.max_user_instances = 200 # or higher if needed

then run

    sudo sysctl -p

If things still don't work as expected, please log an issue and be sure to mention which OS you're using.

### Options

To disable Live Reload, even in development mode, put the following in your `app.js` code:

    ss.client.set({liveReload: false})

Alternatively, you may specify the top-level directories within `/client` you wish Live Reload to observe. E.g.:

    ss.client.set({liveReload: ['views', 'css'])


text:
#!/usr/bin/env python3

# Copyright 2017 gRPC authors.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import print_function

import collections
import ctypes
import json
import math
import sys

import yaml

with open('src/core/lib/debug/stats_data.yaml') as f:
    attrs = yaml.load(f.read())

REQUIRED_FIELDS = ['name', 'doc']

def make_type(name, fields):
    return (collections.namedtuple(
        name, ' '.join(list(set(REQUIRED_FIELDS + fields)))), [])

def c_str(s, encoding='ascii'):
    if isinstance(s, str):
        s = s.encode(encoding)
    result = ''
    for c in s:
        c = chr(c) if isinstance(c, int) else c
        if not (32 <= ord(c) < 127) or c in ('\\', '"'):
            result += '\\%03o' % ord(c)
        else:
            result += c
    return '"' + result + '"'

types = (
    make_type('Counter', []),
    make_type('Histogram', ['max', 'buckets']),
)

inst_map = dict((t[0].__name__, t[1]) for t in types)

stats = []

for attr in attrs:
    found = False
    for t, lst in types:
        t_name = t.__name__.lower()
        if t_name in attr:
            name = attr[t_name]
            del attr[t_name]
            lst.append(t(name=name, **attr))
            found = True
            break
    assert found, "Bad decl: %s" % attr

def dbl2u64(d):
    return ctypes.c_ulonglong.from_buffer(ctypes.c_double(d)).value

def shift_works_until(mapped_bounds, shift_bits):
    for i, ab in enumerate(zip(mapped_bounds, mapped_bounds[1:])):
        a, b = ab
        if (a >> shift_bits) == (b >> shift_bits):
            return i
    return len(mapped_bounds)

def find_ideal_shift(mapped_bounds, max_size):
    best = None
    for shift_bits in reversed(list(range(0, 64))):
        n = shift_works_until(mapped_bounds, shift_bits)
        if n == 0:
            continue
        table_size = mapped_bounds[n - 1] >> shift_bits
        if table_size > max_size:
            continue
        if table_size > 65535:
            continue
        if best is None:
            best = (shift_bits, n, table_size)
        elif best[1] < n:
            best = (shift_bits, n, table_size)
    print(best)
    return best

def gen_map_table(mapped_bounds, shift_data):
    tbl = []
    cur = 0
    print(mapped_bounds)
    mapped_bounds = [x >> shift_data[0] for x in mapped_bounds]
    print(mapped_bounds)
    for i in range(0, mapped_bounds[shift_data[1] - 1]):
        while i > mapped_bounds[cur]:
            cur += 1
        tbl.append(cur)
    return tbl

static_tables = []

def decl_static_table(values, type):
    global static_tables
    v = (type, values)
    for i, vp in enumerate(static_tables):
        if v == vp:
            return i
    print("ADD TABLE: %s %r" % (type, values))
    r = len(static_tables)
    static_tables.append(v)
    return r

def type_for_uint_table(table):
    mv = max(table)
    if mv < 2**8:
        return 'uint8_t'
    elif mv < 2**16:
        return 'uint16_t'
    elif mv < 2**32:
        return 'uint32_t'
    else:
        return 'uint64_t'

def gen_bucket_code(histogram):
    bounds = [0, 1]
    done_trivial = False
    done_unmapped = False
    first_nontrivial = None
    first_unmapped = None
    while len(bounds) < histogram.buckets + 1:
        if len(bounds) == histogram.buckets:
            nextb = int(histogram.max)
        else:
            mul = math.pow(
                float(histogram.max) / bounds[-1],
                1.0 / (histogram.buckets + 1 - len(bounds)))
            nextb = int(math.ceil(bounds[-1] * mul))
        if nextb <= bounds[-1] + 1:
            nextb = bounds[-1] + 1
        elif not done_trivial:
            done_trivial = True
            first_nontrivial = len(bounds)
        bounds.append(nextb)
    bounds_idx = decl_static_table(bounds, 'int')
    if done_trivial:
        first_nontrivial_code = dbl2u64(first_nontrivial)
        code_bounds = [dbl2u64(x) - first_nontrivial_code for x in bounds]
        shift_data = find_ideal_shift(code_bounds[first_nontrivial:],
                                      256 * histogram.buckets)
    #print first_nontrivial, shift_data, bounds
    #if shift_data is not None: print [hex(x >> shift_data[0]) for x in code_bounds[first_nontrivial:]]
    code = 'value = grpc_core::Clamp(value, 0, %d);\n' % histogram.max
    map_table = gen_map_table(code_bounds[first_nontrivial:], shift_data)
    if first_nontrivial is None:
        code += ('GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_%s, value);\n' %
                 histogram.name.upper())
    else:
        code += 'if (value < %d) {\n' % first_nontrivial
        code += ('GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_%s, value);\n' %
                 histogram.name.upper())
        code += 'return;\n'
        code += '}'
        first_nontrivial_code = dbl2u64(first_nontrivial)
        if shift_data is not None:
            map_table_idx = decl_static_table(map_table,
                                              type_for_uint_table(map_table))
            code += 'union { double dbl; uint64_t uint; } _val, _bkt;\n'
            code += '_val.dbl = value;\n'
            code += 'if (_val.uint < %dull) {\n' % (
                (map_table[-1] << shift_data[0]) + first_nontrivial_code)
            code += 'int bucket = '
            code += 'grpc_stats_table_%d[((_val.uint - %dull) >> %d)] + %d;\n' % (
                map_table_idx, first_nontrivial_code, shift_data[0],
                first_nontrivial)
            code += '_bkt.dbl = grpc_stats_table_%d[bucket];\n' % bounds_idx
            code += 'bucket -= (_val.uint < _bkt.uint);\n'
            code += 'GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_%s, bucket);\n' % histogram.name.upper(
            )
            code += 'return;\n'
            code += '}\n'
        code += 'GRPC_STATS_INC_HISTOGRAM(GRPC_STATS_HISTOGRAM_%s, ' % histogram.name.upper(
        )
        code += 'grpc_stats_histo_find_bucket_slow(value, grpc_stats_table_%d, %d));\n' % (
            bounds_idx, histogram.buckets)
    return (code, bounds_idx)

# utility: print a big comment block into a set of files
def put_banner(files, banner):
    for f in files:
        print('/*', file=f)
        for line in banner:
            print(' * %s' % line, file=f)
        print(' */', file=f)
        print(file=f)

with open('src/core/lib/debug/stats_data.h', 'w') as H:
    # copy-paste copyright notice from this file
    with open(sys.argv[0]) as my_source:
        copyright = []
        for line in my_source:
            if line[0] != '#':
                break
        for line in my_source:
            if line[0] == '#':
                copyright.append(line)
                break
        for line in my_source:
            if line[0] != '#':
                break
            copyright.append(line)
        put_banner([H], [line[2:].rstrip() for line in copyright])

    put_banner(
        [H],
        ["Automatically generated by tools/codegen/core/gen_stats_data.py"])

    print("#ifndef GRPC_CORE_LIB_DEBUG_STATS_DATA_H", file=H)
    print("#define GRPC_CORE_LIB_DEBUG_STATS_DATA_H", file=H)
    print(file=H)
    print("#include <grpc/support/port_platform.h>", file=H)
    print(file=H)
    print("#include <inttypes.h>", file=H)
    print("#include \"src/core/lib/iomgr/exec_ctx.h\"", file=H)
    print(file=H)

    for typename, instances in sorted(inst_map.items()):
        print("typedef enum {", file=H)
        for inst in instances:
            print("  GRPC_STATS_%s_%s," % (typename.upper(), inst.name.upper()),
                  file=H)
        print("  GRPC_STATS_%s_COUNT" % (typename.upper()), file=H)
        print("} grpc_stats_%ss;" % (typename.lower()), file=H)
        print("extern const char *grpc_stats_%s_name[GRPC_STATS_%s_COUNT];" %
              (typename.lower(), typename.upper()),
              file=H)
        print("extern const char *grpc_stats_%s_doc[GRPC_STATS_%s_COUNT];" %
              (typename.lower(), typename.upper()),
              file=H)

    histo_start = []
    histo_buckets = []
    histo_bucket_boundaries = []

    print("typedef enum {", file=H)
    first_slot = 0
    for histogram in inst_map['Histogram']:
        histo_start.append(first_slot)
        histo_buckets.append(histogram.buckets)
        print("  GRPC_STATS_HISTOGRAM_%s_FIRST_SLOT = %d," %
              (histogram.name.upper(), first_slot),
              file=H)
        print("  GRPC_STATS_HISTOGRAM_%s_BUCKETS = %d," %
              (histogram.name.upper(), histogram.buckets),
              file=H)
        first_slot += histogram.buckets
    print("  GRPC_STATS_HISTOGRAM_BUCKETS = %d" % first_slot, file=H)
    print("} grpc_stats_histogram_constants;", file=H)

    print("#if defined(GRPC_COLLECT_STATS) || !defined(NDEBUG)", file=H)
    for ctr in inst_map['Counter']:
        print(("#define GRPC_STATS_INC_%s() " +
               "GRPC_STATS_INC_COUNTER(GRPC_STATS_COUNTER_%s)") %
              (ctr.name.upper(), ctr.name.upper()),
              file=H)
    for histogram in inst_map['Histogram']:
        print(
            "#define GRPC_STATS_INC_%s(value) grpc_stats_inc_%s( (int)(value))"
            % (histogram.name.upper(), histogram.name.lower()),
            file=H)
        print("void grpc_stats_inc_%s(int x);" % histogram.name.lower(), file=H)

    print("#else", file=H)
    for ctr in inst_map['Counter']:
        print(("#define GRPC_STATS_INC_%s() ") % (ctr.name.upper()), file=H)
    for histogram in inst_map['Histogram']:
        print("#define GRPC_STATS_INC_%s(value)" % (histogram.name.upper()),
              file=H)
    print("#endif /* defined(GRPC_COLLECT_STATS) || !defined(NDEBUG) */",
          file=H)

    for i, tbl in enumerate(static_tables):
        print("extern const %s grpc_stats_table_%d[%d];" %
              (tbl[0], i, len(tbl[1])),
              file=H)

    print("extern const int grpc_stats_histo_buckets[%d];" %
          len(inst_map['Histogram']),
          file=H)
    print("extern const int grpc_stats_histo_start[%d];" %
          len(inst_map['Histogram']),
          file=H)
    print("extern const int *const grpc_stats_histo_bucket_boundaries[%d];" %
          len(inst_map['Histogram']),
          file=H)
    print("extern void (*const grpc_stats_inc_histogram[%d])(int x);" %
          len(inst_map['Histogram']),
          file=H)

    print(file=H)
    print("#endif /* GRPC_CORE_LIB_DEBUG_STATS_DATA_H */", file=H)

with open('src/core/lib/debug/stats_data.cc', 'w') as C:
    # copy-paste copyright notice from this file
    with open(sys.argv[0]) as my_source:
        copyright = []
        for line in my_source:
            if line[0] != '#':
                break
        for line in my_source:
            if line[0] == '#':
                copyright.append(line)
                break
        for line in my_source:
            if line[0] != '#':
                break
            copyright.append(line)
        put_banner([C], [line[2:].rstrip() for line in copyright])

    put_banner(
        [C],
        ["Automatically generated by tools/codegen/core/gen_stats_data.py"])

    print("#include <grpc/support/port_platform.h>", file=C)
    print(file=C)
    print("#include \"src/core/lib/debug/stats.h\"", file=C)
    print("#include \"src/core/lib/debug/stats_data.h\"", file=C)
    print("#include \"src/core/lib/gpr/useful.h\"", file=C)
    print("#include \"src/core/lib/iomgr/exec_ctx.h\"", file=C)
    print(file=C)

    histo_code = []
    for histogram in inst_map['Histogram']:
        code, bounds_idx = gen_bucket_code(histogram)
        histo_bucket_boundaries.append(bounds_idx)
        histo_code.append(code)

    for typename, instances in sorted(inst_map.items()):
        print("const char *grpc_stats_%s_name[GRPC_STATS_%s_COUNT] = {" %
              (typename.lower(), typename.upper()),
              file=C)
        for inst in instances:
            print("  %s," % c_str(inst.name), file=C)
        print("};", file=C)
        print("const char *grpc_stats_%s_doc[GRPC_STATS_%s_COUNT] = {" %
              (typename.lower(), typename.upper()),
              file=C)
        for inst in instances:
            print("  %s," % c_str(inst.doc), file=C)
        print("};", file=C)

    for i, tbl in enumerate(static_tables):
        print("const %s grpc_stats_table_%d[%d] = {%s};" %
              (tbl[0], i, len(tbl[1]), ','.join('%s' % x for x in tbl[1])),
              file=C)

    for histogram, code in zip(inst_map['Histogram'], histo_code):
        print(("void grpc_stats_inc_%s(int value) {%s}") %
              (histogram.name.lower(), code),
              file=C)

    print(
        "const int grpc_stats_histo_buckets[%d] = {%s};" %
        (len(inst_map['Histogram']), ','.join('%s' % x for x in histo_buckets)),
        file=C)
    print("const int grpc_stats_histo_start[%d] = {%s};" %
          (len(inst_map['Histogram']), ','.join('%s' % x for x in histo_start)),
          file=C)
    print("const int *const grpc_stats_histo_bucket_boundaries[%d] = {%s};" %
          (len(inst_map['Histogram']), ','.join(
              'grpc_stats_table_%d' % x for x in histo_bucket_boundaries)),
          file=C)
    print("void (*const grpc_stats_inc_histogram[%d])(int x) = {%s};" %
          (len(inst_map['Histogram']), ','.join(
              'grpc_stats_inc_%s' % histogram.name.lower()
              for histogram in inst_map['Histogram'])),
          file=C)

# patch qps_test bigquery schema
RECORD_EXPLICIT_PERCENTILES = [50, 95, 99]

with open('tools/run_tests/performance/scenario_result_schema.json', 'r') as f:
    qps_schema = json.loads(f.read())

def FindNamed(js, name):
    for el in js:
        if el['name'] == name:
            return el

def RemoveCoreFields(js):
    new_fields = []
    for field in js['fields']:
        if not field['name'].startswith('core_'):
            new_fields.append(field)
    js['fields'] = new_fields

RemoveCoreFields(FindNamed(qps_schema, 'clientStats'))
RemoveCoreFields(FindNamed(qps_schema, 'serverStats'))

def AddCoreFields(js):
    for counter in inst_map['Counter']:
        js['fields'].append({
            'name': 'core_%s' % counter.name,
            'type': 'INTEGER',
            'mode': 'NULLABLE'
        })
    for histogram in inst_map['Histogram']:
        js['fields'].append({
            'name': 'core_%s' % histogram.name,
            'type': 'STRING',
            'mode': 'NULLABLE'
        })
        js['fields'].append({
            'name': 'core_%s_bkts' % histogram.name,
            'type': 'STRING',
            'mode': 'NULLABLE'
        })
        for pctl in RECORD_EXPLICIT_PERCENTILES:
            js['fields'].append({
                'name': 'core_%s_%dp' % (histogram.name, pctl),
                'type': 'FLOAT',
                'mode': 'NULLABLE'
            })

AddCoreFields(FindNamed(qps_schema, 'clientStats'))
AddCoreFields(FindNamed(qps_schema, 'serverStats'))

with open('tools/run_tests/performance/scenario_result_schema.json', 'w') as f:
    f.write(json.dumps(qps_schema, indent=2, sort_keys=True))

# and generate a helper script to massage scenario results into the format we'd
# like to query
with open('tools/run_tests/performance/massage_qps_stats.py', 'w') as P:
    with open(sys.argv[0]) as my_source:
        for line in my_source:
            if line[0] != '#':
                break
        for line in my_source:
            if line[0] == '#':
                print(line.rstrip(), file=P)
                break
        for line in my_source:
            if line[0] != '#':
                break
            print(line.rstrip(), file=P)

    print(file=P)
    print('# Autogenerated by tools/codegen/core/gen_stats_data.py', file=P)
    print(file=P)

    print('import massage_qps_stats_helpers', file=P)

    print('def massage_qps_stats(scenario_result):', file=P)
    print(
        '  for stats in scenario_result["serverStats"] + scenario_result["clientStats"]:',
        file=P)
    print('    if "coreStats" in stats:', file=P)
    print(
        '      # Get rid of the "coreStats" element and replace it by statistics',
        file=P)
    print('      # that correspond to columns in the bigquery schema.', file=P)
    print('      core_stats = stats["coreStats"]', file=P)
    print('      del stats["coreStats"]', file=P)
    for counter in inst_map['Counter']:
        print(
            '      stats["core_%s"] = massage_qps_stats_helpers.counter(core_stats, "%s")'
            % (counter.name, counter.name),
            file=P)
    for i, histogram in enumerate(inst_map['Histogram']):
        print(
            '      h = massage_qps_stats_helpers.histogram(core_stats, "%s")' %
            histogram.name,
            file=P)
        print(
            '      stats["core_%s"] = ",".join("%%f" %% x for x in h.buckets)' %
            histogram.name,
            file=P)
        print(
            '      stats["core_%s_bkts"] = ",".join("%%f" %% x for x in h.boundaries)'
            % histogram.name,
            file=P)
        for pctl in RECORD_EXPLICIT_PERCENTILES:
            print(
                '      stats["core_%s_%dp"] = massage_qps_stats_helpers.percentile(h.buckets, %d, h.boundaries)'
                % (histogram.name, pctl, pctl),
                file=P)

with open('src/core/lib/debug/stats_data_bq_schema.sql', 'w') as S:
    columns = []
    for counter in inst_map['Counter']:
        columns.append(('%s_per_iteration' % counter.name, 'FLOAT'))
    print(',\n'.join('%s:%s' % x for x in columns), file=S)


text:
@(title: String)(content: Html)

@cssExtra = {
    <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/bootstrap.css")">
    <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/bootstrap-responsive.min.css")">
    <link rel="stylesheet" media="screen" href="@routes.Assets.at("stylesheets/main.css")">
}

@jsExtra = {

}

@header = {

Something in the header

}

@footer = {

Something in the footer

}

@h5bp.index("My Site - " + title)("My site - This is the site description.")(cssExtra)(jsExtra)(header){
    @content
}(footer)


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/speech/v1/cloud_speech.proto

package com.google.cloud.speech.v1;

public interface RecognitionConfigOrBuilder extends
    // @@protoc_insertion_point(interface_extends:google.cloud.speech.v1.RecognitionConfig)
    com.google.protobuf.MessageOrBuilder {

  /**
   *

   * *Required* Encoding of audio data sent in all `RecognitionAudio` messages.
   *

   *
   * .google.cloud.speech.v1.RecognitionConfig.AudioEncoding encoding = 1;
   */
  int getEncodingValue();
  /**
   *

   * *Required* Encoding of audio data sent in all `RecognitionAudio` messages.
   *

   *
   * .google.cloud.speech.v1.RecognitionConfig.AudioEncoding encoding = 1;
   */
  com.google.cloud.speech.v1.RecognitionConfig.AudioEncoding getEncoding();

  /**
   *

   * *Required* Sample rate in Hertz of the audio data sent in all
   * `RecognitionAudio` messages. Valid values are: 8000-48000.
   * 16000 is optimal. For best results, set the sampling rate of the audio
   * source to 16000 Hz. If that's not possible, use the native sample rate of
   * the audio source (instead of re-sampling).
   *

   *
   * int32 sample_rate_hertz = 2;
   */
  int getSampleRateHertz();

  /**
   *

   * *Required* The language of the supplied audio as a
   * [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
   * Example: "en-US".
   * See [Language Support](https://cloud.google.com/speech/docs/languages)
   * for a list of the currently supported language codes.
   *

   *
   * string language_code = 3;
   */
  java.lang.String getLanguageCode();
  /**
   *

   * *Required* The language of the supplied audio as a
   * [BCP-47](https://www.rfc-editor.org/rfc/bcp/bcp47.txt) language tag.
   * Example: "en-US".
   * See [Language Support](https://cloud.google.com/speech/docs/languages)
   * for a list of the currently supported language codes.
   *

   *
   * string language_code = 3;
   */
  com.google.protobuf.ByteString
      getLanguageCodeBytes();

  /**
   *

   * *Optional* Maximum number of recognition hypotheses to be returned.
   * Specifically, the maximum number of `SpeechRecognitionAlternative` messages
   * within each `SpeechRecognitionResult`.
   * The server may return fewer than `max_alternatives`.
   * Valid values are `0`-`30`. A value of `0` or `1` will return a maximum of
   * one. If omitted, will return a maximum of one.
   *

   *
   * int32 max_alternatives = 4;
   */
  int getMaxAlternatives();

  /**
   *

   * *Optional* If set to `true`, the server will attempt to filter out
   * profanities, replacing all but the initial character in each filtered word
   * with asterisks, e.g. "f***". If set to `false` or omitted, profanities
   * won't be filtered out.
   *

   *
   * bool profanity_filter = 5;
   */
  boolean getProfanityFilter();

  /**
   *

   * *Optional* A means to provide context to assist the speech recognition.
   *

   *
   * repeated .google.cloud.speech.v1.SpeechContext speech_contexts = 6;
   */
  java.util.List<com.google.cloud.speech.v1.SpeechContext>
      getSpeechContextsList();
  /**
   *

   * *Optional* A means to provide context to assist the speech recognition.
   *

   *
   * repeated .google.cloud.speech.v1.SpeechContext speech_contexts = 6;
   */
  com.google.cloud.speech.v1.SpeechContext getSpeechContexts(int index);
  /**
   *

   * *Optional* A means to provide context to assist the speech recognition.
   *

   *
   * repeated .google.cloud.speech.v1.SpeechContext speech_contexts = 6;
   */
  int getSpeechContextsCount();
  /**
   *

   * *Optional* A means to provide context to assist the speech recognition.
   *

   *
   * repeated .google.cloud.speech.v1.SpeechContext speech_contexts = 6;
   */
  java.util.List<? extends com.google.cloud.speech.v1.SpeechContextOrBuilder>
      getSpeechContextsOrBuilderList();
  /**
   *

   * *Optional* A means to provide context to assist the speech recognition.
   *

   *
   * repeated .google.cloud.speech.v1.SpeechContext speech_contexts = 6;
   */
  com.google.cloud.speech.v1.SpeechContextOrBuilder getSpeechContextsOrBuilder(
      int index);
}


text:
using System;
using System.Linq;
using FluentAssertions;
using Xunit;

namespace Neo4j.Driver.IntegrationTests.Stress
{
    public class BlockingWrongCommand<TContext> : BlockingCommand<TContext>
        where TContext : StressTestContext
    {
        public BlockingWrongCommand(IDriver driver)
            : base(driver, false)
        {
        }

        public override void Execute(TContext context)
        {
            using (var session = NewSession(AccessMode.Read, context))
            {
                var exc = Record.Exception(() => session.Run("RETURN").Consume());
                exc.Should().BeOfType<ClientException>().Which.Code.Should().Be("Neo.ClientError.Statement.SyntaxError");
            }
        }
    }
}


text:
'use strict';

var parser = require('../../../lib/index.js').flat;

var identifier = require('./identifier.js');
var typename = require('./typename.js');

module.exports = parser.name('argumentList', parser.list(
  parser.labelledSequence(
    ['type', typename],
    parser.whitespace,
    ['name', identifier]
  ),
  parser.wrapOptionalWhitespace(
    parser.single(',')
  )
));


text:
package org.apache.hadoop.filecache;

/**
 * Class is moved to a new package org.apache.hadoop.mapreduce.filecache
 *
 * @deprecated Instead use
 *             {@link org.apache.hadoop.mapreduce.filecache.DistributedCache}
 *
 */
@Deprecated
public class DistributedCache extends
    org.apache.hadoop.mapreduce.filecache.DistributedCache {
  //
}