<commit_before>/**
 * Author: Vova Zaytsev <zaytsev@usc.edu>
 */

app.controller("NlcdClientController", ["$scope", "$location", "$sce", "NcldApiFactory",
    function ($scope, $location, $sce, NcldApiFactory) {
        /**
        **/

        $scope.central              = null;
        $scope.related              = [];
        $scope.meta                 = null;
        $scope.selection            = [];
        $scope.textSelection        = null;
        $scope.display = {

            // Tab 'ALL'
            relatedTabAllReversed:        false,
            relatedTabAllPredicate:       "inSelection",

            // Tab 'SELECTION'
            relatedTabSelectionReversed:  false,
            relatedTabSelectionPredicate: "pubDate",

            // Tab 'SOURCES'
            relatedTabSourcesReversed:    false,
            relatedTabSourcesPredicate:   "referenceCount",

            // Tab 'AUTHORS'
            relatedTabAuthorsReversed:    false,
            relatedTabAuthorsPredicate:   "referenceCount"

        };

        // Init bootstrap javascript
        $("#relatedTabs a").click(function (e) {
            e.preventDefault();
            $(this).tab("show");
        });
        $("#relatedTabs a:first").tab("show");

        // Init tooltipe
        $(".tip-tooltip").tooltip({
            "animation": true,
            "placement": "top"
        });

        $('.tip-popover').popover({
          trigger: 'focus'
        });

        NcldApiFactory.getTestGraph().success(function(data){

            $scope.sg = new StoryGraph(data);
            $scope.central = $scope.sg.getCentralNode();
            $scope.related = $scope.sg.getNodes();
            $scope.meta = data.meta;

            var distrPlaceId = "storyDistribution";
            var nwPlaceId = "storyNetwork";

            var distrWidth = document.getElementById(distrPlaceId).offsetWidth;
            var nwWidth = document.getElementById(nwPlaceId).offsetWidth;

            console.log(nwWidth);

            var height = 300;

            $scope.sg.drawDistribution(distrPlaceId, distrWidth, height);
            $scope.sg.drawNetwork(nwPlaceId, nwWidth, height);
        });

        //
        $scope.RelatedAllTabOrderBy = function(predicate) {
            if ($scope.display.relatedTabAllPredicate == predicate) {
                $scope.display.relatedTabAllReversed = !$scope.display.relatedTabAllReversed;
            }
            $scope.display.relatedTabAllPredicate = predicate;
        }

        //
        $scope.RelatedSelectionTabOrderBy = function(predicate) {
            if ($scope.display.relatedTabSelectionPredicate == predicate) {
                $scope.display.relatedTabSelectionReversed = !$scope.display.relatedTabSelectionReversed;
            }
            $scope.display.relatedTabSelectionPredicate = predicate;
        }

        //
        $scope.SetSelection = function(referencesList) {
            for (var i in $scope.selection) {
                $scope.selection[i].inSelection = null;
            };
            $scope.selection = [];
            for (var i in referencesList) {
                var refId = referencesList[i];
                var item = $scope.sg.getNode(refId);
                item.inSelection = true;
                $scope.selection.push(item);
            };
            $scope.sg.gfx.SetDistributionSelection(referencesList);
            $scope.sg.gfx.SetNetworkSelection(referencesList);
        };

        //
        $scope.TextSelection = function(chunk, referencesList) {
            if ($scope.textSelection) {
                $scope.textSelection.isSelected = false;
                if ($scope.textSelection.tagId == chunk.tagId) {
                    $scope.textSelection = null;
                    $scope.SetSelection([]);
                    return;
                }
            }
            $scope.textSelection = chunk;
            $scope.textSelection.isSelected = true;
            $scope.SetSelection(referencesList);
        };

}]);<commit_msg>update webapp<commit_after>/**
 * Author: Vova Zaytsev <zaytsev@usc.edu>
 */

app.controller("NlcdClientController", ["$scope", "$location", "$sce", "NcldApiFactory",
    function ($scope, $location, $sce, NcldApiFactory) {
        /**
        **/

        $scope.central              = null;
        $scope.related              = [];
        $scope.meta                 = null;
        $scope.selection            = [];
        $scope.textSelection        = null;
        $scope.display = {

            // Tab 'ALL'
            relatedTabAllReversed:        false,
            relatedTabAllPredicate:       "inSelection",

            // Tab 'SELECTION'
            relatedTabSelectionReversed:  false,
            relatedTabSelectionPredicate: "pubDate",

            // Tab 'SOURCES'
            relatedTabSourcesReversed:    false,
            relatedTabSourcesPredicate:   "referenceCount",

            // Tab 'AUTHORS'
            relatedTabAuthorsReversed:    false,
            relatedTabAuthorsPredicate:   "referenceCount"

        };

        // Init bootstrap javascript
        $("#relatedTabs a").click(function (e) {
            e.preventDefault();
            $(this).tab("show");
        });
        $("#relatedTabs a:first").tab("show");

        // Init tooltipe
        $(".tip-tooltip").tooltip({
            "animation": true,
            "placement": "top",
        });

        $(".tip-popover").popover({
              "trigger": "focus",
              "selector": ".tip-popover"
        });

        NcldApiFactory.getTestGraph().success(function(data){

            $scope.sg = new StoryGraph(data);
            $scope.central = $scope.sg.getCentralNode();
            $scope.related = $scope.sg.getNodes();
            $scope.meta = data.meta;

            var distrPlaceId = "storyDistribution";
            var nwPlaceId = "storyNetwork";

            var distrWidth = document.getElementById(distrPlaceId).offsetWidth;
            var nwWidth = document.getElementById(nwPlaceId).offsetWidth;

            console.log(nwWidth);

            var height = 300;

            $scope.sg.drawDistribution(distrPlaceId, distrWidth, height);
            $scope.sg.drawNetwork(nwPlaceId, nwWidth, height);
        });

        //
        $scope.RelatedAllTabOrderBy = function(predicate) {
            if ($scope.display.relatedTabAllPredicate == predicate) {
                $scope.display.relatedTabAllReversed = !$scope.display.relatedTabAllReversed;
            }
            $scope.display.relatedTabAllPredicate = predicate;
        }

        //
        $scope.RelatedSelectionTabOrderBy = function(predicate) {
            if ($scope.display.relatedTabSelectionPredicate == predicate) {
                $scope.display.relatedTabSelectionReversed = !$scope.display.relatedTabSelectionReversed;
            }
            $scope.display.relatedTabSelectionPredicate = predicate;
        }

        //
        $scope.SetSelection = function(referencesList) {
            for (var i in $scope.selection) {
                $scope.selection[i].inSelection = null;
            };
            $scope.selection = [];
            for (var i in referencesList) {
                var refId = referencesList[i];
                var item = $scope.sg.getNode(refId);
                item.inSelection = true;
                $scope.selection.push(item);
            };
            $scope.sg.gfx.SetDistributionSelection(referencesList);
            $scope.sg.gfx.SetNetworkSelection(referencesList);
        };

        //
        $scope.TextSelection = function(chunk, referencesList) {
            if ($scope.textSelection) {
                $scope.textSelection.isSelected = false;
                if ($scope.textSelection.tagId == chunk.tagId) {
                    $scope.textSelection = null;
                    $scope.SetSelection([]);
                    return;
                }
            }
            $scope.textSelection = chunk;
            $scope.textSelection.isSelected = true;
            $scope.SetSelection(referencesList);
        };

}]);<|endoftext|>


<commit_before>export default function(circles) {
  var i = 0, n = circles.length, B = [], p, e;

  while (i < n) {
    p = circles[i];
    if (e && encloses(e, p)) ++i;
    else e = encloseBasis(B = extendBasis(B, p)), i = 0;
  }

  return e;
}

function extendBasis(B, p) {
  var i, j;

  if (enclosesAll(p, B)) return [p];

  // If we get here then B must have at least one element.
  for (i = 0; i < B.length; ++i) {
    if (isBasis2(B[i], p) && enclosesAll(encloseBasis2(B[i], p), B)) {
      return [B[i], p];
    }
  }

  // If we get here then B must have at least two elements.
  for (i = 0; i < B.length - 1; ++i) {
    for (j = i + 1; j < B.length; ++j) {
      if (isBasis3(B[i], B[j], p) && enclosesAll(encloseBasis3(B[i], B[j], p), B)) {
        return [B[i], B[j], p];
      }
    }
  }

  // If we get here then something is very wrong.
  throw new Error;
}

function encloses(a, b) {
  var dr = a.r - b.r + 1e-9, dx = b.x - a.x, dy = b.y - a.y;
  return dr > 0 && dr * dr > dx * dx + dy * dy;
}

function enclosesAll(a, B) {
  for (var i = 0; i < B.length; ++i) {
    if (!encloses(a, B[i])) {
      return false;
    }
  }
  return true;
}

function encloseBasis(B) {
  switch (B.length) {
    case 1: return encloseBasis1(B[0]);
    case 2: return encloseBasis2(B[0], B[1]);
    case 3: return encloseBasis3(B[0], B[1], B[2]);
  }
}

function encloseBasis1(a) {
  return {
    x: a.x,
    y: a.y,
    r: a.r
  };
}

function encloseBasis2(a, b) {
  var x1 = a.x, y1 = a.y, r1 = a.r,
      x2 = b.x, y2 = b.y, r2 = b.r,
      x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1,
      l = Math.sqrt(x21 * x21 + y21 * y21);
  return {
    x: (x1 + x2 + x21 / l * r21) / 2,
    y: (y1 + y2 + y21 / l * r21) / 2,
    r: (l + r1 + r2) / 2
  };
}

function encloseBasis3(a, b, c) {
  var x1 = a.x, y1 = a.y, r1 = a.r,
      x2 = b.x, y2 = b.y, r2 = b.r,
      x3 = c.x, y3 = c.y, r3 = c.r,
      a2 = x1 - x2,
      a3 = x1 - x3,
      b2 = y1 - y2,
      b3 = y1 - y3,
      c2 = r2 - r1,
      c3 = r3 - r1,
      d1 = x1 * x1 + y1 * y1 - r1 * r1,
      d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2,
      d3 = d1 - x3 * x3 - y3 * y3 + r3 * r3,
      ab = a3 * b2 - a2 * b3,
      xa = (b2 * d3 - b3 * d2) / (ab * 2) - x1,
      xb = (b3 * c2 - b2 * c3) / ab,
      ya = (a3 * d2 - a2 * d3) / (ab * 2) - y1,
      yb = (a2 * c3 - a3 * c2) / ab,
      A = xb * xb + yb * yb - 1,
      B = 2 * (r1 + xa * xb + ya * yb),
      C = xa * xa + ya * ya - r1 * r1,
      r = A ? (B + Math.sqrt(B * B - 4 * A * C)) / (2 * A) : C / B,
      x = x1 + xa - xb * r,
      y = y1 + ya - yb * r;
  return {
    x: x,
    y: y,
    r: Math.max(
      Math.sqrt((x1 -= x) * x1 + (y1 -= y) * y1) + r1,
      Math.sqrt((x2 -= x) * x2 + (y2 -= y) * y2) + r2,
      Math.sqrt((x3 -= x) * x3 + (y3 -= y) * y3) + r3
    )
  };
}

function isBasis2(a, b) {
  return !encloses(a, b)
      && !encloses(b, a);
}

function isBasis3(a, b, c) {
  return !encloses(encloseBasis2(a, b), c)
      && !encloses(encloseBasis2(a, c), b)
      && !encloses(encloseBasis2(b, c), a);
}
<commit_msg>Optimize two-basis test.<commit_after>export default function(circles) {
  var i = 0, n = circles.length, B = [], p, e;

  while (i < n) {
    p = circles[i];
    if (e && encloses(e, p)) ++i;
    else e = encloseBasis(B = extendBasis(B, p)), i = 0;
  }

  return e;
}

function extendBasis(B, p) {
  var i, j;

  if (enclosesAll(p, B)) return [p];

  // If we get here then B must have at least one element.
  for (i = 0; i < B.length; ++i) {
    if (!encloses(p, B[i]) && enclosesAll(encloseBasis2(B[i], p), B)) {
      return [B[i], p];
    }
  }

  // If we get here then B must have at least two elements.
  for (i = 0; i < B.length - 1; ++i) {
    for (j = i + 1; j < B.length; ++j) {
      if (isBasis3(B[i], B[j], p) && enclosesAll(encloseBasis3(B[i], B[j], p), B)) {
        return [B[i], B[j], p];
      }
    }
  }

  // If we get here then something is very wrong.
  throw new Error;
}

function encloses(a, b) {
  var dr = a.r - b.r + 1e-9, dx = b.x - a.x, dy = b.y - a.y;
  return dr > 0 && dr * dr > dx * dx + dy * dy;
}

function enclosesAll(a, B) {
  for (var i = 0; i < B.length; ++i) {
    if (!encloses(a, B[i])) {
      return false;
    }
  }
  return true;
}

function encloseBasis(B) {
  switch (B.length) {
    case 1: return encloseBasis1(B[0]);
    case 2: return encloseBasis2(B[0], B[1]);
    case 3: return encloseBasis3(B[0], B[1], B[2]);
  }
}

function encloseBasis1(a) {
  return {
    x: a.x,
    y: a.y,
    r: a.r
  };
}

function encloseBasis2(a, b) {
  var x1 = a.x, y1 = a.y, r1 = a.r,
      x2 = b.x, y2 = b.y, r2 = b.r,
      x21 = x2 - x1, y21 = y2 - y1, r21 = r2 - r1,
      l = Math.sqrt(x21 * x21 + y21 * y21);
  return {
    x: (x1 + x2 + x21 / l * r21) / 2,
    y: (y1 + y2 + y21 / l * r21) / 2,
    r: (l + r1 + r2) / 2
  };
}

function encloseBasis3(a, b, c) {
  var x1 = a.x, y1 = a.y, r1 = a.r,
      x2 = b.x, y2 = b.y, r2 = b.r,
      x3 = c.x, y3 = c.y, r3 = c.r,
      a2 = x1 - x2,
      a3 = x1 - x3,
      b2 = y1 - y2,
      b3 = y1 - y3,
      c2 = r2 - r1,
      c3 = r3 - r1,
      d1 = x1 * x1 + y1 * y1 - r1 * r1,
      d2 = d1 - x2 * x2 - y2 * y2 + r2 * r2,
      d3 = d1 - x3 * x3 - y3 * y3 + r3 * r3,
      ab = a3 * b2 - a2 * b3,
      xa = (b2 * d3 - b3 * d2) / (ab * 2) - x1,
      xb = (b3 * c2 - b2 * c3) / ab,
      ya = (a3 * d2 - a2 * d3) / (ab * 2) - y1,
      yb = (a2 * c3 - a3 * c2) / ab,
      A = xb * xb + yb * yb - 1,
      B = 2 * (r1 + xa * xb + ya * yb),
      C = xa * xa + ya * ya - r1 * r1,
      r = A ? (B + Math.sqrt(B * B - 4 * A * C)) / (2 * A) : C / B,
      x = x1 + xa - xb * r,
      y = y1 + ya - yb * r;
  return {
    x: x,
    y: y,
    r: Math.max(
      Math.sqrt((x1 -= x) * x1 + (y1 -= y) * y1) + r1,
      Math.sqrt((x2 -= x) * x2 + (y2 -= y) * y2) + r2,
      Math.sqrt((x3 -= x) * x3 + (y3 -= y) * y3) + r3
    )
  };
}

function isBasis3(a, b, c) {
  return !encloses(encloseBasis2(a, b), c)
      && !encloses(encloseBasis2(a, c), b)
      && !encloses(encloseBasis2(b, c), a);
}
<|endoftext|>


<commit_before>/*
Flot plugin for adding panning and zooming capabilities to a plot.

The default behaviour is double click and scrollwheel up/down to zoom
in, drag to pan. The plugin defines plot.zoom({ center }),
plot.zoomOut() and plot.pan(offset) so you easily can add custom
controls. It also fires a "plotpan" and "plotzoom" event when
something happens, useful for synchronizing plots.

Example usage:

  plot = $.plot(...);

  // zoom default amount in on the pixel (100, 200)
  plot.zoom({ center: { left: 10, top: 20 } });

  // zoom out again
  plot.zoomOut();

  // pan 100 pixels to the left and 20 down
  plot.pan({ left: -100, top: 20 })

Options:

  zoom: {
    interactive: false
    trigger: "dblclick" // or "click" for single click
    amount: 1.5         // 2 = 200% (zoom in), 0.5 = 50% (zoom out)
  }

  pan: {
    interactive: false
  }

  xaxis, yaxis, x2axis, y2axis: {
    zoomRange: null  // or [number, number] (min range, max range)
    panRange: null   // or [number, number] (min, max)
  }

"interactive" enables the built-in drag/click behaviour. "amount" is
the amount to zoom the viewport relative to the current range, so 1 is
100% (i.e. no change), 1.5 is 150% (zoom in), 0.7 is 70% (zoom out).

"zoomRange" is the interval in which zooming can happen, e.g. with
zoomRange: [1, 100] the zoom will never scale the axis so that the
difference between min and max is smaller than 1 or larger than 100.
You can set either of them to null to ignore.

"panRange" confines the panning to stay within a range, e.g. with
panRange: [-10, 20] panning stops at -10 in one end and at 20 in the
other. Either can be null.
*/

// First two dependencies, jquery.event.drag.js and
// jquery.mousewheel.js, we put them inline here to save people the
// effort of downloading them.

/*
jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
Licensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt
*/
(function(E){E.fn.drag=function(L,K,J){if(K){this.bind("dragstart",L)}if(J){this.bind("dragend",J)}return !L?this.trigger("drag"):this.bind("drag",K?K:L)};var A=E.event,B=A.special,F=B.drag={not:":input",distance:0,which:1,dragging:false,setup:function(J){J=E.extend({distance:F.distance,which:F.which,not:F.not},J||{});J.distance=I(J.distance);A.add(this,"mousedown",H,J);if(this.attachEvent){this.attachEvent("ondragstart",D)}},teardown:function(){A.remove(this,"mousedown",H);if(this===F.dragging){F.dragging=F.proxy=false}G(this,true);if(this.detachEvent){this.detachEvent("ondragstart",D)}}};B.dragstart=B.dragend={setup:function(){},teardown:function(){}};function H(L){var K=this,J,M=L.data||{};if(M.elem){K=L.dragTarget=M.elem;L.dragProxy=F.proxy||K;L.cursorOffsetX=M.pageX-M.left;L.cursorOffsetY=M.pageY-M.top;L.offsetX=L.pageX-L.cursorOffsetX;L.offsetY=L.pageY-L.cursorOffsetY}else{if(F.dragging||(M.which>0&&L.which!=M.which)||E(L.target).is(M.not)){return }}switch(L.type){case"mousedown":E.extend(M,E(K).offset(),{elem:K,target:L.target,pageX:L.pageX,pageY:L.pageY});A.add(document,"mousemove mouseup",H,M);G(K,false);F.dragging=null;return false;case !F.dragging&&"mousemove":if(I(L.pageX-M.pageX)+I(L.pageY-M.pageY)<M.distance){break}L.target=M.target;J=C(L,"dragstart",K);if(J!==false){F.dragging=K;F.proxy=L.dragProxy=E(J||K)[0]}case"mousemove":if(F.dragging){J=C(L,"drag",K);if(B.drop){B.drop.allowed=(J!==false);B.drop.handler(L)}if(J!==false){break}L.type="mouseup"}case"mouseup":A.remove(document,"mousemove mouseup",H);if(F.dragging){if(B.drop){B.drop.handler(L)}C(L,"dragend",K)}G(K,true);F.dragging=F.proxy=M.elem=false;break}return true}function C(M,K,L){M.type=K;var J=E.event.handle.call(L,M);return J===false?false:J||M.result}function I(J){return Math.pow(J,2)}function D(){return(F.dragging===false)}function G(K,J){if(!K){return }K.unselectable=J?"off":"on";K.onselectstart=function(){return J};if(K.style){K.style.MozUserSelect=J?"":"none"}}})(jQuery);

/* jquery.mousewheel.min.js
 * Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.2
 *
 * Requires: 1.2.2+
 */
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);

(function ($) {
    var options = {
        xaxis: {
            zoomRange: null, // or [number, number] (min range, max range)
            panRange: null // or [number, number] (min, max)
        },
        zoom: {
            interactive: false,
            trigger: "dblclick", // or "click" for single click
            amount: 1.5 // how much to zoom relative to current position, 2 = 200% (zoom in), 0.5 = 50% (zoom out)
        },
        pan: {
            interactive: false
        }
    };

    function init(plot) {
        var prevPoint = null;

        function bindEvents(plot, eventHolder) {
            var o = plot.getOptions();
            if (o.zoom.interactive) {
                function clickHandler(e) {
                    prevPoint = plot.offset();
                    prevPoint.left = e.pageX - prevPoint.left;
                    prevPoint.top = e.pageY - prevPoint.top;
                    plot.zoom({ center: prevPoint });
                }

                eventHolder[o.zoom.trigger](clickHandler);

                eventHolder.mousewheel(function (e, delta) {
                    if (delta > 0)
                        clickHandler(e);
                    else
                        plot.zoomOut();
                });
            }
            if (o.pan.interactive) {
                var prevCursor = 'default', pageX = 0, pageY = 0;

                eventHolder.bind("dragstart", { distance: 10 }, function (e) {
                    if (e.which != 1)  // only accept left-click
                        return false;
                    eventHolderCursor = eventHolder.css('cursor');
                    eventHolder.css('cursor', 'move');
                    pageX = e.pageX;
                    pageY = e.pageY;
                });
                eventHolder.bind("drag", function (e) {
                    // unused at the moment, but we need it here to
                    // trigger the dragstart/dragend events
                });
                eventHolder.bind("dragend", function (e) {
                    eventHolder.css('cursor', prevCursor);
                    plot.pan({ left: pageX - e.pageX,
                               top: pageY - e.pageY });
                });
            }
        }

        plot.zoomOut = function () {
            plot.zoom({ amount: 1 / plot.getOptions().zoom.amount });
            prevPoint = null;
        }

        plot.zoom = function (args) {
            var axes = plot.getAxes(),
                options = plot.getOptions(),
                c = args.center ? args.center : prevPoint,
                amount = args.amount ? args.amount : options.zoom.amount,
                w = plot.width(), h = plot.height();

            if (!c)
                c = { left: w / 2, top: h / 2 };

            var xf = c.left / w,
                x1 = c.left - xf * w / amount,
                x2 = c.left + (1 - xf) * w / amount,
                yf = c.top / h,
                y1 = c.top - yf * h / amount,
                y2 = c.top + (1 - yf) * h / amount;

            function scaleAxis(min, max, name) {
                var axis = axes[name],
                    axisOptions = options[name];

                if (!axis.used)
                    return;

                min = axis.c2p(min);
                max = axis.c2p(max);
                if (max < min) { // make sure min < max
                    var tmp = min
                    min = max;
                    max = tmp;
                }

                var range = max - min, zr = axisOptions.zoomRange;
                if (zr &&
                    ((zr[0] != null && range < zr[0]) ||
                     (zr[1] != null && range > zr[1])))
                    return;

                axisOptions.min = min;
                axisOptions.max = max;
            }

            scaleAxis(x1, x2, 'xaxis');
            scaleAxis(x1, x2, 'x2axis');
            scaleAxis(y1, y2, 'yaxis');
            scaleAxis(y1, y2, 'y2axis');

            plot.setupGrid();
            plot.draw();

            if (!args.preventEvent)
                plot.getPlaceholder().trigger("plotzoom", [ plot ]);
        }

        plot.pan = function (args) {
            var l = +args.left, t = +args.top,
                axes = plot.getAxes(), options = plot.getOptions();

            if (isNaN(l))
                l = 0;
            if (isNaN(t))
                t = 0;

            function panAxis(delta, name) {
                var axis = axes[name],
                    axisOptions = options[name],
                    min, max;

                if (!axis.used)
                    return;

                min = axis.c2p(axis.p2c(axis.min) + delta),
                max = axis.c2p(axis.p2c(axis.max) + delta);

                var pr = axisOptions.panRange;
                if (pr) {
                    // check whether we hit the wall
                    if (pr[0] != null && pr[0] > min) {
                        delta = pr[0] - min;
                        min += delta;
                        max += delta;
                    }

                    if (pr[1] != null && pr[1] < max) {
                        delta = pr[1] - max;
                        min += delta;
                        max += delta;
                    }
                }

                axisOptions.min = min;
                axisOptions.max = max;
            }

            panAxis(l, 'xaxis');
            panAxis(l, 'x2axis');
            panAxis(t, 'yaxis');
            panAxis(t, 'y2axis');

            plot.setupGrid();
            plot.draw();

            if (!args.preventEvent)
                plot.getPlaceholder().trigger("plotpan", [ plot ]);
        }

        plot.hooks.bindEvents.push(bindEvents);
    }

    $.plot.plugins.push({
        init: init,
        options: options,
        name: 'navigate',
        version: '1.0'
    });
})(jQuery);
<commit_msg>Base zoom out on current mouse position rather than a one-level undo<commit_after>/*
Flot plugin for adding panning and zooming capabilities to a plot.

The default behaviour is double click and scrollwheel up/down to zoom
in, drag to pan. The plugin defines plot.zoom({ center }),
plot.zoomOut() and plot.pan(offset) so you easily can add custom
controls. It also fires a "plotpan" and "plotzoom" event when
something happens, useful for synchronizing plots.

Example usage:

  plot = $.plot(...);

  // zoom default amount in on the pixel (100, 200)
  plot.zoom({ center: { left: 10, top: 20 } });

  // zoom out again
  plot.zoomOut({ center: { left: 10, top: 20 } });

  // pan 100 pixels to the left and 20 down
  plot.pan({ left: -100, top: 20 })

Options:

  zoom: {
    interactive: false
    trigger: "dblclick" // or "click" for single click
    amount: 1.5         // 2 = 200% (zoom in), 0.5 = 50% (zoom out)
  }

  pan: {
    interactive: false
  }

  xaxis, yaxis, x2axis, y2axis: {
    zoomRange: null  // or [number, number] (min range, max range)
    panRange: null   // or [number, number] (min, max)
  }

"interactive" enables the built-in drag/click behaviour. "amount" is
the amount to zoom the viewport relative to the current range, so 1 is
100% (i.e. no change), 1.5 is 150% (zoom in), 0.7 is 70% (zoom out).

"zoomRange" is the interval in which zooming can happen, e.g. with
zoomRange: [1, 100] the zoom will never scale the axis so that the
difference between min and max is smaller than 1 or larger than 100.
You can set either of them to null to ignore.

"panRange" confines the panning to stay within a range, e.g. with
panRange: [-10, 20] panning stops at -10 in one end and at 20 in the
other. Either can be null.
*/

// First two dependencies, jquery.event.drag.js and
// jquery.mousewheel.js, we put them inline here to save people the
// effort of downloading them.

/*
jquery.event.drag.js ~ v1.5 ~ Copyright (c) 2008, Three Dub Media (http://threedubmedia.com)
Licensed under the MIT License ~ http://threedubmedia.googlecode.com/files/MIT-LICENSE.txt
*/
(function(E){E.fn.drag=function(L,K,J){if(K){this.bind("dragstart",L)}if(J){this.bind("dragend",J)}return !L?this.trigger("drag"):this.bind("drag",K?K:L)};var A=E.event,B=A.special,F=B.drag={not:":input",distance:0,which:1,dragging:false,setup:function(J){J=E.extend({distance:F.distance,which:F.which,not:F.not},J||{});J.distance=I(J.distance);A.add(this,"mousedown",H,J);if(this.attachEvent){this.attachEvent("ondragstart",D)}},teardown:function(){A.remove(this,"mousedown",H);if(this===F.dragging){F.dragging=F.proxy=false}G(this,true);if(this.detachEvent){this.detachEvent("ondragstart",D)}}};B.dragstart=B.dragend={setup:function(){},teardown:function(){}};function H(L){var K=this,J,M=L.data||{};if(M.elem){K=L.dragTarget=M.elem;L.dragProxy=F.proxy||K;L.cursorOffsetX=M.pageX-M.left;L.cursorOffsetY=M.pageY-M.top;L.offsetX=L.pageX-L.cursorOffsetX;L.offsetY=L.pageY-L.cursorOffsetY}else{if(F.dragging||(M.which>0&&L.which!=M.which)||E(L.target).is(M.not)){return }}switch(L.type){case"mousedown":E.extend(M,E(K).offset(),{elem:K,target:L.target,pageX:L.pageX,pageY:L.pageY});A.add(document,"mousemove mouseup",H,M);G(K,false);F.dragging=null;return false;case !F.dragging&&"mousemove":if(I(L.pageX-M.pageX)+I(L.pageY-M.pageY)<M.distance){break}L.target=M.target;J=C(L,"dragstart",K);if(J!==false){F.dragging=K;F.proxy=L.dragProxy=E(J||K)[0]}case"mousemove":if(F.dragging){J=C(L,"drag",K);if(B.drop){B.drop.allowed=(J!==false);B.drop.handler(L)}if(J!==false){break}L.type="mouseup"}case"mouseup":A.remove(document,"mousemove mouseup",H);if(F.dragging){if(B.drop){B.drop.handler(L)}C(L,"dragend",K)}G(K,true);F.dragging=F.proxy=M.elem=false;break}return true}function C(M,K,L){M.type=K;var J=E.event.handle.call(L,M);return J===false?false:J||M.result}function I(J){return Math.pow(J,2)}function D(){return(F.dragging===false)}function G(K,J){if(!K){return }K.unselectable=J?"off":"on";K.onselectstart=function(){return J};if(K.style){K.style.MozUserSelect=J?"":"none"}}})(jQuery);

/* jquery.mousewheel.min.js
 * Copyright (c) 2009 Brandon Aaron (http://brandonaaron.net)
 * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php)
 * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses.
 * Thanks to: http://adomas.org/javascript-mouse-wheel/ for some pointers.
 * Thanks to: Mathias Bank(http://www.mathias-bank.de) for a scope bug fix.
 *
 * Version: 3.0.2
 *
 * Requires: 1.2.2+
 */
(function(c){var a=["DOMMouseScroll","mousewheel"];c.event.special.mousewheel={setup:function(){if(this.addEventListener){for(var d=a.length;d;){this.addEventListener(a[--d],b,false)}}else{this.onmousewheel=b}},teardown:function(){if(this.removeEventListener){for(var d=a.length;d;){this.removeEventListener(a[--d],b,false)}}else{this.onmousewheel=null}}};c.fn.extend({mousewheel:function(d){return d?this.bind("mousewheel",d):this.trigger("mousewheel")},unmousewheel:function(d){return this.unbind("mousewheel",d)}});function b(f){var d=[].slice.call(arguments,1),g=0,e=true;f=c.event.fix(f||window.event);f.type="mousewheel";if(f.wheelDelta){g=f.wheelDelta/120}if(f.detail){g=-f.detail/3}d.unshift(f,g);return c.event.handle.apply(this,d)}})(jQuery);

(function ($) {
    var options = {
        xaxis: {
            zoomRange: null, // or [number, number] (min range, max range)
            panRange: null // or [number, number] (min, max)
        },
        zoom: {
            interactive: false,
            trigger: "dblclick", // or "click" for single click
            amount: 1.5 // how much to zoom relative to current position, 2 = 200% (zoom in), 0.5 = 50% (zoom out)
        },
        pan: {
            interactive: false
        }
    };

    function init(plot) {
        function bindEvents(plot, eventHolder) {
            var o = plot.getOptions();
            if (o.zoom.interactive) {
                function clickHandler(e, zoomOut) {
                    var c = plot.offset();
                    c.left = e.pageX - c.left;
                    c.top = e.pageY - c.top;
                    if (zoomOut)
                        plot.zoomOut({ center: c });
                    else
                        plot.zoom({ center: c });
                }

                eventHolder[o.zoom.trigger](clickHandler);

                eventHolder.mousewheel(function (e, delta) {
                    clickHandler(e, delta < 0);
                });
            }
            if (o.pan.interactive) {
                var prevCursor = 'default', pageX = 0, pageY = 0;

                eventHolder.bind("dragstart", { distance: 10 }, function (e) {
                    if (e.which != 1)  // only accept left-click
                        return false;
                    eventHolderCursor = eventHolder.css('cursor');
                    eventHolder.css('cursor', 'move');
                    pageX = e.pageX;
                    pageY = e.pageY;
                });
                eventHolder.bind("drag", function (e) {
                    // unused at the moment, but we need it here to
                    // trigger the dragstart/dragend events
                });
                eventHolder.bind("dragend", function (e) {
                    eventHolder.css('cursor', prevCursor);
                    plot.pan({ left: pageX - e.pageX,
                               top: pageY - e.pageY });
                });
            }
        }

        plot.zoomOut = function (args) {
            if (!args.amount)
                args.amount = plot.getOptions().zoom.amount

            args.amount = 1 / args.amount;
            plot.zoom(args);
        }

        plot.zoom = function (args) {
            var axes = plot.getAxes(),
                options = plot.getOptions(),
                c = args.center,
                amount = args.amount ? args.amount : options.zoom.amount,
                w = plot.width(), h = plot.height();

            if (!c)
                c = { left: w / 2, top: h / 2 };

            var xf = c.left / w,
                x1 = c.left - xf * w / amount,
                x2 = c.left + (1 - xf) * w / amount,
                yf = c.top / h,
                y1 = c.top - yf * h / amount,
                y2 = c.top + (1 - yf) * h / amount;

            function scaleAxis(min, max, name) {
                var axis = axes[name],
                    axisOptions = options[name];

                if (!axis.used)
                    return;

                min = axis.c2p(min);
                max = axis.c2p(max);
                if (max < min) { // make sure min < max
                    var tmp = min
                    min = max;
                    max = tmp;
                }

                var range = max - min, zr = axisOptions.zoomRange;
                if (zr &&
                    ((zr[0] != null && range < zr[0]) ||
                     (zr[1] != null && range > zr[1])))
                    return;

                axisOptions.min = min;
                axisOptions.max = max;
            }

            scaleAxis(x1, x2, 'xaxis');
            scaleAxis(x1, x2, 'x2axis');
            scaleAxis(y1, y2, 'yaxis');
            scaleAxis(y1, y2, 'y2axis');

            plot.setupGrid();
            plot.draw();

            if (!args.preventEvent)
                plot.getPlaceholder().trigger("plotzoom", [ plot ]);
        }

        plot.pan = function (args) {
            var l = +args.left, t = +args.top,
                axes = plot.getAxes(), options = plot.getOptions();

            if (isNaN(l))
                l = 0;
            if (isNaN(t))
                t = 0;

            function panAxis(delta, name) {
                var axis = axes[name],
                    axisOptions = options[name],
                    min, max;

                if (!axis.used)
                    return;

                min = axis.c2p(axis.p2c(axis.min) + delta),
                max = axis.c2p(axis.p2c(axis.max) + delta);

                var pr = axisOptions.panRange;
                if (pr) {
                    // check whether we hit the wall
                    if (pr[0] != null && pr[0] > min) {
                        delta = pr[0] - min;
                        min += delta;
                        max += delta;
                    }

                    if (pr[1] != null && pr[1] < max) {
                        delta = pr[1] - max;
                        min += delta;
                        max += delta;
                    }
                }

                axisOptions.min = min;
                axisOptions.max = max;
            }

            panAxis(l, 'xaxis');
            panAxis(l, 'x2axis');
            panAxis(t, 'yaxis');
            panAxis(t, 'y2axis');

            plot.setupGrid();
            plot.draw();

            if (!args.preventEvent)
                plot.getPlaceholder().trigger("plotpan", [ plot ]);
        }

        plot.hooks.bindEvents.push(bindEvents);
    }

    $.plot.plugins.push({
        init: init,
        options: options,
        name: 'navigate',
        version: '1.1'
    });
})(jQuery);
<|endoftext|>


<commit_before>
// Write message if not webgl is found
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var simElectron = false;

var pGalacticSystem, Stars3D;

var  molecule, spawnerOptions;

var stats ,material, mesh, GAMA_Z, CMBsphere;

var tick = 0;

var camera, controls, scene, renderer, model,light, ambientLight;

var textMesh,supMesh,boxMesh;

var galRotDegree=0;
var galRotSpeed = 0.0005;

var clock = new THREE.Clock();

var message = document.getElementById('text')

$('body').one('click', function() { document.getElementById("rotate-image").style.visibility = "hidden";})

window.onload = function(){
	document.getElementById("loading").style.visibility = "hidden"
}
var preVal =0;

// Create the slider to show the current scale
var slider = $("#slider").slider({
	min: 0,
	max: 4000,
	step: 500,
});

// Create the slider to enable zoom by updating the field of view (fov)
$( "#slider-vertical" ).slider({
	orientation: "vertical",
	min: 0,
	max: 40,
	value: 0,
	slide: function(event,ui ){
		var fov = camera.fov
		if(ui.value>preVal){
			camera.fov = fov - 2;
      		camera.updateProjectionMatrix();
		}
		else{
			camera.fov = fov + 2;
      		camera.updateProjectionMatrix();
      	}
		preVal = ui.value;

	}

});

init();
animate();

function init() {
	/*
		function to initilize the three js scene
	*/

	// Initialize the scene
	scene = new THREE.Scene();
	scene.fog = new THREE.FogExp2( 0x000000, 0.0000000025 );

	// Setup renderer
	renderer = new THREE.WebGLRenderer();
	renderer.setClearColor( scene.fog.color );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( window.innerWidth, window.innerHeight );

	// Creates containeer to show the framerate
	var container = document.getElementById( 'container' );
	container.appendChild( renderer.domElement );

	// Create the Camera
	camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.01, 1e13 );
	camera.position.set(0,0,0.02)

	// Set the control
	controls = new THREE.OrbitControls( camera, renderer.domElement );
	controls.enableZoom = false;
	controls.enablePan = false;

	//Create light
	light = new THREE.DirectionalLight( 0xffffff,4 );
	light.position.set( 0, 0, 10 );
	light.target.position.set(0,0,0);
	light.castShadow = true;
	ambientLight = new THREE.AmbientLight(0xffffff);

	// Create models
	loadMolecule( "models/caffeine.pdb" );
	addElectron();
	generateGalaxy();
	generateHuman();
	create_meshes();
	create_3Dstars();
	createCMB();

	// add the starts
	stats = new Stats();
	container.appendChild( stats.dom );

	window.addEventListener( 'resize', onWindowResize, false );

	// load in the gama data in the background so the website takes less time to load
	loadScript("data/GAMA_data.js",addGamaData)

	//Add the first model to the scene
	scene.add(proton1,proton2,neutron1,neutron2);
	scene.add(particleSystem);
	scene.add(addElectron)
	simElectron = true;
	message.innerHTML="This is an atomic nucleus surrounded by an electron cloud";

	//Initalize all the tweens
	initTweens();

}
function textSprite(sup,scale, z=0,larger=false) {
	/*
	 function to create text to show size of the current model
	 inputs:
	 sup: power of 10 of that level
	 scale: size of the text needed at that level
	 z: offset of the text along the z axis
	*/

    var font = "Helvetica",
        size = 200,
        color = "#ffffff",
        text = "10  m"
		font = "bold " + size + "px " + font;

    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    context.font = font;
    var supCanvas = document.createElement('canvas');
    var supContext = supCanvas.getContext('2d');
    supContext.font = font;

    // get size data (height depends only on font size)
    var metrics = context.measureText(text),
        textWidth = metrics.width;
    var supMetrics = context.measureText(sup),
        supWidth = supMetrics.width;

    canvas.width = textWidth;
    canvas.height = size + 3;
    supCanvas.width = supWidth + 3;
    supCanvas.height = size + 3;

    context.font = font;
    context.fillStyle = color;
    context.fillText(text, 0, size + 3);
    supContext.font = font;
    supContext.fillStyle = color;
    supContext.fillText(sup, 0, size + 3);

    // canvas contents will be used for a texture
    var texture = new THREE.Texture(canvas);
    texture.needsUpdate = true;
    var supTexture = new THREE.Texture(supCanvas);
    supTexture.needsUpdate = true;

    textMesh = new THREE.Mesh(
    new THREE.PlaneGeometry(canvas.width, canvas.height),
    new THREE.MeshBasicMaterial({
        map: texture,
        side: THREE.DoubleSide
    }));
    supMesh = new THREE.Mesh(
    new THREE.PlaneGeometry(supCanvas.width, supCanvas.height),
    new THREE.MeshBasicMaterial({
        map: supTexture,
        side: THREE.DoubleSide
    }));
    supMesh.scale.set(scale/2,scale/2,scale/2)
    supMesh.position.set(scale*1e3,scale*1e2,z)
    textMesh.scale.set(scale,scale,scale)
    textMesh.position.x = scale*1e3;
    textMesh.position.z = z;
    scene.add( textMesh,supMesh);
    if(larger)
   		box(scale*1.5e3,z)
   	else
   		box(scale*1e3,z)
}
 function box(scale,z=0){
 	/*
		function to create a box around the model to show the scale
		scale: size of the box
		z: offset of the box along the z axis
 	*/
 	var geometry = new THREE.BoxGeometry( scale, scale, 0 );
	var material = new THREE.MeshBasicMaterial( {color: 0xffffff} );
	var cube = new THREE.Mesh( geometry, material );
	boxMesh = new THREE.BoxHelper( cube, 0xFFFFFF );
	boxMesh.position.z = z;
	scene.add( boxMesh );
 }

function loadScript(url, callback)
/*
	function to load scripts
*/
{
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('body')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

function onWindowResize() {

	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize( window.innerWidth, window.innerHeight );

}

function animate() {

	// Make sure the document doesn't scroll
	document.body.scrollTop = document.body.scrollLeft = 0;

	requestAnimationFrame( animate );

	controls.update(); // required if controls.enableDamping = true, or if controls.autoRotate = true

	if( solarsystem){
		update_positions();
	}
	if(galaxy){
		GalaxyRotate();
	}
	stats.update();

	if(simElectron){
		var delta = clock.getDelta() * spawnerOptions.timeScale;
		tick += delta;

		if (tick < 0) tick = 0;

		if((delta > 0) & (simElectron)){

			for (var x = 0; x < spawnerOptions.spawnRate * delta; x++) {
					particleSystem.spawnParticle(options);
				}
		}
		particleSystem.update(tick);
	}

	render();

}

function render() {

	renderer.render( scene, camera );
	TWEEN.update();
}
<commit_msg>add light?<commit_after>
// Write message if not webgl is found
if ( ! Detector.webgl ) Detector.addGetWebGLMessage();

var simElectron = false;

var pGalacticSystem, Stars3D;

var  molecule, spawnerOptions;

var stats ,material, mesh, GAMA_Z, CMBsphere;

var tick = 0;

var camera, controls, scene, renderer, model,light, ambientLight;

var textMesh,supMesh,boxMesh;

var galRotDegree=0;
var galRotSpeed = 0.0005;

var clock = new THREE.Clock();

var message = document.getElementById('text')

$('body').one('click', function() { document.getElementById("rotate-image").style.visibility = "hidden";})

window.onload = function(){
	document.getElementById("loading").style.visibility = "hidden"
}
var preVal =0;

// Create the slider to show the current scale
var slider = $("#slider").slider({
	min: 0,
	max: 4000,
	step: 500,
});

// Create the slider to enable zoom by updating the field of view (fov)
$( "#slider-vertical" ).slider({
	orientation: "vertical",
	min: 0,
	max: 40,
	value: 0,
	slide: function(event,ui ){
		var fov = camera.fov
		if(ui.value>preVal){
			camera.fov = fov - 2;
      		camera.updateProjectionMatrix();
		}
		else{
			camera.fov = fov + 2;
      		camera.updateProjectionMatrix();
      	}
		preVal = ui.value;

	}

});

init();
animate();

function init() {
	/*
		function to initilize the three js scene
	*/

	// Initialize the scene
	scene = new THREE.Scene();
	scene.fog = new THREE.FogExp2( 0x000000, 0.0000000025 );

	// Setup renderer
	renderer = new THREE.WebGLRenderer();
	renderer.setClearColor( scene.fog.color );
	renderer.setPixelRatio( window.devicePixelRatio );
	renderer.setSize( window.innerWidth, window.innerHeight );

	// Creates containeer to show the framerate
	var container = document.getElementById( 'container' );
	container.appendChild( renderer.domElement );

	// Create the Camera
	camera = new THREE.PerspectiveCamera( 50, window.innerWidth / window.innerHeight, 0.01, 1e13 );
	camera.position.set(0,0,0.02)

	// Set the control
	controls = new THREE.OrbitControls( camera, renderer.domElement );
	controls.enableZoom = false;
	controls.enablePan = false;

	//Create light
	light = new THREE.DirectionalLight( 0xffffff,4 );
	light.position.set( 0, 0, 10 );
	light.target.position.set(0,0,0);
	light.castShadow = true;
	ambientLight = new THREE.AmbientLight(0xffffff);
	scene.add(light, ambientLight);

	// Create models
	loadMolecule( "models/caffeine.pdb" );
	addElectron();
	generateGalaxy();
	generateHuman();
	create_meshes();
	create_3Dstars();
	createCMB();

	// add the starts
	stats = new Stats();
	container.appendChild( stats.dom );

	window.addEventListener( 'resize', onWindowResize, false );

	// load in the gama data in the background so the website takes less time to load
	loadScript("data/GAMA_data.js",addGamaData)

	//Add the first model to the scene
	scene.add(proton1,proton2,neutron1,neutron2);
	scene.add(particleSystem);
	scene.add(addElectron)
	simElectron = true;
	message.innerHTML="This is an atomic nucleus surrounded by an electron cloud";

	//Initalize all the tweens
	initTweens();

}
function textSprite(sup,scale, z=0,larger=false) {
	/*
	 function to create text to show size of the current model
	 inputs:
	 sup: power of 10 of that level
	 scale: size of the text needed at that level
	 z: offset of the text along the z axis
	*/

    var font = "Helvetica",
        size = 200,
        color = "#ffffff",
        text = "10  m"
		font = "bold " + size + "px " + font;

    var canvas = document.createElement('canvas');
    var context = canvas.getContext('2d');
    context.font = font;
    var supCanvas = document.createElement('canvas');
    var supContext = supCanvas.getContext('2d');
    supContext.font = font;

    // get size data (height depends only on font size)
    var metrics = context.measureText(text),
        textWidth = metrics.width;
    var supMetrics = context.measureText(sup),
        supWidth = supMetrics.width;

    canvas.width = textWidth;
    canvas.height = size + 3;
    supCanvas.width = supWidth + 3;
    supCanvas.height = size + 3;

    context.font = font;
    context.fillStyle = color;
    context.fillText(text, 0, size + 3);
    supContext.font = font;
    supContext.fillStyle = color;
    supContext.fillText(sup, 0, size + 3);

    // canvas contents will be used for a texture
    var texture = new THREE.Texture(canvas);
    texture.needsUpdate = true;
    var supTexture = new THREE.Texture(supCanvas);
    supTexture.needsUpdate = true;

    textMesh = new THREE.Mesh(
    new THREE.PlaneGeometry(canvas.width, canvas.height),
    new THREE.MeshBasicMaterial({
        map: texture,
        side: THREE.DoubleSide
    }));
    supMesh = new THREE.Mesh(
    new THREE.PlaneGeometry(supCanvas.width, supCanvas.height),
    new THREE.MeshBasicMaterial({
        map: supTexture,
        side: THREE.DoubleSide
    }));
    supMesh.scale.set(scale/2,scale/2,scale/2)
    supMesh.position.set(scale*1e3,scale*1e2,z)
    textMesh.scale.set(scale,scale,scale)
    textMesh.position.x = scale*1e3;
    textMesh.position.z = z;
    scene.add( textMesh,supMesh);
    if(larger)
   		box(scale*1.5e3,z)
   	else
   		box(scale*1e3,z)
}
 function box(scale,z=0){
 	/*
		function to create a box around the model to show the scale
		scale: size of the box
		z: offset of the box along the z axis
 	*/
 	var geometry = new THREE.BoxGeometry( scale, scale, 0 );
	var material = new THREE.MeshBasicMaterial( {color: 0xffffff} );
	var cube = new THREE.Mesh( geometry, material );
	boxMesh = new THREE.BoxHelper( cube, 0xFFFFFF );
	boxMesh.position.z = z;
	scene.add( boxMesh );
 }

function loadScript(url, callback)
/*
	function to load scripts
*/
{
    // Adding the script tag to the head as suggested before
    var head = document.getElementsByTagName('body')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

function onWindowResize() {

	camera.aspect = window.innerWidth / window.innerHeight;
	camera.updateProjectionMatrix();

	renderer.setSize( window.innerWidth, window.innerHeight );

}

function animate() {

	// Make sure the document doesn't scroll
	document.body.scrollTop = document.body.scrollLeft = 0;

	requestAnimationFrame( animate );

	controls.update(); // required if controls.enableDamping = true, or if controls.autoRotate = true

	if( solarsystem){
		update_positions();
	}
	if(galaxy){
		GalaxyRotate();
	}
	stats.update();

	if(simElectron){
		var delta = clock.getDelta() * spawnerOptions.timeScale;
		tick += delta;

		if (tick < 0) tick = 0;

		if((delta > 0) & (simElectron)){

			for (var x = 0; x < spawnerOptions.spawnRate * delta; x++) {
					particleSystem.spawnParticle(options);
				}
		}
		particleSystem.update(tick);
	}

	render();

}

function render() {

	renderer.render( scene, camera );
	TWEEN.update();
}
<|endoftext|>


<commit_before>module.exports = [
  {
    name: 'English',
    code: 'en_US',
    country: 'United States',
  },
  {
    name: 'Nederlands',
    code: 'nl_NL',
    country: 'Nederland',
  },
  {
    name: 'Deutsch',
    code: 'de_DE',
    country: 'Deutschland',
  },
  {
    name: 'Italiano',
    code: 'it_IT',
    country: 'Italia',
  },
  {
    name: 'Polski',
    code: 'pl_PL',
    country: 'Polska',
  },
  {
    name: 'Português',
    code: 'pt_PT',
    country: 'Portugal',
  },
  {
    name: 'Español',
    code: 'es_ES',
    country: 'España',
  },
  {
    name: 'Türkçe',
    code: 'tr_TR',
    country: 'Türkiye',
  },
  {
    name: 'Български',
    code: 'bg_BG',
    country: 'България',
  },
  {
    name: 'Ελληνικά',
    code: 'el_GR',
    country: 'Ελλάδα',
  },
  {
    name: 'Eesti',
    code: 'et_EE',
    country: 'Eesti',
  },
  {
    name: 'हिंदी',
    code: 'hi_IN',
    country: 'इंडिया',
  },
  {
    name: '日本語',
    code: 'ja_JP',
    country: '日本',
  },
  {
    name: 'Română',
    code: 'ro_RO',
    country: 'România',
  },
  {
    name: 'Español',
    code: 'es_AR',
    country: 'Argentina',
  },
  {
    name: 'Français',
    code: 'fr_FR',
    country: 'France',
  },
  {
    name: 'Maltese',
    code: 'mt_MT',
    country: 'Malta',
  },
  {
    name: 'Slovenski',
    code: 'sl_SL',
    country: 'Slovenija',
  },
  {
    name: 'Slovenský',
    code: 'sk_SK',
    country: 'Slovensko',
  },
  {
    name: 'Українська',
    code: 'uk_UK',
    country: 'Україна',
  },
];
<commit_msg>Add new languages<commit_after>module.exports = [
  {
    name: 'English',
    code: 'en_US',
    country: 'United States',
  },
  {
    name: 'Nederlands',
    code: 'nl_NL',
    country: 'Nederland',
  },
  {
    name: 'Deutsch',
    code: 'de_DE',
    country: 'Deutschland',
  },
  {
    name: 'Italiano',
    code: 'it_IT',
    country: 'Italia',
  },
  {
    name: 'Polski',
    code: 'pl_PL',
    country: 'Polska',
  },
  {
    name: 'Português',
    code: 'pt_PT',
    country: 'Portugal',
  },
  {
    name: 'Español',
    code: 'es_ES',
    country: 'España',
  },
  {
    name: 'Türkçe',
    code: 'tr_TR',
    country: 'Türkiye',
  },
  {
    name: 'Български',
    code: 'bg_BG',
    country: 'България',
  },
  {
    name: 'Ελληνικά',
    code: 'el_GR',
    country: 'Ελλάδα',
  },
  {
    name: 'Eesti',
    code: 'et_EE',
    country: 'Eesti',
  },
  {
    name: 'हिंदी',
    code: 'hi_IN',
    country: 'इंडिया',
  },
  {
    name: '日本語',
    code: 'ja_JP',
    country: '日本',
  },
  {
    name: 'Română',
    code: 'ro_RO',
    country: 'România',
  },
  {
    name: 'Español',
    code: 'es_AR',
    country: 'Argentina',
  },
  {
    name: 'Français',
    code: 'fr_FR',
    country: 'France',
  },
  {
    name: 'Maltese',
    code: 'mt_MT',
    country: 'Malta',
  },
  {
    name: 'Slovenski',
    code: 'sl_SL',
    country: 'Slovenija',
  },
  {
    name: 'Slovenský',
    code: 'sk_SK',
    country: 'Slovensko',
  },
  {
    name: 'Українська',
    code: 'uk_UK',
    country: 'Україна',
  },
  {
    name: 'Filipino',
    code: 'fil_PH',
    country: 'Filipino',
  },
  {
    name: '繁體中文',
    code: 'zh_TW',
    country: '台灣',
  },
  {
    name: '简体中文',
    code: 'zh_CN',
    country: '中国',
  },
  {
    name: 'Bahasa Indonesia',
    code: 'id_ID',
    country: 'Indonesia',
  },
  {
    name: 'සිංහල',
    code: 'si_LK',
    country: 'ශ්‍රී ලංකා',
  },
  {
    name: 'اُردُو',
    code: 'ur_PK',
    country: 'پاکستان',
  },
];
<|endoftext|>


<commit_before>'use strict'

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

const log       = require ('ololog')
    , ansi      = require ('ansicolor').nice
    , chai      = require ('chai')
    , expect    = chai.expect
    , assert    = chai.assert
    , testTicker = require ('./test.ticker.js')

/*  ------------------------------------------------------------------------ */

module.exports = async (exchange, symbol) => {

    const method = 'fetchTicker'

    if (exchange.has[method]) {

        // log (symbol.green, 'fetching ticker...')

        let ticker = await exchange.fetchTicker (symbol)

        testTicker (exchange, ticker, method, symbol)

        return ticker

    } else {

        log (symbol.green, 'fetchTicker () not supported')
    }
}

<commit_msg>add one-liner printout to test.fetchTicker.js<commit_after>'use strict'

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

const log       = require ('ololog')
    , ansi      = require ('ansicolor').nice
    , chai      = require ('chai')
    , expect    = chai.expect
    , assert    = chai.assert
    , testTicker = require ('./test.ticker.js')

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

const printTickerOneLiner = (ticker, method, symbol) => {

    log (symbol.toString ().green,
        method,
        ticker['datetime'],
        'bid: '       + (ticker['bid']),
        'ask: '       + (ticker['ask']))
}

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

module.exports = async (exchange, symbol) => {

    const method = 'fetchTicker'

    if (exchange.has[method]) {

        // log (symbol.green, 'fetching ticker...')

        let ticker = await exchange.fetchTicker (symbol)

        testTicker (exchange, ticker, method, symbol)

        printTickerOneLiner (ticker, method, symbol)

        return ticker

    } else {

        log (symbol.green, 'fetchTicker () not supported')
    }
}

<|endoftext|>


<commit_before>'use strict';

var resetUrl = 'http://localhost:8080/camunda/ensureCleanDb/default';
var request = require('request');
var CamSDK = require('camunda-bpm-sdk-js');
var camClient = new CamSDK.Client({
  mock: false,
  apiUri: 'http://localhost:8080/engine-rest'
});

var keys = Object.keys;

module.exports = function (operations, noReset, done) {
  var deferred = protractor.promise.defer();

  if (arguments.length === 1 && typeof operations === 'function') {
    // testHelper(function(){ console.log('setup complete'); });
    done = operations;
    noReset = false;
    operations = {};
  } else if (arguments.length === 1 && typeof operations === 'object') {
    // testHelper(setupObject);
    noReset = false;
    done = function(){};
  } else if (arguments.length === 2 && typeof noReset === 'function') {
    // testHelper(setupObject, function(err, result){ console.log('setup complete', result); });
    done = noReset;
    noReset = false;
  } else if (arguments.length === 2 && typeof noReset === 'boolean') {
    done = function(){};
  }

  var callbacks = [
    function (cb) {
      if (noReset) {
        return cb();
      }

      browser.manage().deleteAllCookies();

      request(resetUrl, function(err, res, body) {
        if (err) {
          return cb(err);
        }
        body = JSON.parse(body);
        cb(null, body);
      });
    }
  ];

  keys(operations).forEach(function (resourceName) {
    keys(operations[resourceName]).forEach(function (methodName) {
      operations[resourceName][methodName].forEach(function (data) {
        var resource = new camClient.resource(resourceName);
        callbacks.push(function (cb) {
          console.info('doing '+resourceName+'.'+methodName, data);
          resource[methodName](data, function(){
            cb();
          });
        });
      });
    });
  });

  CamSDK.utils.series(callbacks, function(err, result) {
    // now all process instances are started, we can start the jobs to create incidents
    if(err) {
      done(err, result);
      deferred.reject();
    }

    var resource = new camClient.resource('job');

    resource.list({}, function(err, result) {
      var jobTasks = [];
      for(var i = 0; i < result.length; i++) {
        jobTasks.push((function(i) {
          return function(cb) {
            resource.setRetries({
              id: result[i].id,
              retries: 0
            }, cb);
          };
        })(i));
      }
      CamSDK.utils.series(jobTasks, function(err, result) {
        done(err, result);
        deferred.fulfill();
      });
    });
  });

  return deferred.promise;
};
<commit_msg>impr(test): prevent logging big chunks when using setup helper<commit_after>'use strict';

var resetUrl = 'http://localhost:8080/camunda/ensureCleanDb/default';
var request = require('request');
var CamSDK = require('camunda-bpm-sdk-js');
var camClient = new CamSDK.Client({
  mock: false,
  apiUri: 'http://localhost:8080/engine-rest'
});

var keys = Object.keys;

module.exports = function (operations, noReset, done) {
  var deferred = protractor.promise.defer();

  if (arguments.length === 1 && typeof operations === 'function') {
    // testHelper(function(){ console.log('setup complete'); });
    done = operations;
    noReset = false;
    operations = {};
  } else if (arguments.length === 1 && typeof operations === 'object') {
    // testHelper(setupObject);
    noReset = false;
    done = function(){};
  } else if (arguments.length === 2 && typeof noReset === 'function') {
    // testHelper(setupObject, function(err, result){ console.log('setup complete', result); });
    done = noReset;
    noReset = false;
  } else if (arguments.length === 2 && typeof noReset === 'boolean') {
    done = function(){};
  }

  var callbacks = [
    function (cb) {
      if (noReset) {
        return cb();
      }

      browser.manage().deleteAllCookies();

      request(resetUrl, function(err, res, body) {
        if (err) {
          return cb(err);
        }
        body = JSON.parse(body);
        cb(null, body);
      });
    }
  ];

  keys(operations).forEach(function (resourceName) {
    keys(operations[resourceName]).forEach(function (methodName) {
      operations[resourceName][methodName].forEach(function (data) {
        var resource = new camClient.resource(resourceName);
        callbacks.push(function (cb) {
          console.info('doing '+resourceName+'.'+methodName);//, data);
          resource[methodName](data, function(){
            cb();
          });
        });
      });
    });
  });

  CamSDK.utils.series(callbacks, function(err, result) {
    // now all process instances are started, we can start the jobs to create incidents
    if(err) {
      done(err, result);
      deferred.reject();
    }

    var resource = new camClient.resource('job');

    resource.list({}, function(err, result) {
      var jobTasks = [];
      for(var i = 0; i < result.length; i++) {
        jobTasks.push((function(i) {
          return function(cb) {
            resource.setRetries({
              id: result[i].id,
              retries: 0
            }, cb);
          };
        })(i));
      }
      CamSDK.utils.series(jobTasks, function(err, result) {
        done(err, result);
        deferred.fulfill();
      });
    });
  });

  return deferred.promise;
};
<|endoftext|>


<commit_before>if (typeof String.prototype.trimLeft !== "function") {
    String.prototype.trimLeft = function() {
        return this.replace(/^\s+/, "");
    };
}
if (typeof String.prototype.trimRight !== "function") {
    String.prototype.trimRight = function() {
        return this.replace(/\s+$/, "");
    };
}
if (typeof Array.prototype.map !== "function") {
    Array.prototype.map = function(callback, thisArg) {
        for (var i=0, n=this.length, a=[]; i<n; i++) {
            if (i in this) a[i] = callback.call(thisArg, this[i]);
        }
        return a;
    };
}
function getCookies() {
  var c = document.cookie, v = 0, cookies = {};
  if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) {
    c = RegExp.$1;
    v = 1;
  }
  if (v === 0) {
    c.split(/[,;]/).map(function(cookie) {
      var parts = cookie.split(/=/, 2),
        name = decodeURIComponent(parts[0].trimLeft()),
        value = parts.length > 1 ? decodeURIComponent(parts[1].trimRight()) : null;
      cookies[name] = value;
    });
  } else {
    c.match(/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g).map(function($0, $1) {
      var name = $0,
        value = $1.charAt(0) === '"' ? $1.substr(1, -1).replace(/\\(.)/g, "$1") : $1;
      cookies[name] = value;
    });
  }
  return cookies;
}
function getCookie(name) {
  return getCookies()[name];
}
function setCookie(name, value) {
  document.cookie = name + "=" + value + "; expires=Thu, 18 Dec 2099 12:00:00 UTC";
}
function htmlToText(html) {
  return $("").html(html).text();
}
function dateDiffInDays(a, b) {
  if (b == null)
    return null;
  // Discard the time and time-zone information.
  var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.round((utc2 - utc1) / (1000 * 60 * 60 * 24));
}

function dateDiffInDaysMinOne(a, b) {
  var d = dateDiffInDays(a, b);
  if (d === null || d < 1)
    return 1;
  return d;
}

function paPopup(cbs) {
  var apiKey, project;
  var p = $("
").attr("id", "projectPopup").css("display", "none");
  $("
").text("Please enter your ProjectAccount API key:").appendTo(p);
  $("<input>").attr("id", "apiKey").css("width", "100%").appendTo(p);
  $("<button>").text("Load Project List").appendTo(p).button().on("click", function() {
    apiKey = $("#apiKey").val();
    setCookie("apiKey", apiKey);

    $("#apiKeyOk").prop("disabled", true);

    $.ajax({
      url: "/project",
      data: {
        key: apiKey
      },
      dataType: "json",
      type: "GET",
      success: function(data, textStatus, jqXHR) {
        console.log("projects status", textStatus);
        console.log("projects data", data);
        $.each(data, function() {
          $("<option>").val(this.id).text(this.name).data("project", this).appendTo("#projectSelector");
        });
        $("#projectSelector").prop("disabled", false);
      },
      complete: function(jqXHR, textStatus) {
        console.log("apikey load: " + textStatus);
        $("#apiKeyOk").prop("disabled", false);
      }
    });
  });

  $("
").appendTo(p);
  $("
").text("Please choose your project:").appendTo(p);
  $("<select>").attr("id", "projectSelector").prop("disabled", true).css("width", "100%").appendTo(p);
  $("<button>").text("Load Project").appendTo(p).button().on("click", function() {
    project = $("#projectSelector > option:selected").data("project");
    if (!project)
      return;

    $("#paLoad").prop("disabled", true);

    $.ajax({
      url: "/projectdata",
      data: {
        key: apiKey,
        project: project.id
      },
      dataType: "json",
      type: "GET",
      success: function(data, textStatus, jqXHR) {
        console.log("project data", data);

        project.start = $.datepicker.parseDate("yy-mm-dd", project.datestart);
        project.end = project.dateend == null ? null : $.datepicker.parseDate("yy-mm-dd", project.dateend);

        (cbs.project || $.noop)(project)

        $.each(data.milestone, function() {
          var milestone = this,
            tasks = $.grep(data.tasks, function(task) {
              return task.milestoneid == milestone.id;
            });

          milestone.start = milestone.dateopen == null ? project.start : $.datepicker.parseDate("yy-mm-dd", milestone.dateopen);
          milestone.end = milestone.datedue == null ? project.end : $.datepicker.parseDate("yy-mm-dd", milestone.datedue);

          (cbs.milestone || $.noop)(project, milestone);
          console.log("milestone tasks: ", tasks);

          $.each(tasks, function() {
            var task = this;

            task.start = task.dateopen == null ? milestone.start : $.datepicker.parseDate("yy-mm-dd", task.dateopen);
            task.end = task.datedue == null ? milestone.end : $.datepicker.parseDate("yy-mm-dd", task.datedue);

            (cbs.task || $.noop)(project, milestone, task);
          });
        });
        $("#projectPopup").dialog("close");
        (cbs.done || $.noop)(false);
      },
      complete: function(jqXHR, textStatus) {
        $("#paLoad").prop("disabled", false);
      }
    });
  });
  $("").html("   ").appendTo(p);
  $("<button>").text("Just load demo data").appendTo(p).button().on("click", function() {
    (cbs.demo || $.noop)(true);
    $("#projectPopup").dialog("close");
  });

  p.appendTo("body");
  $("#apiKey").val(getCookie("apiKey") || ""); //
  $("#projectPopup").dialog({
    modal: true,
    resizable: false,
    width: 400,
    title: "Load Project"
  });
}<commit_msg>devtest<commit_after>if (typeof String.prototype.trimLeft !== "function") {
    String.prototype.trimLeft = function() {
        return this.replace(/^\s+/, "");
    };
}
if (typeof String.prototype.trimRight !== "function") {
    String.prototype.trimRight = function() {
        return this.replace(/\s+$/, "");
    };
}
if (typeof Array.prototype.map !== "function") {
    Array.prototype.map = function(callback, thisArg) {
        for (var i=0, n=this.length, a=[]; i<n; i++) {
            if (i in this) a[i] = callback.call(thisArg, this[i]);
        }
        return a;
    };
}
function getCookies() {
  var c = document.cookie, v = 0, cookies = {};
  if (document.cookie.match(/^\s*\$Version=(?:"1"|1);\s*(.*)/)) {
    c = RegExp.$1;
    v = 1;
  }
  if (v === 0) {
    c.split(/[,;]/).map(function(cookie) {
      var parts = cookie.split(/=/, 2),
        name = decodeURIComponent(parts[0].trimLeft()),
        value = parts.length > 1 ? decodeURIComponent(parts[1].trimRight()) : null;
      cookies[name] = value;
    });
  } else {
    c.match(/(?:^|\s+)([!#$%&'*+\-.0-9A-Z^`a-z|~]+)=([!#$%&'*+\-.0-9A-Z^`a-z|~]*|"(?:[\x20-\x7E\x80\xFF]|\\[\x00-\x7F])*")(?=\s*[,;]|$)/g).map(function($0, $1) {
      var name = $0,
        value = $1.charAt(0) === '"' ? $1.substr(1, -1).replace(/\\(.)/g, "$1") : $1;
      cookies[name] = value;
    });
  }
  return cookies;
}
function getCookie(name) {
  return getCookies()[name];
}
function setCookie(name, value) {
  document.cookie = name + "=" + value + "; expires=Thu, 18 Dec 2099 12:00:00 UTC";
}
function htmlToText(html) {
  return $("").html(html).text();
}
function dateDiffInDays(a, b) {
  if (b == null)
    return null;
  // Discard the time and time-zone information.
  var utc1 = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
  var utc2 = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());

  return Math.round((utc2 - utc1) / (1000 * 60 * 60 * 24));
}

function dateDiffInDaysMinOne(a, b) {
  var d = dateDiffInDays(a, b);
  if (d === null || d < 1)
    return 1;
  return d;
}

function paPopup(cbs) {
  var apiKey, project;
  var p = $("
").attr("id", "projectPopup").css("display", "none");
  $("
").text("Please enter your ProjectAccount API key:").appendTo(p);
  $("<input>").attr("id", "apiKey").css("width", "100%").appendTo(p);
  $("<button>").text("Load Project List").appendTo(p).button().on("click", function() {
    apiKey = $("#apiKey").val();
    setCookie("apiKey", apiKey);

    $("#apiKeyOk").prop("disabled", true);

    $.ajax({
      url: "/project",
      data: {
        key: apiKey
      },
      dataType: "json",
      type: "GET",
      success: function(data, textStatus, jqXHR) {
        console.log("projects status", textStatus);
        console.log("projects data", data);
        $.each(data, function() {
          $("<option>").val(this.id).text(this.name).data("project", this).appendTo("#projectSelector");
        });
        $("#projectSelector").prop("disabled", false);
      },
      complete: function(jqXHR, textStatus) {
        console.log("apikey load: " + textStatus);
        $("#apiKeyOk").prop("disabled", false);
      }
    });
  });

  $("
").appendTo(p);
  $("
").text("Please choose your project:").appendTo(p);
  $("<select>").attr("id", "projectSelector").prop("disabled", true).css("width", "100%").appendTo(p);
  $("<button>").text("Load Project").appendTo(p).button().on("click", function() {
    project = $("#projectSelector > option:selected").data("project");
    if (!project)
      return;

    $("#paLoad").prop("disabled", true);

    $.ajax({
      url: "/projectdata",
      data: {
        key: apiKey,
        project: project.id
      },
      dataType: "json",
      type: "GET",
      success: function(data, textStatus, jqXHR) {
        console.log("project data", data);

        project.start = $.datepicker.parseDate("yy-mm-dd", project.datestart);
        project.end = project.dateend == null ? null : $.datepicker.parseDate("yy-mm-dd", project.dateend);

        (cbs.project || $.noop)(project)

        $.each(data.milestone, function() {
          var milestone = this,
            tasks = $.grep(data.tasks, function(task) {
              return task.milestoneid == milestone.id;
            });

          milestone.start = milestone.dateopen == null ? project.start : $.datepicker.parseDate("yy-mm-dd", milestone.dateopen);
          milestone.end = milestone.datedue == null ? project.end : $.datepicker.parseDate("yy-mm-dd", milestone.datedue);

          (cbs.milestone || $.noop)(project, milestone);
          console.log("milestone tasks: ", tasks);

          $.each(tasks, function() {
            var task = this;

            task.start = task.dateopen == null ? milestone.start : $.datepicker.parseDate("yy-mm-dd", task.dateopen);
            task.end = task.datedue == null ? milestone.end : $.datepicker.parseDate("yy-mm-dd", task.datedue);

            (cbs.task || $.noop)(project, milestone, task);
          });
        });
        $("#projectPopup").dialog("close");
        (cbs.done || $.noop)(false);
      },
      complete: function(jqXHR, textStatus) {
        $("#paLoad").prop("disabled", false);
      }
    });
  });
  $("").html("   ").appendTo(p);
  $("<button>").text("Just load demo data").appendTo(p).button().on("click", function() {
    (cbs.demo || $.noop)(true);
    $("#projectPopup").dialog("close");
  });

  p.appendTo("body");
  $("#apiKey").val(getCookie("apiKey") || ""); //devtest
  $("#projectPopup").dialog({
    modal: true,
    resizable: false,
    width: 400,
    title: "Load Project"
  });
}<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var ok = require('log-ok');
var mkdirp = require('mkdirp');
var writeFile = require('write');
var breakdance = require('..');
var argv = require('yargs')
  .option('file', {
    alias: 'f',
    describe: 'HTML file to convert (with or without .html extension)'
  })
  .option('dest', {
    alias: 'd',
    describe: 'Destination directory. Defaults to process.cwd().',
    default: process.cwd()
  })
  .argv;

var file = argv.file || argv._[0];
var dest = argv.dest || argv._[1];

fs.readFile(path.resolve(process.cwd(), file), function(err, buf) {
  handleError(err);

  var name = path.basename(file, path.extname(file));
  var destPath = path.resolve(dest, name + '.md');

  writeFile(destPath, breakdance(buf.toString(), argv), function(err) {
    handleError(err);
    ok('Markdown file written to', destPath);
  });
});

function handleError(err) {
  if (err) {
    console.error(err);
    process.exit(1);
  }
}
<commit_msg>CLI options and help<commit_after>#!/usr/bin/env node

var fs = require('fs');
var path = require('path');
var ok = require('log-ok');
var writeFile = require('write');
var minimist = require('minimist');
var breakdance = require('..');
var pkg = require('../package');

var opts = {
  alias: {
    condense: 'c',
    domain: 'd',
    help: 'h',
    omit: 'o',
    pick: 'p',
    version: 'V'
  }
};

function help() {
  console.error('Usage: $ breakdance [options] <file> <dest>');
  console.error();
  console.error('  file:  The HTML file to convert to markdown');
  console.error('  dest:  Name of the markdown file to create. By default');
  console.error('         the HTML filename is used with a .md extension');
  console.error();
  console.error('Options:');
  console.error();
  console.error('-c, --condense', 'Collapse more than two newlines to only');
  console.error('', '              two newlines. Enabled by default');
  console.error('-d, --domain', '  Specify the root domain name to prefix onto');
  console.error('', '              "href" or "src" paths that do not star');
  console.error('-o, --omit', '    One or more tags to omit entirely from');
  console.error('', '              the HTML before converting to markdown.');
  console.error('-p, --pick', '    One or more tags to pick entirely from the');
  console.error('', '              HTML before converting to markdown.');
  console.error('--comments', '    Include HTML code comments in the generated');
  console.error('', '              markdown string. Disabled by default');
  console.error();
}

var argv = minimist(process.argv.slice(2), opts);
if (argv.version) {
  console.log('breakdance', pkg.version);
  process.exit();
}

if (argv.help) {
  help();
  process.exit();
}

var file, dest;
if (argv._[0]) {
  file = argv._[0];
  dest = argv._[1];
} else {
  file = argv.file;
  dest = argv.dest;
}

if (!file) {
  help();
  process.exit(1);
}

fs.readFile(path.resolve(process.cwd(), file), function(err, buf) {
  handleError(err);

  var destPath = dest ? path.resolve(dest) : replaceExt(file);

  writeFile(destPath, breakdance(buf.toString(), argv), function(err) {
    handleError(err);
    ok('Markdown file written to', destPath);
  });
});

function handleError(err) {
  if (err) {
    console.error(err);
    process.exit(1);
  }
}

function replaceExt(fp) {
  var name = path.basename(fp, path.extname(fp));
  var dir = path.dirname(fp);
  return path.resolve(dir, name + '.md');
}
<|endoftext|>


<commit_before>(function() {
  'use strict';
  var assert = require('assert');
  var acl = require('../');
  var httpMocks = require('node-mocks-http');

  describe('Acl middleware for express', function() {
    var req, res, next;
    /**
     * Home route
     * traffic to this route should always be allowed
     */

    describe('Home route testing', function() {
      beforeEach(function(done) {
        acl.config();

        req = httpMocks.createRequest({
          method: 'GET',
          url: '/'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};
        done();
      });

      it('should allow traffic for the home route', function(done) {
        //{ status: 403, success: false, error: 'ACCESS DENIED' }
        next = function() {
          res.send({
            status: 200,
            success: true,
            message: 'ACCESS GRANTED'
          });
        };

        acl.authorize(req, res, next);
        var data = res._getData();

        assert(data, true);
        assert.deepEqual(data.status, 200);
        assert.deepEqual(data.success, true);
        assert.deepEqual(data.message, 'ACCESS GRANTED');
        done();
      });

    });

    /**
     * Test if it denies traffic,  when roles are not defined
     */

    describe('Roles', function() {

      beforeEach(function(done) {
        acl.config();

        req = httpMocks.createRequest({
          method: 'GET',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};
        done();
      });

      it('Ensure that authorize middleware is defined', function(done) {
        assert(typeof acl.middleware, 'function');
        done();
      });

      it('should block traffic if no role is defined', function(done) {
        //{ status: 403, success: false, error: 'ACCESS DENIED' }
        acl.authorize(req, res, next);
        var data = res._getData();
        assert(data, true);
        assert(typeof data, 'object');
        assert.deepEqual(data.status, 403);
        assert.deepEqual(data.success, false);
        assert.deepEqual(data.error, 'ACCESS DENIED');
        done();
      });

      it('should allow when role is defined on /api/user/42', function(done) {

        req.decoded.role = 'user';
        /**
         * Ensure that the allowed is false;
         */

        assert(typeof next, 'function');

        acl.authorize(req, res, next);
        /**
         * when traffic is allowed it next method
         *  will be called and changed allowed to true
         *
         */
        var data = res._getData();
        assert(data, true);
        assert.deepEqual(data.status, 200);
        assert.deepEqual(data.success, true);
        assert.deepEqual(data.message, 'ACCESS GRANTED');

        done();
      });

      it('should deny access if no policy for such role', function(done) {

        req.decoded.role = 'guest';
        /**
         * Ensure that the allowed is false;
         */

        assert(typeof next, 'function');

        acl.authorize(req, res, next);
        /**
         * when traffic is allowed it next method
         *  will be called and changed allowed to true
         *
         */
        var data = res._getData();
        assert(data, true);
        assert.deepEqual(data.status, 403);
        assert.deepEqual(data.success, false);
        assert.deepEqual(data.error, 'ACCESS DENIED');

        done();
      });
    });

    /**
     * user policy.
     *
     {
      "group": "user",
      "permissions": [{
        "resource": "users",
        "methods": [
          "POST",
          "GET",
          "PUT"
        ]
      }],
      "action": "allow"
     }
     */
    describe('Policy test based on action "allow"', function() {
      beforeEach(function(done) {
        acl.config({ baseUrl: 'api' });
        done();
      });

      it('should allow POST operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'POST',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be allowed
         * methods: []
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert.deepEqual(data.status, 200);
        assert.deepEqual(data.success, true);
        assert.deepEqual(data.message, 'ACCESS GRANTED');

        done();
      });

      it('should allow PUT operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'PUT',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be allowed
         * methods: []
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert.deepEqual(data.status, 200);
        assert.deepEqual(data.success, true);
        assert.deepEqual(data.message, 'ACCESS GRANTED');

        done();
      });

      it('should denie DElETE operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'DElETE',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be allowed
         * methods: []
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert(typeof data, 'object');
        assert.deepEqual(data.status, 403);
        assert.deepEqual(data.success, false);
        assert.deepEqual(data.error, 'ACCESS DENIED');

        done();
      });
    });

    /**
     * Action: "deny"
     * /**
     * user policy.
     *
     {
      "group": "user",
      "permissions": [{
        "resource": "users",
        "methods": [
          "POST",
          "GET",
          "PUT"
        ]
      }],
      "action": "deny"
     }
     */

    describe('Policy testing based on action: "deny', function() {
      beforeEach(function(done) {
        acl.config({
          baseUrl: 'api',
          filename: 'deny-user-config.json',
          path: './tests/config'
        });
        done();
      });

      it('should allow POST operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'POST',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be denied
         * methods: ["POST","GET","PUT"]
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert(typeof data, 'object');
        assert.deepEqual(data.status, 403);
        assert.deepEqual(data.success, false);
        assert.deepEqual(data.error, 'ACCESS DENIED');

        done();
      });

      it('should allow PUT operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'PUT',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be denied
         * methods: ["POST","GET","PUT"]
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert(typeof data, 'object');
        assert.deepEqual(data.status, 403);
        assert.deepEqual(data.success, false);
        assert.deepEqual(data.error, 'ACCESS DENIED');

        done();
      });

      it('should denie DElETE operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'DElETE',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be allowed
         * {The policy denies traffic on the below methods,
         * but allow traffic to other methods not specified}
         * methods: ["POST","GET","PUT"]
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert.deepEqual(data.status, 200);
        assert.deepEqual(data.success, true);
        assert.deepEqual(data.message, 'ACCESS GRANTED');

        done();
      });

    });

    describe('No policy defined', function() {

      beforeEach(function(done) {
        acl.config({
          baseUrl: 'api'
        });
        done();
      });

      it('should deny if not policy match resource', function(done) {
        req = httpMocks.createRequest({
          method: 'POST',
          url: '/api/cargo/42'
        });
        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be allowed
         * methods: []
         * action: "allow"
         */

        var data = res._getData();
        console.log(data);
        assert(data, true);
        assert.deepEqual(data.status, 403);
        assert.deepEqual(data.success, false);
        assert.deepEqual(data.error, 'ACCESS DENIED');

        done();

      });
    });
  });

})();
<commit_msg>Fix failing tests<commit_after>(function() {
  'use strict';
  var assert = require('assert');
  var acl = require('../');
  var httpMocks = require('node-mocks-http');

  describe('Acl middleware for express', function() {
    var req, res, next;
    /**
     * Home route
     * traffic to this route should always be allowed
     */

    describe('Home route testing', function() {
      beforeEach(function(done) {
        acl.config();

        req = httpMocks.createRequest({
          method: 'GET',
          url: '/'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};
        done();
      });

      it('should allow traffic for the home route', function(done) {
        //{ status: 403, success: false, error: 'ACCESS DENIED' }
        next = function() {
          res.send({
            status: 200,
            success: true,
            message: 'ACCESS GRANTED'
          });
        };

        acl.authorize(req, res, next);
        var data = res._getData();

        assert(data, true);
        assert.deepEqual(data.status, 200);
        assert.deepEqual(data.success, true);
        assert.deepEqual(data.message, 'ACCESS GRANTED');
        done();
      });

    });

    /**
     * Test if it denies traffic,  when roles are not defined
     */

    describe('Roles', function() {

      beforeEach(function(done) {
        acl.config();

        req = httpMocks.createRequest({
          method: 'GET',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse(httpMocks.createResponse({
          eventEmitter: require('events').EventEmitter
        }));

        req.decoded = {};
        req.session = {};
        done();
      });

      it('Ensure that authorize middleware is defined', function(done) {
        assert(typeof acl.middleware, 'function');
        done();
      });

      it('should block traffic if no role is defined', function(done) {
        acl.authorize(req, res, next);
        var data = res._getData();

        assert(data, true);
        assert.deepEqual(res.statusCode, 404);
        done();
      });

      it('should allow when role is defined on /api/user/42', function(done) {

        req.decoded.role = 'user';
        /**
         * Ensure that the allowed is false;
         */

        assert(typeof next, 'function');

        acl.authorize(req, res, next);
        /**
         * when traffic is allowed it next method
         *  will be called and changed allowed to true
         *
         */
        var data = res._getData();
        assert(data, true);
        assert.deepEqual(data.status, 200);
        assert.deepEqual(data.success, true);
        assert.deepEqual(data.message, 'ACCESS GRANTED');

        done();
      });

      it('should deny access if no policy for such role', function(done) {

        req.decoded.role = 'guest';
        /**
         * Ensure that the allowed is false;
         */

        assert(typeof next, 'function');

        acl.authorize(req, res, next);
        /**
         * when traffic is allowed it next method
         *  will be called and changed allowed to true
         *
         */
        var data = res._getData();
        assert(data, true);
        assert.deepEqual(res.statusCode, 404);
        assert.deepEqual(data.message, "group not found");
        done();
      });
    });

    /**
     * user policy.
     *
     {
      "group": "user",
      "permissions": [{
        "resource": "users",
        "methods": [
          "POST",
          "GET",
          "PUT"
        ]
      }],
      "action": "allow"
     }
     */
    describe('Policy test based on action "allow"', function() {
      beforeEach(function(done) {
        acl.config({ baseUrl: 'api' });
        done();
      });

      it('should allow POST operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'POST',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be allowed
         * methods: []
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert.deepEqual(data.status, 200);
        assert.deepEqual(data.success, true);
        assert.deepEqual(data.message, 'ACCESS GRANTED');

        done();
      });

      it('should allow PUT operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'PUT',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be allowed
         * methods: []
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert.deepEqual(data.status, 200);
        assert.deepEqual(data.success, true);
        assert.deepEqual(data.message, 'ACCESS GRANTED');

        done();
      });

      it('should denie DElETE operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'DElETE',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be allowed
         * methods: []
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert(typeof data, 'object');
        assert.deepEqual(data.status, 403);
        assert.deepEqual(data.success, false);
        assert.deepEqual(data.error, 'ACCESS DENIED');

        done();
      });
    });

    /**
     * Action: "deny"
     * /**
     * user policy.
     *
     {
      "group": "user",
      "permissions": [{
        "resource": "users",
        "methods": [
          "POST",
          "GET",
          "PUT"
        ]
      }],
      "action": "deny"
     }
     */

    describe('Policy testing based on action: "deny', function() {
      beforeEach(function(done) {
        acl.config({
          baseUrl: 'api',
          filename: 'deny-user-config.json',
          path: './tests/config'
        });
        done();
      });

      it('should allow POST operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'POST',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be denied
         * methods: ["POST","GET","PUT"]
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert(typeof data, 'object');
        assert.deepEqual(data.status, 403);
        assert.deepEqual(data.success, false);
        assert.deepEqual(data.error, 'ACCESS DENIED');

        done();
      });

      it('should allow PUT operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'PUT',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be denied
         * methods: ["POST","GET","PUT"]
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert(typeof data, 'object');
        assert.deepEqual(data.status, 403);
        assert.deepEqual(data.success, false);
        assert.deepEqual(data.error, 'ACCESS DENIED');

        done();
      });

      it('should denie DElETE operation on /api/user/42', function(done) {
        req = httpMocks.createRequest({
          method: 'DElETE',
          url: '/api/users/42'
        });

        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be allowed
         * {The policy denies traffic on the below methods,
         * but allow traffic to other methods not specified}
         * methods: ["POST","GET","PUT"]
         * action: "allow"
         */

        var data = res._getData();

        assert(data, true);
        assert.deepEqual(data.status, 200);
        assert.deepEqual(data.success, true);
        assert.deepEqual(data.message, 'ACCESS GRANTED');

        done();
      });

    });

    describe('No policy defined', function() {

      beforeEach(function(done) {
        acl.config({
          baseUrl: 'api'
        });
        done();
      });

      it('should deny if not policy match resource', function(done) {
        req = httpMocks.createRequest({
          method: 'POST',
          url: '/api/cargo/42'
        });
        res = httpMocks.createResponse();

        req.decoded = {};
        req.session = {};

        req.decoded.role = 'user';

        acl.authorize(req, res, next);

        /**
         * Traffic should be allowed
         * methods: []
         * action: "allow"
         */

        var data = res._getData();
        console.log(data);
        assert(data, true);
        assert.deepEqual(data.status, 403);
        assert.deepEqual(data.success, false);
        assert.deepEqual(data.error, 'ACCESS DENIED');

        done();

      });
    });
  });

})();
<|endoftext|>