<commit_before>describe('mdInkRipple diretive', function() {

  beforeEach(module('material.core'));

  it('should support custom colors via md-ink-ripple', inject(function ($timeout, $compile, $rootScope) {
    var elem = $compile('

')($rootScope.$new()),
        container, ripple;

    expect(elem.children('.md-ripple-container').length).toBe(0);

    elem.controller('mdInkRipple').createRipple(0, 0);
    container = elem.children('.md-ripple-container');
    expect(container.length).toBe(1);

    ripple = container.children('.md-ripple');
    expect(ripple.length).toBe(1);
    expect(ripple.css('backgroundColor')).toBe('rgb(187, 187, 187)');
  }));

});
<commit_msg>test(ripple): added test to ink-ripple<commit_after>describe('mdInkRipple directive', function() {

  beforeEach(module('material.core'));

  describe('with string values', function () {
    it('should support custom colors', inject(function ($compile, $rootScope) {
      var elem = $compile('

')($rootScope.$new()),
        container, ripple;

      expect(elem.children('.md-ripple-container').length).toBe(0);

      elem.controller('mdInkRipple').createRipple(0, 0);
      container = elem.children('.md-ripple-container');
      expect(container.length).toBe(1);

      ripple = container.children('.md-ripple');
      expect(ripple.length).toBe(1);
      expect(ripple.css('backgroundColor')).toBe('rgb(187, 187, 187)');
    }));

    it('should support true', inject(function ($compile, $rootScope) {
      var elem = $compile('

')($rootScope.$new()),
        container, ripple;

      expect(elem.children('.md-ripple-container').length).toBe(0);

      elem.controller('mdInkRipple').createRipple(0, 0);
      container = elem.children('.md-ripple-container');
      expect(container.length).toBe(1);

      ripple = container.children('.md-ripple');
      expect(ripple.length).toBe(1);
      expect(ripple.css('backgroundColor')).toBe('rgb(0, 0, 0)');
    }));

    it('should support false', inject(function ($compile, $rootScope) {
      var elem = $compile('

')($rootScope.$new()),
        container, ripple;

      expect(elem.children('.md-ripple-container').length).toBe(0);

      elem.controller('mdInkRipple').createRipple(0, 0);
      container = elem.children('.md-ripple-container');
      expect(container.length).toBe(0);

      ripple = container.children('.md-ripple');
      expect(ripple.length).toBe(0);
    }));
  });

  describe('with interpolated false values', function () {
    it('should not ripple with \'false\'', inject(function ($compile, $rootScope) {
      var scope = $rootScope.$new();
      scope.value = false;

      var elem = $compile('

')(scope),
        container, ripple;

      scope.$apply();

      expect(elem.children('.md-ripple-container').length).toBe(0);

      elem.controller('mdInkRipple').createRipple(0, 0);
      container = elem.children('.md-ripple-container');
      expect(container.length).toBe(0);

      ripple = container.children('.md-ripple');
      expect(ripple.length).toBe(0);
    }));

    it('should not ripple with \'0\'', inject(function ($compile, $rootScope) {
      var scope = $rootScope.$new();
      scope.value = 0;

      var elem = $compile('

')(scope),
        container, ripple;

      scope.$apply();

      expect(elem.children('.md-ripple-container').length).toBe(0);

      elem.controller('mdInkRipple').createRipple(0, 0);
      container = elem.children('.md-ripple-container');
      expect(container.length).toBe(0);

      ripple = container.children('.md-ripple');
      expect(ripple.length).toBe(0);
    }));
  });

  describe('with interpolated color values', function () {
    it('should create a ripple', inject(function ($compile, $rootScope) {
      var scope = $rootScope.$new();
      scope.value = '#FF0000';

      var elem = $compile('

')(scope),
        container, ripple;

      scope.$apply();

      expect(elem.children('.md-ripple-container').length).toBe(0);

      var controller = elem.controller('mdInkRipple');

      controller.createRipple(0, 0);
      container = elem.children('.md-ripple-container');
      expect(container.length).toBe(1);

      ripple = container.children('.md-ripple');
      expect(ripple.length).toBe(1);
      expect(ripple.css('backgroundColor')).toBe('rgb(255, 0, 0)');
    }));
  });

  describe('with css color', function () {
    it('should create a ripple', inject(function ($compile, $rootScope, $window) {
      spyOn($window, 'getComputedStyle').and.callFake(function() {
        return { color: '#FF0000' };
      });

      var elem = $compile('

')($rootScope.$new()),
        container, ripple;

      expect(elem.children('.md-ripple-container').length).toBe(0);

      var controller = elem.controller('mdInkRipple');

      controller.createRipple(0, 0);
      container = elem.children('.md-ripple-container');
      expect(container.length).toBe(1);

      ripple = container.children('.md-ripple');
      expect(ripple.length).toBe(1);
      expect(ripple.css('backgroundColor')).toBe('rgb(255, 0, 0)');
    }));
  });
});
<|endoftext|>


<commit_before>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
	res.json({
		status: "ok",
		version: "1"
	});
});

router.get('/announcements/get/', global.apiCall, function(req, res, next) {
	knex("announcements").select("*").then(function(obj) {
		res.json({
			status: "ok",
			feedback: obj
		});
	}).catch(function() {
		res.json({
			status: "error",
			error: "Unknown database error."
		});
	});
});

module.exports = router;
<commit_msg>yay<commit_after>var express = require('express');
var router = express.Router();

router.get('/', function(req, res, next) {
	res.json({
		status: "ok",
		version: "1"
	});
});

router.get('/announcements/get/', global.apiCall, function(req, res, next) {
	knex("announcements").select("*").then(function(obj) {
		res.json({
			status: "ok",
			feedback: obj
		});
	}).catch(function() {
		res.json({
			status: "error",
			error: "Unknown database error."
		});
	});
});

router.get('/events/getDay/', global.apiCall, global.requireUser, global.getUserRecord, function(req, res, next) {
	knex("planner_events").where({
		userId: res.locals.user.id,
		date: req.body.day
	}).select("*").then(function(obj) {
		res.json({
			status: "ok",
			feedback: obj
		});
	}).catch(function() {
		res.json({
			status: "error",
			error: "Unknown database error."
		});
	});
});
module.exports = router;
<|endoftext|>


<commit_before>// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-

define(['jquery'], function($) {
    "use strict";

    function getSides($elem, $slider) {
        var bl = parseInt($elem.css('borderLeftWidth')) + parseInt($slider.css('borderLeftWidth'));
        var br = parseInt($elem.css('borderRightWidth')) + parseInt($slider.css('borderRightWidth'));
        var left = -bl + 1;
        var right = $elem.innerWidth() - $slider.innerWidth() - parseInt($elem.css('borderRightWidth'));
        var center = right / 2 + left;
        return {left: left, right: right, center: center};
    }

    var methods = {
        init: function() {
            return this.each(function() {
                var $elem = $(this);
                var $slider = $('<span>', {'class': 'slider not-dragging'});
                $slider.append($('<span>', {'class': 'handle'}));
                var data = $elem.data('switch');
                if (!data) {
                    data = {};
                    data.activated = undefined;
                    data.insensitive = false;
                    $elem.data('switch', data);
                }

                function mouseup(e) {
                    $slider.addClass('not-dragging');
                    $(document).unbind('mousemove.slider').unbind('mouseup.slider');
                    var s = getSides($elem, $slider);
                    $slider.css('left', data.activated ? s.right : s.left);
                    if (data.activated != data.initialActivated)
                        $elem.trigger('changed', data.activated);
                    return false;
                }

                function mousemove(e) {
                    var s = getSides($elem, $slider);
                    var x = e.pageX - data.initialPageX + data.initialLeft;
                    if (x < s.left)  x = s.left;
                    if (x > s.right) x = s.right;

                    data.activated = x >= s.center;
                    $elem.toggleClass('activated', data.activated);

                    $slider.css('left', x);
                    return false;
                }

                $elem
                    .addClass('_gnome-switch')
                    .append($('<span>', {'class': 'on'}).text("ON"))
                    .append($('<span>', {'class': 'off'}).text("OFF"))
                    .append($slider)

                // Disable selection.
                    .css({'cursor': 'default',
                          '-moz-user-select': 'none'})
                    .attr('unselectable', 'on')
                    .bind('selectstart', function() { return false; });

                methods.activate.call($elem, $elem.hasClass('activated'));
                methods.insensitive.call($elem, $elem.hasClass('insensitive'));

                $slider.bind('mousedown', function(e) {
                    if (data.insensitive)
                        return true;

                    data.initialActivated = data.activated;
                    data.initialPageX = e.pageX;
                    var left = $slider.position().left;
                    data.initialLeft = left;
                    $slider.css({'position': 'absolute', 'left': left});
                    $slider.removeClass('not-dragging');
                    $(document).bind({
                        'mousemove.slider': mousemove,
                        'mouseup.slider': mouseup
                    });
                    return false;
                });

                $elem.bind('click', function(e) {
                    var doToggle;
                    var isActivated = data.activated;
                    if (data.insensitive)
                        return true;

                    if (data.initialPageX === undefined) {
                        doToggle = true;
                    } else {
                        // Make sure we didn't drag before toggling.
                        var travelDistance = Math.abs(e.pageX - data.initialPageX);
                        doToggle = travelDistance < 4 && isActivated == data.initialActivated;

                        delete data.initialActivated;
                        delete data.initialPageX;
                        delete data.initialLeft;
                    }

                    if (doToggle)
                        methods.activate.call($elem, !isActivated);

                    return false;
                });
            });
        },

        activate: function(value) {
            return this.each(function() {
                var $elem = $(this);
                var $slider = $elem.find('span.slider');

                var data = $elem.data('switch');
                if (data.activated == value)
                    return;

                data.activated = value;

                $elem.trigger('changed', value);
                $elem.toggleClass('activated', value);

                var s = getSides($elem, $slider);
                $slider.css('left', value ? s.right : s.left);
                return this;
            });
        },

        insensitive: function(value) {
            return this.each(function() {
                var $elem = $(this);
                var data = $elem.data('switch');
                data.insensitive = value;
                $elem.toggleClass('insensitive', value);
            });
        },
    };

    $.fn.switchify = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist on jQuery.switchify');
        }
    };

});
<commit_msg>switch.js: Make JSLint happy<commit_after>// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*-

define(['jquery'], function($) {
    "use strict";

    function getSides($elem, $slider) {
        var bl = parseInt($elem.css('borderLeftWidth'), 10) + parseInt($slider.css('borderLeftWidth'), 10);
        var br = parseInt($elem.css('borderRightWidth'), 10) + parseInt($slider.css('borderRightWidth'), 10);
        var left = -bl + 1;
        var right = $elem.innerWidth() - $slider.innerWidth() - parseInt($elem.css('borderRightWidth'), 10);
        var center = right / 2 + left;
        return {left: left, right: right, center: center};
    }

    var methods = {
        init: function() {
            return this.each(function() {
                var $elem = $(this);
                var $slider = $('<span>', {'class': 'slider not-dragging'});
                $slider.append($('<span>', {'class': 'handle'}));
                var data = $elem.data('switch');
                if (!data) {
                    data = {};
                    data.activated = undefined;
                    data.insensitive = false;
                    $elem.data('switch', data);
                }

                function mouseup(e) {
                    $slider.addClass('not-dragging');
                    $(document).unbind('mousemove.slider').unbind('mouseup.slider');
                    var s = getSides($elem, $slider);
                    $slider.css('left', data.activated ? s.right : s.left);
                    if (data.activated != data.initialActivated)
                        $elem.trigger('changed', data.activated);
                    return false;
                }

                function mousemove(e) {
                    var s = getSides($elem, $slider);
                    var x = e.pageX - data.initialPageX + data.initialLeft;
                    if (x < s.left)  x = s.left;
                    if (x > s.right) x = s.right;

                    data.activated = x >= s.center;
                    $elem.toggleClass('activated', data.activated);

                    $slider.css('left', x);
                    return false;
                }

                $elem
                    .addClass('_gnome-switch')
                    .append($('<span>', {'class': 'on'}).text("ON"))
                    .append($('<span>', {'class': 'off'}).text("OFF"))
                    .append($slider)

                // Disable selection.
                    .css({'cursor': 'default',
                          '-moz-user-select': 'none'})
                    .attr('unselectable', 'on')
                    .bind('selectstart', function() { return false; });

                methods.activate.call($elem, $elem.hasClass('activated'));
                methods.insensitive.call($elem, $elem.hasClass('insensitive'));

                $slider.bind('mousedown', function(e) {
                    if (data.insensitive)
                        return true;

                    data.initialActivated = data.activated;
                    data.initialPageX = e.pageX;
                    var left = $slider.position().left;
                    data.initialLeft = left;
                    $slider.css({'position': 'absolute', 'left': left});
                    $slider.removeClass('not-dragging');
                    $(document).bind({
                        'mousemove.slider': mousemove,
                        'mouseup.slider': mouseup
                    });
                    return false;
                });

                $elem.bind('click', function(e) {
                    var doToggle;
                    var isActivated = data.activated;
                    if (data.insensitive)
                        return true;

                    if (data.initialPageX === undefined) {
                        doToggle = true;
                    } else {
                        // Make sure we didn't drag before toggling.
                        var travelDistance = Math.abs(e.pageX - data.initialPageX);
                        doToggle = travelDistance < 4 && isActivated == data.initialActivated;

                        delete data.initialActivated;
                        delete data.initialPageX;
                        delete data.initialLeft;
                    }

                    if (doToggle)
                        methods.activate.call($elem, !isActivated);

                    return false;
                });
            });
        },

        activate: function(value) {
            return this.each(function() {
                var $elem = $(this);
                var $slider = $elem.find('span.slider');

                var data = $elem.data('switch');
                if (data.activated == value)
                    return;

                data.activated = value;

                $elem.trigger('changed', value);
                $elem.toggleClass('activated', value);

                var s = getSides($elem, $slider);
                $slider.css('left', value ? s.right : s.left);
                return this;
            });
        },

        insensitive: function(value) {
            return this.each(function() {
                var $elem = $(this);
                var data = $elem.data('switch');
                data.insensitive = value;
                $elem.toggleClass('insensitive', value);
            });
        },
    };

    $.fn.switchify = function(method) {
        if (methods[method]) {
            return methods[method].apply(this, Array.prototype.slice.call(arguments, 1));
        } else if (typeof method === 'object' || !method) {
            return methods.init.apply(this, arguments);
        } else {
            $.error('Method ' +  method + ' does not exist on jQuery.switchify');
        }
    };

});
<|endoftext|>


<commit_before>// ==UserScript==
// @name         Atlas Data Download
// @namespace    https://enopoletus.github.io
// @version      0.25
// @description  Downloads data from U.S. Election Atlas DataGraphs
// @author       E. Harding
// @include      https://uselectionatlas.org/*
// @updateURL    https://enopoletus.github.io/atlasdatagraph.user.js
// @grant        none
// @run-at       document-start
// ==/UserScript==

window.addEventListener("load",
function createHTML() {
    document.getElementById("google").style.display = "none";
    const x = document.getElementsByClassName("content");
    const h = document.createElement("BUTTON");
    const node = document.createTextNode("Press this button to download CSV");
    h.appendChild(node);
    h.setAttribute("id", "silver");
    h.style.maxWidth="120px";
    for(let i=0; i<4; i++){
    x[0].insertBefore(h, x[0].childNodes[0]);}
})
function download_csv(csv, filename) {
    const csvFile = new Blob([csv], {type: "text/csv"});
    const downloadLink = document.createElement("a");
    downloadLink.download = filename;
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}
function export_table_to_csv(html, filename) {
	const csv = [];
	const rowz = document.getElementsByClassName("info")[0].querySelectorAll("tbody")[0];
    const rows = document.getElementsByClassName("info")[0].querySelectorAll("tbody");
    const row1 = []
    row1.push("County");
	//push candidate names into CSV
    const col1 = rowz.querySelectorAll("tr .cnd")[0];
    const colz = rowz.querySelectorAll("tr");
    row1.push(col1.innerText);
    for (let j = 1; j < colz.length; j++){
        row1.push(colz[j].firstChild.innerText.replace(/,/g,''));
    }
		csv.push(row1.join(","));
	//push vote totals into CSV
    for (let i = 0; i < rows.length; i++) {
		const row = [], cols = rows[i].querySelectorAll("b, .dat");
        for (let j = 0; j < cols.length; j++){
        row.push(cols[j].innerText.replace(/,/g,''));}
		csv.push(row.join(","));
	}
    download_csv(csv.join("\n"), filename);
}
window.addEventListener("load", function button(){
document.querySelector("button").addEventListener("click", function () {
    const html=document.querySelector("table").outerHTML;
    const name=document.querySelectorAll(".header")[0].innerText.replace(/\s/g,'');
	export_table_to_csv(html, `${name}.csv`);
})});
<commit_msg>changed atlasdatagraph version<commit_after>// ==UserScript==
// @name         Atlas Data Download
// @namespace    https://enopoletus.github.io
// @version      0.33
// @description  Downloads data from U.S. Election Atlas DataGraphs
// @author       E. Harding
// @include      https://uselectionatlas.org/*
// @updateURL    https://enopoletus.github.io/atlasdatagraph.user.js
// @grant        none
// @run-at       document-start
// ==/UserScript==

window.addEventListener("load",
function createHTML() {
    document.getElementById("google").style.display = "none";
    const x = document.getElementsByClassName("content");
    const h = document.createElement("BUTTON");
    const node = document.createTextNode("Press this button to download CSV");
    h.appendChild(node);
    h.setAttribute("id", "silver");
    h.style.maxWidth="120px";
    for(let i=0; i<4; i++){
    x[0].insertBefore(h, x[0].childNodes[0]);}
})
function download_csv(csv, filename) {
    const csvFile = new Blob([csv], {type: "text/csv"});
    const downloadLink = document.createElement("a");
    downloadLink.download = filename;
    downloadLink.href = window.URL.createObjectURL(csvFile);
    downloadLink.style.display = "none";
    document.body.appendChild(downloadLink);
    downloadLink.click();
}
function export_table_to_csv(html, filename) {
	const csv = [];
	const rowz = document.getElementsByClassName("info")[0].querySelectorAll("tbody")[0];
    const rows = document.getElementsByClassName("info")[0].querySelectorAll("tbody");
    const row1 = []
    row1.push("County");
	//push candidate names into CSV
    const col1 = rowz.querySelectorAll("tr .cnd")[0];
    const colz = rowz.querySelectorAll("tr");
    row1.push(col1.innerText);
    for (let j = 1; j < colz.length; j++){
        row1.push(colz[j].firstChild.innerText.replace(/,/g,''));
    }
		csv.push(row1.join(","));
	//push vote totals into CSV
    for (let i = 0; i < rows.length; i++) {
		const row = [], cols = rows[i].querySelectorAll("b, .dat");
        for (let j = 0; j < cols.length; j++){
        row.push(cols[j].innerText.replace(/,/g,''));}
		csv.push(row.join(","));
	}
    download_csv(csv.join("\n"), filename);
}
window.addEventListener("load", function button(){
document.querySelector("button").addEventListener("click", function () {
    const html=document.querySelector("table").outerHTML;
    const name=document.querySelectorAll(".header")[0].innerText.replace(/\s/g,'');
	export_table_to_csv(html, `${name}.csv`);
})});
<|endoftext|>


<commit_before>'use strict';
var DirectivesModule = angular.module('KMC.directives');
DirectivesModule.directive('modelNumber', [ 'menuSvc', function(menuSvc) {
        return {
            templateUrl: 'template/formcontrols/modelNumber.html',
            replace: true,
            restrict: 'EA',
            scope: {
                model: '=',
                helpnote: '@',
                label: '@',
                'require': '@',
                'kdpattr': '@',
                'strModel': '@model'
            },
            controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
                $scope.defaults = {
                    initvalue: parseInt($attrs['initvalue']) || 0,
                    from: parseInt($attrs['from']) || 0,
                    to: parseInt($attrs['to']) || 100,
                    stepSize: parseInt($attrs['stepsize']) || 1,
                    readonly: false  /// note that a input can be made readonly
                };
                $scope.inputForm = {};
                return $scope;
            }]
        };
    }
    ]).directive('numberInput', ['PlayerService', function(PlayerService) {
        return {
            require: ['^modelNumber', 'ngModel'],
            restrict: 'A',
            scope: true,
            templateUrl: 'template/formcontrols/numberInput.html',
            link: function($scope, $element, $attrs, controllers) {
                var modelScope = controllers[0];
                var ngModelCtrl = controllers[1];
                var inputControl = $element.find('input');
                modelScope.modelCntrl = ngModelCtrl;
                modelScope.inputForm = $scope.inputForm;
                if (typeof $scope.model != 'number' && !(typeof $scope.model == 'string' && parseInt($scope.model))) {
                    ngModelCtrl.$setViewValue($scope.defaults['initvalue'] || 0);
                }
                inputControl.on('blur', function() {
                    if (inputControl.val() === '') {
                        $scope.$apply(function() {
                            ngModelCtrl.$setViewValue($scope.defaults['initvalue'] || 0);
                        });
                    }
                });
                if ($scope.kdpattr) {
                    ngModelCtrl.$viewChangeListeners.push(function(value) {
                        PlayerService.setKDPAttribute($scope.kdpattr, value);
                    });
                }
                ngModelCtrl.$viewChangeListeners.push(function() {
                    modelScope.model = ngModelCtrl.$viewValue;
                });
                var change = function(value) {
                    ngModelCtrl.$setViewValue(value);
                };
                $scope.increment = function() {
                    var resultVal = ngModelCtrl.$viewValue + $scope.defaults.stepSize;
                    if (resultVal < $scope.defaults.to)
                        change(resultVal);
                    else change($scope.defaults.to);
                };
                $scope.decrement = function() {
                    var resultVal = ngModelCtrl.$viewValue - $scope.defaults.stepSize;
                    if (resultVal > $scope.defaults.from)
                        change(resultVal);
                    else change($scope.defaults.from);
                };
            }
        };
    }
    ]);<commit_msg>fix setKDPAttribute<commit_after>'use strict';
var DirectivesModule = angular.module('KMC.directives');
DirectivesModule.directive('modelNumber', [ 'menuSvc', function(menuSvc) {
        return {
            templateUrl: 'template/formcontrols/modelNumber.html',
            replace: true,
            restrict: 'EA',
            scope: {
                model: '=',
                helpnote: '@',
                label: '@',
                'require': '@',
                'kdpattr': '@',
                'strModel': '@model'
            },
            controller: ['$scope', '$element', '$attrs', function($scope, $element, $attrs) {
                $scope.defaults = {
                    initvalue: parseInt($attrs['initvalue']) || 0,
                    from: parseInt($attrs['from']) || 0,
                    to: parseInt($attrs['to']) || 100,
                    stepSize: parseInt($attrs['stepsize']) || 1,
                    readonly: false  /// note that a input can be made readonly
                };
                $scope.inputForm = {};
                return $scope;
            }]
        };
    }
    ]).directive('numberInput', ['PlayerService', function(PlayerService) {
        return {
            require: ['^modelNumber', 'ngModel'],
            restrict: 'A',
            scope: true,
            templateUrl: 'template/formcontrols/numberInput.html',
            link: function($scope, $element, $attrs, controllers) {
                var modelScope = controllers[0];
                var ngModelCtrl = controllers[1];
                var inputControl = $element.find('input');
                modelScope.modelCntrl = ngModelCtrl;
                modelScope.inputForm = $scope.inputForm;
                if (typeof $scope.model != 'number' && !(typeof $scope.model == 'string' && parseInt($scope.model))) {
                    ngModelCtrl.$setViewValue($scope.defaults['initvalue'] || 0);
                }
                inputControl.on('blur', function() {
                    if (inputControl.val() === '') {
                        $scope.$apply(function() {
                            ngModelCtrl.$setViewValue($scope.defaults['initvalue'] || 0);
                        });
                    }
                });
                if ($scope.kdpattr) {
                    ngModelCtrl.$viewChangeListeners.push(function() {
                        PlayerService.setKDPAttribute($scope.kdpattr, ngModelCtrl.$viewValue);
                    });
                }
                ngModelCtrl.$viewChangeListeners.push(function() {
                    modelScope.model = ngModelCtrl.$viewValue;
                });
                var change = function(value) {
                    ngModelCtrl.$setViewValue(value);
                };
                $scope.increment = function() {
                    var resultVal = ngModelCtrl.$viewValue + $scope.defaults.stepSize;
                    if (resultVal < $scope.defaults.to)
                        change(resultVal);
                    else change($scope.defaults.to);
                };
                $scope.decrement = function() {
                    var resultVal = ngModelCtrl.$viewValue - $scope.defaults.stepSize;
                    if (resultVal > $scope.defaults.from)
                        change(resultVal);
                    else change($scope.defaults.from);
                };
            }
        };
    }
    ]);<|endoftext|>


<commit_before>/* globals hopscotch: false */
/*
 * Elements courtesy of https://github.com/gthomas3
 * https://github.com/linkedin/hopscotch/issues/80#issuecomment-48330396
*/
function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
};

function deleteCookie(key) {
  document.cookie = key +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
};

var tour = {
  id: 'hello-spark-on-bluemix',
  steps: [
    {
      target: document.querySelectorAll('.data-nav-title')[0],
      title: 'Welcome to the IBM Bluemix Spark-as-a-Service tl;dr',
      content: 'Hey there!  IBM jStart is honored to be a partner in your journey with Apache Spark, Jupyter Notebooks and OpenStack Object Storage. There\'s plenty of time to read doc and sample code, but join us first on this quick feature fly-by!',
      placement: 'right',
      arrowOffset: 60
    },
    {
      target: ['instances', 'all-instances'],
      title: 'Apache Spark Instances',
      content: 'A multi-tenant Spark cluster means up to 10 separate instances just for you.  As you create \'em, find them here',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: ['storage'],
      title: 'Object Storage',
      content: 'Jupyter (iPython) notebooks need data from somewhere.  Here\'s your goto spot! A tab that shows you OpenStack Object Storage instances',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: ['notebooks', 'all-notebooks'],
      title: 'Jupyter Notebooks',
      content: 'Did you notice this tab to show you all of your Jupyter (iPython) notebooks?',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: document.querySelectorAll('.data-page-icon.services')[0],
      title: 'Services',
      content: 'Look here! Here\'s a view to explore getting data into your services',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.data')[0],
      title: 'Data',
      content: 'Got data sources? View and Edit connections for them here',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.analytics')[0],
      title: 'Analytics',
      content: 'Almost done, this is homebase for Spark using notebooks',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.exchange')[0],
      title: 'Exchange',
      content: 'Behind Door #3, check out 200+ Datasets via the Analytics Exchange.',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.notebooks-desc')[0],
      title: 'Precipitation Analysis',
      content: 'Rain, rain go away - check out the Precipitation Analysis notebook for a simple starter',
      placement: 'top',
      arrowOffset: 30
    },
  ],
  showPrevButton: true,
  scrollTopMargin: 100,
  onEnd: function() {
      setCookie("toured", "toured");
  }
  //onClose: function() {
    //setCookie("toured", "toured");
  //}
},

/* ========== */
/* TOUR SETUP */
/* ========== */
addClickListener = function(el, fn) {
  if (el.addEventListener) {
    el.addEventListener('click', fn, false);
  }
  else {
    el.attachEvent('onclick', fn);
  }
},

init = function() {
  var startBtnId = 'startTourBtn',
      calloutId = 'startTourCallout',
      mgr = hopscotch.getCalloutManager(),
      state = hopscotch.getState();

  if (state && state.indexOf('hello-spark-on-bluemix') === 0) {
    // Already started the tour at some point!
    hopscotch.startTour(tour);
  }
  else {
    // Looking at the page for the first(?) time.
    if (!getCookie("toured")) {
        setTimeout(function() {
          mgr.createCallout({
            id: calloutId,
            target: startBtnId,
            placement: 'left',
            title: 'Friend, interested in a tour?',
            content: 'We shall not cease from exploration
And the end of all our exploring
Will be to arrive where we started
And know the place for the first time.
∞T.S. Eliot∞',
            yOffset: -25,
            arrowOffset: 20,
            width: 240
          });
        }, 100);
    }
  }

  addClickListener(document.getElementById(startBtnId), function() {
    if (!hopscotch.isActive) {
      mgr.removeAllCallouts();
      deleteCookie('toured');
      hopscotch.startTour(tour);
    }
  });
};

init();
<commit_msg>Update spark.js<commit_after>/* globals hopscotch: false */
/*
 * Elements courtesy of https://github.com/gthomas3
 * https://github.com/linkedin/hopscotch/issues/80#issuecomment-48330396
*/
function setCookie(key, value) {
    var expires = new Date();
    expires.setTime(expires.getTime() + (1 * 24 * 60 * 60 * 1000));
    document.cookie = key + '=' + value + ';path=/' + ';expires=' + expires.toUTCString();
};

function deleteCookie(key) {
  document.cookie = key +'=; Path=/; Expires=Thu, 01 Jan 1970 00:00:01 GMT;';
}

function getCookie(key) {
    var keyValue = document.cookie.match('(^|;) ?' + key + '=([^;]*)(;|$)');
    return keyValue ? keyValue[2] : null;
};

var tour = {
  id: 'hello-spark-on-bluemix',
  steps: [
    {
      target: document.querySelectorAll('.data-nav-title')[0],
      title: 'Welcome to the IBM Bluemix Spark-as-a-Service tl;dr',
      content: 'Hey there!  IBM jStart is honored to be a partner in your journey with Apache Spark, Jupyter Notebooks and OpenStack Object Storage. There\'s plenty of time to read doc and sample code, but join us first on this quick feature fly-by!',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: ['instances', 'all-instances'],
      title: 'Apache Spark Instances',
      content: 'A multi-tenant Spark cluster means up to 10 separate instances just for you.  As you create \'em, find them here',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: ['storage'],
      title: 'Object Storage',
      content: 'Jupyter (iPython) notebooks need data from somewhere.  Here\'s your goto spot! A tab that shows you OpenStack Object Storage instances',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: ['notebooks', 'all-notebooks'],
      title: 'Jupyter Notebooks',
      content: 'Did you notice this tab to show you all of your Jupyter (iPython) notebooks?',
      placement: 'bottom',
      arrowOffset: 60
    },
    {
      target: document.querySelectorAll('.data-page-icon.services')[0],
      title: 'Services',
      content: 'Look here! Here\'s a view to explore getting data into your services',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.data')[0],
      title: 'Data',
      content: 'Got data sources? View and Edit connections for them here',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.analytics')[0],
      title: 'Analytics',
      content: 'Almost done, this is homebase for Spark using notebooks',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.data-page-icon.exchange')[0],
      title: 'Exchange',
      content: 'Behind Door #3, check out 200+ Datasets via the Analytics Exchange.',
      placement: 'right',
      arrowOffset: 30
    },
    {
      target: document.querySelectorAll('.notebooks-desc')[0],
      title: 'Precipitation Analysis',
      content: 'Rain, rain go away - check out the Precipitation Analysis notebook for a simple starter',
      placement: 'top',
      arrowOffset: 30
    },
  ],
  showPrevButton: true,
  scrollTopMargin: 100,
  onEnd: function() {
      setCookie("toured", "toured");
  }
  //onClose: function() {
    //setCookie("toured", "toured");
  //}
},

/* ========== */
/* TOUR SETUP */
/* ========== */
addClickListener = function(el, fn) {
  if (el.addEventListener) {
    el.addEventListener('click', fn, false);
  }
  else {
    el.attachEvent('onclick', fn);
  }
},

init = function() {
  var startBtnId = 'startTourBtn',
      calloutId = 'startTourCallout',
      mgr = hopscotch.getCalloutManager(),
      state = hopscotch.getState();

  if (state && state.indexOf('hello-spark-on-bluemix') === 0) {
    // Already started the tour at some point!
    hopscotch.startTour(tour);
  }
  else {
    // Looking at the page for the first(?) time.
    if (!getCookie("toured")) {
        setTimeout(function() {
          mgr.createCallout({
            id: calloutId,
            target: startBtnId,
            placement: 'left',
            title: 'Friend, interested in a tour?',
            content: 'We shall not cease from exploration
And the end of all our exploring
Will be to arrive where we started
And know the place for the first time.
∞T.S. Eliot∞',
            yOffset: -25,
            arrowOffset: 20,
            width: 240
          });
        }, 100);
    }
  }

  addClickListener(document.getElementById(startBtnId), function() {
    if (!hopscotch.isActive) {
      mgr.removeAllCallouts();
      deleteCookie('toured');
      hopscotch.startTour(tour);
    }
  });
};

init();
<|endoftext|>


<commit_before><commit_msg>Change post_ext_init.js from symlink to file<commit_after>// Initialization stuff that must be performed after the ExtJS Javascript files
// have been loaded but before the rest of our own code is run

// Top-level namespace for the application
Ext.namespace('app', 'app.search', 'app.search.languageRow', 'app.search.languageRow.queryTerm');

// Set BLANK_IMAGE_URL as required by Ext
Ext.BLANK_IMAGE_URL = urlRoot + '/images/default/s.gif';

// Required by Rails' CSRF protection
Ext.Ajax.extraParams = {authenticity_token: authenticityToken};

// Putting the authenticity token into extraParams makes POST the default
// action, but we still want it to be GET
Ext.Ajax.method = 'GET';
<|endoftext|>


<commit_before>
// Select our active lineMode choice
var selectLineModeButton = function() {
  var index = $($('.line_mode.btn-group button.line_mode.btn[value="' + myLineMode + '"]')).attr('name');
  $('.line_mode.btn-group button.line_mode.btn.active').removeClass('active');
  $($('.line_mode.btn-group button.line_mode.btn')[index]).addClass('active');
};

// Select our active areaMode choice
var selectAreaModeButton = function() {
  var index = $($('.area_mode.btn-group button.area_mode.btn[value="' + myAreaMode + '"]')).attr('name');
  $('.area_mode.btn-group button.area_mode.btn.active').removeClass('active');
  $($('.area_mode.btn-group button.area_mode.btn')[index]).addClass('active');
};

// Select our active logMode choice
var selectLogModeButton = function() {
  var index = $($('.log_mode.btn-group button.log_mode.btn[value="' + myLogMode + '"]')).attr('name');
  $('.log_mode.btn-group button.log_mode.btn.active').removeClass('active');
  $($('.log_mode.btn-group button.log_mode.btn')[index]).addClass('active');
};

// Select our active drawNullAsZero choice
var selectNullModeButton = function() {
  var index = $($('.null_mode.btn-group button.null_mode.btn[value="' + myNullMode + '"]')).attr('name');
  $('.null_mode.btn-group button.null_mode.btn.active').removeClass('active');
  $($('.null_mode.btn-group button.null_mode.btn')[index]).addClass('active');
};

// Store our updated settings
var updateGraph = function(cb) {
  var myUrl = window.location.pathname;
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    data: {
      'overrides': {
        'lineMode': myLineMode,
        'areaMode': myAreaMode,
        'logBase': myLogMode,
        'drawNullAsZero': myNullMode
      }
    },
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    type: 'PUT',
    url: myUrl
  }).done(function(d) {
    console.log('Graph ' + window.location.pathname.split('/').pop() + ' successfully updated');
    cb();
  });
};

// Grab configuration blob and construct our graph urls
var renderGraphs = function() {
  var myUrl = window.location.pathname;
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    url: myUrl
  }).done(function(d) {
    if (typeof d === 'undefined') {
      console.log('No graphs found');
    }
    updateLocalSettings($.extend($.parseJSON(d.configuration), $.parseJSON(d.overrides)));
    var targets = [];
    for (var i in $.parseJSON(d.configuration).target) {
      targets.push({name: $.parseJSON(d.configuration).target[i]});
    }
    var c = $.extend($.parseJSON(d.configuration), $.parseJSON(d.overrides), {height: 300, options: '&hideLegend=false', targets: targets});
    $('div.graphs').append('

');
    $('div.graphs div.row').append('

');
    $('div.graphs div.row div.graph').append('

');
    $('div.graph div.preview').append('');
    selectActiveIntervalButton();
    renderDescription(d.description);
    renderTags();
    selectLineModeButton();
    selectAreaModeButton();
    selectLogModeButton();
    selectNullModeButton();
  });
};

// Populate our description box
var renderDescription = function(description) {
  if ((typeof description === 'string') && (description.length > 0)) {
    myDescription = description;
    $('span#description').text(description);
  } else {
    $('span#description').html('Click here to add your own description of this graph.');
  }
};

// Reset description form
var resetDescriptionForm = function(desc) {
  $('div.description-wrapper span#description').removeClass('open').addClass('closed');
  $('div.description-wrapper span#description').children('textarea').remove();
  if ((typeof desc === 'string') && (desc.length > 0)) {
    $('div.description-wrapper span#description').text(desc);
  } else if (myDescription.length > 0) {
    $('div.description-wrapper span#description').text(myDescription);
  } else {
    $('div.description-wrapper span#description').append('Click here to add your own description of this graph.');
  }
  $('div.description-wrapper a').remove();
  return false;
};

// Populate our tags box
var renderTags = function() {
  gatherTags(function(tags) {
    $('div.tags-wrapper div.tags ul').remove();
    $('div.tags-wrapper div.tags span').remove();
    $('div.tags-wrapper div.tags').append('

');
    if ((typeof tags === 'object') && (tags.length > 0)) {
      for (var i in tags) {
        $('div.tags-wrapper div.tags ul').append('
 ' + tags[i].name + '
');
      }
    }
    $('div.tags-wrapper div.tags ul').append('
 Add a new tag...
');
  });
};

// Delete a tag
var deleteTag = function(id, cb) {
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    type: 'DELETE',
    url: window.location.pathname + '/tags/' + id
  }).done(function(d) {
    console.log('Tag ' + id + ' successfully deleted');
    cb();
  });
};

// Add a tag
var addTag = function(name, cb) {
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    data: {'name': name},
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    type: 'POST',
    url: window.location.pathname + '/tags'
  }).done(function(d) {
    console.log('Tag ' + name + ' successfully added');
    cb();
  });
};

// Gather tags
var gatherTags = function(cb) {
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    url: window.location.pathname + '/tags'
  }).done(function(d) {
    cb(d);
  });
};

// Invert details button when opened
$('div.well').on('click', 'a.details.btn.closed', function() {
  $(this).text('Close Details').removeClass('closed').addClass('open').addClass('btn-inverse');
});

// Revert details button when closed
$('div.well').on('click', 'a.details.btn.open', function() {
  $(this).text('Details').removeClass('open').addClass('closed').removeClass('btn-inverse');
});

// Convert description span into editable textarea
$('div.description-wrapper').on('click', 'span.closed#description', function() {
  $(this).unbind('click').removeClass('closed').addClass('open');
  $(this).html('<textarea class="description span4" rows="10">' + myDescription + '</textarea>');
  $(this).after('Update Description');
  $(this).after('Cancel');
  $(this).children('textarea').focus().select();
  return false;
});

// Reset description element on cancel
$('div.description-wrapper').on('click', 'a.description_cancel', resetDescriptionForm);

// Update description on submit
$('div.description-wrapper').on('click', 'a.description_submit', function() {
  var newDescription = $(this).parent().children('span#description').children('textarea').val();
  myDescription = newDescription;
  updateObjectAttributes({ 'description': newDescription }, function() {
    resetDescriptionForm(newDescription);
  });
  return false;
});

// Delete tag from list
$('div.tags-wrapper').on('click', 'a.tag_delete i', function() {
  var myTagId = $(this).parent().parent('li').attr('id');
  deleteTag(myTagId, function() {
    renderTags();
  });
  return false;
});

// Convert tag span into editable field
$('div.tags-wrapper').on('click', 'a.tag_add i', function() {
  $(this).parent('a').parent('li').children('span.tag_add').html('<input class="input-medium" type="text" name="new_tag"></input>');
  $(this).addClass('open');
  $('input[name="new_tag"]').focus();
});

// Add new tag
$('div.tags-wrapper div.tags').on('keypress', 'span.tag_add input[name="new_tag"]', function(e) {
  if (e.which === 13) {
    var myNewTag = $(this).val();
    addTag(myNewTag, function() {
      renderTags();
    });
    return false;
  }
});

// Reset tag input field on focusout
// XXX Potential race condition in that we call GET twice...
// XXX first after adding a tag (above), then here on focusout.
// XXX Not really a race condition per se, but a wasted call nonetheless.
$('div.tags-wrapper div.tags').on('focusout', 'span.tag_add input[name="new_tag"]', function() {
  renderTags();
});

// Update lineMode on selection
$('.line_mode.btn-group button.line_mode.btn').click(function() {
  if ($(this).attr('value').length > 0) {
    myLineMode = $(this).attr('value');
    updateGraph(function() {
      clearGraphs();
      renderGraphs();
    });
  }
});

// Update areaMode on selection
$('.area_mode.btn-group button.area_mode.btn').click(function() {
  if ($(this).attr('value').length > 0) {
    myAreaMode = $(this).attr('value');
    updateGraph(function() {
      clearGraphs();
      renderGraphs();
    });
  }
});

// Update logMode on selection
$('.log_mode.btn-group button.log_mode.btn').click(function() {
  if ($(this).attr('value').length > 0) {
    myLogMode = $(this).attr('value');
    updateGraph(function() {
      clearGraphs();
      renderGraphs();
    });
  }
});

// Update drawNullAsZero on selection
$('.null_mode.btn-group button.null_mode.btn').click(function() {
  if ($(this).attr('value').length > 0) {
    myNullMode = $(this).attr('value');
    updateGraph(function() {
      clearGraphs();
      renderGraphs();
    });
  }
});

// POST a new gist from profile
$('.tools.btn-group button.tools.btn.gist').click(function() {
  var graph_url = $('.graph .preview img').attr('src');
  console.log(graph_url);
  $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    data: {'url': graph_url},
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    type: 'POST',
    url: window.location.pathname + '/gists'
  }).done(function(d) {
    $('div.header').before('
' +
      '<button type="button" class="close" data-dismiss="alert">×</button>' +
      'Snapshot successfully created by ' + d.owner + '.');
  });
  return false;
});

// Not used in graph profile
var scrollNextPage = function() {
  return true;
}
<commit_msg>add created_at to alert<commit_after>
// Select our active lineMode choice
var selectLineModeButton = function() {
  var index = $($('.line_mode.btn-group button.line_mode.btn[value="' + myLineMode + '"]')).attr('name');
  $('.line_mode.btn-group button.line_mode.btn.active').removeClass('active');
  $($('.line_mode.btn-group button.line_mode.btn')[index]).addClass('active');
};

// Select our active areaMode choice
var selectAreaModeButton = function() {
  var index = $($('.area_mode.btn-group button.area_mode.btn[value="' + myAreaMode + '"]')).attr('name');
  $('.area_mode.btn-group button.area_mode.btn.active').removeClass('active');
  $($('.area_mode.btn-group button.area_mode.btn')[index]).addClass('active');
};

// Select our active logMode choice
var selectLogModeButton = function() {
  var index = $($('.log_mode.btn-group button.log_mode.btn[value="' + myLogMode + '"]')).attr('name');
  $('.log_mode.btn-group button.log_mode.btn.active').removeClass('active');
  $($('.log_mode.btn-group button.log_mode.btn')[index]).addClass('active');
};

// Select our active drawNullAsZero choice
var selectNullModeButton = function() {
  var index = $($('.null_mode.btn-group button.null_mode.btn[value="' + myNullMode + '"]')).attr('name');
  $('.null_mode.btn-group button.null_mode.btn.active').removeClass('active');
  $($('.null_mode.btn-group button.null_mode.btn')[index]).addClass('active');
};

// Store our updated settings
var updateGraph = function(cb) {
  var myUrl = window.location.pathname;
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    data: {
      'overrides': {
        'lineMode': myLineMode,
        'areaMode': myAreaMode,
        'logBase': myLogMode,
        'drawNullAsZero': myNullMode
      }
    },
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    type: 'PUT',
    url: myUrl
  }).done(function(d) {
    console.log('Graph ' + window.location.pathname.split('/').pop() + ' successfully updated');
    cb();
  });
};

// Grab configuration blob and construct our graph urls
var renderGraphs = function() {
  var myUrl = window.location.pathname;
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    url: myUrl
  }).done(function(d) {
    if (typeof d === 'undefined') {
      console.log('No graphs found');
    }
    updateLocalSettings($.extend($.parseJSON(d.configuration), $.parseJSON(d.overrides)));
    var targets = [];
    for (var i in $.parseJSON(d.configuration).target) {
      targets.push({name: $.parseJSON(d.configuration).target[i]});
    }
    var c = $.extend($.parseJSON(d.configuration), $.parseJSON(d.overrides), {height: 300, options: '&hideLegend=false', targets: targets});
    $('div.graphs').append('

');
    $('div.graphs div.row').append('

');
    $('div.graphs div.row div.graph').append('

');
    $('div.graph div.preview').append('');
    selectActiveIntervalButton();
    renderDescription(d.description);
    renderTags();
    selectLineModeButton();
    selectAreaModeButton();
    selectLogModeButton();
    selectNullModeButton();
  });
};

// Populate our description box
var renderDescription = function(description) {
  if ((typeof description === 'string') && (description.length > 0)) {
    myDescription = description;
    $('span#description').text(description);
  } else {
    $('span#description').html('Click here to add your own description of this graph.');
  }
};

// Reset description form
var resetDescriptionForm = function(desc) {
  $('div.description-wrapper span#description').removeClass('open').addClass('closed');
  $('div.description-wrapper span#description').children('textarea').remove();
  if ((typeof desc === 'string') && (desc.length > 0)) {
    $('div.description-wrapper span#description').text(desc);
  } else if (myDescription.length > 0) {
    $('div.description-wrapper span#description').text(myDescription);
  } else {
    $('div.description-wrapper span#description').append('Click here to add your own description of this graph.');
  }
  $('div.description-wrapper a').remove();
  return false;
};

// Populate our tags box
var renderTags = function() {
  gatherTags(function(tags) {
    $('div.tags-wrapper div.tags ul').remove();
    $('div.tags-wrapper div.tags span').remove();
    $('div.tags-wrapper div.tags').append('

');
    if ((typeof tags === 'object') && (tags.length > 0)) {
      for (var i in tags) {
        $('div.tags-wrapper div.tags ul').append('
 ' + tags[i].name + '
');
      }
    }
    $('div.tags-wrapper div.tags ul').append('
 Add a new tag...
');
  });
};

// Delete a tag
var deleteTag = function(id, cb) {
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    type: 'DELETE',
    url: window.location.pathname + '/tags/' + id
  }).done(function(d) {
    console.log('Tag ' + id + ' successfully deleted');
    cb();
  });
};

// Add a tag
var addTag = function(name, cb) {
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    data: {'name': name},
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    type: 'POST',
    url: window.location.pathname + '/tags'
  }).done(function(d) {
    console.log('Tag ' + name + ' successfully added');
    cb();
  });
};

// Gather tags
var gatherTags = function(cb) {
  return $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    url: window.location.pathname + '/tags'
  }).done(function(d) {
    cb(d);
  });
};

// Invert details button when opened
$('div.well').on('click', 'a.details.btn.closed', function() {
  $(this).text('Close Details').removeClass('closed').addClass('open').addClass('btn-inverse');
});

// Revert details button when closed
$('div.well').on('click', 'a.details.btn.open', function() {
  $(this).text('Details').removeClass('open').addClass('closed').removeClass('btn-inverse');
});

// Convert description span into editable textarea
$('div.description-wrapper').on('click', 'span.closed#description', function() {
  $(this).unbind('click').removeClass('closed').addClass('open');
  $(this).html('<textarea class="description span4" rows="10">' + myDescription + '</textarea>');
  $(this).after('Update Description');
  $(this).after('Cancel');
  $(this).children('textarea').focus().select();
  return false;
});

// Reset description element on cancel
$('div.description-wrapper').on('click', 'a.description_cancel', resetDescriptionForm);

// Update description on submit
$('div.description-wrapper').on('click', 'a.description_submit', function() {
  var newDescription = $(this).parent().children('span#description').children('textarea').val();
  myDescription = newDescription;
  updateObjectAttributes({ 'description': newDescription }, function() {
    resetDescriptionForm(newDescription);
  });
  return false;
});

// Delete tag from list
$('div.tags-wrapper').on('click', 'a.tag_delete i', function() {
  var myTagId = $(this).parent().parent('li').attr('id');
  deleteTag(myTagId, function() {
    renderTags();
  });
  return false;
});

// Convert tag span into editable field
$('div.tags-wrapper').on('click', 'a.tag_add i', function() {
  $(this).parent('a').parent('li').children('span.tag_add').html('<input class="input-medium" type="text" name="new_tag"></input>');
  $(this).addClass('open');
  $('input[name="new_tag"]').focus();
});

// Add new tag
$('div.tags-wrapper div.tags').on('keypress', 'span.tag_add input[name="new_tag"]', function(e) {
  if (e.which === 13) {
    var myNewTag = $(this).val();
    addTag(myNewTag, function() {
      renderTags();
    });
    return false;
  }
});

// Reset tag input field on focusout
// XXX Potential race condition in that we call GET twice...
// XXX first after adding a tag (above), then here on focusout.
// XXX Not really a race condition per se, but a wasted call nonetheless.
$('div.tags-wrapper div.tags').on('focusout', 'span.tag_add input[name="new_tag"]', function() {
  renderTags();
});

// Update lineMode on selection
$('.line_mode.btn-group button.line_mode.btn').click(function() {
  if ($(this).attr('value').length > 0) {
    myLineMode = $(this).attr('value');
    updateGraph(function() {
      clearGraphs();
      renderGraphs();
    });
  }
});

// Update areaMode on selection
$('.area_mode.btn-group button.area_mode.btn').click(function() {
  if ($(this).attr('value').length > 0) {
    myAreaMode = $(this).attr('value');
    updateGraph(function() {
      clearGraphs();
      renderGraphs();
    });
  }
});

// Update logMode on selection
$('.log_mode.btn-group button.log_mode.btn').click(function() {
  if ($(this).attr('value').length > 0) {
    myLogMode = $(this).attr('value');
    updateGraph(function() {
      clearGraphs();
      renderGraphs();
    });
  }
});

// Update drawNullAsZero on selection
$('.null_mode.btn-group button.null_mode.btn').click(function() {
  if ($(this).attr('value').length > 0) {
    myNullMode = $(this).attr('value');
    updateGraph(function() {
      clearGraphs();
      renderGraphs();
    });
  }
});

// POST a new gist from profile
$('.tools.btn-group button.tools.btn.gist').click(function() {
  var graph_url = $('.graph .preview img').attr('src');
  $.ajax({
    accepts: {json: 'application/json'},
    cache: false,
    data: {'url': graph_url},
    dataType: 'json',
    error: function(xhr, textStatus, errorThrown) { console.log(errorThrown); },
    type: 'POST',
    url: window.location.pathname + '/gists'
  }).done(function(d) {
    $('div.header').before(
      '
' +
      '<button type="button" class="close" data-dismiss="alert">×</button>' +
      'Snapshot successfully created by ' + d.owner + ' on ' + d.created_at + '.'
    );
  });
  return false;
});

// Not used in graph profile
var scrollNextPage = function() {
  return true;
}
<|endoftext|>


<commit_before>/*global describe, it, beforeEach */
/**
 * observe-plus.js - https://github.com/podefr/observe-plus
 * Copyright(c) 2014-2015 Olivier Scherrer <pode.fr@gmail.com>
 * MIT Licensed
 */
"use strict";

var chai = require("chai");
var expect = chai.expect;
var asap = require("asap");
var sinon = require("sinon");

var observeArray = require("../src/observe-plus").observe;

describe("GIVEN an observed array", function () {

    var array, observer, aggregatedEvents;

    function resetAggregatedEvents() {
        aggregatedEvents = [];
    }

    beforeEach(function () {
        array = [];
        observer = observeArray(array);
    });

    describe("WHEN observing newly added items", function () {
        var dispose, spy;

        beforeEach(function () {
            spy = sinon.spy();
            dispose = observer.observe("splice", spy);
        });

        afterEach(function () {
            spy.reset();
        });

        it("THEN shouldn't publish any event before a new item is added", function (done) {
            asap(function () {
                expect(spy.called).to.be.false;
                done();
            });
        });

        describe("WHEN a new item is added", function () {
            beforeEach(function () {
                array.push("newItem");
            });

            it("THEN should publish a splice event", function (done) {
                asap(function () {
                    expect(spy.lastCall.args[0]).to.eql({
                        type: 'splice',
                        object: ['newItem'],
                        index: 0,
                        removed: [],
                        addedCount: 1
                    });
                    done();
                });
            });

            it("THEN published only one event", function (done) {
                asap(function () {
                    expect(spy.callCount).to.equal(1);
                    done();
                });
            });

            describe("WHEN destroying", function () {
                beforeEach(function () {
                    observer.destroy();

                    array.push("value");
                });

                it("THEN doesn't publish events anymore", function (done) {
                    asap(function () {
                        expect(spy.callCount).to.equal(1);
                        done();
                    });
                });
            });

            describe("WHEN the item is modified", function () {
                beforeEach(function () {
                    observer.observe("update", spy);
                    array[0] = "updatedItem";
                });

                it("THEN calls the observer with the updated event", function (done) {
                    asap(function () {
                        expect(spy.lastCall.args[0]).to.eql({
                            type: "update",
                            object: ["updatedItem"],
                            name: "0",
                            oldValue: "newItem"
                        });
                        done();
                    });
                });
            });

            describe("WHEN the property is deleted", function () {
                beforeEach(function () {
                    observer.observe("splice", spy);
                    array.pop();
                });

                it("THEN calls the observer with the splice event", function (done) {
                    asap(function () {
                        expect(spy.lastCall.args[0]).to.eql({
                            type: "splice",
                            object: [],
                            index: 0,
                            removed: ["newItem"],
                            addedCount: 0
                        });
                        done();
                    });
                });
            });
        });
    });

    describe("WHEN observing specific indexes", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            observer.observeValue(0, spy);
            array.push("value");
            array[0] = "newValue";
        });

        afterEach(function () {
            sinon.spy();
        });

        it("THEN publishes an event with the new value and a new event with the old value", function (done) {
            asap(function () {
                expect(spy.firstCall.args[0]).to.eql({
                    type: "splice",
                    object: ["newValue"],
                    index: "0",
                    removed: [],
                    addedCount: 1
                });

                expect(spy.lastCall.args[0]).to.eql({
                    type: "update",
                    name: "0",
                    object: ["newValue"],
                    oldValue: "value"
                });
                done();
            });
        });
    });

    describe("WHEN observing nested properties", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            observer.observeValue("0.nested.property", spy);
            array.push({
                nested: {
                    property: true
                }
            });
        });

        afterEach(function () {
            spy.reset();
        });

        it("THEN publishes an event with the new value", function (done) {
            asap(function () {
                expect(spy.firstCall.args[0]).to.eql({
                    type: "splice",
                    object: array,
                    index: "0.nested.property",
                    removed: [],
                    addedCount: 1
                });
                done();
            });
        });

        describe("WHEN the nested property is updated", function () {
            beforeEach(function () {
                array[0].nested.property = false;
            });

            it("THEN publishes an event with the new value", function (done) {
                asap(function () {
                    expect(spy.secondCall.args[0]).to.eql({
                        type: "update",
                        object: array,
                        name: "0.nested.property",
                        oldValue: true
                    });
                    done();
                });
            });
        });

        describe("WHEN the nested property is deleted", function () {
            beforeEach(function () {
                delete array[0].nested.property;
            });

            it("THEN publishes a delete event", function (done) {
                asap(function () {
                    expect(spy.secondCall.args[0]).to.eql({
                        type: "delete",
                        object: array,
                        name: "0.nested.property",
                        oldValue: true
                    });
                    done();
                });
            });
        });

        describe("WHEN a parent object of the nested property is deleted", function () {
            beforeEach(function () {
                delete array[0].nested;
            });

            it("THEN publishes a delete event", function (done) {
                asap(function () {

                    debugger;
                    expect(spy.secondCall.args[0]).to.eql({
                        type: "delete",
                        object: array,
                        name: "0.nested.property",
                        oldValue: true
                    });
                    done();
                });
            });
        });
    });

    describe("WHEN observing specific indexes only once", function () {
        var dispose;

        beforeEach(function () {
            resetAggregatedEvents();
            dispose = observer.observeValueOnce(0, function (ev) {
                aggregatedEvents.push([ev]);
            });
            array.push("value");
            array[0] = "newValue";
        });

        it("THEN the observer is called", function (done) {
            asap(function () {
                var firstEvent = aggregatedEvents[0][0];
                expect(firstEvent.type).to.equal("splice");
                expect(firstEvent.index).to.equal("0");
                expect(firstEvent.object[0]).to.equal("newValue");
                done();
            });
        });

        it("THEN is disposed of", function (done) {
            asap(function () {
                expect(dispose()).to.be.false;
                done();
            });
        });
    });

    describe("WHEN pausing the updates", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();

            observer.observe("splice", spy);
            observer.pause();
        });

        describe("WHEN a property changes", function () {
            beforeEach(function () {
                array.push("value");
                array.pop();
            });

            it("THEN the observers aren't called", function (done) {
                asap(function () {
                    expect(spy.called).to.be.false;
                    done();
                });
            });

            describe("WHEN resuming publishing the updates", function () {
                beforeEach(function () {
                    observer.resume();
                });

                it("THEN calls all the observers in order", function (done) {
                    asap(function () {
                        expect(spy.firstCall.args[0].addedCount).to.equal(1);
                        expect(spy.secondCall.args[0].removed.length).to.equal(1);
                        done();
                    });
                });

                describe("WHEN the updates are paused and resumed again", function () {
                    beforeEach(function () {
                        spy.reset();
                        observer.pause();
                        array.push("lastValue");
                        observer.resume();
                    });

                    it("THEN only publishes the new event", function (done) {
                        asap(function () {
                            expect(spy.callCount).to.equal(1);
                            done();
                        });
                    });
                });
            });
        });
    });
});

describe("GIVEN an array with a nested array ", function () {
    var array, observer;

    beforeEach(function () {
        array = [{nested: []}];
        observer = observeArray(array);
    });

    describe("WHEN observing splice events", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            observer.observe("splice", spy);
        });

        afterEach(function () {
            spy.reset();
        });

        describe("WHEN a value is added to the nested array", function () {
            beforeEach(function () {
                array[0].nested.push(1);
            });

            it("THEN publishes an event", function (done) {
                asap(function () {
                    expect(spy.firstCall.args[0]).to.eql({
                        type: 'splice',
                        object: array,
                        index: '0.nested.0',
                        removed: [],
                        addedCount: 1
                    });
                    done();
                });
            });
        });
    });

    describe("WHEN observing update events", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            observer.observe("update", spy);
            array[0].nested.push(1);
        });

        afterEach(function () {
            spy.reset();
        });

        describe("WHEN a value in the nested array is updated", function () {
            beforeEach(function () {
                array[0].nested[0] = 2
            });

            it("THEN publishes an event", function (done) {
                asap(function () {
                    expect(spy.firstCall.args[0]).to.eql({
                        type: 'update',
                        object: array,
                        name: '0.nested.0',
                        oldValue: 1
                    });
                    done();
                });
            });
        });
    });

    describe("WHEN observing update events", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            observer.observe("update", spy);
            array[0].nested.push(1);
        });

        afterEach(function () {
            spy.reset();
        });

        describe("WHEN the nested array is updated", function () {
            beforeEach(function () {
                array[0].nested = [];
            });

            it("THEN publishes an event", function (done) {
                asap(function () {
                    expect(spy.firstCall.args[0]).to.eql({
                        type: 'update',
                        object: array,
                        name: '0.nested',
                        oldValue: [1]
                    });
                    done();
                });
            });
        });
    });
});<commit_msg>removed aggregatedEvents<commit_after>/*global describe, it, beforeEach */
/**
 * observe-plus.js - https://github.com/podefr/observe-plus
 * Copyright(c) 2014-2015 Olivier Scherrer <pode.fr@gmail.com>
 * MIT Licensed
 */
"use strict";

var chai = require("chai");
var expect = chai.expect;
var asap = require("asap");
var sinon = require("sinon");

var observeArray = require("../src/observe-plus").observe;

describe("GIVEN an observed array", function () {

    var array, observer;

    beforeEach(function () {
        array = [];
        observer = observeArray(array);
    });

    describe("WHEN observing newly added items", function () {
        var dispose, spy;

        beforeEach(function () {
            spy = sinon.spy();
            dispose = observer.observe("splice", spy);
        });

        afterEach(function () {
            spy.reset();
        });

        it("THEN shouldn't publish any event before a new item is added", function (done) {
            asap(function () {
                expect(spy.called).to.be.false;
                done();
            });
        });

        describe("WHEN a new item is added", function () {
            beforeEach(function () {
                array.push("newItem");
            });

            it("THEN should publish a splice event", function (done) {
                asap(function () {
                    expect(spy.lastCall.args[0]).to.eql({
                        type: 'splice',
                        object: ['newItem'],
                        index: 0,
                        removed: [],
                        addedCount: 1
                    });
                    done();
                });
            });

            it("THEN published only one event", function (done) {
                asap(function () {
                    expect(spy.callCount).to.equal(1);
                    done();
                });
            });

            describe("WHEN destroying", function () {
                beforeEach(function () {
                    observer.destroy();

                    array.push("value");
                });

                it("THEN doesn't publish events anymore", function (done) {
                    asap(function () {
                        expect(spy.callCount).to.equal(1);
                        done();
                    });
                });
            });

            describe("WHEN the item is modified", function () {
                beforeEach(function () {
                    observer.observe("update", spy);
                    array[0] = "updatedItem";
                });

                it("THEN calls the observer with the updated event", function (done) {
                    asap(function () {
                        expect(spy.lastCall.args[0]).to.eql({
                            type: "update",
                            object: ["updatedItem"],
                            name: "0",
                            oldValue: "newItem"
                        });
                        done();
                    });
                });
            });

            describe("WHEN the property is deleted", function () {
                beforeEach(function () {
                    observer.observe("splice", spy);
                    array.pop();
                });

                it("THEN calls the observer with the splice event", function (done) {
                    asap(function () {
                        expect(spy.lastCall.args[0]).to.eql({
                            type: "splice",
                            object: [],
                            index: 0,
                            removed: ["newItem"],
                            addedCount: 0
                        });
                        done();
                    });
                });
            });
        });
    });

    describe("WHEN observing specific indexes", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            observer.observeValue(0, spy);
            array.push("value");
            array[0] = "newValue";
        });

        afterEach(function () {
            sinon.spy();
        });

        it("THEN publishes an event with the new value and a new event with the old value", function (done) {
            asap(function () {
                expect(spy.firstCall.args[0]).to.eql({
                    type: "splice",
                    object: ["newValue"],
                    index: "0",
                    removed: [],
                    addedCount: 1
                });

                expect(spy.lastCall.args[0]).to.eql({
                    type: "update",
                    name: "0",
                    object: ["newValue"],
                    oldValue: "value"
                });
                done();
            });
        });
    });

    describe("WHEN observing nested properties", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            observer.observeValue("0.nested.property", spy);
            array.push({
                nested: {
                    property: true
                }
            });
        });

        afterEach(function () {
            spy.reset();
        });

        it("THEN publishes an event with the new value", function (done) {
            asap(function () {
                expect(spy.firstCall.args[0]).to.eql({
                    type: "splice",
                    object: array,
                    index: "0.nested.property",
                    removed: [],
                    addedCount: 1
                });
                done();
            });
        });

        describe("WHEN the nested property is updated", function () {
            beforeEach(function () {
                array[0].nested.property = false;
            });

            it("THEN publishes an event with the new value", function (done) {
                asap(function () {
                    expect(spy.secondCall.args[0]).to.eql({
                        type: "update",
                        object: array,
                        name: "0.nested.property",
                        oldValue: true
                    });
                    done();
                });
            });
        });

        describe("WHEN the nested property is deleted", function () {
            beforeEach(function () {
                delete array[0].nested.property;
            });

            it("THEN publishes a delete event", function (done) {
                asap(function () {
                    expect(spy.secondCall.args[0]).to.eql({
                        type: "delete",
                        object: array,
                        name: "0.nested.property",
                        oldValue: true
                    });
                    done();
                });
            });
        });

        describe("WHEN a parent object of the nested property is deleted", function () {
            beforeEach(function () {
                delete array[0].nested;
            });

            it("THEN publishes a delete event", function (done) {
                asap(function () {
                    expect(spy.secondCall.args[0]).to.eql({
                        type: "delete",
                        object: array,
                        name: "0.nested.property",
                        oldValue: true
                    });
                    done();
                });
            });
        });
    });

    describe("WHEN observing specific indexes only once", function () {
        var dispose, spy;

        beforeEach(function () {
            spy = sinon.spy();
            dispose = observer.observeValueOnce(0, spy);
            array.push("value");
            array[0] = "newValue";
        });

        it("THEN the observer is called", function (done) {
            asap(function () {
                expect(spy.firstCall.args[0]).to.eql({
                    type: "splice",
                    index: "0",
                    object: ["newValue"],
                    removed: [],
                    addedCount: 1
                });
                done();
            });
        });

        it("THEN is disposed of", function (done) {
            asap(function () {
                expect(dispose()).to.be.false;
                done();
            });
        });
    });

    describe("WHEN pausing the updates", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();

            observer.observe("splice", spy);
            observer.pause();
        });

        describe("WHEN a property changes", function () {
            beforeEach(function () {
                array.push("value");
                array.pop();
            });

            it("THEN the observers aren't called", function (done) {
                asap(function () {
                    expect(spy.called).to.be.false;
                    done();
                });
            });

            describe("WHEN resuming publishing the updates", function () {
                beforeEach(function () {
                    observer.resume();
                });

                it("THEN calls all the observers in order", function (done) {
                    asap(function () {
                        expect(spy.firstCall.args[0].addedCount).to.equal(1);
                        expect(spy.secondCall.args[0].removed.length).to.equal(1);
                        done();
                    });
                });

                describe("WHEN the updates are paused and resumed again", function () {
                    beforeEach(function () {
                        spy.reset();
                        observer.pause();
                        array.push("lastValue");
                        observer.resume();
                    });

                    it("THEN only publishes the new event", function (done) {
                        asap(function () {
                            expect(spy.callCount).to.equal(1);
                            done();
                        });
                    });
                });
            });
        });
    });
});

describe("GIVEN an array with a nested array ", function () {
    var array, observer;

    beforeEach(function () {
        array = [{nested: []}];
        observer = observeArray(array);
    });

    describe("WHEN observing splice events", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            observer.observe("splice", spy);
        });

        afterEach(function () {
            spy.reset();
        });

        describe("WHEN a value is added to the nested array", function () {
            beforeEach(function () {
                array[0].nested.push(1);
            });

            it("THEN publishes an event", function (done) {
                asap(function () {
                    expect(spy.firstCall.args[0]).to.eql({
                        type: 'splice',
                        object: array,
                        index: '0.nested.0',
                        removed: [],
                        addedCount: 1
                    });
                    done();
                });
            });
        });
    });

    describe("WHEN observing update events", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            observer.observe("update", spy);
            array[0].nested.push(1);
        });

        afterEach(function () {
            spy.reset();
        });

        describe("WHEN a value in the nested array is updated", function () {
            beforeEach(function () {
                array[0].nested[0] = 2
            });

            it("THEN publishes an event", function (done) {
                asap(function () {
                    expect(spy.firstCall.args[0]).to.eql({
                        type: 'update',
                        object: array,
                        name: '0.nested.0',
                        oldValue: 1
                    });
                    done();
                });
            });
        });
    });

    describe("WHEN observing update events", function () {
        var spy;

        beforeEach(function () {
            spy = sinon.spy();
            observer.observe("update", spy);
            array[0].nested.push(1);
        });

        afterEach(function () {
            spy.reset();
        });

        describe("WHEN the nested array is updated", function () {
            beforeEach(function () {
                array[0].nested = [];
            });

            it("THEN publishes an event", function (done) {
                asap(function () {
                    expect(spy.firstCall.args[0]).to.eql({
                        type: 'update',
                        object: array,
                        name: '0.nested',
                        oldValue: [1]
                    });
                    done();
                });
            });
        });
    });
});<|endoftext|>