<commit_before>
module.exports = DataCenter;

function DataCenter() {

    this.DE_FRANKFURT = {
        id: 'de1',
            name: 'DE1 - Germany (Frankfurt)'
    };

    this.CA_VANCOUVER = {
        id: 'ca1',
        name: 'CA1 - Canada (Vancouver)'
    };

    this.CA_TORONTO_1 = {
        id: 'ca2',
        name: 'CA2 - Canada (Toronto)'
    };

    this.CA_TORONTO_2 = {
        id: 'ca3',
        name: 'CA3 - Canada (Toronto)'
    };

    this.GB_PORTSMOUTH = {
        id: 'gb1',
        name: 'GB1 - Great Britain (Portsmouth)'
    };

    this.GB_SLOUGH = {
        id: 'gb3',
        name: 'GB3 - Great Britain (Slough)'
    };

    this.US_CENTRAL_CHICAGO = {
        id: 'il1',
        name: 'IL1 - US Central (Chicago)'
    };

    this.US_EAST_NEW_YORK = {
        id: 'ny1',
        name: 'NY1 - US East (New York)'
    };

    this.SG_APAC = {
        id: 'sg1',
        name: 'SG1 - APAC (Singapore)'
    };

    this.US_WEST_SANTA_CLARA = {
        id: 'uc1',
        name: 'UC1 - US West (Santa Clara)'
    };

    this.US_CENTRAL_SALT_LAKE_CITY = {
        id: 'ut1',
        name: 'UT1 - US Central (Salt Lake City)'
    };

    this.US_EAST_STERLING = {
        id: 'va1',
        name: 'VA1 - US East (Sterling)'
    };

    this.US_WEST_SEATTLE = {
        id: 'wa1',
        name: 'WA1 - US West (Seattle)'
    }
}
<commit_msg>#2 Datacenter enum<commit_after>
module.exports = DataCenter;

function DataCenter() {

    this.DE_FRANKFURT = {
        id: 'de1',
            name: 'DE1 - Germany (Frankfurt)'
    };

    this.CA_VANCOUVER = {
        id: 'ca1',
        name: 'CA1 - Canada (Vancouver)'
    };

    this.CA_TORONTO_1 = {
        id: 'ca2',
        name: 'CA2 - Canada (Toronto)'
    };

    this.CA_TORONTO_2 = {
        id: 'ca3',
        name: 'CA3 - Canada (Toronto)'
    };

    this.GB_PORTSMOUTH = {
        id: 'gb1',
        name: 'GB1 - Great Britain (Portsmouth)'
    };

    this.GB_SLOUGH = {
        id: 'gb3',
        name: 'GB3 - Great Britain (Slough)'
    };

    this.US_CENTRAL_CHICAGO = {
        id: 'il1',
        name: 'IL1 - US Central (Chicago)'
    };

    this.US_EAST_NEW_YORK = {
        id: 'ny1',
        name: 'NY1 - US East (New York)'
    };

    this.SG_APAC = {
        id: 'sg1',
        name: 'SG1 - APAC (Singapore)'
    };

    this.US_WEST_SANTA_CLARA = {
        id: 'uc1',
        name: 'UC1 - US West (Santa Clara)'
    };

    this.US_CENTRAL_SALT_LAKE_CITY = {
        id: 'ut1',
        name: 'UT1 - US Central (Salt Lake City)'
    };

    this.US_EAST_STERLING = {
        id: 'va1',
        name: 'VA1 - US East (Sterling)'
    };

    this.US_WEST_SEATTLE = {
        id: 'wa1',
        name: 'WA1 - US West (Seattle)'
    };
}
<|endoftext|>


<commit_before>// still needs to be run on a separate file due to the global context
var RunCode = require('./runCode.js');

class CodeRunner {
  constructor(options) {
    this.plugins = options.plugins;
    this.logger = options.logger;
    this.events = options.events;
    this.ipc = options.ipc;
    this.commands = [];
    let self = this;
    // necessary to init the context
    RunCode.initContext();

    if (this.ipc.isServer()) {
      this.ipc.on('runcode:getCommands', (_err, callback) => {
        let result = {web3Config: RunCode.getWeb3Config(), commands: self.commands};
        callback(null, result);
      });
    }

    if (this.ipc.isClient() && this.ipc.connected) {
      this.ipc.listenTo('runcode:newCommand', function (command) {
        if (command.varName) {
          self.events.emit("runcode:register", command.varName, command.code);
        } else {
          self.events.request("runcode:eval", command.code);
        }
      });
    }

    this.events.on("runcode:register", (varName, code) => {
      if (self.ipc.isServer() && varName !== 'web3') {
        self.commands.push({varName, code});
        self.ipc.broadcast("runcode:newCommand", {varName, code});
      }
      RunCode.registerVar(varName, code);
    });

    this.events.setCommandHandler('runcode:eval', (code, cb, forConsoleOnly = false) => {
      if (!cb) {
        cb = function() {};
      }
      const awaitIdx = code.indexOf('await');
      if (awaitIdx > -1) {
        let end = code.length;
        if (code[end - 1] === ';') {
          end--; // Remove the `;` because we add function calls
        }
        if (awaitIdx < 2) {
          code = code.substring(5, end); // remove await keyword
          code += '.then(console.log).catch(console.error);'; // Add promise catch
        } else {
          code = code.substring(0, end); // remove ending `;`
          code = `(async function() {${code}.then(console.log);})();`;
        }
      }
      let result = RunCode.doEval(code);
      if (forConsoleOnly && self.ipc.isServer()) {
        self.commands.push({code});
        self.ipc.broadcast("runcode:newCommand", {code});
      }
      cb(null, result);
    });
  }

}

module.exports = CodeRunner;
<commit_msg>fix one with variable<commit_after>// still needs to be run on a separate file due to the global context
var RunCode = require('./runCode.js');

class CodeRunner {
  constructor(options) {
    this.plugins = options.plugins;
    this.logger = options.logger;
    this.events = options.events;
    this.ipc = options.ipc;
    this.commands = [];
    let self = this;
    // necessary to init the context
    RunCode.initContext();

    if (this.ipc.isServer()) {
      this.ipc.on('runcode:getCommands', (_err, callback) => {
        let result = {web3Config: RunCode.getWeb3Config(), commands: self.commands};
        callback(null, result);
      });
    }

    if (this.ipc.isClient() && this.ipc.connected) {
      this.ipc.listenTo('runcode:newCommand', function (command) {
        if (command.varName) {
          self.events.emit("runcode:register", command.varName, command.code);
        } else {
          self.events.request("runcode:eval", command.code);
        }
      });
    }

    this.events.on("runcode:register", (varName, code) => {
      if (self.ipc.isServer() && varName !== 'web3') {
        self.commands.push({varName, code});
        self.ipc.broadcast("runcode:newCommand", {varName, code});
      }
      RunCode.registerVar(varName, code);
    });

    this.events.setCommandHandler('runcode:eval', (code, cb, forConsoleOnly = false) => {
      if (!cb) {
        cb = function() {};
      }
      const awaitIdx = code.indexOf('await');
      if (awaitIdx > -1) {
        if (awaitIdx < 2) {
          let end = code.length;
          if (code[end - 1] === ';') {
            end--; // Remove the `;` because we add function calls
          }
          code = code.substring(5, end); // remove await keyword
          code += '.then(console.log).catch(console.error);'; // Add promise catch
        } else {
          code = `(async function() {${code}})();`;
        }
      }
      let result = RunCode.doEval(code);
      if (forConsoleOnly && self.ipc.isServer()) {
        self.commands.push({code});
        self.ipc.broadcast("runcode:newCommand", {code});
      }
      cb(null, result);
    });
  }

}

module.exports = CodeRunner;
<|endoftext|>


<commit_before>var util             = require('util'),
    OpenStreetMapGeocoder = require('./openstreetmapgeocoder');

/**
 * Constructor
 */
var NominatimMapquestGeocoder = function NominatimMapquestGeocoder(httpAdapter, options) {
    NominatimMapquestGeocoder.super_.call(this, httpAdapter, options);
};

util.inherits(NominatimMapquestGeocoder, OpenStreetMapGeocoder);

NominatimMapquestGeocoder.prototype._endpoint = 'http://open.mapquestapi.com/nominatim/v1/search';

NominatimMapquestGeocoder.prototype._endpoint_reverse = 'http://open.mapquestapi.com/nominatim/v1/search';

module.exports = NominatimMapquestGeocoder;
<commit_msg>Applied URL fix<commit_after>var util             = require('util'),
    OpenStreetMapGeocoder = require('./openstreetmapgeocoder');

/**
 * Constructor
 */
var NominatimMapquestGeocoder = function NominatimMapquestGeocoder(httpAdapter, options) {
    NominatimMapquestGeocoder.super_.call(this, httpAdapter, options);
};

util.inherits(NominatimMapquestGeocoder, OpenStreetMapGeocoder);

NominatimMapquestGeocoder.prototype._endpoint = 'http://open.mapquestapi.com/nominatim/v1/search';

NominatimMapquestGeocoder.prototype._endpoint_reverse = 'http://open.mapquestapi.com/nominatim/v1/reverse';

module.exports = NominatimMapquestGeocoder;
<|endoftext|>


<commit_before>define([
        '../Core/Color',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/destroyObject',
        '../Core/JulianDate',
        '../Core/Math'
    ], function(
        Color,
        defaultValue,
        defined,
        destroyObject,
        JulianDate,
        CesiumMath) {
    'use strict';

    /**
     * A heatmap colorizer in a {@link Cesium3DTileset}. A tileset can colorize its visible tiles in a heatmap style.
     *
     * @alias Cesium3DTilesetHeatmap
     * @constructor
     * @private
     */
    function Cesium3DTilesetHeatmap(heatmapVariable) {
        /**
         * The tile variable to track for heatmap colorization.
         * Tile's will be colorized relative to the other visible tile's values for this variable.
         *
         * @type {String}
         */
        this.variableName = heatmapVariable;

        // Members that are updated every time a tile is colorized
        this._min = Number.MAX_VALUE;
        this._max = -Number.MAX_VALUE;

        // Members that are updated once every frame
        this._previousMin = Number.MAX_VALUE;
        this._previousMax = -Number.MAX_VALUE;

        // If defined uses a reference min max to colorize by instead of using last frames min max of rendered tiles.
        // NOTE: For special cases, the references must be in the converted form (simple number).
        // _loadTimeStamp uses reference value by default since last frame's min/max aren't useful in it's case.
        // For example, the approximate scene load time can be set with setReferenceMinMax in order to take accurate colored timing diffs of various scenes.
        this._referenceMin = { };
        this._referenceMax = { };
    }

    /**
     * Convert to a usable heatmap value. Ensures that tile values that aren't stored as numbers can be used for colorization (if they can be converted to a number).
     * Also makes sure that external code can use this to set their reference min and max so the conversions are consistant or if they change they only change here.
     *
     * @param {Object} value The value for the specified variableName.
     * @param {String} variableName The name of the tile variable that will be colorized.
     * @returns {Number} The number value used in the heatmap.
     */
     function getHeatmapValue(tileValue, variableName) {
        var value;
        if (variableName === '_loadTimestamp') {
            value = JulianDate.toDate(tileValue).getTime();
        } else {
            value = tileValue;
        }
        return value;
    }

    /**
     * Sets the reference min and max for the variable name.
     *
     * @param {Number} min The min reference value.
     * @param {Number} max The max reference value.
     * @param {String} variableName The tile variable that will use these reference values when it is colorized.
     */
    Cesium3DTilesetHeatmap.prototype.setReferenceMinMax = function(min, max, variableName) {
        this._referenceMin[variableName] = getHeatmapValue(min, variableName);
        this._referenceMax[variableName] = getHeatmapValue(max, variableName);
    };

    function updateMinMax(heatmap, tile) {
        var variableName = heatmap.variableName;
        if (defined(variableName)) {
            var tileValue = getHeatmapValue(tile[variableName], variableName);
            if (!defined(tileValue)) {
                heatmap.variableName = undefined;
                return;
            }
            heatmap._max = Math.max(tileValue, heatmap._max);
            heatmap._min = Math.min(tileValue, heatmap._min);
        }
    }

    var heatmapColors = [new Color(0.000, 0.000, 0.000, 1),  // Black
                         new Color(0.153, 0.278, 0.878, 1),  // Blue
                         new Color(0.827, 0.231, 0.490, 1),  // Pink
                         new Color(0.827, 0.188, 0.220, 1),  // Red
                         new Color(1.000, 0.592, 0.259, 1),  // Orange
                         new Color(1.000, 0.843, 0.000, 1)]; // Yellow
    /**
     * Colorize the tile in heat map style based on where it lies within the min max window.
     * Heatmap colors are black, blue, pink, red, orange, yellow. 'Cold' or low numbers will be black and blue, 'Hot' or high numbers will be orange and yellow,
     * @param {Cesium3DTile} tile The tile to colorize relative to last frame's min and max values of all visible tiles.
     * @param {FrameState} frameState The frame state.
     */
    Cesium3DTilesetHeatmap.prototype.colorize = function (tile, frameState) {
        var variableName = this.variableName;
        if (!defined(variableName) || !tile.contentAvailable || tile._selectedFrame !== frameState.frameNumber) {
            return;
        }

        updateMinMax(this, tile);
        var min = this._previousMin;
        var max = this._previousMax;
        if (min === Number.MAX_VALUE || max === -Number.MAX_VALUE) {
            return;
        }

        // Shift the min max window down to 0
        var shiftedMax = (max - min) + CesiumMath.EPSILON7; // Prevent divide by 0
        var value = getHeatmapValue(tile[variableName], variableName);
        var shiftedValue = CesiumMath.clamp(value - min, 0, shiftedMax);

        // Get position between min and max and convert that to a position in the color array
        var zeroToOne = shiftedValue / shiftedMax;
        var lastIndex = heatmapColors.length - 1;
        var colorPosition = zeroToOne * lastIndex;

        // Take floor and ceil of the value to get the two colors to lerp between, lerp using the fractional portion
        var colorPositionFloor = Math.floor(colorPosition);
        var colorPositionCeil = Math.ceil(colorPosition);
        var t = colorPosition - colorPositionFloor;
        var colorZero = heatmapColors[colorPositionFloor];
        var colorOne = heatmapColors[colorPositionCeil];

        // Perform the lerp
        var finalColor = new Color(1,1,1,1);
        finalColor.red = CesiumMath.lerp(colorZero.red, colorOne.red, t);
        finalColor.green = CesiumMath.lerp(colorZero.green, colorOne.green, t);
        finalColor.blue = CesiumMath.lerp(colorZero.blue, colorOne.blue, t);
        tile._debugColor = finalColor;
    };

    /**
     * Resets the tracked min max values for heatmap colorization. Happens right before tileset traversal.
     */
    Cesium3DTilesetHeatmap.prototype.resetMinMax = function() {
        // For heat map colorization
        var variableName = this.variableName;
        if (defined(variableName)) {
            var referenceMin = this._referenceMin[variableName];
            var referenceMax = this._referenceMax[variableName];
            var useReference = defined(referenceMin) && defined(referenceMax);
            this._previousMin = useReference ? referenceMin : this._min;
            this._previousMax = useReference ? referenceMax : this._max;
            this._min = Number.MAX_VALUE;
            this._max = -Number.MAX_VALUE;
        }
    };

    Cesium3DTilesetHeatmap.prototype.isDestroyed = function() {
        return false;
    };

    Cesium3DTilesetHeatmap.prototype.destroy = function() {
        return destroyObject(this);
    };

    return Cesium3DTilesetHeatmap;
});
<commit_msg>updating comments<commit_after>define([
        '../Core/Color',
        '../Core/defaultValue',
        '../Core/defined',
        '../Core/destroyObject',
        '../Core/JulianDate',
        '../Core/Math'
    ], function(
        Color,
        defaultValue,
        defined,
        destroyObject,
        JulianDate,
        CesiumMath) {
    'use strict';

    /**
     * A heatmap colorizer in a {@link Cesium3DTileset}. A tileset can colorize its visible tiles in a heatmap style.
     *
     * @alias Cesium3DTilesetHeatmap
     * @constructor
     * @private
     */
    function Cesium3DTilesetHeatmap(heatmapVariable) {
        /**
         * The tile variable to track for heatmap colorization.
         * Tile's will be colorized relative to the other visible tile's values for this variable.
         *
         * @type {String}
         */
        this.variableName = heatmapVariable;

        // Members that are updated every time a tile is colorized
        this._min = Number.MAX_VALUE;
        this._max = -Number.MAX_VALUE;

        // Members that are updated once every frame
        this._previousMin = Number.MAX_VALUE;
        this._previousMax = -Number.MAX_VALUE;

        // If defined uses a reference min max to colorize by instead of using last frames min max of rendered tiles.
        // For example, the _loadTimestamp can get a better colorization using setReferenceMinMax in order to take accurate colored timing diffs of various scenes.
        this._referenceMin = { };
        this._referenceMax = { };
    }

    /**
     * Convert to a usable heatmap value (i.e. a number). Ensures that tile values that aren't stored as numbers can be used for colorization.
     *
     * @param {Object} value The value for the specified variableName.
     * @param {String} variableName The name of the tile variable that will be colorized.
     * @returns {Number} The number value used in the heatmap.
     */
     function getHeatmapValue(tileValue, variableName) {
        var value;
        if (variableName === '_loadTimestamp') {
            value = JulianDate.toDate(tileValue).getTime();
        } else {
            value = tileValue;
        }
        return value;
    }

    /**
     * Sets the reference min and max for the variable name. Converted to numbers before they are stored.
     *
     * @param {Object} min The min reference value.
     * @param {Object} max The max reference value.
     * @param {String} variableName The tile variable that will use these reference values when it is colorized.
     */
    Cesium3DTilesetHeatmap.prototype.setReferenceMinMax = function(min, max, variableName) {
        this._referenceMin[variableName] = getHeatmapValue(min, variableName);
        this._referenceMax[variableName] = getHeatmapValue(max, variableName);
    };

    function updateMinMax(heatmap, tile) {
        var variableName = heatmap.variableName;
        if (defined(variableName)) {
            var tileValue = getHeatmapValue(tile[variableName], variableName);
            if (!defined(tileValue)) {
                heatmap.variableName = undefined;
                return;
            }
            heatmap._max = Math.max(tileValue, heatmap._max);
            heatmap._min = Math.min(tileValue, heatmap._min);
        }
    }

    var heatmapColors = [new Color(0.000, 0.000, 0.000, 1),  // Black
                         new Color(0.153, 0.278, 0.878, 1),  // Blue
                         new Color(0.827, 0.231, 0.490, 1),  // Pink
                         new Color(0.827, 0.188, 0.220, 1),  // Red
                         new Color(1.000, 0.592, 0.259, 1),  // Orange
                         new Color(1.000, 0.843, 0.000, 1)]; // Yellow
    /**
     * Colorize the tile in heat map style based on where it lies within the min max window.
     * Heatmap colors are black, blue, pink, red, orange, yellow. 'Cold' or low numbers will be black and blue, 'Hot' or high numbers will be orange and yellow,
     * @param {Cesium3DTile} tile The tile to colorize relative to last frame's min and max values of all visible tiles.
     * @param {FrameState} frameState The frame state.
     */
    Cesium3DTilesetHeatmap.prototype.colorize = function (tile, frameState) {
        var variableName = this.variableName;
        if (!defined(variableName) || !tile.contentAvailable || tile._selectedFrame !== frameState.frameNumber) {
            return;
        }

        updateMinMax(this, tile);
        var min = this._previousMin;
        var max = this._previousMax;
        if (min === Number.MAX_VALUE || max === -Number.MAX_VALUE) {
            return;
        }

        // Shift the min max window down to 0
        var shiftedMax = (max - min) + CesiumMath.EPSILON7; // Prevent divide by 0
        var value = getHeatmapValue(tile[variableName], variableName);
        var shiftedValue = CesiumMath.clamp(value - min, 0, shiftedMax);

        // Get position between min and max and convert that to a position in the color array
        var zeroToOne = shiftedValue / shiftedMax;
        var lastIndex = heatmapColors.length - 1;
        var colorPosition = zeroToOne * lastIndex;

        // Take floor and ceil of the value to get the two colors to lerp between, lerp using the fractional portion
        var colorPositionFloor = Math.floor(colorPosition);
        var colorPositionCeil = Math.ceil(colorPosition);
        var t = colorPosition - colorPositionFloor;
        var colorZero = heatmapColors[colorPositionFloor];
        var colorOne = heatmapColors[colorPositionCeil];

        // Perform the lerp
        var finalColor = new Color(1,1,1,1);
        finalColor.red = CesiumMath.lerp(colorZero.red, colorOne.red, t);
        finalColor.green = CesiumMath.lerp(colorZero.green, colorOne.green, t);
        finalColor.blue = CesiumMath.lerp(colorZero.blue, colorOne.blue, t);
        tile._debugColor = finalColor;
    };

    /**
     * Resets the tracked min max values for heatmap colorization. Happens right before tileset traversal.
     */
    Cesium3DTilesetHeatmap.prototype.resetMinMax = function() {
        // For heat map colorization
        var variableName = this.variableName;
        if (defined(variableName)) {
            var referenceMin = this._referenceMin[variableName];
            var referenceMax = this._referenceMax[variableName];
            var useReference = defined(referenceMin) && defined(referenceMax);
            this._previousMin = useReference ? referenceMin : this._min;
            this._previousMax = useReference ? referenceMax : this._max;
            this._min = Number.MAX_VALUE;
            this._max = -Number.MAX_VALUE;
        }
    };

    Cesium3DTilesetHeatmap.prototype.isDestroyed = function() {
        return false;
    };

    Cesium3DTilesetHeatmap.prototype.destroy = function() {
        return destroyObject(this);
    };

    return Cesium3DTilesetHeatmap;
});
<|endoftext|>


<commit_before>/** section: Language
 * class Template
 *
 *  A class for sophisticated string interpolation.
 *
 *  Any time you have a group of similar objects and you need to produce
 *  formatted output for these objects, maybe inside a loop, you typically
 *  resort to concatenating string literals with the object's fields:
 *
 *      "The TV show " + title + " was created by " + author + ".";
 *
 *  There's nothing wrong with this approach, except that it is hard to
 *  visualize the output immediately just by glancing at the concatenation
 *  expression. The `Template` class provides a much nicer and clearer way of
 *  achieving this formatting.
 *
 *
Straightforward templates

 *
 *  The `Template` class uses a basic formatting syntax, similar to what is
 *  used in Ruby. The templates are created from strings that have embedded
 *  symbols in the form (e.g., `#{fieldName}`) that will be replaced by
 *  actual values when the template is applied (evaluated) to an object.
 *
 *      // the template (our formatting expression)
 *      var myTemplate = new Template(
 *       'The TV show #{title} was created by #{author}.');
 *
 *      // our data to be formatted by the template
 *      var show = {
 *        title: 'The Simpsons',
 *        author: 'Matt Groening',
 *        network: 'FOX'
 *      };
 *
 *      // let's format our data
 *      myTemplate.evaluate(show);
 *      // -> "The TV show The Simpsons was created by Matt Groening."
 *
 *
Templates are meant to be reused

 *
 *  As the example illustrates, `Template` objects are not tied to specific
 *  data. The data is bound to the template only during the evaluation of the
 *  template, without affecting the template itself. The next example shows the
 *  same template being used with a handful of distinct objects.
 *
 *      // creating a few similar objects
 *      var conversion1 = { from: 'meters', to: 'feet', factor: 3.28 };
 *      var conversion2 = { from: 'kilojoules', to: 'BTUs', factor: 0.9478 };
 *      var conversion3 = { from: 'megabytes', to: 'gigabytes', factor: 1024 };
 *
 *      // the template
 *      var templ = new Template(
 *       'Multiply by #{factor} to convert from #{from} to #{to}.');
 *
 *      // let's format each object
 *      [conversion1, conversion2, conversion3].each( function(conv){
 *          templ.evaluate(conv);
 *      });
 *      // -> Multiply by 3.28 to convert from meters to feet.
 *      // -> Multiply by 0.9478 to convert from kilojoules to BTUs.
 *      // -> Multiply by 1024 to convert from megabytes to gigabytes.
 *
 *
Escape sequence

 *
 *  There's always the chance that one day you'll need to have a literal in your
 *  template that looks like a symbol, but is not supposed to be replaced. For
 *  these situations there's an escape character: the backslash (\\).
 *
 *      // NOTE: you're seeing two backslashes here because the backslash
 *      // is also an escape character in JavaScript strings, so a literal
 *      // backslash is represented by two backslashes.
 *      var t = new Template(
 *       'in #{lang} we also use the \\#{variable} syntax for templates.');
 *      var data = { lang:'Ruby', variable: '(not used)' };
 *      t.evaluate(data);
 *      // -> in Ruby we also use the #{variable} syntax for templates.
 *
 *
Custom syntaxes

 *
 *  The default syntax of the template strings will probably be enough for most
 *  scenarios. In the rare occasion where the default Ruby-like syntax is
 *  inadequate, there's a provision for customization. `Template`'s
 *  constructor accepts an optional second argument that is a regular expression
 *  object to match the replaceable symbols in the template string. Let's put
 *  together a template that uses a syntax similar to the ubiquitous `<%= %>`
 *  constructs:
 *
 *      // matches symbols like '<%= field %>'
 *      var syntax = /(^|.|\r|\n)(\<%=\s*(\w+)\s*%\>)/;
 *
 *      var t = new Template(
 *       '
Name: <%= name %>, Age: <%= age %>
',
 *       syntax);
 *      t.evaluate( {name: 'John Smith', age: 26} );
 *      // ->
Name: John Smith, Age: 26

 *
 *  There are important constraints to any custom syntax. Any syntax must
 *  provide at least three groupings in the regular expression. The first
 *  grouping is to capture what comes before the symbol, to detect the backslash
 *  escape character (no, you cannot use a different character). The second
 *  grouping captures the entire symbol and will be completely replaced upon
 *  evaluation. Lastly, the third required grouping captures the name of the
 *  field inside the symbol.
 *
**/
var Template = Class.create({
  /**
   *  new Template(template[, pattern = Template.Pattern])
   *
   *  Creates a Template object.
   *
   *  The optional `pattern` argument expects a `RegExp` that defines a custom
   *  syntax for the replaceable symbols in `template`.
  **/
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern = pattern || Template.Pattern;
  },

  /**
   *  Template#evaluate(object) -> String
   *
   *  Applies the template to `object`'s data, producing a formatted string
   *  with symbols replaced by `object`'s corresponding properties.
  **/
  evaluate: function(object) {
    if (object && Object.isFunction(object.toTemplateReplacements))
      object = object.toTemplateReplacements();

    return this.template.gsub(this.pattern, function(match) {
      if (object == null) return (match[1] + '');

      var before = match[1] || '';
      if (before == '\\') return match[2];

      var ctx = object, expr = match[3],
          pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;

      match = pattern.exec(expr);
      if (match == null) return before;

      while (match != null) {
        var comp = match[1].startsWith('[') ? match[2].replace(/\\\\]/g, ']') : match[1];
        ctx = ctx[comp];
        if (null == ctx || '' == match[3]) break;
        expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
        match = pattern.exec(expr);
      }

      return before + String.interpret(ctx);
    });
  }
});
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
<commit_msg>doc: Fix Template doc to avoid issues with Sprockets.<commit_after>/** section: Language
 * class Template
 *
 *  A class for sophisticated string interpolation.
 *
 *  Any time you have a group of similar objects and you need to produce
 *  formatted output for these objects, maybe inside a loop, you typically
 *  resort to concatenating string literals with the object's fields:
 *
 *      "The TV show " + title + " was created by " + author + ".";
 *
 *  There's nothing wrong with this approach, except that it is hard to
 *  visualize the output immediately just by glancing at the concatenation
 *  expression. The `Template` class provides a much nicer and clearer way of
 *  achieving this formatting.
 *
 *
Straightforward templates

 *
 *  The `Template` class uses a basic formatting syntax, similar to what is
 *  used in Ruby. The templates are created from strings that have embedded
 *  symbols in the form (e.g., `#{fieldName}`) that will be replaced by
 *  actual values when the template is applied (evaluated) to an object.
 *
 *      // the template (our formatting expression)
 *      var myTemplate = new Template(
 *       'The TV show #{title} was created by #{author}.');
 *
 *      // our data to be formatted by the template
 *      var show = {
 *        title: 'The Simpsons',
 *        author: 'Matt Groening',
 *        network: 'FOX'
 *      };
 *
 *      // let's format our data
 *      myTemplate.evaluate(show);
 *      // -> "The TV show The Simpsons was created by Matt Groening."
 *
 *
Templates are meant to be reused

 *
 *  As the example illustrates, `Template` objects are not tied to specific
 *  data. The data is bound to the template only during the evaluation of the
 *  template, without affecting the template itself. The next example shows the
 *  same template being used with a handful of distinct objects.
 *
 *      // creating a few similar objects
 *      var conversion1 = { from: 'meters', to: 'feet', factor: 3.28 };
 *      var conversion2 = { from: 'kilojoules', to: 'BTUs', factor: 0.9478 };
 *      var conversion3 = { from: 'megabytes', to: 'gigabytes', factor: 1024 };
 *
 *      // the template
 *      var templ = new Template(
 *       'Multiply by #{factor} to convert from #{from} to #{to}.');
 *
 *      // let's format each object
 *      [conversion1, conversion2, conversion3].each( function(conv){
 *          templ.evaluate(conv);
 *      });
 *      // -> Multiply by 3.28 to convert from meters to feet.
 *      // -> Multiply by 0.9478 to convert from kilojoules to BTUs.
 *      // -> Multiply by 1024 to convert from megabytes to gigabytes.
 *
 *
Escape sequence

 *
 *  There's always the chance that one day you'll need to have a literal in your
 *  template that looks like a symbol, but is not supposed to be replaced. For
 *  these situations there's an escape character: the backslash (\\).
 *
 *      // NOTE: you're seeing two backslashes here because the backslash
 *      // is also an escape character in JavaScript strings, so a literal
 *      // backslash is represented by two backslashes.
 *      var t = new Template(
 *       'in #{lang} we also use the \\#{variable} syntax for templates.');
 *      var data = { lang:'Ruby', variable: '(not used)' };
 *      t.evaluate(data);
 *      // -> in Ruby we also use the #{variable} syntax for templates.
 *
 *
Custom syntaxes

 *
 *  The default syntax of the template strings will probably be enough for most
 *  scenarios. In the rare occasion where the default Ruby-like syntax is
 *  inadequate, there's a provision for customization. `Template`'s
 *  constructor accepts an optional second argument that is a regular expression
 *  object to match the replaceable symbols in the template string. Let's put
 *  together a template that uses a syntax similar to the now ubiquitous `{{ }}`
 *  constructs:
 *
 *      // matches symbols like '{{ field }}'
 *      var syntax = /(^|.|\r|\n)(\{{\s*(\w+)\s*}})/;
 *
 *      var t = new Template(
 *       '
Name: {{ name }}, Age: {{ age }}
',
 *       syntax);
 *      t.evaluate( {name: 'John Smith', age: 26} );
 *      // ->
Name: John Smith, Age: 26

 *
 *  There are important constraints to any custom syntax. Any syntax must
 *  provide at least three groupings in the regular expression. The first
 *  grouping is to capture what comes before the symbol, to detect the backslash
 *  escape character (no, you cannot use a different character). The second
 *  grouping captures the entire symbol and will be completely replaced upon
 *  evaluation. Lastly, the third required grouping captures the name of the
 *  field inside the symbol.
 *
**/
var Template = Class.create({
  /**
   *  new Template(template[, pattern = Template.Pattern])
   *
   *  Creates a Template object.
   *
   *  The optional `pattern` argument expects a `RegExp` that defines a custom
   *  syntax for the replaceable symbols in `template`.
  **/
  initialize: function(template, pattern) {
    this.template = template.toString();
    this.pattern = pattern || Template.Pattern;
  },

  /**
   *  Template#evaluate(object) -> String
   *
   *  Applies the template to `object`'s data, producing a formatted string
   *  with symbols replaced by `object`'s corresponding properties.
  **/
  evaluate: function(object) {
    if (object && Object.isFunction(object.toTemplateReplacements))
      object = object.toTemplateReplacements();

    return this.template.gsub(this.pattern, function(match) {
      if (object == null) return (match[1] + '');

      var before = match[1] || '';
      if (before == '\\') return match[2];

      var ctx = object, expr = match[3],
          pattern = /^([^.[]+|\[((?:.*?[^\\])?)\])(\.|\[|$)/;

      match = pattern.exec(expr);
      if (match == null) return before;

      while (match != null) {
        var comp = match[1].startsWith('[') ? match[2].replace(/\\\\]/g, ']') : match[1];
        ctx = ctx[comp];
        if (null == ctx || '' == match[3]) break;
        expr = expr.substring('[' == match[3] ? match[1].length : match[0].length);
        match = pattern.exec(expr);
      }

      return before + String.interpret(ctx);
    });
  }
});
Template.Pattern = /(^|.|\r|\n)(#\{(.*?)\})/;
<|endoftext|>


<commit_before><commit_msg>fixed bug, where you could not import muted string<commit_after><|endoftext|>


<commit_before>var botb_api = require('./botb_api.js');

module.exports = {

	aliases: {
		chord: 'ultrachord',
		g: 'google',
		gi: 'image',
		h: 'help',
		i: 'imdb',
		images: 'image',
		uc: 'ultrachord',
		w: 'wikipedia',
		wiki: 'wikipedia',
		y: 'youtube',
		yt: 'youtube',
		b: 'battle',
		ohc: 'battle',
		ohb: 'battle',
		compo: 'battle',
		up: 'uptime',
		pic: 'pix'
	},

	battle: function(bot, info, words) {
		var p = botb_api.request('battle/current');
		p.then(function(data) {
			data.forEach(function(battle) {
				var response = battle.title;
				// XXX bit period v entry period stuff
				response += ' :: ' + battle.entry_count + ' entries';
				response += ' :: ' + battle.period + ' period deadline';
				response += ' ' + battle.period_end_date;
				response += ' ' + battle.period_end_time_left;
				response += ' :: final results ' + battle.end_date;
				response += ' ' + battle.end_time_left;
				response += ' :: ' + battle.profile_url;
				bot.say(info.args[0], response);
			});
		}).catch(function(error) {
			bot.say(info.args[0], 'No current Battles teh running! =0');
		});
	},

	botbr: function(bot, info, words) {
		var name = words.slice(1).join(' ');
		if (typeof name === 'undefined' || name.length < 2) {
			bot.say(info.args[0], 'Moar characters!! =X');
			return;
		}
		var p = botb_api.request('botbr/search/' + name);
		var none_found = function() {
			bot.say(info.args[0], 'BotBr no found! =0');
		}
		p.then(function(data) {
			if (data.length == 0) {
				none_found();
				return;
			}
			var botbr;
			if (data.length > 1) {
				var response;
				var botbrs = [];
				data.forEach(function(botbr_object) {
					botbrs.push(botbr_object.name);
					if (name == botbr_object.name) {
						botbr = botbr_object;
					}
				});
				if (typeof botbr === 'undefined') {
					response = 'Possible matches :: ';
					response += botbrs.join(', ');
					bot.say(info.args[0], response);
					return;
				}
			}
			if (data.length == 1) {
				botbr = data[0];
			}
			var response = botbr.name;
			response += ' :: Lvl ' + botbr.level;
			response += ' ' + botbr.class;
			response += ' :: ' + botbr.profile_url;
			bot.say(info.args[0], response);
		}).catch(function(error) {
			none_found();
		});
	},

	entry: function(bot, info, words) {
		var title = words.slice(1).join(' ');
		var p;
		if (typeof title === 'undefined' || title.length < 2) {
			p = botb_api.request('entry/random');
		}
		else {
			p = botb_api.request('entry/search/' + title);
		}
		var none_found = function() {
			bot.say(info.args[0], 'String "' + title + '" does not match entry %title%;');
		}
		p.then(function(data) {
			if (data.length == 0) {
				none_found();
				return;
			}
			var entry;
			if (data.length == 1) {
				entry = data[0];
			}
			if (data.length > 1) {
				entry = data[Math.floor(Math.random() * data.length)];
			}
			var response = entry.botbr.name;
			response += ' - ' + entry.title;
			response += ' :: ' + entry.profile_url;
			bot.say(info.args[0], response);
		}).catch(function(error) {
			none_found();
		});
	},

	top: function(bot, info, words) {
		var filter = words.slice(1).join(' ');
		var p;
		if (typeof filter === 'undefined' || filter.length < 2) {
			p = botb_api.request('botbr/list/0/5?sort=points&desc=true');
		}
		else {
			p = botb_api.request('botbr/list/0/5?filters=class~' + filter + '&sort=points&desc=true');
		}
		var none_found = function() {
			bot.say(info.args[0], "Couldn't find anything! Did you spell the class right?");
		}
		p.then(function(data) {
			if (data.length == 0) {
				none_found();
				return;
			}
			var response = '';
			var botbrs = [];
			data.forEach(function(botbr_object) {
				if (response !== '') {
					response += ', ';
				}
				response += botbr_object.name;
				response += ' :: ';
				response += 'Lvl ' + botbr_object.level;
				if (typeof filter === 'undefined' || filter.length < 2) {
					response += ' ' + botbr_object.class;
				}
			});
			if (response === '') {
				none_found();
			}
			else {
				bot.say(info.args[0], response);
			}
		}).catch(function(error) {
			none_found();
		});
	},

	uptime: function(bot, info, words) {
		String.prototype.toHHMMSS = function () {
			var sec_num = parseInt(this, 10); // don't forget the second param
			var hours   = Math.floor(sec_num / 3600);
			var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
			var seconds = sec_num - (hours * 3600) - (minutes * 60);

			// if (hours   < 10) {hours   = "0" + hours;}
			// if (minutes < 10) {minutes = "0" + minutes;}
			// if (seconds < 10) {seconds = "0" + seconds;}
			var time    = hours + ' hours, ' + minutes + ' minutes, and ' + seconds + " seconds.";
			return time;
		}

		var time = process.uptime();
		var uptime = (time + "").toHHMMSS();

		bot.say(info.args[0], "BotB has been running for " + uptime);
	},

	/// web commands

	google: function(bot, info, words) {
		bot.say(info.args[0], "https://encrypted.google.com/search?q=" + words.slice(1).join('%20'));
	},

	image: function(bot, info, words) {
		bot.say(info.args[0], "https://www.google.com/search?tbm=isch&q=" + words.slice(1).join('%20'));
	},

	wikipedia: function(bot, info, words) {
		bot.say(info.args[0], "https://en.wikipedia.org/w/index.php?search=" + words.slice(1).join('%20'));
	},

	imdb: function(bot, info, words) {
		bot.say(info.args[0], "http://www.imdb.com/find?s=all&q=" + words.slice(1).join('%20'));
	},

	youtube: function(bot, info, words) {
		bot.say(info.args[0], "https://www.youtube.com/results?search_query=" + words.slice(1).join('%20'))
	},

	ultrachord: function(bot, info, words) { // TODO

	},

	help: function(bot, info, words) { // TODO

	},

	levelup: function(bot, info, words) { // TODO

	},

	pix: function(bot, info, words) { // TODO

	}
};
<commit_msg>worst module ever written<commit_after>var botb_api = require('./botb_api.js');

module.exports = {

	aliases: {
		chord: 'ultrachord',
		g: 'google',
		gi: 'image',
		h: 'help',
		i: 'imdb',
		images: 'image',
		uc: 'ultrachord',
		w: 'wikipedia',
		wiki: 'wikipedia',
		y: 'youtube',
		yt: 'youtube',
		b: 'battle',
		ohc: 'battle',
		ohb: 'battle',
		compo: 'battle',
		up: 'uptime',
		pic: 'pix'
	},

	battle: function(bot, info, words) {
		var p = botb_api.request('battle/current');
		p.then(function(data) {
			data.forEach(function(battle) {
				var response = battle.title;
				// XXX bit period v entry period stuff
				response += ' :: ' + battle.entry_count + ' entries';
				response += ' :: ' + battle.period + ' period deadline';
				response += ' ' + battle.period_end_date;
				response += ' ' + battle.period_end_time_left;
				response += ' :: final results ' + battle.end_date;
				response += ' ' + battle.end_time_left;
				response += ' :: ' + battle.profile_url;
				bot.say(info.args[0], response);
			});
		}).catch(function(error) {
			bot.say(info.args[0], 'No current Battles teh running! =0');
		});
	},

	botbr: function(bot, info, words) {
		var name = words.slice(1).join(' ');
		if (typeof name === 'undefined' || name.length < 2) {
			bot.say(info.args[0], 'Moar characters!! =X');
			return;
		}
		var p = botb_api.request('botbr/search/' + name);
		var none_found = function() {
			bot.say(info.args[0], 'BotBr no found! =0');
		}
		p.then(function(data) {
			if (data.length == 0) {
				none_found();
				return;
			}
			var botbr;
			if (data.length > 1) {
				var response;
				var botbrs = [];
				data.forEach(function(botbr_object) {
					botbrs.push(botbr_object.name);
					if (name == botbr_object.name) {
						botbr = botbr_object;
					}
				});
				if (typeof botbr === 'undefined') {
					response = 'Possible matches :: ';
					response += botbrs.join(', ');
					bot.say(info.args[0], response);
					return;
				}
			}
			if (data.length == 1) {
				botbr = data[0];
			}
			var response = botbr.name;
			response += ' :: Lvl ' + botbr.level;
			response += ' ' + botbr.class;
			response += ' :: ' + botbr.profile_url;
			bot.say(info.args[0], response);
		}).catch(function(error) {
			none_found();
		});
	},

	entry: function(bot, info, words) {
		var title = words.slice(1).join(' ');
		var p;
		if (typeof title === 'undefined' || title.length < 2) {
			p = botb_api.request('entry/random');
		}
		else {
			p = botb_api.request('entry/search/' + title);
		}
		var none_found = function() {
			bot.say(info.args[0], 'String "' + title + '" does not match entry %title%;');
		}
		p.then(function(data) {
			if (data.length == 0) {
				none_found();
				return;
			}
			var entry;
			if (data.length == 1) {
				entry = data[0];
			}
			if (data.length > 1) {
				entry = data[Math.floor(Math.random() * data.length)];
			}
			var response = entry.botbr.name;
			response += ' - ' + entry.title;
			response += ' :: ' + entry.profile_url;
			bot.say(info.args[0], response);
		}).catch(function(error) {
			none_found();
		});
	},

	top: function(bot, info, words) {
		var filter = words.slice(1).join(' ');
		var p;
		if (typeof filter === 'undefined' || filter.length < 2) {
			p = botb_api.request('botbr/list/0/5?sort=points&desc=true');
		}
		else {
			p = botb_api.request('botbr/list/0/5?filters=class~' + filter + '&sort=points&desc=true');
		}
		var none_found = function() {
			bot.say(info.args[0], "Couldn't find anything! Did you spell the class right?");
		}
		p.then(function(data) {
			if (data.length == 0) {
				none_found();
				return;
			}
			var response = '';
			var botbrs = [];
			data.forEach(function(botbr_object) {
				if (response !== '') {
					response += ', ';
				}
				response += botbr_object.name;
				response += ' :: ';
				response += 'Lvl ' + botbr_object.level;
				if (typeof filter === 'undefined' || filter.length < 2) {
					response += ' ' + botbr_object.class;
				}
			});
			if (response === '') {
				none_found();
			}
			else {
				bot.say(info.args[0], response);
			}
		}).catch(function(error) {
			none_found();
		});
	},

	uptime: function(bot, info, words) {
		String.prototype.toHHMMSS = function () {
			var sec_num = parseInt(this, 10); // don't forget the second param
			var hours   = Math.floor(sec_num / 3600);
			var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
			var seconds = sec_num - (hours * 3600) - (minutes * 60);

			// if (hours   < 10) {hours   = "0" + hours;}
			// if (minutes < 10) {minutes = "0" + minutes;}
			// if (seconds < 10) {seconds = "0" + seconds;}
			var time    = hours + ' hours, ' + minutes + ' minutes, and ' + seconds + " seconds.";
			return time;
		}

		var time = process.uptime();
		var uptime = (time + "").toHHMMSS();

		bot.say(info.args[0], "BotB has been running for " + uptime);
	},

	/// web commands

	google: function(bot, info, words) {
		bot.say(info.args[0], "https://encrypted.google.com/search?q=" + words.slice(1).join('%20'));
	},

	image: function(bot, info, words) {
		bot.say(info.args[0], "https://www.google.com/search?tbm=isch&q=" + words.slice(1).join('%20'));
	},

	wikipedia: function(bot, info, words) {
		bot.say(info.args[0], "https://en.wikipedia.org/w/index.php?search=" + words.slice(1).join('%20'));
	},

	imdb: function(bot, info, words) {
		bot.say(info.args[0], "http://www.imdb.com/find?s=all&q=" + words.slice(1).join('%20'));
	},

	youtube: function(bot, info, words) {
		bot.say(info.args[0], "https://www.youtube.com/results?search_query=" + words.slice(1).join('%20'))
	},

	ultrachord: function(bot, info, words) { // TODO
		const execSync = require('child_process').execSync;
		var timbre = "sin"
		var note = []

		function makeid() {
    		var text = "";
    		var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";

   			for(var i = 0; i < 16; i++)
    		    text += possible.charAt(Math.floor(Math.random() * possible.length));

    		return text;
		}

		var i = 0;
		var id = makeid();

		words.forEach(function() {
			switch(words[i]) {
				case "C3":
					note[i-1] = "130.8";
					break;
				case "C#3":
					note[i-1] = "138.6";
					break;
				case "Db3":
					note[i-1] = "138.6";
					break;
				case "D3":
					note[i-1] = "146.8";
					break;
				case "D#3":
					note[i-1] = "155.6";
					break;
				case "Eb3":
					note[i-1] = "155.6";
					break;
				case "E3":
					note[i-1] = "164.8";
					break;
				case "F3":
					note[i-1] = "174.6";
					break;
				case "F#3":
					note[i-1] = "185.0";
					break;
				case "Gb3":
					note[i-1] = "185.0";
					break;
				case "G3":
					note[i-1] = "196.0";
					break;
				case "G#3":
					note[i-1] = "207.7";
					break;
				case "Ab3":
					note[i-1] = "207.7";
					break;
				case "A3":
					note[i-1] = "220.0";
					break;
				case "A#3":
					note[i-1] = "233.1";
					break;
				case "Bb3":
					note[i-1] = "233.1";
					break;
				case "B3":
					note[i-1] = "246.9";
					break;
				case "C4":
					note[i-1] = "261.6";
					break;
				case "C#4":
					note[i-1] = "277.2";
					break;
				case "Db4":
					note[i-1] = "277.2";
					break;
				case "D4":
					note[i-1] = "293.7";
					break;
				case "D#4":
					note[i-1] = "311.1";
					break;
				case "Eb4":
					note[i-1] = "311.1";
					break;
				case "E4":
					note[i-1] = "329.6";
					break;
				case "F4":
					note[i-1] = "349.2";
					break;
				case "F#4":
					note[i-1] = "370.0";
					break;
				case "Gb4":
					note[i-1] = "370.0";
					break;
				case "G4":
					note[i-1] = "392.0";
					break;
				case "G#4":
					note[i-1] = "415.3";
					break;
				case "Ab4":
					note[i-1] = "415.3";
					break;
				case "A4":
					note[i-1] = "440";
					break;
				case "A#4":
					note[i-1] = "466.2";
					break;
				case "Bb4":
					note[i-1] = "466.2";
					break;
				case "B4": // B4 what?
					note[i-1] = "493.9";
					break;
				case "pluck":
					timbre = "pluck";
					break;
				case "square":
					timbre = "square";
					break;
				case "triangle":
					timbre = "triangle";
					break;
				case "sawtooth":
					timbre = "sawtooth";
					break;
				case "sin":
					timbre = "sin";
					break;
			};
			i++;
		});

		// you probably shouldn't look at this code
		console.log(note);
		console.log(words);

		code = execSync('sox -n ' + id + '.wav synth 5 ' + timbre + " " + note.join(" " + timbre + " "));
		upload = execSync('curl -i -F file=@' + id + '.wav https://uguu.se/api.php?d=upload-tool')

		var link = upload.toString().split(/\r?\n/);
		bot.say(info.args[0], link[link.length - 1]);

		console.log(link);

		del = execSync('rm ' + id + '.wav');
		bot.say(info.args[0], "toen work!")
	},

	help: function(bot, info, words) { // TODO

	},

	levelup: function(bot, info, words) { // TODO

	},

	pix: function(bot, info, words) { // TODO

	}
};
<|endoftext|>


<commit_before>define(function() {

  // Export
  return function(Prism) {

    Prism.languages.php = {
      'comment': {
        pattern: /(^|[^\\])(\/\*[\w\W]*?\*\/|\/\/.*?(\r?\n|$))/g,
        lookbehind: true
      },
      'deliminator': /(\?>|\?>|<\?php|<\?php)/ig,
      'variable': /(\$\w+)\b/ig,
      'string': /("|')(\\?.)*?\1/g,
      'regex': {
        pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,
        lookbehind: true
      },
      'keyword': /\b(and|or|xor|array|as|break|case|cfunction|class|const|continue|declare|default|die|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|for|foreach|function|include|include_once|global|if|new|return|static|switch|use|require|require_once|var|while|abstract|interface|public|implements|extends|private|protected|throw)\b/g,
      'function': /\b(abs|acos|acosh|addcslashes|addslashes|array_change_key_case|array_chunk|array_combine|array_count_values|array_diff|array_diff_assoc|array_diff_key|array_diff_uassoc|array_diff_ukey|array_fill|array_filter|array_flip|array_intersect|array_intersect_assoc|array_intersect_key|array_intersect_uassoc|array_intersect_ukey|array_key_exists|array_keys|array_map|array_merge|array_merge_recursive|array_multisort|array_pad|array_pop|array_product|array_push|array_rand|array_reduce|array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|array_udiff_assoc|array_udiff_uassoc|array_uintersect|array_uintersect_assoc|array_uintersect_uassoc|array_unique|array_unshift|array_values|array_walk|array_walk_recursive|atan|atan2|atanh|base64_decode|base64_encode|base_convert|basename|bcadd|bccomp|bcdiv|bcmod|bcmul|bindec|bindtextdomain|bzclose|bzcompress|bzdecompress|bzerrno|bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|ceil|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|chroot|chunk_split|class_exists|closedir|closelog|copy|cos|cosh|count|count_chars|date|decbin|dechex|decoct|deg2rad|delete|ebcdic2ascii|echo|empty|end|ereg|ereg_replace|eregi|eregi_replace|error_log|error_reporting|escapeshellarg|escapeshellcmd|eval|exec|exit|exp|explode|extension_loaded|feof|fflush|fgetc|fgetcsv|fgets|fgetss|file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|fileowner|fileperms|filesize|filetype|floatval|flock|floor|flush|fmod|fnmatch|fopen|fpassthru|fprintf|fputcsv|fputs|fread|fscanf|fseek|fsockopen|fstat|ftell|ftok|getallheaders|getcwd|getdate|getenv|gethostbyaddr|gethostbyname|gethostbynamel|getimagesize|getlastmod|getmxrr|getmygid|getmyinode|getmypid|getmyuid|getopt|getprotobyname|getprotobynumber|getrandmax|getrusage|getservbyname|getservbyport|gettext|gettimeofday|gettype|glob|gmdate|gmmktime|ini_alter|ini_get|ini_get_all|ini_restore|ini_set|interface_exists|intval|ip2long|is_a|is_array|is_bool|is_callable|is_dir|is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|is_readable|is_real|is_resource|is_scalar|is_soap_fault|is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|mkdir|mktime|nl2br|parse_ini_file|parse_str|parse_url|passthru|pathinfo|readlink|realpath|rewind|rewinddir|rmdir|round|str_ireplace|str_pad|str_repeat|str_replace|str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|strcspn|strftime|strip_tags|stripcslashes|stripos|stripslashes|stristr|strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpbrk|strpos|strptime|strrchr|strrev|strripos|strrpos|strspn|strstr|strtok|strtolower|strtotime|strtoupper|strtr|strval|substr|substr_compare)\b/g,
      'constant': /\b(__FILE__|__LINE__|__METHOD__|__FUNCTION__|__CLASS__)\b/g,
      'boolean': /\b(true|false)\b/g,
      'number': /\b-?(0x)?\d*\.?\d+\b/g,
      'operator': /[-+]{1,2}|!|=?\<|=?\>;|={1,2}(?!>)|(\&){1,2}|\|?\||\?|\*|\//g,
      'punctuation': /[{}[\];(),.:]/g
    };

  };

});
<commit_msg>Fix indentation of the PHP grammar<commit_after>define(function() {
  return function(Prism) {
    Prism.languages.php = {
      'comment': {
        pattern: /(^|[^\\])(\/\*[\w\W]*?\*\/|\/\/.*?(\r?\n|$))/g,
        lookbehind: true
      },
      'deliminator': /(\?>|\?>|<\?php|<\?php)/ig,
      'variable': /(\$\w+)\b/ig,
      'string': /("|')(\\?.)*?\1/g,
      'regex': {
        pattern: /(^|[^/])\/(?!\/)(\[.+?]|\\.|[^/\r\n])+\/[gim]{0,3}(?=\s*($|[\r\n,.;})]))/g,
        lookbehind: true
      },
      'keyword': /\b(and|or|xor|array|as|break|case|cfunction|class|const|continue|declare|default|die|do|else|elseif|enddeclare|endfor|endforeach|endif|endswitch|endwhile|extends|for|foreach|function|include|include_once|global|if|new|return|static|switch|use|require|require_once|var|while|abstract|interface|public|implements|extends|private|protected|throw)\b/g,
      'function': /\b(abs|acos|acosh|addcslashes|addslashes|array_change_key_case|array_chunk|array_combine|array_count_values|array_diff|array_diff_assoc|array_diff_key|array_diff_uassoc|array_diff_ukey|array_fill|array_filter|array_flip|array_intersect|array_intersect_assoc|array_intersect_key|array_intersect_uassoc|array_intersect_ukey|array_key_exists|array_keys|array_map|array_merge|array_merge_recursive|array_multisort|array_pad|array_pop|array_product|array_push|array_rand|array_reduce|array_reverse|array_search|array_shift|array_slice|array_splice|array_sum|array_udiff|array_udiff_assoc|array_udiff_uassoc|array_uintersect|array_uintersect_assoc|array_uintersect_uassoc|array_unique|array_unshift|array_values|array_walk|array_walk_recursive|atan|atan2|atanh|base64_decode|base64_encode|base_convert|basename|bcadd|bccomp|bcdiv|bcmod|bcmul|bindec|bindtextdomain|bzclose|bzcompress|bzdecompress|bzerrno|bzerror|bzerrstr|bzflush|bzopen|bzread|bzwrite|ceil|chdir|checkdate|checkdnsrr|chgrp|chmod|chop|chown|chr|chroot|chunk_split|class_exists|closedir|closelog|copy|cos|cosh|count|count_chars|date|decbin|dechex|decoct|deg2rad|delete|ebcdic2ascii|echo|empty|end|ereg|ereg_replace|eregi|eregi_replace|error_log|error_reporting|escapeshellarg|escapeshellcmd|eval|exec|exit|exp|explode|extension_loaded|feof|fflush|fgetc|fgetcsv|fgets|fgetss|file_exists|file_get_contents|file_put_contents|fileatime|filectime|filegroup|fileinode|filemtime|fileowner|fileperms|filesize|filetype|floatval|flock|floor|flush|fmod|fnmatch|fopen|fpassthru|fprintf|fputcsv|fputs|fread|fscanf|fseek|fsockopen|fstat|ftell|ftok|getallheaders|getcwd|getdate|getenv|gethostbyaddr|gethostbyname|gethostbynamel|getimagesize|getlastmod|getmxrr|getmygid|getmyinode|getmypid|getmyuid|getopt|getprotobyname|getprotobynumber|getrandmax|getrusage|getservbyname|getservbyport|gettext|gettimeofday|gettype|glob|gmdate|gmmktime|ini_alter|ini_get|ini_get_all|ini_restore|ini_set|interface_exists|intval|ip2long|is_a|is_array|is_bool|is_callable|is_dir|is_double|is_executable|is_file|is_finite|is_float|is_infinite|is_int|is_integer|is_link|is_long|is_nan|is_null|is_numeric|is_object|is_readable|is_real|is_resource|is_scalar|is_soap_fault|is_string|is_subclass_of|is_uploaded_file|is_writable|is_writeable|mkdir|mktime|nl2br|parse_ini_file|parse_str|parse_url|passthru|pathinfo|readlink|realpath|rewind|rewinddir|rmdir|round|str_ireplace|str_pad|str_repeat|str_replace|str_rot13|str_shuffle|str_split|str_word_count|strcasecmp|strchr|strcmp|strcoll|strcspn|strftime|strip_tags|stripcslashes|stripos|stripslashes|stristr|strlen|strnatcasecmp|strnatcmp|strncasecmp|strncmp|strpbrk|strpos|strptime|strrchr|strrev|strripos|strrpos|strspn|strstr|strtok|strtolower|strtotime|strtoupper|strtr|strval|substr|substr_compare)\b/g,
      'constant': /\b(__FILE__|__LINE__|__METHOD__|__FUNCTION__|__CLASS__)\b/g,
      'boolean': /\b(true|false)\b/g,
      'number': /\b-?(0x)?\d*\.?\d+\b/g,
      'operator': /[-+]{1,2}|!|=?\<|=?\>;|={1,2}(?!>)|(\&){1,2}|\|?\||\?|\*|\//g,
      'punctuation': /[{}[\];(),.:]/g
    };
  };
});
<|endoftext|>


<commit_before>(function() {

	// private
	var _dom, _persistant, _custom , _util;

	// public
	var api;

	// utility functions for event management
	_util = {
		format_type : function(type) {
 			return (type === 'DOMContentLoaded' || /^on/.test(type)) ? type : 'on' + type;
		}
	};

	_dom = {
		collection : [],
		add : function(target, type, cb) {

			type = _util.format_type(type);

			var target_events = this.find_events_by_target(target);
			if (target_events) {
				(target_events.types[type]) ? target_events.types[type].push(cb) : target_events.types[type] = [cb];
			}
			else {
				var new_target_event = { 'target' : target, 'types' : {} };
				new_target_event.types[type] = [cb];
				this.collection.push(new_target_event);
			}

			target[type] = api.alarm;
		},
		fire : function(event, ie_current_target) {

			event = event || window.event;
			var data = _dom.generate_data(event);
			var target_events = _dom.find_events_by_target(event.currentTarget || ie_current_target);

			if (!target_events) return false;

			var callbacks = target_events.types[data.type];
			if (!callbacks) return false;

			for (var i = 0, len = callbacks.length; i < len; i++) callbacks[i](data);
		},
		remove : function(target, type, cb) {
			var collection = this.collection;
			var match = true;
			if (!type) {
				for (var i = 0, len = collection.length; i < len; i++) {
					if (collection[i].target === target) {
						this.collection.remove(collection[i]);
						match = true;
					}
				}
			}
			else if (!cb) {
				for (var i = 0, len = collection.length; i < len; i++) {
					if (collection[i].target === target) {
						if (collection[i].types[type]) {
							delete collection[i].types[type];
							match = true;
						}
					}
				}
			}
			else {
				for (var i = 0, len = collection.length; i < len; i++) {
					if (collection[i].target === target) {
						if (collection[i].types[type].indexOf(cb) > -1) {
							collection[i].types[type].remove(cb);
							match = true;
						}
					}
				}
			}
			return match;
		},
		generate_data : function(event) {
			var custom_event = { 'dom' : event };
			custom_event['target'] = event.target || event.srcElement;
			custom_event['type'] = _util.format_type(event.type);
			custom_event['preventDefault'] = (event.preventDefault) ? function() { event.preventDefault(); } : function() { event.returnValue = false };
   			custom_event['x'] = event.pageX || event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    	    custom_event['y'] = event.pageY || event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
			return custom_event;
		},
		find_events_by_target : function(target) {
			var collection = this.collection;
			for (var i = 0, len = collection.length; i < len; i++) {
    			var set = collection[i];
    			if (set.target === target) return set;
			}
		}
	}

	_persistent = {
		collection : [],
		add : function(query, type, cb) {

			type = _util.format_type(type);

			var existing_query = this.collection[query];
			if (existing_query) {
				(existing_query[type]) ? existing_query[type].push(cb) : existing_query.types[type] = [cb];
			}
			else {
				var new_persistent_event = { 'query' : query, 'types' : {} }
				new_persistent_event.types[type] = [cb];
				this.collection.push(new_persistent_event);
			}

			var current_set = raptor.hunt(query);
			api.lash(current_set, type, cb);
		},
		remove : function(query, type, cb) {
			var collection = this.collection;
			var match = false;
			if (!type) {
				for (var i in collection) {
					if (collection[i].query === query) {
						this.collection.remove(i);
						match = true;
					}
				}
			}
			else if (!cb) {
				for (var i in collection) {
					if (collection[i].query === query) {
						if (collection[i].types[type]) {
							delete collection[i].types[type];
							match = true;
						}
					}
				}
			}
			else {
				for (var i in collection) {
					if (collection[i].query === query) {
						if (collection[i].types[type].indexOf(cb) > -1) {
							collection[i].types[type].remove(cb);
							match = true;
						}
					}
				}
			}
			return match;
		}
	}

	_custom = {
		collection : {},

		/**
        * @param {String} Name of custom event
        * @param {Function} Callback to run
        * @param {Integer} Number of fires required to execute cb
        */
		add : function(name, cb, count) {
			var collection = this.collection;
			var match = false;

			if (count) {
			    var old_cb = cb;

			    cb = function(e) {
                    this.fire_count = this.fire_count || 0;
                    this.fire_count++;

                    if (this.fire_count === count) old_cb(e);
			    }
			}

			for (var i in collection) {
				if (i === name) {
					match = true;
					this.collection[name].push(cb);
				}
			}
			if (!match) this.collection[name] = [cb];
		},
		fire : function(name, data) {
			var collection = this.collection;
			for (var i in collection) {
				if (i === name) {
					var events = collection[i];
					for (var i = 0, len = events.length; i < len; i++) events[i](data);
				}
			}
		},
		remove : function(name, cb) {
			if (!this.collection[name]) return false;
			if (!cb) delete this.collection[name];
			else this.collection[name].remove(cb);
			return true;
		}
	}

	api = {

        /**
		* Queue up methods to run when the document is ready
		*
		* @param {Function} Callback
		*/
		ready : function (fn) {

			if (this.loaded) {
				fn();
				return;
			}

			raptor.lash(document, 'DOMContentLoaded', fn);

			if (document.readyState) {
				if (!timer) {
					var timer = setInterval(function() {
						if (document.readyState === 'complete') {
							if (!api.loaded) {
								api.loaded = true;
								clearInterval(timer);
								timer = null;
								api.alarm({'currentTarget' : document, 'type' : 'DOMContentLoaded'});
							}
						}
					}, 10);
				}
			}
		},

		lash : function(target, type, cb) {
			if (cb) {
				if (typeof target === 'string') {
					if (typeof cb === 'function') _persistent.add(target, type, cb);
					else _custom.add(target, type, cb);
				}
				else {
					if (raptor.type('Array', target)) {
						for (var i = 0, len = target.length; i < len; i++) _dom.add(target[i], type, cb);
					}
					else _dom.add(target, type, cb);
				}
			}
			else _custom.add(target, type);
		},

		unlash : function(target, type, cb) {
			if (cb) {
				(typeof target === 'string') ? _persistent.remove(target, type, cb) : _dom.remove(target, type, cb);
			}
			else {
				if (_custom.remove(target, type)) return;
				if (_persistent.remove(target, type)) return;
				if (_dom.remove(target, type)) return;
			}
		},

		alarm : function(target, data) {
			if (typeof target === 'string') _custom.fire(target, data);
			else _dom.fire(target, this);
		},

		scan_for_life : function(el) {

			var _apply = function(test_el, persistent_event) {
				var types = persistent_event.types;
				for (var type in types) {
					var callbacks = types[type];
					for (var i = 0, len = callbacks.length; i < len; i++) {
						api.lash(test_el, type, callbacks[i]);
					}
				}
			}

			var _test = function(test_el) {
				for (var i = 0, len = persistent_events.length; i < len; i++) {
					var persistent_event = persistent_events[i];
					if (raptor.hunt(persistent_event.query).indexOf(test_el) > -1) _apply(test_el, persistent_event);
				}
			}

			var persistent_events = _persistent.collection;

			_test(el);

			var children = el.getElementsByTagName('*');
			for (var i = 0, len = children.length; i < len; i++) _test(children[i]);
		}
	}

	if (raptor) raptor.extend(api);
})();
<commit_msg>formating type for remove<commit_after>(function() {

	// private
	var _dom, _persistant, _custom , _util;

	// public
	var api;

	// utility functions for event management
	_util = {
		format_type : function(type) {
			if (!type) return false;
 			return (type === 'DOMContentLoaded' || /^on/.test(type)) ? type : 'on' + type;
		}
	};

	_dom = {
		collection : [],
		add : function(target, type, cb) {

			type = _util.format_type(type);

			var target_events = this.find_events_by_target(target);
			if (target_events) {
				(target_events.types[type]) ? target_events.types[type].push(cb) : target_events.types[type] = [cb];
			}
			else {
				var new_target_event = { 'target' : target, 'types' : {} };
				new_target_event.types[type] = [cb];
				this.collection.push(new_target_event);
			}

			target[type] = api.alarm;
		},
		fire : function(event, ie_current_target) {

			event = event || window.event;
			var data = _dom.generate_data(event);
			var target_events = _dom.find_events_by_target(event.currentTarget || ie_current_target);

			if (!target_events) return false;

			var callbacks = target_events.types[data.type];
			if (!callbacks) return false;

			for (var i = 0, len = callbacks.length; i < len; i++) callbacks[i](data);
		},
		remove : function(target, type, cb) {
			type = _util.format_type(type);
			var collection = this.collection;
			var match = true;
			if (!type) {
				for (var i = 0, len = collection.length; i < len; i++) {
					if (collection[i].target === target) {
						this.collection.remove(collection[i]);
						match = true;
					}
				}
			}
			else if (!cb) {
				for (var i = 0, len = collection.length; i < len; i++) {
					if (collection[i].target === target) {
						if (collection[i].types[type]) {
							delete collection[i].types[type];
							match = true;
						}
					}
				}
			}
			else {
				for (var i = 0, len = collection.length; i < len; i++) {
					if (collection[i].target === target) {
						if (collection[i].types[type].indexOf(cb) > -1) {
							collection[i].types[type].remove(cb);
							match = true;
						}
					}
				}
			}
			return match;
		},
		generate_data : function(event) {
			var custom_event = { 'dom' : event };
			custom_event['target'] = event.target || event.srcElement;
			custom_event['type'] = _util.format_type(event.type);
			custom_event['preventDefault'] = (event.preventDefault) ? function() { event.preventDefault(); } : function() { event.returnValue = false };
   			custom_event['x'] = event.pageX || event.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
    	    custom_event['y'] = event.pageY || event.clientY + document.body.scrollTop + document.documentElement.scrollTop;
			return custom_event;
		},
		find_events_by_target : function(target) {
			var collection = this.collection;
			for (var i = 0, len = collection.length; i < len; i++) {
    			var set = collection[i];
    			if (set.target === target) return set;
			}
		}
	}

	_persistent = {
		collection : [],
		add : function(query, type, cb) {

			type = _util.format_type(type);

			var existing_query = this.collection[query];
			if (existing_query) {
				(existing_query[type]) ? existing_query[type].push(cb) : existing_query.types[type] = [cb];
			}
			else {
				var new_persistent_event = { 'query' : query, 'types' : {} }
				new_persistent_event.types[type] = [cb];
				this.collection.push(new_persistent_event);
			}

			var current_set = raptor.hunt(query);
			api.lash(current_set, type, cb);
		},
		remove : function(query, type, cb) {
			var collection = this.collection;
			var match = false;
			if (!type) {
				for (var i in collection) {
					if (collection[i].query === query) {
						this.collection.remove(i);
						match = true;
					}
				}
			}
			else if (!cb) {
				for (var i in collection) {
					if (collection[i].query === query) {
						if (collection[i].types[type]) {
							delete collection[i].types[type];
							match = true;
						}
					}
				}
			}
			else {
				for (var i in collection) {
					if (collection[i].query === query) {
						if (collection[i].types[type].indexOf(cb) > -1) {
							collection[i].types[type].remove(cb);
							match = true;
						}
					}
				}
			}
			return match;
		}
	}

	_custom = {
		collection : {},

		/**
        * @param {String} Name of custom event
        * @param {Function} Callback to run
        * @param {Integer} Number of fires required to execute cb
        */
		add : function(name, cb, count) {
			var collection = this.collection;
			var match = false;

			if (count) {
			    var old_cb = cb;

			    cb = function(e) {
                    this.fire_count = this.fire_count || 0;
                    this.fire_count++;

                    if (this.fire_count === count) old_cb(e);
			    }
			}

			for (var i in collection) {
				if (i === name) {
					match = true;
					this.collection[name].push(cb);
				}
			}
			if (!match) this.collection[name] = [cb];
		},
		fire : function(name, data) {
			var collection = this.collection;
			for (var i in collection) {
				if (i === name) {
					var events = collection[i];
					for (var i = 0, len = events.length; i < len; i++) events[i](data);
				}
			}
		},
		remove : function(name, cb) {
			if (!this.collection[name]) return false;
			if (!cb) delete this.collection[name];
			else this.collection[name].remove(cb);
			return true;
		}
	}

	api = {

        /**
		* Queue up methods to run when the document is ready
		*
		* @param {Function} Callback
		*/
		ready : function (fn) {

			if (this.loaded) {
				fn();
				return;
			}

			raptor.lash(document, 'DOMContentLoaded', fn);

			if (document.readyState) {
				if (!timer) {
					var timer = setInterval(function() {
						if (document.readyState === 'complete') {
							if (!api.loaded) {
								api.loaded = true;
								clearInterval(timer);
								timer = null;
								api.alarm({'currentTarget' : document, 'type' : 'DOMContentLoaded'});
							}
						}
					}, 10);
				}
			}
		},

		lash : function(target, type, cb) {
			if (cb) {
				if (typeof target === 'string') {
					if (typeof cb === 'function') _persistent.add(target, type, cb);
					else _custom.add(target, type, cb);
				}
				else {
					if (raptor.type('Array', target)) {
						for (var i = 0, len = target.length; i < len; i++) _dom.add(target[i], type, cb);
					}
					else _dom.add(target, type, cb);
				}
			}
			else _custom.add(target, type);
		},

		unlash : function(target, type, cb) {
			if (cb) {
				(typeof target === 'string') ? _persistent.remove(target, type, cb) : _dom.remove(target, type, cb);
			}
			else {
				if (_custom.remove(target, type)) return;
				if (_persistent.remove(target, type)) return;
				if (_dom.remove(target, type)) return;
			}
		},

		alarm : function(target, data) {
			if (typeof target === 'string') _custom.fire(target, data);
			else _dom.fire(target, this);
		},

		scan_for_life : function(el) {

			var _apply = function(test_el, persistent_event) {
				var types = persistent_event.types;
				for (var type in types) {
					var callbacks = types[type];
					for (var i = 0, len = callbacks.length; i < len; i++) {
						api.lash(test_el, type, callbacks[i]);
					}
				}
			}

			var _test = function(test_el) {
				for (var i = 0, len = persistent_events.length; i < len; i++) {
					var persistent_event = persistent_events[i];
					if (raptor.hunt(persistent_event.query).indexOf(test_el) > -1) _apply(test_el, persistent_event);
				}
			}

			var persistent_events = _persistent.collection;

			_test(el);

			var children = el.getElementsByTagName('*');
			for (var i = 0, len = children.length; i < len; i++) _test(children[i]);
		}
	}

	if (raptor) raptor.extend(api);
})();
<|endoftext|>


<commit_before>/**
 *  class CssoCompressor
 *
 *  Engine for CSS minification. You will need `csso` Node module installed:
 *
 *      npm install csso
 *
 *
 *  ##### SUBCLASS OF
 *
 *  [[Template]]
 **/

'use strict';

// 3rd-party
var csso; // initialized later

// internal
var Template = require('../template');
var prop     = require('../common').prop;

////////////////////////////////////////////////////////////////////////////////

// Class constructor
var CssoCompressor = module.exports = function CssoCompressor() {
  Template.apply(this, arguments);
  csso = csso || Template.libs.csso || require('csso');
};

require('util').inherits(CssoCompressor, Template);

// Compress data
CssoCompressor.prototype.evaluate = function (/*context, locals*/) {
  this.data = csso.justDoIt(this.data);
};

// Expose default MimeType of an engine
prop(CssoCompressor, 'defaultMimeType', 'text/css');
<commit_msg>Fix CSSO 2.+ compatibility, close #229<commit_after>/**
 *  class CssoCompressor
 *
 *  Engine for CSS minification. You will need `csso` Node module installed:
 *
 *      npm install csso
 *
 *
 *  ##### SUBCLASS OF
 *
 *  [[Template]]
 **/

'use strict';

// 3rd-party
var csso; // initialized later

// internal
var Template = require('../template');
var prop     = require('../common').prop;

////////////////////////////////////////////////////////////////////////////////

// Class constructor
var CssoCompressor = module.exports = function CssoCompressor() {
  Template.apply(this, arguments);
  csso = csso || Template.libs.csso || require('csso');
};

require('util').inherits(CssoCompressor, Template);

// Compress data
CssoCompressor.prototype.evaluate = function (/*context, locals*/) {
  // CSSO 2.+ renamed .justDoIt() -> .minify()
  this.data = csso.minify ? csso.minify(this.data) : csso.justDoIt(this.data);
};

// Expose default MimeType of an engine
prop(CssoCompressor, 'defaultMimeType', 'text/css');
<|endoftext|>


<commit_before>/*
Language: SQL
Contributors: neor-ru <info@neor.ru>, Heiko August <post@auge8472.de>
 */

function(hljs) {
  return {
    case_insensitive: true,
    illegal: /[<>]/,
    contains: [
      {
        className: 'operator',
        beginKeywords: 'begin end start commit rollback savepoint lock alter create drop rename call '+
          'delete do handler insert load replace select truncate update set show pragma grant '+
          'merge describe use explain help declare prepare execute deallocate savepoint release '+
          'unlock purge reset change stop analyze cache flush optimize repair kill '+
          'install uninstall checksum restore check backup',
        end: /;/, endsWithParent: true,
        keywords: 'all partial global month current_timestamp using go revoke smallint ' +
          'indicator end-exec disconnect zone with character assertion to add current_user ' +
          'usage input local alter match collate real then rollback get read timestamp ' +
          'session_user not integer bit unique day minute desc insert execute like ilike ' +
          'level decimal drop continue isolation found where constraints domain right ' +
          'national some module transaction relative second connect escape close system_user ' +
          'for deferred section cast current sqlstate allocate intersect deallocate numeric ' +
          'public preserve full goto initially asc no key output collation group by union ' +
          'session both last language constraint column of space foreign deferrable prior ' +
          'connection unknown action commit view or first into float year primary cascaded ' +
          'except restrict set references names table outer open select size are rows from ' +
          'prepare distinct leading create only next inner authorization schema ' +
          'corresponding option declare precision immediate else timezone_minute external ' +
          'varying translation true case exception join hour default double scroll value ' +
          'cursor descriptor values dec fetch procedure delete and false int is describe ' +
          'char as at in varchar null trailing any absolute current_time end grant ' +
          'privileges when cross check write current_date pad begin temporary exec time ' +
          'update catalog user sql date on identity timezone_hour natural whenever interval ' +
          'work order cascade diagnostics nchar having left call do handler load replace ' +
          'truncate start lock show pragma exists number trigger if before after each row ' +
          'merge matched database limit nvarchar use explain help processlist function return returns ' +
          'concat status declare rename event index logfile server tablespace xml infile lines ' +
          'fields columns tables table ignore partition terminated enclosed escaped identified ' +
          'data concurrent low_priority high_priority starting delayed distinctrow rollup ' +
          'dumpfile share mode straight_join sql_small_result sql_big_result sql_buffer_result ' +
          'sql_cache sql_no_cache sql_calc_found_rows outfile optionally force repeat ' +
          'consistent snapshot chain release savepoint unlock serializable binary purge reset ' +
          'change stop binary logs master slave relaylog binlog events hosts password old_password ' +
          'analyze cache flush optimize repair kill install uninstall plugin query ' +
          'errors warnings checksum authors contributors des_key_file user_resources leaves ' +
          'restore check backup no_write_to_binlog upgrade quick fast medium extended changed ' +
          'databases engine engines grants innodb mutex profile profiles triggers variables ' +
          'string aggregate soname between regexp ' +
          'abs acos adddate addtime aes_decrypt aes_encrypt ascii asin atan atan2 atn2 ' +
          'avg benchmark bin binary bit_and bit_count bit_length bit_or bit_xor case ceil ceiling ' +
          'char char_length character_length charindex charset checksum_agg choose coalesce coercibility ' +
          'collation collationproperty columns_updated compress concat concat_ws connection_id conv convert convert_tz ' +
          'cos cot count count_big crc32 cume_dist curdate current_date current_time current_timestamp current_user ' +
          'curtime database datalength date date_add date_format date_sub dateadd datediff datefromparts datename ' +
          'datepart datetime2fromparts datetimeoffsetfromparts day dayname dayofmonth dayofweek dayofyear ' +
          'decode default degrees des_decrypt des_encrypt difference div elt encode encrypt eomonth eventdata ' +
          'exp export_set extract field find_in_set first_value floor format format found_rows from_base64 from_days ' +
          'from_unixtime get_format get_lock getdate getutcdate greatest group_concat grouping grouping_id gtid_subset ' +
          'gtid_subtract hex hour ident_current ident_incr ident_seed if ifnull iif in inet6_aton inet6_ntoa inet_aton ' +
          'inet_ntoa insert instr interval is is_free_lock is_ipv4 is_ipv4_compat is_ipv4_mapped is_not ' +
          'is_not_null is_used_lock isdate isnull last_day last_insert_id last_value lcase lead least left len lenght ' +
          'like ln load_file localtime localtimestamp locate log log10 log2 lower lpad ltrim ' +
          'make_set makedate maketime master_pos_wait match max md5 microsecond mid min minute mod month monthname ' +
          'name_const now nullif oct octet_length old_password ord parse password patindex percent_rank percentile_cont ' +
          'percentile_disc period_add period_diff pi position pow power procedure_analyze publishingservername ' +
          'quarter quote quotename radians radians rand release_lock repeat replace replicate reverse right ' +
          'rlike round row_count rpad rtrim schema sec_to_time second session_user sha sha1 sha2 sign ' +
          'sin sleep smalldatetimefromparts soundex sounds_like space sql_variant_property sqrt ' +
          'square std stddev stddev_pop stddev_samp stdev stdevp str str_to_date strcmp stuff subdate substr ' +
          'substring subtime subtring_index sum switchoffset sysdate sysdatetime sysdatetimeoffset ' +
          'system_user sysutcdatetime tan tan tertiary_weights time time_format time_to_sec timediff ' +
          'timefromparts timestamp timestampadd timestampdiff to_base64 to_days to_seconds todatetimeoffset ' +
          'trigger_nestlevel trim truncate try_cast try_convert try_parse ucase uncompress uncompressed_length ' +
          'unhex unicode unix_timestamp upped upper user utc_date utc_time utc_timestamp uuid uuid_short ' +
          'validate_password_strength values var var_pop var_samp variance varp version week weekday ' +
          'weekofyear weight_string xor year yearweek',
        contains: [
          {
            className: 'string',
            begin: '\'', end: '\'',
            contains: [hljs.BACKSLASH_ESCAPE, {begin: '\'\''}]
          },
          {
            className: 'string',
            begin: '"', end: '"',
            contains: [hljs.BACKSLASH_ESCAPE, {begin: '""'}]
          },
          {
            className: 'string',
            begin: '`', end: '`',
            contains: [hljs.BACKSLASH_ESCAPE]
          },
          hljs.C_BLOCK_COMMENT_MODE,
          hljs.C_NUMBER_MODE
        ]
      },
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: 'comment',
        begin: '--', end: '$'
      }
    ]
  };
}
<commit_msg>Unique and order SQL keywords<commit_after>/*
Language: SQL
Contributors: neor-ru <info@neor.ru>, Heiko August <post@auge8472.de>
 */

function(hljs) {
  return {
    case_insensitive: true,
    illegal: /[<>]/,
    contains: [
      {
        className: 'operator',
        beginKeywords:
          'begin end start commit rollback savepoint lock alter create drop rename call '+
          'delete do handler insert load replace select truncate update set show pragma grant '+
          'merge describe use explain help declare prepare execute deallocate savepoint release '+
          'unlock purge reset change stop analyze cache flush optimize repair kill '+
          'install uninstall checksum restore check backup',
        end: /;/, endsWithParent: true,
        keywords:
          'abs absolute acos action add adddate addtime aes_decrypt aes_encrypt after aggregate all allocate alter ' +
          'analyze and any are as asc ascii asin assertion at atan atan2 atn2 authorization authors avg backup ' +
          'before begin benchmark between bin binary binlog bit bit_and bit_count bit_length bit_or bit_xor both by ' +
          'cache call cascade cascaded case cast catalog ceil ceiling chain change changed char char_length ' +
          'character character_length charindex charset check checksum checksum_agg choose close coalesce ' +
          'coercibility collate collation collationproperty column columns columns_updated commit compress concat ' +
          'concat_ws concurrent connect connection connection_id consistent constraint constraints continue ' +
          'contributors conv convert convert_tz corresponding cos cot count count_big crc32 create cross cume_dist ' +
          'curdate current current_date current_time current_timestamp current_user cursor curtime data database ' +
          'databases datalength date date_add date_format date_sub dateadd datediff datefromparts datename ' +
          'datepart datetime2fromparts datetimeoffsetfromparts day dayname dayofmonth dayofweek dayofyear ' +
          'deallocate dec decimal declare decode default deferrable deferred degrees delayed delete des_decrypt ' +
          'des_encrypt des_key_file desc describe descriptor diagnostics difference disconnect distinct ' +
          'distinctrow div do domain double drop dumpfile each else elt enclosed encode encrypt end end-exec ' +
          'engine engines eomonth errors escape escaped event eventdata events except exception exec execute ' +
          'exists exp explain export_set extended external extract false fast fetch field fields find_in_set ' +
          'first first_value float floor flush for force foreign format found found_rows from from_base64 ' +
          'from_days from_unixtime full function get get_format get_lock getdate getutcdate global go goto grant ' +
          'grants greatest group group_concat grouping grouping_id gtid_subset gtid_subtract handler having help ' +
          'hex high_priority hosts hour ident_current ident_incr ident_seed identified identity if ifnull ignore ' +
          'iif ilike immediate in index indicator inet6_aton inet6_ntoa inet_aton inet_ntoa infile initially inner ' +
          'innodb input insert install instr int integer intersect interval into is is_free_lock is_ipv4 ' +
          'is_ipv4_compat is_ipv4_mapped is_not is_not_null is_used_lock isdate isnull isolation join key kill ' +
          'language last last_day last_insert_id last_value lcase lead leading least leaves left len lenght level ' +
          'like limit lines ln load load_file local localtime localtimestamp locate lock log log10 log2 logfile ' +
          'logs low_priority lower lpad ltrim make_set makedate maketime master master_pos_wait match matched max ' +
          'md5 medium merge microsecond mid min minute mod mode module month monthname mutex name_const names ' +
          'national natural nchar next no no_write_to_binlog not now null nullif number numeric nvarchar oct ' +
          'octet_length of old_password on only open optimize option optionally or ord order outer outfile output ' +
          'pad parse partial partition password patindex percent_rank percentile_cont percentile_disc period_add ' +
          'period_diff pi plugin position pow power pragma precision prepare preserve primary prior privileges ' +
          'procedure procedure_analyze processlist profile profiles public publishingservername purge quarter ' +
          'query quick quote quotename radians rand read real references regexp relative relaylog release ' +
          'release_lock rename repair repeat replace replicate reset restore restrict return returns reverse ' +
          'revoke right rlike rollback rollup round row row_count rows rpad rtrim savepoint schema scroll ' +
          'sec_to_time second section select serializable server session session_user set sha sha1 sha2 share ' +
          'show sign sin size slave sleep smalldatetimefromparts smallint snapshot some soname soundex ' +
          'sounds_like space sql sql_big_result sql_buffer_result sql_cache sql_calc_found_rows sql_no_cache ' +
          'sql_small_result sql_variant_property sqlstate sqrt square start starting status std ' +
          'stddev stddev_pop stddev_samp stdev stdevp stop str str_to_date straight_join strcmp string stuff ' +
          'subdate substr substring subtime subtring_index sum switchoffset sysdate sysdatetime sysdatetimeoffset ' +
          'system_user sysutcdatetime table tables tablespace tan temporary terminated tertiary_weights then time ' +
          'time_format time_to_sec timediff timefromparts timestamp timestampadd timestampdiff timezone_hour ' +
          'timezone_minute to to_base64 to_days to_seconds todatetimeoffset trailing transaction translation ' +
          'trigger trigger_nestlevel triggers trim true truncate try_cast try_convert try_parse ucase uncompress ' +
          'uncompressed_length unhex unicode uninstall union unique unix_timestamp unknown unlock update upgrade ' +
          'upped upper usage use user user_resources using utc_date utc_time utc_timestamp uuid uuid_short ' +
          'validate_password_strength value values var var_pop var_samp varchar variables variance varp varying ' +
          'version view warnings week weekday weekofyear weight_string when whenever where with work write xml ' +
          'xor year yearweek zon',
        contains: [
          {
            className: 'string',
            begin: '\'', end: '\'',
            contains: [hljs.BACKSLASH_ESCAPE, {begin: '\'\''}]
          },
          {
            className: 'string',
            begin: '"', end: '"',
            contains: [hljs.BACKSLASH_ESCAPE, {begin: '""'}]
          },
          {
            className: 'string',
            begin: '`', end: '`',
            contains: [hljs.BACKSLASH_ESCAPE]
          },
          hljs.C_BLOCK_COMMENT_MODE,
          hljs.C_NUMBER_MODE
        ]
      },
      hljs.C_BLOCK_COMMENT_MODE,
      {
        className: 'comment',
        begin: '--', end: '$'
      }
    ]
  };
}
<|endoftext|>


<commit_before>const test = require('tape')
const models = require('./index')
const rootBus = require('minibus').create()

test('bus', t => {
  const busFactory = models.bus(rootBus, (obj, ev) => {
    return obj.foo === ev.baz && ev.baz === 'bar'
  })

  const obj = {
    foo: 'bar'
  }

  const bus = busFactory(obj)

  let calls = 0
  bus.on('test-event', function (ev) {
    calls += 1
  })

  // Send three test events. Only two should pass the test.
  rootBus.emit('test-event', {
    baz: 'bar'
  })
  rootBus.emit('test-event', {
    baz: '666'
  })
  rootBus.emit('test-event', {
    baz: 'bar'
  })
  // Fourth event with correct ev but wrong event name
  rootBus.emit('other-event', {
    baz: 'bar'
  })

  t.equal(calls, 2, 'number of calls')
  t.end()
})
<commit_msg>Repair tests<commit_after>const test = require('tape')
const models = require('./index')
const rootBus = require('minibus').create()

test('bus', t => {
  const busFactory = models.bus((obj, ev) => {
    return obj.foo === ev.baz && ev.baz === 'bar'
  })

  const obj = {
    foo: 'bar'
  }

  const bus = busFactory(obj, rootBus)

  let calls = 0
  bus.on('test-event', function (ev) {
    calls += 1
  })

  // Send three test events. Only two should pass the test.
  rootBus.emit('test-event', {
    baz: 'bar'
  })
  rootBus.emit('test-event', {
    baz: '666'
  })
  rootBus.emit('test-event', {
    baz: 'bar'
  })
  // Fourth event with correct ev but wrong event name
  rootBus.emit('other-event', {
    baz: 'bar'
  })

  t.equal(calls, 2, 'number of calls')
  t.end()
})
<|endoftext|>


<commit_before>var pk = pk || {};
(function(pk) {
    pk.rating = function(opt) {
        var el = opt.element,
            listeners = opt.listeners === undefined ? {} : opt.listeners,
            inputValue = opt.value || el.getAttribute('value') || 0,
            inputDisabled = (opt.disabled || el.getAttribute('disabled')) ? 'disabled' : '',
            inputName = opt.name || el.getAttribute('name') || 'pk-rating-' + pk.getRand(1, 999),
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0;

        /*jshint multistr:true */
        var str = "
\
            <fieldset>\
                <input type='radio' id='" + inputName + "_5' name='" + inputName + "' value='5' tabindex='" + inputTabIndex + "'/>\
                \
                <input type='radio' id='" + inputName + "_4' name='" + inputName + "' value='4' />\
                \
                <input type='radio' id='" + inputName + "_3' name='" + inputName + "' value='3' />\
                \
                <input type='radio' id='" + inputName + "_2' name='" + inputName + "' value='2' />\
                \
                <input type='radio' id='" + inputName + "_1' name='" + inputName + "' value='1' />\
                \
            </fieldset>\

";
        el = pk.replaceEl(el, str);

        var rEl = [];
        rEl.push(el.children[0].children[8]);
        rEl.push(el.children[0].children[6]);
        rEl.push(el.children[0].children[4]);
        rEl.push(el.children[0].children[2]);
        rEl.push(el.children[0].children[0]);
        pk.bindListeners(listeners, rEl[0]);
        pk.bindListeners(listeners, rEl[1]);
        pk.bindListeners(listeners, rEl[2]);
        pk.bindListeners(listeners, rEl[3]);
        pk.bindListeners(listeners, rEl[4]);

        pk.bindEvent("mousewheel", el, function(e) {
            pk.preventBubble(e);
            var offset = 1;
            if (e.wheelDelta > 0 || e.detail < 0) {
                offset = -1;
            }
            obj.val(obj.val() + offset);
        });

        var obj = {
            0: el,
            val: function(val) {
                if (val === undefined) {
                    for (var r in rEl) {
                        if (rEl[r].checked) {
                            val = rEl[r].value;
                            break;
                        }
                    }
                    return parseInt(val === undefined ? 0 : val, 0);
                }
                val = val < 0 ? 0 : val;
                val = val > 5 ? 5 : val;
                if (val === 0) {
                    rEl[0].checked = true;
                    rEl[0].checked = false;
                } else {
                    rEl[val - 1].checked = true;
                }
            },
            disabled: function(val) {
                if (val !== undefined) {
                    pk.toggleClass(el, 'pk-disabled', val);
                    for (var r in rEl) {
                        pk.attribute(rEl[r], 'disabled', val);
                    }
                }
                return pk.attribute(rEl[0], 'disabled');
            }
        };
        obj.val(inputValue);
        if (inputDisabled) {
            obj.disabled(true);
        }
        return obj;
    };
    return pk;
})(pk);
<commit_msg>Update rating.js<commit_after>var pk = pk || {};
(function(pk) {
    pk.rating = function(opt) {
        var el = opt.element,
            listeners = opt.listeners === undefined ? {} : opt.listeners,
            inputValue = opt.value || el.getAttribute('value') || 0,
            inputDisabled = (opt.disabled || el.getAttribute('disabled')) ? 'disabled' : '',
            inputName = opt.name || el.getAttribute('name') || 'pk-rating-' + pk.getRand(1, 999),
            inputTabIndex = opt.tabindex || el.getAttribute('tabindex') || 0,
            lastVal = inputValue;

        /*jshint multistr:true */
        var str = "
\
            <fieldset>\
                <input type='radio' id='" + inputName + "_5' name='" + inputName + "' value='5' tabindex='" + inputTabIndex + "'/>\
                \
                <input type='radio' id='" + inputName + "_4' name='" + inputName + "' value='4' />\
                \
                <input type='radio' id='" + inputName + "_3' name='" + inputName + "' value='3' />\
                \
                <input type='radio' id='" + inputName + "_2' name='" + inputName + "' value='2' />\
                \
                <input type='radio' id='" + inputName + "_1' name='" + inputName + "' value='1' />\
                \
            </fieldset>\

";
        el = pk.replaceEl(el, str);

        var rEl = [];
        rEl.push(el.children[0].children[8]);
        rEl.push(el.children[0].children[6]);
        rEl.push(el.children[0].children[4]);
        rEl.push(el.children[0].children[2]);
        rEl.push(el.children[0].children[0]);
        pk.bindListeners(listeners, rEl[0]);
        pk.bindListeners(listeners, rEl[1]);
        pk.bindListeners(listeners, rEl[2]);
        pk.bindListeners(listeners, rEl[3]);
        pk.bindListeners(listeners, rEl[4]);

        pk.bindEvent("mousewheel", el, function(e) {
            pk.preventBubble(e);
            var offset = 1;
            if (e.wheelDelta > 0 || e.detail < 0) {
                offset = -1;
            }
            obj.val(obj.val() + offset);
        });

        function clickHandler(e) {
            if (lastVal === obj.val()) {
                obj.val(obj.val() - 1);
            }
            lastVal = obj.val();
        }
        for (var i = 0; i < rEl.length; i++) {
            pk.bindEvent('click', rEl[i], clickHandler);
        }
        var obj = {
            0: el,
            val: function(val) {
                if (val === undefined) {
                    for (var r in rEl) {
                        if (rEl[r].checked) {
                            val = rEl[r].value;
                            break;
                        }
                    }
                    return parseInt(val === undefined ? 0 : val, 0);
                }
                val = val < 0 ? 0 : val;
                val = val > 5 ? 5 : val;
                if (val === 0) {
                    rEl[0].checked = true;
                    rEl[0].checked = false;
                } else {
                    rEl[val - 1].checked = true;
                }
                lastVal = val;
            },
            disabled: function(val) {
                if (val !== undefined) {
                    pk.toggleClass(el, 'pk-disabled', val);
                    for (var r in rEl) {
                        pk.attribute(rEl[r], 'disabled', val);
                    }
                }
                return pk.attribute(rEl[0], 'disabled');
            }
        };
        obj.val(inputValue);
        if (inputDisabled) {
            obj.disabled(true);
        }
        return obj;
    };
    return pk;
})(pk);
<|endoftext|>


<commit_before><commit_msg>indent, add namespace to unreachable keyword<commit_after><|endoftext|>


<commit_before><commit_msg>Fix issue with removing multilingual name entries<commit_after><|endoftext|>