<commit_before>'use strict';

var $ = require('jquery');

var Selectivity = require('./selectivity-base');

function replaceSelectElement($el, options) {

    var value = (options.multiple ? [] : null);

    var mapOptions = function() {
        var $this = $(this);
        if ($this.is('option')) {
            var id = $this.attr('value') || $this.text();
            if ($this.prop('selected')) {
                if (options.multiple) {
                    value.push(id);
                } else {
                    value = id;
                }
            }

            return {
                id: id,
                text: $this.attr('label') || $this.text()
            };
        } else {
            return {
                text: $this.attr('label'),
                children: $this.children('option,optgroup').map(mapOptions).get()
            };
        }
    };

    options.allowClear = ('allowClear' in options ? options.allowClear : !$el.prop('required'));

    options.items = $el.children('option,optgroup').map(mapOptions).get();

    options.placeholder = options.placeholder || $el.data('placeholder') || '';

    options.value = value;

    var $div = $('<div>').attr({
        'id': $el.attr('id'),
        'class': $el.attr('class'),
        'style': $el.attr('style'),
        'data-name': $el.attr('name')
    });
    $el.replaceWith($div);
    return $div;
}

/**
 * Option listener providing support for converting traditional <select> boxes into Selectivity
 * instances.
 */
Selectivity.OptionListeners.push(function(selectivity, options) {

    var $el = selectivity.$el;
    if ($el.is('select')) {
        if ($el.attr('autofocus')) {
            setTimeout(function() {
                selectivity.focus();
            }, 1);
        }

        selectivity.$el = replaceSelectElement($el, options);
        selectivity.$el[0].selectivity = selectivity;
    }
});
<commit_msg>Assure traditional <select> has selectivity-input class<commit_after>'use strict';

var $ = require('jquery');

var Selectivity = require('./selectivity-base');

function replaceSelectElement($el, options) {

    var value = (options.multiple ? [] : null);

    var mapOptions = function() {
        var $this = $(this);
        if ($this.is('option')) {
            var id = $this.attr('value') || $this.text();
            if ($this.prop('selected')) {
                if (options.multiple) {
                    value.push(id);
                } else {
                    value = id;
                }
            }

            return {
                id: id,
                text: $this.attr('label') || $this.text()
            };
        } else {
            return {
                text: $this.attr('label'),
                children: $this.children('option,optgroup').map(mapOptions).get()
            };
        }
    };

    options.allowClear = ('allowClear' in options ? options.allowClear : !$el.prop('required'));

    options.items = $el.children('option,optgroup').map(mapOptions).get();

    options.placeholder = options.placeholder || $el.data('placeholder') || '';

    options.value = value;

    var classes = ($el.attr('class') || 'selectivity-input').split(' ');
    if (classes.indexOf('selectivity-input') === -1) {
        classes.push('selectivity-input');
    }

    var $div = $('<div>').attr({
        'id': $el.attr('id'),
        'class': classes.join(' '),
        'style': $el.attr('style'),
        'data-name': $el.attr('name')
    });
    $el.replaceWith($div);
    return $div;
}

/**
 * Option listener providing support for converting traditional <select> boxes into Selectivity
 * instances.
 */
Selectivity.OptionListeners.push(function(selectivity, options) {

    var $el = selectivity.$el;
    if ($el.is('select')) {
        if ($el.attr('autofocus')) {
            setTimeout(function() {
                selectivity.focus();
            }, 1);
        }

        selectivity.$el = replaceSelectElement($el, options);
        selectivity.$el[0].selectivity = selectivity;
    }
});
<|endoftext|>


<commit_before>"use strict";

const Point= require('../Point');
const Serializable= require('./Serializable');
const Serializer= require('./Serializer');

// constants
const MAX_BENDING_DISTANCE = 10;

/**
 * Defines an objects which can move about in the game world
 */
class DynamicObject extends Serializable {

    static get netScheme() {
        return {
            id: { type: Serializer.TYPES.UINT8 },
            playerId: { type: Serializer.TYPES.UINT8 },
            x: { type: Serializer.TYPES.INT16 },
            y: { type: Serializer.TYPES.INT16 },
            velX: { type: Serializer.TYPES.FLOAT32 },
            velY: { type: Serializer.TYPES.FLOAT32 },
            angle: { type: Serializer.TYPES.INT16 }
        };
    }

    constructor(id, x, y) {
        super();
        this.id = id; // instance id
        this.playerId = 0;
        this.x = x;
        this.y = y;
        this.velX = 0;
        this.velY = 0;
        this.angle = 90;
        this.rotationSpeed = 3;
        this.acceleration = 0.1;
        this.deceleration = 0.99;
        this.maxSpeed = 2;

        // todo deal with what goes over the wire
        this.velocity = new Point();
        this.temp = {
            accelerationVector: new Point()
        };

    }

    // for debugging purposes mostly
    toString() {
        function round3(x) { return Math.round(x * 1000) / 1000; }
        function showVec(x,y,z) { return `(${round3(x)}, ${round3(y)}, ${round3(z)})`; }
        return `DynamicObject[${this.id}] position${showVec(this.x, this.y, this.z)} velocity${showVec(this.velX, this.velY, this.velZ)}`;
    }

    copyFrom(sourceObj) {
        this.id = sourceObj.id;
        this.playerId = sourceObj.playerId;
        this.isPlayerControlled = sourceObj.isPlayerControlled;

        this.x = sourceObj.x;
        this.y = sourceObj.y;
        this.velX = sourceObj.velX;
        this.velY = sourceObj.velY;
        this.velocity.set(sourceObj.velX, sourceObj.velY);
        this.angle = sourceObj.angle;
        this.rotationSpeed = sourceObj.rotationSpeed;
        this.acceleration = sourceObj.acceleration;
        this.deceleration = sourceObj.deceleration;
        this.maxSpeed = sourceObj.maxSpeed;
    }

    step(worldSettings) {
        if (this.isRotatingRight) { this.angle += this.rotationSpeed; }
        if (this.isRotatingLeft) { this.angle -= this.rotationSpeed; }

        if (this.angle > 360) { this.angle -= 360; }
        if (this.angle < 0) { this.angle += 360; }

        if (this.isAccelerating) {
            this.temp.accelerationVector.set(
                Math.cos(this.angle * (Math.PI / 180)),
                Math.sin(this.angle * (Math.PI / 180))
            ).setMagnitude(this.acceleration);
        } else {
            this.temp.accelerationVector.set(0, 0);
        }

        // console.log(this.temp.accelerationVector.x,this.temp.accelerationVector.y);
        // console.log(this.temp.accelerationVector.x, this.temp.accelerationVector.y);
        // console.log(this.temp.accelerationVector.x, this.temp.accelerationVector.y);

        // constant velocity, like a missile
        if (this.constantVelocity) {
            this.velocity.set(
                Math.cos(this.angle * (Math.PI / 180)),
                Math.sin(this.angle * (Math.PI / 180))
            ).setMagnitude(this.constantVelocity);
        } else {
            // acceleration
            Point.add(this.velocity, this.temp.accelerationVector, this.velocity);
            // this.velocity.multiply(this.deceleration, this.deceleration);
            this.velocity.x = Math.round(this.velocity.x * 100) / 100;
            this.velocity.y = Math.round(this.velocity.y * 100) / 100;
        }

        this.velX = this.velocity.x;
        this.velY = this.velocity.y;

        this.isAccelerating = false;
        this.isRotatingLeft = false;
        this.isRotatingRight = false;
        this.x = this.x + this.velocity.x;
        this.y = this.y + this.velocity.y;

        if (this.x >= worldSettings.width) {
            this.x = worldSettings.width - this.x;
        } else if (this.y >= worldSettings.height) {
            this.y = worldSettings.height - this.y;
        } else if (this.x < 0) {
            this.x = worldSettings.width + this.x;
        } else if (this.y < 0) {
            this.y = worldSettings.width + this.y;
        }
    }

    init(options) {
        Object.assign(this, options);
    }

    initRenderObject(renderer) {
        this.renderer = renderer;
        this.renderObject = this.renderer.addObject(this);
    }

    syncTo(other, step, bending) {
        // TODO params should be taken from the netScheme
        // maybe use object.assign?
        if (!bending) bending = 1.0;
        ['x', 'y', 'velX', 'velY', 'angle']
            .forEach(attr => {
                if (Math.abs(other[attr] - this[attr]) > MAX_BENDING_DISTANCE) {
                    this[attr] = other[attr];
                    return;
                }
                this[attr] = (other[attr] - this[attr]) * bending + this[attr];
            });

        // TODO: these next two lines are a side-effect of the fact
        // that velocity is stored both in attribute "velocity" and in velX/velY
        // which is redundant now that we can set a Point instance over the network
        this.velocity.x = this.velX;
        this.velocity.y = this.velY;
        this.lastUpdateStep = step;
    }

    updateRenderObject() {
        this.renderObject.x = this.x;
        this.renderObject.y = this.y;
        this.renderObject.angle = this.angle;
    }

    interpolate(prevObj, nextObj, playPercentage) {

        // update other objects with interpolation
        // TODO refactor into general interpolation class
        // TODO: this interpolate function should not care about worldSettings.
        if (this.isPlayerControlled != true) {

            if (Math.abs(nextObj.x - prevObj.x) > this.renderer.worldSettings.height / 2) { // fix for world wraparound
                this.x = nextObj.x;
            } else {
                this.x = (nextObj.x - prevObj.x) * playPercentage + prevObj.x;
            }

            if (Math.abs(nextObj.y - prevObj.y) > this.renderer.worldSettings.height / 2) { // fix for world wraparound
                this.y = nextObj.y;
            } else {
                this.y = (nextObj.y - prevObj.y) * playPercentage + prevObj.y;
            }

            var shortestAngle = ((((nextObj.angle - prevObj.angle) % 360) + 540) % 360) - 180; // todo wrap this in a util
            this.angle = prevObj.angle + shortestAngle * playPercentage;

            if (this.renderObject) {
                this.updateRenderObject();
            }
        }
    }

    // release resources
    destroy() {
        console.log(`destroying object ${this.id}`);

        // destroy the renderObject
        if (this.renderObject) {
            this.renderer.removeObject(this.renderObject);
        }
    }
}

module.exports = DynamicObject;
<commit_msg>test new bending value<commit_after>"use strict";

const Point= require('../Point');
const Serializable= require('./Serializable');
const Serializer= require('./Serializer');

// constants
const MAX_BENDING_DISTANCE = 50;

/**
 * Defines an objects which can move about in the game world
 */
class DynamicObject extends Serializable {

    static get netScheme() {
        return {
            id: { type: Serializer.TYPES.UINT8 },
            playerId: { type: Serializer.TYPES.UINT8 },
            x: { type: Serializer.TYPES.INT16 },
            y: { type: Serializer.TYPES.INT16 },
            velX: { type: Serializer.TYPES.FLOAT32 },
            velY: { type: Serializer.TYPES.FLOAT32 },
            angle: { type: Serializer.TYPES.INT16 }
        };
    }

    constructor(id, x, y) {
        super();
        this.id = id; // instance id
        this.playerId = 0;
        this.x = x;
        this.y = y;
        this.velX = 0;
        this.velY = 0;
        this.angle = 90;
        this.rotationSpeed = 3;
        this.acceleration = 0.1;
        this.deceleration = 0.99;
        this.maxSpeed = 2;

        // todo deal with what goes over the wire
        this.velocity = new Point();
        this.temp = {
            accelerationVector: new Point()
        };

    }

    // for debugging purposes mostly
    toString() {
        function round3(x) { return Math.round(x * 1000) / 1000; }
        function showVec(x,y,z) { return `(${round3(x)}, ${round3(y)}, ${round3(z)})`; }
        return `DynamicObject[${this.id}] position${showVec(this.x, this.y, this.z)} velocity${showVec(this.velX, this.velY, this.velZ)}`;
    }

    copyFrom(sourceObj) {
        this.id = sourceObj.id;
        this.playerId = sourceObj.playerId;
        this.isPlayerControlled = sourceObj.isPlayerControlled;

        this.x = sourceObj.x;
        this.y = sourceObj.y;
        this.velX = sourceObj.velX;
        this.velY = sourceObj.velY;
        this.velocity.set(sourceObj.velX, sourceObj.velY);
        this.angle = sourceObj.angle;
        this.rotationSpeed = sourceObj.rotationSpeed;
        this.acceleration = sourceObj.acceleration;
        this.deceleration = sourceObj.deceleration;
        this.maxSpeed = sourceObj.maxSpeed;
    }

    step(worldSettings) {
        if (this.isRotatingRight) { this.angle += this.rotationSpeed; }
        if (this.isRotatingLeft) { this.angle -= this.rotationSpeed; }

        if (this.angle > 360) { this.angle -= 360; }
        if (this.angle < 0) { this.angle += 360; }

        if (this.isAccelerating) {
            this.temp.accelerationVector.set(
                Math.cos(this.angle * (Math.PI / 180)),
                Math.sin(this.angle * (Math.PI / 180))
            ).setMagnitude(this.acceleration);
        } else {
            this.temp.accelerationVector.set(0, 0);
        }

        // console.log(this.temp.accelerationVector.x,this.temp.accelerationVector.y);
        // console.log(this.temp.accelerationVector.x, this.temp.accelerationVector.y);
        // console.log(this.temp.accelerationVector.x, this.temp.accelerationVector.y);

        // constant velocity, like a missile
        if (this.constantVelocity) {
            this.velocity.set(
                Math.cos(this.angle * (Math.PI / 180)),
                Math.sin(this.angle * (Math.PI / 180))
            ).setMagnitude(this.constantVelocity);
        } else {
            // acceleration
            Point.add(this.velocity, this.temp.accelerationVector, this.velocity);
            // this.velocity.multiply(this.deceleration, this.deceleration);
            this.velocity.x = Math.round(this.velocity.x * 100) / 100;
            this.velocity.y = Math.round(this.velocity.y * 100) / 100;
        }

        this.velX = this.velocity.x;
        this.velY = this.velocity.y;

        this.isAccelerating = false;
        this.isRotatingLeft = false;
        this.isRotatingRight = false;
        this.x = this.x + this.velocity.x;
        this.y = this.y + this.velocity.y;

        if (this.x >= worldSettings.width) {
            this.x = worldSettings.width - this.x;
        } else if (this.y >= worldSettings.height) {
            this.y = worldSettings.height - this.y;
        } else if (this.x < 0) {
            this.x = worldSettings.width + this.x;
        } else if (this.y < 0) {
            this.y = worldSettings.width + this.y;
        }
    }

    init(options) {
        Object.assign(this, options);
    }

    initRenderObject(renderer) {
        this.renderer = renderer;
        this.renderObject = this.renderer.addObject(this);
    }

    syncTo(other, step, bending) {
        // TODO params should be taken from the netScheme
        // maybe use object.assign?
        if (!bending) bending = 1.0;
        ['x', 'y', 'velX', 'velY', 'angle']
            .forEach(attr => {
                if (Math.abs(other[attr] - this[attr]) > MAX_BENDING_DISTANCE) {
                    this[attr] = other[attr];
                    return;
                }
                this[attr] = (other[attr] - this[attr]) * bending + this[attr];
            });

        // TODO: these next two lines are a side-effect of the fact
        // that velocity is stored both in attribute "velocity" and in velX/velY
        // which is redundant now that we can set a Point instance over the network
        this.velocity.x = this.velX;
        this.velocity.y = this.velY;
        this.lastUpdateStep = step;
    }

    updateRenderObject() {
        this.renderObject.x = this.x;
        this.renderObject.y = this.y;
        this.renderObject.angle = this.angle;
    }

    interpolate(prevObj, nextObj, playPercentage) {

        // update other objects with interpolation
        // TODO refactor into general interpolation class
        // TODO: this interpolate function should not care about worldSettings.
        if (this.isPlayerControlled != true) {

            if (Math.abs(nextObj.x - prevObj.x) > this.renderer.worldSettings.height / 2) { // fix for world wraparound
                this.x = nextObj.x;
            } else {
                this.x = (nextObj.x - prevObj.x) * playPercentage + prevObj.x;
            }

            if (Math.abs(nextObj.y - prevObj.y) > this.renderer.worldSettings.height / 2) { // fix for world wraparound
                this.y = nextObj.y;
            } else {
                this.y = (nextObj.y - prevObj.y) * playPercentage + prevObj.y;
            }

            var shortestAngle = ((((nextObj.angle - prevObj.angle) % 360) + 540) % 360) - 180; // todo wrap this in a util
            this.angle = prevObj.angle + shortestAngle * playPercentage;

            if (this.renderObject) {
                this.updateRenderObject();
            }
        }
    }

    // release resources
    destroy() {
        console.log(`destroying object ${this.id}`);

        // destroy the renderObject
        if (this.renderObject) {
            this.renderer.removeObject(this.renderObject);
        }
    }
}

module.exports = DynamicObject;
<|endoftext|>


<commit_before>/* ========================================================
 * bootstrap-tab.js v2.1.2
 * http://twitter.github.com/bootstrap/javascript.html#tabs
 * ========================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================== */

!function ($) {

  "use strict"; // jshint ;_;

 /* TAB CLASS DEFINITION
  * ==================== */

  var Tab = function (element) {
    this.element = $(element)
  }

  Tab.prototype = {

    constructor: Tab

  , show: function () {
      var $this = this.element
        , $ul = $this.closest('ul:not(.dropdown-menu)')
        , selector = $this.attr('data-target')
        , previous
        , $target
        , e

      if (!selector) {
        selector = $this.attr('href')
        selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
      }

      if ( $this.parent('li').hasClass('active') ) return

      previous = $ul.find('.active a').last()[0]

      e = $.Event('show', {
        relatedTarget: previous
      })

      $this.trigger(e)

      if (e.isDefaultPrevented()) return

      $target = $(selector)

      this.activate($this.parent('li'), $ul)
      this.activate($target, $target.parent(), function () {
        $this.trigger({
          type: 'shown'
        , relatedTarget: previous
        })
      })
    }

  , activate: function ( element, container, callback) {
      var $active = container.find('> .active')
        , transition = callback
            && $.support.transition
            && $active.hasClass('fade')

      function next() {
        $active
          .removeClass('active')
          .find('> .dropdown-menu > .active')
          .removeClass('active')

        element.addClass('active')

        if (transition) {
          element[0].offsetWidth // reflow for transition
          element.addClass('in')
        } else {
          element.removeClass('fade')
        }

        if ( element.parent('.dropdown-menu') ) {
          element.closest('li.dropdown').addClass('active')
        }

        callback && callback()
      }

      transition ?
        $active.one($.support.transition.end, next) :
        next()

      $active.removeClass('in')
    }
  }

 /* TAB PLUGIN DEFINITION
  * ===================== */

  $.fn.tab = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('tab')
      if (!data) $this.data('tab', (data = new Tab(this)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.tab.Constructor = Tab

 /* TAB DATA-API
  * ============ */

  $(function () {
    $('body').on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
      e.preventDefault()
      $(this).tab('show')
    })
  })

}(window.jQuery);<commit_msg>Fix for #5362<commit_after>/* ========================================================
 * bootstrap-tab.js v2.1.2
 * http://twitter.github.com/bootstrap/javascript.html#tabs
 * ========================================================
 * Copyright 2012 Twitter, Inc.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 * ======================================================== */

!function ($) {

  "use strict"; // jshint ;_;

 /* TAB CLASS DEFINITION
  * ==================== */

  var Tab = function (element) {
    this.element = $(element)
  }

  Tab.prototype = {

    constructor: Tab

  , show: function () {
      var $this = this.element
        , $ul = $this.closest('ul:not(.dropdown-menu)')
        , selector = $this.attr('data-target')
        , previous
        , $target
        , e

      if (!selector) {
        selector = $this.attr('href')
        selector = selector && selector.replace(/.*(?=#[^\s]*$)/, '') //strip for ie7
      }

      if ( $this.parent('li').hasClass('active') ) return

      previous = $ul.find('.active:last a')[0]

      e = $.Event('show', {
        relatedTarget: previous
      })

      $this.trigger(e)

      if (e.isDefaultPrevented()) return

      $target = $(selector)

      this.activate($this.parent('li'), $ul)
      this.activate($target, $target.parent(), function () {
        $this.trigger({
          type: 'shown'
        , relatedTarget: previous
        })
      })
    }

  , activate: function ( element, container, callback) {
      var $active = container.find('> .active')
        , transition = callback
            && $.support.transition
            && $active.hasClass('fade')

      function next() {
        $active
          .removeClass('active')
          .find('> .dropdown-menu > .active')
          .removeClass('active')

        element.addClass('active')

        if (transition) {
          element[0].offsetWidth // reflow for transition
          element.addClass('in')
        } else {
          element.removeClass('fade')
        }

        if ( element.parent('.dropdown-menu') ) {
          element.closest('li.dropdown').addClass('active')
        }

        callback && callback()
      }

      transition ?
        $active.one($.support.transition.end, next) :
        next()

      $active.removeClass('in')
    }
  }

 /* TAB PLUGIN DEFINITION
  * ===================== */

  $.fn.tab = function ( option ) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('tab')
      if (!data) $this.data('tab', (data = new Tab(this)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.tab.Constructor = Tab

 /* TAB DATA-API
  * ============ */

  $(function () {
    $('body').on('click.tab.data-api', '[data-toggle="tab"], [data-toggle="pill"]', function (e) {
      e.preventDefault()
      $(this).tab('show')
    })
  })

}(window.jQuery);<|endoftext|>


<commit_before>var path = require('path'),
    graphviz;

try {
    graphviz = require('graphviz');
} catch (e) {
    throw new Error('transforms.drawGraph: The "graphviz" module is required. Please run "npm install graphviz" and try again (tested with version 0.0.3).');
}

var relationLabelByType = {
    HtmlScript: '<script>',
    HtmlStyle: '<style>',
    HtmlCacheManifest: '<html manifest>',
    HtmlIFrame: '<iframe>',
    HtmlFrame: '<frame>',
    HtmlAlternateLink: '<link rel=alternate>',
    HtmlConditionalComment: function (htmlConditionalComment) {return '<!--[if ' + htmlConditionalComment.condition + ']>';},
    HtmlImage: '<img>',
    HtmlAudio: '<audio>',
    HtmlShortcutIcon: 'icon',
    HtmlVideo: '<video>',
    HtmlVideoPoster: '<video poster>',
    HtmlEmbed: '<embed>',
    HtmlApplet: '<applet>',
    HtmlObject: '<object>',
    HtmlEdgeSideInclude: '<esi:include>',
    HtmlAnchor: '<a>',
    JavaScriptOneInclude: 'one.include',
    JavaScriptOneGetStaticUrl: 'one.getStaticUrl',
    JavaScriptAmdDefine: 'define',
    JavaScriptAmdRequire: 'require',
    CssImage: 'background-image',
    CssImport: '@import',
    CssBehavior: 'behavior'
};

module.exports = function (targetFileName) {
    return function drawGraph(assetGraph) {
        var g = graphviz.digraph("G"),
            seenNodes = {};

        function addAssetAsNode(asset, namePrefix) {
            seenNodes[asset.id] = true;
            g.addNode(asset.id, {
                label: "\"" + (namePrefix || '') + (asset.url ? path.basename(asset.url) : 'i:' + asset) + "\""
            });
        }
        assetGraph.findAssets().forEach(function (asset) {
            addAssetAsNode(asset);
        });
        assetGraph.findRelations().forEach(function (relation) {
            if (!seenNodes[relation.from.id]) {
                addAssetAsNode(relation.from, 'o:');
            }
            if (!seenNodes[relation.to.id]) {
                addAssetAsNode(relation.to, 'o:');
            }
            var label = relationLabelByType[relation.type] || '';
            if (typeof label === 'function') {
                label = label(relation);
            }
            g.addEdge(relation.from.id, relation.to.id, {
                fontsize: '9',
                arrowhead: 'empty',
                label: "\"" + label.replace(/\"/g, "\\\"") + "\""
            });
        });
        g.output(path.extname(targetFileName).substr(1), targetFileName);
    };
};
<commit_msg>transforms.drawGraph: More relation labels.<commit_after>var path = require('path'),
    graphviz;

try {
    graphviz = require('graphviz');
} catch (e) {
    throw new Error('transforms.drawGraph: The "graphviz" module is required. Please run "npm install graphviz" and try again (tested with version 0.0.3).');
}

var relationLabelByType = {
    HtmlScript: '<script>',
    HtmlStyle: '<style>',
    HtmlCacheManifest: '<html manifest>',
    HtmlIFrame: '<iframe>',
    HtmlFrame: '<frame>',
    HtmlAlternateLink: '<link rel=alternate>',
    HtmlConditionalComment: function (htmlConditionalComment) {return '<!--[if ' + htmlConditionalComment.condition + ']>';},
    HtmlImage: '<img>',
    HtmlAudio: '<audio>',
    HtmlShortcutIcon: 'icon',
    HtmlVideo: '<video>',
    HtmlVideoPoster: '<video poster>',
    HtmlEmbed: '<embed>',
    HtmlApplet: '<applet>',
    HtmlObject: '<object>',
    HtmlEdgeSideInclude: '<esi:include>',
    HtmlAnchor: '<a>',
    HtmlRequireJsMain: 'data-main',
    JavaScriptOneInclude: 'one.include',
    JavaScriptOneGetText: 'one.getText',
    JavaScriptOneGetStaticUrl: 'one.getStaticUrl',
    JavaScriptAmdDefine: 'define',
    JavaScriptAmdRequire: 'require',
    CssImage: 'background-image',
    CssImport: '@import',
    CssBehavior: 'behavior'
};

module.exports = function (targetFileName) {
    return function drawGraph(assetGraph) {
        var g = graphviz.digraph("G"),
            seenNodes = {};

        function addAssetAsNode(asset, namePrefix) {
            seenNodes[asset.id] = true;
            g.addNode(asset.id, {
                label: "\"" + (namePrefix || '') + (asset.url ? path.basename(asset.url) : 'i:' + asset) + "\""
            });
        }
        assetGraph.findAssets().forEach(function (asset) {
            addAssetAsNode(asset);
        });
        assetGraph.findRelations().forEach(function (relation) {
            if (!seenNodes[relation.from.id]) {
                addAssetAsNode(relation.from, 'o:');
            }
            if (!seenNodes[relation.to.id]) {
                addAssetAsNode(relation.to, 'o:');
            }
            var label = relationLabelByType[relation.type] || '';
            if (typeof label === 'function') {
                label = label(relation);
            }
            g.addEdge(relation.from.id, relation.to.id, {
                fontsize: '9',
                arrowhead: 'empty',
                label: "\"" + label.replace(/\"/g, "\\\"") + "\""
            });
        });
        g.output(path.extname(targetFileName).substr(1), targetFileName);
    };
};
<|endoftext|>


<commit_before>var util = require("util");
var BaseTrigger = require("./baseTrigger.js").BaseTrigger;
/*
 Trigger that responds to messages with the amount of time the bot script has been running, adn some other useful info
 command = string - What is the command. - defaults to !botinfo
 */

var InfoTrigger = function() {
	InfoTrigger.super_.apply(this, arguments);
};

util.inherits(InfoTrigger, BaseTrigger);

var type = "InfoTrigger";
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
	var trigger = new InfoTrigger(type, name, chatBot, options);
	trigger.options.command = trigger.options.command || "!botinfo";
	trigger.startTime = process.hrtime();
	return trigger;
};

// Return true if a message was sent
InfoTrigger.prototype._respondToFriendMessage = function(userId, message) {
	return this._respond(userId, message);
}

// Return true if a message was sent
InfoTrigger.prototype._respondToChatMessage = function(roomId, chatterId, message) {
	return this._respond(roomId, message);
}

InfoTrigger.prototype._respond = function(toId, message) {
	if (this.options.command && message && message.toLowerCase().indexOf(this.options.command.toLowerCase()) === 0) {
		var meminfo = process.memoryUsage();
		var curtime = process.hrtime(this.startTime);
			curtime = curtime[1] + curtime[0]*1000000000;
		var message  = "I have been running for about " + this._nanosecondsToStr(Math.floor(curtime/1000000000));
			message += " on " + process.platform + "/" + process.arch;
			message += ", using " + this._bytesToSize(meminfo.heapUsed) + " of " + this._bytesToSize(meminfo.heapTotal) + " allocated memory (RSS: " + this._bytesToSize(meminfo.rss);
			message += "). Node.js version is "+process.version+".";
			this._sendMessageAfterDelay(toId,message);
		return true;
	}
	return false;
}

InfoTrigger.prototype._nanosecondsToStr = function(seconds, goagain) {
    var temp = seconds;
    function numberEnding (number) {return (number > 1) ? "s" : "";}

    if(temp > 259200) {
        var temp = Math.floor(temp / 86400);
        var next = (goagain===true ? this._nanosecondsToStr(seconds-temp*86400,false) : "");
        return " " + temp + " day" + numberEnding(temp) + next;
    } else if (temp > 10800) {
        var temp = Math.floor(temp / 3600);
        var next = (goagain===true ? this._nanosecondsToStr(seconds-temp*3600,false) : "");
        return " " + temp + " hour" + numberEnding(temp) + next;
    } else if (temp > 180) {
        var temp = Math.floor(temp / 60);
        var next = (goagain===true ? this._nanosecondsToStr(seconds-temp*60,false) : "");
        return " " + temp + " minute" + numberEnding(temp) + next;
    } else return (goagain===true ? " less than a minute" : "");
}
InfoTrigger.prototype._bytesToSize = function(bytes) {
    var sizes = ["Bytes", "KB", "MB", "GB", "TB"];
    if (bytes === 0) return "0 Byte";
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return Math.round(bytes / Math.pow(1024, i), 2) + " " + sizes[i];
};
<commit_msg>Redefined variable<commit_after>var util = require("util");
var BaseTrigger = require("./baseTrigger.js").BaseTrigger;
/*
 Trigger that responds to messages with the amount of time the bot script has been running, adn some other useful info
 command = string - What is the command. - defaults to !botinfo
 */

var InfoTrigger = function() {
	InfoTrigger.super_.apply(this, arguments);
};

util.inherits(InfoTrigger, BaseTrigger);

var type = "InfoTrigger";
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
	var trigger = new InfoTrigger(type, name, chatBot, options);
	trigger.options.command = trigger.options.command || "!botinfo";
	trigger.startTime = process.hrtime();
	return trigger;
};

// Return true if a message was sent
InfoTrigger.prototype._respondToFriendMessage = function(userId, message) {
	return this._respond(userId, message);
}

// Return true if a message was sent
InfoTrigger.prototype._respondToChatMessage = function(roomId, chatterId, message) {
	return this._respond(roomId, message);
}

InfoTrigger.prototype._respond = function(toId, msg) {
	if (this.options.command && msg && msg.toLowerCase().indexOf(this.options.command.toLowerCase()) === 0) {
		var meminfo = process.memoryUsage();
		var curtime = process.hrtime(this.startTime);
			curtime = curtime[1] + curtime[0]*1000000000;
		var message = "I have been running for about " + this._nanosecondsToStr(Math.floor(curtime/1000000000));
			message += " on " + process.platform + "/" + process.arch;
			message += ", using " + this._bytesToSize(meminfo.heapUsed) + " of " + this._bytesToSize(meminfo.heapTotal) + " allocated memory (RSS: " + this._bytesToSize(meminfo.rss);
			message += "). Node.js version is "+process.version+".";
			this._sendMessageAfterDelay(toId,message);
		return true;
	}
	return false;
}

InfoTrigger.prototype._nanosecondsToStr = function(seconds, goagain) {
    var temp = seconds;
    function numberEnding (number) {return (number > 1) ? "s" : "";}

    if(temp > 259200) {
        var temp = Math.floor(temp / 86400);
        var next = (goagain===true ? this._nanosecondsToStr(seconds-temp*86400,false) : "");
        return " " + temp + " day" + numberEnding(temp) + next;
    } else if (temp > 10800) {
        var temp = Math.floor(temp / 3600);
        var next = (goagain===true ? this._nanosecondsToStr(seconds-temp*3600,false) : "");
        return " " + temp + " hour" + numberEnding(temp) + next;
    } else if (temp > 180) {
        var temp = Math.floor(temp / 60);
        var next = (goagain===true ? this._nanosecondsToStr(seconds-temp*60,false) : "");
        return " " + temp + " minute" + numberEnding(temp) + next;
    } else return (goagain===true ? " less than a minute" : "");
}
InfoTrigger.prototype._bytesToSize = function(bytes) {
    var sizes = ["Bytes", "KB", "MB", "GB", "TB"];
    if (bytes === 0) return "0 Byte";
    var i = parseInt(Math.floor(Math.log(bytes) / Math.log(1024)));
    return Math.round(bytes / Math.pow(1024, i), 2) + " " + sizes[i];
};
<|endoftext|>


<commit_before>/*
 * DAlert jQueryPlugin
 * dalert.alert("Making the Alert Box much simpler, yet fancy");
 * Version: 1.0 (Alpha)
 * Author: Andrew dEX (Dilusha)
 * Dependencies : Jquery 1.6 + , Jquery UI 1.6 + Jquery UI CSS Framework
 * Info & API : http://dalert.andrewdex.com
 * Contribute : http://www.github.com/andrewdex/dalert
 *
 * Copyright 2013 Andrew dEX (Dilusha Gonagala)
 *
 * Released under the MIT license
 *http://opensource.org/licenses/MIT
 *Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 *
 */

var dalert = {

	//jQuery UI Override for button padding
	byPassjQueryUI : function() {

		$(".ui-button-text-only .ui-button-text").css("padding-left", "20px");
		$(".ui-button-text-only .ui-button-text").css("padding-right", "20px");
		$(".ui-button-text-only .ui-button-text").css("padding-top", "0px");
		$(".ui-button-text-only .ui-button-text").css("padding-bottom", "0px");
		$(".ui-button-text-only .ui-button-text").css("font-size", "13px");

	},

	alert : function(dalert_msg, title_msg, FontColor, bodyColor) {
		"use strict";
		if (!title_msg)
			title_msg = 'DAlert';

		if (!FontColor)
			FontColor = 'black';

		if (!bodyColor)
			bodyColor = 'rgb(10, 60, 65)';

		if (!dalert_msg)
			dalert_msg = 'This is a Dalert !';

		try {
			$("

").html(dalert_msg).dialog({
				title : title_msg,
				resizable : false,
				modal : true,
				buttons : {
					"Ok" : function() {
						$(this).dialog("close");

					}
				}
			});
			// jQuery UI-CSS Framework ByPass
			$(".ui-widget-content").css("color", FontColor);
			$(".ui-widget-content").css("background", bodyColor);

			//Call buttonPadding ByPass
			dalert.byPassjQueryUI();
			//Catching Errors, In Case if something goes wrong with jQuery UI,
			//Replicate the native alert function.
		} catch (error) {
			console.log(error);
			alert(dalert_msg);
		}

	},

	// DAlert Confirm Dialog
	confirm : function(dalertConf_msg, trueFunction, falseFunction, title_msg,
			FontColor, bodyColor) {
		"use strict";

		if (!title_msg)
			title_msg = 'DAlert';

		if (!FontColor)
			FontColor = 'black';

		if (!bodyColor)
			bodyColor = 'rgb(10, 60, 65)';

		if (!dalertConf_msg)
			dalertConf_msg = 'This is a Dalert Confirm !';

		try {
			$("

").html(dalertConf_msg).dialog({
				title : title_msg,
				resizable : false,
				modal : true,
				buttons : {
					"Ok" : function() {
						if (!trueFunction) {
							$(this).dialog("close");
						} else {
							eval(trueFunction)();
							$(this).dialog("close");

						}

					},
					Cancel : function() {
						if (!falseFunction) {
							$(this).dialog("close");
						} else {
							eval(falseFunction)();
							$(this).dialog("close");

						}

					}
				}
			});
			// jQuery UI-CSS Framework ByPass
			$(".ui-widget-content").css("color", FontColor);
			$(".ui-widget-content").css("background", bodyColor);

			//Call buttonPadding ByPass
			dalert.byPassjQueryUI();

			//Catching Errors, In Case if something goes wrong with jQuery UI,
			//Replicate the native confirm function and handling the parameterized true false functions.
		} catch (error) {
			console.log(error);
			var conf_val = confirm(dalertConf_msg);
			if (conf_val == true) {
				eval(trueFunction)();
			} else {
				eval(falseFunction)();
			}
		}

	},

	// Replace DAlert With Window JavaScript Original objects : alert, confirm.
	ReplaceAlert : function() {

		window.alert = dalert.alert;

	},

	ReplaceConfirm : function() {

		window.confirm = dalert.confirm;

	}

};
<commit_msg>License Modified<commit_after>/*
 * DAlert jQueryPlugin
 * dalert.alert("Making the Alert Box much simpler, yet fancy");
 * Version: 1.0 (Alpha)
 * Author: Andrew dEX (Dilusha)
 * Dependencies : Jquery 1.6 + , Jquery UI 1.6 + Jquery UI CSS Framework
 * Info & API : http://dalert.andrewdex.com
 * Contribute : http://www.github.com/andrewdex/dalert
 *
 * Copyright 2013 Andrew dEX (Dilusha Gonagala)
 *
Released under the MIT license
_______________________________
http://opensource.org/licenses/MIT
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 *
 */

var dalert = {

	//jQuery UI Override for button padding
	byPassjQueryUI : function() {

		$(".ui-button-text-only .ui-button-text").css("padding-left", "20px");
		$(".ui-button-text-only .ui-button-text").css("padding-right", "20px");
		$(".ui-button-text-only .ui-button-text").css("padding-top", "0px");
		$(".ui-button-text-only .ui-button-text").css("padding-bottom", "0px");
		$(".ui-button-text-only .ui-button-text").css("font-size", "13px");

	},

	alert : function(dalert_msg, title_msg, FontColor, bodyColor) {
		"use strict";
		if (!title_msg)
			title_msg = 'DAlert';

		if (!FontColor)
			FontColor = 'black';

		if (!bodyColor)
			bodyColor = 'rgb(10, 60, 65)';

		if (!dalert_msg)
			dalert_msg = 'This is a Dalert !';

		try {
			$("

").html(dalert_msg).dialog({
				title : title_msg,
				resizable : false,
				modal : true,
				buttons : {
					"Ok" : function() {
						$(this).dialog("close");

					}
				}
			});
			// jQuery UI-CSS Framework ByPass
			$(".ui-widget-content").css("color", FontColor);
			$(".ui-widget-content").css("background", bodyColor);

			//Call buttonPadding ByPass
			dalert.byPassjQueryUI();
			//Catching Errors, In Case if something goes wrong with jQuery UI,
			//Replicate the native alert function.
		} catch (error) {
			console.log(error);
			alert(dalert_msg);
		}

	},

	// DAlert Confirm Dialog
	confirm : function(dalertConf_msg, trueFunction, falseFunction, title_msg,
			FontColor, bodyColor) {
		"use strict";

		if (!title_msg)
			title_msg = 'DAlert';

		if (!FontColor)
			FontColor = 'black';

		if (!bodyColor)
			bodyColor = 'rgb(10, 60, 65)';

		if (!dalertConf_msg)
			dalertConf_msg = 'This is a Dalert Confirm !';

		try {
			$("

").html(dalertConf_msg).dialog({
				title : title_msg,
				resizable : false,
				modal : true,
				buttons : {
					"Ok" : function() {
						if (!trueFunction) {
							$(this).dialog("close");
						} else {
							eval(trueFunction)();
							$(this).dialog("close");

						}

					},
					Cancel : function() {
						if (!falseFunction) {
							$(this).dialog("close");
						} else {
							eval(falseFunction)();
							$(this).dialog("close");

						}

					}
				}
			});
			// jQuery UI-CSS Framework ByPass
			$(".ui-widget-content").css("color", FontColor);
			$(".ui-widget-content").css("background", bodyColor);

			//Call buttonPadding ByPass
			dalert.byPassjQueryUI();

			//Catching Errors, In Case if something goes wrong with jQuery UI,
			//Replicate the native confirm function and handling the parameterized true false functions.
		} catch (error) {
			console.log(error);
			var conf_val = confirm(dalertConf_msg);
			if (conf_val == true) {
				eval(trueFunction)();
			} else {
				eval(falseFunction)();
			}
		}

	},

	// Replace DAlert With Window JavaScript Original objects : alert, confirm.
	ReplaceAlert : function() {

		window.alert = dalert.alert;

	},

	ReplaceConfirm : function() {

		window.confirm = dalert.confirm;

	}

};
<|endoftext|>


<commit_before>var util = require("util");
var request = require("request");

var BaseTrigger = require("./baseTrigger.js").BaseTrigger;

/*
Trigger that responds to requests and tells if a server is running
see http://technotip.com/3709/server-up-or-down-node-js/ for more info
command = string - a message must start with this + a space before a response will be given
*/

var isupTrigger = function() {
	isupTrigger.super_.apply(this, arguments);
};

util.inherits(isupTrigger, BaseTrigger);

var type = "isupTrigger";
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
	var trigger = new isupTrigger(type, name, chatBot, options);

	trigger.options.command = trigger.options.command || "!isup";
//	trigger.options.isup = trigger.options.isup || isup;

	return trigger;
};

// Return true if a message was sent
isupTrigger.prototype._respondToFriendMessage = function(userId, message) {
	return this._respond(userId, message);
}

// Return true if a message was sent
isupTrigger.prototype._respondToChatMessage = function(roomId, chatterId, message) {
	return this._respond(roomId, message);
}

isupTrigger.prototype._respond = function(toId, message) {
	var query = this._stripCommand(message);
	var that = this;
	if (query) {
		if(query.indexOf("://") === -1) {
			query = "http://" + query;
		}
		try {
			request(query, function (error, response, body) {
				if (!error) {
					if(response.statusCode===200 || response.statusCode===301) {
						that._sendMessageAfterDelay(toId, "It's working just fine for me.");
					} else {
						that._sendMessageAfterDelay(toId, "The server is running, but it returned http status code "+ response.statusCode+". Please look it up for more information.");
					}
				} else {
					that.winston.warn("ERROR! " + error);
					try{that.sendMessageAfterDelay(toId, "ERROR! Please notify the bot admin to check the logs!");
					} catch(e) { that.winston.error(e.stack); that._sendMessageAfterDelay(toId, "ERROR!"); }
				}
			})
			return true;
		} catch(e) { that.winston.error(e); }
	}
	return false;
}

isupTrigger.prototype._stripCommand = function(message) {
	if (this.options.command && message && message.toLowerCase().indexOf(this.options.command.toLowerCase() + " ") === 0) {
		return message.substring(this.options.command.length + 1);
	}
	return null;
}
<commit_msg>Fix case on isUpTrigger.<commit_after>var util = require("util");
var request = require("request");

var BaseTrigger = require("./baseTrigger.js").BaseTrigger;

/*
Trigger that responds to requests and tells if a server is running
see http://technotip.com/3709/server-up-or-down-node-js/ for more info
command = string - a message must start with this + a space before a response will be given
*/

var IsUpTrigger = function() {
	IsUpTrigger.super_.apply(this, arguments);
};

util.inherits(IsUpTrigger, BaseTrigger);

var type = "IsUpTrigger";
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
	var trigger = new IsUpTrigger(type, name, chatBot, options);

	trigger.options.command = trigger.options.command || "!isup";
//	trigger.options.isup = trigger.options.isup || isup;

	return trigger;
};

// Return true if a message was sent
IsUpTrigger.prototype._respondToFriendMessage = function(userId, message) {
	return this._respond(userId, message);
}

// Return true if a message was sent
IsUpTrigger.prototype._respondToChatMessage = function(roomId, chatterId, message) {
	return this._respond(roomId, message);
}

IsUpTrigger.prototype._respond = function(toId, message) {
	var query = this._stripCommand(message);
	var that = this;
	if (query) {
		if(query.indexOf("://") === -1) {
			query = "http://" + query;
		}
		try {
			request(query, function (error, response, body) {
				if (!error) {
					if(response.statusCode===200 || response.statusCode===301) {
						that._sendMessageAfterDelay(toId, "It's working just fine for me.");
					} else {
						that._sendMessageAfterDelay(toId, "The server is running, but it returned http status code "+ response.statusCode+". Please look it up for more information.");
					}
				} else {
					that.winston.warn("ERROR! " + error);
					try{that.sendMessageAfterDelay(toId, "ERROR! Please notify the bot admin to check the logs!");
					} catch(e) { that.winston.error(e.stack); that._sendMessageAfterDelay(toId, "ERROR!"); }
				}
			})
			return true;
		} catch(e) { that.winston.error(e); }
	}
	return false;
}

IsUpTrigger.prototype._stripCommand = function(message) {
	if (this.options.command && message && message.toLowerCase().indexOf(this.options.command.toLowerCase() + " ") === 0) {
		return message.substring(this.options.command.length + 1);
	}
	return null;
}
<|endoftext|>


<commit_before>/**
 * Class that extends the diff_match_patch class of the google framework with a
 * wordbased approach and
 * @module lib/DiffHandler
*/

function DiffHandler(){
	diff_match_patch.call(this);
}

DiffHandler.prototype = Object.create(diff_match_patch.prototype);
DiffHandler.prototype.constructor = DiffHandler;

/**
 * Returns a HTML representation of the diff where the two texts are represented
 * in one.
 * @return {String} containing the html representation of the diff
*/
DiffHandler.prototype.diff_html = function(diffs){
	var html = [];
	var pattern_amp = /&/g;
	var pattern_lt = /</g;
	var pattern_gt = />/g;
	var pattern_para = /\n/g;
	var editopen=false;
	for (var x = 0; x < diffs.length; x++) {
	var op = diffs[x][0];    // Operation (insert, delete, equal)
	var data = diffs[x][1];  // Text of change.
	var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<')
	    .replace(pattern_gt, '>').replace(pattern_para, '¶
');
	var html_string = "";
	switch (op) {
	  case DIFF_INSERT:
		if(!editopen)
			html_string += '';

		html_string += '' + text + '';

		if(editopen){
	    	html_string += '';
	    	editopen = false;
	    } else{
	    	editopen = true;
	    }
	    break;

	  case DIFF_DELETE:
		if(!editopen)
			html_string += '';

		html_string += '' + text + '';

		if(editopen){
	    	html_string += '';
	    	editopen = false;
	    } else{
	    	editopen = true;
	    }
	    break;

	      case DIFF_EQUAL:
	    	if(editopen){
	        	html_string += '';
	        	editopen = false;
	        }
	        html_string += '' + text.trim() + ' ';
	        break;
	    }

	    html[x] = html_string;
	  }
	  return html.join('');
};

/**
 * Constructs an array that indicates, which parts (influenced by intervalllength)
 * are equal in respect to the diff.
 * @return {Array} representation of the diff, indicating the equal parts
*/
DiffHandler.prototype.equal_line = function(diffs, intervalLength){
	var dataline = [];
	var index = 0;
	var currentvalue = 0;
	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];
		for (var i = 0; i < data.length; i++){
			index++;
			if(op == DIFF_EQUAL)
				currentvalue++;

			if(index%intervalLength===0){
				dataline[index/intervalLength-1]=(currentvalue===0)?0:currentvalue;

				currentvalue = 0;
			}
		}

	}
	return dataline;
};

dataArraytoString = function(datarr){
	var returnvalue = "";
	for(var i in datarr){
		returnvalue += datarr[i] + " ";
	}
	return returnvalue;
}

dataArraytoString2D = function(datarr, dim){
	var returnvalue = "";
	for(var i in datarr){
		returnvalue += datarr[i][dim] + " ";
	}
	return returnvalue;
}

/**
 * Constructs a HTML representation of the diff with alignment of the equal
 * source and dissertation lines. Linebreaks are set after the specified number
 * of characters, with word wrapping-
 * @return {Object} aligned dissertation text and source text
*/
DiffHandler.prototype.alligned_texts = function(diffs, maxchars){
	var source_line = new Allignment();
	var diss_line = new Allignment();

	source_line.maxchars=maxchars;
	diss_line.maxchars=maxchars;

	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];

		switch(op){
			case DIFF_INSERT:
				diss_line.append(dataArraytoString(data), "insertion");
				break;
			case DIFF_DELETE:
				source_line.append(dataArraytoString(data), "deletion");
				break;
			case DIFF_EQUAL:
				disstext = dataArraytoString2D(data,1);
				sourcetext = dataArraytoString2D(data,0);
				if(disstext.length>10){
					maximumLines = Math.max(source_line.linecount, diss_line.linecount);
					source_line.setLineCountTo(maximumLines);
					diss_line.setLineCountTo(maximumLines);
					source_line.append(sourcetext, "equal");
					diss_line.append(disstext, "equal");
				} else{
					diss_line.append(disstext, "insertion");
					source_line.append(sourcetext, "deletion");
				}

				break;
		}
	}

	return {"diss_html":diss_line.line, "source_html":source_line.line};

};

/**
 * Constructs a HTML representation of the diff with alignment of the equal
 * source and dissertation lines. Linebreaks are set after the specified number
 * of characters, strict, with character wrapping.-
 * @return {Object} aligned dissertation text and source text
*/
DiffHandler.prototype.alligned_texts_strict = function(diffs, maxchars){
	var source_line = new Allignment();
	var diss_line = new Allignment();

	source_line.maxchars = maxchars;
	diss_line.maxchars = maxchars;

	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];

		switch(op){
			case DIFF_INSERT:
				//diss_line.append(data, "insertion");
				diss_line.appendStrict(data, "insertion");
				break;
			case DIFF_DELETE:
				//source_line.append(data, "deletion");
				source_line.appendStrict(data, "deletion");
				break;
			case DIFF_EQUAL:
				if(data.length>10){
					maximumLines = Math.max(source_line.linecount, diss_line.linecount);
					source_line.setLineCountTo(maximumLines);
					diss_line.setLineCountTo(maximumLines);
					source_line.appendStrict(data, "equal");
					diss_line.appendStrict(data, "equal");
				} else{
					source_line.appendStrict(data, "deletion");
					diss_line.appendStrict(data, "insertion");
				}

				break;
		}
	}

	return {"diss_html":diss_line.line, "source_html":source_line.line};
};

/**
 * Transforms a given array of words into a character string. Each desinct
 * word is encoded as the same character.
*/
diff_match_patch.prototype.words_to_characters = function(textarr){
	var alphanumericRegExp = /\W/gi;
	var openingSquareBracket = /\[\d+\]/g;
	var textchars = "";

	for(var i in textarr){
		var word = textarr[i];
		var normalized_word = word.toLowerCase();
		normalized_word = normalized_word.replace(openingSquareBracket, '').replace(alphanumericRegExp, '');
		if(this.word_dict.hasOwnProperty(normalized_word)){
			var character = this.word_dict[normalized_word];
			textchars += character;
			if(this.char_dict[character].length != (this.textnumber + 1))
				this.char_dict[character].push(new Array);
			wordlist = this.char_dict[character][this.textnumber];
			wordlist.push(word);
			continue;
		}

		var character = String.fromCharCode(this.charcode);
		this.word_dict[normalized_word] = character;
		this.char_dict[character] = new Array();
		this.char_dict[character].push(new Array());
		this.char_dict[character][this.textnumber] = [word];
		this.charcode += 1;
		textchars += character;
	}

	this.textnumber += 1;

	return textchars;
}

/**
 * Computes the diff on wordbase. This is an extention of the character based
 * diff computation of the google_diff_match_patch framework.
 * @return {Array} word based diff consisting of arrays, in which the first
 * element represents the operation (-1: DIFF_DELETE, 1: DIFF_INSERT,
 * 0:DIFF_EQUAL) and the second element the text of that was applied by this
 * operation.
*/
diff_match_patch.prototype.diff_wordbased = function(text1, text2, lebool){
	text1 = text1.replace(/\r|\n/g, " ");
	text2 = text2.replace(/\r|\n/g, " ");
	textarr1 = text1.split(/\s/g);
	textarr2 = text2.split(/\s/g);
	this.word_dict = {};
	this.charcode = 21;
	this.textnumber = 0;

	this.char_dict= {};
	textchars1 = this.words_to_characters(textarr1);
	textchars2 = this.words_to_characters(textarr2);

	var diffs = this.diff_main(textchars1, textchars2, lebool);
	var result = [];
	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];
		var encodedstring = [];
		var datarr = data.split("");
		for(var i in datarr){
			var character = datarr[i];
			var character_entry = this.char_dict[character];
			var nextword = [];
			switch(op){
				case DIFF_DELETE:
					nextword = character_entry[0][0];
					character_entry[0].splice(0,1);
					break;
				case DIFF_INSERT:
					nextword = character_entry[1][0];
					character_entry[1].splice(0,1);
					break;
				case DIFF_EQUAL:
					nextword.push(character_entry[0][0]);
					nextword.push(character_entry[1][0]);
					character_entry[0].splice(0,1);
					character_entry[1].splice(0,1);
			}
			encodedstring.push(nextword);
			i += 1;
		}
		result.push([op,encodedstring]);
	}

	return result;
};

/*

DiffHandler.prototype.abstract_script = function(diffs){
	var editscript = [];
	for (var x = 0; x < diffs.length; x++) {
		var op = diffs[x][0];    // Operation (insert, delete, equal)
		var data = diffs[x][1];  // Text of change.
		switch (op) {
			case DIFF_INSERT:
				editscript[x] = ['I',data.length];
				break;
			case DIFF_DELETE:
				editscript[x] = ['D',data.length];
				break;
			case DIFF_EQUAL:
				editscript[x] = ['E',data.length];
				break;
		}
	}
	return editscript;
};

DiffHandler.prototype.edit_symbols = function(diffs){
	var symbolstring = "";

	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];
		switch(op){
			case DIFF_INSERT:
				symbolstring += ""+data.length+"+";
				break;
			case DIFF_DELETE:
				symbolstring += ""+data.length+"-";
				break;
			case DIFF_EQUAL:
				symbolstring += ""+data.length+"=";
				break;
		}

	}
	return symbolstring;
}

DiffHandler.prototype.data_line = function(diffs){
	var dataline = [];
	var index = 0;
    var currentvalue = 0;
	for (var x = 0; x < diffs.length; x++) {
	    var op = diffs[x][0];    // Operation (insert, delete, equal)
	    var data = diffs[x][1];  // Text of change.
	    switch (op) {
	      case DIFF_INSERT:
	    	for(var i = 0; i<data.length; i++){
	    		currentvalue += 1;
	    		dataline[index] = currentvalue;
	    		index += 1;
	    	}
	        break;
	      case DIFF_DELETE:
	    	  for(var i = 0; i<data.length; i++){
		    		currentvalue -= 1;
		    		dataline[index] = currentvalue;
		    		index += 1;
		    	}
	    	  break;
	      case DIFF_EQUAL:
	    	  for(var i = 0; i<data.length; i++){
	    		  	dataline[index] = currentvalue;
		    		index += 1;
		    	}
	    	  break;
	    }
	  }
	return dataline;
}

DiffHandler.prototype.equal_sum_line = function(diffs){
	var dataline = [];
	var index = 0;
	var currentvalue = 0;
	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];

		switch(op){
			case DIFF_INSERT:
					dataline[index]=currentvalue;
					index++;

				break;
			case DIFF_DELETE:
				for (var i = 0; i < data.length; i++){
					dataline[index]=currentvalue;
					index++;
				}
				break;
			case DIFF_EQUAL:
				for (var i = 0; i < data.length; i++){
					currentvalue++;
					dataline[index]=currentvalue;
					index++;
				}
				break;
		}

	}
	return dataline;
}

DiffHandler.prototype.html_texts = function(diffs){
	var source_html = "";
	var diss_html = "";

	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];

		switch(op){
			case DIFF_INSERT:
				diss_html += data;
				break;
			case DIFF_DELETE:
				source_html += data;
				break;
			case DIFF_EQUAL:
				var addstring = "" + data + ""
				diss_html += addstring;
				source_html += addstring;
				break;
		}
	}

	return {"diss_html":diss_html, "source_html":source_html};
}

*/
<commit_msg>added words in brackets to regex<commit_after>/**
 * Class that extends the diff_match_patch class of the google framework with a
 * wordbased approach and
 * @module lib/DiffHandler
*/

function DiffHandler(){
	diff_match_patch.call(this);
}

DiffHandler.prototype = Object.create(diff_match_patch.prototype);
DiffHandler.prototype.constructor = DiffHandler;

/**
 * Returns a HTML representation of the diff where the two texts are represented
 * in one.
 * @return {String} containing the html representation of the diff
*/
DiffHandler.prototype.diff_html = function(diffs){
	var html = [];
	var pattern_amp = /&/g;
	var pattern_lt = /</g;
	var pattern_gt = />/g;
	var pattern_para = /\n/g;
	var editopen=false;
	for (var x = 0; x < diffs.length; x++) {
	var op = diffs[x][0];    // Operation (insert, delete, equal)
	var data = diffs[x][1];  // Text of change.
	var text = data.replace(pattern_amp, '&').replace(pattern_lt, '<')
	    .replace(pattern_gt, '>').replace(pattern_para, '¶
');
	var html_string = "";
	switch (op) {
	  case DIFF_INSERT:
		if(!editopen)
			html_string += '';

		html_string += '' + text + '';

		if(editopen){
	    	html_string += '';
	    	editopen = false;
	    } else{
	    	editopen = true;
	    }
	    break;

	  case DIFF_DELETE:
		if(!editopen)
			html_string += '';

		html_string += '' + text + '';

		if(editopen){
	    	html_string += '';
	    	editopen = false;
	    } else{
	    	editopen = true;
	    }
	    break;

	      case DIFF_EQUAL:
	    	if(editopen){
	        	html_string += '';
	        	editopen = false;
	        }
	        html_string += '' + text.trim() + ' ';
	        break;
	    }

	    html[x] = html_string;
	  }
	  return html.join('');
};

/**
 * Constructs an array that indicates, which parts (influenced by intervalllength)
 * are equal in respect to the diff.
 * @return {Array} representation of the diff, indicating the equal parts
*/
DiffHandler.prototype.equal_line = function(diffs, intervalLength){
	var dataline = [];
	var index = 0;
	var currentvalue = 0;
	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];
		for (var i = 0; i < data.length; i++){
			index++;
			if(op == DIFF_EQUAL)
				currentvalue++;

			if(index%intervalLength===0){
				dataline[index/intervalLength-1]=(currentvalue===0)?0:currentvalue;

				currentvalue = 0;
			}
		}

	}
	return dataline;
};

dataArraytoString = function(datarr){
	var returnvalue = "";
	for(var i in datarr){
		returnvalue += datarr[i] + " ";
	}
	return returnvalue;
}

dataArraytoString2D = function(datarr, dim){
	var returnvalue = "";
	for(var i in datarr){
		returnvalue += datarr[i][dim] + " ";
	}
	return returnvalue;
}

/**
 * Constructs a HTML representation of the diff with alignment of the equal
 * source and dissertation lines. Linebreaks are set after the specified number
 * of characters, with word wrapping-
 * @return {Object} aligned dissertation text and source text
*/
DiffHandler.prototype.alligned_texts = function(diffs, maxchars){
	var source_line = new Allignment();
	var diss_line = new Allignment();

	source_line.maxchars=maxchars;
	diss_line.maxchars=maxchars;

	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];

		switch(op){
			case DIFF_INSERT:
				diss_line.append(dataArraytoString(data), "insertion");
				break;
			case DIFF_DELETE:
				source_line.append(dataArraytoString(data), "deletion");
				break;
			case DIFF_EQUAL:
				disstext = dataArraytoString2D(data,1);
				sourcetext = dataArraytoString2D(data,0);
				if(disstext.length>10){
					maximumLines = Math.max(source_line.linecount, diss_line.linecount);
					source_line.setLineCountTo(maximumLines);
					diss_line.setLineCountTo(maximumLines);
					source_line.append(sourcetext, "equal");
					diss_line.append(disstext, "equal");
				} else{
					diss_line.append(disstext, "insertion");
					source_line.append(sourcetext, "deletion");
				}

				break;
		}
	}

	return {"diss_html":diss_line.line, "source_html":source_line.line};

};

/**
 * Constructs a HTML representation of the diff with alignment of the equal
 * source and dissertation lines. Linebreaks are set after the specified number
 * of characters, strict, with character wrapping.-
 * @return {Object} aligned dissertation text and source text
*/
DiffHandler.prototype.alligned_texts_strict = function(diffs, maxchars){
	var source_line = new Allignment();
	var diss_line = new Allignment();

	source_line.maxchars = maxchars;
	diss_line.maxchars = maxchars;

	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];

		switch(op){
			case DIFF_INSERT:
				//diss_line.append(data, "insertion");
				diss_line.appendStrict(data, "insertion");
				break;
			case DIFF_DELETE:
				//source_line.append(data, "deletion");
				source_line.appendStrict(data, "deletion");
				break;
			case DIFF_EQUAL:
				if(data.length>10){
					maximumLines = Math.max(source_line.linecount, diss_line.linecount);
					source_line.setLineCountTo(maximumLines);
					diss_line.setLineCountTo(maximumLines);
					source_line.appendStrict(data, "equal");
					diss_line.appendStrict(data, "equal");
				} else{
					source_line.appendStrict(data, "deletion");
					diss_line.appendStrict(data, "insertion");
				}

				break;
		}
	}

	return {"diss_html":diss_line.line, "source_html":source_line.line};
};

/**
 * Transforms a given array of words into a character string. Each desinct
 * word is encoded as the same character.
*/
diff_match_patch.prototype.words_to_characters = function(textarr){
	var alphanumericRegExp = /\W/gi;
	var openingSquareBracket = /\[(\w+|[a-z]+)\]/gi;
	var textchars = "";

	for(var i in textarr){
		var word = textarr[i];
		var normalized_word = word.toLowerCase();
		normalized_word = normalized_word.replace(openingSquareBracket, '').replace(alphanumericRegExp, '');
		if(this.word_dict.hasOwnProperty(normalized_word)){
			var character = this.word_dict[normalized_word];
			textchars += character;
			if(this.char_dict[character].length != (this.textnumber + 1))
				this.char_dict[character].push(new Array);
			wordlist = this.char_dict[character][this.textnumber];
			wordlist.push(word);
			continue;
		}

		var character = String.fromCharCode(this.charcode);
		this.word_dict[normalized_word] = character;
		this.char_dict[character] = new Array();
		this.char_dict[character].push(new Array());
		this.char_dict[character][this.textnumber] = [word];
		this.charcode += 1;
		textchars += character;
	}

	this.textnumber += 1;

	return textchars;
}

/**
 * Computes the diff on wordbase. This is an extention of the character based
 * diff computation of the google_diff_match_patch framework.
 * @return {Array} word based diff consisting of arrays, in which the first
 * element represents the operation (-1: DIFF_DELETE, 1: DIFF_INSERT,
 * 0:DIFF_EQUAL) and the second element the text of that was applied by this
 * operation.
*/
diff_match_patch.prototype.diff_wordbased = function(text1, text2, lebool){
	text1 = text1.replace(/\r|\n/g, " ");
	text2 = text2.replace(/\r|\n/g, " ");
	textarr1 = text1.split(/\s/g);
	textarr2 = text2.split(/\s/g);
	this.word_dict = {};
	this.charcode = 21;
	this.textnumber = 0;

	this.char_dict= {};
	textchars1 = this.words_to_characters(textarr1);
	textchars2 = this.words_to_characters(textarr2);

	var diffs = this.diff_main(textchars1, textchars2, lebool);
	var result = [];
	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];
		var encodedstring = [];
		var datarr = data.split("");
		for(var i in datarr){
			var character = datarr[i];
			var character_entry = this.char_dict[character];
			var nextword = [];
			switch(op){
				case DIFF_DELETE:
					nextword = character_entry[0][0];
					character_entry[0].splice(0,1);
					break;
				case DIFF_INSERT:
					nextword = character_entry[1][0];
					character_entry[1].splice(0,1);
					break;
				case DIFF_EQUAL:
					nextword.push(character_entry[0][0]);
					nextword.push(character_entry[1][0]);
					character_entry[0].splice(0,1);
					character_entry[1].splice(0,1);
			}
			encodedstring.push(nextword);
			i += 1;
		}
		result.push([op,encodedstring]);
	}

	return result;
};

/*

DiffHandler.prototype.abstract_script = function(diffs){
	var editscript = [];
	for (var x = 0; x < diffs.length; x++) {
		var op = diffs[x][0];    // Operation (insert, delete, equal)
		var data = diffs[x][1];  // Text of change.
		switch (op) {
			case DIFF_INSERT:
				editscript[x] = ['I',data.length];
				break;
			case DIFF_DELETE:
				editscript[x] = ['D',data.length];
				break;
			case DIFF_EQUAL:
				editscript[x] = ['E',data.length];
				break;
		}
	}
	return editscript;
};

DiffHandler.prototype.edit_symbols = function(diffs){
	var symbolstring = "";

	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];
		switch(op){
			case DIFF_INSERT:
				symbolstring += ""+data.length+"+";
				break;
			case DIFF_DELETE:
				symbolstring += ""+data.length+"-";
				break;
			case DIFF_EQUAL:
				symbolstring += ""+data.length+"=";
				break;
		}

	}
	return symbolstring;
}

DiffHandler.prototype.data_line = function(diffs){
	var dataline = [];
	var index = 0;
    var currentvalue = 0;
	for (var x = 0; x < diffs.length; x++) {
	    var op = diffs[x][0];    // Operation (insert, delete, equal)
	    var data = diffs[x][1];  // Text of change.
	    switch (op) {
	      case DIFF_INSERT:
	    	for(var i = 0; i<data.length; i++){
	    		currentvalue += 1;
	    		dataline[index] = currentvalue;
	    		index += 1;
	    	}
	        break;
	      case DIFF_DELETE:
	    	  for(var i = 0; i<data.length; i++){
		    		currentvalue -= 1;
		    		dataline[index] = currentvalue;
		    		index += 1;
		    	}
	    	  break;
	      case DIFF_EQUAL:
	    	  for(var i = 0; i<data.length; i++){
	    		  	dataline[index] = currentvalue;
		    		index += 1;
		    	}
	    	  break;
	    }
	  }
	return dataline;
}

DiffHandler.prototype.equal_sum_line = function(diffs){
	var dataline = [];
	var index = 0;
	var currentvalue = 0;
	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];

		switch(op){
			case DIFF_INSERT:
					dataline[index]=currentvalue;
					index++;

				break;
			case DIFF_DELETE:
				for (var i = 0; i < data.length; i++){
					dataline[index]=currentvalue;
					index++;
				}
				break;
			case DIFF_EQUAL:
				for (var i = 0; i < data.length; i++){
					currentvalue++;
					dataline[index]=currentvalue;
					index++;
				}
				break;
		}

	}
	return dataline;
}

DiffHandler.prototype.html_texts = function(diffs){
	var source_html = "";
	var diss_html = "";

	for(var x = 0; x < diffs.length; x++){
		var op = diffs[x][0];
		var data = diffs[x][1];

		switch(op){
			case DIFF_INSERT:
				diss_html += data;
				break;
			case DIFF_DELETE:
				source_html += data;
				break;
			case DIFF_EQUAL:
				var addstring = "" + data + ""
				diss_html += addstring;
				source_html += addstring;
				break;
		}
	}

	return {"diss_html":diss_html, "source_html":source_html};
}

*/
<|endoftext|>


<commit_before>var util = require("util");
var BaseTrigger = require("./baseTrigger.js").BaseTrigger;
var Roll = require("roll");
var dice = new Roll();
/*
Trigger that responds to messages using Wolfram Alpha.
command = string - a message must start with this + a space before a response will be given
*/

var RollTrigger = function() {
	RollTrigger.super_.apply(this, arguments);
};

util.inherits(RollTrigger, BaseTrigger);

var type = "RollTrigger";
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
	var trigger = new RollTrigger(type, name, chatBot, options);
	trigger.options.command = trigger.options.command || "!roll";
	trigger.respectsMute = false;
	return trigger;
};

// Return true if a message was sent
RollTrigger.prototype._respondToFriendMessage = function(userId, message) {
	return this._respond(null, userId, message);
}

// Return true if a message was sent
RollTrigger.prototype._respondToChatMessage = function(roomId, chatterId, message) {
	return this._respond(roomId, chatterId, message);
}

RollTrigger.prototype._respond = function(roomId, userId, message) {
	var toId = roomId || userId;

	var that = this;
	var params = that._stripCommand(message, that);
	if(params) {
		var split = params.split('d');
		console.log(split);
		if(parseInt(split[0]) === 1) {
			try {
				var rolled = dice.roll(params);
				that._sendMessageAfterDelay(toId, rolled.result.toString() + (parseInt(rolled.input.quantity) > 1 ? " ("+JSON.stringify(rolled.rolled).replace(/,/g,", ")+")" : ""));
			} catch(err) {
				that._sendMessageAfterDelay(toId, "Try using syntax from www.github.com/troygoode/node-roll");
			} return true;
		}
		else if(parseInt(split[0]) > 64 || parseInt(split[1]) > 64) {
			this._sendMessageAfterDelay(toId, 'You cannot specify a number greater than 64 on either side of the "d".');
			return true;
		}
		else {
			try {
				var rolled = dice.roll(params);
				that._sendMessageAfterDelay(toId, rolled.result.toString() + (parseInt(rolled.input.quantity) > 1 ? " ("+JSON.stringify(rolled.rolled).replace(/,/g,", ")+")" : ""));
			} catch(err) {
				that._sendMessageAfterDelay(toId, "Try using syntax from www.github.com/troygoode/node-roll");
			} return true;
		}
	}
	return false;
}

RollTrigger.prototype._stripCommand = function(message, that) {
	if (that.options.command && message && message.toLowerCase().indexOf(that.options.command.toLowerCase() + " ") === 0) {
		return message.substring(that.options.command.length + 1);
	}
	return null;
}
<commit_msg>Remove console.log<commit_after>var util = require("util");
var BaseTrigger = require("./baseTrigger.js").BaseTrigger;
var Roll = require("roll");
var dice = new Roll();
/*
Trigger that responds to messages using Wolfram Alpha.
command = string - a message must start with this + a space before a response will be given
*/

var RollTrigger = function() {
	RollTrigger.super_.apply(this, arguments);
};

util.inherits(RollTrigger, BaseTrigger);

var type = "RollTrigger";
exports.triggerType = type;
exports.create = function(name, chatBot, options) {
	var trigger = new RollTrigger(type, name, chatBot, options);
	trigger.options.command = trigger.options.command || "!roll";
	trigger.respectsMute = false;
	return trigger;
};

// Return true if a message was sent
RollTrigger.prototype._respondToFriendMessage = function(userId, message) {
	return this._respond(null, userId, message);
}

// Return true if a message was sent
RollTrigger.prototype._respondToChatMessage = function(roomId, chatterId, message) {
	return this._respond(roomId, chatterId, message);
}

RollTrigger.prototype._respond = function(roomId, userId, message) {
	var toId = roomId || userId;

	var that = this;
	var params = that._stripCommand(message, that);
	if(params) {
		var split = params.split('d');
		if(parseInt(split[0]) === 1) {
			try {
				var rolled = dice.roll(params);
				that._sendMessageAfterDelay(toId, rolled.result.toString() + (parseInt(rolled.input.quantity) > 1 ? " ("+JSON.stringify(rolled.rolled).replace(/,/g,", ")+")" : ""));
			} catch(err) {
				that._sendMessageAfterDelay(toId, "Try using syntax from www.github.com/troygoode/node-roll");
			} return true;
		}
		else if(parseInt(split[0]) > 64 || parseInt(split[1]) > 64) {
			this._sendMessageAfterDelay(toId, 'You cannot specify a number greater than 64 on either side of the "d".');
			return true;
		}
		else {
			try {
				var rolled = dice.roll(params);
				that._sendMessageAfterDelay(toId, rolled.result.toString() + (parseInt(rolled.input.quantity) > 1 ? " ("+JSON.stringify(rolled.rolled).replace(/,/g,", ")+")" : ""));
			} catch(err) {
				that._sendMessageAfterDelay(toId, "Try using syntax from www.github.com/troygoode/node-roll");
			} return true;
		}
	}
	return false;
}

RollTrigger.prototype._stripCommand = function(message, that) {
	if (that.options.command && message && message.toLowerCase().indexOf(that.options.command.toLowerCase() + " ") === 0) {
		return message.substring(that.options.command.length + 1);
	}
	return null;
}
<|endoftext|>


<commit_before>(function () {
  'use strict';

  function handler () {
    $.removeNodes('iframe');

    var node = $.$('#continuetoimage > form input');
    if (node) {
      // first pass
      node.click();
      // somehow imgrun.net need to click twice
      node.click();
      return;
    }

    // second pass
    var o = $('img[alt="image"]');
    $.openImage(o.src);
  }

  $.register({
    rule: {
      host: [
        /^(img(rill|next|savvy|\.spicyzilla|twyti)|image(corn|picsa)|www\.(imagefolks|imgblow)|hosturimage|img-zone)\.com$/,
        /^img(candy|master|-view|run)\.net$/,
        /^imgcloud\.co|pixup\.us$/,
        /^(www\.)?\.imgult\.com$/,
        /^bulkimg\.info$/,
        /^(image\.adlock|imgspot)\.org$/,
        /^img\.yt$/,
        /^vava\.in$/,
      ],
      path: /^\/img-.*\.html$/,
    },
    ready: handler,
  });

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/\d+\/img-.*\.html$/,
    },
    start: function () {
      // crack the shitty qqc.co visitScript 5440
      unsafeWindow.setTimeout = $.inject(_.nop);

      // this site checks cookie that caculate from session
      // do an AJAX to skip checking
      $.get(window.location.toString(), {}, function (data) {
        var a = $.toDOM(data);

        var bbcode = $.$('#imagecodes input', a);
        bbcode = bbcode.value.match(/.+\[IMG\]([^\[]+)\[\/IMG\].+/);
        bbcode = bbcode[1];
        bbcode = bbcode.replace('small', 'big');

        $.openImage(bbcode);
      });
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<commit_msg>08lkk.com<commit_after>(function () {
  'use strict';

  function handler () {
    $.removeNodes('iframe');

    var node = $.$('#continuetoimage > form input');
    if (node) {
      // first pass
      node.click();
      // somehow imgrun.net need to click twice
      node.click();
      return;
    }

    // second pass
    var o = $('img[alt="image"]');
    $.openImage(o.src);
  }

  $.register({
    rule: {
      host: [
        /^(img(rill|next|savvy|\.spicyzilla|twyti)|image(corn|picsa)|www\.(imagefolks|imgblow)|hosturimage|img-zone|08lkk)\.com$/,
        /^img(candy|master|-view|run)\.net$/,
        /^imgcloud\.co|pixup\.us$/,
        /^(www\.)?\.imgult\.com$/,
        /^bulkimg\.info$/,
        /^(image\.adlock|imgspot)\.org$/,
        /^img\.yt$/,
        /^vava\.in$/,
      ],
      path: /^\/img-.*\.html$/,
    },
    ready: handler,
  });

  $.register({
    rule: {
      host: /^08lkk\.com$/,
      path: /^\/\d+\/img-.*\.html$/,
    },
    start: function () {
      // crack the shitty qqc.co visitScript 5440
      unsafeWindow.setTimeout = $.inject(_.nop);

      // this site checks cookie that caculate from session
      // do an AJAX to skip checking
      $.get(window.location.toString(), {}, function (data) {
        var a = $.toDOM(data);

        var bbcode = $.$('#imagecodes input', a);
        bbcode = bbcode.value.match(/.+\[IMG\]([^\[]+)\[\/IMG\].+/);
        bbcode = bbcode[1];
        bbcode = bbcode.replace('small', 'big');

        $.openImage(bbcode);
      });
    },
  });

})();

// ex: ts=2 sts=2 sw=2 et
// sublime: tab_size 2; translate_tabs_to_spaces true; detect_indentation false; use_tab_stops true;
// kate: space-indent on; indent-width 2;
<|endoftext|>