text:
<?php

namespace NivaShs\SmppBundle\SmppLib;

use \ArrayIterator;
use \InvalidArgumentException;

use NivaShs\SmppBundle\SmppLib\SocketTransportException;

class SocketTransport
{
	protected $socket;
	protected $hosts;
	protected $persist;
	protected $debugHandler;
	public $debug;

	protected static $defaultSendTimeout=100;
	protected static $defaultRecvTimeout=750;
	public static $defaultDebug=false;

	public static $forceIpv6=false;
	public static $forceIpv4=false;
	public static $randomHost=false;

	/**
	 * Construct a new socket for this transport to use.
	 *
	 * @param array $hosts list of hosts to try.
	 * @param mixed $ports list of ports to try, or a single common port
	 * @param boolean $persist use persistent sockets
	 * @param mixed $debugHandler callback for debug info
	 */
	public function __construct(array $hosts,$ports,$persist=false,$debugHandler=null)
	{
		$this->debug = self::$defaultDebug;
		$this->debugHandler = $debugHandler ? $debugHandler : 'error_log';

		// Deal with optional port
		$h = array();
		foreach ($hosts as $key => $host) {
			$h[] = array($host, is_array($ports) ? $ports[$key] : $ports);
		}
		if (self::$randomHost) shuffle($h);
		$this->resolveHosts($h);

		$this->persist = $persist;
	}

	/**
	 * Resolve the hostnames into IPs, and sort them into IPv4 or IPv6 groups.
	 * If using DNS hostnames, and all lookups fail, a InvalidArgumentException is thrown.
	 *
	 * @param array $hosts
	 * @throws InvalidArgumentException
	 */
	protected function resolveHosts($hosts)
	{
		$i = 0;
		foreach($hosts as $host) {
			list($hostname,$port) = $host;
			$ip4s = array();
			$ip6s = array();
			if (preg_match('/^([12]?[0-9]?[0-9]\.){3}([12]?[0-9]?[0-9])$/',$hostname)) {
				// IPv4 address
				$ip4s[] = $hostname;
			} else if (preg_match('/^([0-9a-f:]+):[0-9a-f]{1,4}$/i',$hostname)) {
				// IPv6 address
				$ip6s[] = $hostname;
			} else { // Do a DNS lookup
				if (!self::$forceIpv4) {
					// if not in IPv4 only mode, check the AAAA records first
					$records = dns_get_record($hostname,DNS_AAAA);
					if ($records === false && $this->debug) call_user_func($this->debugHandler, 'DNS lookup for AAAA records for: '.$hostname.' failed');
					if ($records) {
						foreach ($records as $r) {
							if (isset($r['ipv6']) && $r['ipv6']) $ip6s[] = $r['ipv6'];
						}
					}
					if ($this->debug) call_user_func($this->debugHandler, "IPv6 addresses for $hostname: ".implode(', ',$ip6s));
				}
				if (!self::$forceIpv6) {
					// if not in IPv6 mode check the A records also
					$records = dns_get_record($hostname,DNS_A);
					if ($records === false && $this->debug) call_user_func($this->debugHandler, 'DNS lookup for A records for: '.$hostname.' failed');
					if ($records) {
						foreach ($records as $r) {
							if (isset($r['ip']) && $r['ip']) $ip4s[] = $r['ip'];
						}
					}
					// also try gethostbyname, since name could also be something else, such as "localhost" etc.
					$ip = gethostbyname($hostname);
					if ($ip != $hostname && !in_array($ip,$ip4s)) $ip4s[] = $ip;
					if ($this->debug) call_user_func($this->debugHandler, "IPv4 addresses for $hostname: ".implode(', ',$ip4s));
				}
			}

			// Did we get any results?
			if (self::$forceIpv4 && empty($ip4s)) continue;
			if (self::$forceIpv6 && empty($ip6s)) continue;
			if (empty($ip4s) && empty($ip6s)) continue;

			if ($this->debug) $i += count($ip4s)+count($ip6s);

			// Add results to pool
			$this->hosts[] = array($hostname,$port,$ip6s,$ip4s);
		}
		if ($this->debug) call_user_func($this->debugHandler, "Built connection pool of ".count($this->hosts)." host(s) with $i ip(s) in total");
		if (empty($this->hosts)) throw new InvalidArgumentException('No valid hosts was found');
	}

	/**
	 * Get a reference to the socket.
	 * You should use the public functions rather than the socket directly
	 */
	public function getSocket()
	{
		return $this->socket;
	}

	/**
	 * Get an arbitrary option
	 *
	 * @param integer $option
	 * @param integer $lvl
	 */
	public function getSocketOption($option,$lvl=SOL_SOCKET)
	{
		return socket_get_option($this->socket,$lvl,$option);
	}

	/**
	 * Set an arbitrary option
	 *
	 * @param integer $option
	 * @param mixed $value
	 * @param integer $lvl
	 */
	public function setSocketOption($option,$value,$lvl=SOL_SOCKET)
	{
		return socket_set_option($this->socket,$lvl,$option,$value);
	}

	/**
	 * Sets the send timeout.
	 * Returns true on success, or false.
	 * @param int $timeout	Timeout in milliseconds.
	 * @return boolean
	 */
	public function setSendTimeout($timeout)
	{
		if (!$this->isOpen()) {
			self::$defaultSendTimeout = $timeout;
		} else {
			$r = socket_set_option($this->socket,SOL_SOCKET,SO_SNDTIMEO,$this->millisecToSolArray($timeout));
			return $r;
		}
	}

	/**
	 * Sets the receive timeout.
	 * Returns true on success, or false.
	 * @param int $timeout	Timeout in milliseconds.
	 * @return boolean
	 */
	public function setRecvTimeout($timeout)
	{
		if (!$this->isOpen()) {
			self::$defaultRecvTimeout = $timeout;
		} else {
			$r = socket_set_option($this->socket,SOL_SOCKET,SO_RCVTIMEO,$this->millisecToSolArray($timeout));
			return $r;
		}
	}

	/**
	 * Check if the socket is constructed, and there are no exceptions on it
	 * Returns false if it's closed.
	 * Throws SocketTransportException is state could not be ascertained
	 * @throws SocketTransportException
	 */
	public function isOpen()
	{
		if (!is_resource($this->socket)) return false;
		$r = null;
		$w = null;
		$e = array($this->socket);
		$res = socket_select($r,$w,$e,0);
		if ($res === false) throw new SocketTransportException('Could not examine socket; '.socket_strerror(socket_last_error()), socket_last_error());
		if (!empty($e)) return false; // if there is an exception on our socket it's probably dead
		return true;
	}

	/**
	 * Convert a milliseconds into a socket sec+usec array
	 * @param integer $millisec
	 * @return array
	 */
	private function millisecToSolArray($millisec)
	{
		$usec = $millisec*1000;
		return array('sec' => floor($usec/1000000), 'usec' => $usec%1000000);
	}

	/**
	 * Open the socket, trying to connect to each host in succession.
	 * This will prefer IPv6 connections if forceIpv4 is not enabled.
	 * If all hosts fail, a SocketTransportException is thrown.
	 *
	 * @throws SocketTransportException
	 */
	public function open()
	{
		if (!self::$forceIpv4) {
			$socket6 = @socket_create(AF_INET6,SOCK_STREAM,SOL_TCP);
			if ($socket6 == false) throw new SocketTransportException('Could not create socket; '.socket_strerror(socket_last_error()), socket_last_error());
			socket_set_option($socket6,SOL_SOCKET,SO_SNDTIMEO,$this->millisecToSolArray(self::$defaultSendTimeout));
			socket_set_option($socket6,SOL_SOCKET,SO_RCVTIMEO,$this->millisecToSolArray(self::$defaultRecvTimeout));
		}
		if (!self::$forceIpv6) {
			$socket4 = @socket_create(AF_INET,SOCK_STREAM,SOL_TCP);
			if ($socket4 == false) throw new SocketTransportException('Could not create socket; '.socket_strerror(socket_last_error()), socket_last_error());
			socket_set_option($socket4,SOL_SOCKET,SO_SNDTIMEO,$this->millisecToSolArray(self::$defaultSendTimeout));
			socket_set_option($socket4,SOL_SOCKET,SO_RCVTIMEO,$this->millisecToSolArray(self::$defaultRecvTimeout));
		}
		$it = new ArrayIterator($this->hosts);
		while ($it->valid()) {
			list($hostname,$port,$ip6s,$ip4s) = $it->current();
			if (!self::$forceIpv4 && !empty($ip6s)) { // Attempt IPv6s first
				foreach ($ip6s as $ip) {
					if ($this->debug) call_user_func($this->debugHandler, "Connecting to $ip:$port...");
					$r = @socket_connect($socket6, $ip, $port);
					if ($r) {
						if ($this->debug) call_user_func($this->debugHandler, "Connected to $ip:$port!");
						@socket_close($socket4);
						$this->socket = $socket6;
						return;
					} elseif ($this->debug) {
						call_user_func($this->debugHandler, "Socket connect to $ip:$port failed; ".socket_strerror(socket_last_error()));
					}
				}
			}
			if (!self::$forceIpv6 && !empty($ip4s)) {
				foreach ($ip4s as $ip) {
					if ($this->debug) call_user_func($this->debugHandler, "Connecting to $ip:$port...");
					$r = @socket_connect($socket4, $ip, $port);
					if ($r) {
						if ($this->debug) call_user_func($this->debugHandler, "Connected to $ip:$port!");
						@socket_close($socket6);
						$this->socket = $socket4;
						return;
					} elseif ($this->debug) {
						call_user_func($this->debugHandler, "Socket connect to $ip:$port failed; ".socket_strerror(socket_last_error()));
					}
				}
			}
			$it->next();
		}
		throw new SocketTransportException('Could not connect to any of the specified hosts');
	}

	/**
	 * Do a clean shutdown of the socket.
	 * Since we don't reuse sockets, we can just close and forget about it,
	 * but we choose to wait (linger) for the last data to come through.
	 */
	public function close()
	{
		$arrOpt = array('l_onoff' => 1, 'l_linger' => 1);
		socket_set_block($this->socket);
		socket_set_option($this->socket, SOL_SOCKET, SO_LINGER, $arrOpt);
		socket_close($this->socket);
	}

	/**
	 * Check if there is data waiting for us on the wire
	 * @return boolean
	 * @throws SocketTransportException
	 */
	public function hasData()
	{
		$r = array($this->socket);
		$w = null;
		$e = null;
		$res = socket_select($r,$w,$e,0);
		if ($res === false) throw new SocketTransportException('Could not examine socket; '.socket_strerror(socket_last_error()), socket_last_error());
		if (!empty($r)) return true;
		return false;
	}

	/**
	 * Read up to $length bytes from the socket.
	 * Does not guarantee that all the bytes are read.
	 * Returns false on EOF
	 * Returns false on timeout (technically EAGAIN error).
	 * Throws SocketTransportException if data could not be read.
	 *
	 * @param integer $length
	 * @return mixed
	 * @throws SocketTransportException
	 */
	public function read($length)
	{
		$d = socket_read($this->socket,$length,PHP_BINARY_READ);
		if ($d === false && socket_last_error() === SOCKET_EAGAIN) return false; // sockets give EAGAIN on timeout
		if ($d === false) throw new SocketTransportException('Could not read '.$length.' bytes from socket; '.socket_strerror(socket_last_error()), socket_last_error());
		if ($d === '') return false;
		return $d;
	}

	/**
	 * Read all the bytes, and block until they are read.
	 * Timeout throws SocketTransportException
	 *
	 * @param integer $length
	 */
	public function readAll($length)
	{
		$d = "";
		$r = 0;
		$readTimeout = socket_get_option($this->socket,SOL_SOCKET,SO_RCVTIMEO);
		while ($r < $length) {
			$buf = '';
			$r += socket_recv($this->socket,$buf,$length-$r,MSG_DONTWAIT);
			if ($r === false) throw new SocketTransportException('Could not read '.$length.' bytes from socket; '.socket_strerror(socket_last_error()), socket_last_error());
			$d .= $buf;
			if ($r == $length) return $d;

			// wait for data to be available, up to timeout
			$r = array($this->socket);
			$w = null;
			$e = array($this->socket);
			$res = socket_select($r,$w,$e,$readTimeout['sec'],$readTimeout['usec']);

			// check
			if ($res === false) throw new SocketTransportException('Could not examine socket; '.socket_strerror(socket_last_error()), socket_last_error());
			if (!empty($e)) throw new SocketTransportException('Socket exception while waiting for data; '.socket_strerror(socket_last_error()), socket_last_error());
			if (empty($r)) throw new SocketTransportException('Timed out waiting for data on socket');
		}
	}

	/**
	 * Write (all) data to the socket.
	 * Timeout throws SocketTransportException
	 *
	 * @param integer $length
	 */
	public function write($buffer,$length)
	{
		$r = $length;
		$writeTimeout = socket_get_option($this->socket,SOL_SOCKET,SO_SNDTIMEO);

		while ($r>0) {
			$wrote = socket_write($this->socket,$buffer,$r);
			if ($wrote === false) throw new SocketTransportException('Could not write '.$length.' bytes to socket; '.socket_strerror(socket_last_error()), socket_last_error());
			$r -= $wrote;
			if ($r == 0) return;

			$buffer = substr($buffer,$wrote);

			// wait for the socket to accept more data, up to timeout
			$r = null;
			$w = array($this->socket);
			$e = array($this->socket);
			$res = socket_select($r,$w,$e,$writeTimeout['sec'],$writeTimeout['usec']);

			// check
			if ($res === false) throw new SocketTransportException('Could not examine socket; '.socket_strerror(socket_last_error()), socket_last_error());
			if (!empty($e)) throw new SocketTransportException('Socket exception while waiting to write data; '.socket_strerror(socket_last_error()), socket_last_error());
			if (empty($w)) throw new SocketTransportException('Timed out waiting to write data on socket');
		}
	}
}


text:
package org.dspace.curate;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.net.URL;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import org.dspace.handle.HandleManager;
import org.dspace.app.util.DCInput;
import org.dspace.app.util.DCInputSet;
import org.dspace.app.util.DCInputsReader;
import org.dspace.app.util.DCInputsReaderException;
import org.dspace.content.DCValue;
import org.dspace.content.DSpaceObject;
import org.dspace.content.Item;
import org.dspace.content.Bundle;
import org.dspace.content.Bitstream;
import org.dspace.content.crosswalk.MetadataValidationException;
import org.dspace.core.ConfigurationManager;
import org.dspace.core.Context;
import org.dspace.core.Constants;
import org.dspace.identifier.IdentifierService;
import org.dspace.identifier.IdentifierNotFoundException;
import org.dspace.identifier.IdentifierNotResolvableException;
import org.dspace.utils.DSpace;

import org.apache.log4j.Logger;

/**
 * DataPackageStats retrieves detailed statistics about a data package.
 *
 * Some statistics are calculated based on the files that are contained in the
 * data package. Extra processing time is required to load and process the data
 * file metadata, so this report takes some time to run. For simpler information
 * about data packages, see DataPackageInfo.
 *
 * The task succeeds if it was able to locate all required stats, otherwise it fails.
 * Originally based on the RequiredMetadata task by Richard Rodgers.
 *
 * Input: a single data package OR a collection that contains data packages
 * Output: CSV file with appropriate stats
 * @author Ryan Scherle
 */
@Suspendable
public class DataPackageStats extends AbstractCurationTask {

    private static Logger log = Logger.getLogger(DataPackageStats.class);
    private IdentifierService identifierService = null;
    DocumentBuilderFactory dbf = null;
    DocumentBuilder docb = null;
    static long total = 0;
    private Context context;
    private static List<String> journalsThatAllowReview = new ArrayList<String>();
    private static List<String> integratedJournals = new ArrayList<String>();
    private static List<String> integratedJournalsThatAllowEmbargo = new ArrayList<String>();

    @Override
    public void init(Curator curator, String taskId) throws IOException {
        super.init(curator, taskId);

        identifierService = new DSpace().getSingletonService(IdentifierService.class);

	// init xml processing
	try {
	    dbf = DocumentBuilderFactory.newInstance();
	    docb = dbf.newDocumentBuilder();
	} catch (ParserConfigurationException e) {
	    throw new IOException("unable to initiate xml processor", e);
	}

	// init list of journals that support embargo and review
        String journalPropFile = ConfigurationManager.getProperty("submit.journal.config");
	log.info("initializing journal settings from property file " + journalPropFile);
        Properties properties = new Properties();
	try {
	    properties.load(new InputStreamReader(new FileInputStream(journalPropFile), "UTF-8"));
	    String journalTypes = properties.getProperty("journal.order");
	    for (int i = 0; i < journalTypes.split(",").length; i++) {
		String journalType = journalTypes.split(",")[i].trim();
		String journalDisplay = properties.getProperty("journal." + journalType + ".fullname");
		String integrated = properties.getProperty("journal." + journalType + ".integrated");
		String embargo = properties.getProperty("journal." + journalType + ".embargoAllowed", "true");
		String allowReviewWorkflow = properties.getProperty("journal." + journalType + ".allowReviewWorkflow", "false");

		if(integrated != null && Boolean.valueOf(integrated)) {
		    integratedJournals.add(journalDisplay);
		}
		if(allowReviewWorkflow != null && Boolean.valueOf(allowReviewWorkflow)) {
		    journalsThatAllowReview.add(journalDisplay);
		}
		if(embargo != null && Boolean.valueOf(embargo)) {
		    integratedJournalsThatAllowEmbargo.add(journalDisplay);
		}
	    }
	} catch(Exception e) {
	    log.error("Unable to initialize the journal settings");
	}
    }

    /**
     * Perform the curation task upon passed DSO
     *
     * @param dso the DSpace object
     * @throws IOException
     */
    @Override
    public int perform(DSpaceObject dso) throws IOException {
	log.info("performing DataPackageStats task " + total++ );

	String handle = "\"[no handle found]\"";
	String packageDOI = "\"[no package DOI found]\"";
	String articleDOI = "\"[no article DOI found]\"";
	String journal = "[no journal found]"; // don't add quotes here, because journal is always quoted when output below
	boolean journalAllowsEmbargo = false;
	boolean journalAllowsReview = false;
	String numKeywords = "\"[no numKeywords found]\"";
	String numKeywordsJournal = "\"[unknown]\"";
	String numberOfFiles = "\"[no numberOfFiles found]\"";
	long packageSize = 0;
	String embargoType = "none";
	String embargoDate = "";
	int maxDownloads = 0;
	String numberOfDownloads = "\"[unknown]\"";
	String manuscriptNum = null;
	int numReadmes = 0;
	boolean wentThroughReview = false;
	String dateAccessioned = "\"[unknown]\"";

	try {
	    context = new Context();
        } catch (SQLException e) {
	    log.fatal("Unable to open database connection", e);
	    return Curator.CURATE_FAIL;
	}

	if (dso.getType() == Constants.COLLECTION) {
	    // output headers for the CSV file that will be created by processing all items in this collection
	    report("handle, packageDOI, articleDOI, journal, journalAllowsEmbargo, journalAllowsReview, numKeywords, numKeywordsJournal, numberOfFiles, packageSize, " +
		   "embargoType, embargoDate, numberOfDownloads, manuscriptNum, numReadmes, wentThroughReview, dateAccessioned");
	} else if (dso.getType() == Constants.ITEM) {
            Item item = (Item)dso;

	    try {
		handle = item.getHandle();
		log.info("handle = " + handle);

		if (handle == null) {
		    // this item is still in workflow - no handle assigned
		    handle = "in workflow";
		}

		// package DOI
		DCValue[] vals = item.getMetadata("dc.identifier");
		if (vals.length == 0) {
		    setResult("Object has no dc.identifier available " + handle);
		    log.error("Skipping -- no dc.identifier available for " + handle);
		    context.abort();
		    return Curator.CURATE_SKIP;
		} else {
		    for(int i = 0; i < vals.length; i++) {
			if (vals[i].value.startsWith("doi:")) {
			    packageDOI = vals[i].value;
			}
		    }
		}
		log.debug("packageDOI = " + packageDOI);

		// article DOI
		vals = item.getMetadata("dc.relation.isreferencedby");
		if (vals.length == 0) {
		    log.debug("Object has no articleDOI (dc.relation.isreferencedby) " + handle);
		} else {
		    articleDOI = vals[0].value;
		}
		log.debug("articleDOI = " + articleDOI);

		// journal
	 	vals = item.getMetadata("prism.publicationName");
		if (vals.length == 0) {
		    setResult("Object has no prism.publicationName available " + handle);
		    log.error("Skipping -- Object has no prism.publicationName available " + handle);
		    context.abort();
		    return Curator.CURATE_SKIP;
		} else {
		    journal = vals[0].value;
		}
		log.debug("journal = " + journal);

		// journalAllowsEmbargo
		// embargoes are allowed for all non-integrated journals
		// embargoes are also allowed for integrated journals that have set the embargoesAllowed option
		if(!integratedJournals.contains(journal) || integratedJournalsThatAllowEmbargo.contains(journal)) {
		    journalAllowsEmbargo = true;
		}

		// journalAllowsReview
		if(journalsThatAllowReview.contains(journal)) {
		    journalAllowsReview = true;
		}

		// accession date
		vals = item.getMetadata("dc.date.accessioned");
		if (vals.length == 0) {
		    setResult("Object has no dc.date.accessioned available " + handle);
		    log.error("Skipping -- Object has no dc.date.accessioned available " + handle);
		    context.abort();
		    return Curator.CURATE_SKIP;
		} else {
		    dateAccessioned = vals[0].value;
		}
		log.debug("dateAccessioned = " + dateAccessioned);

		// wentThroughReview
		vals = item.getMetadata("dc.description.provenance");
		if (vals.length == 0) {
		    log.warn("That's strange -- Object has no provenance data available " + handle);
		} else {
		    for(DCValue aVal : vals) {
			if(aVal.value != null && aVal.value.contains("requiresReviewStep")) {
			    wentThroughReview = true;
			}
		    }
		}
		log.debug("wentThroughReview = " + wentThroughReview);

		// number of keywords
		int intNumKeywords = item.getMetadata("dc.subject").length +
		    item.getMetadata("dwc.ScientificName").length +
		    item.getMetadata("dc.coverage.temporal").length +
		    item.getMetadata("dc.coverage.spatial").length;

		numKeywords = "" + intNumKeywords; //convert integer to string by appending
		log.debug("numKeywords = " + numKeywords);

		// manuscript number
		DCValue[] manuvals = item.getMetadata("dc.identifier.manuscriptNumber");
		manuscriptNum = null;
		if(manuvals.length > 0) {
		    manuscriptNum = manuvals[0].value;
		}
		if(manuscriptNum != null && manuscriptNum.trim().length() > 0) {
		    log.debug("has a real manuscriptNum = " + manuscriptNum);

		    /*
		    // number of keywords in journal email -- currently commented out because it wasn't working for 2012 and later.

		    //find metadata file for the manuscript
		    int firstdash = manuscriptNum.indexOf("-");
		    String journalAbbrev = manuscriptNum.substring(0, firstdash);
		    if(journalAbbrev.startsWith("0") ||
		       journalAbbrev.startsWith("1") ||
		       journalAbbrev.startsWith("2") ||
		       journalAbbrev.startsWith("3") ||
		       journalAbbrev.startsWith("4") ||
		       journalAbbrev.startsWith("5") ||
		       journalAbbrev.startsWith("6") ||
		       journalAbbrev.startsWith("7") ||
		       journalAbbrev.startsWith("8") ||
		       journalAbbrev.startsWith("9")) {
			//handle older manuscript numbers from amnat
			journalAbbrev = "amNat";
			manuscriptNum = "amNat-" + manuscriptNum;
			firstdash = 5;
		    }

		    if(!journalAbbrev.equals("new")) {
			numKeywordsJournal = "0";
			String journalDir="/opt/dryad/submission/journalMetadata/";
			manuscriptNum = manuscriptNum.substring(firstdash + 1);
			int lastdash = manuscriptNum.lastIndexOf("-");
			if(lastdash >= 0) {
			    manuscriptNum = manuscriptNum.substring(0, lastdash);
			    File journalFile = new File(journalDir + journalAbbrev + "/" + manuscriptNum + ".xml");

			    //get keywords from the file and count them
			    if(journalFile.exists()) {
				Document journaldoc = docb.parse(new FileInputStream(journalFile));
				NodeList nl = journaldoc.getElementsByTagName("keyword");
				numKeywordsJournal = "" + nl.getLength();
			    } else {
				report("Unable to find journal file " + journalFile);
				log.error("Unable to find journal file " + journalFile);
			    }
			} else {
			    report("Unable to parse manuscript number " +  manuvals[0].value);
			    log.error("Unable to parse manuscript number " +  manuvals[0].value);
			}
			log.debug("numKeywordsJournal = " + numKeywordsJournal);
		     }
		    */
		}

		// count the files, and compute statistics that depend on the files
		log.debug("getting data file info");
		DCValue[] dataFiles = item.getMetadata("dc.relation.haspart");
		if (dataFiles.length == 0) {
		    setResult("Object has no dc.relation.haspart available " + handle);
		    log.error("Skipping -- Object has no dc.relation.haspart available " + handle);
		    context.abort();
		    return Curator.CURATE_SKIP;
		} else {
		    numberOfFiles = "" + dataFiles.length;
		    packageSize = 0;

		    // for each data file in the package

		    for(int i = 0; i < dataFiles.length; i++) {
			String fileID = dataFiles[i].value;
			log.debug(" ======= processing fileID = " + fileID);

			// get the DSpace Item for this fileID
			Item fileItem = getDSpaceItem(fileID);

			if(fileItem == null) {
			    log.error("Skipping data file -- it's null");
			    break;
			}
			log.debug("file internalID = " + fileItem.getID());

			// total package size
			// add total size of the bitstreams in this data file
			// to the cumulative total for the package
			// (includes metadata, readme, and textual conversions for indexing)
			for (Bundle bn : fileItem.getBundles()) {
			    for (Bitstream bs : bn.getBitstreams()) {
				packageSize = packageSize + bs.getSize();
			    }
			}
			log.debug("total package size (as of file " + fileID + ") = " + packageSize);

			// Readmes
			// Check for at least one readme bitstream. There may be more, due to indexing and cases
			// where the file itself is named readme. We only count one readme per datafile.
			boolean readmeFound = false;
			for (Bundle bn : fileItem.getBundles()) {
			    for (Bitstream bs : bn.getBitstreams()) {
				String name = bs.getName().trim().toLowerCase();
				if(name.startsWith("readme")) {
				    readmeFound = true;
				}
			    }
			}
			if(readmeFound) {
			    numReadmes++;
			}
			log.debug("total readmes (as of file " + fileID + ") = " + numReadmes);

			// embargo setting (of last file processed)
			vals = fileItem.getMetadata("dc.type.embargo");
			if (vals.length > 0) {
			    embargoType = vals[0].value;
			    log.debug("EMBARGO vals " + vals.length + " type " + embargoType);
			}
			vals = fileItem.getMetadata("dc.date.embargoedUntil");
			if (vals.length > 0) {
			    embargoDate = vals[0].value;
			}
			if((embargoType == null || embargoType.equals("") || embargoType.equals("none")) &&
			   (embargoDate != null && !embargoDate.equals(""))) {
			    // correctly encode embago type to "oneyear" if there is a date set, but the type is blank or none
			    embargoType = "oneyear";
			}
			log.debug("embargoType = " + embargoType);
			log.debug("embargoDate = " + embargoDate);

			// number of downlaods for most downloaded file
			// must use the DSpace item ID, since the solr stats system is based on this ID
			// The SOLR address is hardcoded to the production system here, because even when we run on test servers,
			// it's easiest to use the real stats --the test servers typically don't have useful stats available
			URL downloadStatURL = new URL("http://datadryad.org/solr/statistics/select/?indent=on&q=owningItem:" + fileItem.getID());
			log.debug("fetching " + downloadStatURL);
			Document statsdoc = docb.parse(downloadStatURL.openStream());
			NodeList nl = statsdoc.getElementsByTagName("result");
			String downloadsAtt = nl.item(0).getAttributes().getNamedItem("numFound").getTextContent();
			int currDownloads = Integer.parseInt(downloadsAtt);
			if(currDownloads > maxDownloads) {
			    maxDownloads = currDownloads;
			    // rather than converting maxDownloads back to a string, just use the string we parsed above
			    numberOfDownloads = downloadsAtt;
			}
			log.debug("max downloads (as of file " + fileID + ") = " + numberOfDownloads);

		    }

		}
		log.info(handle + " done.");
	    } catch (Exception e) {
		log.fatal("Skipping -- Exception in processing " + handle, e);
		setResult("Object has a fatal error: " + handle + "\n" + e.getMessage());
		report("Object has a fatal error: " + handle + "\n" + e.getMessage());

		context.abort();
		return Curator.CURATE_SKIP;
	    }
	} else {
	    log.info("Skipping -- non-item DSpace object");
	    setResult("Object skipped (not an item)");
	    context.abort();
	    return Curator.CURATE_SKIP;
        }

	setResult("Last processed item = " + handle + " -- " + packageDOI);
	report(handle + ", " + packageDOI + ", " + articleDOI + ", \"" + journal + "\", " +
	       journalAllowsEmbargo + ", " + journalAllowsReview + ", " + numKeywords + ", " +
	       numKeywordsJournal + ", " + numberOfFiles + ", " + packageSize + ", " +
	       embargoType + ", " + embargoDate + ", " + numberOfDownloads + ", " + manuscriptNum + ", " +
	       numReadmes + ", " + wentThroughReview + ", " + dateAccessioned);

	// slow this down a bit so we don't overwhelm the production SOLR server with requests
	try {
	    Thread.sleep(20);
	} catch(InterruptedException e) {
	    // ignore it
	}

	log.debug("DataPackageStats complete");

	try {
	    context.complete();
        } catch (SQLException e) {
	    log.fatal("Unable to close database connection", e);
	}
	return Curator.CURATE_SUCCESS;
    }

    /**
       An XML utility method that returns the text content of a node.
    **/
    private String getNodeText(Node aNode) {
	return aNode.getChildNodes().item(0).getNodeValue();
    }

    private Item getDSpaceItem(String itemID) {
	Item dspaceItem = null;
	try {
	    dspaceItem = (Item)identifierService.resolve(context, itemID);
        } catch (IdentifierNotFoundException e) {
	    log.fatal("Unable to get DSpace Item for " + itemID, e);
	} catch (IdentifierNotResolvableException e) {
	    log.fatal("Unable to get DSpace Item for " + itemID, e);
	}

	return dspaceItem;
    }

}

redpajama_set_name: RedPajamaGithub


text:
package gnu.CORBA;

import org.omg.CORBA.BAD_OPERATION;
import org.omg.CORBA.TypeCode;
import org.omg.CORBA.UNKNOWN;
import org.omg.CORBA.portable.InputStream;
import org.omg.CORBA.portable.OutputStream;
import org.omg.CORBA.portable.Streamable;

/**
 * This holder can store any CORBA exception that has no user defined fields.
 * Only the repository ID is written when the method {@link #_write} is called.
 * The _read method is not supported for this holder.
 *
 * @author Audrius Meskauskas, Lithuania (AudriusA@Bioinformatics.org)
 */
public class EmptyExceptionHolder
  implements Streamable
{
  /**
   * The wrapped exception.
   */
  public Throwable value;

  /**
   * The typecode of the wrapped exception.
   */
  public TypeCode typecode;

  /**
   * Create the exception holder, initialised to the given values.
   *
   * @param an_exception the wrapped exception.
   * @param an_id the exception repository id.
   */
  public EmptyExceptionHolder(Throwable an_exception, TypeCode a_typecode)
  {
    value = an_exception;
    typecode = a_typecode;
  }

  /**
   * Reads the exception from the input stream.
   *
   * The value field obtains the value of either the read exception or
   * the UNKNOWN if the repository ID does not match
   * the exception from the reachable code.
   */
  public void _read(InputStream input)
  {
    String id = input.read_string();
    Object ex = ObjectCreator.Idl2Object(id);
    if (ex == null)
      value = new UNKNOWN(id);
    else
      value = (Throwable) ex;
  }

  /**
   * Return the typecode of the stored exception.
   *
   * @return the value, passed as a_typecode in constructor.
   */
  public TypeCode _type()
  {
    return typecode;
  }

  /**
   * Write the exception into the give output stream. Writes the
   * repository id that is taken from the typecode. This method also
   * works when no helper class is available.
   *
   * @param output a stream to write into.
   *
   * @throws BAD_OPERATION if the value for the holder is not set or
   * the typecode cannot provide repository id.
   */
  public void _write(OutputStream output)
  {
    try
      {
        output.write_string(typecode.id());
      }
    catch (Exception ex)
      {
        BAD_OPERATION bad = new BAD_OPERATION();
        bad.minor = Minor.CDR;
        bad.initCause(ex);
        throw bad;
      }
  }
}


text:
package com.intellij.openapi.components;

import org.jdom.Element;

public interface PathMacroSubstitutor {
  String expandPath(String path);
  String collapsePath(String path);

  void expandPaths(Element element);
  void collapsePaths(Element element);
}


text:
package com.ibasco.agql.protocols.supercell.coc.webapi.pojos;

import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
import org.jetbrains.annotations.ApiStatus;

/**
 * Created by raffy on 10/28/2016.
 *
 * @author Rafael Luis Ibasco
 */
@Deprecated
@ApiStatus.ScheduledForRemoval
public class CocClanBadgeUrls {

    private String small;

    private String medium;

    private String large;

    /** {@inheritDoc} */
    @Override
    public String toString() {
        return new ToStringBuilder(this, ToStringStyle.NO_CLASS_NAME_STYLE)
                .append("small", getSmall())
                .append("medium", getMedium())
                .append("large", getLarge())
                .toString();
    }

    /**
     *
Getter for the field small.

     *
     * @return a {@link java.lang.String} object
     */
    public String getSmall() {
        return small;
    }

    /**
     *
Setter for the field small.

     *
     * @param small
     *         a {@link java.lang.String} object
     */
    public void setSmall(String small) {
        this.small = small;
    }

    /**
     *
Getter for the field medium.

     *
     * @return a {@link java.lang.String} object
     */
    public String getMedium() {
        return medium;
    }

    /**
     *
Setter for the field medium.

     *
     * @param medium
     *         a {@link java.lang.String} object
     */
    public void setMedium(String medium) {
        this.medium = medium;
    }

    /**
     *
Getter for the field large.

     *
     * @return a {@link java.lang.String} object
     */
    public String getLarge() {
        return large;
    }

    /**
     *
Setter for the field large.

     *
     * @param large
     *         a {@link java.lang.String} object
     */
    public void setLarge(String large) {
        this.large = large;
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

  <TITLE>tracetcp</TITLE>
  <LINK REV="made" HREF="mailto:">
  <META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=UTF-8">
  <META NAME="generator" CONTENT="NoteTab Light 4.95">
  <META NAME="author" CONTENT="">
  <META NAME="description" CONTENT="">
  <META NAME="keywords" CONTENT="trace route traceroute tracert winsock WIN32 raw sockets">

Welcome to tracetcp.

tracetcp is a command line traceroute utility for WIN32 that uses TCP SYN packets rather than ICMP/UDP packets that the usual implementations use, thus bypassing gateways that block traditional traceroute packets.

In addition to providing the functionality of the standard traceroute utility tracetcp allows a trace to be performed over any TCP port. This allows the discovery of what ports a filewall blocks & and also the presence of any transparent proxies that have been put in place.

NEWS:

23-May-2005: New version (0.99.4beta) Fixed problem with inaccurate hop timings.

21-May-2005: New version (0.99.3beta) now functions under Windows XP Service Pack 2, by using winpcap library. Please make sure you download and install winpcap from here before using the new version of tracetcp.
 see the readme.txt in the download zip file for more information.


text:
// Copyright (c) Microsoft Open Technologies, Inc.  All Rights Reserved.  Licensed under the Apache License, Version 2.0.  See License.txt in the project root for license information.

using System.Collections.Generic;
using System.Runtime.CompilerServices;
using Roslyn.Utilities;

namespace Microsoft.CodeAnalysis.CodeGeneration
{
    internal class CodeGenerationMethodInfo
    {
        private static readonly ConditionalWeakTable<IMethodSymbol, CodeGenerationMethodInfo> methodToInfoMap =
            new ConditionalWeakTable<IMethodSymbol, CodeGenerationMethodInfo>();

        private readonly bool isNew;
        private readonly bool isUnsafe;
        private readonly bool isPartial;
        private readonly bool isAsync;
        private readonly IList<SyntaxNode> statements;
        private readonly IList<SyntaxNode> handlesExpressions;

        private CodeGenerationMethodInfo(
            bool isNew,
            bool isUnsafe,
            bool isPartial,
            bool isAsync,
            IList<SyntaxNode> statements,
            IList<SyntaxNode> handlesExpressions)
        {
            this.isNew = isNew;
            this.isUnsafe = isUnsafe;
            this.isPartial = isPartial;
            this.isAsync = isAsync;
            this.statements = statements ?? SpecializedCollections.EmptyList<SyntaxNode>();
            this.handlesExpressions = handlesExpressions ?? SpecializedCollections.EmptyList<SyntaxNode>();
        }

        public static void Attach(
            IMethodSymbol method,
            bool isNew,
            bool isUnsafe,
            bool isPartial,
            bool isAsync,
            IList<SyntaxNode> statements,
            IList<SyntaxNode> handlesExpressions)
        {
            var info = new CodeGenerationMethodInfo(isNew, isUnsafe, isPartial, isAsync, statements, handlesExpressions);
            methodToInfoMap.Add(method, info);
        }

        private static CodeGenerationMethodInfo GetInfo(IMethodSymbol method)
        {
            CodeGenerationMethodInfo info;
            methodToInfoMap.TryGetValue(method, out info);
            return info;
        }

        public static IList<SyntaxNode> GetStatements(IMethodSymbol method)
        {
            return GetStatements(GetInfo(method));
        }

        public static IList<SyntaxNode> GetHandlesExpressions(IMethodSymbol method)
        {
            return GetHandlesExpressions(GetInfo(method));
        }

        public static bool GetIsNew(IMethodSymbol method)
        {
            return GetIsNew(GetInfo(method));
        }

        public static bool GetIsUnsafe(IMethodSymbol method)
        {
            return GetIsUnsafe(GetInfo(method));
        }

        public static bool GetIsPartial(IMethodSymbol method)
        {
            return GetIsPartial(GetInfo(method));
        }

        public static bool GetIsAsync(IMethodSymbol method)
        {
            return GetIsAsync(GetInfo(method));
        }

        private static IList<SyntaxNode> GetStatements(CodeGenerationMethodInfo info)
        {
            return info == null
                ? SpecializedCollections.EmptyList<SyntaxNode>()
                : info.statements;
        }

        private static IList<SyntaxNode> GetHandlesExpressions(CodeGenerationMethodInfo info)
        {
            return info == null
                ? SpecializedCollections.EmptyList<SyntaxNode>()
                : info.handlesExpressions;
        }

        private static bool GetIsNew(CodeGenerationMethodInfo info)
        {
            return info != null && info.isNew;
        }

        private static bool GetIsUnsafe(CodeGenerationMethodInfo info)
        {
            return info != null && info.isUnsafe;
        }

        private static bool GetIsPartial(CodeGenerationMethodInfo info)
        {
            return info != null && info.isPartial;
        }

        private static bool GetIsAsync(CodeGenerationMethodInfo info)
        {
            return info != null && info.isAsync;
        }
    }
}


text:
package com.psygate.dedication;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 *
 * @author psygate (https://github.com/psygate)
 */
public class Helper {

    private static final Map<String, TimeUnit> base = new HashMap<>();
    private static final Map<String, Container> suffixes = new HashMap<>();
    private static final TimeUnit[] units;
    private static final Map<TimeUnit, WordFor> names;

    static {
        base.put("ms", TimeUnit.MILLISECONDS);
        base.put("h", TimeUnit.HOURS);
        base.put("m", TimeUnit.MINUTES);
        base.put("s", TimeUnit.SECONDS);
        base.put("d", TimeUnit.DAYS);

        for (Map.Entry<String, TimeUnit> entry : base.entrySet()) {
            suffixes.put(entry.getKey(), new Container(entry.getValue(), entry.getKey()));
        }

        units = new TimeUnit[]{TimeUnit.DAYS, TimeUnit.HOURS, TimeUnit.MINUTES, TimeUnit.SECONDS, TimeUnit.MILLISECONDS};
        names = new HashMap<>();
        names.put(TimeUnit.DAYS, new WordFor("day", "days"));
        names.put(TimeUnit.HOURS, new WordFor("hour", "hours"));
        names.put(TimeUnit.MINUTES, new WordFor("minute", "minutes"));
        names.put(TimeUnit.SECONDS, new WordFor("second", "seconds"));
        names.put(TimeUnit.MILLISECONDS, new WordFor("milli second", "milli seconds"));
    }

    public static long timeStringAsMillis(final String input) {
        final String matchable = input.toLowerCase();
        long time = 0;
        boolean found = false;
        for (Map.Entry<String, Container> en : suffixes.entrySet()) {
            Pattern pat = en.getValue().getPattern();
            Matcher matcher = pat.matcher(matchable);
            found = matcher.matches() || found;
            if (matcher.matches()) {
                if (matcher.groupCount() > 0) {
                    throw new IllegalArgumentException("Unmatchable string, pattern more than once: " + matchable);
                } else if (matcher.groupCount() == 0) {
                    time += parseTimePartString(matcher.group(), en.getValue());
                    break;
                }
            }
        }

        if (!found) {
            throw new IllegalArgumentException("Cannot parse timestring. No time values found. (" + matchable + ")");
        }

        return time;
    }

    public static String millisAsString(long millis) {

        StringBuilder out = new StringBuilder();

        for (TimeUnit unit : units) {
            long value = unit.convert(millis, TimeUnit.MILLISECONDS);
            if (value > 0) {

                if (out.length() > 0) {
                    out.append(" ");
                }
                out.append(value).append(" ").append(names.get(unit).getFor(value));
                millis -= TimeUnit.MILLISECONDS.convert(value, unit);

            }
        }

        return out.toString();
    }

    private static long parseTimePartString(final String value, Container matching) {
        return matching.getUnit().toMillis(Long.parseLong(value.replace(matching.getStrSuffix(), "")));
    }

    public static Map<String, Container> getSuffixes() {
        return suffixes;
    }

    public final static class WordFor {

        private final String singular;
        private final String plural;

        public WordFor(String singular, String plural) {
            this.singular = singular;
            this.plural = plural;
        }

        public String getFor(long value) {
            if (value == 0 || value != 1) {
                return plural;
            } else {
                return singular;
            }
        }
    }

    public final static class Container {

        private final TimeUnit unit;
        private final String strSuffix;
        private final String timeParts;
        private final Pattern pattern;

        public Container(TimeUnit unit, String strSuffix) {
            this.unit = unit;
            this.strSuffix = strSuffix;
            this.timeParts = "[0-9]+" + strSuffix;
            this.pattern = Pattern.compile(timeParts);
        }

        public TimeUnit getUnit() {
            return unit;
        }

        public String getStrSuffix() {
            return strSuffix;
        }

        public String getTimeParts() {
            return timeParts;
        }

        public Pattern getPattern() {
            return pattern;
        }

    }
}


text:
#ifndef __HEARTBEAT_H
#define __HEARTBEAT_H

typedef struct rdp_heartbeat rdpHeartbeat;

#include "rdp.h"

#include <freerdp/freerdp.h>
#include <freerdp/log.h>

#include <winpr/stream.h>

struct rdp_heartbeat
{
	UINT32 placeholder;
};

int rdp_recv_heartbeat_packet(rdpRdp* rdp, wStream* s);

rdpHeartbeat* heartbeat_new(void);
void heartbeat_free(rdpHeartbeat* heartbeat);

#define HEARTBEAT_TAG FREERDP_TAG("core.heartbeat")

#endif /* __HEARTBEAT_H */


text:
class TileMap;

typedef std::list<CombatEvent*> CombatEventList;
typedef std::vector<Actor*> ActorList;
typedef std::vector<Position> PosList;

class GroundBattle
{
public:
	static GroundBattle& Instance() { static GroundBattle instance;  return instance; };
	~GroundBattle();

	void StartBattle();
	void EndBattle();
	void Update(const float ticks);
	void PlaceAlly(const Position& pos);

	void AddEvent(CombatEvent* pEvent);
	void AddPriorityEvent(CombatEvent* pEvent);
	void ClearEvents();

	Actor& NextTurn();
	Actor& GetActiveActor();
	Actor& GetCurrTarget();
	ActorList& GetPlayerList();
	void ShowMoveRange();

	void Attack();
	bool SpecificAttack(Actor* pAttacker, Actor* pTarget);
	void FindTargets();
	bool SilentTargetCheck(Actor* pAttacker, Actor* pDefender = NULL);
	void NextTarget();
	void PrevTarget();
	bool IsTargeting();

	void WinLossCheck();
	void RemoveActorFromBattlefield(Actor* pActor);

	void ShowCombatText(const std::string& text);
	void HideCombatText();
	AutoAdvanceWindow& GetCombatText();

	void StartCutscene();
	void EndCutscene();
	bool IsCutsceneRunning() const;
	void SetCSPlayerPose(const BattleAniFrames::Type pose);
	void SetCSEnemyPose(const BattleAniFrames::Type pose);

	void DebugToHit(const int toHit);
	void ResetCEData();

private:
	GroundBattle();
	GroundBattle(const GroundBattle& rhs);
	GroundBattle& operator=(const GroundBattle& rhs);

	bool m_bActive;
	Position m_roundStartPos;
	ActorList m_players;
	ActorList m_enemies;
	int m_numEnemies;
	ActorList m_allActors;
	PosList m_startPositions;
	int m_turn;
	int m_round;
	int m_toHit;
	int m_numDead;
	GameString m_debugHUD;
	GameString m_bigText;
	Actor* m_pPlayerLeader;
	Actor* m_pEnemyLeader;
	Actor* m_pAttacker;
	ActorList m_targets;
	int m_currTarget;
	TargetingBracket m_targetBracket;
	TileMap* m_pCurrMap;

	BattleCutscene* m_pCutscene;
	AutoAdvanceWindow m_autoWin;

	CombatEventList m_eventList;
	CombatEvent* m_pCurrEvent;
	CombatEventData m_CEData;
};

#endif //_groundbattle_h_


text:
<?php

declare(strict_types=1);

namespace Biplane\YandexDirect\Api\V5\Contract;

use AllowDynamicProperties;

/**
 * Auto-generated code.
 */
#[AllowDynamicProperties]
class AgencyClientUpdateItem extends ClientUpdateItem
{
    protected $ClientId = null;

//    Can be omitted.
//    protected $Grants = null;

    public function getClientId(): int
    {
        return $this->ClientId;
    }

    /**
     * @return $this
     */
    public function setClientId(int $value)
    {
        $this->ClientId = $value;

        return $this;
    }

    /**
     * @return GrantItem[]|null
     */
    public function getGrants(): ?array
    {
        return $this->Grants ?? null;
    }

    /**
     * @param GrantItem[]|null $value
     *
     * @return $this
     */
    public function setGrants(?array $value = null)
    {
        $this->Grants = $value;

        return $this;
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<?eclipse version="3.2"?>
<plugin>
   <extension
         point="org.jboss.tools.vpe.templates">
      <templates
            decsription="VPE Templates for Ajax4jsf components"
            name="ajax4jsf"
            path="templates/vpe-templates-ajax4jsf.xml"/>
   </extension>

</plugin>


text:
package tabify;

import javafx.application.Application;
import javafx.stage.Stage;
import static tabify.Helper.startJahSpotify;

/**
 *
 * @author Cary
 */
public class Tabify20 extends Application {

    @Override
    public void start(Stage stage) throws Exception {
        Helper helping = new Helper();
        helping.changeScene("MainFXML.fxml", null, 600, 400,"Supporting/Login.css");
        startJahSpotify();

    }

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        launch(args);

    }

}


text:
package org.usfirst.frc.team619.hardware;

import edu.wpi.first.wpilibj.GenericHID.Hand;
import edu.wpi.first.wpilibj.XboxController;

public class Gamepad {

	protected XboxController controller;
	/**
	 * Currently just a wrapper class. Adds nothing new to XboxController from wpilib
	 * This class exists in case we want to add something extra
	 */
	public Gamepad(int port) {
		controller = new XboxController(port);
	}

	/**
	* Get the X axis value of the controller.
	*
	* @param hand Side of controller whose value should be returned.
	* @return The X axis value of the controller.
	*/
	public double getX(Hand hand) {
		if(hand == Hand.kLeft) {
			return controller.getRawAxis(0);
		}else {
			return controller.getRawAxis(2);
		}
	}

	/**
	 * Get the Y axis value of the controller.
	 *
	 * @param hand Side of controller whose value should be returned.
	 * @return The Y axis value of the controller.
	 */
	public double getY(Hand hand) {
		if(hand == Hand.kLeft)
			return controller.getRawAxis(1);
		return controller.getRawAxis(3);
	}

	/**
	 * Read the value of the bumper button on the controller.
	 *
	 * @param hand Side of controller whose value should be returned.
	 * @return The state of the button.
	 */
	public boolean getBumper(Hand hand) {
		if(hand == Hand.kLeft)
			return controller.getRawButton(4);
		return controller.getRawButton(5);
	}

	/**
	 * Get the trigger axis value of the controller.
	 *
	 * @param hand Side of controller whose value should be returned.
	 * @return The trigger axis value of the controller.
	 */
	public double getTriggerAxis(Hand hand) {
		return controller.getTriggerAxis(hand);
	}

	/**
	 * Read the value of the A button on the controller.
	 *
	 * @return The state of the button.
	 */
	public boolean getAButton() {
		return controller.getRawButton(1);
	}

	/**
	 * Read the value of the B button on the controller.
	 *
	 * @return The state of the button.
	 */
	public boolean getBButton() {
		return controller.getRawButton(2);
	}

	/**
	 * Read the value of the X button on the controller.
	 *
	 * @return The state of the button.
	 */
	public boolean getXButton() {
		return controller.getRawButton(0);
	}

	/**
	 * Read the value of the Y button on the controller.
	 *
	 * @return The state of the button.
	 */
	public boolean getYButton() {
		return controller.getRawButton(3);
	}

	/**
	 * Read the value of the stick button on the controller.
	 *
	 * @param hand Side of controller whose value should be returned.
	 * @return The state of the button.
	 */
	public boolean getStickButton(Hand hand) {
		return controller.getStickButton(hand);
	}

	/**
	 * Read the value of the back button on the controller.
	 *
	 * @return The state of the button.
	 */
	public boolean getBackButton() {
		return controller.getRawButton(8);
	}

	/**
	 * Read the value of the start button on the controller.
	 *
	 * @return The state of the button.
	 */
	public boolean getStartButton() {
		return controller.getRawButton(9);
	}

	public int getPOV() {
		return controller.getPOV(0);
	}
}


text:
'use strict';

/**
 * @ngdoc function
 * @name artgalleryApp.controller:StudentsearchCtrl
 * @description
 * # StudentsearchCtrl
 * Controller of the artgalleryApp
 */
angular.module('artgalleryApp')
  .controller('StudentsearchCtrl', function ($scope) {
    $scope.awesomeThings = [
      'HTML5 Boilerplate',
      'AngularJS',
      'Karma'
    ];
  });


text:
import { NgModule } from '@angular/core';
import { AddStudentComponent } from './addStudent.component';
import { RouterModule } from '@angular/router';
import { SharedModule } from '../../shared.module';
import { ExistingStudentComponent } from './existingStudent/existingStudent.component';
import { NewStudentComponent } from './newStudent/newStudent.component';

@NgModule({
	imports : [ SharedModule, RouterModule.forChild([
			{ path:'', redirectTo:'new-student', pathMatch:'full'},
			{
				path : '',
				component : AddStudentComponent,
				children : [
				{
					path : 'existing-student',
					component : ExistingStudentComponent
				},
				{
					path : 'existing-student/:standardId/:studentId',
					component : ExistingStudentComponent
				},
				{
					path : 'new-student',
					component : NewStudentComponent
				}
				]
			}

		])],
	declarations : [ AddStudentComponent,ExistingStudentComponent,NewStudentComponent ]
})
export class AddStudentModule {

}


text:
package in.testpress.testpress.core;

public class ApiError {
    private int code;
    private String error;

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getError() {
        return error;
    }

    public void setError(String error) {
        this.error = error;
    }
}


text:
matchzoo.datasets.wiki\_qa package
==================================

Submodules
----------

matchzoo.datasets.wiki\_qa.load\_data module
--------------------------------------------

.. automodule:: matchzoo.datasets.wiki_qa.load_data
    :members:
    :undoc-members:
    :show-inheritance:

Module contents
---------------

.. automodule:: matchzoo.datasets.wiki_qa
    :members:
    :undoc-members:
    :show-inheritance:


text:
#ifndef JUCE_CORE_H_INCLUDED
#define JUCE_CORE_H_INCLUDED

#ifndef JUCE_MODULE_AVAILABLE_juce_core
 /* If you fail to make sure that all your compile units are building JUCE with the same set of
    option flags, then there's a risk that different compile units will treat the classes as having
    different memory layouts, leading to very nasty memory corruption errors when they all get
    linked together. That's why it's best to always include the Introjucer-generated AppConfig.h
    file before any juce headers.

    Note that if you do have an AppConfig.h file and hit this warning, it means that it doesn't
    contain the JUCE_MODULE_AVAILABLE_xxx flags, which are necessary for some inter-module
    functionality to work correctly. In that case, you should either rebuild your AppConfig.h with
    the latest introjucer, or fix it manually to contain these flags.
 */
 #ifdef _MSC_VER
  #pragma message ("Have you included your AppConfig.h file before including the JUCE headers?")
 #else
  #warning "Have you included your AppConfig.h file before including the JUCE headers?"
 #endif
#endif

//==============================================================================
#include "system/juce_TargetPlatform.h"

//=============================================================================
/** Config: JUCE_FORCE_DEBUG

    Normally, JUCE_DEBUG is set to 1 or 0 based on compiler and project settings,
    but if you define this value, you can override this to force it to be true or false.
*/
#ifndef JUCE_FORCE_DEBUG
 //#define JUCE_FORCE_DEBUG 0
#endif

//=============================================================================
/** Config: JUCE_LOG_ASSERTIONS

    If this flag is enabled, the jassert and jassertfalse macros will always use Logger::writeToLog()
    to write a message when an assertion happens.

    Enabling it will also leave this turned on in release builds. When it's disabled,
    however, the jassert and jassertfalse macros will not be compiled in a
    release build.

    @see jassert, jassertfalse, Logger
*/
#ifndef JUCE_LOG_ASSERTIONS
 #if JUCE_ANDROID
  #define JUCE_LOG_ASSERTIONS 1
 #else
  #define JUCE_LOG_ASSERTIONS 0
 #endif
#endif

//=============================================================================
/** Config: JUCE_CHECK_MEMORY_LEAKS

    Enables a memory-leak check for certain objects when the app terminates. See the LeakedObjectDetector
    class and the JUCE_LEAK_DETECTOR macro for more details about enabling leak checking for specific classes.
*/
#if JUCE_DEBUG && ! defined (JUCE_CHECK_MEMORY_LEAKS)
 #define JUCE_CHECK_MEMORY_LEAKS 1
#endif

//=============================================================================
/** Config: JUCE_DONT_AUTOLINK_TO_WIN32_LIBRARIES

    In a Visual C++  build, this can be used to stop the required system libs being
    automatically added to the link stage.
*/
#ifndef JUCE_DONT_AUTOLINK_TO_WIN32_LIBRARIES
 #define JUCE_DONT_AUTOLINK_TO_WIN32_LIBRARIES 0
#endif

/** Config: JUCE_INCLUDE_ZLIB_CODE
    This can be used to disable Juce's embedded 3rd-party zlib code.
    You might need to tweak this if you're linking to an external zlib library in your app,
    but for normal apps, this option should be left alone.

    If you disable this, you might also want to set a value for JUCE_ZLIB_INCLUDE_PATH, to
    specify the path where your zlib headers live.
*/
#ifndef JUCE_INCLUDE_ZLIB_CODE
 #define JUCE_INCLUDE_ZLIB_CODE 1
#endif

#ifndef JUCE_ZLIB_INCLUDE_PATH
 #define JUCE_ZLIB_INCLUDE_PATH <zlib.h>
#endif

/*  Config: JUCE_CATCH_UNHANDLED_EXCEPTIONS
    If enabled, this will add some exception-catching code to forward unhandled exceptions
    to your JUCEApplicationBase::unhandledException() callback.
*/
#ifndef JUCE_CATCH_UNHANDLED_EXCEPTIONS
 //#define JUCE_CATCH_UNHANDLED_EXCEPTIONS 1
#endif

#ifndef JUCE_STRING_UTF_TYPE
 #define JUCE_STRING_UTF_TYPE 8
#endif

//=============================================================================
//=============================================================================
#if JUCE_MSVC
 #pragma warning (disable: 4251) // (DLL build warning, must be disabled before pushing the warning state)
 #pragma warning (push)
 #pragma warning (disable: 4786) // (long class name warning)
 #ifdef __INTEL_COMPILER
  #pragma warning (disable: 1125)
 #endif
#endif

#include "system/juce_StandardHeader.h"

namespace juce
{

class StringRef;
class MemoryBlock;
class File;
class InputStream;
class OutputStream;
class DynamicObject;
class FileInputStream;
class FileOutputStream;
class XmlElement;
class JSONFormatter;

extern JUCE_API bool JUCE_CALLTYPE juce_isRunningUnderDebugger();
extern JUCE_API void JUCE_CALLTYPE logAssertion (const char* file, int line) noexcept;

#include "memory/juce_Memory.h"
#include "maths/juce_MathsFunctions.h"
#include "memory/juce_ByteOrder.h"
#include "memory/juce_Atomic.h"
#include "text/juce_CharacterFunctions.h"

#if JUCE_MSVC
 #pragma warning (push)
 #pragma warning (disable: 4514 4996)
#endif

#include "text/juce_CharPointer_UTF8.h"
#include "text/juce_CharPointer_UTF16.h"
#include "text/juce_CharPointer_UTF32.h"
#include "text/juce_CharPointer_ASCII.h"

#if JUCE_MSVC
 #pragma warning (pop)
#endif

#include "text/juce_String.h"
#include "text/juce_StringRef.h"
#include "logging/juce_Logger.h"
#include "memory/juce_LeakedObjectDetector.h"
#include "memory/juce_ContainerDeletePolicy.h"
#include "memory/juce_HeapBlock.h"
#include "memory/juce_MemoryBlock.h"
#include "memory/juce_ReferenceCountedObject.h"
#include "memory/juce_ScopedPointer.h"
#include "memory/juce_OptionalScopedPointer.h"
#include "memory/juce_Singleton.h"
#include "memory/juce_WeakReference.h"
#include "threads/juce_ScopedLock.h"
#include "threads/juce_CriticalSection.h"
#include "maths/juce_Range.h"
#include "maths/juce_NormalisableRange.h"
#include "containers/juce_ElementComparator.h"
#include "containers/juce_ArrayAllocationBase.h"
#include "containers/juce_Array.h"
#include "containers/juce_LinkedListPointer.h"
#include "containers/juce_OwnedArray.h"
#include "containers/juce_ReferenceCountedArray.h"
#include "containers/juce_ScopedValueSetter.h"
#include "containers/juce_SortedSet.h"
#include "containers/juce_SparseSet.h"
#include "containers/juce_AbstractFifo.h"
#include "text/juce_NewLine.h"
#include "text/juce_StringPool.h"
#include "text/juce_Identifier.h"
#include "text/juce_StringArray.h"
#include "text/juce_StringPairArray.h"
#include "text/juce_TextDiff.h"
#include "text/juce_LocalisedStrings.h"
#include "misc/juce_Result.h"
#include "containers/juce_Variant.h"
#include "containers/juce_NamedValueSet.h"
#include "containers/juce_DynamicObject.h"
#include "containers/juce_HashMap.h"
#include "time/juce_RelativeTime.h"
#include "time/juce_Time.h"
#include "streams/juce_InputStream.h"
#include "streams/juce_OutputStream.h"
#include "streams/juce_BufferedInputStream.h"
#include "streams/juce_MemoryInputStream.h"
#include "streams/juce_MemoryOutputStream.h"
#include "streams/juce_SubregionStream.h"
#include "streams/juce_InputSource.h"
#include "files/juce_File.h"
#include "files/juce_DirectoryIterator.h"
#include "files/juce_FileInputStream.h"
#include "files/juce_FileOutputStream.h"
#include "files/juce_FileSearchPath.h"
#include "files/juce_MemoryMappedFile.h"
#include "files/juce_TemporaryFile.h"
#include "files/juce_FileFilter.h"
#include "files/juce_WildcardFileFilter.h"
#include "streams/juce_FileInputSource.h"
#include "logging/juce_FileLogger.h"
#include "javascript/juce_JSON.h"
#include "javascript/juce_Javascript.h"
#include "maths/juce_BigInteger.h"
#include "maths/juce_Expression.h"
#include "maths/juce_Random.h"
#include "misc/juce_Uuid.h"
#include "misc/juce_WindowsRegistry.h"
#include "system/juce_PlatformDefs.h"
#include "system/juce_CompilerSupport.h"
#include "system/juce_SystemStats.h"
#include "threads/juce_ChildProcess.h"
#include "threads/juce_DynamicLibrary.h"
#include "threads/juce_HighResolutionTimer.h"
#include "threads/juce_InterProcessLock.h"
#include "threads/juce_Process.h"
#include "threads/juce_SpinLock.h"
#include "threads/juce_WaitableEvent.h"
#include "threads/juce_Thread.h"
#include "threads/juce_ThreadLocalValue.h"
#include "threads/juce_ThreadPool.h"
#include "threads/juce_TimeSliceThread.h"
#include "threads/juce_ReadWriteLock.h"
#include "threads/juce_ScopedReadLock.h"
#include "threads/juce_ScopedWriteLock.h"
#include "network/juce_IPAddress.h"
#include "network/juce_MACAddress.h"
#include "network/juce_NamedPipe.h"
#include "network/juce_Socket.h"
#include "network/juce_URL.h"
#include "time/juce_PerformanceCounter.h"
#include "unit_tests/juce_UnitTest.h"
#include "xml/juce_XmlDocument.h"
#include "xml/juce_XmlElement.h"
#include "zip/juce_GZIPCompressorOutputStream.h"
#include "zip/juce_GZIPDecompressorInputStream.h"
#include "zip/juce_ZipFile.h"
#include "containers/juce_PropertySet.h"
#include "memory/juce_SharedResourcePointer.h"

}

#if JUCE_MSVC
 #pragma warning (pop)
#endif

#endif   // JUCE_CORE_H_INCLUDED


text:
package org.apache.hadoop.io;

import java.util.*;
import java.io.*;

public class RandomDatum implements WritableComparable {
  private int length;
  private byte[] data;

  public RandomDatum() {}

  public RandomDatum(Random random) {
    length = 10 + random.nextInt(100);
    data = new byte[length];
    random.nextBytes(data);
  }

  public void write(DataOutput out) throws IOException {
    out.writeInt(length);
    out.write(data);
  }

  public void readFields(DataInput in) throws IOException {
    length = in.readInt();
    if (data == null || length > data.length)
      data = new byte[length];
    in.readFully(data, 0, length);
  }

  public int compareTo(Object o) {
    RandomDatum that = (RandomDatum)o;
    return WritableComparator.compareBytes(this.data, 0, this.length,
                                           that.data, 0, that.length);
  }

  public boolean equals(Object o) {
    return compareTo(o) == 0;
  }

  private static final char[] HEX_DIGITS =
  {'0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f'};

  /** Returns a string representation of this object. */
  public String toString() {
    StringBuffer buf = new StringBuffer(length*2);
    for (int i = 0; i < length; i++) {
      int b = data[i];
      buf.append(HEX_DIGITS[(b >> 4) & 0xf]);
      buf.append(HEX_DIGITS[b & 0xf]);
    }
    return buf.toString();
  }

  public static class Generator {
    Random random;

    private RandomDatum key;
    private RandomDatum value;

    public Generator() { random = new Random(); }
    public Generator(int seed) { random = new Random(seed); }

    public RandomDatum getKey() { return key; }
    public RandomDatum getValue() { return value; }

    public void next() {
      key = new RandomDatum(random);
      value = new RandomDatum(random);
    }
  }

  /** A WritableComparator optimized for RandomDatum. */
  public static class Comparator extends WritableComparator {
    public Comparator() {
      super(RandomDatum.class);
    }

    public int compare(byte[] b1, int s1, int l1,
                       byte[] b2, int s2, int l2) {
      int n1 = readInt(b1, s1);
      int n2 = readInt(b2, s2);
      return compareBytes(b1, s1+4, n1, b2, s2+4, n2);
    }
  }

}


text:
namespace Moonfish.Guerilla.Tags
{
    using Moonfish.Tags;
    using Moonfish.Model;
    using System.IO;
    using System.Collections.Generic;
    using System.Linq;

    public partial class PlatformSoundEffectBlock : GuerillaBlock, IWriteQueueable
    {
        public PlatformSoundEffectFunctionBlock[] FunctionInputs = new PlatformSoundEffectFunctionBlock[0];
        public PlatformSoundEffectConstantBlock[] ConstantInputs = new PlatformSoundEffectConstantBlock[0];
        public PlatformSoundEffectOverrideDescriptorBlock[] TemplateOverrideDescriptors = new PlatformSoundEffectOverrideDescriptorBlock[0];
        public int InputOverrides;
        public override int SerializedSize
        {
            get
            {
                return 28;
            }
        }
        public override int Alignment
        {
            get
            {
                return 4;
            }
        }
        public override System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> ReadFields(System.IO.BinaryReader binaryReader)
        {
            System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> pointerQueue = new System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer>(base.ReadFields(binaryReader));
            pointerQueue.Enqueue(binaryReader.ReadBlamPointer(16));
            pointerQueue.Enqueue(binaryReader.ReadBlamPointer(4));
            pointerQueue.Enqueue(binaryReader.ReadBlamPointer(1));
            this.InputOverrides = binaryReader.ReadInt32();
            return pointerQueue;
        }
        public override void ReadInstances(System.IO.BinaryReader binaryReader, System.Collections.Generic.Queue<Moonfish.Tags.BlamPointer> pointerQueue)
        {
            base.ReadInstances(binaryReader, pointerQueue);
            this.FunctionInputs = base.ReadBlockArrayData<PlatformSoundEffectFunctionBlock>(binaryReader, pointerQueue.Dequeue());
            this.ConstantInputs = base.ReadBlockArrayData<PlatformSoundEffectConstantBlock>(binaryReader, pointerQueue.Dequeue());
            this.TemplateOverrideDescriptors = base.ReadBlockArrayData<PlatformSoundEffectOverrideDescriptorBlock>(binaryReader, pointerQueue.Dequeue());
        }
        public override void QueueWrites(Moonfish.Guerilla.QueueableBinaryWriter queueableBinaryWriter)
        {
            base.QueueWrites(queueableBinaryWriter);
            queueableBinaryWriter.QueueWrite(this.FunctionInputs);
            queueableBinaryWriter.QueueWrite(this.ConstantInputs);
            queueableBinaryWriter.QueueWrite(this.TemplateOverrideDescriptors);
        }
        public override void Write_(Moonfish.Guerilla.QueueableBinaryWriter queueableBinaryWriter)
        {
            base.Write_(queueableBinaryWriter);
            queueableBinaryWriter.WritePointer(this.FunctionInputs);
            queueableBinaryWriter.WritePointer(this.ConstantInputs);
            queueableBinaryWriter.WritePointer(this.TemplateOverrideDescriptors);
            queueableBinaryWriter.Write(this.InputOverrides);
        }
    }
}


text:
FROM node:boron

MAINTAINER Jason Wang, Lucas Yu, Longlong Li

# Use Alibaba's NPM mirror
RUN npm set registry https://registry.npm.taobao.org/

# creat workdir
RUN mkdir -p /usr/projects/movie-board
WORKDIR /usr/projects/movie-board

# Install dependencies
COPY package.json /usr/projects/movie-board
RUN npm install --production

# copy other codes and resources
COPY . /usr/projects/movie-board

EXPOSE 8080
# ENTRYPOINT diff CMD CDM can be overrided
CMD [ "npm", "start" ]


text:
package com.mgmtp.perfload.perfalyzer.annotations;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

/**
 * @author rnaegele
 */
@Retention(RetentionPolicy.RUNTIME)
@Target({ ElementType.METHOD, ElementType.FIELD, ElementType.PARAMETER })
public @interface NormalizedDir {
	//
}


text:
package syncgroups

import (
	"fmt"

	"gopkg.in/ldap.v2"

	"github.com/openshift/origin/pkg/oauthserver/ldaputil"
	"github.com/openshift/origin/pkg/oc/lib/groupsync/interfaces"
)

// NewUserNameMapper returns a new DefaultLDAPGroupUserNameMapper
func NewUserNameMapper(nameAttributes []string) interfaces.LDAPUserNameMapper {
	return &DefaultLDAPUserNameMapper{
		nameAttributes: nameAttributes,
	}
}

// DefaultLDAPUserNameMapper extracts the OpenShift User name of an LDAP entry representing
// a user in a deterministic manner
type DefaultLDAPUserNameMapper struct {
	nameAttributes []string
}

func (m *DefaultLDAPUserNameMapper) UserNameFor(ldapUser *ldap.Entry) (string, error) {
	openShiftUserName := ldaputil.GetAttributeValue(ldapUser, m.nameAttributes)
	if len(openShiftUserName) == 0 {
		return "", fmt.Errorf("the user entry (%v) does not map to a OpenShift User name with the given mapping",
			ldapUser)
	}
	return openShiftUserName, nil
}


text:
package org.elasticsearch.action.admin.cluster.allocation;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.elasticsearch.action.ActionListener;
import org.elasticsearch.action.support.ActionFilters;
import org.elasticsearch.action.support.master.TransportMasterNodeAction;
import org.elasticsearch.cluster.ClusterInfo;
import org.elasticsearch.cluster.ClusterInfoService;
import org.elasticsearch.cluster.ClusterState;
import org.elasticsearch.cluster.block.ClusterBlockException;
import org.elasticsearch.cluster.block.ClusterBlockLevel;
import org.elasticsearch.cluster.metadata.IndexNameExpressionResolver;
import org.elasticsearch.cluster.node.DiscoveryNode;
import org.elasticsearch.cluster.routing.RoutingNodes;
import org.elasticsearch.cluster.routing.ShardRouting;
import org.elasticsearch.cluster.routing.allocation.AllocationService;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation;
import org.elasticsearch.cluster.routing.allocation.RoutingAllocation.DebugMode;
import org.elasticsearch.cluster.routing.allocation.ShardAllocationDecision;
import org.elasticsearch.cluster.routing.allocation.decider.AllocationDeciders;
import org.elasticsearch.cluster.service.ClusterService;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.snapshots.SnapshotsInfoService;
import org.elasticsearch.tasks.Task;
import org.elasticsearch.threadpool.ThreadPool;
import org.elasticsearch.transport.TransportService;

import java.util.List;

/**
 * The {@code TransportClusterAllocationExplainAction} is responsible for actually executing the explanation of a shard's allocation on the
 * master node in the cluster.
 */
public class TransportClusterAllocationExplainAction extends TransportMasterNodeAction<
    ClusterAllocationExplainRequest,
    ClusterAllocationExplainResponse> {

    private static final Logger logger = LogManager.getLogger(TransportClusterAllocationExplainAction.class);

    private final ClusterInfoService clusterInfoService;
    private final SnapshotsInfoService snapshotsInfoService;
    private final AllocationDeciders allocationDeciders;
    private final AllocationService allocationService;

    @Inject
    public TransportClusterAllocationExplainAction(
        TransportService transportService,
        ClusterService clusterService,
        ThreadPool threadPool,
        ActionFilters actionFilters,
        IndexNameExpressionResolver indexNameExpressionResolver,
        ClusterInfoService clusterInfoService,
        SnapshotsInfoService snapshotsInfoService,
        AllocationDeciders allocationDeciders,
        AllocationService allocationService
    ) {
        super(
            ClusterAllocationExplainAction.NAME,
            transportService,
            clusterService,
            threadPool,
            actionFilters,
            ClusterAllocationExplainRequest::new,
            indexNameExpressionResolver,
            ClusterAllocationExplainResponse::new,
            ThreadPool.Names.MANAGEMENT
        );
        this.clusterInfoService = clusterInfoService;
        this.snapshotsInfoService = snapshotsInfoService;
        this.allocationDeciders = allocationDeciders;
        this.allocationService = allocationService;
    }

    @Override
    protected ClusterBlockException checkBlock(ClusterAllocationExplainRequest request, ClusterState state) {
        return state.blocks().globalBlockedException(ClusterBlockLevel.METADATA_READ);
    }

    @Override
    protected void masterOperation(
        Task task,
        final ClusterAllocationExplainRequest request,
        final ClusterState state,
        final ActionListener<ClusterAllocationExplainResponse> listener
    ) {
        final RoutingNodes routingNodes = state.getRoutingNodes();
        final ClusterInfo clusterInfo = clusterInfoService.getClusterInfo();
        final RoutingAllocation allocation = new RoutingAllocation(
            allocationDeciders,
            routingNodes,
            state,
            clusterInfo,
            snapshotsInfoService.snapshotShardSizes(),
            System.nanoTime()
        );

        ShardRouting shardRouting = findShardToExplain(request, allocation);
        logger.debug("explaining the allocation for [{}], found shard [{}]", request, shardRouting);

        ClusterAllocationExplanation cae = explainShard(
            shardRouting,
            allocation,
            request.includeDiskInfo() ? clusterInfo : null,
            request.includeYesDecisions(),
            request.useAnyUnassignedShard() == false,
            allocationService
        );
        listener.onResponse(new ClusterAllocationExplainResponse(cae));
    }

    // public for testing
    public static ClusterAllocationExplanation explainShard(
        ShardRouting shardRouting,
        RoutingAllocation allocation,
        ClusterInfo clusterInfo,
        boolean includeYesDecisions,
        boolean isSpecificShard,
        AllocationService allocationService
    ) {

        allocation.setDebugMode(includeYesDecisions ? DebugMode.ON : DebugMode.EXCLUDE_YES_DECISIONS);

        ShardAllocationDecision shardDecision;
        if (shardRouting.initializing() || shardRouting.relocating()) {
            shardDecision = ShardAllocationDecision.NOT_TAKEN;
        } else {
            shardDecision = allocationService.explainShardAllocation(shardRouting, allocation);
        }

        return new ClusterAllocationExplanation(
            isSpecificShard,
            shardRouting,
            shardRouting.currentNodeId() != null ? allocation.nodes().get(shardRouting.currentNodeId()) : null,
            shardRouting.relocatingNodeId() != null ? allocation.nodes().get(shardRouting.relocatingNodeId()) : null,
            clusterInfo,
            shardDecision
        );
    }

    // public for testing
    public static ShardRouting findShardToExplain(ClusterAllocationExplainRequest request, RoutingAllocation allocation) {
        ShardRouting foundShard = null;
        if (request.useAnyUnassignedShard()) {
            // If we can use any shard, return the first unassigned primary (if there is one) or the first unassigned replica (if not)
            for (ShardRouting unassigned : allocation.routingNodes().unassigned()) {
                if (foundShard == null || unassigned.primary()) {
                    foundShard = unassigned;
                }
                if (foundShard.primary()) {
                    break;
                }
            }
            if (foundShard == null) {
                throw new IllegalArgumentException(
                    "No shard was specified in the request which means the response should explain a randomly-chosen unassigned shard, "
                        + "but there are no unassigned shards in this cluster. To explain the allocation of an assigned shard you must "
                        + "specify the target shard in the request."
                );
            }
        } else {
            String index = request.getIndex();
            int shard = request.getShard();
            if (request.isPrimary()) {
                // If we're looking for the primary shard, there's only one copy, so pick it directly
                foundShard = allocation.routingTable().shardRoutingTable(index, shard).primaryShard();
                if (request.getCurrentNode() != null) {
                    DiscoveryNode primaryNode = allocation.nodes().resolveNode(request.getCurrentNode());
                    // the primary is assigned to a node other than the node specified in the request
                    if (primaryNode.getId().equals(foundShard.currentNodeId()) == false) {
                        throw new IllegalArgumentException(
                            "unable to find primary shard assigned to node [" + request.getCurrentNode() + "]"
                        );
                    }
                }
            } else {
                // If looking for a replica, go through all the replica shards
                List<ShardRouting> replicaShardRoutings = allocation.routingTable().shardRoutingTable(index, shard).replicaShards();
                if (request.getCurrentNode() != null) {
                    // the request is to explain a replica shard already assigned on a particular node,
                    // so find that shard copy
                    DiscoveryNode replicaNode = allocation.nodes().resolveNode(request.getCurrentNode());
                    for (ShardRouting replica : replicaShardRoutings) {
                        if (replicaNode.getId().equals(replica.currentNodeId())) {
                            foundShard = replica;
                            break;
                        }
                    }
                    if (foundShard == null) {
                        throw new IllegalArgumentException(
                            "unable to find a replica shard assigned to node [" + request.getCurrentNode() + "]"
                        );
                    }
                } else {
                    if (replicaShardRoutings.size() > 0) {
                        // Pick the first replica at the very least
                        foundShard = replicaShardRoutings.get(0);
                        for (ShardRouting replica : replicaShardRoutings) {
                            // In case there are multiple replicas where some are assigned and some aren't,
                            // try to find one that is unassigned at least
                            if (replica.unassigned()) {
                                foundShard = replica;
                                break;
                            } else if (replica.started() && (foundShard.initializing() || foundShard.relocating())) {
                                // prefer started shards to initializing or relocating shards because started shards
                                // can be explained
                                foundShard = replica;
                            }
                        }
                    }
                }
            }
        }

        if (foundShard == null) {
            throw new IllegalArgumentException("unable to find any shards to explain [" + request + "] in the routing table");
        }
        return foundShard;
    }
}


text:
package interpreter.tree;

import interpreter.ProgramExecutionException;
import codeblocks.Block;

/**
 * The Remainder (modulo) function. (genus remainder)
 * @author Brandon Oubre
 */
public class Remainder extends BinaryOperator<NumberResult, NumberResult> implements NumberResult {
	/**
	 * Create a new remainder function.
	 * @param block The associated block.
	 * @param arg1 The first argument.
	 * @param arg2 The second argument.
	 */
	public Remainder(Block block, NumberResult arg1, NumberResult arg2) {
		super(block, arg1, arg2);
	}

	@Override
	public double getResult() throws ProgramExecutionException {
		return arg1.getResult() % arg2.getResult();
	}
}


text:
using Newtonsoft.Json;
using ElectronicObserver.Data;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace ElectronicObserver.Utility
{
    public delegate void DialogueAddedEventHandler(DialogueData d);

    public sealed class DialogueTranslator
    {
        private static readonly DialogueTranslator instance = new DialogueTranslator();
        public static DialogueTranslator Instance { get { return instance; } }

        public event DialogueAddedEventHandler DialogueAdded = delegate { };

        private List<DialogueData> dialogue;
        private dynamic quotes;
        private static Dictionary<string, ShipDataMaster> shipCache = new Dictionary<string, ShipDataMaster>();
        // Diffs are from KC3. Licensed under MIT.
        private static List<int> voiceDiffs = new List<int>{
            2475,    0,    0, 8691, 7847, 3595, 1767, 3311, 2507,
            9651, 5321, 4473, 7117, 5947, 9489, 2669, 8741, 6149,
            1301, 7297, 2975, 6413, 8391, 9705, 2243, 2091, 4231,
            3107, 9499, 4205, 6013, 3393, 6401, 6985, 3683, 9447,
            3287, 5181, 7587, 9353, 2135, 4947, 5405, 5223, 9457,
            5767, 9265, 8191, 3927, 3061, 2805, 3273, 7331};
        private static Dictionary<string, int> specialDiffs = new Dictionary<string, int> {
            { "1555", 2 }, // valentines 2016, hinamatsuri 2015
            { "3347", 3 }, // valentines 2016, hinamatsuri 2015
            { "6547", 2 }, // whiteday 2015
			{ "1471", 3 } // whiteday 2015
        };

        private DialogueTranslator()
        {
            dialogue = new List<DialogueData>();
            // Right now, I'm using the JSON raw from KC3
            // I plan on implementing something that'll use less RAM and such later,
            // but if I want something out quickly, this'll have to do.
            WebClient client = new WebClient();
            string quotesJson = client.DownloadString("https://raw.githubusercontent.com/KC3Kai/kc3-translations/master/data/en/quotes.json");
            quotes = JsonConvert.DeserializeObject(quotesJson);
            int i = 0;
        }

        public static void Add(DialogueType type, string identifier, string filename)
        {
            DialogueData data = new DialogueData() { Time = DateTime.Now };
            string voiceLine = "-1";
            string newIdentifier = "";

            switch (type)
            {
                case DialogueType.Titlecall:
                    data.Ship = "Title Call";
                    newIdentifier = "titlecall_" + identifier;
                    voiceLine = filename;
                    break;
                case DialogueType.NPC:
                    data.Ship = "NPC";
                    newIdentifier = "npc";
                    voiceLine = filename;
                    break;
                case DialogueType.Shipgirl:
                    ShipDataMaster master;
                    // This lookup is gonna be slow if it's our first time.
                    // To save time on lookups later, we're gonna do some caching.
                    // Ironic that I'm caching here while specifically subverting cache in requests.
                    if (shipCache.ContainsKey(identifier))
                        master = shipCache[identifier];
                    else
                    {
                        master = KCDatabase.Instance.MasterShips.Where(kvp => kvp.Value.ResourceName == identifier)
                            .Select(kvp => kvp.Value).FirstOrDefault();
                        lock (shipCache)
                        {
                            shipCache.Add(identifier, master);
                        }
                    }
                    newIdentifier = master.ShipID.ToString();
                    data.Ship = master.Name;
                    voiceLine = getVoiceLineNumber(master.ShipID, filename).ToString();
                    break;
                default:
                    data = null;
                    break;
            }
            if (data == null) return;
            if (Instance.quotes[newIdentifier] != null)
            {
                if (Instance.quotes[newIdentifier][voiceLine] != null)
                {
                    data.Line = Instance.quotes[newIdentifier][voiceLine].ToString();
                }
                else
                {
                    if (specialDiffs.ContainsKey(voiceLine))
                    {
                        if (Instance.quotes[newIdentifier][specialDiffs[voiceLine].ToString()] != null)
                        {
                            data.Line = Instance.quotes[newIdentifier][specialDiffs[voiceLine].ToString()];
                        }
                        else data.Line = "<unknown>";
                    }
                    else data.Line = "<unknown>";
                }
            }
            else data.Line = "<unknown>";
            lock (Instance)
            {
                Instance.dialogue.Add(data);
            }
            Instance.DialogueAdded(data);
            Logger.Add(2, $"Hacktastic Subtitle: {data.Ship}: \"{data.Line}\"");
        }

        /// <summary>
        /// METHOD ADAPTED FROM KC3改.
        /// LICENSED UNDER MIT LICENSE, (c) Dragonjet and contributors.
        /// Gets the voice number from its filename.
        /// </summary>
        private static int getVoiceLineNumber(int id, string filename)
        {
            int computedDiff = getVoiceDiffByFilename(id, filename);
            int computedIndex = voiceDiffs.IndexOf(computedDiff);
            if (computedIndex > -1) return computedIndex + 1;
            else return computedDiff;
        }

        /// <summary>
        /// METHOD ADAPTED FROM KC3改.
        /// LICENSED UNDER MIT LICENSE, (C) Dragonjet and contributors.
        /// Gets the voice key by filename.
        /// </summary>
        private static int getVoiceDiffByFilename(int id, string filename)
        {
            int number;
            bool success;
            success = int.TryParse(filename, out number);
            if (!success)
            {
                throw new ArgumentException("Sound filename is not a number!");
            }
            else
            {
                int k = 17 * (id + 7);
                int r = number - 100000;
                for (int i = 0; i < 1000; ++i)
                {
                    int a = r + i * 99173;
                    if (a % k == 0)
                    {
                        return a / k;
                    }
                }
            }
            return -1;
        }
    }

    public enum DialogueType
    {
        Titlecall,
        NPC,
        Shipgirl
    }

    public class DialogueData
    {
        public DateTime Time { get; set; }
        public string Ship { get; set; }
        public string Line { get; set; }
    }
}


text:
<!DOCTYPE html>

  <meta charset="UTF-8">
  <title>Code Coverage for /var/www/html/Album/vendor/zendframework/zendframework/library/Zend/I18n/View/Helper/Translate.php</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <link href="css/bootstrap.min.css" rel="stylesheet">
  <link href="css/bootstrap-responsive.min.css" rel="stylesheet">
  <link href="css/style.css" rel="stylesheet">

/var/www/html/Album /

vendor /

zendframework /

zendframework /

library /

Zend /

I18n /

View /

Helper /

Translate.php

Code Coverage

Classes and Traits

Functions and Methods

Lines

      Total

0.00%

0 / 1

0.00%

0 / 1

      CRAP

85.71%

6 / 7

      Translate

0.00%

0 / 1

0.00%

0 / 1

      3.03

85.71%

6 / 7

       __invoke($message, $textDomain = null, $locale = null)

0.00%

0 / 1

      3.03

85.71%

6 / 7

1
	<?php

2

9

10
	namespace Zend\I18n\View\Helper;

11

12
	use Zend\I18n\Exception;

13

14
	/**

15
	 * View helper for translating messages.

16
	 */

17
	class Translate extends AbstractTranslatorHelper

18
	{

19
	    /**

20
	     * Translate a message

21
	     *

22
	     * @param  string $message

23
	     * @param  string $textDomain

24
	     * @param  string $locale

25
	     * @throws Exception\RuntimeException

26
	     * @return string

27
	     */

28
	    public function __invoke($message, $textDomain = null, $locale = null)

29
	    {

30
	        $translator = $this->getTranslator();

31
	        if (null === $translator) {

32
	            throw new Exception\RuntimeException('Translator has not been set');

33
	        }

34
	        if (null === $textDomain) {

35
	            $textDomain = $this->getTranslatorTextDomain();

36
	        }

37

38
	        return $translator->translate($message, $textDomain, $locale);

39
	    }

40
	}

Legend

     Executed
     Not Executed
     Dead Code

     Generated by PHP_CodeCoverage 1.2.13 using PHP 5.6.0-1+deb.sury.org~trusty+1 and PHPUnit 3.7.28 at Tue Oct 7 22:36:47 AMT 2014.


text:
define(function(require, exports, module) {
  "use strict";

  var cc = require("./cc");
  var utils  = require("./utils");
  var extend = require("../common/extend");

  var nodes = {};

  var Node = (function() {
    var nodeId = 0;
    function Node() {
      this.klassName = "Node";
      this.nodeId    = nodeId++;
      this._blocking  = true;
      nodes[this.nodeId] = this;
    }
    extend(Node, cc.Object);

    Node.prototype.play = function() {
      cc.lang.pushToTimeline([
        "/n_run", this.nodeId, true
      ]);
      return this;
    };

    Node.prototype.pause = function() {
      cc.lang.pushToTimeline([
        "/n_run", this.nodeId, false
      ]);
      return this;
    };

    Node.prototype.stop = function() {
      cc.lang.pushToTimeline([
        "/n_free", this.nodeId
      ]);
      this._blocking = false;
      return this;
    };

    Node.prototype.free = Node.prototype.stop;

    Node.prototype.set = function(args) {
      var controls = args2controls(args, this.params);
      if (controls.length) {
        cc.lang.pushToTimeline([
          "/n_set", this.nodeId, controls
        ]);
      }
      return this;
    };

    Node.prototype.release = function(releaseTime) {
      releaseTime = -1 - utils.asNumber(releaseTime);
      var controls = args2controls({ gate:releaseTime }, this.params);
      if (controls.length) {
        cc.lang.pushToTimeline([
          "/n_set", this.nodeId, controls
        ]);
      }
      return this;
    };

    Node.prototype.performWait = function() {
      return this._blocking;
    };

    Node.prototype.asString = function() {
      return this.klassName + "(" + this.nodeId + ")";
    };

    return Node;
  })();

  var Group = (function() {
    function Group(target, addAction) {
      Node.call(this);
      this.klassName = "Group";
      if (target instanceof Node) {
        cc.lang.pushToTimeline([
          "/g_new", this.nodeId, addAction, target.nodeId
        ]);
      }
    }
    extend(Group, Node);

    return Group;
  })();

  var Synth = (function() {
    function Synth(target, addAction, def, args) {
      Node.call(this);
      this.klassName = "Synth";
      if (target instanceof Node && cc.instanceOfSynthDef(def)) {
        this.params  = def.specs.params;
        var nodeId   = this.nodeId;
        var controls = args2controls(args, this.params);
        cc.lang.pushToTimeline([
          "/s_new", nodeId, addAction, target.nodeId, def._defId, controls
        ]);
      }
    }
    extend(Synth, Node);

    return Synth;
  })();

  var args2controls = function(args, params) {
    var controls = [];
    if (utils.isDict(args) && params) {
      Object.keys(args).forEach(function(key) {
        var value  = args[key];
        var index  = params.names.indexOf(key);
        if (index === -1) {
          return;
        }
        var length = params.length[index];
        index = params.indices[index];
        if (Array.isArray(value)) {
          value.forEach(function(value, i) {
            if (i < length) {
              if (typeof value === "number" && !isNaN(value)) {
                controls.push(index + i, value);
              }
            }
          });
        } else if (typeof value === "number" && !isNaN(value)) {
          controls.push(index, value);
        }
      });
    }
    return controls;
  };

  var sortArgs = function(list) {
    var node, def, args;
    if (cc.instanceOfSynthDef(list[0])) {
      node = cc.lang.rootNode;
      def  = list[0];
      args = list[1] || {};
    } else if (cc.instanceOfSynthDef(list[1])) {
      node = list[0];
      def  = list[1];
      args = list[2] || {};
    } else {
      node = cc.lang.rootNode;
      def  = null;
      args = {};
    }
    return [node, def, args];
  };

  cc.global.Group = function() {
    var target, addAction = C.ADD_TO_HEAD;
    var i = 0;
    if (cc.instanceOfNode(arguments[i])) {
      target = arguments[i++];
    } else {
      target = cc.lang.rootNode;
    }
    if (typeof arguments[i] === "string") {
      addAction = {
        addToHead:C.ADD_TO_HEAD, addToTail:C.ADD_TO_TAIL, addBefore:C.ADD_BEFORE, addAfter:C.ADD_AFTER, replace:C.REPLACE
      }[arguments[i++]] || C.ADD_TO_HEAD;
    } else if (typeof arguments[i] === "number") {
      if (0 <= arguments[i] && arguments[i] <= 4) {
        addAction = arguments[i++];
      }
    }
    return new Group(target, addAction);
  };
  cc.global.Group["new"] = cc.global.Group;
  cc.global.Group.after = function(node) {
    return new Group(node || cc.lang.rootNode, C.ADD_AFTER);
  };
  cc.global.Group.before = function(node) {
    return new Group(node || cc.lang.rootNode, C.ADD_BEFORE);
  };
  cc.global.Group.head = function(node) {
    return new Group(node || cc.lang.rootNode, C.ADD_TO_HEAD);
  };
  cc.global.Group.tail = function(node) {
    return new Group(node || cc.lang.rootNode, C.ADD_TO_TAIL);
  };
  cc.global.Group.replace = function(node) {
    return new Group(node, C.REPLACE);
  };

  cc.global.Synth = function(def) {
    var args, target, addAction = C.ADD_TO_HEAD;
    var i = 1;
    if (utils.isDict(arguments[i])) {
      args = arguments[i++];
    } else {
      args = {};
    }
    if (cc.instanceOfNode(arguments[i])) {
      target = arguments[i++];
    } else {
      target = cc.lang.rootNode;
    }
    if (typeof arguments[i] === "string") {
      addAction = {
        addToHead:C.ADD_TO_HEAD, addToTail:C.ADD_TO_TAIL, addBefore:C.ADD_BEFORE, addAfter:C.ADD_AFTER, replace:C.REPLACE
      }[arguments[i++]] || C.ADD_TO_HEAD;
    } else if (typeof arguments[i] === "number") {
      if (0 <= arguments[i] && arguments[i] <= 4) {
        addAction = arguments[i++];
      }
    }
    return new Synth(target, addAction, def, args);
  };
  cc.global.Synth["new"] = cc.global.Synth;
  cc.global.Synth.after = function() {
    var list = sortArgs(arguments);
    return new Synth(list[0], C.ADD_AFTER, list[1], list[2]);
  };
  cc.global.Synth.before = function() {
    var list = sortArgs(arguments);
    return new Synth(list[0], C.ADD_BEFORE, list[1], list[2]);
  };
  cc.global.Synth.head = function() {
    var list = sortArgs(arguments);
    return new Synth(list[0], C.ADD_TO_HEAD, list[1], list[2]);
  };
  cc.global.Synth.tail = function() {
    var list = sortArgs(arguments);
    return new Synth(list[0], C.ADD_TO_TAIL, list[1], list[2]);
  };
  cc.global.Synth.replace = function(node, def, args) {
    return new Synth(node, C.REPLACE, def, args);
  };

  cc.createLangRootNode = function() {
    return new Group();
  };
  cc.instanceOfNode = function(obj) {
    return obj instanceof Node;
  };
  cc.instanceOfGroup = function(obj) {
    return obj instanceof Group;
  };
  cc.instanceOfSynth = function(obj) {
    return obj instanceof Synth;
  };
  cc.getNode   = function(nodeId) {
    return nodes[nodeId];
  };
  cc.resetNode = function() {
    nodes = {};
  };

  module.exports = {
    Node : Node,
    Group: Group,
    Synth: Synth,
    args2controls: args2controls
  };

});