<commit_before>// Requires ====================================================================
var pkg = require ('./package.json');
var fs = require ('fs');
var express = require ('express');

// Constants ===================================================================
var VERSION         = pkg.version;
var LOG_FILE        = 'ugly.log';
var PORT            = 3333;

// Logging =====================================================================
function initLog () {
	// Clear the log
	fs.writeFileSync (LOG_FILE, "");

	// Write header data
	writeToFile ('Created with ugly v' + VERSION);
	writeToFile ('Start date: ' + (new Date ().toString ()));
	writeToFile ('===========================================================');
}

function writeToFile (msg_) {
	fs.appendFileSync (LOG_FILE, msg_ + '\n');
}

function info (msg_) {
	var time = new Date ().getTime ();

	msg_ = '[' + time + '] INFO: ' + msg_;

	console.log (msg_);
	writeToFile (msg_);
}

function error (msg_) {
	var time = new Date ().getTime ();

	msg_ = '[' + time + '] ERROR: ' + msg_;

	console.error (msg_);
	writeToFile (msg_);
	process.exit (1);
}

// Main code ==================================================================

// Start listening on stdin
function main () {
	initLog ();
	info ("Initializing...");

	serveViewer ();
	info ("Listening on stdin");
	readlines (handleLine);
}

function serveViewer () {
	var app = express ();

	app.use (express.static (__dirname + '/viewer'));
	app.listen (PORT);

	info ('Serving viewer at localhost:' + PORT);
}

// Listen on stdin and call callback_ on each line
function readlines (callback_) {
	console.assert (typeof (callback_) === 'function');

	var unhandledText = '';

	process.stdin.setEncoding ('utf8');
	process.stdin.on ('readable', function () {
		var chunk = process.stdin.read ();

		if (chunk === null)
			return;

		unhandledText += chunk;

		var lineBreak = unhandledText.indexOf ('\n');

		while (lineBreak >= 0) {
			callback_ (unhandledText.substring (0, lineBreak));

			unhandledText = unhandledText.slice (lineBreak + 1);
			lineBreak = unhandledText.indexOf ('\n');
		}
	});
}

function handleLine (line_) {
	console.assert (typeof (line_) === 'string');

	// TODO: Handle the line
}

// GO!
main ();
<commit_msg>Moved stdin log message to readLines function<commit_after>// Requires ====================================================================
var pkg = require ('./package.json');
var fs = require ('fs');
var express = require ('express');

// Constants ===================================================================
var VERSION         = pkg.version;
var LOG_FILE        = 'ugly.log';
var PORT            = 3333;

// Logging =====================================================================
function initLog () {
	// Clear the log
	fs.writeFileSync (LOG_FILE, "");

	// Write header data
	writeToFile ('Created with ugly v' + VERSION);
	writeToFile ('Start date: ' + (new Date ().toString ()));
	writeToFile ('===========================================================');
}

function writeToFile (msg_) {
	fs.appendFileSync (LOG_FILE, msg_ + '\n');
}

function info (msg_) {
	var time = new Date ().getTime ();

	msg_ = '[' + time + '] INFO: ' + msg_;

	console.log (msg_);
	writeToFile (msg_);
}

function error (msg_) {
	var time = new Date ().getTime ();

	msg_ = '[' + time + '] ERROR: ' + msg_;

	console.error (msg_);
	writeToFile (msg_);
	process.exit (1);
}

// Main code ==================================================================

// Start listening on stdin
function main () {
	initLog ();
	info ("Initializing...");

	serveViewer ();
	readlines (handleLine);
}

function serveViewer () {
	var app = express ();

	app.use (express.static (__dirname + '/viewer'));
	app.listen (PORT);

	info ('Serving viewer at localhost:' + PORT);
}

// Listen on stdin and call callback_ on each line
function readlines (callback_) {
	console.assert (typeof (callback_) === 'function');

	info ("Listening on stdin");

	var unhandledText = '';

	process.stdin.setEncoding ('utf8');
	process.stdin.on ('readable', function () {
		var chunk = process.stdin.read ();

		if (chunk === null)
			return;

		unhandledText += chunk;

		var lineBreak = unhandledText.indexOf ('\n');

		while (lineBreak >= 0) {
			callback_ (unhandledText.substring (0, lineBreak));

			unhandledText = unhandledText.slice (lineBreak + 1);
			lineBreak = unhandledText.indexOf ('\n');
		}
	});
}

function handleLine (line_) {
	console.assert (typeof (line_) === 'string');

	// TODO: Handle the line
}

// GO!
main ();
<|endoftext|>


<commit_before>function Event(channel_url, last_known_change) {
    this.url = channel_url;
    this.last_etag = null;
    this.last_change = null;
    this.request = new XMLHttpRequest();
    this.error_count = 0;
    this.handlers = {};

    this._timer = null;

    this._register_event();
}

Event.prototype._callback = function() {
	if (this.request.readyState == 4) {
	    if(this.request.status == 200) {
		this.error_count = 0;
		this.last_etag = this.request.getResponseHeader('Etag');
		this.last_change = this.request.getResponseHeader('Last-Modified');

                var data = this.request.responseText;
                // TODO: assert charAt(1) is '\n'
		this.handlers(data.charAt(0))(this.request.responseText.slice(2));
		this._register_event();
	    }
	    else {
		// If this is the first error, try again right away
		// If not, delay some time before trying again
		if(this.error_count)
		    this.error_count = Math.min(this.error_count + 1, 10);
		else
		    this.error_count = 1;

		if(this.error_count > 1) {
		    var delay = (this.error_count - 1) * 500;
		    this._timer = setTimeout(this._register_event.bind(this), delay);
		}
		else
		    this._register_event();
	    }
	}
};

Event.prototype._register_event = function() {
        this.request.open('GET', this.url, true);
        if(this.last_etag)
            this.request.setRequestHeader('If-None-Match', this.last_etag);
        if (this.last_change)
            this.request.setRequestHeader('If-Modified-Since', this.last_change);
        this.request.onreadystatechange = this._callback.bind(this);
        this.request.send(null);
};

Event.prototype.register_handler = function(id, func) {
    this.handlers[id] = func;
};

Event.prototype.stop = function() {
    clearTimeout(this._timer);
    this.request.abort();
};
<commit_msg>Bugfix: Correct accessor.<commit_after>function Event(channel_url, last_known_change) {
    this.url = channel_url;
    this.last_etag = null;
    this.last_change = null;
    this.request = new XMLHttpRequest();
    this.error_count = 0;
    this.handlers = {};

    this._timer = null;

    this._register_event();
}

Event.prototype._callback = function() {
	if (this.request.readyState == 4) {
	    if(this.request.status == 200) {
		this.error_count = 0;
		this.last_etag = this.request.getResponseHeader('Etag');
		this.last_change = this.request.getResponseHeader('Last-Modified');

                var data = this.request.responseText;
                // TODO: assert charAt(1) is '\n'
		this.handlers[data.charAt(0)](this.request.responseText.slice(2));
		this._register_event();
	    }
	    else {
		// If this is the first error, try again right away
		// If not, delay some time before trying again
		if(this.error_count)
		    this.error_count = Math.min(this.error_count + 1, 10);
		else
		    this.error_count = 1;

		if(this.error_count > 1) {
		    var delay = (this.error_count - 1) * 500;
		    this._timer = setTimeout(this._register_event.bind(this), delay);
		}
		else
		    this._register_event();
	    }
	}
};

Event.prototype._register_event = function() {
        this.request.open('GET', this.url, true);
        if(this.last_etag)
            this.request.setRequestHeader('If-None-Match', this.last_etag);
        if (this.last_change)
            this.request.setRequestHeader('If-Modified-Since', this.last_change);
        this.request.onreadystatechange = this._callback.bind(this);
        this.request.send(null);
};

Event.prototype.register_handler = function(id, func) {
    this.handlers[id] = func;
};

Event.prototype.stop = function() {
    clearTimeout(this._timer);
    this.request.abort();
};
<|endoftext|>


<commit_before><commit_msg>JavaScript Update (Weather Load)<commit_after><|endoftext|>


<commit_before>F.ext({
	/**
	 *
	 * @param {Object} ctx Context object
	 * @param [r] placeholder
	 * @param [S] placeholder
	 * @returns {F}
	 */
	parse: function(ctx, r, S) {
		S = String.prototype;

		/**
		 * Parse object
		 * @param {Object} ctx Context object
		 * @param {Number} n number of the iteration
		 * @param [s] placeholder
		 * @returns {String}
		 */
		S.parseObject = function(ctx, n, s) {
			// look for each-tag
			return this[r = "replace"](RegExp("{{#{"+n+"}each(?: *)(\\w+)(?: *)}}([\\s\\S]*?){{\\/{"+n+"}each}}", "g"), function(p, a, b) {
				s = "";
				if(ctx[a])
					// when each is found
					ctx[a].forEach(function(obj, i) {
						// replace vars
						s += b.parseTag(n, "ctx['"+a+"']["+i+"]", ctx);

						// if statement
						s = s.parseIf(n, "ctx."+a+"["+i+"].", ctx);

						// check for another each
						if(s.match(RegExp("{{#{"+ (n+1) +"}each", "g")))
							s = s.parseObject(ctx[a][i], n+1)
					});

				return s
			});
		};

		/**
		 * Parse {{#if}} ... {{/if}, {{##if}} ... {{//if}, etc
		 * @param {Number} n Number of #
		 * @param {String} V eval base
		 * @param {Object} ctx context to look for vars in eval
		 * @param [m] placeholder
		 * @param [v] placeholder
		 * @param [e] placeholder
		 * @returns {RegExp}
		 */
		S.parseIf = function(n, V, ctx, m, v, e) {
			return this[r](RegExp("(?:{{#{"+n+"}if(?: *))(.*)(?: *)}}([\\s\\S]*?)(?:{{\\/{"+n+"}if}})", "g"), function(p, c, d, f) {
				// match ! or not statement
				m = c.match(/(^!|^not) */); v = V;
				if(m) c = c.replace(m[0], ""), v = '!'+v;

				try {
					f = eval(v+c)
				} catch(e) {
					f = 0
				}

				return d.match(e = /{{(#+)else}}[\s\S]*/)
					? d[r](f ? e : /[\s\S]*\{{(#+)else}}/, '')
					: f ? d : ''
			})
		};

		/**
		 * Parse tags like {{abc}}, {{#abc}}, {{##abc}} etc
		 * @param {Number} n Number of #
		 * @param {String} V eval base
		 * @param {Object} ctx context to look for vars in eval
		 * @returns {RegExp}
		 */
		S.parseTag = function(n, V, ctx) {
			return this[r](RegExp("{+\\{#{"+ n +"} *(?!else)([A-Za-z0-9_.]+) *}}+", "g"), function(p, $1, f) {
				try {
					f = eval(!V.big || ~$1.indexOf('.') ? V+"['"+$1.replace(/\./g, "']['")+"']" : V)
				} catch(e) {}

				// return string or object
				f = f ? f.big ? f : f[$1] : '';

				// if set, escape {{{ }}} tags
				return p[2] == '{' ? new Option(f)[F.H] : f
			})
		};

		return F(
				this.html()
				// each
				.parseObject(ctx, 1)
				// vars at level 0
				.parseTag(0, "ctx", ctx)
				// if's at level 0
				.parseIf(1, "ctx.", ctx)
				// JS
				[r](/{%(.*)%}/g, function(p, $1) {
					return eval($1);
				})
				// remove whitespace
				.trim()
			)
	}
});<commit_msg>Templates: replaced var<commit_after>F.ext({
	/**
	 *
	 * @param {Object} ctx Context object
	 * @param [r] placeholder
	 * @param [S] placeholder
	 * @returns {F}
	 */
	parse: function(ctx, r, S) {
		S = String.prototype;

		/**
		 * Parse object
		 * @param {Object} ctx Context object
		 * @param {Number} n number of the iteration
		 * @param [s] placeholder
		 * @returns {String}
		 */
		S.parseObject = function(ctx, n, s) {
			// look for each-tag
			return this[r = "replace"](RegExp("{{#{"+n+"}each(?: *)(\\w+)(?: *)}}([\\s\\S]*?){{\\/{"+n+"}each}}", "g"), function(p, a, b) {
				s = "";
				if(ctx[a])
					// when each is found
					ctx[a].forEach(function(z, i) {
						// replace vars
						s += b.parseTag(n, "ctx['"+a+"']["+i+"]", ctx);

						// if statement
						s = s.parseIf(n, "ctx."+a+"["+i+"].", ctx);

						// check for another each
						if(s.match(RegExp("{{#{"+ (n+1) +"}each", "g")))
							s = s.parseObject(ctx[a][i], n+1)
					});

				return s
			});
		};

		/**
		 * Parse {{#if}} ... {{/if}, {{##if}} ... {{//if}, etc
		 * @param {Number} n Number of #
		 * @param {String} V eval base
		 * @param {Object} ctx context to look for vars in eval
		 * @param [m] placeholder
		 * @param [v] placeholder
		 * @param [e] placeholder
		 * @returns {RegExp}
		 */
		S.parseIf = function(n, V, ctx, m, v, e) {
			return this[r](RegExp("(?:{{#{"+n+"}if(?: *))(.*)(?: *)}}([\\s\\S]*?)(?:{{\\/{"+n+"}if}})", "g"), function(p, c, d, f) {
				// match ! or not statement
				m = c.match(/(^!|^not) */); v = V;
				if(m) c = c.replace(m[0], ""), v = '!'+v;

				try {
					f = eval(v+c)
				} catch(e) {
					f = 0
				}

				return d.match(e = /{{(#+)else}}[\s\S]*/)
					? d[r](f ? e : /[\s\S]*\{{(#+)else}}/, '')
					: f ? d : ''
			})
		};

		/**
		 * Parse tags like {{abc}}, {{#abc}}, {{##abc}} etc
		 * @param {Number} n Number of #
		 * @param {String} V eval base
		 * @param {Object} ctx context to look for vars in eval
		 * @returns {RegExp}
		 */
		S.parseTag = function(n, V, ctx) {
			return this[r](RegExp("{+\\{#{"+ n +"} *(?!else)([A-Za-z0-9_.]+) *}}+", "g"), function(p, $1, f) {
				try {
					f = eval(!V.big || ~$1.indexOf('.') ? V+"['"+$1.replace(/\./g, "']['")+"']" : V)
				} catch(e) {}

				// return string or object
				f = f ? f.big ? f : f[$1] : '';

				// if set, escape {{{ }}} tags
				return p[2] == '{' ? new Option(f)[F.H] : f
			})
		};

		return F(
				this.html()
				// each
				.parseObject(ctx, 1)
				// vars at level 0
				.parseTag(0, "ctx", ctx)
				// if's at level 0
				.parseIf(1, "ctx.", ctx)
				// JS
				[r](/{%(.*)%}/g, function(p, $1) {
					return eval($1);
				})
				// remove whitespace
				.trim()
			)
	}
});<|endoftext|>


<commit_before>/**
 * @fileoverview This file provides a draw directive. This directive is used
 * to create a draw panel in the page.
 *
 * Example:
 *
 * <app-draw app-draw-map="::mainCtrl.map"
 *           app-draw-queryactive="mainCtrl.queryActive"
 *           app-draw-active="mainCtrl.drawOpen"></app-draw>
 *
 * Note the use of the one-time binding operator (::) in the map expression.
 * One-time binding is used because we know the map is not going to change
 * during the lifetime of the application.
 */
goog.provide('app.DrawController');
goog.provide('app.drawDirective');

goog.require('app');
goog.require('app.DrawnFeatures');
goog.require('app.FeaturePopup');
goog.require('app.SelectedFeatures');
goog.require('goog.asserts');
goog.require('ngeo.DecorateInteraction');
goog.require('ngeo.FeatureOverlayMgr');
goog.require('ngeo.Location');
goog.require('ngeo.format.FeatureHash');
goog.require('ol.CollectionEventType');
goog.require('ol.FeatureStyleFunction');
goog.require('ol.events.condition');
goog.require('ol.geom.GeometryType');
goog.require('ol.interaction.Draw');
goog.require('ol.interaction.Modify');
goog.require('ol.interaction.Select');
goog.require('ol.style.RegularShape');

/**
 * @param {string} appDrawTemplateUrl Url to draw template
 * @return {angular.Directive} The Directive Definition Object.
 * @ngInject
 */
app.drawDirective = function(appDrawTemplateUrl) {
  return {
    restrict: 'E',
    scope: {
      'map': '=appDrawMap',
      'active': '=appDrawActive',
      'queryActive': '=appDrawQueryactive'
    },
    controller: 'AppDrawController',
    controllerAs: 'ctrl',
    bindToController: true,
    templateUrl: appDrawTemplateUrl
  };
};

app.module.directive('appDraw', app.drawDirective);

/**
 * @param {!angular.Scope} $scope Scope.
 * @param {ngeo.DecorateInteraction} ngeoDecorateInteraction Decorate
 *     interaction service.
 * @param {ngeo.Location} ngeoLocation Location service.
 * @param {ngeo.FeatureOverlayMgr} ngeoFeatureOverlayMgr Feature overlay
 * manager.
 * @param {app.FeaturePopup} appFeaturePopup Feature popup service.
 * @param {app.DrawnFeatures} appDrawnFeatures Drawn features service.
 * @param {app.SelectedFeatures} appSelectedFeatures Selected features service.
 * @constructor
 * @export
 * @ngInject
 */
app.DrawController = function($scope, ngeoDecorateInteraction, ngeoLocation,
    ngeoFeatureOverlayMgr, appFeaturePopup, appDrawnFeatures,
    appSelectedFeatures) {

  /**
   * @type {ol.Map}
   *  @export
   */
  this.map;

  /**
   * @type {boolean}
   *  @export
   */
  this.active;

  /**
   * @type {number}
   * @private
   */
  this.featureSeq_ = 0;

  /**
   * @type {ol.Collection.<ol.Feature>}
   * @private
   */
  this.features_ = appDrawnFeatures;

  /**
   * @type {ol.Collection<ol.Feature>}
   * @private
   */
  this.selectedFeatures_ = appSelectedFeatures;

  /**
   * @type {app.FeaturePopup}
   * @private
   */
  this.featurePopup_ = appFeaturePopup;

  /**
   * @type {angular.Scope}
   * @private
   */
  this.scope_ = $scope;

  /**
   * @type {ngeo.Location}
   * @private
   */
  this.ngeoLocation_ = ngeoLocation;

  /**
   * @type {ngeo.format.FeatureHash}
   * @private
   */
  this.fhFormat_ = new ngeo.format.FeatureHash();

  var drawPoint = new ol.interaction.Draw({
    features: this.features_,
    type: ol.geom.GeometryType.POINT
  });

  /**
   * @type {ol.interaction.Draw}
   * @export
   */
  this.drawPoint = drawPoint;

  drawPoint.setActive(false);
  ngeoDecorateInteraction(drawPoint);
  this.map.addInteraction(drawPoint);
  goog.events.listen(drawPoint, ol.Object.getChangeEventType(
      ol.interaction.InteractionProperty.ACTIVE),
      this.onChangeActive_, false, this);
  goog.events.listen(drawPoint, ol.interaction.DrawEventType.DRAWEND,
      this.onDrawEnd_, false, this);

  var drawLine = new ol.interaction.Draw({
    features: this.features_,
    type: ol.geom.GeometryType.LINE_STRING
  });

  /**
   * @type {ol.interaction.Draw}
   * @export
   */
  this.drawLine = drawLine;

  drawLine.setActive(false);
  ngeoDecorateInteraction(drawLine);
  this.map.addInteraction(drawLine);
  goog.events.listen(drawLine, ol.Object.getChangeEventType(
      ol.interaction.InteractionProperty.ACTIVE),
      this.onChangeActive_, false, this);
  goog.events.listen(drawLine, ol.interaction.DrawEventType.DRAWEND,
      this.onDrawEnd_, false, this);

  var drawPolygon = new ol.interaction.Draw({
    features: this.features_,
    type: ol.geom.GeometryType.POLYGON
  });

  /**
   * @type {ol.interaction.Draw}
   * @export
   */
  this.drawPolygon = drawPolygon;

  drawPolygon.setActive(false);
  ngeoDecorateInteraction(drawPolygon);
  this.map.addInteraction(drawPolygon);
  goog.events.listen(drawPolygon, ol.Object.getChangeEventType(
      ol.interaction.InteractionProperty.ACTIVE),
      this.onChangeActive_, false, this);
  goog.events.listen(drawPolygon, ol.interaction.DrawEventType.DRAWEND,
      this.onDrawEnd_, false, this);

  // Watch the "active" property, and disable the draw interactions
  // when "active" gets set to false.
  $scope.$watch(goog.bind(function() {
    return this.active;
  }, this), goog.bind(function(newVal) {
    if (newVal === false) {
      this.drawPoint.setActive(false);
      this.drawLine.setActive(false);
      this.drawPolygon.setActive(false);
      this['queryActive'] = true;
    } else {
      this['queryActive'] = false;
    }
  }, this));

  // Decode the features encoded in the URL and add them to the collection
  // of drawn features.
  var encodedFeatures = ngeoLocation.getParam('features');
  if (goog.isDef(encodedFeatures)) {
    var features = this.fhFormat_.readFeatures(encodedFeatures);
    goog.asserts.assert(!goog.isNull(features));
    this.features_.extend(features);
  }

  var selectInteraction = new ol.interaction.Select({
    features: appSelectedFeatures,
    filter: goog.bind(function(feature, layer) {
      return this.features_.getArray().indexOf(feature) != -1;
    }, this)
  });
  this.map.addInteraction(selectInteraction);

  /**
   * @type {ol.interaction.Select}
   * @private
   */
  this.selectInteraction_ = selectInteraction;

  appFeaturePopup.init(this.map, selectInteraction.getFeatures());

  goog.events.listen(appSelectedFeatures, ol.CollectionEventType.ADD,
      /**
       * @param {ol.CollectionEvent} evt
       */
      function(evt) {
        goog.asserts.assertInstanceof(evt.element, ol.Feature);
        var feature = evt.element;
        feature.set('__selected__', true);
      });

  goog.events.listen(appSelectedFeatures, ol.CollectionEventType.REMOVE,
      /**
       * @param {ol.CollectionEvent} evt
       */
      function(evt) {
        goog.asserts.assertInstanceof(evt.element, ol.Feature);
        var feature = evt.element;
        feature.set('__selected__', false);
      });

  goog.events.listen(selectInteraction,
      ol.interaction.SelectEventType.SELECT,
      /**
       * @param {ol.interaction.SelectEvent} evt
       */
      function(evt) {
        if (evt.selected.length > 0) {
          var feature = evt.selected[0];
          this.featurePopup_.show(feature, evt.mapBrowserEvent.coordinate);
        } else {
          this.featurePopup_.hide();
        }
        $scope.$apply();
      }, true, this);

  var modifyInteraction = new ol.interaction.Modify({
    features: appSelectedFeatures
  });
  this.map.addInteraction(modifyInteraction);

  var drawOverlay = ngeoFeatureOverlayMgr.getFeatureOverlay();
  drawOverlay.setFeatures(appDrawnFeatures);
};

/**
 * @param {ol.ObjectEvent} event
 * @private
 */
app.DrawController.prototype.onChangeActive_ = function(event) {
  var active = this.drawPoint.getActive() || this.drawLine.getActive() ||
      this.drawPolygon.getActive();
  this.selectInteraction_.setActive(!active);
};

/**
 * @param {ol.interaction.DrawEvent} event
 * @private
 */
app.DrawController.prototype.onDrawEnd_ = function(event) {
  var feature = event.feature;
  feature.set('name', 'element ' + (++this.featureSeq_));
  feature.set('__editable__', true);
  feature.set('color', '#ed1c24');
  feature.set('opacity', 0.2);
  feature.set('stroke', 1.25);
  feature.set('size', 10);
  feature.set('angle', 0);
  feature.set('is_label', false);
  feature.set('linestyle', 'plain');
  feature.set('symbol_id', 'circle');
  feature.setStyle(app.DrawController.createStyleFunction_());

  // Deactivating asynchronosly to prevent dbl-click to zoom in
  window.setTimeout(goog.bind(function() {
    this.scope_.$apply(function() {
      event.target.setActive(false);
    });
  }, this), 0);

  // Encode the features in the URL.
  // warning: the drawn feature is not yet in the collection when the
  // "drawend" event is triggered. So we create a new array and append
  // the drawn feature to that array.
  var features = this.features_.getArray().slice();
  features.push(feature);
  this.ngeoLocation_.updateParams({
    'features': this.fhFormat_.writeFeatures(features)
  });
  this.selectedFeatures_.clear();
  this.selectedFeatures_.push(feature);
  this.featurePopup_.show(feature);
};

/**
 * @return {ol.FeatureStyleFunction}
 * @private
 */
app.DrawController.createStyleFunction_ = function() {

  var styles = [];

  var vertexStyle = new ol.style.Style({
    image: new ol.style.RegularShape({
      radius: 6,
      points: 4,
      angle: Math.PI / 4,
      fill: new ol.style.Fill({
        color: 'rgba(255, 255, 255, 0.5)'
      }),
      stroke: new ol.style.Stroke({
        color: 'rgba(0, 0, 0, 1)'
      })
    }),
    geometry: function(feature) {
      var geom = feature.getGeometry();

      if (geom.getType() == ol.geom.GeometryType.POINT) {
        return;
      }

      var coordinates;
      if (geom instanceof ol.geom.LineString) {
        coordinates = feature.getGeometry().getCoordinates();
        return new ol.geom.MultiPoint(coordinates);
      } else if (geom instanceof ol.geom.Polygon) {
        coordinates = feature.getGeometry().getCoordinates()[0];
        return new ol.geom.MultiPoint(coordinates);
      } else {
        return feature.getGeometry();
      }
    }
  });

  var fillStyle = new ol.style.Fill();

  return function(resolution) {

    // clear the styles
    styles.length = 0;

    if (this.get('__editable__') && this.get('__selected__')) {
      styles.push(vertexStyle);
    }

    // goog.asserts.assert(goog.isDef(this.get('__style__'));
    var color = this.get('color');
    var rgb = goog.color.hexToRgb(color);
    var fillColor = goog.color.alpha.rgbaToRgbaStyle(rgb[0], rgb[1], rgb[2],
        this.get('opacity'));
    fillStyle.setColor(fillColor);

    var lineDash;
    if (this.get('linestyle')) {
      switch (this.get('linestyle')) {
        case 'dashed':
          lineDash = [10, 10];
          break;
        case 'dotted':
          lineDash = [1, 6];
          break;
      }
    }

    var stroke;

    if (this.get('stroke') > 0) {
      stroke = new ol.style.Stroke({
        color: color,
        width: this.get('stroke'),
        lineDash: lineDash
      });
    }
    var imageOptions = {
      fill: fillStyle,
      stroke: new ol.style.Stroke({
        color: color,
        width: this.get('size') / 7
      }),
      radius: this.get('size')
    };
    var image = new ol.style.Circle(imageOptions);
    if (this.get('symbol_id') && this.get('symbol_id') != 'circle') {
      goog.object.extend(imageOptions, ({
        points: 4,
        angle: Math.PI / 4,
        rotation: this.get('angle')
      }));
      image = new ol.style.RegularShape(
          /** @type {olx.style.RegularShapeOptions} */ (imageOptions));
    }

    if (this.get('text')) {
      return [new ol.style.Style({
        text: new ol.style.Text(/** @type {olx.style.TextOptions} */ ({
          text: this.get('name'),
          font: this.get('size') + 'px Sans-serif',
          rotation: this.get('angle'),
          fill: new ol.style.Fill({
            color: color
          }),
          stroke: new ol.style.Stroke({
            color: 'white',
            width: 2
          })
        }))
      })];
    } else {
      styles.push(new ol.style.Style({
        image: image,
        fill: fillStyle,
        stroke: stroke
      }));
    }

    return styles;
  };
};

app.module.controller('AppDrawController', app.DrawController);
<commit_msg>Change variable name for clarity<commit_after>/**
 * @fileoverview This file provides a draw directive. This directive is used
 * to create a draw panel in the page.
 *
 * Example:
 *
 * <app-draw app-draw-map="::mainCtrl.map"
 *           app-draw-queryactive="mainCtrl.queryActive"
 *           app-draw-active="mainCtrl.drawOpen"></app-draw>
 *
 * Note the use of the one-time binding operator (::) in the map expression.
 * One-time binding is used because we know the map is not going to change
 * during the lifetime of the application.
 */
goog.provide('app.DrawController');
goog.provide('app.drawDirective');

goog.require('app');
goog.require('app.DrawnFeatures');
goog.require('app.FeaturePopup');
goog.require('app.SelectedFeatures');
goog.require('goog.asserts');
goog.require('ngeo.DecorateInteraction');
goog.require('ngeo.FeatureOverlayMgr');
goog.require('ngeo.Location');
goog.require('ngeo.format.FeatureHash');
goog.require('ol.CollectionEventType');
goog.require('ol.FeatureStyleFunction');
goog.require('ol.events.condition');
goog.require('ol.geom.GeometryType');
goog.require('ol.interaction.Draw');
goog.require('ol.interaction.Modify');
goog.require('ol.interaction.Select');
goog.require('ol.style.RegularShape');

/**
 * @param {string} appDrawTemplateUrl Url to draw template
 * @return {angular.Directive} The Directive Definition Object.
 * @ngInject
 */
app.drawDirective = function(appDrawTemplateUrl) {
  return {
    restrict: 'E',
    scope: {
      'map': '=appDrawMap',
      'active': '=appDrawActive',
      'queryActive': '=appDrawQueryactive'
    },
    controller: 'AppDrawController',
    controllerAs: 'ctrl',
    bindToController: true,
    templateUrl: appDrawTemplateUrl
  };
};

app.module.directive('appDraw', app.drawDirective);

/**
 * @param {!angular.Scope} $scope Scope.
 * @param {ngeo.DecorateInteraction} ngeoDecorateInteraction Decorate
 *     interaction service.
 * @param {ngeo.Location} ngeoLocation Location service.
 * @param {ngeo.FeatureOverlayMgr} ngeoFeatureOverlayMgr Feature overlay
 * manager.
 * @param {app.FeaturePopup} appFeaturePopup Feature popup service.
 * @param {app.DrawnFeatures} appDrawnFeatures Drawn features service.
 * @param {app.SelectedFeatures} appSelectedFeatures Selected features service.
 * @constructor
 * @export
 * @ngInject
 */
app.DrawController = function($scope, ngeoDecorateInteraction, ngeoLocation,
    ngeoFeatureOverlayMgr, appFeaturePopup, appDrawnFeatures,
    appSelectedFeatures) {

  /**
   * @type {ol.Map}
   *  @export
   */
  this.map;

  /**
   * @type {boolean}
   *  @export
   */
  this.active;

  /**
   * @type {number}
   * @private
   */
  this.featureSeq_ = 0;

  /**
   * @type {ol.Collection.<ol.Feature>}
   * @private
   */
  this.drawnFeatures_ = appDrawnFeatures;

  /**
   * @type {ol.Collection<ol.Feature>}
   * @private
   */
  this.selectedFeatures_ = appSelectedFeatures;

  /**
   * @type {app.FeaturePopup}
   * @private
   */
  this.featurePopup_ = appFeaturePopup;

  /**
   * @type {angular.Scope}
   * @private
   */
  this.scope_ = $scope;

  /**
   * @type {ngeo.Location}
   * @private
   */
  this.ngeoLocation_ = ngeoLocation;

  /**
   * @type {ngeo.format.FeatureHash}
   * @private
   */
  this.fhFormat_ = new ngeo.format.FeatureHash();

  var drawPoint = new ol.interaction.Draw({
    features: this.drawnFeatures_,
    type: ol.geom.GeometryType.POINT
  });

  /**
   * @type {ol.interaction.Draw}
   * @export
   */
  this.drawPoint = drawPoint;

  drawPoint.setActive(false);
  ngeoDecorateInteraction(drawPoint);
  this.map.addInteraction(drawPoint);
  goog.events.listen(drawPoint, ol.Object.getChangeEventType(
      ol.interaction.InteractionProperty.ACTIVE),
      this.onChangeActive_, false, this);
  goog.events.listen(drawPoint, ol.interaction.DrawEventType.DRAWEND,
      this.onDrawEnd_, false, this);

  var drawLine = new ol.interaction.Draw({
    features: this.drawnFeatures_,
    type: ol.geom.GeometryType.LINE_STRING
  });

  /**
   * @type {ol.interaction.Draw}
   * @export
   */
  this.drawLine = drawLine;

  drawLine.setActive(false);
  ngeoDecorateInteraction(drawLine);
  this.map.addInteraction(drawLine);
  goog.events.listen(drawLine, ol.Object.getChangeEventType(
      ol.interaction.InteractionProperty.ACTIVE),
      this.onChangeActive_, false, this);
  goog.events.listen(drawLine, ol.interaction.DrawEventType.DRAWEND,
      this.onDrawEnd_, false, this);

  var drawPolygon = new ol.interaction.Draw({
    features: this.drawnFeatures_,
    type: ol.geom.GeometryType.POLYGON
  });

  /**
   * @type {ol.interaction.Draw}
   * @export
   */
  this.drawPolygon = drawPolygon;

  drawPolygon.setActive(false);
  ngeoDecorateInteraction(drawPolygon);
  this.map.addInteraction(drawPolygon);
  goog.events.listen(drawPolygon, ol.Object.getChangeEventType(
      ol.interaction.InteractionProperty.ACTIVE),
      this.onChangeActive_, false, this);
  goog.events.listen(drawPolygon, ol.interaction.DrawEventType.DRAWEND,
      this.onDrawEnd_, false, this);

  // Watch the "active" property, and disable the draw interactions
  // when "active" gets set to false.
  $scope.$watch(goog.bind(function() {
    return this.active;
  }, this), goog.bind(function(newVal) {
    if (newVal === false) {
      this.drawPoint.setActive(false);
      this.drawLine.setActive(false);
      this.drawPolygon.setActive(false);
      this['queryActive'] = true;
    } else {
      this['queryActive'] = false;
    }
  }, this));

  // Decode the features encoded in the URL and add them to the collection
  // of drawn features.
  var encodedFeatures = ngeoLocation.getParam('features');
  if (goog.isDef(encodedFeatures)) {
    var features = this.fhFormat_.readFeatures(encodedFeatures);
    goog.asserts.assert(!goog.isNull(features));
    this.drawnFeatures_.extend(features);
  }

  var selectInteraction = new ol.interaction.Select({
    features: appSelectedFeatures,
    filter: goog.bind(function(feature, layer) {
      return this.drawnFeatures_.getArray().indexOf(feature) != -1;
    }, this)
  });
  this.map.addInteraction(selectInteraction);

  /**
   * @type {ol.interaction.Select}
   * @private
   */
  this.selectInteraction_ = selectInteraction;

  appFeaturePopup.init(this.map, selectInteraction.getFeatures());

  goog.events.listen(appSelectedFeatures, ol.CollectionEventType.ADD,
      /**
       * @param {ol.CollectionEvent} evt
       */
      function(evt) {
        goog.asserts.assertInstanceof(evt.element, ol.Feature);
        var feature = evt.element;
        feature.set('__selected__', true);
      });

  goog.events.listen(appSelectedFeatures, ol.CollectionEventType.REMOVE,
      /**
       * @param {ol.CollectionEvent} evt
       */
      function(evt) {
        goog.asserts.assertInstanceof(evt.element, ol.Feature);
        var feature = evt.element;
        feature.set('__selected__', false);
      });

  goog.events.listen(selectInteraction,
      ol.interaction.SelectEventType.SELECT,
      /**
       * @param {ol.interaction.SelectEvent} evt
       */
      function(evt) {
        if (evt.selected.length > 0) {
          var feature = evt.selected[0];
          this.featurePopup_.show(feature, evt.mapBrowserEvent.coordinate);
        } else {
          this.featurePopup_.hide();
        }
        $scope.$apply();
      }, true, this);

  var modifyInteraction = new ol.interaction.Modify({
    features: appSelectedFeatures
  });
  this.map.addInteraction(modifyInteraction);

  var drawOverlay = ngeoFeatureOverlayMgr.getFeatureOverlay();
  drawOverlay.setFeatures(appDrawnFeatures);
};

/**
 * @param {ol.ObjectEvent} event
 * @private
 */
app.DrawController.prototype.onChangeActive_ = function(event) {
  var active = this.drawPoint.getActive() || this.drawLine.getActive() ||
      this.drawPolygon.getActive();
  this.selectInteraction_.setActive(!active);
};

/**
 * @param {ol.interaction.DrawEvent} event
 * @private
 */
app.DrawController.prototype.onDrawEnd_ = function(event) {
  var feature = event.feature;
  feature.set('name', 'element ' + (++this.featureSeq_));
  feature.set('__editable__', true);
  feature.set('color', '#ed1c24');
  feature.set('opacity', 0.2);
  feature.set('stroke', 1.25);
  feature.set('size', 10);
  feature.set('angle', 0);
  feature.set('is_label', false);
  feature.set('linestyle', 'plain');
  feature.set('symbol_id', 'circle');
  feature.setStyle(app.DrawController.createStyleFunction_());

  // Deactivating asynchronosly to prevent dbl-click to zoom in
  window.setTimeout(goog.bind(function() {
    this.scope_.$apply(function() {
      event.target.setActive(false);
    });
  }, this), 0);

  // Encode the features in the URL.
  // warning: the drawn feature is not yet in the collection when the
  // "drawend" event is triggered. So we create a new array and append
  // the drawn feature to that array.
  var features = this.drawnFeatures_.getArray().slice();
  features.push(feature);
  this.ngeoLocation_.updateParams({
    'features': this.fhFormat_.writeFeatures(features)
  });
  this.selectedFeatures_.clear();
  this.selectedFeatures_.push(feature);
  this.featurePopup_.show(feature);
};

/**
 * @return {ol.FeatureStyleFunction}
 * @private
 */
app.DrawController.createStyleFunction_ = function() {

  var styles = [];

  var vertexStyle = new ol.style.Style({
    image: new ol.style.RegularShape({
      radius: 6,
      points: 4,
      angle: Math.PI / 4,
      fill: new ol.style.Fill({
        color: 'rgba(255, 255, 255, 0.5)'
      }),
      stroke: new ol.style.Stroke({
        color: 'rgba(0, 0, 0, 1)'
      })
    }),
    geometry: function(feature) {
      var geom = feature.getGeometry();

      if (geom.getType() == ol.geom.GeometryType.POINT) {
        return;
      }

      var coordinates;
      if (geom instanceof ol.geom.LineString) {
        coordinates = feature.getGeometry().getCoordinates();
        return new ol.geom.MultiPoint(coordinates);
      } else if (geom instanceof ol.geom.Polygon) {
        coordinates = feature.getGeometry().getCoordinates()[0];
        return new ol.geom.MultiPoint(coordinates);
      } else {
        return feature.getGeometry();
      }
    }
  });

  var fillStyle = new ol.style.Fill();

  return function(resolution) {

    // clear the styles
    styles.length = 0;

    if (this.get('__editable__') && this.get('__selected__')) {
      styles.push(vertexStyle);
    }

    // goog.asserts.assert(goog.isDef(this.get('__style__'));
    var color = this.get('color');
    var rgb = goog.color.hexToRgb(color);
    var fillColor = goog.color.alpha.rgbaToRgbaStyle(rgb[0], rgb[1], rgb[2],
        this.get('opacity'));
    fillStyle.setColor(fillColor);

    var lineDash;
    if (this.get('linestyle')) {
      switch (this.get('linestyle')) {
        case 'dashed':
          lineDash = [10, 10];
          break;
        case 'dotted':
          lineDash = [1, 6];
          break;
      }
    }

    var stroke;

    if (this.get('stroke') > 0) {
      stroke = new ol.style.Stroke({
        color: color,
        width: this.get('stroke'),
        lineDash: lineDash
      });
    }
    var imageOptions = {
      fill: fillStyle,
      stroke: new ol.style.Stroke({
        color: color,
        width: this.get('size') / 7
      }),
      radius: this.get('size')
    };
    var image = new ol.style.Circle(imageOptions);
    if (this.get('symbol_id') && this.get('symbol_id') != 'circle') {
      goog.object.extend(imageOptions, ({
        points: 4,
        angle: Math.PI / 4,
        rotation: this.get('angle')
      }));
      image = new ol.style.RegularShape(
          /** @type {olx.style.RegularShapeOptions} */ (imageOptions));
    }

    if (this.get('text')) {
      return [new ol.style.Style({
        text: new ol.style.Text(/** @type {olx.style.TextOptions} */ ({
          text: this.get('name'),
          font: this.get('size') + 'px Sans-serif',
          rotation: this.get('angle'),
          fill: new ol.style.Fill({
            color: color
          }),
          stroke: new ol.style.Stroke({
            color: 'white',
            width: 2
          })
        }))
      })];
    } else {
      styles.push(new ol.style.Style({
        image: image,
        fill: fillStyle,
        stroke: stroke
      }));
    }

    return styles;
  };
};

app.module.controller('AppDrawController', app.DrawController);
<|endoftext|>


<commit_before> // Load a user using the QuickUser class
user = new QuickUser();

// Read the user ID that was assigned
var id = user.get("id");
var hits = user.get("hits");
var registered = user.get("registered");

// Assign the register function to the onClick event of the register button
$('#registerButton').click( function() { register(); } );

$('.build').html(hits);

// If this user has been here several times ask them to register
if (hits >= 5) {
    // If they are not registered
    if (registered != true) {
        // Ask them to register
        $('.register').show();
    }
}

// Register the app
function register() {
    // Set the user value to registered
    user.set("registered", true);
    // If the email address is not blank
    if ($("#email").val() != '') {
        // Set the users email address
        user.set("email", $('#email').val() );
    }
    // Submit the email address to the API
    $.get('http://joeldare.com/register/', {from: 'random_riff', email: $('#email').val()});
    // Hide the dialog
    $('.register').hide();
}<commit_msg>Adjusted it to prompt for registration on the third load.<commit_after> // Load a user using the QuickUser class
user = new QuickUser();

// Read the user ID that was assigned
var id = user.get("id");
var hits = user.get("hits");
var registered = user.get("registered");

// Assign the register function to the onClick event of the register button
$('#registerButton').click( function() { register(); } );

$('.build').html(hits);

// If this user has been here several times ask them to register
if (hits >= 3) {
    // If they are not registered
    if (registered != true) {
        // Ask them to register
        $('.register').show();
    }
}

// Register the app
function register() {
    // Set the user value to registered
    user.set("registered", true);
    // If the email address is not blank
    if ($("#email").val() != '') {
        // Set the users email address
        user.set("email", $('#email').val() );
    }
    // Submit the email address to the API
    $.get('http://joeldare.com/register/', {from: 'random_riff', email: $('#email').val()});
    // Hide the dialog
    $('.register').hide();
}<|endoftext|>


<commit_before>/**
 * Copyright 2014 Solinea, Inc.
 *
 * Licensed under the Solinea Software License Agreement (goldstone),
 * Version 1.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *     http://www.solinea.com/goldstone/LICENSE.pdf
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: Alex Jacobs
 */

/*
to invoke:
1. include infoButonText.js in the template script tags
2. instantiate the model as a variable: var infoButtonText = new InfoButtonText().get('infoText');
3. invoke via infoButtonText, and an index corresponding to the particular text desired.

2 styles:
---------
1. infoButtonText.discoverCloudTopology (Front Page Cloud Topology)
2. infoButtonText['eventTimeline'] (Front Page Event Timeline)
etc...

*/

var InfoButtonText = Backbone.Model.extend({
    defaults: {
        infoText: {

            // populate info-button-text here.
            // accepts html markup such as

            discoverCloudTopology: 'This is the OpenStack topology map.  You ' +
                'can use leaf nodes to navigate to specific types of resources.',

            eventTimeline: 'The event timeline displays key events that have occurred ' +
                'in your cloud.  You can adjust the displayed data with the filter and ' +
                'time settings in the menu bar.  Hovering on an event brings up the ' +
                'event detail.',

            nodeAvailability: 'The node presence chart keeps track of the last time each ' +
                'node in the cloud was seen.  Nodes on the right have been seen more recently ' +
                'than nodes on the left.  The center lane shows nodes that have been detected ' +
                'in the log stream.  The top lane shows nodes that are not logging, but can be ' +
                'pinged.',

            serviceStatus: 'The service status panel shows the last known state of all OS services' +
                'on the node.',

            utilization: 'The utilization charts show the OS level utilization of the node.',

            hypervisor: 'The hypervisor charts show the last known allocation and usage of resources ' +
                'across all of the VMs on the node.',

            novaTopologyDiscover: 'This is the OpenStack Nova topology map.  You ' +
                'can use leaf nodes to populate the resource list on the right.  In some cases, ' +
                'such as hypervisors, clicking a resource in the table will navigate you ' +
                'to a resource specific view.',

            cinderTopologyDiscover: 'This is the OpenStack Cinder topology map.  You ' +
                'can use leaf nodes to populate the resource list on the right.  In some cases, ' +
                'clicking a resource in the table will navigate you ' +
                'to a resource specific view.',

            glanceTopologyDiscover: 'This is the OpenStack Glance topology map.  You ' +
                'can use leaf nodes to populate the resource list on the right.  In some cases, ' +
                'clicking a resource in the table will navigate you ' +
                'to a resource specific view.',

            keystoneTopologyDiscover: 'This is the OpenStack Keystone topology map.  You ' +
                'can use leaf nodes to populate the resource list on the right.  In some cases, ' +
                'clicking a resource in the table will navigate you ' +
                'to a resource specific view.',

            novaSpawns: 'This chart displays VM spawn success and failure counts ' +
                'across your cloud.  You can adjust the displayed data with the ' +
                'time settings in the menu bar.  This data is derived from the ' +
                'log stream, so if no logging occurs for a period of time, gaps may ' +
                'appear in the data.',

            novaCpuResources: 'This chart displays aggregate CPU core allocation ' +
                'across your cloud.  You can adjust the displayed data with the ' +
                'time settings in the menu bar.  This data is derived from the ' +
                'log stream, so if no logging occurs for a period of time, gaps may ' +
                'appear in the data.',

            novaMemResources: 'This chart displays aggregate memory allocation ' +
                'across your cloud.  You can adjust the displayed data with the ' +
                'time settings in the menu bar.  This data is derived from the ' +
                'log stream, so if no logging occurs for a period of time, gaps may ' +
                'appear in the data.',

            novaDiskResources: 'This chart displays aggregate disk allocation ' +
                'across your cloud.  You can adjust the displayed data with the ' +
                'time settings in the menu bar.  This data is derived from the ' +
                'log stream, so if no logging occurs for a period of time, gaps may ' +
                'appear in the data.',

            searchLogAnalysis: 'This chart displays log stream data ' +
                'across your cloud.  You can adjust the displayed data with the ' +
                'time settings in the menu bar, and with the filter buttons that double ' +
                'as a legend.  The table below contains the individual log entries for ' +
                'the time range and filter settings.'
        }
    }
});
<commit_msg>Inserts missing space in infoButtonText for serviceStatus.<commit_after>/**
 * Copyright 2014 Solinea, Inc.
 *
 * Licensed under the Solinea Software License Agreement (goldstone),
 * Version 1.0 (the "License"); you may not use this file except in compliance
 * with the License. You may obtain a copy of the License at:
 *
 *     http://www.solinea.com/goldstone/LICENSE.pdf
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * Author: Alex Jacobs
 */

/*
to invoke:
1. include infoButonText.js in the template script tags
2. instantiate the model as a variable: var infoButtonText = new InfoButtonText().get('infoText');
3. invoke via infoButtonText, and an index corresponding to the particular text desired.

2 styles:
---------
1. infoButtonText.discoverCloudTopology (Front Page Cloud Topology)
2. infoButtonText['eventTimeline'] (Front Page Event Timeline)
etc...

*/

var InfoButtonText = Backbone.Model.extend({
    defaults: {
        infoText: {

            // populate info-button-text here.
            // accepts html markup such as

            discoverCloudTopology: 'This is the OpenStack topology map.  You ' +
                'can use leaf nodes to navigate to specific types of resources.',

            eventTimeline: 'The event timeline displays key events that have occurred ' +
                'in your cloud.  You can adjust the displayed data with the filter and ' +
                'time settings in the menu bar.  Hovering on an event brings up the ' +
                'event detail.',

            nodeAvailability: 'The node presence chart keeps track of the last time each ' +
                'node in the cloud was seen.  Nodes on the right have been seen more recently ' +
                'than nodes on the left.  The center lane shows nodes that have been detected ' +
                'in the log stream.  The top lane shows nodes that are not logging, but can be ' +
                'pinged.',

            serviceStatus: 'The service status panel shows the last known state of all OS services ' +
                'on the node.',

            utilization: 'The utilization charts show the OS level utilization of the node.',

            hypervisor: 'The hypervisor charts show the last known allocation and usage of resources ' +
                'across all of the VMs on the node.',

            novaTopologyDiscover: 'This is the OpenStack Nova topology map.  You ' +
                'can use leaf nodes to populate the resource list on the right.  In some cases, ' +
                'such as hypervisors, clicking a resource in the table will navigate you ' +
                'to a resource specific view.',

            cinderTopologyDiscover: 'This is the OpenStack Cinder topology map.  You ' +
                'can use leaf nodes to populate the resource list on the right.  In some cases, ' +
                'clicking a resource in the table will navigate you ' +
                'to a resource specific view.',

            glanceTopologyDiscover: 'This is the OpenStack Glance topology map.  You ' +
                'can use leaf nodes to populate the resource list on the right.  In some cases, ' +
                'clicking a resource in the table will navigate you ' +
                'to a resource specific view.',

            keystoneTopologyDiscover: 'This is the OpenStack Keystone topology map.  You ' +
                'can use leaf nodes to populate the resource list on the right.  In some cases, ' +
                'clicking a resource in the table will navigate you ' +
                'to a resource specific view.',

            novaSpawns: 'This chart displays VM spawn success and failure counts ' +
                'across your cloud.  You can adjust the displayed data with the ' +
                'time settings in the menu bar.  This data is derived from the ' +
                'log stream, so if no logging occurs for a period of time, gaps may ' +
                'appear in the data.',

            novaCpuResources: 'This chart displays aggregate CPU core allocation ' +
                'across your cloud.  You can adjust the displayed data with the ' +
                'time settings in the menu bar.  This data is derived from the ' +
                'log stream, so if no logging occurs for a period of time, gaps may ' +
                'appear in the data.',

            novaMemResources: 'This chart displays aggregate memory allocation ' +
                'across your cloud.  You can adjust the displayed data with the ' +
                'time settings in the menu bar.  This data is derived from the ' +
                'log stream, so if no logging occurs for a period of time, gaps may ' +
                'appear in the data.',

            novaDiskResources: 'This chart displays aggregate disk allocation ' +
                'across your cloud.  You can adjust the displayed data with the ' +
                'time settings in the menu bar.  This data is derived from the ' +
                'log stream, so if no logging occurs for a period of time, gaps may ' +
                'appear in the data.',

            searchLogAnalysis: 'This chart displays log stream data ' +
                'across your cloud.  You can adjust the displayed data with the ' +
                'time settings in the menu bar, and with the filter buttons that double ' +
                'as a legend.  The table below contains the individual log entries for ' +
                'the time range and filter settings.'
        }
    }
});
<|endoftext|>


<commit_before>'use strict';
var _ = require('lodash');
var extend = require('deep-extend');
var generators = require('yeoman-generator');
var parseAuthor = require('parse-author');
var githubUsername = require('github-username');
var path = require('path');
var askName = require('inquirer-npm-name');

module.exports = generators.Base.extend({
  constructor: function () {
    generators.Base.apply(this, arguments);

    this.option('travis', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: 'Include travis config'
    });

    this.option('boilerplate', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: 'Include boilerplate files'
    });

    this.option('babel', {
      type: Boolean,
      required: false,
      desc: 'Compile ES2015 using Babel'
    });

    this.option('cli', {
      type: Boolean,
      required: false,
      defaults: false,
      desc: 'Add a CLI'
    });

    this.option('name', {
      type: String,
      required: false,
      desc: 'Project name'
    });

    this.option('projectRoot', {
      type: String,
      required: false,
      defaults: 'lib',
      desc: 'Relative path to the project code root'
    });

    this.option('readme', {
      type: String,
      required: false,
      desc: 'Content to insert in the README.md file'
    });
  },

  initializing: function () {
    this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    // Pre set the default props from the information we have at this point
    this.props = {
      name: this.pkg.name,
      description: this.pkg.description,
      version: this.pkg.version,
      homepage: this.pkg.homepage,
      babel: Boolean(this.options.babel)
    };

    if (_.isObject(this.pkg.author)) {
      this.props.authorName = this.pkg.author.name;
      this.props.authorEmail = this.pkg.author.email;
      this.props.authorUrl = this.pkg.author.url;
    } else if (_.isString(this.pkg.author)) {
      var info = parseAuthor(this.pkg.author);
      this.props.authorName = info.name;
      this.props.authorEmail = info.email;
      this.props.authorUrl = info.url;
    }
  },

  prompting: {
    askForModuleName: function () {
      if (this.pkg.name || this.options.name) {
        this.props.name = this.pkg.name || _.kebabCase(this.options.name);
        return;
      }

      var done = this.async();

      askName({
        name: 'name',
        message: 'Module Name',
        default: path.basename(process.cwd()),
        filter: _.kebabCase,
        validate: function (str) {
          return str.length > 0;
        }
      }, this, function (name) {
        this.props.name = name;
        done();
      }.bind(this));
    },

    askFor: function () {
      var done = this.async();

      var prompts = [{
        name: 'description',
        message: 'Description',
        when: !this.pkg.description
      }, {
        name: 'homepage',
        message: 'Project homepage url',
        when: !this.pkg.homepage
      }, {
        name: 'authorName',
        message: 'Author\'s Name',
        when: !this.pkg.author,
        default: this.user.git.name(),
        store: true
      }, {
        name: 'authorEmail',
        message: 'Author\'s Email',
        when: !this.pkg.author,
        default: this.user.git.email(),
        store: true
      }, {
        name: 'authorUrl',
        message: 'Author\'s Homepage',
        when: !this.pkg.author,
        store: true
      }, {
        name: 'keywords',
        message: 'Package keywords (comma to split)',
        when: !this.pkg.keywords,
        filter: _.words
      }, {
        name: 'babel',
        type: 'confirm',
        message: 'Use es2015 (precompiled with Babel)',
        when: this.options.babel === undefined
      }, {
        name: 'includeCoveralls',
        type: 'confirm',
        message: 'Send coverage reports to coveralls',
        when: this.options.coveralls === undefined
      }];

      this.prompt(prompts, function (props) {
        this.props = extend(this.props, props);
        done();
      }.bind(this));
    },

    askForGithubAccount: function () {
      var done = this.async();

      githubUsername(this.props.authorEmail, function (err, username) {
        this.prompt({
          name: 'githubAccount',
          message: 'GitHub username or organization',
          default: username
        }, function (prompt) {
          this.props.githubAccount = prompt.githubAccount;
          done();
        }.bind(this));
      }.bind(this));
    }
  },

  writing: function () {
    // Re-read the content at this point because a composed generator might modify it.
    var currentPkg = this.fs.readJSON(this.destinationPath('package.json'), {});
    var pkg = {
      name: _.kebabCase(this.props.name),
      version: '0.0.0',
      description: this.props.description,
      homepage: this.props.homepage,
      author: {
        name: this.props.authorName,
        email: this.props.authorEmail,
        url: this.props.authorUrl
      },
      files: [
        this.props.babel ? 'dist' : this.options.projectRoot
      ],
      main: this.props.babel ? 'dist/index.js' : path.join(
        this.options.projectRoot,
        'index.js'
      ),
      keywords: this.props.keywords
    };

    // Let's extend package.json so we're not overwriting user previous fields
    this.fs.writeJSON('package.json', extend(pkg, currentPkg));
  },

  default: function () {
    if (this.options.travis) {
      this.composeWith('travis', {}, {
        local: require.resolve('generator-travis/generators/app')
      });
    }

    this.composeWith('node:editorconfig', {}, {
      local: require.resolve('../editorconfig')
    });

    this.composeWith('node:eslint', {
      options: {
        es2015: this.props.babel
      }
    }, {
      local: require.resolve('../eslint')
    });

    this.composeWith('node:git', {
      options: {
        name: this.props.name,
        githubAccount: this.props.githubAccount
      }
    }, {
      local: require.resolve('../git')
    });

    this.composeWith('node:gulp', {
      options: {
        coveralls: this.props.includeCoveralls,
        babel: this.props.babel,
        projectRoot: this.options.projectRoot
      }
    }, {
      local: require.resolve('../gulp')
    });

    if (this.options.boilerplate) {
      this.composeWith('node:boilerplate', {
        options: {
          name: this.props.name,
          babel: this.props.babel
        }
      }, {
        local: require.resolve('../boilerplate')
      });
    }

    if (this.options.cli) {
      this.composeWith('node:cli', {
        options: {
          babel: this.props.babel
        }
      }, {
        local: require.resolve('../cli')
      });
    }

    if (!this.pkg.license) {
      this.composeWith('license', {
        options: {
          name: this.props.authorName,
          email: this.props.authorEmail,
          website: this.props.authorUrl
        }
      }, {
        local: require.resolve('generator-license/app')
      });
    }

    if (!this.fs.exists(this.destinationPath('README.md'))) {
      this.composeWith('node:readme', {
        options: {
          name: this.props.name,
          description: this.props.description,
          githubAccount: this.props.githubAccount,
          authorName: this.props.authorName,
          authorUrl: this.props.authorUrl,
          coveralls: this.props.includeCoveralls,
          content: this.options.readme
        }
      }, {
        local: require.resolve('../readme')
      });
    }
  },

  installing: function () {
    this.npmInstall();
  }
});
<commit_msg>Prevent error if authorEmail is empty - Fix #185<commit_after>'use strict';
var _ = require('lodash');
var extend = require('deep-extend');
var generators = require('yeoman-generator');
var parseAuthor = require('parse-author');
var githubUsername = require('github-username');
var path = require('path');
var askName = require('inquirer-npm-name');

module.exports = generators.Base.extend({
  constructor: function () {
    generators.Base.apply(this, arguments);

    this.option('travis', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: 'Include travis config'
    });

    this.option('boilerplate', {
      type: Boolean,
      required: false,
      defaults: true,
      desc: 'Include boilerplate files'
    });

    this.option('babel', {
      type: Boolean,
      required: false,
      desc: 'Compile ES2015 using Babel'
    });

    this.option('cli', {
      type: Boolean,
      required: false,
      defaults: false,
      desc: 'Add a CLI'
    });

    this.option('name', {
      type: String,
      required: false,
      desc: 'Project name'
    });

    this.option('projectRoot', {
      type: String,
      required: false,
      defaults: 'lib',
      desc: 'Relative path to the project code root'
    });

    this.option('readme', {
      type: String,
      required: false,
      desc: 'Content to insert in the README.md file'
    });
  },

  initializing: function () {
    this.pkg = this.fs.readJSON(this.destinationPath('package.json'), {});

    // Pre set the default props from the information we have at this point
    this.props = {
      name: this.pkg.name,
      description: this.pkg.description,
      version: this.pkg.version,
      homepage: this.pkg.homepage,
      babel: Boolean(this.options.babel)
    };

    if (_.isObject(this.pkg.author)) {
      this.props.authorName = this.pkg.author.name;
      this.props.authorEmail = this.pkg.author.email;
      this.props.authorUrl = this.pkg.author.url;
    } else if (_.isString(this.pkg.author)) {
      var info = parseAuthor(this.pkg.author);
      this.props.authorName = info.name;
      this.props.authorEmail = info.email;
      this.props.authorUrl = info.url;
    }
  },

  prompting: {
    askForModuleName: function () {
      if (this.pkg.name || this.options.name) {
        this.props.name = this.pkg.name || _.kebabCase(this.options.name);
        return;
      }

      var done = this.async();

      askName({
        name: 'name',
        message: 'Module Name',
        default: path.basename(process.cwd()),
        filter: _.kebabCase,
        validate: function (str) {
          return str.length > 0;
        }
      }, this, function (name) {
        this.props.name = name;
        done();
      }.bind(this));
    },

    askFor: function () {
      var done = this.async();

      var prompts = [{
        name: 'description',
        message: 'Description',
        when: !this.props.description
      }, {
        name: 'homepage',
        message: 'Project homepage url',
        when: !this.props.homepage
      }, {
        name: 'authorName',
        message: 'Author\'s Name',
        when: !this.props.authorName,
        default: this.user.git.name(),
        store: true
      }, {
        name: 'authorEmail',
        message: 'Author\'s Email',
        when: !this.props.authorEmail,
        default: this.user.git.email(),
        store: true
      }, {
        name: 'authorUrl',
        message: 'Author\'s Homepage',
        when: !this.props.authorUrl,
        store: true
      }, {
        name: 'keywords',
        message: 'Package keywords (comma to split)',
        when: !this.pkg.keywords,
        filter: _.words
      }, {
        name: 'babel',
        type: 'confirm',
        message: 'Use es2015 (precompiled with Babel)',
        when: this.options.babel === undefined
      }, {
        name: 'includeCoveralls',
        type: 'confirm',
        message: 'Send coverage reports to coveralls',
        when: this.options.coveralls === undefined
      }];

      this.prompt(prompts, function (props) {
        this.props = extend(this.props, props);
        done();
      }.bind(this));
    },

    askForGithubAccount: function () {
      var done = this.async();

      githubUsername(this.props.authorEmail, function (err, username) {
        this.prompt({
          name: 'githubAccount',
          message: 'GitHub username or organization',
          default: username
        }, function (prompt) {
          this.props.githubAccount = prompt.githubAccount;
          done();
        }.bind(this));
      }.bind(this));
    }
  },

  writing: function () {
    // Re-read the content at this point because a composed generator might modify it.
    var currentPkg = this.fs.readJSON(this.destinationPath('package.json'), {});
    var pkg = {
      name: _.kebabCase(this.props.name),
      version: '0.0.0',
      description: this.props.description,
      homepage: this.props.homepage,
      author: {
        name: this.props.authorName,
        email: this.props.authorEmail,
        url: this.props.authorUrl
      },
      files: [
        this.props.babel ? 'dist' : this.options.projectRoot
      ],
      main: this.props.babel ? 'dist/index.js' : path.join(
        this.options.projectRoot,
        'index.js'
      ),
      keywords: this.props.keywords
    };

    // Let's extend package.json so we're not overwriting user previous fields
    this.fs.writeJSON('package.json', extend(pkg, currentPkg));
  },

  default: function () {
    if (this.options.travis) {
      this.composeWith('travis', {}, {
        local: require.resolve('generator-travis/generators/app')
      });
    }

    this.composeWith('node:editorconfig', {}, {
      local: require.resolve('../editorconfig')
    });

    this.composeWith('node:eslint', {
      options: {
        es2015: this.props.babel
      }
    }, {
      local: require.resolve('../eslint')
    });

    this.composeWith('node:git', {
      options: {
        name: this.props.name,
        githubAccount: this.props.githubAccount
      }
    }, {
      local: require.resolve('../git')
    });

    this.composeWith('node:gulp', {
      options: {
        coveralls: this.props.includeCoveralls,
        babel: this.props.babel,
        projectRoot: this.options.projectRoot
      }
    }, {
      local: require.resolve('../gulp')
    });

    if (this.options.boilerplate) {
      this.composeWith('node:boilerplate', {
        options: {
          name: this.props.name,
          babel: this.props.babel
        }
      }, {
        local: require.resolve('../boilerplate')
      });
    }

    if (this.options.cli) {
      this.composeWith('node:cli', {
        options: {
          babel: this.props.babel
        }
      }, {
        local: require.resolve('../cli')
      });
    }

    if (!this.pkg.license) {
      this.composeWith('license', {
        options: {
          name: this.props.authorName,
          email: this.props.authorEmail,
          website: this.props.authorUrl
        }
      }, {
        local: require.resolve('generator-license/app')
      });
    }

    if (!this.fs.exists(this.destinationPath('README.md'))) {
      this.composeWith('node:readme', {
        options: {
          name: this.props.name,
          description: this.props.description,
          githubAccount: this.props.githubAccount,
          authorName: this.props.authorName,
          authorUrl: this.props.authorUrl,
          coveralls: this.props.includeCoveralls,
          content: this.options.readme
        }
      }, {
        local: require.resolve('../readme')
      });
    }
  },

  installing: function () {
    this.npmInstall();
  }
});
<|endoftext|>


<commit_before>//= require /urlHandling/urlHelper.js

"use strict";

var OpenSpeedMonitor = OpenSpeedMonitor || {};
OpenSpeedMonitor.ChartModules = OpenSpeedMonitor.ChartModules || {};
OpenSpeedMonitor.ChartModules.UrlHandling = OpenSpeedMonitor.ChartModules.UrlHandling || {};

OpenSpeedMonitor.ChartModules.UrlHandling.ChartSwitch = (function () {

    var oldParameter = {};

    var getJobGroup = function (map) {
        var folder = null;
        if ($("#pageComparisonSelectionCard").length) {
            folder = OpenSpeedMonitor.PageComparisonSelection.getJobGroups();
        } else {
            folder = $("#folderSelectHtmlId").val();
        }
        if (folder != null) map["selectedFolder"] = folder
    };

    var getBrowser = function (map) {
        var browserSelect = $("#selectedBrowsersHtmlId");
        if (browserSelect != null) {
            var selectedBrowser = browserSelect.val();
            if (selectedBrowser != null) map["selectedBrowsers"] = selectedBrowser;
            var selectedAllBrosers = $("#selectedAllBrowsers").prop("checked");
            if (selectedAllBrosers != null) map["selectedAllBrowsers"] = selectedAllBrosers;
        }
    };

    var getLocation = function (map) {
        var selectedLocations = $("#selectedLocationsHtmlId_chosen");
        if (selectedLocations != null) {
            var selectedAllLocations = $("#selectedAllLocations").prop("checked");
            if (selectedAllLocations) map["selectedAllLocations"] = selectedAllLocations;
        }
    };

    var getConnectivity = function (map) {
        var selectedConnectivities = $("#selectedConnectivityProfilesHtmlId");
        if (selectedConnectivities != null) {
            var connectivities = selectedConnectivities.val();
            if (connectivities != null) map["selectedConnectivities"] = connectivities;
            var allConnectivies = $("#selectedAllConnectivityProfiles").prop("checked");
            if (allConnectivies) map["selectedAllConnectivityProfiles"] = allConnectivies;
        }
    };

    var getPage = function (map) {
        var pages = null;
        if($("#pageComparisonSelectionCard").length) {
            pages = OpenSpeedMonitor.PageComparisonSelection.getPages();
        }else {
         pages = $("#pageSelectHtmlId").val();
        }
        if (pages) map["selectedPages"] = pages;
    };

    var getStep = function (map) {
        var selectedSteps = $("#selectedMeasuredEventsHtmlId");
        if (selectedSteps != null) {
            var values = selectedSteps.val();
            if (values) map["selectedMeasuredEventIds"] = values
        }
    };

    var getTimeFrame = function (map) {
        map["setFromHour"] = ($('#setFromHour:checked').length > 0) ? "on" : "";
        map["setToHour"] = ($('#setToHour:checked').length > 0) ? "on" : "";
        map["from"] = $("#fromDatepicker").val();
        map["fromHour"] = $("#startDateTimePicker").find(".input-group.bootstrap-timepicker.time-control").find(".form-control").val();
        map["to"] = $("#toDatepicker").val();
        map["toHour"] = $("#endDateTimePicker").find(".input-group.bootstrap-timepicker.time-control").find(".form-control").val();
    };

    var updateUrls = function (withCurrentSelection) {
        var updatedMap = $.extend({}, oldParameter);
        if (withCurrentSelection) {
            getTimeFrame(updatedMap);
            getJobGroup(updatedMap);
            getPage(updatedMap);
            getBrowser(updatedMap);
            getLocation(updatedMap);
            getConnectivity(updatedMap);
            getStep(updatedMap);
        }
        if (updatedMap["selectedFolder"] == null) {
            updatedMap = {};
        } else {
            if (updatedMap["selectedInterval"] == null) updatedMap["selectedInterval"] = 60;
            if (updatedMap["selectedTimeFrameInterval"] == null) updatedMap["selectedTimeFrameInterval"] = 0;
            if (updatedMap["selectedAggrGroupValuesUnCached"] == null) updatedMap["selectedAggrGroupValuesUnCached"] = "docCompleteTimeInMillisecsUncached";
        }
        var params = $.param(updatedMap, true);
        var showLinks = false;
        if (params.length > 0) {
            showLinks = true;
        }
        updateUrl("#timeSeriesWithDataLink", OpenSpeedMonitor.urls.eventResultDashboardShowAll + "?" + params, showLinks);
        updateUrl("#pageAggregationWithDataLink", OpenSpeedMonitor.urls.pageAggregationShow + "?" + params, showLinks);
        updateUrl("#jobGroupAggregationWithDataLink", OpenSpeedMonitor.urls.jobGroupAggregationShow + "?" + params, showLinks);
        updateUrl("#distributionWithDataLink", OpenSpeedMonitor.urls.distributionChartShow + "?" + params, showLinks);
        updateUrl("#detailAnalysisWithDataLink", OpenSpeedMonitor.urls.detailAnalysisShow + "?" + params, showLinks);
        updateUrl("#resultListWithDataLink", OpenSpeedMonitor.urls.tabularResultPresentation + "?" + params, showLinks);
        updateUrl("#pageComparisonWithDataLink", OpenSpeedMonitor.urls.pageComparisonShow + "?" + params, showLinks)
    };

    var updateUrl = function (selector, newUrl, showLink) {
        if (!showLink) {
            $(selector).addClass("hidden");
        } else {
            $(selector).attr("href", newUrl);
            $(selector).removeClass("hidden");
        }
    };

    var init = function () {
        var oldParameter = getOldParameter();

        if (oldParameter["selectedPages"] == null && oldParameter["selectedMeasuredEventIds"] != null) {
            fetchPages(oldParameter["selectedMeasuredEventIds"]);
        } else {
            updateUrls(false);
        }
        // $('#graphButtonHtmlId').on('click', function(){updateUrls(true)});
        // $('#show-button').on('click', function(){updateUrls(true)});
    };

    var getOldParameter = function () {
        var urlParameter = OpenSpeedMonitor.ChartModules.UrlHandling.UrlHelper.getUrlParameter();
        oldParameter["selectedFolder"] = urlParameter["selectedFolder"];
        oldParameter["selectedBrowsers"] = urlParameter["selectedBrowsers"];
        oldParameter["selectedAllBrowsers"] = urlParameter["selectedAllBrowsers"];
        oldParameter["selectedAllLocations"] = urlParameter["selectedAllLocations"];
        oldParameter["selectedConnectivities"] = urlParameter["selectedConnectivities"];
        oldParameter["selectedAllConnectivityProfiles"] = urlParameter["selectedAllConnectivityProfiles"];
        oldParameter["selectedPages"] = urlParameter["selectedPages"];
        oldParameter["selectedMeasuredEventIds"] = urlParameter["selectedMeasuredEventIds"];
        oldParameter["selectedInterval"] = urlParameter["selectedInterval"];
        oldParameter["selectedTimeFrameInterval"] = urlParameter["selectedTimeFrameInterval"];
        oldParameter["setFromHour"] = urlParameter["setFromHour"];
        oldParameter["setToHour"] = urlParameter["setToHour"];
        oldParameter["from"] = urlParameter["from"];
        oldParameter["fromHour"] = decodeURIComponent(urlParameter["fromHour"]);
        oldParameter["to"] = urlParameter["to"];
        oldParameter["toHour"] = decodeURIComponent(urlParameter["toHour"]);
        return oldParameter;
    };

    var fetchPages = function (measuredEvents) {
        $.ajax({
            url: OpenSpeedMonitor.urls.getPagesForMeasuredEvents,
            data: {"measuredEventList": measuredEvents},
            success: function (data) {
                oldParameter["selectedPages"] = JSON.parse(data);
                $("#pageSelectHtmlId").val(oldParameter["selectedPages"]);
                updateUrls(false);
            },
            traditional: true
        });
    };

    init();

    return {
        getJobGroup: getJobGroup,
        getPage: getPage,
        getTimeFrame: getTimeFrame,
        updateUrls: updateUrls
    };
})();<commit_msg>[IT-1651] Don't show aggregated data when switching to time series chart fom another one<commit_after>//= require /urlHandling/urlHelper.js

"use strict";

var OpenSpeedMonitor = OpenSpeedMonitor || {};
OpenSpeedMonitor.ChartModules = OpenSpeedMonitor.ChartModules || {};
OpenSpeedMonitor.ChartModules.UrlHandling = OpenSpeedMonitor.ChartModules.UrlHandling || {};

OpenSpeedMonitor.ChartModules.UrlHandling.ChartSwitch = (function () {

    var oldParameter = {};

    var getJobGroup = function (map) {
        var folder = null;
        if ($("#pageComparisonSelectionCard").length) {
            folder = OpenSpeedMonitor.PageComparisonSelection.getJobGroups();
        } else {
            folder = $("#folderSelectHtmlId").val();
        }
        if (folder != null) map["selectedFolder"] = folder
    };

    var getBrowser = function (map) {
        var browserSelect = $("#selectedBrowsersHtmlId");
        if (browserSelect != null) {
            var selectedBrowser = browserSelect.val();
            if (selectedBrowser != null) map["selectedBrowsers"] = selectedBrowser;
            var selectedAllBrosers = $("#selectedAllBrowsers").prop("checked");
            if (selectedAllBrosers != null) map["selectedAllBrowsers"] = selectedAllBrosers;
        }
    };

    var getLocation = function (map) {
        var selectedLocations = $("#selectedLocationsHtmlId_chosen");
        if (selectedLocations != null) {
            var selectedAllLocations = $("#selectedAllLocations").prop("checked");
            if (selectedAllLocations) map["selectedAllLocations"] = selectedAllLocations;
        }
    };

    var getConnectivity = function (map) {
        var selectedConnectivities = $("#selectedConnectivityProfilesHtmlId");
        if (selectedConnectivities != null) {
            var connectivities = selectedConnectivities.val();
            if (connectivities != null) map["selectedConnectivities"] = connectivities;
            var allConnectivies = $("#selectedAllConnectivityProfiles").prop("checked");
            if (allConnectivies) map["selectedAllConnectivityProfiles"] = allConnectivies;
        }
    };

    var getPage = function (map) {
        var pages = null;
        if($("#pageComparisonSelectionCard").length) {
            pages = OpenSpeedMonitor.PageComparisonSelection.getPages();
        }else {
         pages = $("#pageSelectHtmlId").val();
        }
        if (pages) map["selectedPages"] = pages;
    };

    var getStep = function (map) {
        var selectedSteps = $("#selectedMeasuredEventsHtmlId");
        if (selectedSteps != null) {
            var values = selectedSteps.val();
            if (values) map["selectedMeasuredEventIds"] = values
        }
    };

    var getTimeFrame = function (map) {
        map["setFromHour"] = ($('#setFromHour:checked').length > 0) ? "on" : "";
        map["setToHour"] = ($('#setToHour:checked').length > 0) ? "on" : "";
        map["from"] = $("#fromDatepicker").val();
        map["fromHour"] = $("#startDateTimePicker").find(".input-group.bootstrap-timepicker.time-control").find(".form-control").val();
        map["to"] = $("#toDatepicker").val();
        map["toHour"] = $("#endDateTimePicker").find(".input-group.bootstrap-timepicker.time-control").find(".form-control").val();
    };

    var updateUrls = function (withCurrentSelection) {
        var updatedMap = $.extend({}, oldParameter);
        if (withCurrentSelection) {
            getTimeFrame(updatedMap);
            getJobGroup(updatedMap);
            getPage(updatedMap);
            getBrowser(updatedMap);
            getLocation(updatedMap);
            getConnectivity(updatedMap);
            getStep(updatedMap);
        }
        if (updatedMap["selectedFolder"] == null) {
            updatedMap = {};
        } else {
            if (updatedMap["selectedInterval"] == null) updatedMap["selectedInterval"] = -1;
            if (updatedMap["selectedTimeFrameInterval"] == null) updatedMap["selectedTimeFrameInterval"] = 0;
            if (updatedMap["selectedAggrGroupValuesUnCached"] == null) updatedMap["selectedAggrGroupValuesUnCached"] = "docCompleteTimeInMillisecsUncached";
        }
        var params = $.param(updatedMap, true);
        var showLinks = false;
        if (params.length > 0) {
            showLinks = true;
        }
        updateUrl("#timeSeriesWithDataLink", OpenSpeedMonitor.urls.eventResultDashboardShowAll + "?" + params, showLinks);
        updateUrl("#pageAggregationWithDataLink", OpenSpeedMonitor.urls.pageAggregationShow + "?" + params, showLinks);
        updateUrl("#jobGroupAggregationWithDataLink", OpenSpeedMonitor.urls.jobGroupAggregationShow + "?" + params, showLinks);
        updateUrl("#distributionWithDataLink", OpenSpeedMonitor.urls.distributionChartShow + "?" + params, showLinks);
        updateUrl("#detailAnalysisWithDataLink", OpenSpeedMonitor.urls.detailAnalysisShow + "?" + params, showLinks);
        updateUrl("#resultListWithDataLink", OpenSpeedMonitor.urls.tabularResultPresentation + "?" + params, showLinks);
        updateUrl("#pageComparisonWithDataLink", OpenSpeedMonitor.urls.pageComparisonShow + "?" + params, showLinks)
    };

    var updateUrl = function (selector, newUrl, showLink) {
        if (!showLink) {
            $(selector).addClass("hidden");
        } else {
            $(selector).attr("href", newUrl);
            $(selector).removeClass("hidden");
        }
    };

    var init = function () {
        var oldParameter = getOldParameter();

        if (oldParameter["selectedPages"] == null && oldParameter["selectedMeasuredEventIds"] != null) {
            fetchPages(oldParameter["selectedMeasuredEventIds"]);
        } else {
            updateUrls(false);
        }
        // $('#graphButtonHtmlId').on('click', function(){updateUrls(true)});
        // $('#show-button').on('click', function(){updateUrls(true)});
    };

    var getOldParameter = function () {
        var urlParameter = OpenSpeedMonitor.ChartModules.UrlHandling.UrlHelper.getUrlParameter();
        oldParameter["selectedFolder"] = urlParameter["selectedFolder"];
        oldParameter["selectedBrowsers"] = urlParameter["selectedBrowsers"];
        oldParameter["selectedAllBrowsers"] = urlParameter["selectedAllBrowsers"];
        oldParameter["selectedAllLocations"] = urlParameter["selectedAllLocations"];
        oldParameter["selectedConnectivities"] = urlParameter["selectedConnectivities"];
        oldParameter["selectedAllConnectivityProfiles"] = urlParameter["selectedAllConnectivityProfiles"];
        oldParameter["selectedPages"] = urlParameter["selectedPages"];
        oldParameter["selectedMeasuredEventIds"] = urlParameter["selectedMeasuredEventIds"];
        oldParameter["selectedInterval"] = urlParameter["selectedInterval"];
        oldParameter["selectedTimeFrameInterval"] = urlParameter["selectedTimeFrameInterval"];
        oldParameter["setFromHour"] = urlParameter["setFromHour"];
        oldParameter["setToHour"] = urlParameter["setToHour"];
        oldParameter["from"] = urlParameter["from"];
        oldParameter["fromHour"] = decodeURIComponent(urlParameter["fromHour"]);
        oldParameter["to"] = urlParameter["to"];
        oldParameter["toHour"] = decodeURIComponent(urlParameter["toHour"]);
        return oldParameter;
    };

    var fetchPages = function (measuredEvents) {
        $.ajax({
            url: OpenSpeedMonitor.urls.getPagesForMeasuredEvents,
            data: {"measuredEventList": measuredEvents},
            success: function (data) {
                oldParameter["selectedPages"] = JSON.parse(data);
                $("#pageSelectHtmlId").val(oldParameter["selectedPages"]);
                updateUrls(false);
            },
            traditional: true
        });
    };

    init();

    return {
        getJobGroup: getJobGroup,
        getPage: getPage,
        getTimeFrame: getTimeFrame,
        updateUrls: updateUrls
    };
})();<|endoftext|>


<commit_before>'use strict';

let fs = require('fs');
let del = require('del');
let path = require('path');
let fse = require('fs-extra');
let colors = require('colors');
let shell = require('shelljs');
let generator = require('yeoman-generator');

let log = console.log;

/**
 * [Task List]
 */
let task = {
    overwrite_src : true,
    copy_rest_files : false,
    overwrite_webpack : true,
    copy_package_json : true,
    install_node_modules : true,
    overwrite_package_json_dev_dependencies : false,
};

let basicPath = process.cwd();
let templatePath = path.join(__dirname, 'templates');
let packageJson = fse.readJsonSync(path.join(templatePath, 'package.json'), { throws : false });

module.exports = generator.Base.extend({
    /**
     * [Prompting Stage] Inquire questions, include the project name, version and description.
     */
    prompting () {
        if (fs.existsSync(path.join(basicPath, 'package.json'))) {
            log('> package.json', '√'.green);
            task.copy_package_json = false;
        }
        if (fs.existsSync(path.join(basicPath, 'src'))) {
            log('> src', '√'.green);
            task.overwrite_src = false;
        }
        if (fs.existsSync(path.join(basicPath, 'webpack'))) {
            log('> webpack', '√'.green);
            task.overwrite_webpack = false;
        }
        if (fs.existsSync(path.join(basicPath, 'node_modules'))) {
            log('> node_modules', '√'.green);
            task.install_node_modules = false;
        }
        let done = this.async();
        let timestamp = +new Date();
        let questions = [];
        if (task.copy_package_json) {
            questions.push({
                name : 'name',
                message : 'Name',
                default : path.basename(basicPath) || 'Project',
            });
            questions.push({
                name : 'version',
                message : 'Version',
                default : '0.0.1',
            });
            questions.push({
                name : 'description',
                message : 'Description',
                default : 'none',
            });
        } else {
            questions.push({
                type : 'confirm',
                name : 'overwrite_package_json_dev_dependencies',
                message : 'Whether to overwrite [package.json]',
                default : false,
            });
        }
        if (!task.overwrite_src) {
            questions.push({
                type : 'confirm',
                name : 'overwrite_src',
                message : 'Whether to overwrite [src]',
                default : false,
            });
        }
        if (!task.overwrite_webpack) {
            questions.push({
                type : 'confirm',
                name : 'overwrite_webpack',
                message : 'Whether to overwrite [webpack]',
                default : true,
            });
        }
        questions.push({
            type : 'confirm',
            name : 'copy_rest_files',
            message : 'Whether to copy [rest files]',
            default : false,
        });
        this.prompt(questions).then(( answers ) => {
            if (task.copy_package_json) {
                packageJson.name = answers.name;
                packageJson.version = answers.version;
                packageJson.description = answers.description;
            } else {
                task.overwrite_package_json_dev_dependencies = answers.overwrite_package_json_dev_dependencies;
            }
            task.overwrite_src = task.overwrite_src || answers.overwrite_src;
            task.overwrite_webpack = task.overwrite_webpack || answers.overwrite_webpack;
            task.copy_rest_files = answers.copy_rest_files;
            done();
        });
    },
    /**
     * [Writing Stage] Copy file.
     */
    writing () {
        if (task.overwrite_package_json_dev_dependencies) {
            let projectPackageJson = fse.readJsonSync(path.join(basicPath, 'package.json'), { throws : false });
            let devDependencies = projectPackageJson.devDependencies || {};
            for (let pack in packageJson.devDependencies) {
                devDependencies[pack] = packageJson.devDependencies[pack];
            }
            projectPackageJson.devDependencies = {};
            Object.keys(devDependencies).sort(( packA, packB ) => {
                return packA > packB ? 1 : -1;
            }).forEach(( pack ) => {
                projectPackageJson.devDependencies[pack] = devDependencies[pack];
            });
            packageJson = projectPackageJson;
        }
        if (task.copy_package_json || task.overwrite_package_json_dev_dependencies) {
            fse.writeJsonSync('package.json', packageJson);
        }
        if (task.copy_rest_files) {
            fs.readdirSync(templatePath).forEach(( filename ) => {
                let stats = fs.statSync(path.join(templatePath, filename));
                if (stats.isFile()) {
                    if (filename == 'package.json') {
                        return;
                    }
                    if (filename == '.DS_Store') {
                        return;
                    }
                    del(filename);
                    this.template(filename, filename, {
                        name : packageJson.name,
                        year : new Date().getFullYear(),
                    });
                }
                if (stats.isDirectory()) {
                    if (filename == 'src') {
                        return;
                    }
                    if (filename == 'webpack') {
                        return;
                    }
                    if (filename == 'node_modules') {
                        return;
                    }
                    del(filename);
                    this.directory(filename, filename);
                }
            });
        }
        if (task.overwrite_src) {
            del('src/*');
            this.directory('src', 'src');
        }
        if (task.overwrite_webpack) {
            del('webpack/*');
            this.directory('webpack', 'webpack');
        }
    },
    /**
     * [Install Stage] Install node_modules and you can use Ctrl+C to leave.
     */
    install () {
        if (task.copy_package_json) {
            del(['src/**/.gitignore','src/**/.npmignore']);
        }
        if (task.install_node_modules) {
            let choices = [
                'Link to the shared node_modules',
                'Install here',
            ];
            this.prompt([
                {
                    type : 'list',
                    name : 'install_node_modules',
                    message : 'Link to shared node_modules or Install node_modules here?',
                    choices,
                },
            ]).then(( answers ) => {
                if (answers.install_node_modules == choices[0]) {
                    // shell.exec(`ln -s ${ path.join(__dirname, './templates/node_modules') } node_modules`);
                    fs.symlinkSync(path.join(__dirname, './templates/node_modules'), 'node_modules');
                    log('> 初始化已完成');
                    process.exit(1);
                } else {
                    this.installDependencies({
                        npm : true,
                        bower : false,
                        skipInstall : false,
                        callback () {
                            log('> 初始化已完成');
                            process.exit(1);
                        }
                    });
                }
            });
        } else {
            log('> 初始化已完成');
            process.exit(1);
        }
    },
});
<commit_msg>update<commit_after>'use strict';

let fs = require('fs');
let del = require('del');
let path = require('path');
let fse = require('fs-extra');
let colors = require('colors');
let shell = require('shelljs');
let generator = require('yeoman-generator');

let log = console.log;

/**
 * [Task List]
 */
let task = {
    overwrite_src : true,
    copy_rest_files : false,
    overwrite_webpack : true,
    copy_package_json : true,
    install_node_modules : true,
    overwrite_package_json_dev_dependencies : false,
};

let basicPath = process.cwd();
let templatePath = path.join(__dirname, 'templates');
let packageJson = fse.readJsonSync(path.join(templatePath, 'package.json'), { throws : false });

module.exports = generator.Base.extend({
    /**
     * [Prompting Stage] Inquire questions, include the project name, version and description.
     */
    prompting () {
        if (fs.existsSync(path.join(basicPath, 'package.json'))) {
            log('> package.json', '√'.green);
            task.copy_package_json = false;
        }
        if (fs.existsSync(path.join(basicPath, 'src'))) {
            log('> src', '√'.green);
            task.overwrite_src = false;
        }
        if (fs.existsSync(path.join(basicPath, 'webpack'))) {
            log('> webpack', '√'.green);
            task.overwrite_webpack = false;
        }
        if (fs.existsSync(path.join(basicPath, 'node_modules'))) {
            log('> node_modules', '√'.green);
            task.install_node_modules = false;
        }
        let done = this.async();
        let timestamp = +new Date();
        let questions = [];
        if (task.copy_package_json) {
            questions.push({
                name : 'name',
                message : 'Name',
                default : path.basename(basicPath) || 'Project',
            });
            questions.push({
                name : 'version',
                message : 'Version',
                default : '0.0.1',
            });
            questions.push({
                name : 'description',
                message : 'Description',
                default : 'none',
            });
        } else {
            questions.push({
                type : 'confirm',
                name : 'overwrite_package_json_dev_dependencies',
                message : 'Whether to overwrite [package.json]',
                default : false,
            });
        }
        if (!task.overwrite_src) {
            questions.push({
                type : 'confirm',
                name : 'overwrite_src',
                message : 'Whether to overwrite [src]',
                default : false,
            });
        }
        if (!task.overwrite_webpack) {
            questions.push({
                type : 'confirm',
                name : 'overwrite_webpack',
                message : 'Whether to overwrite [webpack]',
                default : true,
            });
        }
        questions.push({
            type : 'confirm',
            name : 'copy_rest_files',
            message : 'Whether to copy [rest files]',
            default : false,
        });
        this.prompt(questions).then(( answers ) => {
            if (task.copy_package_json) {
                packageJson.name = answers.name;
                packageJson.version = answers.version;
                packageJson.description = answers.description;
            } else {
                task.overwrite_package_json_dev_dependencies = answers.overwrite_package_json_dev_dependencies;
            }
            task.overwrite_src = task.overwrite_src || answers.overwrite_src;
            task.overwrite_webpack = task.overwrite_webpack || answers.overwrite_webpack;
            task.copy_rest_files = answers.copy_rest_files;
            done();
        });
    },
    /**
     * [Writing Stage] Copy file.
     */
    writing () {
        if (task.overwrite_package_json_dev_dependencies) {
            let projectPackageJson = fse.readJsonSync(path.join(basicPath, 'package.json'), { throws : false });
            let devDependencies = projectPackageJson.devDependencies || {};
            for (let pack in packageJson.devDependencies) {
                devDependencies[pack] = packageJson.devDependencies[pack];
            }
            projectPackageJson.devDependencies = {};
            Object.keys(devDependencies).sort(( packA, packB ) => {
                return packA > packB ? 1 : -1;
            }).forEach(( pack ) => {
                projectPackageJson.devDependencies[pack] = devDependencies[pack];
            });
            packageJson = projectPackageJson;
        }
        if (task.copy_package_json || task.overwrite_package_json_dev_dependencies) {
            fse.writeJsonSync('package.json', packageJson);
        }
        if (task.copy_rest_files) {
            fs.readdirSync(templatePath).forEach(( filename ) => {
                let stats = fs.statSync(path.join(templatePath, filename));
                if (stats.isFile()) {
                    if (filename == 'package.json') {
                        return;
                    }
                    if (filename == '.DS_Store') {
                        return;
                    }
                    del(filename);
                    this.template(filename, filename, {
                        name : packageJson.name,
                        year : new Date().getFullYear(),
                    });
                }
                if (stats.isDirectory()) {
                    if (filename == 'src') {
                        return;
                    }
                    if (filename == 'webpack') {
                        return;
                    }
                    if (filename == 'node_modules') {
                        return;
                    }
                    del(filename);
                    this.directory(filename, filename);
                }
            });
        }
        if (task.overwrite_src) {
            del('src/*');
            this.directory('src', 'src');
        }
        if (task.overwrite_webpack) {
            del('webpack/*');
            this.directory('webpack', 'webpack');
        }
    },
    /**
     * [Install Stage] Install node_modules and you can use Ctrl+C to leave.
     */
    install () {
        if (task.overwrite_src) {
            del(['src/**/.gitignore','src/**/.npmignore']);
        }
        if (task.install_node_modules) {
            let choices = [
                'Link to the shared node_modules',
                'Install here',
            ];
            this.prompt([
                {
                    type : 'list',
                    name : 'install_node_modules',
                    message : 'Link to shared node_modules or Install node_modules here?',
                    choices,
                },
            ]).then(( answers ) => {
                if (answers.install_node_modules == choices[0]) {
                    // shell.exec(`ln -s ${ path.join(__dirname, './templates/node_modules') } node_modules`);
                    fs.symlinkSync(path.join(__dirname, './templates/node_modules'), 'node_modules');
                    log('> 初始化已完成');
                    process.exit(1);
                } else {
                    this.installDependencies({
                        npm : true,
                        bower : false,
                        skipInstall : false,
                        callback () {
                            log('> 初始化已完成');
                            process.exit(1);
                        }
                    });
                }
            });
        } else {
            log('> 初始化已完成');
            process.exit(1);
        }
    },
});
<|endoftext|>