<commit_before>// Dev node: Come on!!! this is super ugly...
// If you find a stable way to debug the jest tests please fork me!
// As documented here: https://facebook.github.io/jest/docs/troubleshooting.html is not working as far of May/17
if (typeof global === 'undefined' && typeof window !== 'undefined') global = window;

let HIDE_SUCCESS_VALIDATION = true;

// init section

global._mockJest = null;

global.clearTest = () => {
	global._mockJest = {
		errors: 0,
		passed: 0,
		descriptions: []
	};
};
global.clearTest();

global.describe = (description, cbDefineIts) => {
	global._mockJest.descriptions.push({
		description,
		its: []
	});

	cbDefineIts();
	startTests();
};

global.describe.skip = description => global.describe(description, ()=>console.log('               --> skipped'));

global.it = (description, cbTest) => {
	global._mockJest.descriptions[global._mockJest.descriptions.length - 1].its.push({
		description,
		cbTest
	});
	startTests();
};

global.it.skip = description => global.it(description, () => console.log('          --> skipped'));

global.expect = (expectValue) => {
	return comparisons(expectValue);
};

global.fail = (error) => {
  console.log(`        FAILED, by error`, error);
  global._mockJest.errors++;
};

// start and functions section

let comparisons = (expectValue, not = false) => {
	return {
		get not() {
			return comparisons(expectValue, true)
		},
		toBe: (toBeValue) => {
			let result = expectValue === toBeValue;
			if (not) result = !result;
			if (result) {
				if (!HIDE_SUCCESS_VALIDATION) console.log(`        Success, equal value [${expectValue} === ${toBeValue}]`);
				global._mockJest.passed++;
			}
			else {
				console.log(`        FAILED, ${not ? "not " : ""}expected [${toBeValue}] but received [${expectValue}]`);
				global._mockJest.errors++;
			}
		}
	}
};

let startTimer = null;

function startTests() {
	if (startTimer) clearTimeout(startTimer);
	startTimer = setTimeout(executeTests, 100);
}

function executeTests() {
	let descriptions = [].concat(global._mockJest.descriptions);

	const processTheNextDescription = () => {
		let description = descriptions.shift();
		if (description) {
			executeADescription(description, () => {
				processTheNextDescription();
			});
		}
		else {
			finished();
		}
	};

	// start
	processTheNextDescription();
}

function executeADescription(description, cbCompleted) {
	console.log('Description::: Start:', description.description);
	let its = [].concat(description.its);

	executeIts(its, () => {
		console.log('Description::: Finished:', description.description);
		console.log('');
		cbCompleted();
	});
}

function executeIts(its, cbCompleted) {
	let it = its.shift();
	if (!it) {
		cbCompleted();
		return;
	}

	console.log('    it:::', it.description);
	if (it.cbTest.length === 0) {
		it.cbTest();
		executeIts(its, cbCompleted);
	}
	else {
		it.cbTest(() => {
			executeIts(its, cbCompleted);
		});
	}
}

function exit(code) {
	if (typeof process !== 'undefined' && typeof process.exit !== 'undefined'){
		process.exit(code);
	}
}

function finished() {
	let report = 'All TEST finished, results:' + ' ' + 'errors:' + ' ' + global._mockJest.errors + ' ' + 'passed:' + ' ' + global._mockJest.passed;
	console.log('');
	if (global._mockJest.errors) {
    console.log('xx   xx');
    console.log(' xx xx ');
    console.log('  xxx  ');
    console.log(' xx xx ');
    console.log('xx   xx' + report);
		exit(100);
	}
	else {
    console.log('      vv');
    console.log('     vv');
    console.log('vv  vv');
    console.log(' vvvv');
    console.log('  vv      ' + report);
		exit(0);
	}
}
<commit_msg>Maintenance: clean up<commit_after>if (typeof global === 'undefined' && typeof window !== 'undefined') global = window;

let HIDE_SUCCESS_VALIDATION = true;

// init section

global._mockJest = null;

global.clearTest = () => {
	global._mockJest = {
		errors: 0,
		passed: 0,
		descriptions: []
	};
};
global.clearTest();

global.describe = (description, cbDefineIts) => {
	global._mockJest.descriptions.push({
		description,
		its: []
	});

	cbDefineIts();
	startTests();
};

global.describe.skip = description => global.describe(description, ()=>console.log('               --> skipped'));

global.it = (description, cbTest) => {
	global._mockJest.descriptions[global._mockJest.descriptions.length - 1].its.push({
		description,
		cbTest
	});
	startTests();
};

global.it.skip = description => global.it(description, () => console.log('          --> skipped'));

global.expect = (expectValue) => {
	return comparisons(expectValue);
};

global.fail = (error) => {
  console.log(`        FAILED, by error`, error);
  global._mockJest.errors++;
};

// start and functions section

let comparisons = (expectValue, not = false) => {
	return {
		get not() {
			return comparisons(expectValue, true)
		},
		toBe: (toBeValue) => {
			let result = expectValue === toBeValue;
			if (not) result = !result;
			if (result) {
				if (!HIDE_SUCCESS_VALIDATION) console.log(`        Success, equal value [${expectValue} === ${toBeValue}]`);
				global._mockJest.passed++;
			}
			else {
				console.log(`        FAILED, ${not ? "not " : ""}expected [${toBeValue}] but received [${expectValue}]`);
				global._mockJest.errors++;
			}
		}
	}
};

let startTimer = null;

function startTests() {
	if (startTimer) clearTimeout(startTimer);
	startTimer = setTimeout(executeTests, 100);
}

function executeTests() {
	let descriptions = [].concat(global._mockJest.descriptions);

	const processTheNextDescription = () => {
		let description = descriptions.shift();
		if (description) {
			executeADescription(description, () => {
				processTheNextDescription();
			});
		}
		else {
			finished();
		}
	};

	// start
	processTheNextDescription();
}

function executeADescription(description, cbCompleted) {
	console.log('Description::: Start:', description.description);
	let its = [].concat(description.its);

	executeIts(its, () => {
		console.log('Description::: Finished:', description.description);
		console.log('');
		cbCompleted();
	});
}

function executeIts(its, cbCompleted) {
	let it = its.shift();
	if (!it) {
		cbCompleted();
		return;
	}

	console.log('    it:::', it.description);
	if (it.cbTest.length === 0) {
		it.cbTest();
		executeIts(its, cbCompleted);
	}
	else {
		it.cbTest(() => {
			executeIts(its, cbCompleted);
		});
	}
}

function exit(code) {
	if (typeof process !== 'undefined' && typeof process.exit !== 'undefined'){
		process.exit(code);
	}
}

function finished() {
	let report = 'All TEST finished, results:' + ' ' + 'errors:' + ' ' + global._mockJest.errors + ' ' + 'passed:' + ' ' + global._mockJest.passed;
	console.log('');
	if (global._mockJest.errors) {
    console.log('xx   xx');
    console.log(' xx xx ');
    console.log('  xxx  ');
    console.log(' xx xx ');
    console.log('xx   xx' + report);
		exit(100);
	}
	else {
    console.log('      vv');
    console.log('     vv');
    console.log('vv  vv');
    console.log(' vvvv');
    console.log('  vv      ' + report);
		exit(0);
	}
}
<|endoftext|>


<commit_before>import Ember from 'ember';
import layout from '../templates/components/ember-circle-progress';

export default Ember.Component.extend({
  layout,

  size: 80,
  value: 0.5,
  responsive: false,
  startAngle: -Math.PI,
  reverse: false,
  thickness: "false",
  lineCap: 'butt',
  fill: { gradient: ["#3aeabb", "#fdd250"] },
  emptyFill: "rgba(0, 0, 0, .1)",
  animation: { duration: 1200 },
  animationStartValue: 0.0,
  textColor: 'gray',
  showText: true,

  classNames: ['ember-circle-progress'],
  classNameBindings: ['responsive:ember-circle-progress-responsive'],

  didInsertElement() {
    let size = this.get('size');
    let textColor = this.get('textColor');

    let circle = this.$().circleProgress({
      value: this.get('value'),
      size: size,
      startAngle: this.get('startAngle'),
      reverse: this.get('reverse'),
      thickness: this.get('thickness'),
      lineCap: this.get('lineCap'),
      fill: this.get('fill'),
      emptyFill: this.get('emptyFill'),
      animation: this.get('animation'),
      animationStartValue: this.get('animationStartValue'),
    });

    if (this.get('showText')) {

      circle.on('circle-inited', (event, progress, value) => {
        this.drawText(textColor, size, value);
      });

      circle.on('circle-animation-progress', (event, progress, value) => {
        this.drawText(textColor, size, value);
      });
    }

  },

  drawText(textColor, size, valueStep) {
    let ctx = this.$('canvas')[0].getContext('2d');

    ctx.fillStyle = textColor;
    ctx.font = (size/4) + 'px arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    let value = Math.round(100 * valueStep) + '%';
    ctx.fillText(value, size/2, size/2);
  }
});
<commit_msg>Arreglo menor para que los eventos no queden propagando errores.<commit_after>import Ember from 'ember';
import layout from '../templates/components/ember-circle-progress';

export default Ember.Component.extend({
  layout,

  size: 80,
  value: 0.5,
  responsive: false,
  startAngle: -Math.PI,
  reverse: false,
  thickness: "false",
  lineCap: 'butt',
  fill: { gradient: ["#3aeabb", "#fdd250"] },
  emptyFill: "rgba(0, 0, 0, .1)",
  animation: { duration: 1200 },
  animationStartValue: 0.0,
  textColor: 'gray',
  showText: true,

  classNames: ['ember-circle-progress'],
  classNameBindings: ['responsive:ember-circle-progress-responsive'],

  didInsertElement() {
    let size = this.get('size');
    let textColor = this.get('textColor');

    let circle = this.$().circleProgress({
      value: this.get('value'),
      size: size,
      startAngle: this.get('startAngle'),
      reverse: this.get('reverse'),
      thickness: this.get('thickness'),
      lineCap: this.get('lineCap'),
      fill: this.get('fill'),
      emptyFill: this.get('emptyFill'),
      animation: this.get('animation'),
      animationStartValue: this.get('animationStartValue'),
    });

    if (this.get('showText')) {

      circle.on('circle-inited', (event, progress, value) => {
        this.drawText(textColor, size, value);
      });

      circle.on('circle-animation-progress', (event, progress, value) => {
        this.drawText(textColor, size, value);
      });
    }

  },

  drawText(textColor, size, valueStep) {
    let canvas = this.$('canvas');

    if (!canvas) {
      return;
    }

    let ctx = canvas[0].getContext('2d');

    ctx.fillStyle = textColor;
    ctx.font = (size/4) + 'px arial';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';

    let value = Math.round(100 * valueStep) + '%';
    ctx.fillText(value, size/2, size/2);
  }
});
<|endoftext|>


<commit_before>import { h, Component } from 'preact';
import { Router } from 'preact-router';

import Header from './header';
import Home from '../routes/home';
import Profile from '../routes/profile';
// import Home from 'async!../routes/home';
// import Profile from 'async!../routes/profile';

export default class App extends Component {

	/** Gets fired when the route changes.
	 *	@param {Object} event		"change" event from [preact-router](http://git.io/preact-router)
	 *	@param {string} event.url	The newly routed URL
	 */
	handleRoute = e => {
		this.currentUrl = e.url;
	};

	render() {
		return (

				<Router onChange={this.handleRoute}>
					<Home path="/" />
					<Profile path="/profile/" user="me" />
					<Profile path="/profile/:user" />
				</Router>

		);
	}
}
<commit_msg>chore(template): removes async prefix for imports in the template (#19)<commit_after>import { h, Component } from 'preact';
import { Router } from 'preact-router';

import Header from './header';

// Code-splitting is automated for routes
import Home from '../routes/home';
import Profile from '../routes/profile';

export default class App extends Component {

	/** Gets fired when the route changes.
	 *	@param {Object} event		"change" event from [preact-router](http://git.io/preact-router)
	 *	@param {string} event.url	The newly routed URL
	 */
	handleRoute = e => {
		this.currentUrl = e.url;
	};

	render() {
		return (

				<Router onChange={this.handleRoute}>
					<Home path="/" />
					<Profile path="/profile/" user="me" />
					<Profile path="/profile/:user" />
				</Router>

		);
	}
}
<|endoftext|>


<commit_before>/**
 * @module Ink.UI.Carousel_1
 * @author inkdev AT sapo.pt
 * @version 1
 */
Ink.createModule('Ink.UI.Carousel', '1',
    ['Ink.UI.Common_1', 'Ink.Dom.Event_1', 'Ink.Dom.Css_1', 'Ink.Dom.Element_1', 'Ink.UI.Pagination_1', 'Ink.Dom.Browser_1', 'Ink.Dom.Selector_1'],
    function(Aux, InkEvent, Css, InkElement, Pagination, Browser/*, Selector*/) {
    'use strict';

    /*
     * TODO:
     *  keyboardSupport
     *  swipe
     */

    /**
     * @class Ink.UI.Carousel_1
     * @constructor
     *
     * @param {String|DOMElement} selector
     * @param {Object} [options]
     *  @param {String} [options.axis='x'] Can be `'x'` or `'y'`, for a horizontal or vertical carousel
     *  @param {Boolean} [options.center=false] Center the carousel.
     *  @TODO @param {Boolean} [options.keyboardSupport=false] Enable keyboard support
     *  @param {String|DOMElement|Ink.UI.Pagination_1} [options.pagination] Either an `<ul>` element to add pagination markup to, or an `Ink.UI.Pagination` instance to use.
     *  @param {Function} [options.onChange] Callback for when the page is changed.
     */
    var Carousel = function(selector, options) {
        this._handlers = {
            paginationChange: Ink.bind(this._onPaginationChange, this),
            windowResize:     Ink.bind(this.refit, this)
        };

        InkEvent.observe(window, 'resize', this._handlers.windowResize);

        this._element = Aux.elOrSelector(selector, '1st argument');

        this._options = Ink.extendObj({
            axis:           'x',
            hideLast:       false,
            center:         false,
            keyboardSupport:false,
            pagination:     null,
            onChange:       null
        }, options || {}, InkElement.data(this._element));

        this._isY = (this._options.axis === 'y');

        var rEl = this._element;

        var ulEl = Ink.s('ul.stage', rEl);
        this._ulEl = ulEl;

        InkElement.removeTextNodeChildren(ulEl);

        if (this._options.hideLast) {
            var hiderEl = document.createElement('div');
            hiderEl.className = 'hider';
            this._element.appendChild(hiderEl);
            hiderEl.style.position = 'absolute';
            hiderEl.style[ this._isY ? 'left' : 'top' ] = '0';  // fix to top..
            hiderEl.style[ this._isY ? 'right' : 'bottom' ] = '0';  // and bottom...
            hiderEl.style[ this._isY ? 'bottom' : 'right' ] = '0';  // and move to the end.
            this._hiderEl = hiderEl;
        }

        this.refit();

        if (this._isY) {
            // Override white-space: no-wrap which is only necessary to make sure horizontal stuff stays horizontal, but breaks stuff intended to be vertical.
            this._ulEl.style.whiteSpace = 'normal';
        }

        if (this._options.pagination) {
            if (Aux.isDOMElement(this._options.pagination) || typeof this._options.pagination === 'string') {
                // if dom element or css selector string...
                this._pagination = new Pagination(this._options.pagination, {
                    size:     this._numPages,
                    onChange: this._handlers.paginationChange
                });
            } else {
                // assumes instantiated pagination
                this._pagination = this._options.pagination;
                this._pagination._options.onChange = this._handlers.paginationChange;
                this._pagination.setSize(this._numPages);
                this._pagination.setCurrent(0);
            }
        }
    };

    Carousel.prototype = {
        /**
         * Measure the carousel once again, adjusting the involved elements'
         * sizes. Called automatically when the window resizes, in order to
         * cater for changes from responsive media queries, for instance.
         *
         * @method refit
         */
        refit: function() {
            this._liEls = Ink.ss('li.slide', this._ulEl);
            var numItems = this._liEls.length;
            this._ctnLength = this._size(this._element);
            this._elLength = this._size(this._liEls[0]);
            this._itemsPerPage = Math.floor( this._ctnLength / this._elLength  );
            this._numPages = Math.ceil( numItems / this._itemsPerPage );
            this._deltaLength = this._itemsPerPage * this._elLength;

            if (this._isY) {
                this._element.style.width = this._liEls[0].offsetWidth + 'px';
                this._ulEl.style.width  =  this._liEls[0].offsetWidth + 'px';
            } else {
                this._ulEl.style.height =  this._liEls[0].offsetHeight + 'px';
            }

            this._center();
            this._updateHider();
            this._IE7();

            if (this._pagination) {
                this._pagination.setSize(this._numPages);
                this._pagination.setCurrent(0);
            }
        },

        _size: function (elm) {
            var dims = InkElement.outerDimensions(elm)
            return this._isY ? dims[1] : dims[0];
        },

        _center: function() {
            if (!this._options.center) { return; }
            var gap = Math.floor( (this._ctnLength - (this._elLength * this._itemsPerPage) ) / 2 );

            var pad;
            if (this._isY) {
                pad = [gap, 'px 0'];
            }
            else {
                pad = ['0 ', gap, 'px'];
            }
            this._ulEl.style.padding = pad.join('');
        },

        _updateHider: function() {
            if (!this._hiderEl) { return; }
            var gap = Math.floor( this._ctnLength - (this._elLength * this._itemsPerPage) );
            if (this._options.center) {
                gap /= 2;
            }
            this._hiderEl.style[ this._isY ? 'height' : 'width' ] = gap + 'px';
        },

        /**
         * Refit stuff for IE7 because it won't support inline-block.
         *
         * @method _IE7
         * @private
         */
        _IE7: function () {
            if (Browser.IE && '' + Browser.version.split('.')[0] === '7') {
                var numPages = this._numPages;
                var slides = Ink.ss('li.slide', this._ulEl);
                var stl = function (prop, val) {slides[i].style[prop] = val; };
                for (var i = 0, len = slides.length; i < len; i++) {
                    stl('position', 'absolute');
                    stl(this._isY ? 'top' : 'left', (i * this._elLength) + 'px');
                }
            }
        },

        _onPaginationChange: function(pgn) {
            var currPage = pgn.getCurrent();
            this._ulEl.style[ this._options.axis === 'y' ? 'top' : 'left'] = ['-', currPage * this._deltaLength, 'px'].join('');
            if (this._options.onChange) {
                this._options.onChange.call(this, currPage);
            }
        }
    };

    return Carousel;

});
<commit_msg>starting up<commit_after>/**
 * @module Ink.UI.Carousel_1
 * @author inkdev AT sapo.pt
 * @version 1
 */
Ink.createModule('Ink.UI.Carousel', '1',
    ['Ink.UI.Common_1', 'Ink.Dom.Event_1', 'Ink.Dom.Css_1', 'Ink.Dom.Element_1', 'Ink.UI.Pagination_1', 'Ink.Dom.Browser_1', 'Ink.Dom.Selector_1'],
    function(Aux, InkEvent, Css, InkElement, Pagination, Browser/*, Selector*/) {
    'use strict';

    /*
     * TODO:
     *  keyboardSupport
     *  swipe
     */

    /**
     * @class Ink.UI.Carousel_1
     * @constructor
     *
     * @param {String|DOMElement} selector
     * @param {Object} [options]
     *  @param {String} [options.axis='x'] Can be `'x'` or `'y'`, for a horizontal or vertical carousel
     *  @param {Boolean} [options.center=false] Center the carousel.
     *  @TODO @param {Boolean} [options.keyboardSupport=false] Enable keyboard support
     *  @param {String|DOMElement|Ink.UI.Pagination_1} [options.pagination] Either an `<ul>` element to add pagination markup to, or an `Ink.UI.Pagination` instance to use.
     *  @param {Function} [options.onChange] Callback for when the page is changed.
     */
    var Carousel = function(selector, options) {
        this._handlers = {
            paginationChange: Ink.bind(this._onPaginationChange, this),
            windowResize:     Ink.bind(this.refit, this)
        };

        InkEvent.observe(window, 'resize', this._handlers.windowResize);

        this._element = Aux.elOrSelector(selector, '1st argument');

        var options = this._options = Ink.extendObj({
            axis:           'x',
            hideLast:       false,
            center:         false,
            keyboardSupport:false,
            pagination:     null,
            onChange:       null,
            swipe:          true
        }, options || {}, InkElement.data(this._element));

        this._isY = (options.axis === 'y');

        var rEl = this._element;

        var ulEl = Ink.s('ul.stage', rEl);
        this._ulEl = ulEl;

        InkElement.removeTextNodeChildren(ulEl);

        if (options.hideLast) {
            var hiderEl = document.createElement('div');
            hiderEl.className = 'hider';
            this._element.appendChild(hiderEl);
            hiderEl.style.position = 'absolute';
            hiderEl.style[ this._isY ? 'left' : 'top' ] = '0';  // fix to top..
            hiderEl.style[ this._isY ? 'right' : 'bottom' ] = '0';  // and bottom...
            hiderEl.style[ this._isY ? 'bottom' : 'right' ] = '0';  // and move to the end.
            this._hiderEl = hiderEl;
        }

        this.refit();

        if (this._isY) {
            // Override white-space: no-wrap which is only necessary to make sure horizontal stuff stays horizontal, but breaks stuff intended to be vertical.
            this._ulEl.style.whiteSpace = 'normal';
        }

        if (options.pagination) {
            if (Aux.isDOMElement(options.pagination) || typeof options.pagination === 'string') {
                // if dom element or css selector string...
                var pagination = this._pagination = new Pagination(options.pagination, {
                    size:     this._numPages,
                    onChange: this._handlers.paginationChange
                });
            } else {
                // assumes instantiated pagination
                this._pagination = options.pagination;
                this._pagination._options.onChange = this._handlers.paginationChange;
                this._pagination.setSize(this._numPages);
                this._pagination.setCurrent(0);
            }
        }

        if (options.swipe) {
        }
    };

    Carousel.prototype = {
        /**
         * Measure the carousel once again, adjusting the involved elements'
         * sizes. Called automatically when the window resizes, in order to
         * cater for changes from responsive media queries, for instance.
         *
         * @method refit
         */
        refit: function() {
            this._liEls = Ink.ss('li.slide', this._ulEl);
            var numItems = this._liEls.length;
            this._ctnLength = this._size(this._element);
            this._elLength = this._size(this._liEls[0]);
            this._itemsPerPage = Math.floor( this._ctnLength / this._elLength  );
            this._numPages = Math.ceil( numItems / this._itemsPerPage );
            this._deltaLength = this._itemsPerPage * this._elLength;

            if (this._isY) {
                this._element.style.width = this._liEls[0].offsetWidth + 'px';
                this._ulEl.style.width  =  this._liEls[0].offsetWidth + 'px';
            } else {
                this._ulEl.style.height =  this._liEls[0].offsetHeight + 'px';
            }

            this._center();
            this._updateHider();
            this._IE7();

            if (this._pagination) {
                this._pagination.setSize(this._numPages);
                this._pagination.setCurrent(0);
            }
        },

        _size: function (elm) {
            var dims = InkElement.outerDimensions(elm)
            return this._isY ? dims[1] : dims[0];
        },

        _center: function() {
            if (!this._options.center) { return; }
            var gap = Math.floor( (this._ctnLength - (this._elLength * this._itemsPerPage) ) / 2 );

            var pad;
            if (this._isY) {
                pad = [gap, 'px 0'];
            }
            else {
                pad = ['0 ', gap, 'px'];
            }
            this._ulEl.style.padding = pad.join('');
        },

        _updateHider: function() {
            if (!this._hiderEl) { return; }
            var gap = Math.floor( this._ctnLength - (this._elLength * this._itemsPerPage) );
            if (this._options.center) {
                gap /= 2;
            }
            this._hiderEl.style[ this._isY ? 'height' : 'width' ] = gap + 'px';
        },

        /**
         * Refit stuff for IE7 because it won't support inline-block.
         *
         * @method _IE7
         * @private
         */
        _IE7: function () {
            if (Browser.IE && '' + Browser.version.split('.')[0] === '7') {
                var numPages = this._numPages;
                var slides = Ink.ss('li.slide', this._ulEl);
                var stl = function (prop, val) {slides[i].style[prop] = val; };
                for (var i = 0, len = slides.length; i < len; i++) {
                    stl('position', 'absolute');
                    stl(this._isY ? 'top' : 'left', (i * this._elLength) + 'px');
                }
            }
        },

        _onPaginationChange: function(pgn) {
            var currPage = pgn.getCurrent();
            this._ulEl.style[ this._options.axis === 'y' ? 'top' : 'left'] = ['-', currPage * this._deltaLength, 'px'].join('');
            if (this._options.onChange) {
                this._options.onChange.call(this, currPage);
            }
        }
    };

    return Carousel;

});
<|endoftext|>


<commit_before>$(function() {
    var cloudmade = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    });
    var map = L.map('map',{zoom: 15}).addLayer(cloudmade);
    var osmGeocoder = new L.Control.OSMGeocoder();
    map.addControl(osmGeocoder);
    map.addControl( L.control.zoom({position: 'bottomright'}) );

    var markers = new L.MarkerClusterGroup({ maxClusterRadius: 1 });
    $("#commentDialog").dialog({ autoOpen: false, modal: true, buttons: [ { text: "Cancel", click: function() { $(this).dialog("close"); } }, { text: "Submit", click: submitFlag } ] });
    $("#deleteDialog").dialog({ autoOpen: false, modal: true, buttons: [ { text: "Cancel", click: function() { $(this).dialog("close"); } }, { text: "Submit", click: submitDelete } ] });
    $(".ui-icon").text("X");
    var listRetrieved = false;
    var videoList = [];
    var activeVideo = {}
/**
    var requestURL = 'http://localhost:8081/AIDRTrainerAPI/rest/drone/jsonp/getdrones';
    $.ajax({
            type: 'GET',
            url: requestURL,
            dataType: 'jsonp',
            success: renderList,
            error: FailedRenderList,
            jsonp: false,
            jsonpCallback: "jsonp"
        });
**/
    var autoGeoRefresh = setInterval(function() { // Call out to get the time
        var requestURL = "http://st1.uaviators.org/drone/rest/web/jsonp/getdrones" //'http://gis.micromappers.org/drone/rest/web/jsonp/getdrones';
        if (typeof indexID != 'undefined')
            requestURL = 'http://st1.uaviators.org/drone/rest/web/jsonp/drones/after/' + indexID; //'http://gis.micromappers.org/drone/rest/web/jsonp/drones/after/'

        $.ajax({
            type: 'GET',
            url: requestURL,
            dataType: 'jsonp',
            timeout: 4000,
            success: renderList,
            error: failedRenderList,
            jsonp: false,
            jsonpCallback: "jsonp",
        });
    }, 5000);// end check

    function renderList(data) {
        var dataCount = 0;
        listRetrieved = true;
        $("#loading-gif").remove();
        $("#loading-failure").remove();

        $.each(data, function(i, field) {
            video = {
            	vidId: field.info.id,
            	email: null,
            	url: field.info.url,
            	name: field.info.displayName,
            	lat: field.features.geometry.coordinates[1],
            	lng: field.features.geometry.coordinates[0] }
            videoList.push(video);
            mapDataCollection.push(field);
            dataCount++;
        });

        if (dataCount > 0) {
            displayAllRow(data);
            populateMakers();
            map.addLayer(markers);
            map.fitBounds(markers.getBounds());
        }
    }

    function populateMakers(){
        for (var i in mapDataCollection) {
            var item = mapDataCollection[i];
            if (!checkDuplicateEntry(item.info.url)){
                 var layName = L.geoJson(item.features, {
                    onEachFeature: function (features, layer) {
                        indexID = item.info.id;

                        layer.on("click", function (e) {
                        	var url = getSelectedLayerURL(layer);
                            var src = getSrcUrl(url);
                            $("#uavVideo").attr('src', src);
                            window.location.href='#uavOpenModal';
                            activeVideo.vidId = getSelectedLayerID(layer);
                            activeVideo.name = getSelectedLayerName(layer);
                            activeVideo.email = getSelectedLayerEmail(layer);
                            activeVideo.url = url;
                            activeVideo.lng = getSelectedLayerCoordinates(layer)[0];
                            activeVideo.lat = getSelectedLayerCoordinates(layer)[1];
                        });
                        geoLayerCollection.push( new layerInfo(layer, item.info.url, item.info.displayName, item.info.id, item.info.email, item.features.geometry.coordinates) ) ;
                    }
                });
                markers.addLayer(layName);
            }
        }
    }

    function displayAllRow(data){
        $.each(data, function(i, field){

            if(!checkDuplicateEntry(field.info.url)){
                var displayTxt = '';
                displayTxt =  displayTxt + '
'+ field.info.displayName +'
';
                displayTxt =  displayTxt + '
'+ field.info.created +'
';

                var hiddenURL = '<input name="uavVideURL" class="uavVideURL" email="' + field.info.email + '" type="hidden" value = "'+ field.info.url +'"/>';
                var hiddenLat = '<input name="uavCoords" class="uavLat" type="hidden" value="'+ field.features.geometry.coordinates[1] +'"/>';
                var hiddenLng = '<input name="uavCoords" class="uavLng" type="hidden" value="'+ field.features.geometry.coordinates[0] +'"/>';
                var liContent = displayTxt + hiddenURL + hiddenLat + hiddenLng;
                $( "#tweetList" ).prepend($("

").html(liContent));
                $("#tweetList li").unbind("click").click(function(evt) {
                    // console.log("clicker!!!");
                    // var answer = $(evt.currentTarget).text();
                    // var answer2 =$(evt.currentTarget).children('#uavVideURL');
                    var url = $(evt.currentTarget).children('.uavVideURL').attr('value');
                    var src = getSrcUrl(url);
                    $("#uavVideo").attr('src', src);
                    activeVideo.vidId = $(evt.currentTarget).attr('name');
                    activeVideo.name = $(evt.currentTarget).find('.displayName').text();
                    activeVideo.lng = $(evt.currentTarget).find('.uavLng').val();
                    activeVideo.lat = $(evt.currentTarget).find('.uavLat').val();
                    activeVideo.email = $(evt.currentTarget).children('.uavVideURL').attr('email');
                    activeVideo.url = url;
                    //var vid =  $(this).attr("uavVideURL");
                    // console.log($(evt.currentTarget));
                    // console.log(this);
                    // usersid =  $(this).attr("uavVideoID");
                });
            }
         });
    }

    function getSrcUrl(origUrl) {
        if (origUrl.match(/youtube/)) {
            var vid = origUrl.match(/v=([^&]+)/)[1];
            return "http://www.youtube.com/embed/" + vid + "?autoplay=1&showinfo=1&controls=1";
        } else if (origUrl.match(/vimeo/)) {
            var vid = origUrl.substr(17);
            return "http://player.vimeo.com/video/" + vid;
        }
        return origUrl;
    }

    function failedRenderList(jqXHR, textStatus) {
        $("#loading-gif").remove();
        if (!listRetrieved & !$("#loading-failure").length)
            $("body").append("

Sorry, couldn't retrieve drone videos. The server appears to be down, please come back later.

");
    }

    $("#submit").click(function(e) {
        if (hasAllRequiredFields()){
            e.preventDefault();
            var email = $("input#email").val();
            var vURL = $("input#vURL").val();
            var info = new Object();
            info.email = email;
            info.url = vURL;

            var data = new Object();
            data.features = geoInfoProperty;
            data.info = info;
            if ($("input#vId").length)
          		data.id = $("input#vId").val();

            var myString = JSON.stringify(data);
            var urlPost = $("#uavInfo").attr('action');

            $.post( urlPost, myString );
            window.location.href='#close';
        }
    });

    $("#flag-btn").click(reportVideo);
    $("#edit-btn").click(editVideo);
    $("#delete-btn").click(deleteVideoConfirm);

    function reportVideo() {
        $("#commentDialog .error").remove();
        $("#commentDialog #flagComment").val("");
        $("#commentDialog").dialog("open");
    }

    function submitFlag() {
        var comment = $("#commentDialog #flagComment").val();
        if (comment == "" || comment == undefined) {
            $("#commentDialog label").after("
You must add a comment
");
        } else {
            jsonData = JSON.stringify({ "id": activeVideo.vidId, "comment": comment });
            $.post("http://st1.uaviators.org/drone/rest/report/post", jsonData);
           // $.post("http://qcricl1linuxvm2.cloudapp.net:8081/AIDRDRONE/rest/report/post", jsonData);
            $("#commentDialog").dialog("close");
            $("#commentDialog #flagComment").val("");
        }
    }

    function editVideo() {
    	$("#uavVideo").attr('src', '');
    	window.location.href='#close';

    	window.location.href='#openModal';
    	$("#openModal #locationRef").val(activeVideo.name);
    	$("#openModal .existingEmail").show();
    	$("#openModal #vURL").val(activeVideo.url);
    	$("#openModal #lon").text(activeVideo.lng);
    	$("#openModal #lat").text(activeVideo.lat);

    	damageLayer.removeAllFeatures();
    	var lonLat = new OpenLayers.LonLat(activeVideo.lng, activeVideo.lat)
            .transform(
                new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                tinyMap.getProjectionObject() // to Spherical Mercator Projection
            );
    	point = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
        damageLayer.addFeatures([new OpenLayers.Feature.Vector(point)]);
        tinyMap.setCenter(lonLat,5);

        $("#uavInfo").append("<input id='vId' type='hidden' value='" + activeVideo.vidId + "'></input>")
       // $("#uavInfo").attr('action', "http://qcricl1linuxvm2.cloudapp.net:8081/AIDRDRONE/rest/web/update");
        $("#uavInfo").attr('action', "http://st1.uaviators.org/drone/rest/web/update");
    }

    function deleteVideoConfirm() {
        $("#deleteDialog .error").remove();
        $("#deleteDialog input").val("").show();
        $("#deleteDialog label").show();
        $("#deleteDialog").dialog( "option", "buttons", [ { text: "Cancel", click: function() { $(this).dialog("close"); } }, { text: "Submit", click: submitDelete } ] );
        $("#deleteDialog").dialog("open");
    }

    function submitDelete() {
        var email = $("#deleteDialog input").val();
        if (true) { // email == openVidEmail
            jsonData = JSON.stringify({ "id": activeVideo.vidId, "email": email });
            //$.post("http://qcricl1linuxvm2.cloudapp.net:8081/AIDRDRONE/rest/web/jsonp/delete/" + activeVideo.vidId + "/" + email, jsonData, function(data, response) {
                // alert(response);
           // });

            $.post("http://st1.uaviators.org/drone/rest/web/jsonp/delete/" + activeVideo.vidId + "/" + email, jsonData, function(data, response) {
                 alert(response);
            });

            $("#deleteDialog").dialog("close");
            $("#tweetList li[name=" + activeVideo.vidId + "]").remove();
            window.location.href='#close';
        } else {
            $("#deleteDialog label").after("
That email is not correct.
");
            $("#deleteDialog label").hide();
            $("#deleteDialog input").hide();
            $("#deleteDialog").dialog( "option", "buttons", [ { text: "Cancel", click: function() { $(this).dialog("close"); } } ] );
        }
    }

    function hasAllRequiredFields(){
        var email = $("input#email").val();
        var vURL = $("input#vURL").val();
        if (email == "" || email.length < 5 || geoInfoProperty == "" || typeof geoInfoProperty == 'undefined' || vURL == "" || vURL.length < 5)
            return false;

        return true;
    }

    function checkDuplicateEntry(newVideoURL){
        for( var i in geoLayerCollection) {
            if (geoLayerCollection[i].url == newVideoURL)
                return  true;
        }
        return false;
    }

    function layerInfo(layer, vURL, name, id, email, coordinates) {
        this.layer=layer;
        this.url = vURL;
        this.name = name;
        this.id = id;
        this.email = email;
        this.coordinates = coordinates;
    }

    function getSelectedLayerURL(layer) {
        for( var i in geoLayerCollection){
            var item = geoLayerCollection[i];
            if(item.layer == layer)
                return item.url;
        }
    }

    function getSelectedLayerID(layer){
        for( var i in geoLayerCollection){
            var item = geoLayerCollection[i];
            if(item.layer == layer)
                return item.id;
        }
    }

    function getSelectedLayerName(layer){
        for( var i in geoLayerCollection){
            var item = geoLayerCollection[i];
            if(item.layer == layer) {
                return item.name;
            }
        }
    }

    function getSelectedLayerEmail(layer){
        for( var i in geoLayerCollection){
            var item = geoLayerCollection[i];
            if(item.layer == layer)
                return item.email;
        }
    }

    function getSelectedLayerCoordinates(layer) {
        for( var i in geoLayerCollection){
            var item = geoLayerCollection[i];
            if(item.layer == layer)
                return item.coordinates;
        }
    }

    $("#agree").change(function() {
        if ($(this).is(":checked"))
            $("#submit").removeAttr('disabled');
        else
            $("#submit").attr('disabled','disabled');
    });

    $('#newUAV').click(function() {
    	$("#openModal #locationRef").val("");
    	$("#openModal #vURL").val("");
    	$("#openModal .existingEmail").hide();

    	$("#uavInfo #vId").remove();
        $("#uavInfo").attr('action', "http://qcricl1linuxvm2.cloudapp.net:8081/AIDRDRONE/rest/web/add");
    });
});
<commit_msg>Fix to previous merge<commit_after>$(function() {
    var cloudmade = L.tileLayer('http://{s}.tile.osm.org/{z}/{x}/{y}.png', {
        attribution: '© OpenStreetMap contributors'
    });
    var map = L.map('map',{zoom: 15}).addLayer(cloudmade);
    var osmGeocoder = new L.Control.OSMGeocoder();
    map.addControl(osmGeocoder);
    map.addControl( L.control.zoom({position: 'bottomright'}) );

    var markers = new L.MarkerClusterGroup({ maxClusterRadius: 1 });
    $("#commentDialog").dialog({ autoOpen: false, modal: true, buttons: [ { text: "Cancel", click: function() { $(this).dialog("close"); } }, { text: "Submit", click: submitFlag } ] });
    $("#deleteDialog").dialog({ autoOpen: false, modal: true, buttons: [ { text: "Cancel", click: function() { $(this).dialog("close"); } }, { text: "Submit", click: submitDelete } ] });
    $(".ui-icon").text("X");
    var listRetrieved = false;
    var videoList = [];
    var activeVideo = {}
/**
    var requestURL = 'http://localhost:8081/AIDRTrainerAPI/rest/drone/jsonp/getdrones';
    $.ajax({
            type: 'GET',
            url: requestURL,
            dataType: 'jsonp',
            success: renderList,
            error: FailedRenderList,
            jsonp: false,
            jsonpCallback: "jsonp"
        });
**/
    var autoGeoRefresh = setInterval(function() { // Call out to get the time
        var requestURL = "http://st1.uaviators.org/drone/rest/web/jsonp/getdrones" //'http://gis.micromappers.org/drone/rest/web/jsonp/getdrones';
        if (typeof indexID != 'undefined')
            requestURL = 'http://st1.uaviators.org/drone/rest/web/jsonp/drones/after/' + indexID; //'http://gis.micromappers.org/drone/rest/web/jsonp/drones/after/'

        $.ajax({
            type: 'GET',
            url: requestURL,
            dataType: 'jsonp',
            timeout: 4000,
            success: renderList,
            error: failedRenderList,
            jsonp: false,
            jsonpCallback: "jsonp",
        });
    }, 5000);// end check

    function renderList(data) {
        var dataCount = 0;
        listRetrieved = true;
        $("#loading-gif").remove();
        $("#loading-failure").remove();

        $.each(data, function(i, field) {
            video = {
            	vidId: field.info.id,
            	email: null,
            	url: field.info.url,
            	name: field.info.displayName,
            	lat: field.features.geometry.coordinates[1],
            	lng: field.features.geometry.coordinates[0] }
            videoList.push(video);
            mapDataCollection.push(field);
            dataCount++;
        });

        if (dataCount > 0) {
            displayAllRow(data);
            populateMakers();
            map.addLayer(markers);
            map.fitBounds(markers.getBounds());
        }
    }

    function populateMakers(){
        for (var i in mapDataCollection) {
            var item = mapDataCollection[i];
            if (!checkDuplicateEntry(item.info.url)){
                 var layName = L.geoJson(item.features, {
                    onEachFeature: function (features, layer) {
                        indexID = item.info.id;

                        layer.on("click", function (e) {
                        	var url = getSelectedLayerURL(layer);
                            var src = getSrcUrl(url);
                            $("#uavVideo").attr('src', src);
                            window.location.href='#uavOpenModal';
                            activeVideo.vidId = getSelectedLayerID(layer);
                            activeVideo.name = getSelectedLayerName(layer);
                            activeVideo.email = getSelectedLayerEmail(layer);
                            activeVideo.url = url;
                            activeVideo.lng = getSelectedLayerCoordinates(layer)[0];
                            activeVideo.lat = getSelectedLayerCoordinates(layer)[1];
                        });
                        geoLayerCollection.push( new layerInfo(layer, item.info.url, item.info.displayName, item.info.id, item.info.email, item.features.geometry.coordinates) ) ;
                    }
                });
                markers.addLayer(layName);
            }
        }
    }

    function displayAllRow(data){
        $.each(data, function(i, field){

            if(!checkDuplicateEntry(field.info.url)){
                var displayTxt = '';
                displayTxt =  displayTxt + '
'+ field.info.displayName +'
';
                displayTxt =  displayTxt + '
'+ field.info.created +'
';

                var hiddenURL = '<input name="uavVideURL" class="uavVideURL" email="' + field.info.email + '" type="hidden" value = "'+ field.info.url +'"/>';
                var hiddenLat = '<input name="uavCoords" class="uavLat" type="hidden" value="'+ field.features.geometry.coordinates[1] +'"/>';
                var hiddenLng = '<input name="uavCoords" class="uavLng" type="hidden" value="'+ field.features.geometry.coordinates[0] +'"/>';
                var liContent = displayTxt + hiddenURL + hiddenLat + hiddenLng;
                $( "#tweetList" ).prepend($("

").html(liContent));
                $("#tweetList li").unbind("click").click(function(evt) {
                    // console.log("clicker!!!");
                    // var answer = $(evt.currentTarget).text();
                    // var answer2 =$(evt.currentTarget).children('#uavVideURL');
                    var url = $(evt.currentTarget).children('.uavVideURL').attr('value');
                    var src = getSrcUrl(url);
                    $("#uavVideo").attr('src', src);
                    activeVideo.vidId = $(evt.currentTarget).attr('name');
                    activeVideo.name = $(evt.currentTarget).find('.displayName').text();
                    activeVideo.lng = $(evt.currentTarget).find('.uavLng').val();
                    activeVideo.lat = $(evt.currentTarget).find('.uavLat').val();
                    activeVideo.email = $(evt.currentTarget).children('.uavVideURL').attr('email');
                    activeVideo.url = url;
                    //var vid =  $(this).attr("uavVideURL");
                    // console.log($(evt.currentTarget));
                    // console.log(this);
                    // usersid =  $(this).attr("uavVideoID");
                });
            }
         });
    }

    function getSrcUrl(origUrl) {
        if (origUrl.match(/youtube/)) {
            var vid = origUrl.match(/v=([^&]+)/)[1];
            return "http://www.youtube.com/embed/" + vid + "?autoplay=1&showinfo=1&controls=1";
        } else if (origUrl.match(/vimeo/)) {
            var vid = origUrl.substr(17);
            return "http://player.vimeo.com/video/" + vid;
        }
        return origUrl;
    }

    function failedRenderList(jqXHR, textStatus) {
        $("#loading-gif").remove();
        if (!listRetrieved & !$("#loading-failure").length)
            $("body").append("

Sorry, couldn't retrieve drone videos. The server appears to be down, please come back later.

");
    }

    $("#submit").click(function(e) {
        if (hasAllRequiredFields()){
            e.preventDefault();
            var email = $("input#email").val();
            var vURL = $("input#vURL").val();
            var info = new Object();
            info.email = email;
            info.url = vURL;

            var data = new Object();
            data.features = geoInfoProperty;
            data.info = info;
            if ($("input#vId").length)
          		data.id = $("input#vId").val();

            var myString = JSON.stringify(data);
            var urlPost = $("#uavInfo").attr('action');

            $.post( urlPost, myString );
            window.location.href='#close';
        }
    });

    $("#flag-btn").click(reportVideo);
    $("#edit-btn").click(editVideo);
    $("#delete-btn").click(deleteVideoConfirm);

    function reportVideo() {
        $("#commentDialog .error").remove();
        $("#commentDialog #flagComment").val("");
        $("#commentDialog").dialog("open");
    }

    function submitFlag() {
        var comment = $("#commentDialog #flagComment").val();
        if (comment == "" || comment == undefined) {
            $("#commentDialog label").after("
You must add a comment
");
        } else {
            jsonData = JSON.stringify({ "id": activeVideo.vidId, "comment": comment });
            $.post("http://st1.uaviators.org/drone/rest/report/post", jsonData);
           // $.post("http://qcricl1linuxvm2.cloudapp.net:8081/AIDRDRONE/rest/report/post", jsonData);
            $("#commentDialog").dialog("close");
            $("#commentDialog #flagComment").val("");
        }
    }

    function editVideo() {
    	$("#uavVideo").attr('src', '');
    	window.location.href='#close';

    	window.location.href='#openModal';
    	$("#openModal #locationRef").val(activeVideo.name);
    	$("#openModal .existingEmail").show();
    	$("#openModal #vURL").val(activeVideo.url);
    	$("#openModal #lon").text(activeVideo.lng);
    	$("#openModal #lat").text(activeVideo.lat);

    	damageLayer.removeAllFeatures();
    	var lonLat = new OpenLayers.LonLat(activeVideo.lng, activeVideo.lat)
            .transform(
                new OpenLayers.Projection("EPSG:4326"), // transform from WGS 1984
                tinyMap.getProjectionObject() // to Spherical Mercator Projection
            );
    	point = new OpenLayers.Geometry.Point(lonLat.lon, lonLat.lat);
        damageLayer.addFeatures([new OpenLayers.Feature.Vector(point)]);
        tinyMap.setCenter(lonLat,5);

        $("#uavInfo").append("<input id='vId' type='hidden' value='" + activeVideo.vidId + "'></input>")
       // $("#uavInfo").attr('action', "http://qcricl1linuxvm2.cloudapp.net:8081/AIDRDRONE/rest/web/update");
        $("#uavInfo").attr('action', "http://st1.uaviators.org/drone/rest/web/update");
    }

    function deleteVideoConfirm() {
        $("#deleteDialog .error").remove();
        $("#deleteDialog input").val("").show();
        $("#deleteDialog label").show();
        $("#deleteDialog").dialog( "option", "buttons", [ { text: "Cancel", click: function() { $(this).dialog("close"); } }, { text: "Submit", click: submitDelete } ] );
        $("#deleteDialog").dialog("open");
    }

    function submitDelete() {
        var email = $("#deleteDialog input").val();
        jsonData = JSON.stringify({ "id": activeVideo.vidId, "email": email });
	$.post("http://qcricl1linuxvm2.cloudapp.net:8081/AIDRDRONE/rest/web/jsonp/delete/" + activeVideo.vidId + "/" + email, jsonData)
                .success(function() {
                    $("#deleteDialog").dialog("close");
                    $("#tweetList li[name=" + activeVideo.vidId + "]").remove();
                    window.location.href='#close';
                })
                .fail(function() {
                    alert("Sorry, unable to delete video. Please make sure you used the same email to submit the video");
                });
    }

    function hasAllRequiredFields(){
        var email = $("input#email").val();
        var vURL = $("input#vURL").val();
        if (email == "" || email.length < 5 || geoInfoProperty == "" || typeof geoInfoProperty == 'undefined' || vURL == "" || vURL.length < 5)
            return false;

        return true;
    }

    function checkDuplicateEntry(newVideoURL){
        for( var i in geoLayerCollection) {
            if (geoLayerCollection[i].url == newVideoURL)
                return  true;
        }
        return false;
    }

    function layerInfo(layer, vURL, name, id, email, coordinates) {
        this.layer=layer;
        this.url = vURL;
        this.name = name;
        this.id = id;
        this.email = email;
        this.coordinates = coordinates;
    }

    function getSelectedLayerURL(layer) {
        for( var i in geoLayerCollection){
            var item = geoLayerCollection[i];
            if(item.layer == layer)
                return item.url;
        }
    }

    function getSelectedLayerID(layer){
        for( var i in geoLayerCollection){
            var item = geoLayerCollection[i];
            if(item.layer == layer)
                return item.id;
        }
    }

    function getSelectedLayerName(layer){
        for( var i in geoLayerCollection){
            var item = geoLayerCollection[i];
            if(item.layer == layer) {
                return item.name;
            }
        }
    }

    function getSelectedLayerEmail(layer){
        for( var i in geoLayerCollection){
            var item = geoLayerCollection[i];
            if(item.layer == layer)
                return item.email;
        }
    }

    function getSelectedLayerCoordinates(layer) {
        for( var i in geoLayerCollection){
            var item = geoLayerCollection[i];
            if(item.layer == layer)
                return item.coordinates;
        }
    }

    $("#agree").change(function() {
        if ($(this).is(":checked"))
            $("#submit").removeAttr('disabled');
        else
            $("#submit").attr('disabled','disabled');
    });

    $('#newUAV').click(function() {
    	$("#openModal #locationRef").val("");
    	$("#openModal #vURL").val("");
    	$("#openModal .existingEmail").hide();

    	$("#uavInfo #vId").remove();
        $("#uavInfo").attr('action', "http://qcricl1linuxvm2.cloudapp.net:8081/AIDRDRONE/rest/web/add");
    });
});
<|endoftext|>


<commit_before>module.exports = {
	'root': true ,
	'env': {
		'browser': true ,
		'es6': true ,
		'node': true
	} ,
	'parserOptions': {
		'ecmaVersion': 2020
	} ,
	'extends': [ 'eslint:recommended' ] ,
	'rules': {

		/*
			Bad code -- detect anything that can be broken or lead to bugs
		*/

		'strict': [ 'error' , 'global' ] ,
		'unicode-bom': [ 'error' , 'never' ] ,
		'radix': 'error' ,
		'eqeqeq': 'error' ,
		'consistent-return': 'off' ,
		'valid-typeof': 'error' ,
		'no-unneeded-ternary': 'error' ,
		'no-unused-vars': 'warn' ,	// During development phase, it's boring to clean unused var since they can be used later
		'no-lonely-if': 'error' ,
		'no-nested-ternary': 'off' ,	// Now I use the streamlined ternary operator a lot
		'no-shadow': 'warn' ,
		'no-shadow-restricted-names': 'error' ,
		'require-atomic-updates': 'off' ,	// check for possible race condition on assignment, interesting but too nitpicky

		/*
			Code preferences
		*/

		'prefer-arrow-callback': 'error' ,
		'prefer-spread': 'warn' ,
		'prefer-rest-params': 'warn' ,
		'no-control-regex': 'off' ,	// because thing like \x00 are considered like a control even if escaped...
		'no-fallthrough': 'off' ,
		'no-empty': [ 'error' , {
			'allowEmptyCatch': true
		} ] ,

		/*
			Coding styles -- cosmetic rules and opinionated preferences
		*/

		// Indent & spaces (general)
		'indent': [ 'error' , 'tab' , {
			'SwitchCase': 1 ,
			'MemberExpression': 1 ,
			'flatTernaryExpressions': true
		} ] ,
		'newline-per-chained-call': [ 'error', {
			'ignoreChainWithDepth': 2
		} ] ,
		'no-multi-spaces': 'off' ,
		'block-spacing': 'error' ,
		'comma-spacing': [ 'error' , {
			'before': true ,
			'after': true
		} ] ,
		'no-whitespace-before-property': 'error' ,
		'space-before-blocks': 'error' ,
		'space-before-function-paren': [ 'error' , {
			'anonymous': 'never',
			'named': 'never',
			'asyncArrow': 'always'
		} ] ,
		'space-infix-ops': 'error' ,
		'space-unary-ops': [ 'error' , {
			'words': true ,
			'nonwords': true ,
			'overrides': {
				'-': false ,
			}
		} ] ,
		'space-in-parens': [ 'error' , 'always' , {
			'exceptions': [ 'empty' ]
		} ] ,
		'no-trailing-spaces': 'error' ,
		'switch-colon-spacing': [ 'error' , {
			'after': true ,
			'before': true
		} ] ,
		'arrow-spacing': 'error' ,
		'rest-spread-spacing': [ 'error' , 'always' ] ,
		/* Troublesome with commented line of code
		'spaced-comment': [ 'error' , 'always' , {
			'line': {
				'markers': [ '/' ],
				'exceptions': [ '-', '*', '/' ]
			} ,
			'block': {
				'exceptions': [ '*' ] ,
				'balanced': true
			}
		} ] ,
		*/

		// Semi-colon
		'semi': [ 'error' , 'always' ] ,
		'semi-style': [ 'error' , 'last' ] ,
		'semi-spacing': [ 'error' , {
			'before': true ,
			'after': true
		} ] ,

		// Objects
		'key-spacing': [ 'error' , {
			'beforeColon': false ,
			'afterColon': true ,
			'mode': 'strict'
		} ] ,
		'object-curly-newline': [ 'error' , {
			'ObjectExpression' : {
				'consistent': true ,
				'minProperties': 4
			} ,
			'ObjectPattern' : {
				// object destructuring assigment
				'consistent': true ,
				'minProperties': 8
			}
		} ] ,
		'object-curly-spacing': [ 'error' , 'always' ] ,
		'object-property-newline': [ 'error' , { 'allowMultiplePropertiesPerLine': true } ] ,

		// Arrays
		'array-bracket-newline': [ 'error' , 'consistent' ] ,
		//'array-element-newline': [ 'error' , { 'multiline': true , 'minItems': 5 } ] ,
		'array-bracket-spacing': [ 'error' , 'always' ],

		'brace-style': [ 'error' , 'stroustrup' , {
			'allowSingleLine': true
		} ] ,

		// Misc style
		'no-else-return': 'warn' ,
		'comma-dangle': [ 'error' , 'never' ] ,
		'quotes': 'off' ,
		'camelcase': 'warn' ,

		/*
			Method limitation
		*/

		'no-console': 'off'
	}
} ;
<commit_msg>.eslintrc.js<commit_after>module.exports = {
	'root': true ,
	'env': {
		'browser': true ,
		'es6': true ,
		'node': true
	} ,
	'parserOptions': {
		'ecmaVersion': 2020
	} ,
	'extends': [ 'eslint:recommended' ] ,
	'rules': {

		/*
			Bad code -- detect anything that can be broken or lead to bugs
		*/

		'strict': [ 'error' , 'global' ] ,
		'unicode-bom': [ 'error' , 'never' ] ,
		'radix': 'error' ,
		'eqeqeq': 'error' ,
		'consistent-return': 'off' ,
		'valid-typeof': 'error' ,
		'no-unneeded-ternary': 'error' ,
		'no-unused-vars': 'warn' ,	// During development phase, it's boring to clean unused var since they can be used later
		'no-lonely-if': 'error' ,
		'no-nested-ternary': 'off' ,	// Now I use the streamlined ternary operator a lot
		'no-shadow': 'warn' ,
		'no-shadow-restricted-names': 'error' ,
		'require-atomic-updates': 'off' ,	// check for possible race condition on assignment, interesting but too nitpicky

		/*
			Code preferences
		*/

		'prefer-arrow-callback': 'error' ,
		'prefer-spread': 'warn' ,
		'prefer-rest-params': 'warn' ,
		'no-control-regex': 'off' ,	// because thing like \x00 are considered like a control even if escaped...
		'no-fallthrough': 'off' ,
		'no-empty': [ 'error' , {
			'allowEmptyCatch': true
		} ] ,

		/*
			Coding styles -- cosmetic rules and opinionated preferences
		*/

		// Indent & spaces (general)
		'indent': [ 'error' , 'tab' , {
			'SwitchCase': 1 ,
			'MemberExpression': 1 ,
			'flatTernaryExpressions': true
		} ] ,
		'newline-per-chained-call': 'off',
		'no-multi-spaces': 'off' ,
		'block-spacing': 'error' ,
		'comma-spacing': [ 'error' , {
			'before': true ,
			'after': true
		} ] ,
		'no-whitespace-before-property': 'error' ,
		'space-before-blocks': 'error' ,
		'space-before-function-paren': [ 'error' , {
			'anonymous': 'never',
			'named': 'never',
			'asyncArrow': 'always'
		} ] ,
		'space-infix-ops': 'error' ,
		'space-unary-ops': [ 'error' , {
			'words': true ,
			'nonwords': true ,
			'overrides': {
				'-': false ,
			}
		} ] ,
		'space-in-parens': [ 'error' , 'always' , {
			'exceptions': [ 'empty' ]
		} ] ,
		'no-trailing-spaces': 'error' ,
		'switch-colon-spacing': [ 'error' , {
			'after': true ,
			'before': true
		} ] ,
		'arrow-spacing': 'error' ,
		'rest-spread-spacing': [ 'error' , 'always' ] ,
		/* Troublesome with commented line of code
		'spaced-comment': [ 'error' , 'always' , {
			'line': {
				'markers': [ '/' ],
				'exceptions': [ '-', '*', '/' ]
			} ,
			'block': {
				'exceptions': [ '*' ] ,
				'balanced': true
			}
		} ] ,
		*/

		// Semi-colon
		'semi': [ 'error' , 'always' ] ,
		'semi-style': [ 'error' , 'last' ] ,
		'semi-spacing': [ 'error' , {
			'before': true ,
			'after': true
		} ] ,

		// Objects
		'key-spacing': [ 'error' , {
			'beforeColon': false ,
			'afterColon': true ,
			'mode': 'strict'
		} ] ,
		'object-curly-newline': [ 'error' , {
			'ObjectExpression' : {
				'consistent': true ,
				'minProperties': 4
			} ,
			'ObjectPattern' : {
				// object destructuring assigment
				'consistent': true ,
				'minProperties': 8
			}
		} ] ,
		'object-curly-spacing': [ 'error' , 'always' ] ,
		'object-property-newline': [ 'error' , { 'allowMultiplePropertiesPerLine': true } ] ,

		// Arrays
		'array-bracket-newline': [ 'error' , 'consistent' ] ,
		//'array-element-newline': [ 'error' , { 'multiline': true , 'minItems': 5 } ] ,
		'array-bracket-spacing': [ 'error' , 'always' ],

		'brace-style': [ 'error' , 'stroustrup' , {
			'allowSingleLine': true
		} ] ,

		// Misc style
		'no-else-return': 'warn' ,
		'comma-dangle': [ 'error' , 'never' ] ,
		'quotes': 'off' ,
		'camelcase': 'warn' ,

		/*
			Method limitation
		*/

		'no-console': 'off'
	}
} ;
<|endoftext|>


<commit_before>'use strict';

var express = require('express'),
    mongo = require('mongodb').MongoClient,
    app = express(),
    regex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
    urls = {};

mongo.connect('mongodb://localhost:27017/urls', function(err, db) {
    if(err) {
        console.log("Can't connect to DB!");
    } else {
        console.log("Connected to DB!");
        var userCreated = db.collection('userCreated');
        app.use('/*', function(req, res) {

            if(req.params['0'].match(regex)) {
               userCreated.find({ "original url": req.params['0'] }).limit(1).toArray(function(err, result) {
                if (err) {
                    throw err;
                    }
                if(result.length === 0) {
                    var shortUrl = "http://url-shortener-microservice-timrizzo.c9users.io/" + Math.floor(Math.random() * 100 + 1);
                   if(userCreated.find({ "short url" : shortUrl }).toArray().length === undefined) {
                       userCreated.insert(
                        {
                            "original url": req.params['0'],
                            "short url": shortUrl
                        });
                    } else {
                        console.log("Duplicate!" + userCreated.find({ "short url" : shortUrl }).toArray().length);
                    }

                    urls = {
                    	"original url": req.params['0'],
                        "short url": "",
                        "db": "Not in DB!"
                    };
                } else {
                    urls = {
                    	"original url": req.params['0'],
                        "short url": "",
                        "db": result,
                        "typeof result": typeof result
                    };
                }
                res.send(urls);
                });
            } else {
                res.send("Not proper URL!");
            }
        });
    }
});

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});

<commit_msg>got redirect working<commit_after>'use strict';

var express = require('express'),
    http = require('http'),
    mongo = require('mongodb').MongoClient,
    app = express(),
    regex = /^(https?:\/\/)?([\da-z\.-]+)\.([a-z\.]{2,6})([\/\w \.-]*)*\/?$/,
    urls = {};

mongo.connect('mongodb://localhost:27017/urls', function(err, db) {
    if(err) {
        console.log("Can't connect to DB!");
    } else {
        console.log("Connected to DB!");
        var userCreated = db.collection('userCreated');
        app.use('/*', function (req, res) {
            // Determine if passed url is in database for forwarding
           var passedUrl = { "short url": req.protocol + "s://" + req.get('host') + "/" + req.params['0'] };

            userCreated.find(passedUrl).toArray(function(err,result) {
                if(err) { throw err; }
                console.log(passedUrl);
                if(result.length > 0) {
                res.redirect("http://www.google.com" );
                res.end();
                }
            });
        });

        /*

        app.use('/*', function(req, res) {

// If url submitted as param is in correct format, search in database
            if(req.params['0'].match(regex)) {
               userCreated.find({ "original url": req.params['0'] }).limit(1).toArray(function(err, result) {
                if (err) {
                    throw err;
                    }
// If url submitted as param is not found in database, create new short url
                if(result.length === 0) {
                    var shortUrl = "https://url-shortener-microservice-timrizzo.c9users.io/" + Math.floor(Math.random() * 100 + 1);
// If new short url is not found in database, insert both urls in a new document
                   if(userCreated.find({ "short url" : shortUrl }).toArray().length === undefined) {
                       userCreated.insert(
                        {
                            "original url": req.params['0'],
                            "short url": shortUrl
                        });
                    } else {
                        console.log("Duplicate!" + userCreated.find({ "short url" : shortUrl }).toArray().length);
                    }

                    urls = {
                    	"original url": req.params['0'],
                        "short url": "",
                        "db": "Not in DB!"
                    };
                } else {
                    urls = {
                    	"original url": req.params['0'],
                        "short url": "",
                        "db": result,
                        "url": req.protocol + "//:" + req.get('host')
                    };
                }
                res.send(urls);
                });
            } else {
                res.send("Not proper URL!");
            }
        });

        */
    }
});

var port = process.env.PORT || 8080;
app.listen(port,  function () {
	console.log('Node.js listening on port ' + port + '...');
});

<|endoftext|>


<commit_before>var Note = React.createClass({
  componentDidMount: function() {
    this.attrs = this.props;
    this.syntaxHighlight();
  },

  componentDidUpdate: function() {
    this.syntaxHighlight();
  },

  getInitialState: function() {
    return {
      cssClass: 'note'
    };
  },

  setAttrs: function(updatedAttrs) {
    Object.keys(updatedAttrs).forEach(function(key) {
      this.attrs[key] = updatedAttrs[key];
    }.bind(this));
  },

  mouseDown: function(event) {
    event.stopPropagation();
    this.isDragging = true;
    this.hasDragged = false;
    this.clickX = event.pageX;
    this.clickY = event.pageY;
    this.updateCssState();
  },

  mouseUp: function(event) {
    event.stopPropagation();
    this.isDragging = false;
    this.updateCssState();
    if (!this.hasDragged) {
      this.setAttrs({ isEditing: true });
      EventBus.emitEvent('update-note', [this.attrs]);
      this.change();
    }
  },

  mouseMove: function(event) {
    event.stopPropagation();
    if (this.isDragging) {
      this.hasDragged = true;

      var dx = this.clickX - event.pageX;
      var dy = this.clickY - event.pageY;

      this.setAttrs({ x: this.props.x - dx, y: this.props.y - dy });

      this.updateMatrixState();

      this.clickX = event.pageX;
      this.clickY = event.pageY;
      this.updateCssState();
    }
  },

  syntaxHighlight: function() {
    var blocks = this.getDOMNode().querySelectorAll('pre code');
    for (var index = 0; index < blocks.length; index++) {
      var block = blocks[index];
      hljs.highlightBlock(block);
    };
  },

  updateCssState: function() {
    if (this.isDragging) {
      this.setState({ cssClass: 'note dragging' });
    } else {
      this.setState({ cssClass: 'note' });
    }
  },

  updateMatrixState: function() {
    var matrix = 'translate(' +
        this.attrs.x.toFixed() + 'px, ' +
        this.attrs.y.toFixed()  + 'px)';
    this.setAttrs({ matrix: matrix });
    EventBus.emitEvent('update-note', [this.attrs]);
  },

  blur: function() {
    var content = this.getDOMNode().value;
    if (content === '') {
      EventBus.emitEvent('delete-note', [this.props.id]);
    } else {
      var attrs = { isEditing: false, content: content };
      this.setAttrs(attrs);
      EventBus.emitEvent('update-note', [this.attrs]);
    }
  },

  change: function() {
    var node = this.getDOMNode();
    node.style.height = 'auto';
    node.style.height = node.scrollHeight + 'px';
  },

  keyUp: function(event) {
    if (event.keyCode === 27) {
      this.blur();
    }
  },

  render: function() {
    if (this.props.isEditing) {
      return (
        <textarea className="note"
          style={{transform: this.props.matrix, '-webkit-transform': this.props.matrix}}
          onMouseDown={this.mouseDown}
          onMouseUp={this.mouseUp}
          onBlur={this.blur}
          onChange={this.change}
          onKeyUp={this.keyUp}>
          {this.props.content}
        </textarea>
      );
    } else {
      var val = this.props.content;
      return (

      );
    }
  }
});
<commit_msg>fix: autp height textarea after render<commit_after>var Note = React.createClass({
  componentDidMount: function() {
    this.attrs = this.props;
    this.syntaxHighlight();
    this.change();
  },

  componentDidUpdate: function() {
    this.syntaxHighlight();
    this.change();
  },

  getInitialState: function() {
    return {
      cssClass: 'note'
    };
  },

  setAttrs: function(updatedAttrs) {
    Object.keys(updatedAttrs).forEach(function(key) {
      this.attrs[key] = updatedAttrs[key];
    }.bind(this));
  },

  mouseDown: function(event) {
    event.stopPropagation();
    this.isDragging = true;
    this.hasDragged = false;
    this.clickX = event.pageX;
    this.clickY = event.pageY;
    this.updateCssState();
  },

  mouseUp: function(event) {
    event.stopPropagation();
    this.isDragging = false;
    this.updateCssState();
    if (!this.hasDragged) {
      this.setAttrs({ isEditing: true });
      EventBus.emitEvent('update-note', [this.attrs]);
      this.change();
    }
  },

  mouseMove: function(event) {
    event.stopPropagation();
    if (this.isDragging) {
      this.hasDragged = true;

      var dx = this.clickX - event.pageX;
      var dy = this.clickY - event.pageY;

      this.setAttrs({ x: this.props.x - dx, y: this.props.y - dy });

      this.updateMatrixState();

      this.clickX = event.pageX;
      this.clickY = event.pageY;
      this.updateCssState();
    }
  },

  syntaxHighlight: function() {
    var blocks = this.getDOMNode().querySelectorAll('pre code');
    for (var index = 0; index < blocks.length; index++) {
      var block = blocks[index];
      hljs.highlightBlock(block);
    };
  },

  updateCssState: function() {
    if (this.isDragging) {
      this.setState({ cssClass: 'note dragging' });
    } else {
      this.setState({ cssClass: 'note' });
    }
  },

  updateMatrixState: function() {
    var matrix = 'translate(' +
        this.attrs.x.toFixed() + 'px, ' +
        this.attrs.y.toFixed()  + 'px)';
    this.setAttrs({ matrix: matrix });
    EventBus.emitEvent('update-note', [this.attrs]);
  },

  blur: function() {
    var content = this.getDOMNode().value;
    if (content === '') {
      EventBus.emitEvent('delete-note', [this.props.id]);
    } else {
      var attrs = { isEditing: false, content: content };
      this.setAttrs(attrs);
      EventBus.emitEvent('update-note', [this.attrs]);
    }
  },

  change: function() {
    if (this.attrs.isEditing) {
      var node = this.getDOMNode();
      node.style.height = 'auto';
      node.style.height = node.scrollHeight + 'px';
    }
  },

  keyUp: function(event) {
    if (event.keyCode === 27) {
      this.blur();
    }
  },

  render: function() {
    if (this.props.isEditing) {
      return (
        <textarea className="note"
          style={{transform: this.props.matrix, '-webkit-transform': this.props.matrix}}
          onMouseDown={this.mouseDown}
          onMouseUp={this.mouseUp}
          onBlur={this.blur}
          onChange={this.change}
          onKeyUp={this.keyUp}>
          {this.props.content}
        </textarea>
      );
    } else {
      var val = this.props.content;
      return (

      );
    }
  }
});
<|endoftext|>


<commit_before>define([
  'angular',
  'lodash',
  './zabbixAPIService'
  ],
function (angular, _) {
  'use strict';

  var module = angular.module('grafana.services');

  /**
   * Zabbix API Wrapper.
   * Creates Zabbix API instance with given parameters (url, credentials and other).
   * Wraps API calls and provides high-level methods.
   */
  module.factory('ZabbixAPI', function($q, backendSrv, ZabbixAPIService) {

    // Initialize Zabbix API.
    function ZabbixAPI(api_url, username, password, basicAuth, withCredentials) {
      this.url              = api_url;
      this.username         = username;
      this.password         = password;
      this.auth             = null;

      this.requestOptions = {
        basicAuth: basicAuth,
        withCredentials: withCredentials
      };
    }

    var p = ZabbixAPI.prototype;

    //////////////////
    // Core methods //
    //////////////////

    p.request = function(method, params) {
      var self = this;
      if (this.auth) {
        return ZabbixAPIService.request(this.url, method, params, this.requestOptions, this.auth)
          .then(function(result) {
            return result;
          },

          // Handle errors
          function(error) {
            if (error.message === "Session terminated, re-login, please.") {
              return ZabbixAPIService.login(self.url, self.username, self.password, self.requestOptions)
                .then(function(auth) {
                  self.auth = auth;
                  return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth);
                });
            }
          });
      } else {

        // Login first
        return ZabbixAPIService.login(this.url, this.username, this.password, this.requestOptions)
          .then(function(auth) {
            self.auth = auth;
            return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth);
          });
      }
    };

    /**
     * Get authentication token.
     */
    p.login = function() {
      return ZabbixAPIService.login(this.url, this.username, this.password, this.requestOptions);
    };

    /**
     * Get Zabbix API version
     */
    p.getVersion = function() {
      return ZabbixAPIService.getVersion(this.url, this.requestOptions);
    };

    /////////////////
    // API methods //
    /////////////////

    p.getGroups = function() {
      var params = {
        output: ['name'],
        sortfield: 'name'
      };

      return this.request('hostgroup.get', params);
    };

    p.getHosts = function() {
      var params = {
        output: ['name', 'host'],
        sortfield: 'name',
        selectGroups: []
      };

      return this.request('host.get', params);
    };

    p.getApplications = function() {
      var params = {
        output: ['name'],
        sortfield: 'name',
        selectHosts: []
      };

      return this.request('application.get', params);
    };

    p.getItems = function() {
      var params = {
        output: ['name', 'key_', 'value_type', 'hostid', 'status', 'state'],
        sortfield: 'name',
        selectApplications: []
      };

      return this.request('item.get', params);
    };

    /**
     * Perform history query from Zabbix API
     *
     * @param  {Array}  items       Array of Zabbix item objects
     * @param  {Number} time_from   Time in seconds
     * @param  {Number} time_till   Time in seconds
     * @return {Array}  Array of Zabbix history objects
     */
    p.getHistory = function(items, time_from, time_till) {
      var self = this;

      // Group items by value type
      var grouped_items = _.groupBy(items, 'value_type');

      // Perform request for each value type
      return $q.all(_.map(grouped_items, function (items, value_type) {
        var itemids = _.map(items, 'itemid');
        var params = {
          output: 'extend',
          history: value_type,
          itemids: itemids,
          sortfield: 'clock',
          sortorder: 'ASC',
          time_from: time_from
        };

        // Relative queries (e.g. last hour) don't include an end time
        if (time_till) {
          params.time_till = time_till;
        }

        return self.request('history.get', params);
      })).then(_.flatten);
    };

    /**
     * Perform trends query from Zabbix API
     * Use trends api extension from ZBXNEXT-1193 patch.
     *
     * @param  {Array}  items       Array of Zabbix item objects
     * @param  {Number} time_from   Time in seconds
     * @param  {Number} time_till   Time in seconds
     * @return {Array}  Array of Zabbix trend objects
     */
    p.getTrends = function(items, time_from, time_till) {
      var self = this;

      // Group items by value type
      var grouped_items = _.groupBy(items, 'value_type');

      // Perform request for each value type
      return $q.all(_.map(grouped_items, function (items, value_type) {
        var itemids = _.map(items, 'itemid');
        var params = {
          output: 'extend',
          trend: value_type,
          itemids: itemids,
          sortfield: 'clock',
          sortorder: 'ASC',
          time_from: time_from
        };

        // Relative queries (e.g. last hour) don't include an end time
        if (time_till) {
          params.time_till = time_till;
        }

        return self.request('trend.get', params);
      })).then(_.flatten);
    };

    p.getITService = function(/* optional */ serviceids) {
      var params = {
        output: 'extend',
        serviceids: serviceids
      };
      return this.request('service.get', params);
    };

    p.getSLA = function(serviceids, from, to) {
      var params = {
        serviceids: serviceids,
        intervals: [{
          from: from,
          to: to
        }]
      };
      return this.request('service.getsla', params);
    };

    p.getTriggers = function(limit, sortfield, groupids, hostids, applicationids, name) {
      var params = {
        output: 'extend',
        expandDescription: true,
        expandData: true,
        monitored: true,
        //only_true: true,
        filter: {
          value: 1
        },
        search : {
          description: name
        },
        searchWildcardsEnabled: false,
        groupids: groupids,
        hostids: hostids,
        applicationids: applicationids,
        limit: limit,
        sortfield: 'lastchange',
        sortorder: 'DESC'
      };

      if (sortfield) {
        params.sortfield = sortfield;
      }

      return this.request('trigger.get', params);
    };

    p.getAcknowledges = function(triggerids, from) {
      var params = {
        output: 'extend',
        objectids: triggerids,
        acknowledged: true,
        select_acknowledges: 'extend',
        sortfield: 'clock',
        sortorder: 'DESC',
        time_from: from
      };

      return this.request('event.get', params)
        .then(function (events) {
          return _.flatten(_.map(events, 'acknowledges'));
        });
    };

    return ZabbixAPI;

  });

});
<commit_msg>Call login() once.<commit_after>define([
  'angular',
  'lodash',
  './zabbixAPIService'
  ],
function (angular, _) {
  'use strict';

  var module = angular.module('grafana.services');

  /**
   * Zabbix API Wrapper.
   * Creates Zabbix API instance with given parameters (url, credentials and other).
   * Wraps API calls and provides high-level methods.
   */
  module.factory('ZabbixAPI', function($q, backendSrv, ZabbixAPIService) {

    // Initialize Zabbix API.
    function ZabbixAPI(api_url, username, password, basicAuth, withCredentials) {
      this.url              = api_url;
      this.username         = username;
      this.password         = password;
      this.auth             = null;

      this.requestOptions = {
        basicAuth: basicAuth,
        withCredentials: withCredentials
      };

      this.loginPromise = null;
    }

    var p = ZabbixAPI.prototype;

    //////////////////
    // Core methods //
    //////////////////

    p.request = function(method, params) {
      var self = this;
      if (this.auth) {
        return ZabbixAPIService.request(this.url, method, params, this.requestOptions, this.auth)
          .then(function(result) {
            return result;
          },

          // Handle errors
          function(error) {
            if (error.message === "Session terminated, re-login, please.") {
              throw 'expired';
              return self.login().then(function(auth) {
                self.auth = auth;
                return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth);
              });
            }
          });
      } else {

        // Login first
        //throw 'unauthenticated';
        return self.loginOnce().then(function(auth) {
          self.auth = auth;
          return ZabbixAPIService.request(self.url, method, params, self.requestOptions, self.auth);
        });
      }
    };

    /**
     * When API unauthenticated or auth token expired each request produce login()
     * call. But auth token is common to all requests. This function wraps login() method
     * and call it once. If login() already called just wait for it (return its promise).
     * @return login promise
     */
    p.loginOnce = function() {
      var self = this;
      var deferred  = $q.defer();
      if (!self.loginPromise) {
        self.loginPromise = deferred.promise;
        self.login().then(function(auth) {
          self.loginPromise = null;
          deferred.resolve(auth);
        });
      } else {
        return self.loginPromise;
      }
      return deferred.promise;
    };

    /**
     * Get authentication token.
     */
    p.login = function() {
      return ZabbixAPIService.login(this.url, this.username, this.password, this.requestOptions);
    };

    /**
     * Get Zabbix API version
     */
    p.getVersion = function() {
      return ZabbixAPIService.getVersion(this.url, this.requestOptions);
    };

    /////////////////
    // API methods //
    /////////////////

    p.getGroups = function() {
      var params = {
        output: ['name'],
        sortfield: 'name'
      };

      return this.request('hostgroup.get', params);
    };

    p.getHosts = function() {
      var params = {
        output: ['name', 'host'],
        sortfield: 'name',
        selectGroups: []
      };

      return this.request('host.get', params);
    };

    p.getApplications = function() {
      var params = {
        output: ['name'],
        sortfield: 'name',
        selectHosts: []
      };

      return this.request('application.get', params);
    };

    p.getItems = function() {
      var params = {
        output: ['name', 'key_', 'value_type', 'hostid', 'status', 'state'],
        sortfield: 'name',
        selectApplications: []
      };

      return this.request('item.get', params);
    };

    /**
     * Perform history query from Zabbix API
     *
     * @param  {Array}  items       Array of Zabbix item objects
     * @param  {Number} time_from   Time in seconds
     * @param  {Number} time_till   Time in seconds
     * @return {Array}  Array of Zabbix history objects
     */
    p.getHistory = function(items, time_from, time_till) {
      var self = this;

      // Group items by value type
      var grouped_items = _.groupBy(items, 'value_type');

      // Perform request for each value type
      return $q.all(_.map(grouped_items, function (items, value_type) {
        var itemids = _.map(items, 'itemid');
        var params = {
          output: 'extend',
          history: value_type,
          itemids: itemids,
          sortfield: 'clock',
          sortorder: 'ASC',
          time_from: time_from
        };

        // Relative queries (e.g. last hour) don't include an end time
        if (time_till) {
          params.time_till = time_till;
        }

        return self.request('history.get', params);
      })).then(_.flatten);
    };

    /**
     * Perform trends query from Zabbix API
     * Use trends api extension from ZBXNEXT-1193 patch.
     *
     * @param  {Array}  items       Array of Zabbix item objects
     * @param  {Number} time_from   Time in seconds
     * @param  {Number} time_till   Time in seconds
     * @return {Array}  Array of Zabbix trend objects
     */
    p.getTrends = function(items, time_from, time_till) {
      var self = this;

      // Group items by value type
      var grouped_items = _.groupBy(items, 'value_type');

      // Perform request for each value type
      return $q.all(_.map(grouped_items, function (items, value_type) {
        var itemids = _.map(items, 'itemid');
        var params = {
          output: 'extend',
          trend: value_type,
          itemids: itemids,
          sortfield: 'clock',
          sortorder: 'ASC',
          time_from: time_from
        };

        // Relative queries (e.g. last hour) don't include an end time
        if (time_till) {
          params.time_till = time_till;
        }

        return self.request('trend.get', params);
      })).then(_.flatten);
    };

    p.getITService = function(/* optional */ serviceids) {
      var params = {
        output: 'extend',
        serviceids: serviceids
      };
      return this.request('service.get', params);
    };

    p.getSLA = function(serviceids, from, to) {
      var params = {
        serviceids: serviceids,
        intervals: [{
          from: from,
          to: to
        }]
      };
      return this.request('service.getsla', params);
    };

    p.getTriggers = function(limit, sortfield, groupids, hostids, applicationids, name) {
      var params = {
        output: 'extend',
        expandDescription: true,
        expandData: true,
        monitored: true,
        //only_true: true,
        filter: {
          value: 1
        },
        search : {
          description: name
        },
        searchWildcardsEnabled: false,
        groupids: groupids,
        hostids: hostids,
        applicationids: applicationids,
        limit: limit,
        sortfield: 'lastchange',
        sortorder: 'DESC'
      };

      if (sortfield) {
        params.sortfield = sortfield;
      }

      return this.request('trigger.get', params);
    };

    p.getAcknowledges = function(triggerids, from) {
      var params = {
        output: 'extend',
        objectids: triggerids,
        acknowledged: true,
        select_acknowledges: 'extend',
        sortfield: 'clock',
        sortorder: 'DESC',
        time_from: from
      };

      return this.request('event.get', params)
        .then(function (events) {
          return _.flatten(_.map(events, 'acknowledges'));
        });
    };

    return ZabbixAPI;

  });

});
<|endoftext|>


<commit_before>import _assign from 'lodash/object/assign';
import _isNumber from 'lodash/lang/isNumber';
import _isArray from 'lodash/lang/isArray';
import _isEqual from 'lodash/lang/isEqual';
import _sortBy from 'lodash/collection/sortBy';

function duplicate(data) {
  if (_isArray(data)) {
    return data.map(duplicate);
  } else {
    return _assign({}, data);
  }
}

function isNumber(n) {
  return (+n).toString() === n.toString();
}

/*
  A collection of db records i.e. a database table.
*/
class DbCollection {

  constructor(name, initialData) {
    this.name = name;
    this._records = [];
    this.identityManager = new IdentityManager();

    if (initialData) {
      this.insert(initialData);
    }
  }
  /*
    Returns a copy of the data, to prevent inadvertent data manipulation.
  */
  all() {
    return duplicate(this._records);
  }

  insert(data) {
    if (!_isArray(data)) {
      return this._insertRecord(data);
    } else {
      // Need to sort in order to ensure IDs inserted in the correct order
      return _sortBy(data, 'id').map(this._insertRecord, this);
    }
  }

  find(ids) {
    if (_isArray(ids)) {
      let records = this._findRecords(ids)
        .filter(Boolean)
        .map(duplicate); // Return a copy

      return records;
    } else {
      let record = this._findRecord(ids);
      if (!record) { return null; }

      // Return a copy
      return duplicate(record);
    }
  }

  where(query) {
    return this._findRecordsWhere(query).map(duplicate);
  }

  firstOrCreate(query, attributesForNew={}) {
    let queryResult = this.where(query);
    let record = queryResult[0];

    if (record) {
      return record;
    } else {
      let mergedAttributes = _assign(attributesForNew, query);
      let createdRecord = this.insert(mergedAttributes);

      return createdRecord;
    }
  }

  update(target, attrs) {
    let records;

    if (typeof attrs === 'undefined') {
      attrs = target;
      let changedRecords = [];

      this._records.forEach(record => {
        let oldRecord = _assign({}, record);

        this._updateRecord(record, attrs);

        if (!_isEqual(oldRecord, record)) {
          changedRecords.push(record);
        }
      });

      return changedRecords;

    } else if (typeof target === 'number' || typeof target === 'string') {
      let id = target;
      let record = this._findRecord(id);

      this._updateRecord(record, attrs);

      return record;

    } else if (_isArray(target)) {
      let ids = target;
      records = this._findRecords(ids);

      records.forEach(record => {
        this._updateRecord(record, attrs);
      });

      return records;

    } else if (typeof target === 'object') {
      let query = target;
      records = this._findRecordsWhere(query);

      records.forEach(record => {
        this._updateRecord(record, attrs);
      });

      return records;
    }
  }

  remove(target) {
    let records;

    if (typeof target === 'undefined') {
      this._records = [];
      this.identityManager.reset();

    } else if (typeof target === 'number' || typeof target === 'string') {
      let record = this._findRecord(target);
      let index = this._records.indexOf(record);
      this._records.splice(index, 1);

    } else if (_isArray(target)) {
      records = this._findRecords(target);
      records.forEach(record =>  {
        let index = this._records.indexOf(record);
        this._records.splice(index, 1);
      });

    } else if (typeof target === 'object') {
      records = this._findRecordsWhere(target);
      records.forEach(record =>  {
        let index = this._records.indexOf(record);
        this._records.splice(index, 1);
      });
    }
  }

  /*
    Private methods.

    These return the actual db objects, whereas the public
    API query methods return copies.
  */

  _findRecord(id) {
    id = id.toString();

    let record = this._records.filter(obj => obj.id === id)[0];

    return record;
  }

  _findRecords(ids) {
    return ids.map(this._findRecord, this);
  }

  _findRecordsWhere(query) {
    let records = this._records;

    function defaultQueryFunction (record) {
      let keys = Object.keys(query);

      return keys.every(function(key) {
        return String(record[key]) === String(query[key]);
      });
    }

    let queryFunction = typeof query === 'object' ? defaultQueryFunction : query;

    return records.filter(queryFunction);
  }

  _insertRecord(data) {
    let attrs = duplicate(data);

    if (attrs && (attrs.id === undefined || attrs.id === null)) {
      attrs.id = this.identityManager.fetch();
    } else {
      attrs.id = attrs.id.toString();

      this.identityManager.set(attrs.id);
    }

    this._records.push(attrs);

    return duplicate(attrs);
  }

  _updateRecord(record, attrs) {
    let targetId = (attrs && attrs.hasOwnProperty('id')) ? attrs.id.toString() : null;
    let currentId = record.id;

    if (targetId && currentId !== targetId) {
      throw new Error('Updating the ID of a record is not permitted');
    }

    for (let attr in attrs) {
      if (attr === 'id') { continue; }

      record[attr] = attrs[attr];
    }
  }
}

class IdentityManager {
  constructor() {
    this._currentValue = null;
    this._ids = {};
  }

  get() {
    return this._currentValue || 1;
  }

  set(n) {
    if (this._ids[n]) {
      throw new Error(`Attempting to use the ID ${n}, but it's already been used`);
    }

    if (isNumber(n) && +n > this._currentValue) {
      this._currentValue = +n + 1;
    }

    this._ids[n] = true;
  }

  inc() {
    let nextValue = this.get() + 1;

    this._currentValue = nextValue;

    return nextValue;
  }

  fetch() {
    let id = this.get();

    this._ids[id] = true;

    this.inc();

    return id.toString();
  }

  reset() {
    this._ids = {};
    this._currentValue = null;
  }
}

export default DbCollection;

export { IdentityManager };
<commit_msg>Fix jshint error<commit_after>import _assign from 'lodash/object/assign';
import _isArray from 'lodash/lang/isArray';
import _isEqual from 'lodash/lang/isEqual';
import _sortBy from 'lodash/collection/sortBy';

function duplicate(data) {
  if (_isArray(data)) {
    return data.map(duplicate);
  } else {
    return _assign({}, data);
  }
}

function isNumber(n) {
  return (+n).toString() === n.toString();
}

/*
  A collection of db records i.e. a database table.
*/
class DbCollection {

  constructor(name, initialData) {
    this.name = name;
    this._records = [];
    this.identityManager = new IdentityManager();

    if (initialData) {
      this.insert(initialData);
    }
  }
  /*
    Returns a copy of the data, to prevent inadvertent data manipulation.
  */
  all() {
    return duplicate(this._records);
  }

  insert(data) {
    if (!_isArray(data)) {
      return this._insertRecord(data);
    } else {
      // Need to sort in order to ensure IDs inserted in the correct order
      return _sortBy(data, 'id').map(this._insertRecord, this);
    }
  }

  find(ids) {
    if (_isArray(ids)) {
      let records = this._findRecords(ids)
        .filter(Boolean)
        .map(duplicate); // Return a copy

      return records;
    } else {
      let record = this._findRecord(ids);
      if (!record) { return null; }

      // Return a copy
      return duplicate(record);
    }
  }

  where(query) {
    return this._findRecordsWhere(query).map(duplicate);
  }

  firstOrCreate(query, attributesForNew={}) {
    let queryResult = this.where(query);
    let record = queryResult[0];

    if (record) {
      return record;
    } else {
      let mergedAttributes = _assign(attributesForNew, query);
      let createdRecord = this.insert(mergedAttributes);

      return createdRecord;
    }
  }

  update(target, attrs) {
    let records;

    if (typeof attrs === 'undefined') {
      attrs = target;
      let changedRecords = [];

      this._records.forEach(record => {
        let oldRecord = _assign({}, record);

        this._updateRecord(record, attrs);

        if (!_isEqual(oldRecord, record)) {
          changedRecords.push(record);
        }
      });

      return changedRecords;

    } else if (typeof target === 'number' || typeof target === 'string') {
      let id = target;
      let record = this._findRecord(id);

      this._updateRecord(record, attrs);

      return record;

    } else if (_isArray(target)) {
      let ids = target;
      records = this._findRecords(ids);

      records.forEach(record => {
        this._updateRecord(record, attrs);
      });

      return records;

    } else if (typeof target === 'object') {
      let query = target;
      records = this._findRecordsWhere(query);

      records.forEach(record => {
        this._updateRecord(record, attrs);
      });

      return records;
    }
  }

  remove(target) {
    let records;

    if (typeof target === 'undefined') {
      this._records = [];
      this.identityManager.reset();

    } else if (typeof target === 'number' || typeof target === 'string') {
      let record = this._findRecord(target);
      let index = this._records.indexOf(record);
      this._records.splice(index, 1);

    } else if (_isArray(target)) {
      records = this._findRecords(target);
      records.forEach(record =>  {
        let index = this._records.indexOf(record);
        this._records.splice(index, 1);
      });

    } else if (typeof target === 'object') {
      records = this._findRecordsWhere(target);
      records.forEach(record =>  {
        let index = this._records.indexOf(record);
        this._records.splice(index, 1);
      });
    }
  }

  /*
    Private methods.

    These return the actual db objects, whereas the public
    API query methods return copies.
  */

  _findRecord(id) {
    id = id.toString();

    let record = this._records.filter(obj => obj.id === id)[0];

    return record;
  }

  _findRecords(ids) {
    return ids.map(this._findRecord, this);
  }

  _findRecordsWhere(query) {
    let records = this._records;

    function defaultQueryFunction (record) {
      let keys = Object.keys(query);

      return keys.every(function(key) {
        return String(record[key]) === String(query[key]);
      });
    }

    let queryFunction = typeof query === 'object' ? defaultQueryFunction : query;

    return records.filter(queryFunction);
  }

  _insertRecord(data) {
    let attrs = duplicate(data);

    if (attrs && (attrs.id === undefined || attrs.id === null)) {
      attrs.id = this.identityManager.fetch();
    } else {
      attrs.id = attrs.id.toString();

      this.identityManager.set(attrs.id);
    }

    this._records.push(attrs);

    return duplicate(attrs);
  }

  _updateRecord(record, attrs) {
    let targetId = (attrs && attrs.hasOwnProperty('id')) ? attrs.id.toString() : null;
    let currentId = record.id;

    if (targetId && currentId !== targetId) {
      throw new Error('Updating the ID of a record is not permitted');
    }

    for (let attr in attrs) {
      if (attr === 'id') { continue; }

      record[attr] = attrs[attr];
    }
  }
}

class IdentityManager {
  constructor() {
    this._currentValue = null;
    this._ids = {};
  }

  get() {
    return this._currentValue || 1;
  }

  set(n) {
    if (this._ids[n]) {
      throw new Error(`Attempting to use the ID ${n}, but it's already been used`);
    }

    if (isNumber(n) && +n > this._currentValue) {
      this._currentValue = +n + 1;
    }

    this._ids[n] = true;
  }

  inc() {
    let nextValue = this.get() + 1;

    this._currentValue = nextValue;

    return nextValue;
  }

  fetch() {
    let id = this.get();

    this._ids[id] = true;

    this.inc();

    return id.toString();
  }

  reset() {
    this._ids = {};
    this._currentValue = null;
  }
}

export default DbCollection;

export { IdentityManager };
<|endoftext|>