<commit_before>function startRender(canvas, getStarsCallback) {
  var STAR_SIZE_PIXELS = 1.5;
  var DECELERATION_BLEED_RATIO_PER_TICK = 0.05; // A tick is 1/60 sec.
  var DEBUG = false;
  var timestamps = [];

  var worldOffsetX = 0; // Top left has this x coordinate in world frame.
  var worldOffsetY = 0;
  // scale of 1 means 1 world unit = 1 canvas pixel
  // scale of 100 means 1 world unit = 100 canvas pixels
  var scale = 1;

  // Used to determine whether or not to redraw.
  var lastWorldOffsetX = null;
  var lastWorldOffsetY = null;
  var lastScale = null;

  var mousedown = false;
  var isPinching = false;
  var lastMouseX;
  var lastMouseY;
  var lastScale;
  var pixelVelocityX = 0;
  var pixelVelocityY = 0;
  var lastRenderTimestamp = 0;

  canvas.style['background-color'] = 'black';

  function render(timestamp) {
    var star, stars, i, j, context, brightnessToStars, dt, ratio;

    requestAnimationFrame(render);

    timestamps.push(timestamp);
    if (timestamps.length > 10) {
      if (DEBUG) console.log(
        (10 * 1000 / (timestamps[10] - timestamps[0])).toFixed(2) + ' fps'
      );
      timestamps = [];
    }

    // deceleration
    if (lastRenderTimestamp && !mousedown) {
      dt = timestamp - lastRenderTimestamp;
      if (pixelVelocityX || pixelVelocityY) {
        worldOffsetX -= pixelVelocityX * dt / scale;
        worldOffsetY -= pixelVelocityY * dt / scale;
      }
      ratio = 1 - Math.min(
        1, DECELERATION_BLEED_RATIO_PER_TICK * dt / (1000 / 60)
      );
      pixelVelocityX *= ratio;
      pixelVelocityY *= ratio;
    }
    // Prevent redrawing
    if (Math.abs(pixelVelocityX) < 0.01 && Math.abs(pixelVelocityY) < 0.01) {
      if (DEBUG) console.log("locked");
      pixelVelocityX = 0;
      pixelVelocityY = 0;
    }
    lastRenderTimestamp = timestamp;

    if (
      (worldOffsetX === lastWorldOffsetX) &&
      (worldOffsetY === lastWorldOffsetY) &&
      (scale === lastScale)
    ) return;

    lastWorldOffsetX = worldOffsetX;
    lastWorldOffsetY = worldOffsetY;
    lastScale = scale;

    stars = getStarsCallback(
      worldOffsetX,
      worldOffsetY,
      canvas.width / scale,
      canvas.height / scale
    );

    // setting fillStyle is expensive, so quantize and batch it.
    brightnessToStars = [];
    for (i = 0; i < 100; i++) brightnessToStars.push([]);
    for (i = 0; i < stars.length; i++) {
      star = stars[i];
      brightnessToStars[Math.floor(star.brightness * 100)].push(star);
    }

    context = canvas.getContext('2d')
    context.clearRect(0, 0, canvas.width, canvas.height);

    for (i = 0; i < 100; i++) {
      context.fillStyle = 'rgba(255, 255, 255, ' + i / 100 + ')';
      stars = brightnessToStars[i];
      for (j = 0; j < stars.length; j++) {
        star = stars[j];
        context.fillRect(
          (star.worldX - worldOffsetX) * scale,
          (star.worldY - worldOffsetY) * scale,
          STAR_SIZE_PIXELS,
          STAR_SIZE_PIXELS
        );
      }
    }
  }

  requestAnimationFrame(render);

  var hammer = new Hammer.Manager(canvas)
  hammer.add(new Hammer.Pan());
  hammer.add(new Hammer.Pinch());

  hammer.on('panstart', function(e) {
    mousedown = true;
    lastMouseX = 0;
    lastMouseY = 0;
  });

  hammer.on('panmove', function(e) {
    worldOffsetX -= (e.deltaX - lastMouseX) / scale;
    worldOffsetY -= (e.deltaY - lastMouseY) / scale;
    lastMouseX = e.deltaX;
    lastMouseY = e.deltaY;
  });

  hammer.on('panend', function(e) {
    mousedown = false;
    pixelVelocityX = -e.velocityX;
    pixelVelocityY = -e.velocityY;
  });

  hammer.on('pinchstart', function(e) {
    isPinching = true;
    lastScale = 1;
    pixelVelocityX = 0;
    pixelVelocityY = 0;
  });

  hammer.on('pinchmove', function(e) {
    var rect = canvas.getBoundingClientRect();
    var scaleDelta = e.scale / lastScale;
    worldOffsetX += (e.center.x - rect.left) * (1 - 1 / scaleDelta) / scale;
    worldOffsetY += (e.center.y - rect.top) * (1 - 1 / scaleDelta) / scale;
    scale *= scaleDelta;
    lastScale = e.scale;
  });

  hammer.on('pinchend', function(e) {
    isPinching = false;
  });

  canvas.addEventListener("mousewheel", function(e) {
    var mult;
    var rect = canvas.getBoundingClientRect();
    if (e.wheelDelta > 0) mult = 1.1; else mult = 1 / 1.1;
    worldOffsetX += (e.clientX - rect.left) * (1 - 1 / mult) / scale;
    worldOffsetY += (e.clientY - rect.top) * (1 - 1 / mult) / scale;
    scale *= mult;
    pixelVelocityX = 0;
    pixelVelocityY = 0;
  }, false);

}
<commit_msg>prevent scroll<commit_after>function startRender(canvas, getStarsCallback) {
  var STAR_SIZE_PIXELS = 1.5;
  var DECELERATION_BLEED_RATIO_PER_TICK = 0.05; // A tick is 1/60 sec.
  var DEBUG = false;
  var timestamps = [];

  var worldOffsetX = 0; // Top left has this x coordinate in world frame.
  var worldOffsetY = 0;
  // scale of 1 means 1 world unit = 1 canvas pixel
  // scale of 100 means 1 world unit = 100 canvas pixels
  var scale = 1;

  // Used to determine whether or not to redraw.
  var lastWorldOffsetX = null;
  var lastWorldOffsetY = null;
  var lastScale = null;

  var mousedown = false;
  var isPinching = false;
  var lastMouseX;
  var lastMouseY;
  var lastScale;
  var pixelVelocityX = 0;
  var pixelVelocityY = 0;
  var lastRenderTimestamp = 0;

  canvas.style['background-color'] = 'black';

  function render(timestamp) {
    var star, stars, i, j, context, brightnessToStars, dt, ratio;

    requestAnimationFrame(render);

    timestamps.push(timestamp);
    if (timestamps.length > 10) {
      if (DEBUG) console.log(
        (10 * 1000 / (timestamps[10] - timestamps[0])).toFixed(2) + ' fps'
      );
      timestamps = [];
    }

    // deceleration
    if (lastRenderTimestamp && !mousedown) {
      dt = timestamp - lastRenderTimestamp;
      if (pixelVelocityX || pixelVelocityY) {
        worldOffsetX -= pixelVelocityX * dt / scale;
        worldOffsetY -= pixelVelocityY * dt / scale;
      }
      ratio = 1 - Math.min(
        1, DECELERATION_BLEED_RATIO_PER_TICK * dt / (1000 / 60)
      );
      pixelVelocityX *= ratio;
      pixelVelocityY *= ratio;
    }
    // Prevent redrawing
    if (Math.abs(pixelVelocityX) < 0.01 && Math.abs(pixelVelocityY) < 0.01) {
      if (DEBUG) console.log("locked");
      pixelVelocityX = 0;
      pixelVelocityY = 0;
    }
    lastRenderTimestamp = timestamp;

    if (
      (worldOffsetX === lastWorldOffsetX) &&
      (worldOffsetY === lastWorldOffsetY) &&
      (scale === lastScale)
    ) return;

    lastWorldOffsetX = worldOffsetX;
    lastWorldOffsetY = worldOffsetY;
    lastScale = scale;

    stars = getStarsCallback(
      worldOffsetX,
      worldOffsetY,
      canvas.width / scale,
      canvas.height / scale
    );

    // setting fillStyle is expensive, so quantize and batch it.
    brightnessToStars = [];
    for (i = 0; i < 100; i++) brightnessToStars.push([]);
    for (i = 0; i < stars.length; i++) {
      star = stars[i];
      brightnessToStars[Math.floor(star.brightness * 100)].push(star);
    }

    context = canvas.getContext('2d')
    context.clearRect(0, 0, canvas.width, canvas.height);

    for (i = 0; i < 100; i++) {
      context.fillStyle = 'rgba(255, 255, 255, ' + i / 100 + ')';
      stars = brightnessToStars[i];
      for (j = 0; j < stars.length; j++) {
        star = stars[j];
        context.fillRect(
          (star.worldX - worldOffsetX) * scale,
          (star.worldY - worldOffsetY) * scale,
          STAR_SIZE_PIXELS,
          STAR_SIZE_PIXELS
        );
      }
    }
  }

  requestAnimationFrame(render);

  var hammer = new Hammer.Manager(canvas)
  hammer.add(new Hammer.Pan());
  hammer.add(new Hammer.Pinch());

  hammer.on('panstart', function(e) {
    mousedown = true;
    lastMouseX = 0;
    lastMouseY = 0;
  });

  hammer.on('panmove', function(e) {
    worldOffsetX -= (e.deltaX - lastMouseX) / scale;
    worldOffsetY -= (e.deltaY - lastMouseY) / scale;
    lastMouseX = e.deltaX;
    lastMouseY = e.deltaY;
  });

  hammer.on('panend', function(e) {
    mousedown = false;
    pixelVelocityX = -e.velocityX;
    pixelVelocityY = -e.velocityY;
  });

  hammer.on('pinchstart', function(e) {
    isPinching = true;
    lastScale = 1;
    pixelVelocityX = 0;
    pixelVelocityY = 0;
  });

  hammer.on('pinchmove', function(e) {
    var rect = canvas.getBoundingClientRect();
    var scaleDelta = e.scale / lastScale;
    worldOffsetX += (e.center.x - rect.left) * (1 - 1 / scaleDelta) / scale;
    worldOffsetY += (e.center.y - rect.top) * (1 - 1 / scaleDelta) / scale;
    scale *= scaleDelta;
    lastScale = e.scale;
  });

  hammer.on('pinchend', function(e) {
    isPinching = false;
  });

  canvas.addEventListener("mousewheel", function(e) {
    var mult;
    var rect = canvas.getBoundingClientRect();
    if (e.wheelDelta > 0) mult = 1.1; else mult = 1 / 1.1;
    worldOffsetX += (e.clientX - rect.left) * (1 - 1 / mult) / scale;
    worldOffsetY += (e.clientY - rect.top) * (1 - 1 / mult) / scale;
    scale *= mult;
    pixelVelocityX = 0;
    pixelVelocityY = 0;
    e.preventDefault();
  }, false);

}
<|endoftext|>


<commit_before>/* ========================================================================
 * Password Strength Meter: password-strength-meter.js v0.0.1
 * ======================================================================== */

!function ($) {

  "use strict"; // jshint ;_;

 /* TOOLTIP PUBLIC CLASS DEFINITION
  * =============================== */

  var StrengthMeter = function (element, options) {
    this.init(input, strength_meter, options)
  }

  StrengthMeter.prototype = {

    constructor: StrengthMeter

  /**
   * Init plugin with input field and streng meter markup
   * @param  {jQuery} input
   * @param  {jQuery} strength_meter
   * @param  {Object} options
   *    - strength_meter_copys (Object) - Copys to be displayed
   */
  , init: function (input, strength_meter, options) {
      this.$input = $(input);
      this.$strength_meter = $(strength_meter);
      this.options = this.getOptions(options);
    }
  , getOptions: function (options) {
      options = $.extend({}, $.fn.passwordStrengthMeter.defaults, this.$input.data(), options);
      return options;
    }
  , check: function () {

    }
  };

 /* PASSWORD STRENGTH METER PLUGIN DEFINITION
  * ========================= */

  var old = $.fn.passwordStrengthMeter

  $.fn.passwordStrengthMeter = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('passwordStrengthMeter')
        , options = typeof option == 'object' && option
      if (!data) $this.data('passwordStrengthMeter', (data = new StrengthMeter(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.passwordStrengthMeter.Constructor = StrengthMeter

  $.fn.passwordStrengthMeter.defaults = {
    strength_meter_copys: {
      weak: 'Weak'
    , fair: 'Fair'
    , good: 'Good'
    , strong: 'Strong'
    }
  }

 /* PASSWORD STRENGTH METER NO CONFLICT
  * =================== */

  $.fn.passwordStrengthMeter.noConflict = function () {
    $.fn.passwordStrengthMeter = old
    return this
  }

}(window.jQuery);
<commit_msg>Added option<commit_after>/* ========================================================================
 * Password Strength Meter: password-strength-meter.js v0.0.1
 * ======================================================================== */

!function ($) {

  "use strict"; // jshint ;_;

 /* TOOLTIP PUBLIC CLASS DEFINITION
  * =============================== */

  var StrengthMeter = function (element, options) {
    this.init(input, strength_meter, options)
  }

  StrengthMeter.prototype = {

    constructor: StrengthMeter

  /**
   * Init plugin with input field and streng meter markup
   * @param  {jQuery} input
   * @param  {jQuery} strength_meter
   * @param  {Object} options
   *    - strength_meter_copys (Object) - Copys to be displayed
   */
  , init: function (input, strength_meter, options) {
      this.$input = $(input);
      this.$strength_meter = $(strength_meter);
      this.options = this.getOptions(options);
    }
  , getOptions: function (options) {
      options = $.extend({}, $.fn.passwordStrengthMeter.defaults, this.$input.data(), options);
      return options;
    }
  , check: function () {

    }
  };

 /* PASSWORD STRENGTH METER PLUGIN DEFINITION
  * ========================= */

  var old = $.fn.passwordStrengthMeter

  $.fn.passwordStrengthMeter = function (option) {
    return this.each(function () {
      var $this = $(this)
        , data = $this.data('passwordStrengthMeter')
        , options = typeof option == 'object' && option
      if (!data) $this.data('passwordStrengthMeter', (data = new StrengthMeter(this, options)))
      if (typeof option == 'string') data[option]()
    })
  }

  $.fn.passwordStrengthMeter.Constructor = StrengthMeter

  $.fn.passwordStrengthMeter.defaults = {
    strength_meter_copys: {
      weak: 'Weak'
    , fair: 'Fair'
    , good: 'Good'
    , strong: 'Strong'
    }
  , strength_meter_copys_element: 'js-strength-meter-copy'
  }

 /* PASSWORD STRENGTH METER NO CONFLICT
  * =================== */

  $.fn.passwordStrengthMeter.noConflict = function () {
    $.fn.passwordStrengthMeter = old
    return this
  }

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


<commit_before>/* @flow */

export default function({ types: t }: { types: Object }) {
  const classBodyVisitor = {
    ClassMethod(path: Object) {
      if (path.node.key.name === 'render') {
        path.node.body.body.unshift(
          t.expressionStatement(
            t.assignmentExpression('=',
              t.memberExpression(
                t.identifier('React'),
                t.identifier('createElement')
              ),
              t.identifier('this.fancyElement.bind(this)')
            )
          )
        )
      }
    }
  }

  return {
    visitor: {
      ClassExpression(path: Object, state: Object) {
        const node = path.node
        if (!node.decorators || !node.decorators.length) {
          return
        }

        // -- Validate if class is what we're looking for
        // Default to @style
        const decoratorName = state.opts.decoratorName || 'style'
        const isMotionStyle = node.decorators.some(item => {
          if (!item.expression) {
            return false
          }
          if (item.expression.type === 'Identifier' && item.expression.name === decoratorName) {
            return true
          }
          if (
            t.isCallExpression(item.expression) && t.isMemberExpression(item.expression.callee) &&
            item.expression.callee.object.name === decoratorName
          ) {
            return true
          }
          if (
            t.isMemberExpression(item.expression) && item.expression.object.name === decoratorName
          ) {
            return true
          }

          return false
        })
        // -- Add a unique var to scope and all of JSX elements
        if (isMotionStyle) {
          path.traverse(classBodyVisitor, state)
        }
      }
    }
  }
}
<commit_msg>:car: perf<commit_after>/* @flow */

export default function({ types: t }: { types: Object }) {
  const classBodyVisitor = {
    ClassMethod(path: Object) {
      if (path.node.key.name === 'render') {
        path.node.body.body.unshift(
          t.expressionStatement(
            t.assignmentExpression('=',
              t.memberExpression(
                t.identifier('React'),
                t.identifier('createElement')
              ),
              t.identifier('this.fancyElement.bind(this)')
            )
          )
        )
      }
    }
  }

  return {
    visitor: {
      ClassExpression(path: Object, state: Object) {
        const node = path.node
        if (!node.decorators || !node.decorators.length) {
          return
        }

        // -- Validate if class is what we're looking for
        // Default to @style
        const decoratorName = state.opts.decoratorName || 'style'
        const isMotionStyle = node.decorators.some(item => {
          if (!item.expression) {
            return false
          }
          if (item.expression.type === 'Identifier' && item.expression.name === decoratorName) {
            return true
          }
          if (
            item.expression.callee && t.isMemberExpression(item.expression.callee) &&
            item.expression.callee.object.name === decoratorName
          ) {
            return true
          }
          if (
            item.expression.object && item.expression.object.name === decoratorName
          ) {
            return true
          }

          return false
        })
        // -- Add a unique var to scope and all of JSX elements
        if (isMotionStyle) {
          path.traverse(classBodyVisitor, state)
        }
      }
    }
  }
}
<|endoftext|>


<commit_before>"use strict";

/* global dagreD3 */

angular.module('arethusa.depTree').directive('dependencyTree', function(state, $compile) {
  return {
    restrict: 'A',
    scope: {
      tokens: '=',
      styles: '='
    },
    link: function(scope, element, attrs) {
      // This will be needed once we manage to get this into an isolated scope
      //scope.state = state;

      function tokenPlaceholder(token) {
        return '
' + token.string + '
';
      }

      function edgePlaceholder(token) {
        var label = token.relation.label;
        var id = token.id
        // tel is for token edge label
        return '
' + label + '
';
      }

      function tokenHasCustomStyling(token) {
        var t = scope.styles[token.id] || {};
        return t.token;
      }

      function applyTokenStyling(childScope, token) {
        childScope.style = scope.styles[token.id].token;
      }

      // Struggling d3 a bit here...
      //
      // Right now this function is responsible for managing the label and
      // edge colors when a custom styling is available.
      //
      // Once the relation plugin is ready, the label will be handled by
      // a directive that is coming from there.
      //
      // The edges will stay the responsibility of this directive - and
      // they are really solved messy right now.
      // Guess one more look into the d3 API is needed.
      function applyCustomStyling() {
        var edges = vis.selectAll("g.edgePath path");
        angular.forEach(scope.styles, function(value, key) {
          if ('label' in value) {
            vis.select('#tel' + key).style({ color: 'red' });
          }
          if ('edge' in value) {
            edges.each(function(d) {
              if (key == d) {
                angular.element(this).css({ 'stroke': 'red', 'stroke-width': '1px' });
              }
            });
          }
        });
      }

      function compiledToken(token) {
        var childScope = scope.$new();
        childScope.token = token;

        // Ugly but working...
        // We replace the colorize value in our token template string.
        // If custom styles are given, we check if one is available for
        // this token. If yes, we use it, otherwise we just pass one
        // undefined which leaves the token unstyled.
        //
        // Without custom styles we let the token itself decide what color
        // it has.
        var style;
        if (scope.styles) {
          if (tokenHasCustomStyling(token)) {
            applyTokenStyling(childScope, token);
          } // else we just stay undefined
          style = 'style';
        } else {
          style = 'true';
        }
        return $compile(tokenHtml.replace('STYLE', style))(childScope)[0];
      }

      var tokenHtml = '\
        \
        \
      ';

      // Creating the node set

      // g will hold the graph and be set when new tokens are loaded,
      // vis will be it's d3 representation
      var g;
      var vis;

      function createNodes() {
        g.addNode("0000", { label: "[-]"});
        angular.forEach(scope.tokens, function(token, index) {
          g.addNode(token.id, { label: tokenPlaceholder(token) });
        });
      }

      function createEdges() {
        angular.forEach(scope.tokens, function(token, index) {
          if (token.head) {
            drawEdge(token);
          }
        });
      }

      function drawEdge(token) {
        g.addEdge(token.id, token.id, token.head.id, { label: edgePlaceholder(token) });
      }

      function updateEdge(token) {
        g.delEdge(token.id);
        drawEdge(token);
      }

      function createGraph() {
        g = new dagreD3.Digraph();
        createNodes();
        createEdges();
        render();
      }

      // Initialize the graph

      var layout = dagreD3.layout().rankDir("BT");
      var svg = d3.select(element[0]);
      svg.call(d3.behavior.zoom().on("zoom", function() {
         var ev = d3.event;
         svg.select("g")
           .attr("transform",
                 "translate(" + ev.translate + ") scale(" + ev.scale + ")");
      }));

      var renderer = new dagreD3.Renderer();

      function render() {
        vis = svg.select('g');
        renderer.layout(layout).run(g, vis);

        // Customize the graph so that it holds our directives

        vis.selectAll("div.node").append(function() {
          // This is the element we append to and we created as a placeholder
          // We clear out its text content so that we can display the content
          // of our compiled token directive.
          // The placholder has an id in the format of tphXXXX where XXXX is the id.
          this.textContent = "";
          return compiledToken(scope.tokens[this.id.slice(3)]);
        });

        // Not very elegant, but we don't want marker-end arrowheads right now
        vis.selectAll("g.edgePath path").attr('marker-end', '');
      }

      angular.forEach(scope.tokens, function(token, id) {
        var childScope = scope.$new();
        childScope.token = token.id;
        childScope.head =  token.head;
        childScope.$watch('head.id', function(newVal, oldVal) {
          // Very important to do here, otherwise the tree will
          // be render a little often on startup...
          if (newVal !== oldVal) {
            updateEdge(token);
            render();
          }
        });
      });

      scope.$watch('tokens', function(newVal, oldVal) {
        createGraph();
      });

      scope.$watch('styles', function(newVal, oldVal) {
        if (newVal !== oldVal) {
          render();
          if (newVal) {
            applyCustomStyling();
          }
        }
      });
    },
    template: '<g transform="translate(20,20)"/>'
  };
});
<commit_msg>Properly reset edge styling in dependencyTree<commit_after>"use strict";

/* global dagreD3 */

angular.module('arethusa.depTree').directive('dependencyTree', function(state, $compile) {
  return {
    restrict: 'A',
    scope: {
      tokens: '=',
      styles: '='
    },
    link: function(scope, element, attrs) {
      // This will be needed once we manage to get this into an isolated scope
      //scope.state = state;

      function tokenPlaceholder(token) {
        return '
' + token.string + '
';
      }

      function edgePlaceholder(token) {
        var label = token.relation.label;
        var id = token.id
        // tel is for token edge label
        return '
' + label + '
';
      }

      function tokenHasCustomStyling(token) {
        var t = scope.styles[token.id] || {};
        return t.token;
      }

      function applyTokenStyling(childScope, token) {
        childScope.style = scope.styles[token.id].token;
      }

      // Struggling d3 a bit here...
      //
      // Right now this function is responsible for managing the label and
      // edge colors when a custom styling is available.
      //
      // Once the relation plugin is ready, the label will be handled by
      // a directive that is coming from there.
      //
      // The edges will stay the responsibility of this directive - and
      // they are really solved messy right now.
      // Guess one more look into the d3 API is needed.
      function applyCustomStyling() {
        var edges = vis.selectAll("g.edgePath path");
        angular.forEach(scope.styles, function(value, key) {
          if ('label' in value) {
            vis.select('#tel' + key).style({ color: 'red' });
          }
          if ('edge' in value) {
            edges.each(function(d) {
              if (key == d) {
                angular.element(this).css({ 'stroke': 'red', 'stroke-width': '1px' });
              }
            });
          }
        });
      }

      function compiledToken(token) {
        var childScope = scope.$new();
        childScope.token = token;

        // Ugly but working...
        // We replace the colorize value in our token template string.
        // If custom styles are given, we check if one is available for
        // this token. If yes, we use it, otherwise we just pass one
        // undefined which leaves the token unstyled.
        //
        // Without custom styles we let the token itself decide what color
        // it has.
        var style;
        if (scope.styles) {
          if (tokenHasCustomStyling(token)) {
            applyTokenStyling(childScope, token);
          } // else we just stay undefined
          style = 'style';
        } else {
          style = 'true';
        }
        return $compile(tokenHtml.replace('STYLE', style))(childScope)[0];
      }

      var tokenHtml = '\
        \
        \
      ';

      // Creating the node set

      // g will hold the graph and be set when new tokens are loaded,
      // vis will be it's d3 representation
      var g;
      var vis;

      function createNodes() {
        g.addNode("0000", { label: "[-]"});
        angular.forEach(scope.tokens, function(token, index) {
          g.addNode(token.id, { label: tokenPlaceholder(token) });
        });
      }

      function createEdges() {
        angular.forEach(scope.tokens, function(token, index) {
          if (token.head) {
            drawEdge(token);
          }
        });
      }

      function drawEdge(token) {
        g.addEdge(token.id, token.id, token.head.id, { label: edgePlaceholder(token) });
      }

      function updateEdge(token) {
        g.delEdge(token.id);
        drawEdge(token);
      }

      function createGraph() {
        g = new dagreD3.Digraph();
        createNodes();
        createEdges();
        render();
      }

      // Initialize the graph
      function resetEdgeStyling() {
        vis.selectAll("g.edgePath path").style({ stroke: '#333', 'stroke-width': '0.5px' });
      }

      var layout = dagreD3.layout().rankDir("BT");
      var svg = d3.select(element[0]);
      svg.call(d3.behavior.zoom().on("zoom", function() {
         var ev = d3.event;
         svg.select("g")
           .attr("transform",
                 "translate(" + ev.translate + ") scale(" + ev.scale + ")");
      }));

      var renderer = new dagreD3.Renderer();

      function render() {
        vis = svg.select('g');
        renderer.layout(layout).run(g, vis);

        // Customize the graph so that it holds our directives

        vis.selectAll("div.node").append(function() {
          // This is the element we append to and we created as a placeholder
          // We clear out its text content so that we can display the content
          // of our compiled token directive.
          // The placholder has an id in the format of tphXXXX where XXXX is the id.
          this.textContent = "";
          return compiledToken(scope.tokens[this.id.slice(3)]);
        });

        // Not very elegant, but we don't want marker-end arrowheads right now
        vis.selectAll("g.edgePath path").attr('marker-end', '');
      }

      angular.forEach(scope.tokens, function(token, id) {
        var childScope = scope.$new();
        childScope.token = token.id;
        childScope.head =  token.head;
        childScope.$watch('head.id', function(newVal, oldVal) {
          // Very important to do here, otherwise the tree will
          // be render a little often on startup...
          if (newVal !== oldVal) {
            updateEdge(token);
            render();
          }
        });
      });

      scope.$watch('tokens', function(newVal, oldVal) {
        createGraph();
      });

      scope.$watch('styles', function(newVal, oldVal) {
        if (newVal !== oldVal) {
          render();
          if (newVal) {
            applyCustomStyling();
          }
        }
      });
    },
    template: '<g transform="translate(20,20)"/>'
  };
});
          } else {
            resetEdgeStyling();
<|endoftext|>


<commit_before>'use strict';
define(['app'], function (app) {

	var injectParams = ['$scope','$rootScope','$injector', '$routeParams','upload','dataService'];
  // This is controller for this view
	var addprojectController = function ($scope,$rootScope, $injector,$routeParams,upload,dataService) {
		$rootScope.metaTitle = "Real Estate Add Project";
		$scope.alerts = [];
		$scope.project = {};
		$scope.project.overview = {};
		$scope.project.overview.details = {};
		$scope.project.amenities = {};
		$scope.project.amenities.details = {};
		$scope.project.specification = {};
		$scope.project.specification.details = {};
		$scope.project.location_map = {};
		$scope.project.location_map.details = {};
		$scope.project.layout_map = {};
		$scope.project.layout_map.details = {};
		$scope.project.floor_plan = {};
		$scope.project.floor_plan.details = {};
		$scope.project.project_gallery = {};
		$scope.Date = dataService.currentDate;
		$scope.project.project_gallery.details = {};
		console.log($rootScope.userDetails);

		console.log($scope.project.user_id);
		$scope.addToObject = function(data, object){
			object[data.title] = data.description;
		}

		$scope.removeObject = function(key, object){
			delete object[key];
		}
		//add project
		$scope.reset = function() {
			$scope.project = {};
		};

		// to close alert message
		$scope.closeAlert = function(index) {
			$scope.alerts.splice(index, 1);
		};

			console.log($rootScope.userDetails);
		 // this function will generate thumbnails of images
		$scope.generateThumb = function(files){
			upload.generateThumbs(files);
		};// End upload function
		$scope.addproject = function(project){
			console.log(project,$rootScope.userDetails.status);
			$scope.user_id={ user_id:$rootScope.userDetails.id };
			//Upload Function for uploading files
			$scope.project={};

			$scope.userinfo = {user_id:$rootScope.userDetails.id};
			$scope.path = "project/"; // path to store images on server
			$scope.project.project_images  = {};

			// uploaded images will store in this array
			$scope.upload = function(files,path,userinfo,picArr){
				console.log(picArr);
				upload.upload(files,path,userinfo,function(data){
					var picArrKey = 0, x;
					for(x in picArr) picArrKey++;
					if(data.status === 'success'){
						console.log(data.details);
						picArr[picArrKey] = (JSON.stringify(data.details));
						console.log(data.message);
					}else{
						$scope.alerts.push({type: response.status, msg: response.message});
					}

				});
			};
		};
	};

	// Inject controller's dependencies
	addprojectController.$inject = injectParams;
	// Register/apply controller dynamically
    app.register.controller('addprojectController',addprojectController);

});

	<commit_msg>"addprojectController.js modified"<commit_after>'use strict';
define(['app'], function (app) {

	var injectParams = ['$scope','$rootScope','$injector', '$routeParams','upload','dataService'];
  // This is controller for this view
	var addprojectController = function ($scope,$rootScope, $injector,$routeParams,upload,dataService) {
		$rootScope.metaTitle = "Real Estate Add Project";
		$scope.alerts = [];
		$scope.project = {};
		$scope.project.overview = {};
		$scope.project.overview.details = {};
		$scope.project.amenities = {};
		$scope.project.amenities.details = {};
		$scope.project.specification = {};
		$scope.project.specification.details = {};
		$scope.project.location_map = {};
		$scope.project.location_map.details = {};
		$scope.project.layout_map = {};
		$scope.project.layout_map.details = {};
		$scope.project.floor_plan = {};
		$scope.project.floor_plan.details = {};
		$scope.project.project_gallery = {};
		$scope.date = dataService.currentDate;
		$scope.project.project_gallery.details = {};
		console.log($rootScope.userDetails);

		$scope.addToObject = function(data, object){
			object[data.title] = data.description;
		}

		$scope.removeObject = function(key, object){
			delete object[key];
		}
		//add project
		$scope.reset = function() {
			$scope.project = {};
		};

		// to close alert message
		$scope.closeAlert = function(index) {
			$scope.alerts.splice(index, 1);
		};

		$scope.user_id={id:$rootScope.userDetails.id };

		$scope.project={};
		$scope.addproject = function(project){
			//Upload Function for uploading files
			$scope.project.created_date=$scope.date;
			$scope.userinfo = {id:$rootScope.userDetails.id};
			$scope.path = "project/"; // path to store images on server
			$scope.project.project_images  = {};

			// uploaded images will store in this array
			$scope.upload = function(files,path,userinfo,picArr){
				console.log(picArr);
				upload.upload(files,path,userinfo,function(data){
					var picArrKey = 0, x;
					for(x in picArr) picArrKey++;
					if(data.status === 'success'){
						console.log(data.details);
						picArr[picArrKey] = (JSON.stringify(data.details));
						console.log(data.message);
					}else{
						$scope.alerts.push({type: response.status, msg: response.message});
					}

				});

				// this function will generate thumbnails of images
				$scope.generateThumb = function(files){
					upload.generateThumbs(files);
				};

			};
		};
	};

	// Inject controller's dependencies
	addprojectController.$inject = injectParams;
	// Register/apply controller dynamically
    app.register.controller('addprojectController',addprojectController);

});

	<|endoftext|>


<commit_before>'use strict';

/**
 */
angular.module('openolitor-admin')
  .controller('ReportsDetailController', ['$scope', '$rootScope', '$filter', '$routeParams',
    '$location', '$uibModal', 'gettext', 'ReportsModel', '$log', 'NgTableParams', 'lodash',
    function($scope, $rootScope, $filter, $routeParams, $location, $uibModal, gettext, ReportsModel, $log, NgTableParams, lodash) {
      $rootScope.viewId = 'D-Rept';

      $scope.isModifying = false;

      $scope.result = {
        entries: []
      }
      $scope.cols = [];

      var defaults = {
        model: {
          id: undefined
        }
      };

      $scope.search = {
        query: ''
      };

      if (!$routeParams.id || $routeParams.id === 'new') {
        $scope.isModifying = true;
        $scope.report = new ReportsModel(defaults.model);
      } else {
        ReportsModel.get({
          id: $routeParams.id
        }, function(result) {
          result.query = sqlFormatter.format(result.query);
          $scope.report = result;
        });
      }

      $scope.isExisting = function() {
        return angular.isDefined($scope.report) && angular.isDefined($scope.report.id);
      };

      $scope.renderedInput = function($scope, row) {
        if (row[this.field] !== null) {
          if (/kundeid|kunde_id|kunde-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/zusatz-abo-id|zusatz_abo_id|zusatzaboid|zusatzabo_id|zusatzabo-id/.test(this.field.toLowerCase())) {
            return row[this.field];
          } else if (/abotypid|abotyp_id|abotyp-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/aboid|abo_id|abo-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/tourid|tour_id|tour-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/depotid|depot_id|depot-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/produzentid|produzent_id|produzent-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else {
            return row[this.field];
          }
        }
        return row[this.field];
      };

      $scope.renderedTitles = function(key) {
        if (key !== null) {
          if (/kundeid|kunde_id|kunde-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/zusatz-abo-id|zusatz_abo_id|zusatzaboid|zusatzabo_id|zusatzabo-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/aboid|abo_id|abo-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/personid|person_id|person-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/rechnungpositionid|rechnungposition_id|rechnungposition-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/einkaufsrechnungid|einkaufsrechnung_id|einkaufsrechnung-id|sammelbestellungid|sammelbestellung-id|sammelbestellung_id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/rechnung_id|rechnungId|rechnung-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else {
            return '' + key + '';
          }
        }
        return '' + key + '';
      };

      $scope.executeReport = function() {
        $scope.result = {};
        ReportsModel.executeReport({
          id: $scope.report.id,
          query: $scope.report.query
        }, function(data) {
          if (data && data[0]) {
            $scope.cols = [];
            for (var key in data[0]) {
              if (key.indexOf('$') !== 0 && key !== 'toJSON') {
                $scope.cols.push({
                  field: key,
                  getValue: $scope.renderedInput
                });
              }
            }
          }
          if (!$scope.result || !$scope.result.entries) {
            $scope.result.entries = data;
            $scope.tableParams.reload();
          }
        });
      };

      if (!$scope.tableParams) {
        //use default tableParams
        $scope.tableParams = new NgTableParams({ // jshint ignore:line
          page: 1,
          count: 10,
        }, {
          filterDelay: 0,
          groupOptions: {
            isExpanded: true
          },
          exportODSModel: ReportsModel,
          exportODSFilter: function() {
            return {
              id: $scope.report.id,
              query: $scope.report.query
            };
          },
          getData: function(params) {
            if (!$scope.result || !$scope.result.entries) {
              return;
            }
            // use build-in angular filter
            var dataSet = $filter('filter')($scope.result.entries, $scope.search.query);
            // also filter by ngtable filters
            dataSet = $filter('filter')(dataSet, params.filter());

            params.total(dataSet.length);
            return dataSet.slice((params.page() - 1) * params.count(), params.page() * params.count());
          }
        });
      }

      $scope.save = function() {
        return $scope.report.$save(function() {
          $scope.isModifying = false;
          $scope.reportForm.$setPristine();
        });
      };

      $scope.created = function(id) {
        $location.path('/reports/' + id);
      };

      $scope.backToList = function() {
        $location.path('/reports');
      };

      $scope.delete = function() {
        return $scope.report.$delete();
      };

      $scope.changeReport = function() {
        $scope.result.entries = [];
      };
    }
  ]);<commit_msg>dropped the additional params<commit_after>'use strict';

/**
 */
angular.module('openolitor-admin')
  .controller('ReportsDetailController', ['$scope', '$rootScope', '$filter', '$routeParams',
    '$location', '$uibModal', 'gettext', 'ReportsModel', '$log', 'NgTableParams', 'lodash',
    function($scope, $rootScope, $filter, $routeParams, $location, $uibModal, gettext, ReportsModel, $log, NgTableParams, lodash) {
      $rootScope.viewId = 'D-Rept';

      $scope.isModifying = false;

      $scope.result = {
        entries: []
      }
      $scope.cols = [];

      var defaults = {
        model: {
          id: undefined
        }
      };

      $scope.search = {
        query: ''
      };

      if (!$routeParams.id || $routeParams.id === 'new') {
        $scope.isModifying = true;
        $scope.report = new ReportsModel(defaults.model);
      } else {
        ReportsModel.get({
          id: $routeParams.id
        }, function(result) {
          result.query = sqlFormatter.format(result.query);
          $scope.report = result;
        });
      }

      $scope.isExisting = function() {
        return angular.isDefined($scope.report) && angular.isDefined($scope.report.id);
      };

      $scope.renderedInput = function($scope, row) {
        if (row[this.field] !== null) {
          if (/kundeid|kunde_id|kunde-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/zusatz-abo-id|zusatz_abo_id|zusatzaboid|zusatzabo_id|zusatzabo-id/.test(this.field.toLowerCase())) {
            return row[this.field];
          } else if (/abotypid|abotyp_id|abotyp-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/aboid|abo_id|abo-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/tourid|tour_id|tour-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/depotid|depot_id|depot-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else if (/produzentid|produzent_id|produzent-id/.test(this.field.toLowerCase())) {
            return '' + row[this.field] + '';
          } else {
            return row[this.field];
          }
        }
        return row[this.field];
      };

      $scope.renderedTitles = function(key) {
        if (key !== null) {
          if (/kundeid|kunde_id|kunde-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/zusatz-abo-id|zusatz_abo_id|zusatzaboid|zusatzabo_id|zusatzabo-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/aboid|abo_id|abo-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/personid|person_id|person-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/rechnungpositionid|rechnungposition_id|rechnungposition-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/einkaufsrechnungid|einkaufsrechnung_id|einkaufsrechnung-id|sammelbestellungid|sammelbestellung-id|sammelbestellung_id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else if (/rechnung_id|rechnungId|rechnung-id/.test(key.toLowerCase())) {
            var items = lodash.map($scope.result.entries, key);
            var uniqueItems = lodash.reject(lodash.uniq(items), _.isEmpty);
            return '' + key + '';
          } else {
            return '' + key + '';
          }
        }
        return '' + key + '';
      };

      $scope.executeReport = function() {
        $scope.result = {};
        ReportsModel.executeReport({
          id: $scope.report.id,
          query: $scope.report.query
        }, function(data) {
          if (data && data[0]) {
            $scope.cols = [];
            for (var key in data[0]) {
              if (key.indexOf('$') !== 0 && key !== 'toJSON') {
                $scope.cols.push({
                  field: key,
                  getValue: $scope.renderedInput
                });
              }
            }
          }
          if (!$scope.result || !$scope.result.entries) {
            $scope.result.entries = data;
            $scope.tableParams.reload();
          }
        });
      };

      if (!$scope.tableParams) {
        //use default tableParams
        $scope.tableParams = new NgTableParams({ // jshint ignore:line
          page: 1,
          count: 10,
        }, {
          filterDelay: 0,
          groupOptions: {
            isExpanded: true
          },
          exportODSModel: ReportsModel,
          exportODSFilter: function() {
            return {
              id: $scope.report.id,
              query: $scope.report.query
            };
          },
          getData: function(params) {
            if (!$scope.result || !$scope.result.entries) {
              return;
            }
            // use build-in angular filter
            var dataSet = $filter('filter')($scope.result.entries, $scope.search.query);
            // also filter by ngtable filters
            dataSet = $filter('filter')(dataSet, params.filter());

            params.total(dataSet.length);
            return dataSet.slice((params.page() - 1) * params.count(), params.page() * params.count());
          }
        });
      }

      $scope.save = function() {
        return $scope.report.$save(function() {
          $scope.isModifying = false;
          $scope.reportForm.$setPristine();
        });
      };

      $scope.created = function(id) {
        $location.path('/reports/' + id);
      };

      $scope.backToList = function() {
        $location.path('/reports');
      };

      $scope.delete = function() {
        return $scope.report.$delete();
      };

      $scope.changeReport = function() {
        $scope.result.entries = [];
      };
    }
  ]);<|endoftext|>


<commit_before>
<commit_msg>remove unused file<commit_after><|endoftext|>


<commit_before>// Generated on 2015-02-15 using
// generator-webapp 0.5.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// If you want to recursively match all subfolders, use:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Configurable paths
  var config = {
    app: 'app',
    dist: 'dist'
  };

  var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest ;

  var singlePage = function(req, res, next) {
    var url = req.url;
    if (/^\/app\//.test(url)) {
      req.url = '/';
    }
    return next();
  };

  // Define the configuration for all the tasks
  grunt.option("force",true);
  grunt.initConfig({

    // Project settings
    config: config,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= config.app %>/scripts/{,*/}*.js'],
        tasks: ['jshint'],
        options: {
          livereload: true
        }
      },
      jstest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['test:watch']
      },
      jade: {
        files: [
          '<%= config.app %>/*.jade',
          '<%= config.app %>/jade/{,*/}*.jade'
        ],
        tasks: ['jade:compile']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      less: {
        files: ['<%= config.app %>/styles/{,*/}*.less'],
        tasks: ['less:server', 'autoprefixer']
      },
      styles: {
        files: ['<%= config.app %>/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= config.app %>/images/{,*/}*',
          '.tmp/{,*/}*.html',
          '.tmp/styles/{,*/}*.css'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        open: true,
        livereload: 35729,
        // Change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      proxies: [{
        context: ['/api/v1', '/topic', '/chat', '/dionysus'],
        host: 'localhost',
        port: 8080,
        https: false,
        changeOrigin: true
      }],
      livereload: {
        options: {
          middleware: function(connect) {
            return [
              singlePage,
              proxySnippet,
              connect.static('.tmp'),
              connect().use('/bower_components', connect.static('./bower_components')),
              connect.static(config.app)
            ];
          }
        }
      },
      test: {
        options: {
          open: false,
          port: 9001,
          middleware: function(connect) {
            return [
              connect.static('test'),
              connect.static('.tmp'),
              connect().use('/bower_components', connect.static('./bower_components')),
              connect.static(config.app)
            ];
          }
        }
      },
      dist: {
        options: {
          base: '<%= config.dist %>',
          livereload: false
        }
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= config.dist %>/*',
            '!<%= config.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= config.app %>/scripts/{,*/}*.js',
        '!<%= config.app %>/scripts/vendor/*',
        'test/spec/{,*/}*.js'
      ]
    },

    // Mocha testing framework configuration options
    mocha: {
      all: {
        options: {
          run: true,
          urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/test.html']
        }
      }
    },

    less: {
      options: {
        paths: ['./bower_components'],
      },
      dist: {
        options: {
          cleancss: true,
          report: 'gzip'
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>/styles',
          src: '*.less',
          dest: '.tmp/styles',
          ext: '.css'
        }]
      },
      server: {
        options: {
          sourceMap: true,
          sourceMapBasepath: '<%= config.app %>/',
          sourceMapRootpath: '../'
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>/styles',
          src: '*.less',
          dest: '.tmp/styles',
          ext: '.css'
        }]
      }
    },
    jade: {
      compile: {
        options: {
          client: false,
          pretty: true
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>',
          src: 'index.jade',
          dest: '.tmp',
          ext: '.html'
        }]
      }
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the HTML file
    wiredep: {
      app: {
        ignorePath: /^\/|\.\.\//,
        src: [ '<%= config.app %>/index.jade' ]
      },
      less: {
        src: ['<%= config.app %>/styles/{,*/}*.less'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= config.dist %>/scripts/{,*/}*.js',
            '<%= config.dist %>/styles/{,*/}*.css',
            '<%= config.dist %>/images/{,*/}*.*',
            '<%= config.dist %>/font/{,*/}*.*',
            '<%= config.dist %>/*.{ico,png}'
          ]
        }
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      options: {
        dest: '<%= config.dist %>'
      },
      html: '.tmp/index.html'
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      options: {
        assetsDirs: [
          '<%= config.dist %>',
          '<%= config.dist %>/images',
          '<%= config.dist %>/styles'
        ]
      },
      html: [
        '.tmp/{,*/}*.html'
      ],
      css: [
        '<%= config.dist %>/styles/{,*/}*.css',
        '.tmp/styles/{,*/}*.css'
      ]
    },

    // The following *-min tasks produce minified files in the dist folder
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= config.app %>/images',
          src: '{,*/}*.{gif,jpeg,jpg,png}',
          dest: '<%= config.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= config.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= config.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseBooleanAttributes: true,
          collapseWhitespace: true,
          conservativeCollapse: true,
          removeAttributeQuotes: true,
          removeCommentsFromCDATA: true,
          removeEmptyAttributes: true,
          removeOptionalTags: true,
          removeRedundantAttributes: true,
          useShortDoctype: true
        },
        files: [{
          expand: true,
          cwd: '.tmp',
          src: '{,*/}*.html',
          dest: '<%= config.dist %>'
        }]
      }
    },

    // By default, your `index.html`'s <!-- Usemin block --> will take care
    // of minification. These next options are pre-configured if you do not
    // wish to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= config.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css',
    //         '<%= config.app %>/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= config.dist %>/scripts/scripts.js': [
    //         '<%= config.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.app %>',
          dest: '<%= config.dist %>',
          src: [
            '*.{ico,png,txt}',
            'images/{,*/}*.webp',
            '{,*/}*.html',
            'styles/fonts/{,*/}*.*',
            'public/{,*/}*.*'
          ]
        }, {
          src: 'node_modules/apache-server-configs/dist/.htaccess',
          dest: '<%= config.dist %>/.htaccess'
        }, {
          expand: true,
          cwd: 'bower_components/materialize/dist',
          src: 'font/{,*/}*.*',
          dest: '<%= config.dist %>'
        }]
      },
      styles: {
        expand: true,
        dot: true,
        cwd: '<%= config.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Generates a custom Modernizr build that includes only the tests you
    // reference in your app
    modernizr: {
      dist: {
        devFile: 'bower_components/modernizr/modernizr.js',
        outputFile: '<%= config.dist %>/scripts/modernizr.js',
        files: {
          src: [
            '<%= config.dist %>/scripts/{,*/}*.js',
            '<%= config.dist %>/styles/{,*/}*.css',
            '!<%= config.dist %>/scripts/vendor/*'
          ]
        },
        uglify: true
      }
    },

    // Run some tasks in parallel to speed up build process
    concurrent: {
      server: [
        'less:server',
        'copy:styles',
        'jade:compile'
      ],
      test: [
        'copy:styles'
      ],
      dist: [
        'less:dist',
        'copy:styles',
        'imagemin',
        'svgmin'
      ]
    }
  });

  grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
    if (grunt.option('allow-remote')) {
      grunt.config.set('connect.options.hostname', '0.0.0.0');
    }
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'configureProxies:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run([target ? ('serve:' + target) : 'serve']);
  });

  grunt.registerTask('test', function (target) {
    if (target !== 'watch') {
      grunt.task.run([
        'clean:server',
        'concurrent:test',
        'autoprefixer'
      ]);
    }

    grunt.task.run([
      'connect:test',
      'mocha'
    ]);
  });

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'jade:compile',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'cssmin',
    'uglify',
    'copy:dist',
    'modernizr',
    'rev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<commit_msg>revert mischange in file Gruntfile.js that only changed in local environment<commit_after>// Generated on 2015-02-15 using
// generator-webapp 0.5.1
'use strict';

// # Globbing
// for performance reasons we're only matching one level down:
// 'test/spec/{,*/}*.js'
// If you want to recursively match all subfolders, use:
// 'test/spec/**/*.js'

module.exports = function (grunt) {

  // Time how long tasks take. Can help when optimizing build times
  require('time-grunt')(grunt);

  // Load grunt tasks automatically
  require('load-grunt-tasks')(grunt);

  // Configurable paths
  var config = {
    app: 'app',
    dist: 'dist'
  };

  var proxySnippet = require('grunt-connect-proxy/lib/utils').proxyRequest ;

  var singlePage = function(req, res, next) {
    var url = req.url;
    if (/^\/app\//.test(url)) {
      req.url = '/';
    }
    return next();
  };

  // Define the configuration for all the tasks
  grunt.initConfig({

    // Project settings
    config: config,

    // Watches files for changes and runs tasks based on the changed files
    watch: {
      bower: {
        files: ['bower.json'],
        tasks: ['wiredep']
      },
      js: {
        files: ['<%= config.app %>/scripts/{,*/}*.js'],
        tasks: ['jshint'],
        options: {
          livereload: true
        }
      },
      jstest: {
        files: ['test/spec/{,*/}*.js'],
        tasks: ['test:watch']
      },
      jade: {
        files: [
          '<%= config.app %>/*.jade',
          '<%= config.app %>/jade/{,*/}*.jade'
        ],
        tasks: ['jade:compile']
      },
      gruntfile: {
        files: ['Gruntfile.js']
      },
      less: {
        files: ['<%= config.app %>/styles/{,*/}*.less'],
        tasks: ['less:server', 'autoprefixer']
      },
      styles: {
        files: ['<%= config.app %>/styles/{,*/}*.css'],
        tasks: ['newer:copy:styles', 'autoprefixer']
      },
      livereload: {
        options: {
          livereload: '<%= connect.options.livereload %>'
        },
        files: [
          '<%= config.app %>/images/{,*/}*',
          '.tmp/{,*/}*.html',
          '.tmp/styles/{,*/}*.css'
        ]
      }
    },

    // The actual grunt server settings
    connect: {
      options: {
        port: 9000,
        open: true,
        livereload: 35729,
        // Change this to '0.0.0.0' to access the server from outside
        hostname: 'localhost'
      },
      proxies: [{
        context: ['/api/v1', '/topic', '/chat', '/dionysus'],
        host: 'localhost',
        port: 8080,
        https: false,
        changeOrigin: true
      }],
      livereload: {
        options: {
          middleware: function(connect) {
            return [
              singlePage,
              proxySnippet,
              connect.static('.tmp'),
              connect().use('/bower_components', connect.static('./bower_components')),
              connect.static(config.app)
            ];
          }
        }
      },
      test: {
        options: {
          open: false,
          port: 9001,
          middleware: function(connect) {
            return [
              connect.static('test'),
              connect.static('.tmp'),
              connect().use('/bower_components', connect.static('./bower_components')),
              connect.static(config.app)
            ];
          }
        }
      },
      dist: {
        options: {
          base: '<%= config.dist %>',
          livereload: false
        }
      }
    },

    // Empties folders to start fresh
    clean: {
      dist: {
        files: [{
          dot: true,
          src: [
            '.tmp',
            '<%= config.dist %>/*',
            '!<%= config.dist %>/.git*'
          ]
        }]
      },
      server: '.tmp'
    },

    // Make sure code styles are up to par and there are no obvious mistakes
    jshint: {
      options: {
        jshintrc: '.jshintrc',
        reporter: require('jshint-stylish')
      },
      all: [
        'Gruntfile.js',
        '<%= config.app %>/scripts/{,*/}*.js',
        '!<%= config.app %>/scripts/vendor/*',
        'test/spec/{,*/}*.js'
      ]
    },

    // Mocha testing framework configuration options
    mocha: {
      all: {
        options: {
          run: true,
          urls: ['http://<%= connect.test.options.hostname %>:<%= connect.test.options.port %>/test.html']
        }
      }
    },

    less: {
      options: {
        paths: ['./bower_components'],
      },
      dist: {
        options: {
          cleancss: true,
          report: 'gzip'
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>/styles',
          src: '*.less',
          dest: '.tmp/styles',
          ext: '.css'
        }]
      },
      server: {
        options: {
          sourceMap: true,
          sourceMapBasepath: '<%= config.app %>/',
          sourceMapRootpath: '../'
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>/styles',
          src: '*.less',
          dest: '.tmp/styles',
          ext: '.css'
        }]
      }
    },
    jade: {
      compile: {
        options: {
          client: false,
          pretty: true
        },
        files: [{
          expand: true,
          cwd: '<%= config.app %>',
          src: 'index.jade',
          dest: '.tmp',
          ext: '.html'
        }]
      }
    },

    // Add vendor prefixed styles
    autoprefixer: {
      options: {
        browsers: ['> 1%', 'last 2 versions', 'Firefox ESR', 'Opera 12.1']
      },
      dist: {
        files: [{
          expand: true,
          cwd: '.tmp/styles/',
          src: '{,*/}*.css',
          dest: '.tmp/styles/'
        }]
      }
    },

    // Automatically inject Bower components into the HTML file
    wiredep: {
      app: {
        ignorePath: /^\/|\.\.\//,
        src: [ '<%= config.app %>/index.jade' ]
      },
      less: {
        src: ['<%= config.app %>/styles/{,*/}*.less'],
        ignorePath: /(\.\.\/){1,2}bower_components\//
      }
    },

    // Renames files for browser caching purposes
    rev: {
      dist: {
        files: {
          src: [
            '<%= config.dist %>/scripts/{,*/}*.js',
            '<%= config.dist %>/styles/{,*/}*.css',
            '<%= config.dist %>/images/{,*/}*.*',
            '<%= config.dist %>/font/{,*/}*.*',
            '<%= config.dist %>/*.{ico,png}'
          ]
        }
      }
    },

    // Reads HTML for usemin blocks to enable smart builds that automatically
    // concat, minify and revision files. Creates configurations in memory so
    // additional tasks can operate on them
    useminPrepare: {
      options: {
        dest: '<%= config.dist %>'
      },
      html: '.tmp/index.html'
    },

    // Performs rewrites based on rev and the useminPrepare configuration
    usemin: {
      options: {
        assetsDirs: [
          '<%= config.dist %>',
          '<%= config.dist %>/images',
          '<%= config.dist %>/styles'
        ]
      },
      html: [
        '.tmp/{,*/}*.html'
      ],
      css: [
        '<%= config.dist %>/styles/{,*/}*.css',
        '.tmp/styles/{,*/}*.css'
      ]
    },

    // The following *-min tasks produce minified files in the dist folder
    imagemin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= config.app %>/images',
          src: '{,*/}*.{gif,jpeg,jpg,png}',
          dest: '<%= config.dist %>/images'
        }]
      }
    },

    svgmin: {
      dist: {
        files: [{
          expand: true,
          cwd: '<%= config.app %>/images',
          src: '{,*/}*.svg',
          dest: '<%= config.dist %>/images'
        }]
      }
    },

    htmlmin: {
      dist: {
        options: {
          collapseBooleanAttributes: true,
          collapseWhitespace: true,
          conservativeCollapse: true,
          removeAttributeQuotes: true,
          removeCommentsFromCDATA: true,
          removeEmptyAttributes: true,
          removeOptionalTags: true,
          removeRedundantAttributes: true,
          useShortDoctype: true
        },
        files: [{
          expand: true,
          cwd: '.tmp',
          src: '{,*/}*.html',
          dest: '<%= config.dist %>'
        }]
      }
    },

    // By default, your `index.html`'s <!-- Usemin block --> will take care
    // of minification. These next options are pre-configured if you do not
    // wish to use the Usemin blocks.
    // cssmin: {
    //   dist: {
    //     files: {
    //       '<%= config.dist %>/styles/main.css': [
    //         '.tmp/styles/{,*/}*.css',
    //         '<%= config.app %>/styles/{,*/}*.css'
    //       ]
    //     }
    //   }
    // },
    // uglify: {
    //   dist: {
    //     files: {
    //       '<%= config.dist %>/scripts/scripts.js': [
    //         '<%= config.dist %>/scripts/scripts.js'
    //       ]
    //     }
    //   }
    // },
    // concat: {
    //   dist: {}
    // },

    // Copies remaining files to places other tasks can use
    copy: {
      dist: {
        files: [{
          expand: true,
          dot: true,
          cwd: '<%= config.app %>',
          dest: '<%= config.dist %>',
          src: [
            '*.{ico,png,txt}',
            'images/{,*/}*.webp',
            '{,*/}*.html',
            'styles/fonts/{,*/}*.*',
            'public/{,*/}*.*'
          ]
        }, {
          src: 'node_modules/apache-server-configs/dist/.htaccess',
          dest: '<%= config.dist %>/.htaccess'
        }, {
          expand: true,
          cwd: 'bower_components/materialize/dist',
          src: 'font/{,*/}*.*',
          dest: '<%= config.dist %>'
        }]
      },
      styles: {
        expand: true,
        dot: true,
        cwd: '<%= config.app %>/styles',
        dest: '.tmp/styles/',
        src: '{,*/}*.css'
      }
    },

    // Generates a custom Modernizr build that includes only the tests you
    // reference in your app
    modernizr: {
      dist: {
        devFile: 'bower_components/modernizr/modernizr.js',
        outputFile: '<%= config.dist %>/scripts/modernizr.js',
        files: {
          src: [
            '<%= config.dist %>/scripts/{,*/}*.js',
            '<%= config.dist %>/styles/{,*/}*.css',
            '!<%= config.dist %>/scripts/vendor/*'
          ]
        },
        uglify: true
      }
    },

    // Run some tasks in parallel to speed up build process
    concurrent: {
      server: [
        'less:server',
        'copy:styles',
        'jade:compile'
      ],
      test: [
        'copy:styles'
      ],
      dist: [
        'less:dist',
        'copy:styles',
        'imagemin',
        'svgmin'
      ]
    }
  });

  grunt.registerTask('serve', 'start the server and preview your app, --allow-remote for remote access', function (target) {
    if (grunt.option('allow-remote')) {
      grunt.config.set('connect.options.hostname', '0.0.0.0');
    }
    if (target === 'dist') {
      return grunt.task.run(['build', 'connect:dist:keepalive']);
    }

    grunt.task.run([
      'clean:server',
      'wiredep',
      'concurrent:server',
      'configureProxies:server',
      'autoprefixer',
      'connect:livereload',
      'watch'
    ]);
  });

  grunt.registerTask('server', function (target) {
    grunt.log.warn('The `server` task has been deprecated. Use `grunt serve` to start a server.');
    grunt.task.run([target ? ('serve:' + target) : 'serve']);
  });

  grunt.registerTask('test', function (target) {
    if (target !== 'watch') {
      grunt.task.run([
        'clean:server',
        'concurrent:test',
        'autoprefixer'
      ]);
    }

    grunt.task.run([
      'connect:test',
      'mocha'
    ]);
  });

  grunt.registerTask('build', [
    'clean:dist',
    'wiredep',
    'jade:compile',
    'useminPrepare',
    'concurrent:dist',
    'autoprefixer',
    'concat',
    'cssmin',
    'uglify',
    'copy:dist',
    'modernizr',
    'rev',
    'usemin',
    'htmlmin'
  ]);

  grunt.registerTask('default', [
    'newer:jshint',
    'test',
    'build'
  ]);
};
<|endoftext|>


<commit_before>/*
 * Rusha, a JavaScript implementation of the Secure Hash Algorithm, SHA-1,
 * as defined in FIPS PUB 180-1, tuned for high performance with large inputs.
 * (http://github.com/srijs/rusha)
 *
 * Inspired by Paul Johnstons implementation (http://pajhome.org.uk/crypt/md5).
 *
 * Copyright (c) 2013 Sam Rijs (http://awesam.de).
 * Released under the terms of the MIT license as follows:
 *
 * 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.
 */

(function () {

  // If we'e running in Node.JS, export a module.
  if (typeof module !== 'undefined') {
    module.exports = Rusha;
  }

  // If we're running in a DOM context, export
  // the Rusha object to toplevel.
  if (typeof window !== 'undefined') {
    window.Rusha = Rusha;
  }

  // If we're running in a webworker, accept
  // messages containing a jobid and a buffer
  // or blob object, and return the hash result.
  if (typeof FileReaderSync !== 'undefined') {
    var reader = new FileReaderSync(),
        hasher = new Rusha(4 * 1024 * 1024);
    self.onmessage = function onMessage (event) {
      var hash, data = event.data.data;
      if (data instanceof Blob) {
        try {
          data = reader.readAsBinaryString(data);
        } catch (e) {
          self.postMessage({id: event.data.id, error: e.name});
          return;
        }
      }
      hash = hasher.digest(data);
      self.postMessage({id: event.data.id, hash: hash});
    };
  }

  // The Rusha object is a wrapper around the low-level RushaCore.
  // It provides means of converting different inputs to the
  // format accepted by RushaCore as well as other utility methods.
  function Rusha (sizeHint) {
    "use strict";

    // Private object structure.
    var self = {fill: 0};

    // Calculate the length of buffer that the sha1 routine uses
    // including the padding.
    var padlen = function (len) {
      return len + 1 + ((len ) % 64 < 56 ? 56 : 56 + 64) - (len ) % 64 + 8;
    };

    var padZeroes = function (bin, len) {
      for (var i = len >> 2; i < bin.length; i++) bin[i] = 0;
    };

    var padData = function (bin, len) {
      bin[len>>2] |= 0x80 << (24 - (len % 4 << 3));
      bin[(((len >> 2) + 2) & ~0x0f) + 15] = len << 3;
    };

    // Convert a binary string to a big-endian Int32Array using
    // four characters per slot and pad it per the sha1 spec.
    // A binary string is expected to only contain char codes < 256.
    var convStr = function (str, bin, len) {
      var i;
      for (i = 0; i < len; i = i + 4 |0) {
        bin[i>>2] = str.charCodeAt(i)   << 24 |
                    str.charCodeAt(i+1) << 16 |
                    str.charCodeAt(i+2) <<  8 |
                    str.charCodeAt(i+3);
      }
    };

    // Convert a buffer or array to a big-endian Int32Array using
    // four elements per slot and pad it per the sha1 spec.
    // The buffer or array is expected to only contain elements < 256.
    var convBuf = function (buf, bin, len) {
      var i, m = len % 4, j = len - m;
      for (i = 0; i < j; i = i + 4 |0) {
        bin[i>>2] = buf[i]   << 24 |
                    buf[i+1] << 16 |
                    buf[i+2] <<  8 |
                    buf[i+3];
      }
      switch (m) {
        case 0: bin[j>>2] |= buf[j+3];
        case 3: bin[j>>2] |= buf[j+2] << 8;
        case 2: bin[j>>2] |= buf[j+1] << 16;
        case 1: bin[j>>2] |= buf[j]   << 24;
      }
    };

    // Convert general data to a big-endian Int32Array written on the
    // heap and return it's length;
    var conv = function (data, bin, len) {
      if (typeof data === 'string') {
        return convStr(data, bin, len);
      } else if (data instanceof Array || (typeof global !== 'undefined' &&
                                           typeof global.Buffer !== 'undefined' &&
                                           global.Buffer.isBuffer(data))) {
        return convBuf(data, bin, len);
      } else if (data instanceof ArrayBuffer) {
        return convBuf(new Uint8Array(data), bin, len);
      } else if (data.buffer instanceof ArrayBuffer) {
        return convBuf(new Uint8Array(data.buffer), bin, len);
      } else {
        throw new Error('Unsupported data type.');
      }
    };

    // Convert an ArrayBuffer into its hexadecimal string representation.
    var hex = function (arrayBuffer) {
      var i, x, hex_tab = "0123456789abcdef", res = [], binarray = new Uint8Array(arrayBuffer);
      for (i = 0; i < binarray.length; i++) {
        x = binarray[i];
        res[i] = hex_tab.charAt((x >>  4) & 0xF) +
                 hex_tab.charAt((x >>  0) & 0xF);
      }
      return res.join('');
    };

    var ceilHeapSize = function (v) {
      // The asm.js spec says:
      // The heap object's byteLength must be either
      // 2^n for n in [12, 24) or 2^24 * n for n ≥ 1.
      var p;
      // If v is smaller than 2^12, the smallest possible solution
      // is 2^12.
      if (v <= 4096) return 4096;
      // If v < 2^24, we round up to 2^n,
      // otherwise we round up to 2^24 * n.
      if (v < 16777216) {
        for (p = 1; p < v; p = p << 1);
      } else {
        for (p = 16777216; p < v; p += 16777216);
      }
      return p;
    };

    // Resize the internal data structures to a new capacity.
    var resize = function (size) {
      self.sizeHint = size;
      self.heap     = new ArrayBuffer(ceilHeapSize(padlen(size) + 320));
      self.core     = RushaCore({Int32Array: Int32Array, DataView: DataView}, {}, self.heap);
    };

    // On initialize, resize the datastructures according
    // to an optional size hint.
    resize(sizeHint || 0);

    // Initialize and call the RushaCore,
    // assuming an input buffer of length len * 4.
    var coreCall = function (len) {
      var h = new Int32Array(self.heap, len << 2, 5);
      h[0] =  1732584193;
      h[1] =  -271733879;
      h[2] = -1732584194;
      h[3] =   271733878;
      h[4] = -1009589776;
      self.core.hash(len);
    };

    // Calculate the hash digest as an array of 5 32bit integers.
    var rawDigest = this.rawDigest = function (str) {
      var len = str.byteLength || str.length;
      if (len > self.sizeHint) {
        resize(len);
      }
      var view = new Int32Array(self.heap, 0, padlen(len) >> 2);
      padZeroes(view, len);
      conv(str, view, len);
      padData(view, len);
      coreCall(view.length);
      var out = new Int32Array(5);
      var arr = new DataView(out.buffer);
      arr.setInt32(0,  view[0], false);
      arr.setInt32(4,  view[1], false);
      arr.setInt32(8,  view[2], false);
      arr.setInt32(12, view[3], false);
      arr.setInt32(16, view[4], false);
      return out;
    };

    // The digest and digestFrom* interface returns the hash digest
    // as a hex string.
    this.digest = this.digestFromString =
    this.digestFromBuffer = this.digestFromArrayBuffer =
    function (str) {
      return hex(rawDigest(str).buffer);
    };

  };

  // The low-level RushCore module provides the heart of Rusha,
  // a high-speed sha1 implementation working on an Int32Array heap.
  // At first glance, the implementation seems complicated, however
  // with the SHA1 spec at hand, it is obvious this almost a textbook
  // implementation that has a few functions hand-inlined and a few loops
  // hand-unrolled.
  function RushaCore (stdlib, foreign, heap) {
    "use asm";

    var H = new stdlib.Int32Array(heap);

    function hash (k) {

      k = k|0;
      var i = 0, j = 0,
          y0 = 0, z0 = 0, y1 = 0, z1 = 0,
          y2 = 0, z2 = 0, y3 = 0, z3 = 0,
          y4 = 0, z4 = 0, t0 = 0, t1 = 0;

      y0 = H[k+0<<2>>2]|0;
      y1 = H[k+1<<2>>2]|0;
      y2 = H[k+2<<2>>2]|0;
      y3 = H[k+3<<2>>2]|0;
      y4 = H[k+4<<2>>2]|0;

      for (i = 0; (i|0) < (k|0); i = i + 16 |0) {

        z0 = y0;
        z1 = y1;
        z2 = y2;
        z3 = y3;
        z4 = y4;

#define HX(x)       H[x<<2>>2]
#define ADD(x, y) ((y + x)|0)
#define ROL1(v)  ((v) << 1 | (v) >>> 31)
#define ROL5(v)  ((v) << 5 | (v) >>> 27)
#define ROL30(v) ((v) << 30 | (v) >>> 2)
#define EXTENDED(j) (ROL1(HX(j-3) ^ HX(j-8) ^ HX(j-14) ^ HX(j-16)))
#define F0(b,c,d) (b & c | ~b & d)
#define F1(b,c,d) (b ^ c ^ d)
#define F2(b,c,d) (b & c | b & d | c & d)
#define ROUND(f, add) ((ROL5(y0) + f(y1,y2,y3) |0) + ((t1 + y4 | 0) add |0) |0)
#define SWAP y4 = y3; y3 = y2; y2 = ROL30(y1); y1 = y0; y0 = t0;

        for (j = 0; (j|0) < 16; j = j + 1 |0) {
          t1 = HX(i+j)|0;
          t0 = ROUND(F0, +1518500249);
          SWAP
          HX(k+j) = t1;
        }

        for (j = k + 16 |0; (j|0) < (k + 20 |0); j = j + 1 |0) {
          t1 = EXTENDED(j);
          t0 = ROUND(F0, +1518500249);
          SWAP
          HX(j) = t1;
        }

        for (j = k + 20 |0; (j|0) < (k + 40 |0); j = j + 1 |0) {
          t1 = EXTENDED(j);
          t0 = ROUND(F1, +1859775393);
          SWAP
          HX(j) = t1;
        }

        for (j = k + 40 |0; (j|0) < (k + 60 |0); j = j + 1 |0) {
          t1 = EXTENDED(j);
          t0 = ROUND(F2, -1894007588);
          SWAP
          HX(j) = t1;
        }

        for (j = k + 60 |0; (j|0) < (k + 80 |0); j = j + 1 |0) {
          t1 = EXTENDED(j);
          t0 = ROUND(F1, -899497514);
          SWAP
          HX(j) = t1;
        }

        y0 = y0 + z0 |0;
        y1 = y1 + z1 |0;
        y2 = y2 + z2 |0;
        y3 = y3 + z3 |0;
        y4 = y4 + z4 |0;

      }

      H[0] = y0;
      H[1] = y1;
      H[2] = y2;
      H[3] = y3;
      H[4] = y4;

    }

    return {hash: hash};

  }

})();
<commit_msg>simplify core routine<commit_after>/*
 * Rusha, a JavaScript implementation of the Secure Hash Algorithm, SHA-1,
 * as defined in FIPS PUB 180-1, tuned for high performance with large inputs.
 * (http://github.com/srijs/rusha)
 *
 * Inspired by Paul Johnstons implementation (http://pajhome.org.uk/crypt/md5).
 *
 * Copyright (c) 2013 Sam Rijs (http://awesam.de).
 * Released under the terms of the MIT license as follows:
 *
 * 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.
 */

(function () {

  // If we'e running in Node.JS, export a module.
  if (typeof module !== 'undefined') {
    module.exports = Rusha;
  }

  // If we're running in a DOM context, export
  // the Rusha object to toplevel.
  if (typeof window !== 'undefined') {
    window.Rusha = Rusha;
  }

  // If we're running in a webworker, accept
  // messages containing a jobid and a buffer
  // or blob object, and return the hash result.
  if (typeof FileReaderSync !== 'undefined') {
    var reader = new FileReaderSync(),
        hasher = new Rusha(4 * 1024 * 1024);
    self.onmessage = function onMessage (event) {
      var hash, data = event.data.data;
      if (data instanceof Blob) {
        try {
          data = reader.readAsBinaryString(data);
        } catch (e) {
          self.postMessage({id: event.data.id, error: e.name});
          return;
        }
      }
      hash = hasher.digest(data);
      self.postMessage({id: event.data.id, hash: hash});
    };
  }

  // The Rusha object is a wrapper around the low-level RushaCore.
  // It provides means of converting different inputs to the
  // format accepted by RushaCore as well as other utility methods.
  function Rusha (sizeHint) {
    "use strict";

    // Private object structure.
    var self = {fill: 0};

    // Calculate the length of buffer that the sha1 routine uses
    // including the padding.
    var padlen = function (len) {
      return len + 1 + ((len ) % 64 < 56 ? 56 : 56 + 64) - (len ) % 64 + 8;
    };

    var padZeroes = function (bin, len) {
      for (var i = len >> 2; i < bin.length; i++) bin[i] = 0;
    };

    var padData = function (bin, len) {
      bin[len>>2] |= 0x80 << (24 - (len % 4 << 3));
      bin[(((len >> 2) + 2) & ~0x0f) + 15] = len << 3;
    };

    // Convert a binary string to a big-endian Int32Array using
    // four characters per slot and pad it per the sha1 spec.
    // A binary string is expected to only contain char codes < 256.
    var convStr = function (str, bin, len) {
      var i;
      for (i = 0; i < len; i = i + 4 |0) {
        bin[i>>2] = str.charCodeAt(i)   << 24 |
                    str.charCodeAt(i+1) << 16 |
                    str.charCodeAt(i+2) <<  8 |
                    str.charCodeAt(i+3);
      }
    };

    // Convert a buffer or array to a big-endian Int32Array using
    // four elements per slot and pad it per the sha1 spec.
    // The buffer or array is expected to only contain elements < 256.
    var convBuf = function (buf, bin, len) {
      var i, m = len % 4, j = len - m;
      for (i = 0; i < j; i = i + 4 |0) {
        bin[i>>2] = buf[i]   << 24 |
                    buf[i+1] << 16 |
                    buf[i+2] <<  8 |
                    buf[i+3];
      }
      switch (m) {
        case 0: bin[j>>2] |= buf[j+3];
        case 3: bin[j>>2] |= buf[j+2] << 8;
        case 2: bin[j>>2] |= buf[j+1] << 16;
        case 1: bin[j>>2] |= buf[j]   << 24;
      }
    };

    // Convert general data to a big-endian Int32Array written on the
    // heap and return it's length;
    var conv = function (data, bin, len) {
      if (typeof data === 'string') {
        return convStr(data, bin, len);
      } else if (data instanceof Array || (typeof global !== 'undefined' &&
                                           typeof global.Buffer !== 'undefined' &&
                                           global.Buffer.isBuffer(data))) {
        return convBuf(data, bin, len);
      } else if (data instanceof ArrayBuffer) {
        return convBuf(new Uint8Array(data), bin, len);
      } else if (data.buffer instanceof ArrayBuffer) {
        return convBuf(new Uint8Array(data.buffer), bin, len);
      } else {
        throw new Error('Unsupported data type.');
      }
    };

    // Convert an ArrayBuffer into its hexadecimal string representation.
    var hex = function (arrayBuffer) {
      var i, x, hex_tab = "0123456789abcdef", res = [], binarray = new Uint8Array(arrayBuffer);
      for (i = 0; i < binarray.length; i++) {
        x = binarray[i];
        res[i] = hex_tab.charAt((x >>  4) & 0xF) +
                 hex_tab.charAt((x >>  0) & 0xF);
      }
      return res.join('');
    };

    var ceilHeapSize = function (v) {
      // The asm.js spec says:
      // The heap object's byteLength must be either
      // 2^n for n in [12, 24) or 2^24 * n for n ≥ 1.
      var p;
      // If v is smaller than 2^12, the smallest possible solution
      // is 2^12.
      if (v <= 4096) return 4096;
      // If v < 2^24, we round up to 2^n,
      // otherwise we round up to 2^24 * n.
      if (v < 16777216) {
        for (p = 1; p < v; p = p << 1);
      } else {
        for (p = 16777216; p < v; p += 16777216);
      }
      return p;
    };

    // Resize the internal data structures to a new capacity.
    var resize = function (size) {
      self.sizeHint = size;
      self.heap     = new ArrayBuffer(ceilHeapSize(padlen(size) + 320));
      self.core     = RushaCore({Int32Array: Int32Array, DataView: DataView}, {}, self.heap);
    };

    // On initialize, resize the datastructures according
    // to an optional size hint.
    resize(sizeHint || 0);

    // Initialize and call the RushaCore,
    // assuming an input buffer of length len * 4.
    var coreCall = function (len) {
      var h = new Int32Array(self.heap, len << 2, 5);
      h[0] =  1732584193;
      h[1] =  -271733879;
      h[2] = -1732584194;
      h[3] =   271733878;
      h[4] = -1009589776;
      self.core.hash(len);
    };

    // Calculate the hash digest as an array of 5 32bit integers.
    var rawDigest = this.rawDigest = function (str) {
      var len = str.byteLength || str.length;
      if (len > self.sizeHint) {
        resize(len);
      }
      var view = new Int32Array(self.heap, 0, padlen(len) >> 2);
      padZeroes(view, len);
      conv(str, view, len);
      padData(view, len);
      coreCall(view.length);
      var out = new Int32Array(5);
      var arr = new DataView(out.buffer);
      arr.setInt32(0,  view[0], false);
      arr.setInt32(4,  view[1], false);
      arr.setInt32(8,  view[2], false);
      arr.setInt32(12, view[3], false);
      arr.setInt32(16, view[4], false);
      return out;
    };

    // The digest and digestFrom* interface returns the hash digest
    // as a hex string.
    this.digest = this.digestFromString =
    this.digestFromBuffer = this.digestFromArrayBuffer =
    function (str) {
      return hex(rawDigest(str).buffer);
    };

  };

  // The low-level RushCore module provides the heart of Rusha,
  // a high-speed sha1 implementation working on an Int32Array heap.
  // At first glance, the implementation seems complicated, however
  // with the SHA1 spec at hand, it is obvious this almost a textbook
  // implementation that has a few functions hand-inlined and a few loops
  // hand-unrolled.
  function RushaCore (stdlib, foreign, heap) {
    "use asm";

    var H = new stdlib.Int32Array(heap);

    function hash (k) {

      k = k|0;
      var i = 0, j = 0,
          y0 = 0, z0 = 0, y1 = 0, z1 = 0,
          y2 = 0, z2 = 0, y3 = 0, z3 = 0,
          y4 = 0, z4 = 0, t0 = 0, t1 = 0;

      k = k<<2;

      y0 = H[k+0>>2]|0;
      y1 = H[k+4>>2]|0;
      y2 = H[k+8>>2]|0;
      y3 = H[k+12>>2]|0;
      y4 = H[k+16>>2]|0;

      for (i = 0; (i|0) < (k|0); i = i + 64 |0) {

        z0 = y0;
        z1 = y1;
        z2 = y2;
        z3 = y3;
        z4 = y4;

#define ROL1(v)  ((v) <<  1 | (v) >>> 31)
#define ROL5(v)  ((v) <<  5 | (v) >>> 27)
#define ROL30(v) ((v) << 30 | (v) >>>  2)

#define EXTENDED(j) ROL1(H[j-12>>2] ^ H[j-32>>2] ^ H[j-56>>2] ^ H[j-64>>2])

#define F0(b,c,d) (b & c | ~b & d)
#define F1(b,c,d) (b ^ c ^ d)
#define F2(b,c,d) (b & c | b & d | c & d)

#define ROUND(f, add) ((ROL5(y0) + f(y1,y2,y3) |0) + ((t1 + y4 | 0) add |0) |0)

#define SWAP y4 = y3; y3 = y2; y2 = ROL30(y1); y1 = y0; y0 = t0;

        for (j = 0; (j|0) < 64; j = j + 4 |0) {
          t1 = H[i+j>>2]|0;
          t0 = ROUND(F0, +1518500249);
          SWAP
          H[k+j>>2] = t1;
        }

        for (j = k + 64 |0; (j|0) < (k + 80 |0); j = j + 4 |0) {
          t1 = EXTENDED(j);
          t0 = ROUND(F0, +1518500249);
          SWAP
          H[j>>2] = t1;
        }

        for (j = k + 80 |0; (j|0) < (k + 160 |0); j = j + 4 |0) {
          t1 = EXTENDED(j);
          t0 = ROUND(F1, +1859775393);
          SWAP
          H[j>>2] = t1;
        }

        for (j = k + 160 |0; (j|0) < (k + 240 |0); j = j + 4 |0) {
          t1 = EXTENDED(j);
          t0 = ROUND(F2, -1894007588);
          SWAP
          H[j>>2] = t1;
        }

        for (j = k + 240 |0; (j|0) < (k + 320 |0); j = j + 4 |0) {
          t1 = EXTENDED(j);
          t0 = ROUND(F1, -899497514);
          SWAP
          H[j>>2] = t1;
        }

        y0 = y0 + z0 |0;
        y1 = y1 + z1 |0;
        y2 = y2 + z2 |0;
        y3 = y3 + z3 |0;
        y4 = y4 + z4 |0;

      }

      H[0] = y0;
      H[1] = y1;
      H[2] = y2;
      H[3] = y3;
      H[4] = y4;

    }

    return {hash: hash};

  }

})();
<|endoftext|>