text:
package net.sf.sparql.benchmarking.monitoring;

import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;

import net.sf.sparql.benchmarking.operations.Operation;
import net.sf.sparql.benchmarking.operations.OperationMix;
import net.sf.sparql.benchmarking.options.BenchmarkOptions;
import net.sf.sparql.benchmarking.options.Options;
import net.sf.sparql.benchmarking.runners.Runner;
import net.sf.sparql.benchmarking.stats.OperationMixRun;
import net.sf.sparql.benchmarking.stats.OperationRun;
import net.sf.sparql.benchmarking.util.FileUtils;

/**
 * A Progress Listener that generates a XML output file
 *
 * @author rvesse
 */
public class XmlProgressListener implements ProgressListener {

    private File file;
    private PrintWriter writer;
    private int indent = 0;
    private boolean allowOverwrite = false;

    //@formatter:off
    /**
     * Constants for Tag and Attribute Names
     */
    @SuppressWarnings("javadoc")
    public static final String TAG_SPARQL_BENCHMARK = "sparqlBenchmark",
                               TAG_CONFIGURATION = "configuration",
                               TAG_CONFIG_PROPERTY = "property",
                               ATTR_ID = "id",
                               ATTR_NAME = "name",
                               ATTR_VALUE = "value",
                               ATTR_TYPE = "type",
                               TAG_OPERATIONS = "operations",
                               TAG_OPERATION = "operation",
                               TAG_MIX_RUNS = "operationMixRuns",
                               TAG_MIX_RUN = "operationMixRun",
                               TAG_STATS = "statistics",
                               TAG_SUMMARY = "summary",
                               ATTR_COMPRESSION = "compression",
                               ATTR_LIMIT = "limit",
                               ATTR_LOCAL_LIMIT = "localLimit",
                               ATTR_COUNTING = "counting",
                               ATTR_THREADS = "threads",
                               ATTR_SELECT_FORMAT = "selectFormat",
                               ATTR_GRAPH_FORMAT = "graphFormat",
                               ATTR_ASK_FORMAT = "askFormat",
                               ATTR_MAX_DELAY = "maxDelay",
                               ATTR_TIMEOUT = "timeout",
                               ATTR_OUTLIERS = "outliers",
                               ATTR_RANDOM_ORDER = "randomOrder",
                               ATTR_RUNS = "runs",
                               ATTR_WARMUPS = "warmups",
                               ATTR_SANITY_CHECKING = "sanityChecking",
                               ATTR_QUERY_ENDPOINT = "queryEndpoint",
                               ATTR_RESPONSE_TIME = "responseTime",
                               ATTR_TOTAL_RESPONSE_TIME = "totalResponseTime",
                               ATTR_RUNTIME = "runtime",
                               ATTR_RESULT_COUNT = "resultCount",
                               ATTR_TOTAL_RUNTIME = "totalRuntime",
                               ATTR_ACTUAL_RUNTIME = "actualRuntime",
                               ATTR_ACTUAL_AVG_RUNTIME = "averageActualRuntime",
                               ATTR_MIN_OPERATION_RUNTIME = "minOperationRuntime",
                               ATTR_MAX_OPERATION_RUNTIME = "maxOperationRuntime",
                               ATTR_MIN_MIX_RUNTIME = "minMixRuntime",
                               ATTR_MAX_MIX_RUNTIME = "maxMixRuntime",
                               ATTR_AVG_RUNTIME = "averageRuntime",
                               ATTR_AVG_RUNTIME_GEOM = "averageRuntimeGeometric",
                               ATTR_AVG_RESPONSE_TIME = "averageResponseTime",
                               ATTR_AVG_RESPONSE_TIME_GEOM = "averageResponseTimeGeometric",
                               ATTR_VARIANCE = "variance",
                               ATTR_STD_DEV = "standardDeviation",
                               ATTR_OPS = "operationsPerSecond",
                               ATTR_ACTUAL_OPS = "actualOperationsPerSecond",
                               ATTR_OPH = "operationsPerHour",
                               ATTR_ACTUAL_OPH = "actualOperationsPerHour",
                               ATTR_OMPH = "operationMixesPerHour",
                               ATTR_ACTUAL_OMPH = "actualOperationMixesPerHour",
                               ATTR_FASTEST_OPERATION = "fastestOperation",
                               ATTR_SLOWEST_OPERATION = "slowestOperation",
                               ATTR_RUN_ORDER = "runOrder";
    //@formatter:on

    /**
     * Creates a new XML progress listener which writes to the given path unless
     * it already exists
     *
     * @param outputPath
     *            Output File Path
     */
    public XmlProgressListener(String outputPath) {
        this(outputPath, false);
    }

    /**
     * Constructor to be called when the file to write to is known in advance of
     * benchmarking
     *
     * @param outputPath
     *            Output File Path
     * @param allowOverwrite
     *            Whether overwriting an existing file is permitted
     */
    public XmlProgressListener(String outputPath, boolean allowOverwrite) {
        this.setup(outputPath, allowOverwrite);
    }

    /**
     * Sets up the file for output throwing an error if the file cannot be
     * written to
     *
     * @param outputPath
     *            Output File Path
     */
    private void setup(String outputPath, boolean allowOverwrite) {
        this.file = new File(outputPath);
        this.allowOverwrite = allowOverwrite;
    }

    /**
     * Handles the started event by printing run configuration to the XML file
     */
    @Override
    public <T extends Options> void start(Runner<T> runner, T options) {
        if (!FileUtils.checkFile(this.file, allowOverwrite)) {
            throw new RuntimeException("XML Output File is not a file, already exists or is not writable");
        }

        BenchmarkOptions bOps = null;
        if (options instanceof BenchmarkOptions) {
            bOps = (BenchmarkOptions) options;
        }

        try {
            // Open Print Writer
            writer = new PrintWriter(file);

            // Generate XML Header
            writer.println("<?xml version=\"1.0\"?>");
            openTag(TAG_SPARQL_BENCHMARK);

            // Generate an <configuration> element detailing configuration
            openTag(TAG_CONFIGURATION);
            printProperty(ATTR_QUERY_ENDPOINT, options.getQueryEndpoint());
            if (bOps != null) {
                printProperty(ATTR_SANITY_CHECKING, bOps.getSanityCheckLevel());
            }
            if (bOps != null) {
                printProperty(ATTR_WARMUPS, bOps.getWarmups());
                printProperty(ATTR_RUNS, bOps.getRuns());
            }
            printProperty(ATTR_RANDOM_ORDER, options.getRandomizeOrder());
            if (bOps != null) {
                printProperty(ATTR_OUTLIERS, bOps.getOutliers());
            }
            printProperty(ATTR_TIMEOUT, options.getTimeout() > 0 ? Integer.toString(options.getTimeout()) : "disabled");
            printProperty(ATTR_MAX_DELAY, options.getMaxDelay());
            printProperty(ATTR_ASK_FORMAT, options.getResultsAskFormat());
            printProperty(ATTR_GRAPH_FORMAT, options.getResultsGraphFormat());
            printProperty(ATTR_SELECT_FORMAT, options.getResultsSelectFormat());
            printProperty(ATTR_THREADS, options.getParallelThreads());
            printProperty(ATTR_COUNTING, !options.getNoCount());
            printProperty(ATTR_LIMIT, options.getLimit());
            printProperty(ATTR_LOCAL_LIMIT, options.getLocalLimit());
            printProperty(ATTR_COMPRESSION, options.getAllowCompression());

            // Print Queries
            openTag(TAG_OPERATIONS);
            OperationMix mix = options.getOperationMix();
            Iterator<Operation> ops = mix.getOperations();
            int id = 0;
            while (ops.hasNext()) {
                Operation op = ops.next();
                openTag(TAG_OPERATION, true);
                addAttribute(ATTR_ID, id);
                addAttribute(ATTR_NAME, op.getName());
                addAttribute(ATTR_TYPE, op.getType());
                id++;
                finishAttributes();

                openCData();
                writer.print(op.getContentString());
                closeCData();
                closeTag(TAG_OPERATION);
            }
            closeTag(TAG_OPERATIONS);

            closeTag(TAG_CONFIGURATION);

            // Open Tag for Mix Run stats
            openTag(TAG_MIX_RUNS);

            writer.flush();
        } catch (Exception e) {
            System.err.println("Unexpected error writing XML stats");
            runner.halt(options, e.getMessage());
        }
    }

    protected void printProperty(String name, int value) {
        printProperty(name, Integer.toString(value));
    }

    protected void printProperty(String name, long value) {
        printProperty(name, Long.toString(value));
    }

    protected void printProperty(String name, boolean value) {
        printProperty(name, Boolean.toString(value));
    }

    protected void printProperty(String name, String value) {
        openTag(TAG_CONFIG_PROPERTY, true);
        addAttribute(ATTR_NAME, name);
        if (value == null)
            value = "";
        addAttribute(ATTR_VALUE, value);
        finishAttributes(true);
    }

    /**
     * Handles the finished event by printing statistics to the XML file
     *
     * @param ok
     *            Whether benchmarking finished OK
     */
    @Override
    public <T extends Options> void finish(Runner<T> runner, T options, boolean ok) {
        if (writer == null)
            throw new RuntimeException(
                    "handleFinished() on XmlProgressListener was called but it appears handleStarted() was never called, another listener may have caused handleStarted() to be bypassed for this listener");

        try {
            closeTag(TAG_MIX_RUNS);

            openTag(TAG_STATS);

            boolean wasMultithreaded = options.getParallelThreads() > 1;

            // Query Summary
            openTag(TAG_OPERATIONS);
            OperationMix mix = options.getOperationMix();
            Iterator<Operation> ops = mix.getOperations();
            int id = 0;
            while (ops.hasNext()) {
                Operation op = ops.next();
                openTag(TAG_OPERATION, true);

                // Per-operation summary
                addAttribute(ATTR_ID, id);
                addAttribute(ATTR_NAME, op.getName());
                addAttribute(ATTR_TYPE, op.getType());
                addAttribute(ATTR_TOTAL_RESPONSE_TIME, op.getStats().getTotalResponseTime());
                addAttribute(ATTR_AVG_RESPONSE_TIME, op.getStats().getAverageResponseTime());
                addAttribute(ATTR_TOTAL_RUNTIME, op.getStats().getTotalRuntime());
                if (wasMultithreaded)
                    addAttribute(ATTR_ACTUAL_RUNTIME, op.getStats().getActualRuntime());
                addAttribute(ATTR_AVG_RUNTIME, op.getStats().getAverageRuntime());
                if (wasMultithreaded)
                    addAttribute(ATTR_ACTUAL_AVG_RUNTIME, op.getStats().getActualAverageRuntime());
                addAttribute(ATTR_AVG_RUNTIME_GEOM, op.getStats().getGeometricAverageRuntime());
                addAttribute(ATTR_MIN_OPERATION_RUNTIME, op.getStats().getMinimumRuntime());
                addAttribute(ATTR_MAX_OPERATION_RUNTIME, op.getStats().getMaximumRuntime());
                addAttribute(ATTR_VARIANCE, op.getStats().getVariance());
                addAttribute(ATTR_STD_DEV, op.getStats().getStandardDeviation());
                addAttribute(ATTR_OPS, op.getStats().getOperationsPerSecond());
                if (wasMultithreaded)
                    addAttribute(ATTR_ACTUAL_OPS, op.getStats().getActualOperationsPerSecond());
                addAttribute(ATTR_OPH, op.getStats().getOperationsPerHour());
                if (wasMultithreaded)
                    addAttribute(ATTR_ACTUAL_OPH, op.getStats().getActualOperationsPerHour());
                finishAttributes(true);

                id++;
            }
            closeTag(TAG_OPERATIONS);

            // Overall Summary
            openTag(TAG_SUMMARY, true);
            addAttribute(ATTR_TOTAL_RESPONSE_TIME, mix.getStats().getTotalResponseTime());
            addAttribute(ATTR_AVG_RESPONSE_TIME, mix.getStats().getAverageResponseTime());
            addAttribute(ATTR_TOTAL_RUNTIME, mix.getStats().getTotalRuntime());
            if (wasMultithreaded)
                addAttribute(ATTR_ACTUAL_RUNTIME, mix.getStats().getActualRuntime());
            addAttribute(ATTR_AVG_RUNTIME, mix.getStats().getAverageRuntime());
            if (wasMultithreaded)
                addAttribute(ATTR_ACTUAL_AVG_RUNTIME, mix.getStats().getActualAverageRuntime());
            addAttribute(ATTR_AVG_RUNTIME_GEOM, mix.getStats().getGeometricAverageRuntime());
            addAttribute(ATTR_MIN_MIX_RUNTIME, mix.getStats().getMinimumRuntime());
            addAttribute(ATTR_MAX_MIX_RUNTIME, mix.getStats().getMaximumRuntime());
            addAttribute(ATTR_VARIANCE, mix.getStats().getVariance());
            addAttribute(ATTR_STD_DEV, mix.getStats().getStandardDeviation());
            addAttribute(ATTR_OMPH, mix.getStats().getOperationMixesPerHour());
            if (wasMultithreaded)
                addAttribute(ATTR_ACTUAL_OMPH, mix.getStats().getActualOperationMixesPerHour());
            finishAttributes(true);

            closeTag(TAG_STATS);
            closeTag(TAG_SPARQL_BENCHMARK);

            writer.flush();
            writer.close();
        } catch (Exception e) {
            System.err.println("Unexpected error writing XML stats " + e);
            e.printStackTrace();
            if (options.getHaltAny() || options.getHaltOnError())
                runner.halt(options, e.getMessage());
        }
    }

    @Override
    public <T extends Options> void progress(Runner<T> runner, T options, String message) {
        // Not relevant for XML output
    }

    /**
     * Does nothing as this listener discards individual operation run
     * statistics
     *
     * @param operation
     *            Benchmark Operation
     */
    @Override
    public <T extends Options> void beforeOperation(Runner<T> runner, T options, Operation operation) {
        // We don't handle before operation events
    }

    @Override
    public <T extends Options> void afterOperation(Runner<T> runner, T options, Operation operation, OperationRun run) {
        // We don't handle individual operation run stats, we only handle mix
        // and
        // aggregate stats
    }

    @Override
    public <T extends Options> void beforeOperationMix(Runner<T> runner, T options, OperationMix mix) {
        // We don't handle before operation mix events
    }

    @Override
    public synchronized <T extends Options> void afterOperationMix(Runner<T> runner, T options, OperationMix mix,
            OperationMixRun run) {
        // Print run information
        openTag(TAG_MIX_RUN, true);

        this.addAttribute(ATTR_RUN_ORDER, run.getRunOrder());
        this.addAttribute(ATTR_TOTAL_RESPONSE_TIME, run.getTotalResponseTime());
        this.addAttribute(ATTR_TOTAL_RUNTIME, run.getTotalRuntime());
        this.addAttribute(ATTR_MIN_OPERATION_RUNTIME, run.getMinimumRuntime());
        this.addAttribute(ATTR_MAX_OPERATION_RUNTIME, run.getMaximumRuntime());
        this.addAttribute(ATTR_FASTEST_OPERATION, run.getMinimumRuntimeOperationID());
        this.addAttribute(ATTR_SLOWEST_OPERATION, run.getMaximumRuntimeOperationID());

        finishAttributes();

        Iterator<OperationRun> rs = run.getRuns();
        while (rs.hasNext()) {
            OperationRun r = rs.next();
            openTag(TAG_OPERATION, true);
            addAttribute(ATTR_ID, r.getId());
            addAttribute(ATTR_RUN_ORDER, r.getRunOrder());
            addAttribute(ATTR_RESPONSE_TIME, r.getResponseTime());
            addAttribute(ATTR_RUNTIME, r.getRuntime());
            addAttribute(ATTR_RESULT_COUNT, r.getResultCount());

            if (r.getErrorMessage() != null) {
                finishAttributes();
                writer.print(escape(r.getErrorMessage()));
                closeTag(TAG_OPERATION);
            } else {
                finishAttributes(true);
            }
        }

        closeTag(TAG_MIX_RUN);

        writer.flush();
    }

    private void openTag(String tagname) {
        openTag(tagname, false);
    }

    private void openTag(String tagname, boolean allowAttributes) {
        if (allowAttributes) {
            writer.print(indent() + "<" + tagname);
        } else {
            writer.println(indent() + "<" + tagname + ">");
            indent++;
        }
    }

    private void closeTag(String tagname) {
        indent--;
        writer.println(indent() + "</" + tagname + ">");
    }

    private void openCData() {
        indent++;
        writer.println(indent() + "<![CDATA[");
    }

    private void closeCData() {
        writer.println("]]>");
        indent--;
    }

    private void addAttribute(String attr, int value) {
        addAttribute(attr, Integer.toString(value));
    }

    private void addAttribute(String attr, long value) {
        addAttribute(attr, Long.toString(value));
    }

    private void addAttribute(String attr, double value) {
        addAttribute(attr, Double.toString(value));
    }

    private void addAttribute(String attr, String value) {
        writer.print(' ');
        writer.print(attr);
        writer.print('=');
        writer.print('"');
        writer.print(escapeForAttribute(value));
        writer.print('"');
    }

    private void finishAttributes() {
        finishAttributes(false);
    }

    private void finishAttributes(boolean closeTag) {
        if (closeTag)
            writer.print(" /");
        writer.println(">");
        if (!closeTag)
            indent++;
    }

    @SuppressWarnings("unused")
    private void printTag(String tagname, String value) {
        writer.println(indent() + "<" + tagname + ">" + escape(value) + "</" + tagname + ">");
    }

    private String indent() {
        if (indent == 0)
            return "";
        StringBuffer buffer = new StringBuffer();
        int i = 0;
        while (i < indent) {
            buffer.append(' ');
            i++;
        }
        return buffer.toString();
    }

    private String escape(String string) {
        final StringBuilder sb = new StringBuilder(string);

        int offset = 0;
        String replacement;
        char found;
        for (int i = 0; i < string.length(); i++) {
            found = string.charAt(i);

            switch (found) {
            case '&':
                replacement = "&";
                break;
            case '<':
                replacement = "<";
                break;
            case '>':
                replacement = ">";
                break;
            case '\r':
                replacement = "
";
                break;
            case '\n':
                replacement = "
";
                break;
            default:
                replacement = null;
            }

            if (replacement != null) {
                sb.replace(offset + i, offset + i + 1, replacement);
                offset += replacement.length() - 1; // account for added chars
            }
        }

        return sb.toString();
    }

    private String escapeForAttribute(String string) {
        string = escape(string);
        return string.replace("\"", """);
    }
}


text:
<?php

/**
 * Description of BaseReportEmployeeController
 *
 * @author ben.dokter
 */

require_once('modules/model/service/report/BaseReportController.class.php');

class BaseReportEmployeeController extends BaseReportController
{

}

?>

redpajama_set_name: RedPajamaGithub


text:
<?php

namespace Presta\SitemapBundle\Tests\Integration\Controller;

use Presta\SitemapBundle\Messenger\DumpSitemapMessage;
use Symfony\Component\HttpFoundation\Request;
use Symfony\Component\HttpFoundation\Response;
use Symfony\Component\Messenger\MessageBusInterface;
use Symfony\Component\Routing\Annotation\Route;

final class MessengerController
{
    /**
     * @Route("/dispatch-message", name="dispatch_message")
     */
    #[Route(path: '/dispatch-message', name: 'dispatch_message')]
    public function dispatch(Request $request, MessageBusInterface $bus): Response
    {
        $bus->dispatch(new DumpSitemapMessage(null, null, null, ['gzip' => $request->query->getBoolean('gzip')]));

        return new Response(__FUNCTION__);
    }
}


text:
define(function(require, exports, module) {

exports.isDark = true;
exports.cssClass = "ace--rebecca-dark";
exports.cssText = require("../requirejs/text!./Rebecca-dark.css");

var dom = require("../lib/dom");
dom.importCssString(exports.cssText, exports.cssClass);
});


text:
/**
 * Created by qichenglao on 2015-08-05.
 */

var Client = function() {

    this.__contruct = function() {
        console.log("Client Created");
        Template = new Template();
        Event = new Event();
        Result = new Result();

        get_client();
        delete_client();

    };

    //---------------------------------------------------------------------------

    var get_client = function() {
        $.get('api/get_client', function(o) {

            var output = '';
            for(var i = 0; i < o.length; i++) {
                output += Template.client(o[i]);
            }
            $("#client_table").html(output);

        }, 'json');

    };

    var delete_client = function() {
        $("body").on('click', '.client_delete', function(evt) {
            evt.preventDefault();

            var self = $(this).closest('tr');
            var url = $(this).attr('href');
            var postData = {
                'client_id': $(this).attr('client_id')
            };

            $.post(url, postData, function(o) {
                if(o.result == 1) {
                    Result.success('Client successfully deleted.');
                    self.remove();
                } else {
                    Result.error(o.error);
                }
            }, 'json');
        });
    };

    this.__contruct();

};


text:
'use strict';

var fnArgs = require('fn-args');
var poppies = {};

function isRegistering(name) {
  return typeof name === 'string';
}

function getDep(name) {
  if (!name) {
    throw new Error('No dependencies specified?');
  }
  if (!poppies[name]) {
    throw new Error('Couldn\'t Pop: ' + name);
  }
  if (typeof poppies[name].value === 'function') {
    return poppies[name].value.bind(poppies[name].context);
  } else {
    return poppies[name].value;
  }
}

function register(name, value, context) {
  poppies[name] = {
    value: value,
    context: context
  };
}

function pop(name, value) {
  if (isRegistering(name)) {
    register.apply(null, [].slice.call(arguments));
    return;
  }

  var fn = arguments[0];
  var context = arguments[arguments.length - 1];

  return function () {
    return fn.apply(context, fnArgs(fn).map(getDep));
  };
}

module.exports = pop;


text:
'use strict';
let sql; // 放到内部require,可以做成非强制依赖。
class MSSQL {
  constructor(config) {
    this.config = config;
    sql = require('mssql');
    this.connection = new sql.Connection(this.config);
  }

  _buildRequestParams(request, params, outputParams) {
    if (params && typeof params === 'object') {
      Object.keys(params).forEach((key, value) => {
        if (value.type && value.value) {
          request.input(key, value.type, value.value);
        } else {
          request.input(key, value);
        }
      });
    }
    if (outputParams && typeof outputParams === 'object') {
      Object.keys(params).forEach((key, type) => {
        request.output(key, type);
      });
    }
  }

  _getOpenedConnection(callback) {
    if (this.connection.connected) {
      return callback(null);
    }
    this.connection.connect((err) => {
      callback(err);
    });
  }

  _executeQuery(type, commandText, params) {
    let request = new sql.Request(this.connection);
    this._buildRequestParams(request, params);
    return new Promise((resolve, reject) => {
      this._getOpenedConnection((err) => {
        if (err) {
          return reject(err);
        }
        request.query(commandText, (err2, recordset, returnValue) => {
          if (err2) {
            return reject(err2);
          }
          let result;
          switch (type) {
            case 'nonQuery':
              result = returnValue;
              break;
            case 'scalar':
              result = recordset[0];
              if (typeof result === 'object' && result['']) {
                result = result[''];
              }
              break;
            case 'query':
              result = recordset;
              break;
          }
          resolve(result);
        });
      });
    });
  }

  getConnection() {
    return this.connection;
  }

  executeNonQuery(commandText, params) {
    return this._executeQuery('nonQuery', commandText, params);
  }

  executeScalar(commandText, params) {
    return this._executeQuery('scalar', commandText, params);
  }

  executeQuery(commandText, params) {
    return this._executeQuery('query', commandText, params);
  }

  executeProcedure(procedureName, params, outputParams) {
    let request = new sql.Request(this.connection);
    this._buildRequestParams(request, params, outputParams);
    return new Promise((resolve, reject) => {
      this._getOpenedConnection((err) => {
        if (err) {
          return reject(err);
        }
        request.execute(procedureName, (err2, recordset, returnValue, affected) => {
          if (err2) {
            return reject(err2);
          }
          let resultOutput = {};
          if (outputParams) {
            Object.keys(outputParams).forEach((key) => {
              resultOutput[key] = request.parameters[key].value
            });
          }
          resolve({
            result: recordset,
            affectedRowCount: affected,
            output: resultOutput
          });
        });
      });
    });
  }

  newTransaction() {
    return new sql.Transaction(this.connection);
  }

  // useTransaction(promiseArr) {
  //   Promise.all(promiseArr)
  // }
}

module.exports = MSSQL;


text:
<?php

require_once 'propel/engine/database/reverse/BaseSchemaParser.php';

/**
 * Mysql database schema parser.
 *
 * @author     Hans Lellelid <hans@xmpl.org>
 * @version    $Revision: 1262 $
 * @package    propel.engine.database.reverse.mysql
 */
class MysqlSchemaParser extends BaseSchemaParser {

	/**
	 * @var        boolean
	 */
	private $addVendorInfo = false;

	/**
	 * Map MySQL native types to Propel types.
	 * @var        array
	 */
	private static $mysqlTypeMap = array(
		'tinyint' => PropelTypes::TINYINT,
		'smallint' => PropelTypes::SMALLINT,
		'mediumint' => PropelTypes::SMALLINT,
		'int' => PropelTypes::INTEGER,
		'integer' => PropelTypes::INTEGER,
		'bigint' => PropelTypes::BIGINT,
		'int24' => PropelTypes::BIGINT,
		'real' => PropelTypes::REAL,
		'float' => PropelTypes::FLOAT,
		'decimal' => PropelTypes::DECIMAL,
		'numeric' => PropelTypes::NUMERIC,
		'double' => PropelTypes::DOUBLE,
		'char' => PropelTypes::CHAR,
		'varchar' => PropelTypes::VARCHAR,
		'date' => PropelTypes::DATE,
		'time' => PropelTypes::TIME,
		'year' => PropelTypes::INTEGER,
		'datetime' => PropelTypes::TIMESTAMP,
		'timestamp' => PropelTypes::TIMESTAMP,
		'tinyblob' => PropelTypes::BINARY,
		'blob' => PropelTypes::BLOB,
		'mediumblob' => PropelTypes::BLOB,
		'longblob' => PropelTypes::BLOB,
		'longtext' => PropelTypes::CLOB,
		'tinytext' => PropelTypes::VARCHAR,
		'mediumtext' => PropelTypes::LONGVARCHAR,
		'text' => PropelTypes::LONGVARCHAR,
		'enum' => PropelTypes::CHAR,
		'set' => PropelTypes::CHAR,
	);

	/**
	 * Gets a type mapping from native types to Propel types
	 *
	 * @return     array
	 */
	protected function getTypeMapping()
	{
		return self::$mysqlTypeMap;
	}

	/**
	 *
	 */
	public function parse(Database $database)
	{
		$this->addVendorInfo = $this->getGeneratorConfig()->getBuildProperty('addVendorInfo');

		$stmt = $this->dbh->query("SHOW TABLES");

		// First load the tables (important that this happen before filling out details of tables)
		$tables = array();
		while ($row = $stmt->fetch(PDO::FETCH_NUM)) {
			$name = $row[0];
			$table = new Table($name);
			$database->addTable($table);
			$tables[] = $table;
		}

		// Now populate only columns.
		foreach ($tables as $table) {
			$this->addColumns($table);
		}

		// Now add indexes and constraints.
		foreach ($tables as $table) {
			$this->addForeignKeys($table);
			$this->addIndexes($table);
			$this->addPrimaryKey($table);
			if ($this->addVendorInfo) {
				$this->addTableVendorInfo($table);
			}
		}
	}

	/**
	 * Adds Columns to the specified table.
	 *
	 * @param      Table $table The Table model class to add columns to.
	 */
	protected function addColumns(Table $table)
	{
		$stmt = $this->dbh->query("SHOW COLUMNS FROM `" . $table->getName() . "`");

		while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {

			$name = $row['Field'];
			$is_nullable = ($row['Null'] == 'YES');
			$autoincrement = (strpos($row['Extra'], 'auto_increment') !== false);
			$size = null;
			$precision = null;
			$scale = null;

			if (preg_match('/^(\w+)[\(]?([\d,]*)[\)]?( |$)/', $row['Type'], $matches)) {
				//            colname[1]   size/precision[2]
				$nativeType = $matches[1];
				if ($matches[2]) {
					if ( ($cpos = strpos($matches[2], ',')) !== false) {
						$size = (int) substr($matches[2], 0, $cpos);
						$precision = $size;
						$scale = (int) substr($matches[2], $cpos + 1);
					} else {
						$size = (int) $matches[2];
					}
				}
			} elseif (preg_match('/^(\w+)\(/', $row['Type'], $matches)) {
				$nativeType = $matches[1];
			} else {
				$nativeType = $row['Type'];
			}

			//BLOBs can't have any default values in MySQL
			$default = preg_match('~blob|text~', $nativeType) ? null : $row['Default'];

			$propelType = $this->getMappedPropelType($nativeType);
			if (!$propelType) {
				$propelType = Column::DEFAULT_TYPE;
				$this->warn("Column [" . $table->getName() . "." . $name. "] has a column type (".$nativeType.") that Propel does not support.");
			}

			$column = new Column($name);
			$column->setTable($table);
			$column->setDomainForType($propelType);
			// We may want to provide an option to include this:
			// $column->getDomain()->replaceSqlType($type);
			$column->getDomain()->replaceSize($size);
			$column->getDomain()->replaceScale($scale);
			if ($default !== null) {
				$column->getDomain()->setDefaultValue(new ColumnDefaultValue($default, ColumnDefaultValue::TYPE_VALUE));
			}
			$column->setAutoIncrement($autoincrement);
			$column->setNotNull(!$is_nullable);

			if ($this->addVendorInfo) {
				$vi = $this->getNewVendorInfoObject($row);
				$column->addVendorInfo($vi);
			}

			$table->addColumn($column);
		}

	} // addColumn()

	/**
	 * Load foreign keys for this table.
	 */
	protected function addForeignKeys(Table $table)
	{
		$database = $table->getDatabase();

		$stmt = $this->dbh->query("SHOW CREATE TABLE `" . $table->getName(). "`");
		$row = $stmt->fetch(PDO::FETCH_NUM);

		$foreignKeys = array(); // local store to avoid duplicates

		// Get the information on all the foreign keys
		$regEx = '/CONSTRAINT `([^`]+)` FOREIGN KEY \((.+)\) REFERENCES `([^`]*)` \((.+)\)(.*)/';
		if (preg_match_all($regEx,$row[1],$matches)) {
			$tmpArray = array_keys($matches[0]);
			foreach ($tmpArray as $curKey) {
				$name = $matches[1][$curKey];
				$rawlcol = $matches[2][$curKey];
				$ftbl = $matches[3][$curKey];
				$rawfcol = $matches[4][$curKey];
				$fkey = $matches[5][$curKey];

				$lcols = array();
				foreach(preg_split('/`, `/', $rawlcol) as $piece) {
					$lcols[] = trim($piece, '` ');
				}

				$fcols = array();
				foreach(preg_split('/`, `/', $rawfcol) as $piece) {
					$fcols[] = trim($piece, '` ');
				}

				//typical for mysql is RESTRICT
				$fkactions = array(
					'ON DELETE'	=> ForeignKey::RESTRICT,
					'ON UPDATE'	=> ForeignKey::RESTRICT,
				);

				if ($fkey) {
					//split foreign key information -> search for ON DELETE and afterwords for ON UPDATE action
					foreach (array_keys($fkactions) as $fkaction) {
						$result = NULL;
						preg_match('/' . $fkaction . ' (' . ForeignKey::CASCADE . '|' . ForeignKey::SETNULL . ')/', $fkey, $result);
						if ($result && is_array($result) && isset($result[1])) {
							$fkactions[$fkaction] = $result[1];
						}
					}
				}

				$localColumns = array();
				$foreignColumns = array();

				$foreignTable = $database->getTable($ftbl);

				foreach($fcols as $fcol) {
					$foreignColumns[] = $foreignTable->getColumn($fcol);
				}
				foreach($lcols as $lcol) {
					$localColumns[] = $table->getColumn($lcol);
				}

				if (!isset($foreignKeys[$name])) {
					$fk = new ForeignKey($name);
					$fk->setForeignTableName($foreignTable->getName());
					$fk->setOnDelete($fkactions['ON DELETE']);
					$fk->setOnUpdate($fkactions['ON UPDATE']);
					$table->addForeignKey($fk);
					$foreignKeys[$name] = $fk;
				}

				for($i=0; $i < count($localColumns); $i++) {
					$foreignKeys[$name]->addReference($localColumns[$i], $foreignColumns[$i]);
				}

			}

		}

	}

	/**
	 * Load indexes for this table
	 */
	protected function addIndexes(Table $table)
	{
		$stmt = $this->dbh->query("SHOW INDEX FROM `" . $table->getName() . "`");

		// Loop through the returned results, grouping the same key_name together
		// adding each column for that key.

		$indexes = array();
		while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			$colName = $row["Column_name"];
			$name = $row["Key_name"];

			if ($name == "PRIMARY") {
				continue;
			}

			if (!isset($indexes[$name])) {
				$isUnique = ($row["Non_unique"] == 0);
				if ($isUnique) {
					$indexes[$name] = new Unique($name);
				} else {
					$indexes[$name] = new Index($name);
				}
				if ($this->addVendorInfo) {
					$vi = $this->getNewVendorInfoObject($row);
					$indexes[$name]->addVendorInfo($vi);
				}
				$table->addIndex($indexes[$name]);
			}

			$indexes[$name]->addColumn($table->getColumn($colName));
		}
	}

	/**
	 * Loads the primary key for this table.
	 */
	protected function addPrimaryKey(Table $table)
	{
		$stmt = $this->dbh->query("SHOW KEYS FROM `" . $table->getName() . "`");

		// Loop through the returned results, grouping the same key_name together
		// adding each column for that key.
		while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
			// Skip any non-primary keys.
			if ($row['Key_name'] !== 'PRIMARY') {
				continue;
			}
			$name = $row["Column_name"];
			$table->getColumn($name)->setPrimaryKey(true);
		}
	}

	/**
	 * Adds vendor-specific info for table.
	 *
	 * @param      Table $table
	 */
	protected function addTableVendorInfo(Table $table)
	{
		$stmt = $this->dbh->query("SHOW TABLE STATUS LIKE '" . $table->getName() . "'");
		$row = $stmt->fetch(PDO::FETCH_ASSOC);
		$vi = $this->getNewVendorInfoObject($row);
		$table->addVendorInfo($vi);
	}
}


text:
require 'spec_helper'

include TwitterCldr::Localized

describe LocalizedSymbol do

  describe "#as_language_code" do
    it "returns the correct localized language from the symbol" do
      :es.localize.as_language_code.should == "Spanish"
      TwitterCldr.locale = :es
      :es.localize.as_language_code.should == "español"
    end

    it "returns nil if the symbol doesn't correspond to a language code" do
      :blarg.localize.as_language_code.should == nil
    end

    it "returns the correct value for mapped as well as CLDR language codes" do
      :'zh-cn'.localize.as_language_code.should == "Chinese"
      :'zh-tw'.localize.as_language_code.should == "Traditional Chinese"
      :'zh-Hant'.localize.as_language_code.should == "Traditional Chinese"
      :'zh'.localize.as_language_code.should == "Chinese"
    end
  end

  describe "#is_rtl?" do
    it "should return true or false depending on the locale" do
      :es.localize.is_rtl?.should be_false
      :ar.localize.is_rtl?.should be_true
    end
  end

end


text:
#include <boost/noncopyable.hpp>

namespace oxt {

/**
 * A spin lock. It's more efficient than a mutex for locking very small
 * critical sections with few contentions, but less efficient otherwise.
 *
 * The interface is similar to that of boost::mutex.
 */
class spin_lock {
private:
	volatile int exclusion;

public:
	/**
	 * Instantiate this class to lock a spin lock within a scope.
	 */
	class scoped_lock: boost::noncopyable {
	private:
		spin_lock &l;

	public:
		scoped_lock(spin_lock &lock): l(lock) {
			l.lock();
		}

		~scoped_lock() {
			l.unlock();
		}
	};

	spin_lock(): exclusion(0) { }

	/**
	 * Lock this spin lock.
	 * @throws boost::thread_resource_error Something went wrong.
	 */
	void lock() {
		while (__sync_lock_test_and_set(&exclusion, 1)) {
			// Do nothing. This GCC builtin instruction
			// ensures memory barrier.
		}
	}

	/**
	 * Unlock this spin lock.
	 * @throws boost::thread_resource_error Something went wrong.
	 */
	void unlock() {
		__sync_lock_release(&exclusion);
	}

	bool try_lock() {
		return !__sync_lock_test_and_set(&exclusion, 1);
	}
};

} // namespace oxt


text:
// ======================================================================
/*!
 * \file NFmiSatelQueryData.h
 * \brief Interface of class NFmiSatelQueryData
 */
// ======================================================================
/*!
 * \class NFmiSatelQueryData
 *
 * Undocumented
 *
 */
// ======================================================================

#pragma once

#include "NFmiQueryData.h"
#include "NFmiSatel.h"

//! Undocumented
class NFmiSatelQueryData : public NFmiQueryData
{
 public:
  ~NFmiSatelQueryData();
  NFmiSatelQueryData();
  NFmiSatelQueryData(const NFmiSatelQueryData &theData);
  NFmiSatelQueryData(NFmiQueryInfo &theInfo);

  virtual NFmiSatel *Value();
  bool Value(NFmiSatel *theData);

  virtual unsigned long ClassId() const;

  using NFmiQueryData::Clone;
  virtual NFmiQueryData *Clone();

  virtual std::ostream &Write(std::ostream &file) const;
  virtual std::istream &Read(std::istream &file);

 private:
};  // class NFmiSatelQueryData

// ----------------------------------------------------------------------
/*!
 * Destructor
 */
// ----------------------------------------------------------------------

inline NFmiSatelQueryData::~NFmiSatelQueryData()
{
  Reset();
  while (Next())
  {
    delete Value();
  }
}

// ----------------------------------------------------------------------
/*!
 * Void constructor
 */
// ----------------------------------------------------------------------

inline NFmiSatelQueryData::NFmiSatelQueryData() : NFmiQueryData(kVoid) {}
// ----------------------------------------------------------------------
/*!
 * Copy constructor
 *
 * \param theData The object being copied
 */
// ----------------------------------------------------------------------

inline NFmiSatelQueryData::NFmiSatelQueryData(const NFmiSatelQueryData &theData)
    : NFmiQueryData(theData)
{
}

// ----------------------------------------------------------------------
/*!
 * Constructor
 *
 * \param theInfo Undocumented
 */
// ----------------------------------------------------------------------

inline NFmiSatelQueryData::NFmiSatelQueryData(NFmiQueryInfo &theInfo)
    : NFmiQueryData(theInfo, kVoid)
{
}

// ----------------------------------------------------------------------
/*!
 * \
 */
// ----------------------------------------------------------------------

inline NFmiSatel *NFmiSatelQueryData::Value()
{
  return static_cast<NFmiSatel *>(VoidValue());
}
// ----------------------------------------------------------------------
/*!
 * \param theData Undocumented
 * \return Undocumented
 */
// ----------------------------------------------------------------------

inline bool NFmiSatelQueryData::Value(NFmiSatel *theData)
{
  return VoidValue(static_cast<void *>(theData));
}

// ----------------------------------------------------------------------
/*!
 * \return Undocumented
 */
// ----------------------------------------------------------------------

inline unsigned long NFmiSatelQueryData::ClassId() const
{
  return kNFmiSatelQueryData;
}
// ----------------------------------------------------------------------
/*!
 * Write the object to the given output stream
 *
 * \param file The output stream to write to
 * \return The output stream written to
 */
// ----------------------------------------------------------------------

inline std::ostream &NFmiSatelQueryData::Write(std::ostream &file) const
{
  NFmiQueryData::Write(file);
  Reset();
  while (Next())
    file << *Value();
  return file;
}

// ----------------------------------------------------------------------
/*!
 * Read new object contents from the given input stream
 *
 * \param file The input stream to read from
 * \return The input stream read from
 */
// ----------------------------------------------------------------------

inline std::istream &NFmiSatelQueryData::Read(std::istream &file)
{
  NFmiQueryData::Read(file);
  Reset();
  while (Next())
  {
    NFmiSatel *strBufr = new NFmiSatel();
    file >> *strBufr;
    Value(strBufr);
  }
  return file;
}

// ----------------------------------------------------------------------
/*!
 * \return Undocumented
 * \todo Should return auto_ptr
 */
// ----------------------------------------------------------------------

inline NFmiQueryData *NFmiSatelQueryData::Clone()
{
  NFmiSatelQueryData *data = new NFmiSatelQueryData(*this);
  Reset();
  data->Reset();
  while (Next())
  {
    data->Next();
    data->Value(new NFmiSatel(*Value()));
  }

  return static_cast<NFmiQueryData *>(data);
}

// ======================================================================


text:
const helpers = require('../../helpers')

module.exports = {
  command: 'duplicate <testId>',
  desc: 'Duplicate a test.',
  builder: {},
  handler: async function (argv) {
    const client = helpers.getClient(argv)
    const result = await client.duplicateTest(argv.testId)
    if (argv.json) {
      helpers.printJson(result)
    } else {
      helpers.print({
        message: `Test duplicated: ${result.name}`,
        id: result._id,
      })
    }

    process.exit(0)
  },
}


text: Wercker box for PGTA.


text:
package flow

import (
	"fmt"

	"github.com/github/hub/git"
	"github.com/github/hub/utils"
)

type BranchingFlow struct {
	master        string
	develop       string
	featurePrefix string
	releasePrefix string
	hotfixPrefix  string
}

func getBranching() (branching BranchingFlow) {
	fmt.Print("Which branch for master [master]: ")
	branching.master = "master"
	fmt.Scanln(&branching.master)

	fmt.Print("Which branch for develop [develop]: ")
	branching.develop = "develop"
	fmt.Scanln(&branching.develop)

	fmt.Println()

	fmt.Print("Which prefix for feature branch [feature/]: ")
	branching.featurePrefix = "feature/"
	fmt.Scanln(&branching.featurePrefix)

	fmt.Print("Which prefix for release branch [release/]: ")
	branching.releasePrefix = "release/"
	fmt.Scanln(&branching.releasePrefix)

	fmt.Print("Which prefix for hotfix branch [hotfix/]: ")
	branching.hotfixPrefix = "hotfix/"
	fmt.Scanln(&branching.hotfixPrefix)

	return
}

func updateConfigFile(branching BranchingFlow) (err error) {
	gitConfig, err := NewConfig()

	if err != nil {
		utils.Check(fmt.Errorf("%s", err.Error()))
	}

	err = gitConfig.CreateSections(gitConfig.sectionBranch, gitConfig.sectionPrefix)

	if err != nil {
		return
	}

	gitConfig.CreateKey(gitConfig.sectionBranch, "master", branching.master)
	gitConfig.CreateKey(gitConfig.sectionBranch, "develop", branching.develop)

	gitConfig.CreateKey(gitConfig.sectionPrefix, "feature", branching.featurePrefix)
	gitConfig.CreateKey(gitConfig.sectionPrefix, "release", branching.releasePrefix)
	gitConfig.CreateKey(gitConfig.sectionPrefix, "hotfix", branching.hotfixPrefix)

	gitConfig.Save()

	return
}

func initMasterBranch() (err error) {
	git.Quiet("checkout", "master")

	_, err = git.Ref("HEAD")

	if err != nil {
		git.Run("commit", "-m", "Initial commit", "--allow-empty")
	}

	return
}

func initDevelopBranch() (err error) {
	var branches []string

	branches, err = git.LocalBranches()

	if err != nil {
		return
	}

	developExist := false
	for _, branch := range branches {
		if branch == "develop" {
			developExist = true
		}
	}

	if developExist {
		git.Quiet("checkout", "develop")
	} else {
		git.Quiet("checkout", "-b", "develop")
	}

	if err != nil {
		return
	}

	_, err = git.Ref("HEAD")

	if err != nil {
		git.Run("commit", "-m", "Initial commit", "--allow-empty")
	}

	return
}

func FlowInit() (err error) {
	branching := getBranching()

	err = updateConfigFile(branching)

	if err != nil {
		return
	}

	err = initMasterBranch()
	err = initDevelopBranch()

	return
}

func CheckInit() {
	errorMessage := "You need to init your repository with git flow init before."
	gitConfig, err := NewConfig()

	if err != nil {
		utils.Check(fmt.Errorf("%s", err.Error()))
	}

	sectionBranch := gitConfig.GetSection(gitConfig.sectionBranch)

	if !sectionBranch.HasKey("develop") && !sectionBranch.HasKey("master") {
		utils.Check(fmt.Errorf("%s", errorMessage))
	}

	sectionPrefix := gitConfig.GetSection(gitConfig.sectionPrefix)

	if !sectionPrefix.HasKey("feature") ||
		!sectionPrefix.HasKey("release") ||
		!sectionPrefix.HasKey("hotfix") {
		utils.Check(fmt.Errorf("%s", errorMessage))
	}
}


text:
set -o errexit

main() {
  set -o xtrace

  export DEBIAN_FRONTEND=noninteractive

  sudo apt update -y
  sudo apt install -y \
    build-essential \
    git \
    redis-tools

  if ! gimme version; then
    curl -sSL \
      -o /usr/local/bin/gimme \
      https://raw.githubusercontent.com/travis-ci/gimme/master/gimme
    chmod +x /usr/local/bin/gimme
  fi

  sudo -u vagrant HOME=/home/vagrant bash -c 'gimme 1.8.3'

  if ! docker version; then
    curl -sSL https://get.docker.io | sudo bash
  fi

  docker run -d -p 5672:5672 --name rabbitmq rabbitmq:3-management
  docker run -d -p 6379:6379 --name redis redis

  cat >/home/vagrant/.bash_profile <<EOF
export PATH="\$HOME/bin:\$HOME/go/bin:\$PATH"
export GOPATH="\$HOME/go"
eval "\$(gimme 1.8.3)"
set -o vi
EOF

  chown vagrant:vagrant /home/vagrant/.bash_profile
  chown -R vagrant:vagrant /home/vagrant/go

  sudo -u vagrant HOME=/home/vagrant bash <<EOBASH
source \$HOME/.bash_profile
go get github.com/FiloSottile/gvt
go get -u github.com/alecthomas/gometalinter
gometalinter --install || echo look whatever OK
EOBASH
}

main "$@"


text:
package com.google.gwt.dev.js.ast;

import java.io.Serializable;

/**
 * A well-known name in the root scope.
 */
public class JsRootName extends JsName {

  private static class SerializedForm implements Serializable {
    private final String ident;

    public SerializedForm(String ident) {
      this.ident = ident;
    }

    private Object readResolve() {
      return JsRootScope.INSTANCE.findExistingName(ident);
    }
  }

  JsRootName(JsRootScope rootScope, String ident) {
    super(rootScope, ident, ident);
    super.setObfuscatable(false);
  }

  @Override
  public void setObfuscatable(boolean isObfuscatable) {
    throw new UnsupportedOperationException("Root names are immutable");
  }

  @Override
  public void setShortIdent(String shortIdent) {
    throw new UnsupportedOperationException("Root names are immutable");
  }

  @Override
  public void setStaticRef(JsNode node) {
    throw new UnsupportedOperationException("Root names are immutable");
  }

  private Object writeReplace() {
    return new SerializedForm(getIdent());
  }

}


text:
/* ARCress, TODO: improve error handling and remove all assert() calls here. */

#include "ipmitool/log.h"
#include "ipmitool/ipmi_constants.h"
#include "lanplus.h"
#include "lanplus_crypt_impl.h"
#include <openssl/hmac.h>
#include <openssl/evp.h>
#include <openssl/rand.h>
#include <openssl/err.h>
#include <assert.h>

/*
 * lanplus_seed_prng
 *
 * Seed our PRNG with the specified number of bytes from /dev/random
 *
 * param bytes specifies the number of bytes to read from /dev/random
 *
 * returns 0 on success
 *         1 on failure
 */
int lanplus_seed_prng(uint32_t bytes)
{
#ifdef WIN32
        const char *randfile;
        char buffer[200];
        static FILE *fp = NULL;
        size_t i;
        randfile = RAND_file_name(buffer, sizeof buffer); /* usu C:\.rnd */
	if ((randfile != NULL) && (fp == NULL)) {
	   /*first time, so open/create file*/
           fp = fopen(randfile,"w");  /*create the randfile*/
           if (fp != NULL) {
               i = fwrite(" \n",2,1,fp);
               fclose(fp);
           }
        }
        if (verbose > 0)
            printf("seed_prng: RAND_file_name = %s, fp=%p\n",randfile,fp);
#else
        const char *randfile = "/dev/urandom";
#endif

        if (RAND_load_file(randfile, bytes) == 0) {
                printf("seed_prng: RAND_load_file(%s) failed\n",randfile);
		return 1;
	} else {  /*success*/
		return 0;
	}
}

/*
 * lanplus_rand
 *
 * Generate a random number of the specified size
 *
 * param num_bytes [in]  is the size of the random number to be
 *       generated
 * param buffer [out] is where we will place our random number
 *
 * return 0 on success
 *        1 on failure
 */
int
lanplus_rand(uint8_t * buffer, uint32_t num_bytes)
{
#undef IPMI_LANPLUS_FAKE_RAND
#ifdef IPMI_LANPLUS_FAKE_RAND
	/*
	 * This code exists so that we can easily find the generated random
	 * number in the hex dumps.
	 */
 	int i;
	for (i = 0; i < num_bytes; ++i)
		buffer[i] = 0x70 | i;
	return 0;
#else
	return (! RAND_bytes(buffer, num_bytes));
#endif
}

/*
 * lanplus_HMAC
 *
 * param mac specifies the algorithm to be used, currently only SHA1 is supported
 * param key is the key used for HMAC generation
 * param key_len is the lenght of key
 * param d is the data to be MAC'd
 * param n is the length of the data at d
 * param md is the result of the HMAC algorithm
 * param md_len is the length of md
 *
 * returns a pointer to md
 */
uint8_t *
lanplus_HMAC(uint8_t        mac,
			 const void    *key,
			 int            key_len,
			 const uint8_t *d,
			 int            n,
			 uint8_t       *md,
			 uint32_t      *md_len)
{
	const EVP_MD *evp_md = NULL;
	unsigned int mlen;
	uint8_t *pnew;

	*md_len = 0;  /*if return NULL, also return zero length*/
	if ((mac == IPMI_AUTH_RAKP_HMAC_SHA1) ||
		(mac == IPMI_INTEGRITY_HMAC_SHA1_96))
		evp_md = EVP_sha1();
	else if ((mac == IPMI_AUTH_RAKP_HMAC_MD5) ||
		     (mac == IPMI_INTEGRITY_HMAC_MD5_128))
		evp_md = EVP_md5();
	else if ((mac == IPMI_AUTH_RAKP_HMAC_SHA256) ||
		     (mac == IPMI_INTEGRITY_HMAC_SHA256_128)) {
#ifdef HAVE_SHA256
		evp_md = EVP_sha256();
#else
		lprintf(LOG_ERR, "Invalid EVP_sha256 in lanplus_HMAC");
		return NULL; // assert(0);
#endif
	} else {
		lprintf(LOG_ERR,"Invalid mac type 0x%x in lanplus_HMAC",mac);
		return NULL; // assert(0);
	}
	mlen = 20; /* *md_len is usually not initialized */
	pnew = HMAC(evp_md, key, key_len, d, n, md, &mlen);
	*md_len = (uint32_t)mlen;
	return(pnew);
}

/*
 * lanplus_encrypt_aes_cbc_128
 *
 * Encrypt with the AES CBC 128 algorithm
 *
 * param iv is the 16 byte initialization vector
 * param key is the 16 byte key used by the AES algorithm
 * param input is the data to be encrypted
 * param input_length is the number of bytes to be encrypted.  This MUST
 *       be a multiple of the block size, 16.
 * param output is the encrypted output
 * param bytes_written is the number of bytes written.  This param is set
 *       to 0 on failure, or if 0 bytes were input.
 */
void
lanplus_encrypt_aes_cbc_128(const uint8_t * iv,
				const uint8_t * key,
				const uint8_t * input,
				uint32_t        input_length,
				uint8_t       * output,
				uint32_t      * bytes_written)
{
	int nwritten = 0;
	int inlen = 0;
	EVP_CIPHER_CTX ctx;
	EVP_CIPHER_CTX_init(&ctx);
	EVP_EncryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv);
	EVP_CIPHER_CTX_set_padding(&ctx, 0);

	*bytes_written = 0;
	if (input_length == 0) return;

	if (verbose >= 5)
	{
		printbuf(iv,  16, "encrypting with this IV");
		printbuf(key, 16, "encrypting with this key");
		printbuf(input, input_length, "encrypting this data");
	}

	/*
	 * The default implementation adds a whole block of padding if the input
	 * data is perfectly aligned. We would like to keep that from happening.
	 * We have made a point to have our input perfectly padded.
	 */
	assert((input_length % IPMI_CRYPT_AES_CBC_128_BLOCK_SIZE) == 0);
	inlen = input_length;

	if(!EVP_EncryptUpdate(&ctx, output, &nwritten, input, inlen))
	{
		/* Error */
		*bytes_written = 0;
		return;
	}
	else
	{
		int tmplen;

		if(!EVP_EncryptFinal_ex(&ctx, output + nwritten, &tmplen))
		{
			*bytes_written = 0;
			return; /* Error */
		}
		else
		{
			/* Success */
			*bytes_written = nwritten + tmplen;
			EVP_CIPHER_CTX_cleanup(&ctx);
		}
	}
}

/*
 * lanplus_decrypt_aes_cbc_128
 *
 * Decrypt with the AES CBC 128 algorithm
 *
 * param iv is the 16 byte initialization vector
 * param key is the 16 byte key used by the AES algorithm
 * param input is the data to be decrypted
 * param input_length is the number of bytes to be decrypted.  This MUST
 *       be a multiple of the block size, 16.
 * param output is the decrypted output
 * param bytes_written is the number of bytes written.  This param is set
 *       to 0 on failure, or if 0 bytes were input.
 */
void
lanplus_decrypt_aes_cbc_128(const uint8_t * iv,
					const uint8_t * key,
					const uint8_t * input,
					uint32_t        input_length,
					uint8_t       * output,
					uint32_t      * bytes_written)
{
	int nwritten = 0;
	int inlen = 0;
	EVP_CIPHER_CTX ctx;
	EVP_CIPHER_CTX_init(&ctx);
	EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(), NULL, key, iv);
	EVP_CIPHER_CTX_set_padding(&ctx, 0);

	if (verbose >= 5)
	{
		printbuf(iv,  16, "decrypting with this IV");
		printbuf(key, 16, "decrypting with this key");
		printbuf(input, input_length, "decrypting this data");
	}

	*bytes_written = 0;
	if (input_length == 0) return;

	/*
	 * The default implementation adds a whole block of padding if the input
	 * data is perfectly aligned. We would like to keep that from happening.
	 * We have made a point to have our input perfectly padded.
	 */
	assert((input_length % IPMI_CRYPT_AES_CBC_128_BLOCK_SIZE) == 0);
	inlen = input_length;

	if (!EVP_DecryptUpdate(&ctx, output, &nwritten, input, inlen))
	{
		/* Error */
		lprintf(LOG_DEBUG, "ERROR: decrypt update failed");
		*bytes_written = 0;
		return;
	}
	else
	{
		int tmplen;

		if (!EVP_DecryptFinal_ex(&ctx, output + nwritten, &tmplen))
		{
			char buffer[1000];
			ERR_error_string(ERR_get_error(), buffer);
			lprintf(LOG_DEBUG, "the ERR error %s", buffer);
			lprintf(LOG_DEBUG, "ERROR: decrypt final failed");
			*bytes_written = 0;
			return; /* Error */
		}
		else
		{
			/* Success */
			*bytes_written = nwritten + tmplen;
			EVP_CIPHER_CTX_cleanup(&ctx);
		}
	}

	if (verbose >= 5)
	{
		lprintf(LOG_DEBUG, "Decrypted %d encrypted bytes",input_length);
		printbuf(output, *bytes_written, "Decrypted this data");
	}
}


text:
from .restarts import restart, restarts, invoke_restart
from .handlers import handle
from .signals import signal

__version__ = "0.2.0"


text:
package shredzzz.kirkwood.cumath.tensor.modules

import shredzzz.kirkwood.cumath.tensor.{CuVector, CuMatrix, CuTensor}

trait ElementModule[V]
{
  def typePrefix: String
}

trait TensorModule[TT[X] <: CuTensor[X, _, TT]]
{
  def tensorPostfix: String
}

trait BooleanModule extends ElementModule[Boolean]
{
  override val typePrefix = "I"
}

trait IntModule extends ElementModule[Int]
{
  override val typePrefix = "I"
}

trait FloatModule extends ElementModule[Float]
{
  override val typePrefix = "S"
}

trait DoubleModule extends ElementModule[Double]
{
  override val typePrefix = "D"
}

trait VectorModule extends TensorModule[CuVector]
{
  override val tensorPostfix = "V"
}

trait MatrixModule extends TensorModule[CuMatrix]
{
  override val tensorPostfix = "M"
}


text:
package org.apache.syncope.wa.bootstrap;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.cloud.bootstrap.config.PropertySourceLocator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;

@Configuration(proxyBeanMethods = false)
@PropertySource("classpath:wa.properties")
@PropertySource(value = "file:${conf.directory}/wa.properties", ignoreResourceNotFound = true)
public class WABootstrapConfiguration {

    @Configuration(proxyBeanMethods = false)
    public static class WAClientConfiguration {

        @Value("${wa.anonymousUser}")
        private String anonymousUser;

        @Value("${wa.anonymousKey}")
        private String anonymousKey;

        @Value("${wa.useGZIPCompression:true}")
        private boolean useGZIPCompression;

        @Bean
        public WARestClient waRestClient() {
            return new WARestClient(anonymousUser, anonymousKey, useGZIPCompression);
        }
    }

    @Configuration(proxyBeanMethods = false)
    public static class PropertySourceConfiguration {

        @ConditionalOnMissingBean
        @Bean
        public AuthModulePropertySourceMapper authModulePropertySourceMapper(final WARestClient waRestClient) {
            return new AuthModulePropertySourceMapper(waRestClient);
        }

        @ConditionalOnMissingBean
        @Bean
        public AttrRepoPropertySourceMapper attrRepoPropertySourceMapper(final WARestClient waRestClient) {
            return new AttrRepoPropertySourceMapper(waRestClient);
        }

        @Bean
        public PropertySourceLocator configPropertySourceLocator(
                final WARestClient waRestClient,
                final AuthModulePropertySourceMapper authModulePropertySourceMapper,
                final AttrRepoPropertySourceMapper attrRepoPropertySourceMapper) {

            return new WAPropertySourceLocator(
                    waRestClient, authModulePropertySourceMapper, attrRepoPropertySourceMapper);
        }
    }
}


text:
module Vimeo
  module Advanced
    class GroupForums < Vimeo::Advanced::Base

      # Returns a list of comments for a group forum topic.
      create_api_method :get_topic_comments,
                        "vimeo.groups.forums.getTopicComments",
                        :required => [:group_id, :topic_id],
                        :optional => [:page, :per_page]

      # Returns a list of all group forum topics.
      create_api_method :get_topics,
                        "vimeo.groups.forums.getTopics",
                        :required => [:group_id],
                        :optional => [:page, :per_page]

    end # GroupForums
  end # Advanced
end # Vimeo


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

namespace Trifolia.Web.Models.Account
{
    public class WhoAmIModel
    {
        public WhoAmIModel()
        {
            this.Securables = new List<string>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string UserName { get; set; }
        public string Email { get; set; }
        public IEnumerable<string> Securables { get; set; }
    }
}


text:
require 'rails_helper'

RSpec.describe Course::LearningRateRecord, type: :model do
  it { is_expected.to belong_to(:course_user).inverse_of(:learning_rate_records) }
  it { is_expected.to validate_presence_of(:course_user) }
  it { is_expected.to validate_presence_of(:learning_rate) }
  it { is_expected.to validate_presence_of(:effective_min) }
  it { is_expected.to validate_presence_of(:effective_max) }
  it { is_expected.to validate_numericality_of(:learning_rate).is_greater_than_or_equal_to(0) }
  it { is_expected.to validate_numericality_of(:effective_min) }
  it { is_expected.to validate_numericality_of(:effective_max) }

  let!(:instance) { Instance.default }
  with_tenant(:instance) do
    let(:learning_rate_record) { create(:learning_rate_record) }

    describe 'validations' do
      subject { learning_rate_record }

      context 'when learning_rate is less than effective_min' do
        it 'is invalid' do
          subject.assign_attributes(learning_rate: 0.4, effective_min: 0.5)
          expect(subject).not_to be_valid
          expect(subject.errors[:learning_rate]).to be_present
        end
      end

      context 'when learning_rate is greater than effective_max' do
        it 'is invalid' do
          subject.assign_attributes(learning_rate: 2.1, effective_max: 2)
          expect(subject).not_to be_valid
          expect(subject.errors[:learning_rate]).to be_present
        end
      end

      context 'when learning_rate is between effective_min and effective_max' do
        it 'is valid' do
          subject.assign_attributes(learning_rate: 1, effective_min: 0.5, effective_max: 1.5)
          expect(subject).to be_valid
        end
      end

      context 'when learning_rate is equal to both effective_min and effective_max' do
        it 'is valid' do
          subject.assign_attributes(learning_rate: 1, effective_min: 1, effective_max: 1)
          expect(subject).to be_valid
        end
      end
    end

    describe '.default_scope' do
      before { create_list(:learning_rate_record, 5) }

      it 'orders by descending created_at' do
        dates = Course::LearningRateRecord.pluck(:created_at)
        expect(dates.length).to be > 1
        expect(dates.each_cons(2).all? { |x, y| x >= y }).to be_truthy
      end
    end
  end
end


text:
var noble = require('noble');
var Q = require('q');
var timer = require('./timer');
var settings = require('../settings');

var isScanning = false;
var config = {
    powered: false
};

var targetPeripheralAddress = settings.multiroleAddress; //can find by address too...
var scannedIDs = {};
var connectedIDs = {};

var peripheralPromise;
var peripheralRef;

//Event listeners
noble.on('stateChange', function(state) {
    //console.log('stateChange', state)
    config.powered = state === 'poweredOn';
});

noble.on('scanStart', function() {
    isScanning = true;
    console.log('scan started');
});

function mulinodeDisconnect() {
    console.log('d/c!')

    if (!peripheralRef) {
        console.log('Multiple disconnections of one device detected...');
        return;
    }

    peripheralRef.removeAllListeners('disconnect'); //insurance

    delete connectedIDs[peripheralRef.uuid];
    peripheralRef = null;
};

//Callback function for timer to turn off scanner
function timerDone() {

    noble.removeAllListeners('discover')
    noble.stopScanning();
    isScanning = false;

    console.log('scan stopped')
        //Promise never got resolved and timer is done.
        //Return 'device not found'.
    if (peripheralPromise.promise.isPending()) {
        peripheralPromise.reject(-1)
    }
}

//returns a promise containing target peripheral data
//attempts to pair to peripheral in order to prevent other devices from pairing with it
//and taking down its advertisement
function getPeripheral() {
    return new Promise(function(resolve, reject) {
        //Check once to discover device
        noble.once('discover', discoverPeripheral);

        function discoverPeripheral(peripheral) {
            var isTargetDevice = peripheral.address == targetPeripheralAddress.toLowerCase();
            console.log(peripheral.address)
            if (scannedIDs[peripheral.uuid]) {
                //Target device
                if (isTargetDevice) {
                    console.log(peripheral.advertisement.localName)
                    console.log("Already have target device's data - we'll use that!")
                        // peripheralPromise.resolve(peripheral);
                    resolve(peripheral);
                    return;
                }

                //Not target device
                reject("Already seen " + peripheral.advertisement.localName + " skipping...");
            }

            //Not aware of device, but also havent seen it before.
            if (!isTargetDevice) {
                scannedIDs[peripheral.uuid] = true;
                reject("Uninterested in " + peripheral.advertisement.localName + " (" + peripheral.address + ")" + " skipping...");
            }

            //Not aware of target device.
            scannedIDs[peripheral.uuid] = true;

            //Resolve promise
            // peripheralPromise.resolve(peripheral);
            resolve(peripheral);
        }
    }).catch(function(err) { console.log(err) });
}

//Iterates using noble.on event listener until target peripheral is found or timer up
function verifyPeripheralPromise() {
    //Insurance that works soooo well!
    noble.removeAllListeners('discover')

    getPeripheral().then(processPeripheral);

    function processPeripheral(peripheral) {
        if (peripheral) {
            foundPeripheral(peripheral);
        } else if (!peripheral && isScanning) {
            verifyPeripheralPromise();
        } else if (!isScanning) {
            //Never reached
            peripheralPromise.reject("Error: Timer issue");
        }
    }
}

function foundPeripheral(peripheral) {
    console.log('successfully found peripheral');

    peripheralRef = peripheral;
    peripheralRef.once('disconnect', mulinodeDisconnect);
    peripheralPromise.resolve(peripheral);

    //Must come after resolve!
    timer.stop();
}

//Exports

function getServices() {
    console.log('gittin served')
    return new Promise(function(resolve, reject) {

        //To our knowledge, device must be paired/connected
        if (!module.exports.hasDevice() || !module.exports.isPaired())
            reject("Error: device isn't paired");

        peripheralRef.discoverAllServicesAndCharacteristics(function(error, services, characteristics) {
            if (error) reject(error)

            resolve({
                characteristics: characteristics,
                services: services
            });

            //test chars
            // for (s in services) {
            //     services[s].discoverCharacteristics(['f000caf204514000b000000000000000', 'f000caf504514000b000000000000000'], function(error, characteristics) {
            //         for (c in characteristics) {
            //             console.log(characteristics[c])
            //             characteristics[c].read(function(error,data){
            //                 console.log(error, data)
            //             })
            // var buffer = new Buffer(1);
            // buffer.writeUInt8(1, 0);
            // characteristics[c].write(buffer)

            //characteristics[c]
            // characteristics[c].on('read', function(data, isNotification){
            //     console.log('OH YEAH', data, isNotification)
            // })

            // characteristics[c].on('data', function(data, isNotification){
            //     console.log('OH YEAH 2', data, isNotification)
            // })

            // characteristics[c].subscribe(function(data, isNotification){
            // console.log('OH YEAH 3', data, isNotification)
            // })

        })
    })
};

function readData(s_uuid, c_uuid) {
    return new Promise(function(resolve, reject) {
        if (!s_uuid || !c_uuid) reject('Need service and characteristic uuid!');
        peripheralRef.discoverServices([s_uuid], function(error, service) {
            if (error) reject(error);
            service[0].discoverCharacteristics([c_uuid], function(error, characteristic) {
                if (error) reject(error);
                characteristic[0].read(function(error, data) {
                    if (error) reject(error);
                    resolve(data);
                })
            })
        })
    })
}

function writeData(s_uuid, c_uuid, data_to_write) {
       return new Promise(function(resolve, reject) {
        if (!s_uuid || !c_uuid) reject('Need service and characteristic uuid!');
        if (!data_to_write) reject('Need data to write!');
     peripheralRef.discoverServices([s_uuid], function(error, service) {
            if (error) reject(error);
            service[0].discoverCharacteristics([c_uuid], function(error, characteristic) {
                if (error) reject(error);
                //just write 1 for now...
                var buffer = new Buffer(1);
                buffer.writeUInt8(1, 0);
                ///
                characteristic[0].write(buffer, function(error) {
                    if (error) reject(error);
                    resolve();
                })
            })
        })
    })
}

//Returns promise containing peripheral services
function startScanning(scanTime) {
    if (!config.powered) {
        return -1;
    }

    noble.startScanning();
    timer.start(scanTime, timerDone);

    peripheralPromise = new Q.defer();
    verifyPeripheralPromise();
    return peripheralPromise.promise;
}

function pair(cb) {
    return new Promise(function(resolve, reject) {
        if (connectedIDs[peripheralRef.uuid]) resolve(); //Ignore the fact that we are "Already connected!";
        peripheralRef.connect(function(error) {
            if (error && error != "Error: Peripheral already connected") reject(error)
            else {
                connectedIDs[peripheralRef.uuid] = true;
                resolve();
            };
        })
    })
}

module.exports = {
    hasDevice: function() {
        return peripheralRef != null;
    },
    isPaired: function() {
        return peripheralRef != null && connectedIDs[peripheralRef.uuid];
    },
    getServices: getServices,
    pair: pair,
    readData: readData,
    writeData: writeData,
    startScanning: startScanning,
    stopScanning: function() { noble.stopScanning() }
}


text:
"""Application base class for providing a list of data as output.
"""
import abc
import logging

import six

from .display import DisplayCommandBase

LOG = logging.getLogger(__name__)

@six.add_metaclass(abc.ABCMeta)
class Lister(DisplayCommandBase):
    """Command base class for providing a list of data as output.
    """

    @property
    def formatter_namespace(self):
        return 'cliff.formatter.list'

    @property
    def formatter_default(self):
        return 'table'

    @abc.abstractmethod
    def take_action(self, parsed_args):
        """Return a tuple containing the column names and an iterable
        containing the data to be listed.
        """

    def produce_output(self, parsed_args, column_names, data):
        if not parsed_args.columns:
            columns_to_include = column_names
            data_gen = data
        else:
            columns_to_include = [c for c in column_names
                                  if c in parsed_args.columns
                                  ]
            if not columns_to_include:
                raise ValueError('No recognized column names in %s' %
                                 str(parsed_args.columns))
            # Set up argument to compress()
            selector = [(c in columns_to_include)
                        for c in column_names]
            # Generator expression to only return the parts of a row
            # of data that the user has expressed interest in
            # seeing. We have to convert the compress() output to a
            # list so the table formatter can ask for its length.
            data_gen = (list(self._compress_iterable(row, selector))
                        for row in data)
        self.formatter.emit_list(columns_to_include,
                                 data_gen,
                                 self.app.stdout,
                                 parsed_args,
                                 )
        return 0


text:
require 'socket'
require 'resolv'
require 'zlib'

#
# This class represents a single socket used to transfer file chunks as part of
# an inverse multiplex session.  It is controlled by an instance of IMUXManager.
# This class controls opening, closing, or recycling the socket, as well as serving
# or recieving chunks of a file.
#

class IMUXSocket
	attr_reader :state
	attr_reader :port
	attr_reader :peer_ip
	attr_reader :bind_ip
	attr_reader :transfer_speed
	attr_reader :bytes_transfered
	attr_accessor :reset

	def initialize(manager)
		@manager = manager
		@state = :new
		@port = nil
		@peer_ip = nil
		@bind_ip = nil
		@closed = true
		@transfer_speed = 0
		@bytes_transfered = 0
		@reset = false
	end

	def open_socket(peer_ip, port, bind_ip=nil)
		@state = :connecting
		@bind_ip = bind_ip
		@bind_ip = nil if @bind_ip == "nil"
		@port = port
		@peer_ip = Resolv::getaddress(peer_ip)
		begin
			if @bind_ip != nil
				lhost = Socket.pack_sockaddr_in(0, @bind_ip)
				rhost = Socket.pack_sockaddr_in(@port, @peer_ip)
				@socket = Socket.new(Socket::AF_INET, Socket::SOCK_STREAM, 0)
				@socket.bind(lhost)
				@socket.connect(rhost)
			else
				@socket = TCPSocket.new(@peer_ip, @port)
			end
			@closed = false
			@state = :idle
			return true
		rescue StandardError => e
			@state = :failed
			return false
		end
	end

	def recieve_connection(server)
		@socket = server.accept
		@state = :idle
		@closed = false
	end

	def process_download(buffer)
		raise "Socket in use: #{@state}" if @state != :idle
		@state = :downloading
		@bytes_transfered = 0
		@transfer_speed = 0
		loop{
			open_socket(@peer_ip, @port, @bind_ip) if @closed
			@socket.puts "GETNEXT"
			begin
				header = @socket.gets.chomp
			rescue
				close_connection
				break
			end
			break if header == "DONE"
			chunk_id, chunk_size = header.split(":")
			chunk_id = chunk_id.to_i
			chunk_size = chunk_size.to_i
			start = Time.now
			chunk_data = recieve_chunk_data(chunk_size)
			if chunk_data == nil
				close_connection
				break
			end
			buffer.insert({:id => chunk_id, :data => chunk_data})
			time_elapsed = Time.now - start
			@transfer_speed = chunk_size / time_elapsed
			@bytes_transfered += chunk_size
			reset_socket
		}
		@transfer_speed = 0
		@state = :idle
	end

	def serve_download(file_queue)
		raise "Socket in use: #{@state}" if @state != :idle
		@state = :serving
		@bytes_transfered = 0
		@transfer_speed = 0
		loop{
			recieve_connection(@manager.server) if @closed
			request = @socket.gets.chomp
			chunk = file_queue.next_chunk
			if chunk[:data] == nil
				@socket.puts "DONE"
				break
			end
			@socket.puts "#{chunk[:id]}:#{chunk[:data].size}"
			success = send_chunk_data(chunk[:data])
			if !success
				file_queue.stale_chunks << chunk
			end
			reset_socket_server
		}
		@transfer_speed = 0
		@state = :idle
	end

	def close_connection
		begin
			@socket.close
		rescue
		end
	end

	private

	#
	# Download methods
	#

	def recieve_chunk_data(chunk_size)
		begin
			chunk_data = @socket.read(chunk_size)
		rescue
			chunk_data = nil
		end
		chunk_data
	end

	def reset_socket
		if @reset
			@socket.puts "RESET"
			@socket.close
			@closed = true
		else
			@socket.puts "NORESET"
		end
	end

	#
	# Upload methods
	#

	def send_chunk_data(data)
		begin
			@socket.write(data)
			return true
		rescue
			return false
		end
	end

	def reset_socket_server
		reset = @socket.gets.chomp
		if reset == "RESET"
			@socket.close
			@closed = true
		end
	end
end


text:
{{< layout}}

{{$pageTitle}}Delivering your new passport{{/pageTitle}}

{{$header}}

Delivering your new passport

{{/header}}

{{$content}}

{{< hmpo-partials-form}}
{{$form}}

We'll send your new passport by special delivery (included in the passport fee) to: DYNAMIC DATA

        We'll send your new passport at a different time and from a different location to your old one.

    {{#input-submit}}{{/input-submit}}
{{/form}}
{{/ hmpo-partials-form}}

{{/content}}

{{/ layout}}


text:
<?xml version="1.0" encoding="utf-8" ?>
<!DOCTYPE erlref SYSTEM "erlref.dtd">

<erlref>

  <copyright>
    <year>2020</year>
    <holder>Ericsson AB. All Rights Reserved.</holder></copyright>
  <legalnotice>
      Licensed under the Apache License, Version 2.0 (the "License");
      you may not use this file except in compliance with the License.
      You may obtain a copy of the License at

          http://www.apache.org/licenses/LICENSE-2.0

      Unless required by applicable law or agreed to in writing, software
      distributed under the License is distributed on an "AS IS" BASIS,
      WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
      See the License for the specific language governing permissions and
      limitations under the License.

  </legalnotice>
  <title>wxQueryNewPaletteEvent</title>

<module>wxQueryNewPaletteEvent</module>
<modulesummary>Functions for wxQueryNewPaletteEvent class</modulesummary>
<description>

This class is derived (and can use functions) from:
    <seeerl marker="wxEvent"><c>wxEvent</c></seeerl>

wxWidgets docs: <url href="https://docs.wxwidgets.org/3.1/classwx_query_new_palette_event.html">wxQueryNewPaletteEvent</url>

  </description>
<datatypes>
    <datatype><name name="wxQueryNewPaletteEvent"/></datatype>
    <datatype><name name="wxQueryNewPalette"/></datatype>
    <datatype><name name="wxQueryNewPaletteEventType"/></datatype></datatypes>

<funcs>
  <func>
    <name name="setPaletteRealized" arity="2" clause_i="1" since=""/>
    <fsummary/>
    <desc/>
  </func>

  <func>
    <name name="getPaletteRealized" arity="1" clause_i="1" since=""/>
    <fsummary/>
    <desc/>
  </func>
  </funcs>
</erlref>


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Trans. Br. mycol. Soc. 55(2): 310 (1970)

#### Original name
Penicillium dimorphosporum H.J. Swart, 1970

### Remarks
null


text:
var http = require('http');
var fs = require('fs');
var path = require('path');
var request = require('supertest');
var should = require('should');
var serveIndex = require('../');

var fixtures = path.resolve(__dirname, './fixtures');
var relative = path.relative(process.cwd(), fixtures);

var skipRelative = ~relative.indexOf('..') || path.resolve(relative) === relative;

describe('serveIndex(root)', function () {
    it('should require root', function () {
        serveIndex.should.throw(/root path required/)
    })

    it('should serve text/html without Accept header', function (done) {
        var server = createServer()

        request(server)
            .get('/')
            .expect('Content-Type', 'text/html; charset=utf-8')
            .expect(200, done)
    })

    it('should serve a directory index', function (done) {
        var server = createServer()

        request(server)
            .get('/')
            .expect(200, /todo\.txt/, done)
    })

    it('should work with HEAD requests', function (done) {
        var server = createServer()

        request(server)
            .head('/')
            .expect(200, '', done)
    })

    it('should work with OPTIONS requests', function (done) {
        var server = createServer()

        request(server)
            .options('/')
            .expect('Allow', 'GET, HEAD, OPTIONS')
            .expect(200, done)
    })

    it('should deny POST requests', function (done) {
        var server = createServer()

        request(server)
            .post('/')
            .expect(405, done)
    })

    it('should deny path will NULL byte', function (done) {
        var server = createServer()

        request(server)
            .get('/%00')
            .expect(400, done)
    })

    it('should deny path outside root', function (done) {
        var server = createServer()

        request(server)
            .get('/../')
            .expect(403, done)
    })

    it('should skip non-existent paths', function (done) {
        var server = createServer()

        request(server)
            .get('/bogus')
            .expect(404, 'Not Found', done)
    })

    it('should treat an ENAMETOOLONG as a 414', function (done) {
        var path = Array(11000).join('foobar')
        var server = createServer()

        request(server)
            .get('/' + path)
            .expect(414, done)
    })

    it('should skip non-directories', function (done) {
        var server = createServer()

        request(server)
            .get('/nums')
            .expect(404, 'Not Found', done)
    })

    describe('when given Accept: header', function () {
        describe('when Accept: application/json is given', function () {
            it('should respond with json', function (done) {
                var server = createServer()

                request(server)
                    .get('/')
                    .set('Accept', 'application/json')
                    .expect('Content-Type', /json/)
                    .expect(/g# %3 o %2525 %37 dir/)
                    .expect(/users/)
                    .expect(/file #1\.txt/)
                    .expect(/nums/)
                    .expect(/todo\.txt/)
                    .expect(/さくら\.txt/)
                    .expect(200, done)
            });
        });

        describe('when Accept: text/html is given', function () {
            it('should respond with html', function (done) {
                var server = createServer()

                request(server)
                    .get('/')
                    .set('Accept', 'text/html')
                    .expect(200)
                    .expect('Content-Type', 'text/html; charset=utf-8')
                    .expect(/<a href="\/g%23%20%253%20o%20%252525%20%2537%20dir"/)
                    .expect(/<a href="\/users"/)
                    .expect(/<a href="\/file%20%231.txt"/)
                    .expect(/<a href="\/todo.txt"/)
                    .expect(/<a href="\/%E3%81%95%E3%81%8F%E3%82%89\.txt"/)
                    .end(done);
            });

            it('should sort folders first', function (done) {
                var server = createServer()

                request(server)
                    .get('/')
                    .set('Accept', 'text/html')
                    .expect(200)
                    .expect('Content-Type', 'text/html; charset=utf-8')
                    .end(function (err, res) {
                        if (err) throw err;
                        var urls = res.text.split(/<a href="([^"]*)"/).filter(function (s, i) {
                            return i % 2;
                        });
                        urls.should.eql([
                            '/%23directory',
                            '/g%23%20%253%20o%20%252525%20%2537%20dir',
                            '/users',
                            '/file%20%231.txt',
                            '/foo%20bar',
                            '/nums',
                            '/todo.txt',
                            '/%E3%81%95%E3%81%8F%E3%82%89.txt'
                        ]);
                        done();
                    });
            });
        });

        describe('when Accept: text/plain is given', function () {
            it('should respond with text', function (done) {
                var server = createServer()

                request(server)
                    .get('/')
                    .set('Accept', 'text/plain')
                    .expect(200)
                    .expect('Content-Type', 'text/plain; charset=utf-8')
                    .expect(/users/)
                    .expect(/g# %3 o %2525 %37 dir/)
                    .expect(/file #1.txt/)
                    .expect(/todo.txt/)
                    .expect(/さくら\.txt/)
                    .end(done);
            });
        });

        describe('when Accept: application/x-bogus is given', function () {
            it('should respond with 406', function (done) {
                var server = createServer()

                request(server)
                    .get('/')
                    .set('Accept', 'application/x-bogus')
                    .expect(406, done)
            });
        });
    });

    describe('with "hidden" option', function () {
        it('should filter hidden files by default', function (done) {
            var server = createServer()

            request(server)
                .get('/')
                .expect(200, function (err, res) {
                    if (err) return done(err)
                    res.text.should.not.containEql('.hidden')
                    done()
                });
        });

        it('should filter hidden files', function (done) {
            var server = createServer('test/fixtures', {'hidden': false})

            request(server)
                .get('/')
                .expect(200, function (err, res) {
                    if (err) return done(err)
                    res.text.should.not.containEql('.hidden')
                    done()
                });
        });

        it('should not filter hidden files', function (done) {
            var server = createServer('test/fixtures', {'hidden': true})

            request(server)
                .get('/')
                .expect(200, /\.hidden/, done)
        });
    });

    describe('with "filter" option', function () {
        it('should custom filter files', function (done) {
            var seen = false
            var server = createServer(fixtures, {'filter': filter})

            function filter(name) {
                if (name.indexOf('foo') === -1) return true
                seen = true
                return false
            }

            request(server)
                .get('/')
                .expect(200, function (err, res) {
                    if (err) return done(err)
                    seen.should.be.true
                    res.text.should.not.containEql('foo')
                    done()
                });
        });

        it('should support filter files dir', function (done) {
            var seen = false
            var server = createServer(fixtures, {'filter': filter})

            function filter(name, i, files, dir) {
                if (dir === '/users') {
                  seen = true
                }
                return false
            }

            request(server)
                .get('/users')
                .expect(200, function (err, res) {
                    if (err) return done(err)
                    seen.should.be.true
                    res.text.should.not.containEql('foo')
                    done()
                });
        });
        it('should filter after hidden filter', function (done) {
            var seen = false
            var server = createServer(fixtures, {'filter': filter, 'hidden': false})

            function filter(name) {
                seen = seen || name.indexOf('.') === 0
                return true
            }

            request(server)
                .get('/')
                .expect(200, function (err, res) {
                    if (err) return done(err)
                    seen.should.be.false
                    done()
                });
        });
    });

    describe('with "icons" option', function () {
        it('should include icons for html', function (done) {
            var server = createServer(fixtures, {'icons': true})

            request(server)
                .get('/')
                .expect(/data:image\/png/)
                .expect(/icon-default/)
                .expect(/icon-directory/)
                .expect(/icon-txt/)
                .expect(200, done)
        });
    });

    describe('when using custom handler', function () {
        describe('exports.html', function () {
            var orig = serveIndex.html
            after(function () {
                serveIndex.html = orig
            })

            it('should get called with Accept: text/html', function (done) {
                var server = createServer()

                serveIndex.html = function (req, res, files) {
                    res.set('Content-Type', 'text/html');
                    res.body = 'called';
                }

                request(server)
                    .get('/')
                    .set('Accept', 'text/html')
                    .expect(200, 'called', done)
            });

            it('should get file list', function (done) {
                var server = createServer()

                serveIndex.html = function (req, res, files) {
                    var text = files
                        .filter(function (f) {
                            return /\.txt$/.test(f)
                        })
                        .sort()
                    res.set('Content-Type', 'text/html')
                    res.body = ('' + text.length + ' text files')
                }

                request(server)
                    .get('/')
                    .set('Accept', 'text/html')
                    .expect(200, '3 text files', done)
            });

            it('should get dir name', function (done) {
                var server = createServer()

                serveIndex.html = function (req, res, files, next, dir) {
                    res.set('Content-Type', 'text/html')
                    res.body = ('' + dir + '')
                }

                request(server)
                    .get('/users/')
                    .set('Accept', 'text/html')
                    .expect(200, '/users/', done)
            });

            it('should get template path', function (done) {
                var server = createServer()

                serveIndex.html = function (req, res, files, next, dir, showUp, icons, path, view, template) {
                    res.set('Content-Type', 'text/html')
                    res.body = (String(fs.existsSync(template)))
                }

                request(server)
                    .get('/users/')
                    .set('Accept', 'text/html')
                    .expect(200, 'true', done)
            });

            it('should get template with tokens', function (done) {
                var server = createServer()

                serveIndex.html = function (req, res, files, next, dir, showUp, icons, path, view, template) {
                    res.set('Content-Type', 'text/html')
                    res.body = (fs.readFileSync(template, 'utf8'))
                }

                request(server)
                    .get('/users/')
                    .set('Accept', 'text/html')
                    .expect(/{directory}/)
                    .expect(/{files}/)
                    .expect(/{linked-path}/)
                    .expect(/{style}/)
                    .expect(200, done)
            });

            it('should get stylesheet path', function (done) {
                var server = createServer()

                serveIndex.html = function (req, res, files, next, dir, showUp, icons, path, view, template, stylesheet) {
                    res.set('Content-Type', 'text/html')
                    res.body = (String(fs.existsSync(stylesheet)))
                }

                request(server)
                    .get('/users/')
                    .set('Accept', 'text/html')
                    .expect(200, 'true', done)
            });

            it('should sort by custom function', function(done) {
                var server = createServer(null, {
                  fileSort: function(a, b) {
                      return a.stat.ctime.getTime() - b.stat.ctime.getTime();
                  },
                });
                serveIndex.html = function (req, res, files) {
                    res.set('Content-Type', 'text/html')
                    res.body = (files.join());
                };

                request(server)
                    .get('/')
                    .set('Accept', 'text/html')
                    .expect(200, '#directory,file #1.txt,foo bar,g# %3 o %2525 %37 dir,nums,todo.txt,users,さくら.txt', done);
            });
        });

        describe('exports.plain', function () {
            var orig = serveIndex.plain
            after(function () {
                serveIndex.plain = orig
            })

            it('should get called with Accept: text/plain', function (done) {
                var server = createServer()

                serveIndex.plain = function (req, res, files) {
                    res.set('Content-Type', 'text/plain');
                    res.body = ('called');
                }

                request(server)
                    .get('/')
                    .set('Accept', 'text/plain')
                    .expect(200, 'called', done)
            });
        });

        describe('exports.json', function () {
            var orig = serveIndex.json
            after(function () {
                serveIndex.json = orig
            })

            it('should get called with Accept: application/json', function (done) {
                var server = createServer()

                serveIndex.json = function (req, res, files) {
                    res.set('Content-Type', 'application/json');
                    res.body = ('"called"');
                }

                request(server)
                    .get('/')
                    .set('Accept', 'application/json')
                    .expect(200, '"called"', done)
            });
        });
    });

    describe('when navigating to other directory', function () {
        it('should respond with correct listing', function (done) {
            var server = createServer()

            request(server)
                .get('/users/')
                .set('Accept', 'text/html')
                .expect(200)
                .expect('Content-Type', 'text/html; charset=utf-8')
                .expect(/<a href="\/users\/index.html"/)
                .expect(/<a href="\/users\/tobi.txt"/)
                .end(done);
        });

        it('should work for directory with #', function (done) {
            var server = createServer()

            request(server)
                .get('/%23directory/')
                .set('Accept', 'text/html')
                .expect(200)
                .expect('Content-Type', 'text/html; charset=utf-8')
                .expect(/<a href="\/%23directory"/)
                .expect(/<a href="\/%23directory\/index.html"/)
                .end(done);
        });

        it('should work for directory with special chars', function (done) {
            var server = createServer()

            request(server)
                .get('/g%23%20%253%20o%20%252525%20%2537%20dir/')
                .set('Accept', 'text/html')
                .expect(200)
                .expect('Content-Type', 'text/html; charset=utf-8')
                .expect(/<a href="\/g%23%20%253%20o%20%252525%20%2537%20dir"/)
                .expect(/<a href="\/g%23%20%253%20o%20%252525%20%2537%20dir\/empty.txt"/)
                .end(done);
        });

        it('should not work for outside root', function (done) {
            var server = createServer()

            request(server)
                .get('/../support/')
                .set('Accept', 'text/html')
                .expect(403, done);
        });
    });

    describe('when setting a custom template', function () {
        var server;
        before(function () {
            server = createServer(fixtures, {'template': __dirname + '/shared/template.html'});
        });

        it('should respond with file list', function (done) {
            request(server)
                .get('/')
                .set('Accept', 'text/html')
                .expect(/<a href="\/g%23%20%253%20o%20%252525%20%2537%20dir"/)
                .expect(/<a href="\/users"/)
                .expect(/<a href="\/file%20%231.txt"/)
                .expect(/<a href="\/todo.txt"/)
                .expect(200, done)
        });

        it('should respond with testing template sentence', function (done) {
            request(server)
                .get('/')
                .set('Accept', 'text/html')
                .expect(200, /This is the test template/, done)
        });

        it('should have default styles', function (done) {
            request(server)
                .get('/')
                .set('Accept', 'text/html')
                .expect(200, /ul#files/, done)
        });
    });

    describe('when setting a custom stylesheet', function () {
        var server;
        before(function () {
            server = createServer(fixtures, {'stylesheet': __dirname + '/shared/styles.css'});
        });

        it('should respond with appropriate embedded styles', function (done) {
            request(server)
                .get('/')
                .set('Accept', 'text/html')
                .expect(200)
                .expect('Content-Type', 'text/html; charset=utf-8')
                .expect(/color: #00ff00;/)
                .end(done);
        });
    });

    describe('when set with trailing slash', function () {
        var server;
        before(function () {
            server = createServer(fixtures + '/');
        });

        it('should respond with file list', function (done) {
            request(server)
                .get('/')
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect(/users/)
                .expect(/file #1\.txt/)
                .expect(/nums/)
                .expect(/todo\.txt/)
                .expect(200, done)
        });
    });

    (skipRelative ? describe.skip : describe)('when set to \'.\'', function () {
        var server;
        before(function () {
            server = createServer('.');
        });

        it('should respond with file list', function (done) {
            var dest = relative.split(path.sep).join('/');
            request(server)
                .get('/' + dest + '/')
                .set('Accept', 'application/json')
                .expect('Content-Type', /json/)
                .expect(/users/)
                .expect(/file #1\.txt/)
                .expect(/nums/)
                .expect(/todo\.txt/)
                .expect(200, done)
        });

        it('should not allow serving outside root', function (done) {
            request(server)
                .get('/../')
                .set('Accept', 'text/html')
                .expect(403, done);
        });
    });
});

function createServer(dir, opts) {
    dir = dir || fixtures;
    var app = require('koa')();
    app.use(serveIndex(dir, opts));
    return http.createServer(app.callback());
}