<commit_before>/**
	_moon.ExpandableListItem_, which extends [moon.Item](#moon.Item), displays a
	header while also allowing additional content to be stored in an
	[enyo.Drawer](#enyo.Drawer). When the header is selected, the drawer opens
	below. To close the drawer, tap on the header text or navigate (via 5-way)
	back to the top of the drawer.

	The control's child components may be of any kind; by default, they are
	instances of _moon.Item_.

		{kind: "moon.ExpandableListItem", content: "A Countries", components: [
			{content: "Algeria"},
			{content: "Argentina"},
			{content: "Australia"}
		]},
		{kind: "moon.ExpandableListItem", content: "B Countries", components: [
			{content: "Belgium"},
			{content: "Bolivia"},
			{content: "Brazil"}
		]}

	When multiple ExpandableListItems are used in a group, only one may be open at a given
	time.

		{kind: "enyo.Group", highlander: true, components: [
			{kind: "moon.ExpandableListItem",  active: true,
				content: "This is a grouped ExpandableListItem", components: [
					{content: "Item One"},
					{content: "Item Two"}
				]
			},
			{kind: "moon.ExpandableListItem",
				content: "This is another grouped ExpandableListItem", components: [
					{content: "Item Three"},
					{content: "Item Four"}
				]
			},
			{kind: "moon.ExpandableListItem",
				content: "This is yet another grouped ExpandableListItem", components: [
					{content: "Item Five"},
					{content: "Item Six"}
				]
			}
		]}
*/
enyo.kind({
	name: "moon.ExpandableListItem",
	//* @public
	published: {
		/**
			If true, the drawer automatically closes when the user navigates to the
			top of the control. If false (the default), the user must select/tap the
			header to close the drawer.
		*/
		autoCollapse: false,
		/**
			If true, the drawer is expanded, showing this item's contents. Use this property
			(rather than _active_) to set the item's initial state.
		*/
		open: false,
		/**
			_active_ is a notification to container that it is currently selected, focused or manupulated control.
			True if the item is currently selected, false it the item is not selected.
			It is prepared to support grouping. When multiple pickers which use moon.ExpandableListItem
			are grouped	(inside of _enyo.Group_), only one pickers can be expanded.
		*/
		active: false,
		//* If true, the user is prevented from spotting off the bottom of the drawer (when open) using five-way controls
		lockBottom: false,
		//* When true, item is shown as disabled and does not generate tap events
		disabled: false
	},
	//* @protected
	classes: "moon-expandable-list-item",
	spotlight: false,
	defaultKind: "moon.Item",
	handlers: {
		onSpotlightDown: "spotlightDown",
		onDrawerAnimationEnd: "drawerAnimationEnd"
	},
	components: [
		{name: "header", kind: "moon.Item", onSpotlightFocus: "headerFocus", ontap: "expandContract", classes: "moon-expandable-list-item-header"},
		{name: "drawer", kind: "enyo.Drawer", classes: "moon-expandable-list-item-client", components: [
			{name: "client", kind: "Group", tag: null}
		]}
	],
	bindings: [
		{from: ".disabled", to: ".$.header.disabled"}
	],
	//* @protected
	create: function() {
		this.inherited(arguments);
		this.openChanged();
		this.setActive(this.open);
		this.disabledChanged();
	},
	//* Facade for header content
	contentChanged: function() {
		this.$.header.setContent(this.getContent());
	},
	//* Facade for drawer
	openChanged: function() {
		var open = this.getOpen();
		this.addRemoveClass("open", open);
		this.$.drawer.setOpen(open);
		if (this.generated) {
			this.stopHeaderMarquee();
		}
	},
	disabledChanged: function() {
		var disabled = this.getDisabled();

		this.addRemoveClass("disabled", disabled);
		if (disabled) {
			this.setOpen(false);
		}
	},
	activeChanged: function() {
		this.bubble("onActivate", {allowHighlanderDeactivate:true});
		this.setOpen(this.active);
	},
	//* If closed, opens drawer and highlights first spottable child.
	expandContract: function(inSender, inEvent) {
		if (this.disabled) {
			return true;
		}

		this.toggleActive();

		if (this.getActive() && !enyo.Spotlight.getPointerMode()) {
			enyo.Spotlight.spot(enyo.Spotlight.getFirstChild(this.$.drawer));
		}
	},
	stopHeaderMarquee: function() {
		this.$.header.stopMarquee();
	},
	toggleActive: function() {
		if (this.getOpen()) {
			this.setActive(false);
		} else {
			this.setActive(true);
		}
	},
	//* If drawer is currently open, and event was sent via keypress (i.e., it has a direction), process header focus
	headerFocus: function(inSender, inEvent) {
		var direction = inEvent && inEvent.dir;

		if (this.getOpen() && this.getAutoCollapse() && direction === "UP") {
			this.setActive(false);
		}

		if (inEvent.originator === this.$.header) {
			this.bubble("onRequestScrollIntoView", {side: "top"});
		}
	},
	//* Check for the last item in the client area, and prevent 5-way focus movement below it, per UX specs
	spotlightDown: function(inSender, inEvent) {
		var children = enyo.Spotlight.getChildren(this.$.client);
		if (this.getLockBottom() && this.getOpen() && children.length && inEvent.originator == children[children.length - 1]) {
			return true;
		}
	},
	drawerAnimationEnd: function() {
		this.bubble("onRequestScrollIntoView", {side: "top", scrollInPointerMode:true});
		return true;
	}
});
<commit_msg>GF-43742: Edited API comments. DCO-1.1-Signed-Off-By: Kevin Schaaf <kevin.schaaf@lge.com><commit_after>/**
	_moon.ExpandableListItem_, which extends [moon.Item](#moon.Item), displays a
	header while also allowing additional content to be stored in an
	[enyo.Drawer](#enyo.Drawer). When the header is selected, the drawer opens
	below. To close the drawer, tap on the header text or navigate (via 5-way)
	back to the top of the drawer.

	The control's child components may be of any kind; by default, they are
	instances of _moon.Item_.

		{kind: "moon.ExpandableListItem", content: "A Countries", components: [
			{content: "Algeria"},
			{content: "Argentina"},
			{content: "Australia"}
		]},
		{kind: "moon.ExpandableListItem", content: "B Countries", components: [
			{content: "Belgium"},
			{content: "Bolivia"},
			{content: "Brazil"}
		]}

	When multiple ExpandableListItems are used in a group, only one may be open at a given
	time.

		{kind: "enyo.Group", highlander: true, components: [
			{kind: "moon.ExpandableListItem",  active: true,
				content: "This is a grouped ExpandableListItem", components: [
					{content: "Item One"},
					{content: "Item Two"}
				]
			},
			{kind: "moon.ExpandableListItem",
				content: "This is another grouped ExpandableListItem", components: [
					{content: "Item Three"},
					{content: "Item Four"}
				]
			},
			{kind: "moon.ExpandableListItem",
				content: "This is yet another grouped ExpandableListItem", components: [
					{content: "Item Five"},
					{content: "Item Six"}
				]
			}
		]}
*/
enyo.kind({
	name: "moon.ExpandableListItem",
	//* @public
	published: {
		/**
			If true, the drawer automatically closes when the user navigates to the
			top of the control. If false (the default), the user must select/tap the
			header to close the drawer.
		*/
		autoCollapse: false,
		/**
			If true, the drawer is expanded, showing this item's contents. Use this property
			(rather than _active_) to set the item's initial state.
		*/
		open: false,
		/**
			The _active_ reflects the value of the open property, and is used to support the _enyo.Group_
			API for grouping a set of ExpandableListItems where only one is expanded at a time.
			Note, the _open_ property will control the initial state of the picker, not this property.
		*/
		active: false,
		//* If true, the user is prevented from spotting off the bottom of the drawer (when open) using five-way controls
		lockBottom: false,
		//* When true, item is shown as disabled and does not generate tap events
		disabled: false
	},
	//* @protected
	classes: "moon-expandable-list-item",
	spotlight: false,
	defaultKind: "moon.Item",
	handlers: {
		onSpotlightDown: "spotlightDown",
		onDrawerAnimationEnd: "drawerAnimationEnd"
	},
	components: [
		{name: "header", kind: "moon.Item", onSpotlightFocus: "headerFocus", ontap: "expandContract", classes: "moon-expandable-list-item-header"},
		{name: "drawer", kind: "enyo.Drawer", classes: "moon-expandable-list-item-client", components: [
			{name: "client", kind: "Group", tag: null}
		]}
	],
	bindings: [
		{from: ".disabled", to: ".$.header.disabled"}
	],
	//* @protected
	create: function() {
		this.inherited(arguments);
		this.openChanged();
		this.setActive(this.open);
		this.disabledChanged();
	},
	//* Facade for header content
	contentChanged: function() {
		this.$.header.setContent(this.getContent());
	},
	//* Facade for drawer
	openChanged: function() {
		var open = this.getOpen();
		this.addRemoveClass("open", open);
		this.$.drawer.setOpen(open);
		if (this.generated) {
			this.stopHeaderMarquee();
		}
	},
	disabledChanged: function() {
		var disabled = this.getDisabled();

		this.addRemoveClass("disabled", disabled);
		if (disabled) {
			this.setOpen(false);
		}
	},
	activeChanged: function() {
		this.bubble("onActivate", {allowHighlanderDeactivate:true});
		this.setOpen(this.active);
	},
	//* If closed, opens drawer and highlights first spottable child.
	expandContract: function(inSender, inEvent) {
		if (this.disabled) {
			return true;
		}

		this.toggleActive();

		if (this.getActive() && !enyo.Spotlight.getPointerMode()) {
			enyo.Spotlight.spot(enyo.Spotlight.getFirstChild(this.$.drawer));
		}
	},
	stopHeaderMarquee: function() {
		this.$.header.stopMarquee();
	},
	toggleActive: function() {
		if (this.getOpen()) {
			this.setActive(false);
		} else {
			this.setActive(true);
		}
	},
	//* If drawer is currently open, and event was sent via keypress (i.e., it has a direction), process header focus
	headerFocus: function(inSender, inEvent) {
		var direction = inEvent && inEvent.dir;

		if (this.getOpen() && this.getAutoCollapse() && direction === "UP") {
			this.setActive(false);
		}

		if (inEvent.originator === this.$.header) {
			this.bubble("onRequestScrollIntoView", {side: "top"});
		}
	},
	//* Check for the last item in the client area, and prevent 5-way focus movement below it, per UX specs
	spotlightDown: function(inSender, inEvent) {
		var children = enyo.Spotlight.getChildren(this.$.client);
		if (this.getLockBottom() && this.getOpen() && children.length && inEvent.originator == children[children.length - 1]) {
			return true;
		}
	},
	drawerAnimationEnd: function() {
		this.bubble("onRequestScrollIntoView", {side: "top", scrollInPointerMode:true});
		return true;
	}
});
<|endoftext|>


<commit_before>/**
 * @module reference
 */

'use strict';

var client = require('../client');

module.exports = {
  /**
   * Gets required beneficiary details and their basic validation formats.
   * @param {Object} params Parameters object
   * @return {Promise}      Promise; if fulfilled returns object, which contains required fields of a beneficiary object and their format; if rejected returns APIerror.
   */
  getBeneficiaryRequiredDetails: function (params) {
    var url = '/v2/reference/beneficiary_required_details';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets dates for which the given currency pair can not be traded.
   * @param {Object} params                Parameters object
   * @param {String} params.conversionPair Currency conversion pair, required
   * @return {Promise}                     Promise; if fulfilled returns object, which contains invalid conversion dates as well as first and default date; if rejected returns APIerror.
   */
  getConversionDates: function (params) {
    params = params || {};
    if (!params.hasOwnProperty('conversionPair')) {
      throw new Error('conversionPair is required');
    }

    var url = '/v2/reference/conversion_dates';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets a list of all the currencies that are tradeable.
   * @return {Promise} Promise; if fulfilled returns object, which contains array of currencies; if rejected returns APIerror.
   */
  getAvailableCurrencies: function () {
    var url = '/v2/reference/currencies';

    var promise = client.request({
      url: url,
      method: 'GET'
    });

    return promise;
  },

  /**
   * Gets dates for which the given currency can not be paid.
   * @param {Object} params          Parameters object
   * @param {String} params.currency Currency, required
   * @return {Promise}               Promise; if fulfilled returns object, which contains invalid payment dates as well as first date; if rejected returns APIerror.
   */
  getPaymentDates: function (params) {
    params = params || {};
    if (!params.hasOwnProperty('currency')) {
      throw new Error('currency is required');
    }

    var url = '/v2/reference/payment_dates';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets settlement account information, detailing where funds need to be sent to.
   * @param {Object} params Parameters object
   * @return {Promise}      Promise; if fulfilled returns array of settlement accounts; if rejected returns APIerror.
   */
  getSettlementAccounts: function (params) {
    var url = '/v2/reference/settlement_accounts';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets dates for which the given currency pair can not be traded.
   * @param {Object} params                Parameters object
   * @param {String} params.payerCountry   Currency conversion pair, required
   * @return {Promise}                     Promise; if fulfilled returns object, which contains invalid conversion dates as well as first and default date; if rejected returns APIerror.
   */
  getPayerRequiredDetails: function (params) {
    params = params || {};
    if (!params.hasOwnProperty('payerCountry')) {
      throw new Error('payerCountry is required');
    }

    var url = '/v2/reference/payer_required_details';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets valid purpose codes for a given currency.
   * @param {Object} params                Parameters object
   * @param {String} params.currency       Currency for the payment to be created, required
   * @return {Promise}                     Promise; if fulfilled returns object, which contains valid purpose codes; if rejected returns APIerror.
   */
  getPaymentPurposeCodes: function (params) {
    params = params || {};
    if (!params.hasOwnProperty('currency')) {
      throw new Error('currency is required');
    }

    var url = '/v2/reference/payment_purpose_codes';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets details of the bank for a given identifier.
   * @param {Object} params                Parameters object
   * @param {String} params.identifierType Type of the identifier, required
   * @param {String} params.identifierValue Value of the identifier, required
   * @return {Promise}                     Promise; if fulfilled returns object, which contains valid purpose codes; if rejected returns APIerror.
   */
  getBankDetails: function (params) {
    params = params || {};
    if (!params.hasOwnProperty('identifierType')) {
      throw new Error('identifierType is required');
    }
    if (!params.hasOwnProperty('identifierValue')) {
      throw new Error('identifierValue is required');
    }

    var url = '/v2/reference/bank_details';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  }
};
<commit_msg>Updates bank details description<commit_after>/**
 * @module reference
 */

'use strict';

var client = require('../client');

module.exports = {
  /**
   * Gets required beneficiary details and their basic validation formats.
   * @param {Object} params Parameters object
   * @return {Promise}      Promise; if fulfilled returns object, which contains required fields of a beneficiary object and their format; if rejected returns APIerror.
   */
  getBeneficiaryRequiredDetails: function (params) {
    var url = '/v2/reference/beneficiary_required_details';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets dates for which the given currency pair can not be traded.
   * @param {Object} params                Parameters object
   * @param {String} params.conversionPair Currency conversion pair, required
   * @return {Promise}                     Promise; if fulfilled returns object, which contains invalid conversion dates as well as first and default date; if rejected returns APIerror.
   */
  getConversionDates: function (params) {
    params = params || {};
    if (!params.hasOwnProperty('conversionPair')) {
      throw new Error('conversionPair is required');
    }

    var url = '/v2/reference/conversion_dates';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets a list of all the currencies that are tradeable.
   * @return {Promise} Promise; if fulfilled returns object, which contains array of currencies; if rejected returns APIerror.
   */
  getAvailableCurrencies: function () {
    var url = '/v2/reference/currencies';

    var promise = client.request({
      url: url,
      method: 'GET'
    });

    return promise;
  },

  /**
   * Gets dates for which the given currency can not be paid.
   * @param {Object} params          Parameters object
   * @param {String} params.currency Currency, required
   * @return {Promise}               Promise; if fulfilled returns object, which contains invalid payment dates as well as first date; if rejected returns APIerror.
   */
  getPaymentDates: function (params) {
    params = params || {};
    if (!params.hasOwnProperty('currency')) {
      throw new Error('currency is required');
    }

    var url = '/v2/reference/payment_dates';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets settlement account information, detailing where funds need to be sent to.
   * @param {Object} params Parameters object
   * @return {Promise}      Promise; if fulfilled returns array of settlement accounts; if rejected returns APIerror.
   */
  getSettlementAccounts: function (params) {
    var url = '/v2/reference/settlement_accounts';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets dates for which the given currency pair can not be traded.
   * @param {Object} params                Parameters object
   * @param {String} params.payerCountry   Currency conversion pair, required
   * @return {Promise}                     Promise; if fulfilled returns object, which contains invalid conversion dates as well as first and default date; if rejected returns APIerror.
   */
  getPayerRequiredDetails: function (params) {
    params = params || {};
    if (!params.hasOwnProperty('payerCountry')) {
      throw new Error('payerCountry is required');
    }

    var url = '/v2/reference/payer_required_details';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets valid purpose codes for a given currency.
   * @param {Object} params                Parameters object
   * @param {String} params.currency       Currency for the payment to be created, required
   * @return {Promise}                     Promise; if fulfilled returns object, which contains valid purpose codes; if rejected returns APIerror.
   */
  getPaymentPurposeCodes: function (params) {
    params = params || {};
    if (!params.hasOwnProperty('currency')) {
      throw new Error('currency is required');
    }

    var url = '/v2/reference/payment_purpose_codes';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  },

  /**
   * Gets details of the bank for a given identifier.
   * @param {Object} params                Parameters object
   * @param {String} params.identifierType Type of the identifier, required
   * @param {String} params.identifierValue Value of the identifier, required
   * @return {Promise}                     Promise; if fulfilled returns object, which contains details of the bank; if rejected returns APIerror.
   */
  getBankDetails: function (params) {
    params = params || {};
    if (!params.hasOwnProperty('identifierType')) {
      throw new Error('identifierType is required');
    }
    if (!params.hasOwnProperty('identifierValue')) {
      throw new Error('identifierValue is required');
    }

    var url = '/v2/reference/bank_details';

    var promise = client.request({
      url: url,
      method: 'GET',
      qs: params
    });

    return promise;
  }
};
<|endoftext|>


<commit_before>require.config({
	baseUrl : '../bower_components',
    //urlArgs: "bust=" + (new Date()).getTime(),
	paths : {
		// configuration base dir
		services : '../javascripts/services',
		controllers : '../javascripts/controllers',
		directives : '../javascripts/directives',

		// module shortcut
		app : '../javascripts/app',
		angular : 'angular/angular',
		angularBootstrap : 'angular-bootstrap/ui-bootstrap-tpls',
		angularRoute : 'angular-route/angular-route.min',
		easyAlgoParser : '../javascripts/easyAlgoLanguage/easyAlgoParser',
		easyAlgoRunner : '../javascripts/easyAlgoLanguage/easyAlgoRunner',
		easyAlgoLint : '../javascripts/easyAlgoLanguage/easyAlgoLint',
		easyAlgoFold : '../javascripts/easyAlgoLanguage/easyAlgoFold',
		easyAlgoCloseTag : '../javascripts/easyAlgoLanguage/easyAlgoCloseTag',
		easyAlgoValidator : '../javascripts/easyAlgoLanguage/easyAlgoValidator',
		easyAlgoConfiguration : '../javascripts/easyAlgoLanguage/easyAlgoConfiguration',
		easyAlgoSyntaxHighlighter : '../javascripts/easyAlgoLanguage/easyAlgoSyntaxHighlighter',
		easyAlgoContext : '../javascripts/easyAlgoLanguage/easyAlgoContext',
		easyAlgoRuntimeException : '../javascripts/easyAlgoLanguage/easyAlgoRuntimeException',
		terminalEmulator : '../javascripts/terminalEmulator/vtortola.ng-terminal',
		routes : '../javascripts/routes',
		appDir : '../javascripts/',
		ffFileSystem : 'idb.filesystem.js/src/idb.filesystem.min'
	},
	shim : {
		'angularBootstrap' : {
			deps : [
				'angular'
			],
			exports: 'angular-ui-bootstrap'
		},
		'angular-ui-codemirror/ui-codemirror' : {
			deps : [
				'angular',
				'codemirror/lib/codemirror'
			],
			exports: 'codeMirrorAngular'
		},
		'angularRoute': {
			deps : [
				'angular'
			],
			exports: 'angularRoute'
		},
		'terminalEmulator': {
			deps : [
				'angular'
			],
			exports : 'terminalEmulator'
		},
		'controllers/easyAlgoEditor' : {
			deps : [
				'codemirror/mode/htmlmixed/htmlmixed',
				'codemirror/addon/hint/show-hint',
				'codemirror/addon/lint/lint',
				'codemirror/addon/fold/foldgutter',
                'easyAlgoSyntaxHighlighter',
                'easyAlgoParser',
				'easyAlgoLint',
				'easyAlgoFold',
				'easyAlgoValidator',
				'easyAlgoCloseTag',
				'easyAlgoRunner',
				'services/fileSystem'
			],
			exports : 'controllers/easyAlgoEditor'
		},
		'ng-flow/dist/ng-flow-standalone' : {
			deps : ['angular']
		},
		'tc-angular-chartjs/dist/tc-angular-chartjs' : {
			deps : [
				'Chart.js/Chart.min'
			]
		},
		app : {
			deps: [
				'angular',
				'angularRoute',
				'appDir/services/dependencyResolverFor',
				'routes',
				'angularBootstrap',
				'terminalEmulator',
				'angular-ui-codemirror/ui-codemirror',
				'ng-flow/dist/ng-flow-standalone',
				'tc-angular-chartjs/dist/tc-angular-chartjs'
			],
			exports: 'app'
		}
	}
});

require(['app'], function (app) {
  // create CodeMirror on window for correcte usage of ui.codemirror
  window.CodeMirror = require('codemirror/lib/codemirror');
  app.init();
});<commit_msg>correct tc-angular-chartjs dependencies<commit_after>require.config({
	baseUrl : '../bower_components',
    //urlArgs: "bust=" + (new Date()).getTime(),
	paths : {
		// configuration base dir
		services : '../javascripts/services',
		controllers : '../javascripts/controllers',
		directives : '../javascripts/directives',

		// module shortcut
		app : '../javascripts/app',
		angular : 'angular/angular.min',
		angularBootstrap : 'angular-bootstrap/ui-bootstrap-tpls',
		angularRoute : 'angular-route/angular-route.min',
		easyAlgoParser : '../javascripts/easyAlgoLanguage/easyAlgoParser',
		easyAlgoRunner : '../javascripts/easyAlgoLanguage/easyAlgoRunner',
		easyAlgoLint : '../javascripts/easyAlgoLanguage/easyAlgoLint',
		easyAlgoFold : '../javascripts/easyAlgoLanguage/easyAlgoFold',
		easyAlgoCloseTag : '../javascripts/easyAlgoLanguage/easyAlgoCloseTag',
		easyAlgoValidator : '../javascripts/easyAlgoLanguage/easyAlgoValidator',
		easyAlgoConfiguration : '../javascripts/easyAlgoLanguage/easyAlgoConfiguration',
		easyAlgoSyntaxHighlighter : '../javascripts/easyAlgoLanguage/easyAlgoSyntaxHighlighter',
		easyAlgoContext : '../javascripts/easyAlgoLanguage/easyAlgoContext',
		easyAlgoRuntimeException : '../javascripts/easyAlgoLanguage/easyAlgoRuntimeException',
		terminalEmulator : '../javascripts/terminalEmulator/vtortola.ng-terminal',
		routes : '../javascripts/routes',
		appDir : '../javascripts/',
		ffFileSystem : 'idb.filesystem.js/src/idb.filesystem.min'
	},
	shim : {
		'angularBootstrap' : {
			deps : [
				'angular'
			],
			exports: 'angular-ui-bootstrap'
		},
		'angular-ui-codemirror/ui-codemirror' : {
			deps : [
				'angular',
				'codemirror/lib/codemirror'
			],
			exports: 'codeMirrorAngular'
		},
		'angularRoute': {
			deps : [
				'angular'
			],
			exports: 'angularRoute'
		},
		'terminalEmulator': {
			deps : [
				'angular'
			],
			exports : 'terminalEmulator'
		},
		'controllers/easyAlgoEditor' : {
			deps : [
				'codemirror/mode/htmlmixed/htmlmixed',
				'codemirror/addon/hint/show-hint',
				'codemirror/addon/lint/lint',
				'codemirror/addon/fold/foldgutter',
                'easyAlgoSyntaxHighlighter',
                'easyAlgoParser',
				'easyAlgoLint',
				'easyAlgoFold',
				'easyAlgoValidator',
				'easyAlgoCloseTag',
				'easyAlgoRunner',
				'services/fileSystem'
			],
			exports : 'controllers/easyAlgoEditor'
		},
		'ng-flow/dist/ng-flow-standalone' : {
			deps : ['angular']
		},
		'tc-angular-chartjs/dist/tc-angular-chartjs' : {
			deps : [
				'Chart.js/Chart.min',
				'angular'
			]
		},
		app : {
			deps: [
				'angular',
				'angularRoute',
				'appDir/services/dependencyResolverFor',
				'routes',
				'angularBootstrap',
				'terminalEmulator',
				'angular-ui-codemirror/ui-codemirror',
				'ng-flow/dist/ng-flow-standalone',
				'tc-angular-chartjs/dist/tc-angular-chartjs'
			],
			exports: 'app'
		}
	}
});

require(['app'], function (app) {
  // create CodeMirror on window for correcte usage of ui.codemirror
  window.CodeMirror = require('codemirror/lib/codemirror');
  app.init();
});<|endoftext|>


<commit_before>var express = require('express');
var ratchet = require('../ratchet');

var app = express();

app.get('/', function(req, res) {
  req.user_id = "test-user";
  throw new Error('Hello World');
});

app.use(ratchet.errorHandler("8802be7c990a4922beadaaefb6e0327b",
                             {environment: 'playground'}));

console.log('browse to http://localhost:9876/');
app.listen(9876);
<commit_msg>clearer output<commit_after>var express = require('express');
var ratchet = require('../ratchet');

var app = express();

app.get('/', function(req, res) {
  req.user_id = "test-user";
  throw new Error('Hello World');
});

app.use(ratchet.errorHandler("ACCESS_TOKEN",
                             {environment: 'playground'}));

console.log('browse to http://localhost:9876/ then go to your ratchet.io account: http://ratchet.io/');
app.listen(9876);
<|endoftext|>


<commit_before>'use strict';

import url from 'url';
import cookies from 'cookies-js';
import {parseReferrer, parseUtm} from './parsers';

/**
 * The deliverable
 */
let acquisition;

/**
 * Settings
 *
 * @type {Object}
 */
let settings = {
    cookieName: 'acqsrc',
    cookiePath: '/',
    referrer: typeof document !== 'undefined' ? document.referrer : null,
    location: typeof location !== 'undefined' ? location.href : null
};

/**
 * Initialize all the things!
 */
function init () {
    let currentCookie = cookies.get(settings.cookieName);

    if (typeof currentCookie === 'string') {
        try {
            acquisition = JSON.parse(currentCookie);
        } catch (e) {
            cookies.expire(settings.cookieName);
        }
    }
}

/** Kick it off */
init();

/**
 * Acquires the source/medium, returns it and saves it to a cookie
 *
 * @return {[type]} [description]
 */
function doAcquire () {
    let thisUrl = url.parse(settings.location, true);
    let referrerUrl = url.parse(settings.referrer);

    if (acquisition !== null && typeof acquisition === 'object') {
        return acquisition;
    } else if (referrerUrl.hostname === thisUrl.hostname) {
        return undefined;
    } else {
        acquisition = getAcquisition(thisUrl, referrerUrl);
        return acquisition;
    }
}

function hasUtmParams (query) {
    return query.hasOwnProperty('utm_source') || query.hasOwnProperty('utm_medium');
}

function hasGclid (query) {
    return query.hasOwnProperty('gclid');
}

function getAcquisition (thisUrl, referrerUrl) {
    if (hasUtmParams(thisUrl.query)) {
        return parseUtm(thisUrl.query, referrer);
    } else if (hasGclid(this.url.query)) {
        return {
            source: 'google',
            medium: 'ppc'
        };
    } else if (referrerUrl.hostname !== null) {
        return parseReferrer(referrerUrl);
    } else {
        return {
            source: '(direct)',
            medium: '(none)'
        };
    }
}

const acquisitionSource = {

    settings,

    get acquisition () {
        return acquisition;
    },

    get source () {
        return this.acquisition.source;
    },

    get medium () {
        return this.acquisition.medium;
    },

    acquire (overrides = {}) {
        return doAcquire(Object.assign(settings, overrides));
    },

    parseReferrer,

    parseUtm

};

export {acquisitionSource as default};
<commit_msg>Fixed misnamed variable<commit_after>'use strict';

import url from 'url';
import cookies from 'cookies-js';
import {parseReferrer, parseUtm} from './parsers';

/**
 * The deliverable
 */
let acquisition;

/**
 * Settings
 *
 * @type {Object}
 */
let settings = {
    cookieName: 'acqsrc',
    cookiePath: '/',
    referrer: typeof document !== 'undefined' ? document.referrer : null,
    location: typeof location !== 'undefined' ? location.href : null
};

/**
 * Initialize all the things!
 */
function init () {
    let currentCookie = cookies.get(settings.cookieName);

    if (typeof currentCookie === 'string') {
        try {
            acquisition = JSON.parse(currentCookie);
        } catch (e) {
            cookies.expire(settings.cookieName);
        }
    }
}

/** Kick it off */
init();

/**
 * Acquires the source/medium, returns it and saves it to a cookie
 *
 * @return {[type]} [description]
 */
function doAcquire () {
    let thisUrl = url.parse(settings.location, true);
    let referrerUrl = url.parse(settings.referrer);

    if (acquisition !== null && typeof acquisition === 'object') {
        return acquisition;
    } else if (referrerUrl.hostname === thisUrl.hostname) {
        return undefined;
    } else {
        acquisition = getAcquisition(thisUrl, referrerUrl);
        return acquisition;
    }
}

function hasUtmParams (query) {
    return query.hasOwnProperty('utm_source') || query.hasOwnProperty('utm_medium');
}

function hasGclid (query) {
    return query.hasOwnProperty('gclid');
}

function getAcquisition (thisUrl, referrerUrl) {
    if (hasUtmParams(thisUrl.query)) {
        return parseUtm(thisUrl.query, referrer);
    } else if (hasGclid(thisUrl.query)) {
        return {
            source: 'google',
            medium: 'ppc'
        };
    } else if (referrerUrl.hostname !== null) {
        return parseReferrer(referrerUrl);
    } else {
        return {
            source: '(direct)',
            medium: '(none)'
        };
    }
}

const acquisitionSource = {

    settings,

    get acquisition () {
        return acquisition;
    },

    get source () {
        return this.acquisition.source;
    },

    get medium () {
        return this.acquisition.medium;
    },

    acquire (overrides = {}) {
        return doAcquire(Object.assign(settings, overrides));
    },

    parseReferrer,

    parseUtm

};

export {acquisitionSource as default};
<|endoftext|>


<commit_before>/* eslint-disable operator-assignment */

const logger = require('logger');
const SubscriptionModel = require('models/subscription');
const StatisticModel = require('models/statistic');
const GenericError = require('errors/genericError');
const SubscriptionService = require('services/subscriptionService');
const SparkpostService = require('services/sparkpostService');
const ctRegisterMicroservice = require('ct-register-microservice-node');

const JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;

class StatisticsService {

    static async getUsers(startDate, endDate) {
        logger.info('[StatisticsService] Loading users');
        try {
            const result = await ctRegisterMicroservice.requestToMicroservice({
                uri: `/user/obtain/all-users?start=${startDate.toISOString().substring(0, 10)}&end=${endDate.toISOString().substring(0, 10)}`,
                method: 'GET',
                json: true
            });

            return await new JSONAPIDeserializer({
                keyForAttribute: 'camelCase'
            }).deserialize(result);
        } catch (err) {
            logger.error('Error obtaining users:', err);
            throw new GenericError(500, 'Error obtaining data');
        }

    }

    static async getTopSubscriptions(startDate, endDate, application) {
        logger.debug(`Obtaining getTopSubscriptions with startDate ${startDate}, endDate ${endDate} and application ${application}`);
        const topSubs = {};
        const defaultFilter = {
            createdAt: { $gte: startDate, $lt: endDate },
            application: { $eq: application },
        };
        topSubs.geostore = await SubscriptionModel.count({
            ...defaultFilter,
            'params.geostore': {
                $ne: null
            }
        });
        topSubs.country = await SubscriptionModel.count({
            ...defaultFilter,
            'params.iso.country': {
                $ne: null
            },
            'params.iso.region': null
        });
        topSubs.region = await SubscriptionModel.count({
            ...defaultFilter,
            'params.iso.region': {
                $ne: null
            }
        });
        topSubs.wdpa = await SubscriptionModel.count({
            ...defaultFilter,
            'params.wdpaid': {
                $ne: null
            }
        });
        topSubs.use = await SubscriptionModel.count({
            ...defaultFilter,
            'params.use': {
                $ne: null
            }
        });

        return topSubs;
    }

    static async getUser(userId) {
        try {
            const result = await ctRegisterMicroservice.requestToMicroservice({
                uri: `/user/${userId}`,
                method: 'GET',
                json: true
            });

            return await new JSONAPIDeserializer({
                keyForAttribute: 'camelCase'
            }).deserialize(result);
        } catch (err) {
            if (err.statusCode !== 404) {
                logger.error('Error obtaining users:', err);
            }
            return null;
        }

    }

    static async infoByUserSubscriptions(startDate, endDate, application) {
        logger.debug(`Obtaining  subscriptions with startDate ${startDate}, endDate ${endDate} and application ${application}`);
        const filter = {
            createdAt: { $gte: startDate, $lt: endDate },
            application: { $eq: application },
        };

        const subscriptions = await SubscriptionModel.find(filter);
        const usersCache = {};
        const data = [];
        for (let i = 0, { length } = subscriptions; i < length; i++) {
            if (!usersCache[subscriptions[i].userId]) {
                usersCache[subscriptions[i].userId] = await StatisticsService.getUser(subscriptions[i].userId);
            }
            const subs = subscriptions[i].toJSON();
            subs.user = usersCache[subscriptions[i].userId];
            data.push(subs);

        }
        return data;
    }

    static async infoGroupSubscriptions(startDate, endDate, application) {
        logger.debug(`Obtaining group subscriptions with startDate ${startDate}, endDate ${endDate} and application ${application}`);
        const filter = {
            createdAt: { $gte: startDate, $lt: endDate },
            datasets: { $ne: [] },
            application: { $eq: application },
        };

        const subscriptions = await SubscriptionModel.find(filter);
        const data = {};
        logger.debug('Subscriptions', subscriptions.length);
        subscriptions.forEach((sub) => {
            logger.debug('Iterating subs', sub);
            sub.datasets.forEach((dat) => {
                logger.debug('Iterating dataset', data);
                if (!data[dat]) {
                    data[dat] = {
                        country: 0,
                        region: 0,
                        use: 0,
                        wdpa: 0,
                        geostore: 0,
                        countries: {},
                        regions: {},
                        wdpas: {},
                        countryTop: {
                            name: null,
                            value: 0
                        },
                        regionTop: {
                            nameRegion: null,
                            nameCountry: null,
                            value: 0
                        },
                        wdpaTop: {
                            id: null,
                            value: 0
                        }
                    };
                }
                if (sub.params.geostore) {
                    data[dat].geostore = data[dat].geostore + 1;
                } else if (sub.params.iso && (sub.params.iso.country || sub.params.iso.region)) {
                    if (sub.params.iso.region) {
                        data[dat].region = data[dat].region + 1;
                        if (!data[dat].regions[sub.params.iso.region]) {
                            data[dat].regions[sub.params.iso.region] = 0;
                        }
                        data[dat].regions[sub.params.iso.region] = data[dat].regions[sub.params.iso.region] + 1;
                        if (data[dat].regions[sub.params.iso.region] > data[dat].regionTop.value) {
                            data[dat].regionTop.nameRegion = sub.params.iso.region;
                            data[dat].regionTop.nameCountry = sub.params.iso.country;
                            data[dat].regionTop.value = data[dat].regions[sub.params.iso.region];
                        }
                    } else {
                        data[dat].country = data[dat].country + 1;
                        if (!data[dat].countries[sub.params.iso.country]) {
                            data[dat].countries[sub.params.iso.country] = 0;
                        }
                        data[dat].countries[sub.params.iso.country] = data[dat].countries[sub.params.iso.country] + 1;
                        if (data[dat].countries[sub.params.iso.country] > data[dat].countryTop.value) {
                            data[dat].countryTop.name = sub.params.iso.country;
                            data[dat].countryTop.value = data[dat].countries[sub.params.iso.country];
                        }
                    }
                } else if (sub.params.wdpaid) {
                    data[dat].wdpa = data[dat].wdpa + 1;
                    if (!data[dat].wdpas[sub.params.wdpaid]) {
                        data[dat].wdpas[sub.params.wdpaid] = 0;
                    }
                    data[dat].wdpas[sub.params.wdpaid] = data[dat].wdpas[sub.params.wdpaid] + 1;
                    if (data[dat].wdpas[sub.params.wdpaid] > data[dat].wdpaTop.value) {
                        data[dat].wdpaTop.id = sub.params.wdpaid;
                        data[dat].wdpaTop.value = data[dat].wdpas[sub.params.wdpaid];
                    }
                } else {
                    data[dat].use = data[dat].use + 1;
                }
            });

        });

        return data;
    }

    static async infoSubscriptions(startDate, endDate, application) {
        logger.debug(`Obtaining infoSubscriptions with startDate ${startDate}, endDate ${endDate} and application ${application}`);
        const info = {};

        const defaultFilter = {
            createdAt: { $gte: startDate, $lt: endDate },
            application: { $eq: application },
        };

        info.numSubscriptions = await SubscriptionModel.count(defaultFilter);
        info.totalSubscriptions = await SubscriptionModel.count();
        logger.debug(SubscriptionModel.aggregate([
            { $match: { application: { $eq: application } } },
            { $group: { _id: '$userId' } },
            {
                $group: {
                    _id: 1,
                    count: {
                        $sum: 1
                    }
                }
            }]));
        const usersWithSubscriptionResult = await SubscriptionModel.aggregate([
            { $match: { application: { $eq: application } } },
            { $group: { _id: '$userId' } },
            {
                $group: {
                    _id: 1,
                    count: { $sum: 1 }
                }
            }]).exec();
        info.usersWithSubscriptions = usersWithSubscriptionResult.length > 0
            ? usersWithSubscriptionResult[0].count
            : 0;
        info.totalEmailsSentInThisQ = await StatisticModel.count(defaultFilter);
        info.totalEmailsSended = await StatisticModel.count();

        return info;
    }

    static async getNewUsersWithSubs(users, application) {
        let usersCount = 0;
        if (users) {
            for (let i = 0, { length } = users; i < length; i++) {
                usersCount += await SubscriptionModel.count({
                    userId: users[i].id,
                    application: { $eq: application },
                });
            }
        }
        return usersCount;
    }

    static async getStatistics(startDate, endDate, application = 'gfw') {
        const users = await StatisticsService.getUsers(startDate, endDate);
        const topSubs = await StatisticsService.getTopSubscriptions(startDate, endDate, application);
        const info = await StatisticsService.infoSubscriptions(startDate, endDate, application);
        const groupStatistics = await StatisticsService.infoGroupSubscriptions(startDate, endDate, application);
        const usersWithSubscription = await StatisticsService.getNewUsersWithSubs(users, application);
        return {
            topSubscriptions: topSubs,
            info,
            usersWithSubscription,
            newUsers: users ? users.length : 0,
            groupStatistics
        };
    }

    static async countEmailsSentForSlugOnDate(date, slug) {
        return StatisticModel.countDocuments({
            slug,
            createdAt: {
                $gte: date.clone()
                    .hours(0)
                    .minutes(0)
                    .seconds(0)
                    .toDate(),

                $lt: date.clone()
                    .hours(23)
                    .minutes(59)
                    .seconds(59)
                    .toDate(),
            },
        });
    }

    static async getGLADEmailsValidationObject(date) {
        const gladSubs = await SubscriptionService.findGLADEmailSubscriptions();
        const gladSent = await StatisticsService.countEmailsSentForSlugOnDate(date, 'glad-alerts');
        const gladSparkpostCount = await SparkpostService.getGLADCountInjectedOnDate(date);

        return {
            success: true,
            expectedSubscriptionEmailsSent: gladSubs.length,
            actualSubscriptionEmailsSent: gladSent,
            sparkPostAPICalls: gladSparkpostCount,
        };
    }

    static async getVIIRSEmailsValidationObject(date) {
        const viirsSubs = await SubscriptionService.findVIIRSEmailSubscriptions();
        const viirsSent = await StatisticsService.countEmailsSentForSlugOnDate(date, 'viirs-active-fires');
        const viirsSparkpostCount = await SparkpostService.getVIIRSCountInjectedOnDate(date);

        return {
            success: true,
            expectedSubscriptionEmailsSent: viirsSubs.length,
            actualSubscriptionEmailsSent: viirsSent,
            sparkPostAPICalls: viirsSparkpostCount,
        };
    }

    static async getMonthlyEmailsValidationObject(date) {
        const monthlySubs = await SubscriptionService.findMonthlySummaryEmailSubscriptions();
        const monthlySent = await StatisticsService.countEmailsSentForSlugOnDate(date, 'monthly-summary');
        const monthlySparkpostCount = await SparkpostService.getMonthlyCountInjectedOnDate(date);

        return {
            success: true,
            expectedSubscriptionEmailsSent: monthlySubs.length,
            actualSubscriptionEmailsSent: monthlySent,
            sparkPostAPICalls: monthlySparkpostCount,
        };
    }

}

module.exports = StatisticsService;
<commit_msg>Fix success conditions<commit_after>/* eslint-disable operator-assignment */

const logger = require('logger');
const SubscriptionModel = require('models/subscription');
const StatisticModel = require('models/statistic');
const GenericError = require('errors/genericError');
const SubscriptionService = require('services/subscriptionService');
const SparkpostService = require('services/sparkpostService');
const ctRegisterMicroservice = require('ct-register-microservice-node');

const JSONAPIDeserializer = require('jsonapi-serializer').Deserializer;

class StatisticsService {

    static async getUsers(startDate, endDate) {
        logger.info('[StatisticsService] Loading users');
        try {
            const result = await ctRegisterMicroservice.requestToMicroservice({
                uri: `/user/obtain/all-users?start=${startDate.toISOString().substring(0, 10)}&end=${endDate.toISOString().substring(0, 10)}`,
                method: 'GET',
                json: true
            });

            return await new JSONAPIDeserializer({
                keyForAttribute: 'camelCase'
            }).deserialize(result);
        } catch (err) {
            logger.error('Error obtaining users:', err);
            throw new GenericError(500, 'Error obtaining data');
        }

    }

    static async getTopSubscriptions(startDate, endDate, application) {
        logger.debug(`Obtaining getTopSubscriptions with startDate ${startDate}, endDate ${endDate} and application ${application}`);
        const topSubs = {};
        const defaultFilter = {
            createdAt: { $gte: startDate, $lt: endDate },
            application: { $eq: application },
        };
        topSubs.geostore = await SubscriptionModel.count({
            ...defaultFilter,
            'params.geostore': {
                $ne: null
            }
        });
        topSubs.country = await SubscriptionModel.count({
            ...defaultFilter,
            'params.iso.country': {
                $ne: null
            },
            'params.iso.region': null
        });
        topSubs.region = await SubscriptionModel.count({
            ...defaultFilter,
            'params.iso.region': {
                $ne: null
            }
        });
        topSubs.wdpa = await SubscriptionModel.count({
            ...defaultFilter,
            'params.wdpaid': {
                $ne: null
            }
        });
        topSubs.use = await SubscriptionModel.count({
            ...defaultFilter,
            'params.use': {
                $ne: null
            }
        });

        return topSubs;
    }

    static async getUser(userId) {
        try {
            const result = await ctRegisterMicroservice.requestToMicroservice({
                uri: `/user/${userId}`,
                method: 'GET',
                json: true
            });

            return await new JSONAPIDeserializer({
                keyForAttribute: 'camelCase'
            }).deserialize(result);
        } catch (err) {
            if (err.statusCode !== 404) {
                logger.error('Error obtaining users:', err);
            }
            return null;
        }

    }

    static async infoByUserSubscriptions(startDate, endDate, application) {
        logger.debug(`Obtaining  subscriptions with startDate ${startDate}, endDate ${endDate} and application ${application}`);
        const filter = {
            createdAt: { $gte: startDate, $lt: endDate },
            application: { $eq: application },
        };

        const subscriptions = await SubscriptionModel.find(filter);
        const usersCache = {};
        const data = [];
        for (let i = 0, { length } = subscriptions; i < length; i++) {
            if (!usersCache[subscriptions[i].userId]) {
                usersCache[subscriptions[i].userId] = await StatisticsService.getUser(subscriptions[i].userId);
            }
            const subs = subscriptions[i].toJSON();
            subs.user = usersCache[subscriptions[i].userId];
            data.push(subs);

        }
        return data;
    }

    static async infoGroupSubscriptions(startDate, endDate, application) {
        logger.debug(`Obtaining group subscriptions with startDate ${startDate}, endDate ${endDate} and application ${application}`);
        const filter = {
            createdAt: { $gte: startDate, $lt: endDate },
            datasets: { $ne: [] },
            application: { $eq: application },
        };

        const subscriptions = await SubscriptionModel.find(filter);
        const data = {};
        logger.debug('Subscriptions', subscriptions.length);
        subscriptions.forEach((sub) => {
            logger.debug('Iterating subs', sub);
            sub.datasets.forEach((dat) => {
                logger.debug('Iterating dataset', data);
                if (!data[dat]) {
                    data[dat] = {
                        country: 0,
                        region: 0,
                        use: 0,
                        wdpa: 0,
                        geostore: 0,
                        countries: {},
                        regions: {},
                        wdpas: {},
                        countryTop: {
                            name: null,
                            value: 0
                        },
                        regionTop: {
                            nameRegion: null,
                            nameCountry: null,
                            value: 0
                        },
                        wdpaTop: {
                            id: null,
                            value: 0
                        }
                    };
                }
                if (sub.params.geostore) {
                    data[dat].geostore = data[dat].geostore + 1;
                } else if (sub.params.iso && (sub.params.iso.country || sub.params.iso.region)) {
                    if (sub.params.iso.region) {
                        data[dat].region = data[dat].region + 1;
                        if (!data[dat].regions[sub.params.iso.region]) {
                            data[dat].regions[sub.params.iso.region] = 0;
                        }
                        data[dat].regions[sub.params.iso.region] = data[dat].regions[sub.params.iso.region] + 1;
                        if (data[dat].regions[sub.params.iso.region] > data[dat].regionTop.value) {
                            data[dat].regionTop.nameRegion = sub.params.iso.region;
                            data[dat].regionTop.nameCountry = sub.params.iso.country;
                            data[dat].regionTop.value = data[dat].regions[sub.params.iso.region];
                        }
                    } else {
                        data[dat].country = data[dat].country + 1;
                        if (!data[dat].countries[sub.params.iso.country]) {
                            data[dat].countries[sub.params.iso.country] = 0;
                        }
                        data[dat].countries[sub.params.iso.country] = data[dat].countries[sub.params.iso.country] + 1;
                        if (data[dat].countries[sub.params.iso.country] > data[dat].countryTop.value) {
                            data[dat].countryTop.name = sub.params.iso.country;
                            data[dat].countryTop.value = data[dat].countries[sub.params.iso.country];
                        }
                    }
                } else if (sub.params.wdpaid) {
                    data[dat].wdpa = data[dat].wdpa + 1;
                    if (!data[dat].wdpas[sub.params.wdpaid]) {
                        data[dat].wdpas[sub.params.wdpaid] = 0;
                    }
                    data[dat].wdpas[sub.params.wdpaid] = data[dat].wdpas[sub.params.wdpaid] + 1;
                    if (data[dat].wdpas[sub.params.wdpaid] > data[dat].wdpaTop.value) {
                        data[dat].wdpaTop.id = sub.params.wdpaid;
                        data[dat].wdpaTop.value = data[dat].wdpas[sub.params.wdpaid];
                    }
                } else {
                    data[dat].use = data[dat].use + 1;
                }
            });

        });

        return data;
    }

    static async infoSubscriptions(startDate, endDate, application) {
        logger.debug(`Obtaining infoSubscriptions with startDate ${startDate}, endDate ${endDate} and application ${application}`);
        const info = {};

        const defaultFilter = {
            createdAt: { $gte: startDate, $lt: endDate },
            application: { $eq: application },
        };

        info.numSubscriptions = await SubscriptionModel.count(defaultFilter);
        info.totalSubscriptions = await SubscriptionModel.count();
        logger.debug(SubscriptionModel.aggregate([
            { $match: { application: { $eq: application } } },
            { $group: { _id: '$userId' } },
            {
                $group: {
                    _id: 1,
                    count: {
                        $sum: 1
                    }
                }
            }]));
        const usersWithSubscriptionResult = await SubscriptionModel.aggregate([
            { $match: { application: { $eq: application } } },
            { $group: { _id: '$userId' } },
            {
                $group: {
                    _id: 1,
                    count: { $sum: 1 }
                }
            }]).exec();
        info.usersWithSubscriptions = usersWithSubscriptionResult.length > 0
            ? usersWithSubscriptionResult[0].count
            : 0;
        info.totalEmailsSentInThisQ = await StatisticModel.count(defaultFilter);
        info.totalEmailsSended = await StatisticModel.count();

        return info;
    }

    static async getNewUsersWithSubs(users, application) {
        let usersCount = 0;
        if (users) {
            for (let i = 0, { length } = users; i < length; i++) {
                usersCount += await SubscriptionModel.count({
                    userId: users[i].id,
                    application: { $eq: application },
                });
            }
        }
        return usersCount;
    }

    static async getStatistics(startDate, endDate, application = 'gfw') {
        const users = await StatisticsService.getUsers(startDate, endDate);
        const topSubs = await StatisticsService.getTopSubscriptions(startDate, endDate, application);
        const info = await StatisticsService.infoSubscriptions(startDate, endDate, application);
        const groupStatistics = await StatisticsService.infoGroupSubscriptions(startDate, endDate, application);
        const usersWithSubscription = await StatisticsService.getNewUsersWithSubs(users, application);
        return {
            topSubscriptions: topSubs,
            info,
            usersWithSubscription,
            newUsers: users ? users.length : 0,
            groupStatistics
        };
    }

    static async countEmailsSentForSlugOnDate(date, slug) {
        return StatisticModel.countDocuments({
            slug,
            createdAt: {
                $gte: date.clone()
                    .hours(0)
                    .minutes(0)
                    .seconds(0)
                    .toDate(),

                $lt: date.clone()
                    .hours(23)
                    .minutes(59)
                    .seconds(59)
                    .toDate(),
            },
        });
    }

    static async getGLADEmailsValidationObject(date) {
        const gladSubs = await SubscriptionService.findGLADEmailSubscriptions();
        const gladSent = await StatisticsService.countEmailsSentForSlugOnDate(date, 'glad-alerts');
        const gladSparkpostCount = await SparkpostService.getGLADCountInjectedOnDate(date);

        return {
            success: gladSubs.length === gladSent && gladSent === gladSparkpostCount,
            expectedSubscriptionEmailsSent: gladSubs.length,
            actualSubscriptionEmailsSent: gladSent,
            sparkPostAPICalls: gladSparkpostCount,
        };
    }

    static async getVIIRSEmailsValidationObject(date) {
        const viirsSubs = await SubscriptionService.findVIIRSEmailSubscriptions();
        const viirsSent = await StatisticsService.countEmailsSentForSlugOnDate(date, 'viirs-active-fires');
        const viirsSparkpostCount = await SparkpostService.getVIIRSCountInjectedOnDate(date);

        return {
            success: viirsSubs.length === viirsSent && viirsSent === viirsSparkpostCount,
            expectedSubscriptionEmailsSent: viirsSubs.length,
            actualSubscriptionEmailsSent: viirsSent,
            sparkPostAPICalls: viirsSparkpostCount,
        };
    }

    static async getMonthlyEmailsValidationObject(date) {
        const monthlySubs = await SubscriptionService.findMonthlySummaryEmailSubscriptions();
        const monthlySent = await StatisticsService.countEmailsSentForSlugOnDate(date, 'monthly-summary');
        const monthlySparkpostCount = await SparkpostService.getMonthlyCountInjectedOnDate(date);

        return {
            success: monthlySubs.length === monthlySent && monthlySent === monthlySparkpostCount,
            expectedSubscriptionEmailsSent: monthlySubs.length,
            actualSubscriptionEmailsSent: monthlySent,
            sparkPostAPICalls: monthlySparkpostCount,
        };
    }

}

module.exports = StatisticsService;
<|endoftext|>


<commit_before>/*
This is the defualt transformations library.
It works with the Tools API, which specifies
 */

var Hist = new Array();

// History framework
//{func: function, params: [x, y, z]}

function Trans(map){
	this.func = map['func'];
	this.params = map['params'];
	// automatically record
	this.index = this.record();
}

// calls a function
Trans.prototype.call = function(){
	this.func(this.params);
}

Trans.prototype.record = function(){
	Hist.push(this);
	return Hist.length - 1
}

Trans.prototype.toString = function(){
	var s = new Array();
	s.push(this.func.name, '(');
	var p = new Array();
	for (var i = 0; i < this.params.length; i++){
		p.push(this.params[i])
	}
	s.push(p.join(', '));
	s.push(')');
	return s.join('');
}

Trans.prototype.Set = function(){
	var s = document.createElement('p');
	s.appendChild(document.createTextNode(this.toString()));
	s.setAttribute('onclick', 'Hist['+this.index+'].call()')
	var h = document.getElementById('hist');
	h.insertBefore(s, h.firstChild);
}

// Default Transformations
var lastScale = [1.0,1.0,1.0]; // for reverting after scale
var lastRotate = [0.0,0.0,0.0];
var lastShift = [0.0, 0.0, 0.0];
var lastAutoCenter = [0.0,0.0,0.0];

// Set functions parse the
function setTrans(x, y, z, def, trans){
	if (isNaN(px = parseFloat(x))) {
		px = def;
	}
	if (isNaN(py = parseFloat(y))) {
		py = def;
	}
	if (isNaN(pz = parseFloat(z))) {
		pz = def;
	}
	var t = new Trans({
		func: trans,
		params: [px, py, pz]
	})
	t.call();
	t.Set(); // shows on page
}

function Scale(par){
	for (var i = 0; i < geometry.vertices.length; i++) {
		geometry.vertices[i].x *= (par[0]/lastScale[0]);
		geometry.vertices[i].y *= (par[1]/lastScale[1]);
		geometry.vertices[i].z *= (par[2]/lastScale[2]);
	}
	// save state
	lastScale[0] = par[0];
	lastScale[1] = par[1];
	lastScale[2] = par[2];

	geometry.verticesNeedUpdate = true;
}

function Shift(par){
	for (var i = 0; i < geometry.vertices.length; i++) {
		geometry.vertices[i].x += (par[0] - lastRotate[0]);
		geometry.vertices[i].y += (par[1] - lastRotate[1]);
		geometry.vertices[i].z += (par[2] - lastRotate[2]);
	}
	// save state
	lastShift[0] = par[0];
	lastShift[1] = par[1];
	lastShift[2] = par[2];
	geometry.verticesNeedUpdate = true;
}

function Rotate(par){
	var rotx = new THREE.Matrix4().makeRotationX(Math.PI*par[0]/180);
	var roty = new THREE.Matrix4().makeRotationY(Math.PI*par[1]/180);
	var rotz = new THREE.Matrix4().makeRotationZ(Math.PI*par[2]/180);

	geometry.applyMatrix(rotx.multiply(roty).multiply(rotz));
	lastRotate[0] = par[0];
	lastRotate[1] = par[1];
	lastRotate[2] = par[2];
	geometry.verticesNeedUpdate = true;
}

function AutoCenter(){
	var b = cube.geometry.boundingBox;
	var lenX = (b.max.x - b.min.x)/2;
	var x = lenX - b.max.x;
	var lenY = (b.max.y - b.min.y)/2;
	var y = lenY - b.max.y;
	// do not center z, min should be 0
	var lenZ = (b.max.z - b.min.z);
	var z = (lenZ - b.max.z);

	// use Shift invisibly
	var last = lastShift.slice(0);
	setTrans(x-lastAutoCenter[0], y-lastAutoCenter[1], z-lastAutoCenter[2], 0.0, Shift);
	lastShift = last.slice(0);
	// save
	lastAutoCenter[0] = x;
	lastAutoCenter[1] = y;
	lastAutoCenter[2] = z;
}

/*function Stats(){
	var b = cube.geometry.boundingBox;
	var s = ['Min x:', b.min.x, 'Min y:', b.min.y, 'Min z:', b.min.z];
	s.push('Max x:', b.max.x, 'Max y:', b.max.y, 'Min z:', b.max.z);
	var d = document.createElement('div');
	d.appendChild(document.createTextNode(s.join(' ')));
	var l = document.getElementById('hist');
	l.innerHTML = '';
	l.appendChild(d);
}*/
<commit_msg>Bad Seward, AutoCenter is sort of a macro<commit_after>/*
This is the defualt transformations library.
It works with the Tools API, which specifies
 */

var Hist = new Array();

// History framework
//{func: function, params: [x, y, z]}

function Trans(map){
	this.func = map['func'];
	this.params = map['params'];
	// automatically record
	this.index = this.record();
}

// calls a function
Trans.prototype.call = function(){
	this.func(this.params);
}

Trans.prototype.record = function(){
	Hist.push(this);
	return Hist.length - 1
}

Trans.prototype.toString = function(){
	var s = new Array();
	s.push(this.func.name, '(');
	var p = new Array();
	for (var i = 0; i < this.params.length; i++){
		p.push(this.params[i])
	}
	s.push(p.join(', '));
	s.push(')');
	return s.join('');
}

Trans.prototype.Set = function(){
	var s = document.createElement('p');
	s.appendChild(document.createTextNode(this.toString()));
	s.setAttribute('onclick', 'Hist['+this.index+'].call()')
	var h = document.getElementById('hist');
	h.insertBefore(s, h.firstChild);
}

// Default Transformations
var lastScale = [1.0,1.0,1.0]; // for reverting after scale
var lastRotate = [0.0,0.0,0.0];
var lastShift = [0.0, 0.0, 0.0];
var lastAutoCenter = [0.0,0.0,0.0];

// Set functions parse the
function setTrans(x, y, z, def, trans){
	if (isNaN(px = parseFloat(x))) {
		px = def;
	}
	if (isNaN(py = parseFloat(y))) {
		py = def;
	}
	if (isNaN(pz = parseFloat(z))) {
		pz = def;
	}
	var t = new Trans({
		func: trans,
		params: [px, py, pz]
	})
	t.call();
	t.Set(); // shows on page
}

function Scale(par){
	for (var i = 0; i < geometry.vertices.length; i++) {
		geometry.vertices[i].x *= (par[0]/lastScale[0]);
		geometry.vertices[i].y *= (par[1]/lastScale[1]);
		geometry.vertices[i].z *= (par[2]/lastScale[2]);
	}
	// save state
	lastScale[0] = par[0];
	lastScale[1] = par[1];
	lastScale[2] = par[2];

	geometry.verticesNeedUpdate = true;
}

function Shift(par){
	for (var i = 0; i < geometry.vertices.length; i++) {
		geometry.vertices[i].x += (par[0] - lastRotate[0]);
		geometry.vertices[i].y += (par[1] - lastRotate[1]);
		geometry.vertices[i].z += (par[2] - lastRotate[2]);
	}
	// save state
	lastShift[0] = par[0];
	lastShift[1] = par[1];
	lastShift[2] = par[2];
	geometry.verticesNeedUpdate = true;
}

function Rotate(par){
	var rotx = new THREE.Matrix4().makeRotationX(Math.PI*par[0]/180);
	var roty = new THREE.Matrix4().makeRotationY(Math.PI*par[1]/180);
	var rotz = new THREE.Matrix4().makeRotationZ(Math.PI*par[2]/180);

	geometry.applyMatrix(rotx.multiply(roty).multiply(rotz));
	lastRotate[0] = par[0];
	lastRotate[1] = par[1];
	lastRotate[2] = par[2];
	geometry.verticesNeedUpdate = true;
}

function AutoCenter(){
	geometry.computeBoundingBox ();
	var b =geometry.boundingBox;
	var lenX = (b.max.x - b.min.x)/2;
	var x = lenX - b.max.x;
	var lenY = (b.max.y - b.min.y)/2;
	var y = lenY - b.max.y;
	// do not center z, min should be 0
	var lenZ = (b.max.z - b.min.z);
	var z = (lenZ - b.max.z);
	//alert([x,y,z]);
	//Shift([x,y,z]);
	// use Shift invisibly
	var last = lastShift.slice(0);
	setTrans(x-lastAutoCenter[0], y-lastAutoCenter[1], z-lastAutoCenter[2], 0.0, Shift);
	lastShift = last.slice(0);
	// save
	lastAutoCenter[0] = x;
	lastAutoCenter[1] = y;
	lastAutoCenter[2] = z;
}

/*function Stats(){
	var b = cube.geometry.boundingBox;
	var s = ['Min x:', b.min.x, 'Min y:', b.min.y, 'Min z:', b.min.z];
	s.push('Max x:', b.max.x, 'Max y:', b.max.y, 'Min z:', b.max.z);
	var d = document.createElement('div');
	d.appendChild(document.createTextNode(s.join(' ')));
	var l = document.getElementById('hist');
	l.innerHTML = '';
	l.appendChild(d);
}*/
<|endoftext|>


<commit_before>import { ShredderStorage } from './storage';
import { Scenario } from './models/scenario';

export class Scenarios {

  public scenarios = [];
  public currentScenario;

  constructor() {
    this.loadFromStorage();
  }

  loadFromStorage() {
    const fromStorage = ShredderStorage.getSerialized();

    fromStorage.scenarios.forEach((scenario) => {
      this.scenarios.push(new Scenario(scenario));

      this.setCurrentScenario(fromStorage.currentScenario);
    });
  }

  setCurrentScenario(scenarioId) {
    this.currentScenario = scenarioId ? this.getById(scenarioId) : null;
  }

  saveToStorage() {
    const currentScenarioId = this.currentScenario.id;

    ShredderStorage.save(this.scenarios, currentScenarioId);
    return true;
  }

  getById(scenarioId) {
    return this.scenarios.filter((scenario) => scenario.id === scenarioId)[0];
  }

  addRuleToScenario(scenarioId, capturedRequest) {
    this.getById(scenarioId).addRule(capturedRequest);

    this.saveToStorage();
  }

  addScenario(name) {
    this.scenarios.push(new Scenario({ name }));
    this.saveToStorage();
  }

  duplicateScenario(scenarioId) {
    const selectedScenario = this.getById(scenarioId);

    const newScenario = {
      name: `${ selectedScenario.name } copy`,
      rules: selectedScenario.rules,
    };

    this.scenarios.push(new Scenario(newScenario));

    this.saveToStorage();
  }

  removeScenario(scenarioId) {
    this.scenarios = this.scenarios
      .filter((scenario) => scenario.id !== scenarioId);

    this.saveToStorage();
  }

  updateRuleInScenario(scenarioId, ruleId, request, response) {
    this.getById(scenarioId).updateRule(ruleId, request, response);

    this.saveToStorage();
  }
}

export default new Scenarios();
<commit_msg>remove typescript leftovers from Scenarios<commit_after>import { ShredderStorage } from './storage';
import { Scenario } from './models/scenario';

export class Scenarios {

  constructor() {
    this.scenarios = [];
    this.loadFromStorage();
  }

  loadFromStorage() {
    const fromStorage = ShredderStorage.getSerialized();

    fromStorage.scenarios.forEach((scenario) => {
      this.scenarios.push(new Scenario(scenario));

      this.setCurrentScenario(fromStorage.currentScenario);
    });
  }

  setCurrentScenario(scenarioId) {
    this.currentScenario = scenarioId ? this.getById(scenarioId) : null;
  }

  saveToStorage() {
    const currentScenarioId = this.currentScenario.id;

    ShredderStorage.save(this.scenarios, currentScenarioId);
    return true;
  }

  getById(scenarioId) {
    return this.scenarios.filter((scenario) => scenario.id === scenarioId)[0];
  }

  addRuleToScenario(scenarioId, capturedRequest) {
    this.getById(scenarioId).addRule(capturedRequest);

    this.saveToStorage();
  }

  addScenario(name) {
    this.scenarios.push(new Scenario({ name }));
    this.saveToStorage();
  }

  duplicateScenario(scenarioId) {
    const selectedScenario = this.getById(scenarioId);

    const newScenario = {
      name: `${ selectedScenario.name } copy`,
      rules: selectedScenario.rules,
    };

    this.scenarios.push(new Scenario(newScenario));

    this.saveToStorage();
  }

  removeScenario(scenarioId) {
    this.scenarios = this.scenarios
      .filter((scenario) => scenario.id !== scenarioId);

    this.saveToStorage();
  }

  updateRuleInScenario(scenarioId, ruleId, request, response) {
    this.getById(scenarioId).updateRule(ruleId, request, response);

    this.saveToStorage();
  }
}

export default new Scenarios();
<|endoftext|>


<commit_before>var protrons = 0;
var neutrons = 0;
var electrons = 0;

function protClick(number){
    protrons = protrons + number;
    document.getElementById("protrons").innerHTML = protrons;
};

function neutClick(number){
    neutrons = neutrons + number;
    document.getElementById("neutrons").innerHTML = neutrons;
};

function elecClick(number){
    electrons = electrons + number;
    document.getElementById("electrons").innerHTML = electrons;
};

var Hydrogen = 0;

function buyHydrogen(){
    if(protrons >= 1 && electrons >= 1){
        Hydrogen = Hydrogen + 1;
        protrons = protrons - 1;
        electrons = electrons - 1;
        document.getElementById('H').innerHTML = Hydrogen;
        document.getElementById('protrons').innerHTML = protrons;
        document.getElementById('electrons').innerHTML = electrons;

    };

};

var protCreators = 0;
var neutCreators = 0;
var elecCreators = 0;
var HCreators = 0;

function protCreator(){
    var protCreatorCost = Math.floor(10 * Math.pow(1.1,protCreators));
    if(protrons >= protCreatorCost){
        protCreators = protCreators + 1;
        protrons = protrons - protCreatorCost;
        document.getElementById('protCreators').innerHTML = protCreators;
        document.getElementById('protrons').innerHTML = protrons;
    };
    var nextprotCreatorCost = Math.floor(10 * Math.pow(1.1,protCreators));
    document.getElementById('protCreatorCost').innerHTML = nextprotCreatorCost;

};

function neutCreator(){
    var neutCreatorCost = Math.floor(10 * Math.pow(1.1,neutCreators));
    if(neutrons >= neutCreatorCost){
        neutCreators = neutCreators + 1;
        neutrons = neutrons - neutCreatorCost;
        document.getElementById('neutCreators').innerHTML = neutCreators;
        document.getElementById('neutrons').innerHTML = neutrons;
    };
    var nextneutCreatorCost = Math.floor(10 * Math.pow(1.1,neutCreators));
    document.getElementById('neutCreatorCost').innerHTML = nextneutCreatorCost;

};
function elecCreator(){
    var elecCreatorCost = Math.floor(10 * Math.pow(1.1,elecCreators));
    if(electrons >= elecCreatorCost){
        elecCreators = elecCreators + 1;
        electrons = electrons - elecCreatorCost;
        document.getElementById('elecCreators').innerHTML = elecCreators;
        document.getElementById('electrons').innerHTML = elecrons;
    };
    var nextelecCreatorCost = Math.floor(10 * Math.pow(1.1,elecCreators));
    document.getElementById('elecCreatorCost').innerHTML = nextelecCreatorCost;

};

function HCreator(){
    var HCreatorCost = Math.floor(10 * Math.pow(1.1,HCreators));
    if(Hydrogen >= HCreatorCost){
        HCreators = HCreators + 1;
        Hydrogen = Hydrogen - HCreatorCost;
        document.getElementById('HCreators').innerHTML = HCreators;
        document.getElementById('H').innerHTML = Hydrogen;
    };
    var nextHCreatorCost = Math.floor(10 * Math.pow(1.1,HCreators));
    document.getElementById('HCreatorCost').innerHTML = nextHCreatorCost;

};

window.setInterval(function(){

	protClick(protCreators);
	neutClick(neutCreators);
	elecClick(elecCreators);
	HydrClick(HCreators);

}, 1000);
<commit_msg>Update main.js<commit_after>var protrons = 0;
var neutrons = 0;
var electrons = 0;

function protClick(number){
    protrons = protrons + number;
    document.getElementById("protrons").innerHTML = protrons;
};

function neutClick(number){
    neutrons = neutrons + number;
    document.getElementById("neutrons").innerHTML = neutrons;
};

function elecClick(number){
    electrons = electrons + number;
    document.getElementById("electrons").innerHTML = electrons;
};

var Hydrogen = 0;

function HydrClick(){
    if(protrons >= 1 && electrons >= 1){
        Hydrogen = Hydrogen + 1;
        protrons = protrons - 1;
        electrons = electrons - 1;
        document.getElementById('H').innerHTML = Hydrogen;
        document.getElementById('protrons').innerHTML = protrons;
        document.getElementById('electrons').innerHTML = electrons;

    };

};

var protCreators = 0;
var neutCreators = 0;
var elecCreators = 0;
var HCreators = 0;

function protCreator(){
    var protCreatorCost = Math.floor(10 * Math.pow(1.1,protCreators));
    if(protrons >= protCreatorCost){
        protCreators = protCreators + 1;
        protrons = protrons - protCreatorCost;
        document.getElementById('protCreators').innerHTML = protCreators;
        document.getElementById('protrons').innerHTML = protrons;
    };
    var nextprotCreatorCost = Math.floor(10 * Math.pow(1.1,protCreators));
    document.getElementById('protCreatorCost').innerHTML = nextprotCreatorCost;

};

function neutCreator(){
    var neutCreatorCost = Math.floor(10 * Math.pow(1.1,neutCreators));
    if(neutrons >= neutCreatorCost){
        neutCreators = neutCreators + 1;
        neutrons = neutrons - neutCreatorCost;
        document.getElementById('neutCreators').innerHTML = neutCreators;
        document.getElementById('neutrons').innerHTML = neutrons;
    };
    var nextneutCreatorCost = Math.floor(10 * Math.pow(1.1,neutCreators));
    document.getElementById('neutCreatorCost').innerHTML = nextneutCreatorCost;

};
function elecCreator(){
    var elecCreatorCost = Math.floor(10 * Math.pow(1.1,elecCreators));
    if(electrons >= elecCreatorCost){
        elecCreators = elecCreators + 1;
        electrons = electrons - elecCreatorCost;
        document.getElementById('elecCreators').innerHTML = elecCreators;
        document.getElementById('electrons').innerHTML = elecrons;
    };
    var nextelecCreatorCost = Math.floor(10 * Math.pow(1.1,elecCreators));
    document.getElementById('elecCreatorCost').innerHTML = nextelecCreatorCost;

};

function HCreator(){
    var HCreatorCost = Math.floor(10 * Math.pow(1.1,HCreators));
    if(Hydrogen >= HCreatorCost){
        HCreators = HCreators + 1;
        Hydrogen = Hydrogen - HCreatorCost;
        document.getElementById('HCreators').innerHTML = HCreators;
        document.getElementById('H').innerHTML = Hydrogen;
    };
    var nextHCreatorCost = Math.floor(10 * Math.pow(1.1,HCreators));
    document.getElementById('HCreatorCost').innerHTML = nextHCreatorCost;

};

window.setInterval(function(){

	protClick(protCreators);
	neutClick(neutCreators);
	elecClick(elecCreators);
	HydrClick(HCreators);

}, 1000);
<|endoftext|>


<commit_before>/* jshint -W079 */ // prevent redefinition of $ warning

'use strict';
// gulp
var gulp = require('gulp');
var paths = gulp.paths;
var options = gulp.options;
// plugins
var $ = require('gulp-load-plugins')();
// modules
var wiredep = require('wiredep');
var mainBowerFiles = require('main-bower-files');

// inject app/**/*.js, bower components, css into index.html
// inject environment variables into config.js constant
gulp.task('inject-all', ['styles', 'wiredep', 'bower-fonts', 'environment'], function () {

  return gulp.src('app/index.html')
    .pipe(
      $.inject( // app/**/*.js files
        gulp.src(paths.jsFiles)
          .pipe($.plumber()) // use plumber so watch can start despite js errors
          .pipe($.naturalSort())
          .pipe($.angularFilesort()),
        {relative: true}))
    .pipe(
      $.inject( // inject compiled css
        gulp.src('.tmp/*/styles/main.css', {read: false}),
        {
          ignorePath: '../.tmp',
          relative: true,
        }))
    .pipe(gulp.dest('app'));
});

// build styles to tmp
gulp.task('styles', function () {
  // compile css starting from each module's main.scss
  return gulp.src('app/**/styles/main.scss')
    .pipe($.plumber())
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10,
      'sourcemap=none': true // disable sourcemap to avoid unkown word error
      // issue (should be fixed when 1.0.0 is stable: https://github.com/sindresorhus/gulp-autoprefixer/issues/20
      // solution: http://stackoverflow.com/questions/26979433/gulp-with-gulp-ruby-sass-error-style-css-map31-unknown-word
    }))
    .pipe($.autoprefixer({ browsers: ['last 2 version'], remove: false}))
    .pipe(gulp.dest('.tmp/'));
});

// inject bower components
gulp.task('wiredep', function () {
  return gulp.src('app/index.html') // into index.html
    .pipe(wiredep.stream({exclude: ['bower_components/ionic/release/css']}))
       // exclude ionic scss since we're using ionic sass
    .pipe(gulp.dest('app'));
});

// copy bower-fonts to do app/main/assets/fonts
gulp.task('bower-fonts', function () {
  var fontFiles = mainBowerFiles({filter: /\.(eot|svg|ttf|woff)/i})
    .concat('app/main/assets/fonts/**/*');
  return gulp.src(fontFiles)
    .pipe(gulp.dest('app/main/assets/fonts'));
});

gulp.task('environment', function () {
  return gulp.src('app/*/constants/config-const.js')
    .pipe(
      $.inject(
        gulp.src('app/main/constants/env-' + options.env + '.json'),
        {
          starttag: '/*inject-env*/',
          endtag: '/*endinject*/',
          transform: function (filePath, file) {
            var json;
            try {
              json = JSON.parse(file.contents.toString('utf8'));
            }
            catch (e) {
              console.log(e);
            }

            if (json) {
              json = JSON.stringify(json, null, 2);
              // replace all doublequotes with singlequotes
              json = json.replace(/\"/g, '\'');
              // remove first and last line curly braces
              json = json.replace(/^\{\n/, '').replace(/\n\}$/, '');
              // remove first level of indentation
              json = json.replace(/^  /g, '');
            }
            return json;
          }
        }))
    .pipe(gulp.dest('app/'));
});
<commit_msg>work on #172 - nested objects in environments<commit_after>/* jshint -W079 */ // prevent redefinition of $ warning

'use strict';
// gulp
var gulp = require('gulp');
var paths = gulp.paths;
var options = gulp.options;
// plugins
var $ = require('gulp-load-plugins')();
// modules
var wiredep = require('wiredep');
var mainBowerFiles = require('main-bower-files');

// inject app/**/*.js, bower components, css into index.html
// inject environment variables into config.js constant
gulp.task('inject-all', ['styles', 'wiredep', 'bower-fonts', 'environment'], function () {

  return gulp.src('app/index.html')
    .pipe(
      $.inject( // app/**/*.js files
        gulp.src(paths.jsFiles)
          .pipe($.plumber()) // use plumber so watch can start despite js errors
          .pipe($.naturalSort())
          .pipe($.angularFilesort()),
        {relative: true}))
    .pipe(
      $.inject( // inject compiled css
        gulp.src('.tmp/*/styles/main.css', {read: false}),
        {
          ignorePath: '../.tmp',
          relative: true,
        }))
    .pipe(gulp.dest('app'));
});

// build styles to tmp
gulp.task('styles', function () {
  // compile css starting from each module's main.scss
  return gulp.src('app/**/styles/main.scss')
    .pipe($.plumber())
    .pipe($.rubySass({
      style: 'expanded',
      precision: 10,
      'sourcemap=none': true // disable sourcemap to avoid unkown word error
      // issue (should be fixed when 1.0.0 is stable: https://github.com/sindresorhus/gulp-autoprefixer/issues/20
      // solution: http://stackoverflow.com/questions/26979433/gulp-with-gulp-ruby-sass-error-style-css-map31-unknown-word
    }))
    .pipe($.autoprefixer({ browsers: ['last 2 version'], remove: false}))
    .pipe(gulp.dest('.tmp/'));
});

// inject bower components
gulp.task('wiredep', function () {
  return gulp.src('app/index.html') // into index.html
    .pipe(wiredep.stream({exclude: ['bower_components/ionic/release/css']}))
       // exclude ionic scss since we're using ionic sass
    .pipe(gulp.dest('app'));
});

// copy bower-fonts to do app/main/assets/fonts
gulp.task('bower-fonts', function () {
  var fontFiles = mainBowerFiles({filter: /\.(eot|svg|ttf|woff)/i})
    .concat('app/main/assets/fonts/**/*');
  return gulp.src(fontFiles)
    .pipe(gulp.dest('app/main/assets/fonts'));
});

gulp.task('environment', function () {
  return gulp.src('app/*/constants/config-const.js')
    .pipe(
      $.inject(
        gulp.src('app/main/constants/env-' + options.env + '.json'),
        {
          starttag: '/*inject-env*/',
          endtag: '/*endinject*/',
          transform: function (filePath, file) {
            var json;
            try {
              json = JSON.parse(file.contents.toString('utf8'));
            }
            catch (e) {
              console.log(e);
            }

            if (json) {
              json = JSON.stringify(json, null, 2);
              // replace all doublequotes with singlequotes
              json = json.replace(/\"/g, '\'');
              // remove first and last line curly braces
              json = json.replace(/^\{\n/, '').replace(/\n\}$/, '');
              // remove first level of indentation
              json = json.replace(/^  /g, '');    // first line
              json = json.replace(/\n  /g, '\n'); // all other lines
            }
            return json;
          }
        }))
    .pipe(gulp.dest('app/'));
});
<|endoftext|>