<commit_before>Spaz.AccountPrefs = {};

Spaz.AccountPrefs.init = function(){

	this.spaz_acc = Spaz.Prefs._accounts;

	this.metavals = ['twitter-api-accesskey', 'twitter-api-base-url', 'twitter-disable-direct-posting', 'services-pingfm-userappkey', 'services-pingfm-enabled', 'services-pingfm-sendreplies', 'services-shortie-email', 'services-shortie-secretkey', 'services-twitpic-sharepassword'];

	this.checkboxes = ['twitter-disable-direct-posting', 'services-pingfm-enabled', 'services-pingfm-sendreplies', 'services-twitpic-sharepassword'];

	var that = this,
	    $accountList    = $('#account-list'),
	    $accountDetails = $('#account-details'),
	    $idEdit         = $('#id_edit'),
	    $username       = $('#username'),
	    $password       = $('#password'),
	    $accountType    = $('#account-type'),
	    $saveAccountButton    = $('#save_account_button'),
	    $cancelAccountButton  = $('#cancel_account_button');

	$().ready(function(){

		/*
		 bind click on account
		 */
		$accountList.change(function(e){
			var account_id = $(this).val();
			Spaz.AccountPrefs.setAccount(account_id);
		});

		/*
		 bind [+] button to popup
		 */
		$('.add-account').click(function(){

			sch.debug('ADD BUTTON CLICKED');

			$saveAccountButton.unbind('click');
			$cancelAccountButton.unbind('click');

			sch.debug('SHOW #account-details');
			Spaz.UI.openPopboxInline('#account-details');

			sch.debug($accountDetails.get(0).outerHTML);

			/*
			 populate form
			 */
			$idEdit.val('');
			$username.val('');
			$password.val('');
			$accountType.val(SPAZCORE_ACCOUNT_TWITTER);

			/*
			 populate meta
			 */
			for (var i = 0; i < that.metavals.length; i++) {
				if (that.checkboxes.indexOf(that.metavals[i]) !== -1) { // is a checkbox
					$('#' + that.metavals[i]).attr('checked', false);
				} else {
					$('#' + that.metavals[i]).val('');
				}

			};

			/*
			 bind save button
			 */
			$saveAccountButton.click(function(){
				var newaccid = Spaz.AccountPrefs.add($username.val(), $password.val(), $accountType.val()).id;
				var val;
				for (var i = 0; i < that.metavals.length; i++) {
					if (that.checkboxes.indexOf(that.metavals[i]) !== -1) { // is a checkbox
						val = !!($('#' + that.metavals[i] + ':checked').length) || false;
					}
					else {
						val = $('#' + that.metavals[i]).val();
					}
					that.spaz_acc.setMeta(newaccid, that.metavals[i], val);
				};

				$accountList.val(newaccid);
				Spaz.AccountPrefs.setAccount(newaccid);
				Spaz.UI.closePopbox();
			});

			/*
			 bind cancel button
			 */
			$cancelAccountButton.click(function(){
				Spaz.UI.closePopbox();
			});
		});

		/*
		 bind the [-] button
		 */
		$('#del-account').click(function(){
			var id = Spaz.AccountPrefs.getSelectedId();
			if (id) {
				var deleted = that.spaz_acc.remove(id);
				$('option[value="' + id + '"]').remove();
				Spaz.AccountPrefs.toggleCTA();
				Spaz.Timelines.toggleNewUserCTAs();
			}
			else {
				sch.error('Nothing selected to delete');
			}
		});

		/*
		 bind the [edit] button to modal
		 */
		$('#edit-account').click(function(){

			$saveAccountButton.unbind('click');
			$cancelAccountButton.unbind('click');

			var id = Spaz.AccountPrefs.getSelectedId();
			if (id) {
				var editing = that.spaz_acc.get(id);

				Spaz.UI.openPopboxInline('#account-details');

				/*
				 populate form
				 */
				$idEdit.val(editing.id);
				$username.val(editing.username);
				$password.val(editing.password);
				$accountType.val(editing.type);

				/*
				 populate meta
				 */
				for (var i = 0; i < that.metavals.length; i++) {
					var val = that.spaz_acc.getMeta(editing.id, that.metavals[i]);
					if (that.checkboxes.indexOf(that.metavals[i]) !== -1) { // is a checkbox
						$('#' + that.metavals[i]).attr('checked', !!(val));
					}
					else {
						$('#' + that.metavals[i]).val(that.spaz_acc.getMeta(editing.id, that.metavals[i]));
					}

				};

				/*
				 bind save button
				 */
				$saveAccountButton.click(function(){
					var editedaccid = Spaz.AccountPrefs.edit($idEdit.val(), {
						'username': $username.val(),
						'password': $password.val(),
						'type': $accountType.val()
					}).id;

					var val;
					for (var i = 0, iMax = that.metavals.length; i < iMax; i++) {
						if (that.checkboxes.indexOf(that.metavals[i]) !== -1) {
							val = !!($('#' + that.metavals[i] + ':checked').length) || false;
						}
						else {
							val = $('#' + that.metavals[i]).val();
						}
						that.spaz_acc.setMeta(editedaccid, that.metavals[i], val);
					};

					Spaz.UI.closePopbox();
				});

				/*
				 bind cancel button
				 */
				$cancelAccountButton.click(function(){
					Spaz.UI.closePopbox();

				});

			}
			else {
				sch.error('Nothing selected to edit');
			}

		});

		/*
		 if "custom" is set for type, showthe api-base-url row
		 */
		$accountType.change(function(){
			$('#twitter-api-base-url-row').toggle($accountType.val() === 'custom');
		});

		sch.debug('LOADED USERS:');
		sch.debug(sch.enJSON(Spaz.AccountPrefs.spaz_acc._accounts));

		/*
		 Load data into GUI
		 */
		$accountList.append((function(){
			var accts = Spaz.AccountPrefs.spaz_acc._accounts, acct,
			    options = [];
			for(var i = 0, iMax = accts.length; i < iMax; i++){
				acct = accts[i];
				options.push(
					'<option' +
						((acct.username === Spaz.Prefs.getUsername() &&
							acct.type === Spaz.Prefs.getAccountType()) ?
							' selected' : '') +
					    ' value="' + acct.id + '">' +
						acct.username + '@' + acct.type +
					'</option>'
				);
			}
			return options.join('');
		})());

		// Clean up UI
		$accountDetails.hide();
		$('#twitter-api-base-url-row').hide();
		Spaz.AccountPrefs.toggleCTA();

	});

};

Spaz.AccountPrefs.setAccount = function(account_id) {

	if (account_id != Spaz.Prefs.getCurrentUserId()) {
		sch.trigger('before_account_switched', document, Spaz.Prefs.getCurrentAccount());

		Spaz.Prefs.setCurrentUserId(account_id);

		sch.trigger('account_switched', document, Spaz.Prefs.getCurrentAccount());
	}
};

Spaz.AccountPrefs.add = function(username, password, type){
	var newacct = Spaz.AccountPrefs.spaz_acc.add(username, password, type);
	sch.debug(newacct);
	var html = "<option value='" + newacct.id + "'>" + newacct.username + "@" + newacct.type + "</option>";
	$('#account-list').append(html);
	Spaz.AccountPrefs.toggleCTA();
	Spaz.Timelines.toggleNewUserCTAs();
	sch.debug("Added:");
	sch.debug(newacct);
	return newacct;
};

Spaz.AccountPrefs.edit = function(id, acctobj){
	var savedacct = Spaz.AccountPrefs.spaz_acc.update(id, acctobj);
	sch.debug(savedacct);
	$('#account-list option[value="' + savedacct.id + '"]').html(savedacct.username + "@" + savedacct.type);
	sch.debug("Edited:");
	sch.debug(savedacct);
	return savedacct;
};

Spaz.AccountPrefs.toggleCTA = function(){
	// Show the special CTA if this is a new Spaz user

	// var anyAccts = Spaz.DB.getUserCount() <= 0,
	var anyAccts  = Spaz.AccountPrefs.spaz_acc.getAll().length > 0,
	    $fieldset = $('#account-list-fieldset');
	$fieldset.find('div.formrow.cta').toggle(!anyAccts);
	$fieldset.find('div.formrow:not(.cta)').toggle(anyAccts);
		// `.siblings()` didn't chain properly here for some reason.
};

Spaz.AccountPrefs.getSelectedId = function(){
	return $('#account-list').val() || null;
};
<commit_msg>Autofocused username field when account details popbox opens (ticket 58)<commit_after>Spaz.AccountPrefs = {};

Spaz.AccountPrefs.init = function(){

	this.spaz_acc = Spaz.Prefs._accounts;

	this.metavals = ['twitter-api-accesskey', 'twitter-api-base-url', 'twitter-disable-direct-posting', 'services-pingfm-userappkey', 'services-pingfm-enabled', 'services-pingfm-sendreplies', 'services-shortie-email', 'services-shortie-secretkey', 'services-twitpic-sharepassword'];

	this.checkboxes = ['twitter-disable-direct-posting', 'services-pingfm-enabled', 'services-pingfm-sendreplies', 'services-twitpic-sharepassword'];

	var that = this,
	    $accountList    = $('#account-list'),
	    $accountDetails = $('#account-details'),
	    $idEdit         = $('#id_edit'),
	    $username       = $('#username'),
	    $password       = $('#password'),
	    $accountType    = $('#account-type'),
	    $saveAccountButton    = $('#save_account_button'),
	    $cancelAccountButton  = $('#cancel_account_button');

	$().ready(function(){

		/*
		 bind click on account
		 */
		$accountList.change(function(e){
			var account_id = $(this).val();
			Spaz.AccountPrefs.setAccount(account_id);
		});

		/*
		 bind [+] button to popup
		 */
		$('.add-account').click(function(){

			sch.debug('ADD BUTTON CLICKED');

			$saveAccountButton.unbind('click');
			$cancelAccountButton.unbind('click');

			sch.debug('SHOW #account-details');
			Spaz.UI.openPopboxInline('#account-details');

			sch.debug($accountDetails.get(0).outerHTML);

			/*
			 populate form
			 */
			$idEdit.val('');
			$username.val('').focus();
			$password.val('');
			$accountType.val(SPAZCORE_ACCOUNT_TWITTER);

			/*
			 populate meta
			 */
			for (var i = 0; i < that.metavals.length; i++) {
				if (that.checkboxes.indexOf(that.metavals[i]) !== -1) { // is a checkbox
					$('#' + that.metavals[i]).attr('checked', false);
				} else {
					$('#' + that.metavals[i]).val('');
				}

			};

			/*
			 bind save button
			 */
			$saveAccountButton.click(function(){
				var newaccid = Spaz.AccountPrefs.add($username.val(), $password.val(), $accountType.val()).id;
				var val;
				for (var i = 0; i < that.metavals.length; i++) {
					if (that.checkboxes.indexOf(that.metavals[i]) !== -1) { // is a checkbox
						val = !!($('#' + that.metavals[i] + ':checked').length) || false;
					}
					else {
						val = $('#' + that.metavals[i]).val();
					}
					that.spaz_acc.setMeta(newaccid, that.metavals[i], val);
				};

				$accountList.val(newaccid);
				Spaz.AccountPrefs.setAccount(newaccid);
				Spaz.UI.closePopbox();
			});

			/*
			 bind cancel button
			 */
			$cancelAccountButton.click(function(){
				Spaz.UI.closePopbox();
			});
		});

		/*
		 bind the [-] button
		 */
		$('#del-account').click(function(){
			var id = Spaz.AccountPrefs.getSelectedId();
			if (id) {
				var deleted = that.spaz_acc.remove(id);
				$('option[value="' + id + '"]').remove();
				Spaz.AccountPrefs.toggleCTA();
				Spaz.Timelines.toggleNewUserCTAs();
			}
			else {
				sch.error('Nothing selected to delete');
			}
		});

		/*
		 bind the [edit] button to modal
		 */
		$('#edit-account').click(function(){

			$saveAccountButton.unbind('click');
			$cancelAccountButton.unbind('click');

			var id = Spaz.AccountPrefs.getSelectedId();
			if (id) {
				var editing = that.spaz_acc.get(id);

				Spaz.UI.openPopboxInline('#account-details');

				/*
				 populate form
				 */
				$idEdit.val(editing.id);
				$username.val(editing.username).focus();
				$password.val(editing.password);
				$accountType.val(editing.type);

				/*
				 populate meta
				 */
				for (var i = 0; i < that.metavals.length; i++) {
					var val = that.spaz_acc.getMeta(editing.id, that.metavals[i]);
					if (that.checkboxes.indexOf(that.metavals[i]) !== -1) { // is a checkbox
						$('#' + that.metavals[i]).attr('checked', !!(val));
					}
					else {
						$('#' + that.metavals[i]).val(that.spaz_acc.getMeta(editing.id, that.metavals[i]));
					}

				};

				/*
				 bind save button
				 */
				$saveAccountButton.click(function(){
					var editedaccid = Spaz.AccountPrefs.edit($idEdit.val(), {
						'username': $username.val(),
						'password': $password.val(),
						'type': $accountType.val()
					}).id;

					var val;
					for (var i = 0, iMax = that.metavals.length; i < iMax; i++) {
						if (that.checkboxes.indexOf(that.metavals[i]) !== -1) {
							val = !!($('#' + that.metavals[i] + ':checked').length) || false;
						}
						else {
							val = $('#' + that.metavals[i]).val();
						}
						that.spaz_acc.setMeta(editedaccid, that.metavals[i], val);
					};

					Spaz.UI.closePopbox();
				});

				/*
				 bind cancel button
				 */
				$cancelAccountButton.click(function(){
					Spaz.UI.closePopbox();

				});

			}
			else {
				sch.error('Nothing selected to edit');
			}

		});

		/*
		 if "custom" is set for type, showthe api-base-url row
		 */
		$accountType.change(function(){
			$('#twitter-api-base-url-row').toggle($accountType.val() === 'custom');
		});

		sch.debug('LOADED USERS:');
		sch.debug(sch.enJSON(Spaz.AccountPrefs.spaz_acc._accounts));

		/*
		 Load data into GUI
		 */
		$accountList.append((function(){
			var accts = Spaz.AccountPrefs.spaz_acc._accounts, acct,
			    options = [];
			for(var i = 0, iMax = accts.length; i < iMax; i++){
				acct = accts[i];
				options.push(
					'<option' +
						((acct.username === Spaz.Prefs.getUsername() &&
							acct.type === Spaz.Prefs.getAccountType()) ?
							' selected' : '') +
					    ' value="' + acct.id + '">' +
						acct.username + '@' + acct.type +
					'</option>'
				);
			}
			return options.join('');
		})());

		// Clean up UI
		$accountDetails.hide();
		$('#twitter-api-base-url-row').hide();
		Spaz.AccountPrefs.toggleCTA();

	});

};

Spaz.AccountPrefs.setAccount = function(account_id) {

	if (account_id != Spaz.Prefs.getCurrentUserId()) {
		sch.trigger('before_account_switched', document, Spaz.Prefs.getCurrentAccount());

		Spaz.Prefs.setCurrentUserId(account_id);

		sch.trigger('account_switched', document, Spaz.Prefs.getCurrentAccount());
	}
};

Spaz.AccountPrefs.add = function(username, password, type){
	var newacct = Spaz.AccountPrefs.spaz_acc.add(username, password, type);
	sch.debug(newacct);
	var html = "<option value='" + newacct.id + "'>" + newacct.username + "@" + newacct.type + "</option>";
	$('#account-list').append(html);
	Spaz.AccountPrefs.toggleCTA();
	Spaz.Timelines.toggleNewUserCTAs();
	sch.debug("Added:");
	sch.debug(newacct);
	return newacct;
};

Spaz.AccountPrefs.edit = function(id, acctobj){
	var savedacct = Spaz.AccountPrefs.spaz_acc.update(id, acctobj);
	sch.debug(savedacct);
	$('#account-list option[value="' + savedacct.id + '"]').html(savedacct.username + "@" + savedacct.type);
	sch.debug("Edited:");
	sch.debug(savedacct);
	return savedacct;
};

Spaz.AccountPrefs.toggleCTA = function(){
	// Show the special CTA if this is a new Spaz user

	// var anyAccts = Spaz.DB.getUserCount() <= 0,
	var anyAccts  = Spaz.AccountPrefs.spaz_acc.getAll().length > 0,
	    $fieldset = $('#account-list-fieldset');
	$fieldset.find('div.formrow.cta').toggle(!anyAccts);
	$fieldset.find('div.formrow:not(.cta)').toggle(anyAccts);
		// `.siblings()` didn't chain properly here for some reason.
};

Spaz.AccountPrefs.getSelectedId = function(){
	return $('#account-list').val() || null;
};
<|endoftext|>


<commit_before>'use strict';

const { run } = require('../utils/test-utils');
const pkgJSON = require('../../package.json');

describe('version flag with multiple arguments', () => {
    it('outputs version with mixed syntax', () => {
        const { stdout, stderr } = run(__dirname, ['--version', '--target', 'browser']);
        expect(stdout).toContain(pkgJSON.version);
        expect(stderr).toHaveLength(0);
    });

    it('outputs version with multiple commands', () => {
        const { stdout, stderr } = run(__dirname, ['version', 'init']);
        expect(stdout).toContain(pkgJSON.version);
        expect(stderr).toHaveLength(0);
    });

    it('does not output version with help command', () => {
        const { stdout, stderr } = run(__dirname, ['version', 'help']);
        expect(stdout).not.toContain(pkgJSON.version);

        const uniqueIdentifier = 'Made with ♥  by the webpack team';
        expect(stdout).toContain(uniqueIdentifier);
        expect(stderr).toHaveLength(0);
    });

    it('does not output version with help dashed', () => {
        const { stdout, stderr } = run(__dirname, ['version', '--help']);
        expect(stdout).not.toContain(pkgJSON.version);

        const uniqueIdentifier = 'Made with ♥  by the webpack team';
        expect(stdout).toContain(uniqueIdentifier);
        expect(stderr).toHaveLength(0);
    });

    it('outputs version with multiple dashed args and has precidence', () => {
        const { stdout, stderr } = run(__dirname, ['--target', 'browser', '--version']);
        expect(stdout).toContain(pkgJSON.version);
        expect(stderr).toHaveLength(0);
    });
});
<commit_msg>fix: typo fix<commit_after>'use strict';

const { run } = require('../utils/test-utils');
const pkgJSON = require('../../package.json');

describe('version flag with multiple arguments', () => {
    it('outputs version with mixed syntax', () => {
        const { stdout, stderr } = run(__dirname, ['--version', '--target', 'browser']);
        expect(stdout).toContain(pkgJSON.version);
        expect(stderr).toHaveLength(0);
    });

    it('outputs version with multiple commands', () => {
        const { stdout, stderr } = run(__dirname, ['version', 'init']);
        expect(stdout).toContain(pkgJSON.version);
        expect(stderr).toHaveLength(0);
    });

    it('does not output version with help command', () => {
        const { stdout, stderr } = run(__dirname, ['version', 'help']);
        expect(stdout).not.toContain(pkgJSON.version);

        const uniqueIdentifier = 'Made with ♥  by the webpack team';
        expect(stdout).toContain(uniqueIdentifier);
        expect(stderr).toHaveLength(0);
    });

    it('does not output version with help dashed', () => {
        const { stdout, stderr } = run(__dirname, ['version', '--help']);
        expect(stdout).not.toContain(pkgJSON.version);

        const uniqueIdentifier = 'Made with ♥  by the webpack team';
        expect(stdout).toContain(uniqueIdentifier);
        expect(stderr).toHaveLength(0);
    });

    it('outputs version with multiple dashed args and has precedence', () => {
        const { stdout, stderr } = run(__dirname, ['--target', 'browser', '--version']);
        expect(stdout).toContain(pkgJSON.version);
        expect(stderr).toHaveLength(0);
    });
});
<|endoftext|>


<commit_before>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var Plugin = require('../../base/plugin');
var StatsEvents = require('./stats_events');
var $ = require("jquery");

var StatsPlugin = Plugin.extend({
  name: 'stats',
  type: 'stats',
  initialize: function(options) {
    console.log("initializing stats");
    StatsPlugin.super('initialize').call(this, options);
    this.container.with(StatsEvents);
    this.setInitialAttrs();
    this.reportInterval = options.reportInterval || 5000;
    this.state = "IDLE";
  },
  bindEvents: function() {
    this.listenTo(this.container, 'container:play', this.onPlay);
    this.listenTo(this.container, 'container:stop', this.onStop);
    this.listenTo(this.container, 'container:destroyed', this.onStop);
    this.listenTo(this.container, 'container:setreportinterval', this.setReportInterval);
    this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
    this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull);
    this.listenTo(this.container, 'container:stats:add', this.onStatsAdd);
    this.listenTo(this.container.playback, 'playback:stats:add', this.onStatsAdd);
  },
  setReportInterval: function(reportInterval) {
    this.reportInterval = reportInterval;
  },
  setInitialAttrs: function() {
    console.log("setou aqui initial attrs");
    this.firstPlay = true;
    this.startupTime = 0;
    this.rebufferingTime = 0;
    this.watchingTime = 0;
    this.rebuffers = 0;
    this.externalMetrics = {};
  },
  onPlay: function() {
    this.state = "PLAYING";
    this.watchingTimeInit = Date.now();
    this.intervalId = setInterval(this.report.bind(this), this.reportInterval);
  },
  onStop: function() {
    clearInterval(this.intervalId);
    this.state = "STOPPED";
  },
  onBuffering: function() {
    if (this.firstPlay) {
      console.log("first buffer");
      this.startupTimeInit = Date.now();
    } else {
      console.log("not first buffer");
      this.rebufferingTimeInit = Date.now();
    }
    this.state = "BUFFERING";
    this.rebuffers++;
  },
  onBufferFull: function() {
    if (this.state !== "BUFFERING") return;

    if (this.firstPlay) {
      console.log("first buffer full");
      this.firstPlay = false;
      this.startupTime = Date.now() - this.startupTimeInit;
      this.watchingTimeInit = Date.now();
    } else {
      console.log("not first buffer full");
      this.rebufferingTime += this.getRebufferingTime();
    }
    this.rebufferingTimeInit = undefined;
    this.state = "PLAYING";
  },
  getRebufferingTime: function() {
    return Date.now() - this.rebufferingTimeInit;
  },
  getWatchingTime: function() {
    var totalTime = (Date.now() - this.watchingTimeInit);
    return totalTime - this.rebufferingTime - this.startupTime;
  },
  isRebuffering: function() {
    return !!this.rebufferingTimeInit;
  },
  onStatsAdd: function(metric) {
    $.extend(this.externalMetrics, metric);
  },
  getStats: function() {
    var metrics = {
      startupTime:     this.startupTime,
      rebuffers:       this.rebuffers,
      rebufferingTime: this.isRebuffering()? this.rebufferingTime + this.getRebufferingTime(): this.rebufferingTime,
      watchingTime:    this.isRebuffering()? this.getWatchingTime() - this.getRebufferingTime(): this.getWatchingTime()
    };
    $.extend(metrics, this.externalMetrics);
    return metrics;
  },
  report: function() {
    console.log(this.getStats());
    this.container.statsReport(this.getStats());
  }
});

module.exports = StatsPlugin;
<commit_msg>stats: remove comments<commit_after>// Copyright 2014 Globo.com Player authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.

var Plugin = require('../../base/plugin');
var StatsEvents = require('./stats_events');
var $ = require("jquery");

var StatsPlugin = Plugin.extend({
  name: 'stats',
  type: 'stats',
  initialize: function(options) {
    StatsPlugin.super('initialize').call(this, options);
    this.container.with(StatsEvents);
    this.setInitialAttrs();
    this.reportInterval = options.reportInterval || 5000;
    this.state = "IDLE";
  },
  bindEvents: function() {
    this.listenTo(this.container, 'container:play', this.onPlay);
    this.listenTo(this.container, 'container:stop', this.onStop);
    this.listenTo(this.container, 'container:destroyed', this.onStop);
    this.listenTo(this.container, 'container:setreportinterval', this.setReportInterval);
    this.listenTo(this.container, 'container:state:buffering', this.onBuffering);
    this.listenTo(this.container, 'container:state:bufferfull', this.onBufferFull);
    this.listenTo(this.container, 'container:stats:add', this.onStatsAdd);
    this.listenTo(this.container.playback, 'playback:stats:add', this.onStatsAdd);
  },
  setReportInterval: function(reportInterval) {
    this.reportInterval = reportInterval;
  },
  setInitialAttrs: function() {
    this.firstPlay = true;
    this.startupTime = 0;
    this.rebufferingTime = 0;
    this.watchingTime = 0;
    this.rebuffers = 0;
    this.externalMetrics = {};
  },
  onPlay: function() {
    this.state = "PLAYING";
    this.watchingTimeInit = Date.now();
    this.intervalId = setInterval(this.report.bind(this), this.reportInterval);
  },
  onStop: function() {
    clearInterval(this.intervalId);
    this.state = "STOPPED";
  },
  onBuffering: function() {
    if (this.firstPlay) {
      this.startupTimeInit = Date.now();
    } else {
      this.rebufferingTimeInit = Date.now();
    }
    this.state = "BUFFERING";
    this.rebuffers++;
  },
  onBufferFull: function() {
    if (this.state !== "BUFFERING") return;

    if (this.firstPlay) {
      this.firstPlay = false;
      this.startupTime = Date.now() - this.startupTimeInit;
      this.watchingTimeInit = Date.now();
    } else {
      this.rebufferingTime += this.getRebufferingTime();
    }
    this.rebufferingTimeInit = undefined;
    this.state = "PLAYING";
  },
  getRebufferingTime: function() {
    return Date.now() - this.rebufferingTimeInit;
  },
  getWatchingTime: function() {
    var totalTime = (Date.now() - this.watchingTimeInit);
    return totalTime - this.rebufferingTime - this.startupTime;
  },
  isRebuffering: function() {
    return !!this.rebufferingTimeInit;
  },
  onStatsAdd: function(metric) {
    $.extend(this.externalMetrics, metric);
  },
  getStats: function() {
    var metrics = {
      startupTime:     this.startupTime,
      rebuffers:       this.rebuffers,
      rebufferingTime: this.isRebuffering()? this.rebufferingTime + this.getRebufferingTime(): this.rebufferingTime,
      watchingTime:    this.isRebuffering()? this.getWatchingTime() - this.getRebufferingTime(): this.getWatchingTime()
    };
    $.extend(metrics, this.externalMetrics);
    return metrics;
  },
  report: function() {
    this.container.statsReport(this.getStats());
  }
});

module.exports = StatsPlugin;
<|endoftext|>


<commit_before>// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })

Cypress.Commands.add('setRadioInput', (selector, value) => {
  const selectorValue = value === 'Yes' ? '1' : '0'
  cy.get(`input[name="${selector}"]`).each(($el, index, $list) => {
    if($el.val() === selectorValue) {
      cy.wrap($el).check();
    }
  })
})
<commit_msg>Refactor<commit_after>// ***********************************************
// This example commands.js shows you how to
// create various custom commands and overwrite
// existing commands.
//
// For more comprehensive examples of custom
// commands please read more here:
// https://on.cypress.io/custom-commands
// ***********************************************
//
//
// -- This is a parent command --
// Cypress.Commands.add("login", (email, password) => { ... })
//
//mm
// -- This is a child command --
// Cypress.Commands.add("drag", { prevSubject: 'element'}, (subject, options) => { ... })
//
//
// -- This is a dual command --
// Cypress.Commands.add("dismiss", { prevSubject: 'optional'}, (subject, options) => { ... })
//
//
// -- This will overwrite an existing command --
// Cypress.Commands.overwrite("visit", (originalFn, url, options) => { ... })

Cypress.Commands.add('setRadioInput', (selector, value) => {
  const selectorValue = value === 'Yes' ? '0' : '1'
  cy.get(`#${selector}-${selectorValue}`).check();
})
<|endoftext|>


<commit_before>import { computed } from '@ember/object';
import DS from 'ember-data';
import ENUMS from 'irene/enums';

export default DS.Model.extend({
  name: DS.attr('string'),
  user: DS.belongsTo('user'),
  apiScanStatus: DS.attr('number'),
  project: DS.belongsTo('security/project'),
  analyses: DS.hasMany('security/analysis'),

  analysesSorting: ['risk:desc'],
  sortedAnalyses: computed.sort('analyses', 'analysesSorting'),

  isApiDone: computed('apiScanStatus', function() {
    const apiScanStatus = this.get("apiScanStatus");
    if(apiScanStatus === ENUMS.SCAN_STATUS.COMPLETED) return true;
  }),
  isDynamicDone: DS.attr('boolean'),
  isManualDone: DS.attr('boolean'),
  isStaticDone: DS.attr('boolean'),
  manual: DS.attr('number'),

});
<commit_msg>Removed isManualDone from security File model<commit_after>import { computed } from '@ember/object';
import DS from 'ember-data';
import ENUMS from 'irene/enums';

export default DS.Model.extend({
  name: DS.attr('string'),
  user: DS.belongsTo('user'),
  apiScanStatus: DS.attr('number'),
  project: DS.belongsTo('security/project'),
  analyses: DS.hasMany('security/analysis'),

  analysesSorting: ['risk:desc'],
  sortedAnalyses: computed.sort('analyses', 'analysesSorting'),

  isApiDone: computed('apiScanStatus', function() {
    const apiScanStatus = this.get("apiScanStatus");
    if(apiScanStatus === ENUMS.SCAN_STATUS.COMPLETED) return true;
  }),
  isDynamicDone: DS.attr('boolean'),
  isStaticDone: DS.attr('boolean'),
  manual: DS.attr('number'),

});
<|endoftext|>


<commit_before>
var mime = require( 'mime-lib' )
var buffer = require( './lib/buffer' )

/**
 * Envelope
 * @param {String|Buffer} mail
 */
function Envelope( mail ) {

  if( !(this instanceof Envelope) )
    return new Envelope( mail )

  if( !Buffer.isBuffer( mail ) )
    mail = new Buffer( mail )

  var boundary = buffer.indexOf(
    new Buffer( "\r\n\r\n" ), mail
  )

  boundary = !~boundary
    ? mail.length - 1
    : boundary

  this.original = {
    header: mail.slice( 0, boundary ),
    body:   mail.slice( boundary )
  }

  this.header = Envelope.parseHeader( this.original.header )
  this.parseBody( this.original.body )

}

Envelope.filter = require( './lib/filter' )

Envelope.parse = function( mail ) {
  return new Envelope( mail )
}

/**
 * @param  {Buffer} header
 * @return {Object}
 */
Envelope.parseHeader = function( header ) {

  // Buffer -> String
  header = header.toString()
  // Unfold folded header lines
  header = header.replace( /\r\n\s+/g, ' ' )

  // String -> Array of lines
  var lines = header.split( '\r\n' )
  // Splits line up into a key/value pair
  var pattern = /^([^:]*?)[:]\s*?([^\s].*)/
  var field, key, value, header = {}

  // Convert each line
  for ( i = 0; i < lines.length; i++ ) {
    // Split line up into a key/value pair
    field = pattern.exec( lines[i] )
    // Make the key js-dot-notation accessible
    key   = field[1].toLowerCase().replace( /[^a-z0-9]/gi, '_' )
    value = Envelope.filter( key, field[2].trim() )
    // Store value under it's key
    if ( header[ key ] && header[ key ].push ) {
      header[ key ].push( value )
    } else if ( header[ key ] ) {
      header[ key ] = [ header[ key ], value ]
    } else {
      header[ key ] = value
    }

  }

  return header

}

/**
 * Envelope prototype
 * @type {Object}
 */
Envelope.prototype = {

  /**
   * @param  {Buffer} body
   * @return {Object}
   */
  parseBody: function( body ) {

    body = body.toString()

    var header   = this.header
    var boundary = header.content_type && header.content_type.boundary
    var bounds   = []
    var index    = -1

    if( boundary ) {

      var start = '--' + boundary + '\r\n'
      var end   = '--' + boundary + '--'

      index = body.indexOf( start )

      while( ~index ) {
        bounds.push( index )
        index += start.length
        index  = body.indexOf( start, index )
      }

      var b = start.length
      var c = bounds.length
      var i = 0

      for( ; i < c; i++ ) {
        this[i] = body.slice( bounds[i] + b, bounds[ i + 1 ] )
        this[i] = new Envelope( this[i] )
      }

    } else {

      var isText = header.content_type && /^text/.test( header.content_type.mime )

      this[0] = body.trim()

      // Automatically create a buffer from
      // non-text base64 encoded data
      if( !isText && header.content_transfer_encoding === 'base64' ) {
        this[0] = new Buffer( this[0], 'base64' )
      }

      // Automatically decode text from either
      // base64 or quoted-printable encoding
      if( isText ) {
        if( header.content_transfer_encoding === 'quoted-printable' )
          this[0] = mime.decodeQP( this[0] )
        if( header.content_transfer_encoding === 'base64' )
          this[0] = new Buffer( this[0], 'base64' ).toString()
      }

    }

    return this

  }

}

module.exports = Envelope
<commit_msg>Fixed #3 - Added proper boundary and header field pattern match checks<commit_after>
var mime = require( 'mime-lib' )
var buffer = require( './lib/buffer' )

/**
 * Envelope
 * @param {String|Buffer} mail
 */
function Envelope( mail ) {

  if( !(this instanceof Envelope) )
    return new Envelope( mail )

  if( !Buffer.isBuffer( mail ) )
    mail = new Buffer( mail )

  var boundary = buffer.indexOf(
    new Buffer( "\r\n\r\n" ), mail
  )

  if( !~boundary ) {
    boundary = mail.length - 1
    boundary = boundary < 0 ? 0 : boundary
  }

  this.original = {
    header: mail.slice( 0, boundary ),
    body:   mail.slice( boundary )
  }

  this.header = Envelope.parseHeader( this.original.header )
  this.parseBody( this.original.body )

}

Envelope.filter = require( './lib/filter' )

Envelope.parse = function( mail ) {
  return new Envelope( mail )
}

/**
 * @param  {Buffer} header
 * @return {Object}
 */
Envelope.parseHeader = function( header ) {

  // Buffer -> String
  header = header.toString()
  // Unfold folded header lines
  header = header.replace( /\r\n\s+/g, ' ' )

  // String -> Array of lines
  var lines = header.split( '\r\n' )
  // Splits line up into a key/value pair
  var pattern = /^([^:]*?)[:]\s*?([^\s].*)/
  var field, key, value, header = {}

  // Convert each line
  for ( i = 0; i < lines.length; i++ ) {
    // Split line up into a key/value pair
    if( field = pattern.exec( lines[i] ) ) {
      // Make the key js-dot-notation accessible
      key   = field[1].toLowerCase().replace( /[^a-z0-9]/gi, '_' )
      value = Envelope.filter( key, field[2].trim() )
      // Store value under it's key
      if ( header[ key ] && header[ key ].push ) {
        header[ key ].push( value )
      } else if ( header[ key ] ) {
        header[ key ] = [ header[ key ], value ]
      } else {
        header[ key ] = value
      }
    }
  }

  return header

}

/**
 * Envelope prototype
 * @type {Object}
 */
Envelope.prototype = {

  /**
   * @param  {Buffer} body
   * @return {Object}
   */
  parseBody: function( body ) {

    body = body.toString()

    var header   = this.header
    var boundary = header.content_type && header.content_type.boundary
    var bounds   = []
    var index    = -1

    if( boundary ) {

      var start = '--' + boundary + '\r\n'
      var end   = '--' + boundary + '--'

      index = body.indexOf( start )

      while( ~index ) {
        bounds.push( index )
        index += start.length
        index  = body.indexOf( start, index )
      }

      var b = start.length
      var c = bounds.length

      for( var i = 0; i < c; i++ ) {
        this[i] = body.slice( bounds[i] + b, bounds[ i + 1 ] || void 0 )
        this[i] = new Envelope( this[i] )
      }

    } else {

      var isText = header.content_type && /^text/.test( header.content_type.mime )

      this[0] = body.trim()

      // Automatically create a buffer from
      // non-text base64 encoded data
      if( !isText && header.content_transfer_encoding === 'base64' ) {
        this[0] = new Buffer( this[0], 'base64' )
      }

      // Automatically decode text from either
      // base64 or quoted-printable encoding
      if( isText ) {
        if( header.content_transfer_encoding === 'quoted-printable' )
          this[0] = mime.decodeQP( this[0] )
        if( header.content_transfer_encoding === 'base64' )
          this[0] = new Buffer( this[0], 'base64' ).toString()
      }

    }

    return this

  }

}

module.exports = Envelope
<|endoftext|>


<commit_before>"use strict";

/* global dagreD3 */

angular.module('arethusa.depTree').directive('dependencyTree', function(state, $compile) {
  return {
    restrict: 'A',
    scope: {
      tokens: '=',
      styles: '='
    },
    link: function(scope, element, attrs) {
      // This will be needed once we manage to get this into an isolated scope
      //scope.state = state;

      function tokenPlaceholder(token) {
        return '
' + token.string + '
';
      }

      function edgePlaceholder(token) {
        var label = token.relation.label;
        var id = token.id;
        // tel is for token edge label
        return '
' + label + '
';
      }

      function tokenHasCustomStyling(token) {
        var t = scope.styles[token.id] || {};
        return t.token;
      }

      function applyTokenStyling(childScope, token) {
        childScope.style = scope.styles[token.id].token;
      }

      // Struggling d3 a bit here...
      //
      // Right now this function is responsible for managing the label and
      // edge colors when a custom styling is available.
      //
      // Once the relation plugin is ready, the label will be handled by
      // a directive that is coming from there.
      //
      // The edges will stay the responsibility of this directive - and
      // they are really solved messy right now.
      // Guess one more look into the d3 API is needed.
      function applyCustomStyling() {
        var edges = vis.selectAll("g.edgePath path");
        angular.forEach(scope.styles, function(value, key) {
          if ('label' in value) {
            vis.select('#tel' + key).style({ color: 'red' });
          }
          if ('edge' in value) {
            edges.each(function(d) {
              if (key == d) {
                angular.element(this).css({ 'stroke': 'red', 'stroke-width': '1px' });
              }
            });
          }
        });
      }

      function compiledToken(token) {
        var childScope = scope.$new();
        childScope.token = token;

        // Ugly but working...
        // We replace the colorize value in our token template string.
        // If custom styles are given, we check if one is available for
        // this token. If yes, we use it, otherwise we just pass one
        // undefined which leaves the token unstyled.
        //
        // Without custom styles we let the token itself decide what color
        // it has.
        var style;
        if (scope.styles) {
          if (tokenHasCustomStyling(token)) {
            applyTokenStyling(childScope, token);
          } // else we just stay undefined
          style = 'style';
        } else {
          style = 'true';
        }
        return $compile(tokenHtml.replace('STYLE', style))(childScope)[0];
      }

      var tokenHtml = '\
        \
        \
      ';

      // Creating the node set

      // g will hold the graph and be set when new tokens are loaded,
      // vis will be it's d3 representation
      var g;
      var vis;

      function createNodes() {
        g.addNode("0000", { label: "[-]"});
        angular.forEach(scope.tokens, function(token, index) {
          g.addNode(token.id, { label: tokenPlaceholder(token) });
        });
      }

      function createEdges() {
        angular.forEach(scope.tokens, function(token, index) {
          if (token.head) {
            drawEdge(token);
          }
        });
      }

      function edges() {
        return vis.selectAll("g.edgePath path");
      }

      function nodes() {
        return vis.selectAll("div.node");
      }

      function drawEdge(token) {
        g.addEdge(token.id, token.id, token.head.id, { label: edgePlaceholder(token) });
      }

      function updateEdge(token) {
        g.delEdge(token.id);
        drawEdge(token);
      }

      function resetEdgeStyling() {
        edges().style({ stroke: '#333', 'stroke-width': '0.5px' });
      }

      function createGraph() {
        g = new dagreD3.Digraph();
        createNodes();
        createEdges();
        render();
      }

      // Initialize the graph

      var layout = dagreD3.layout().rankDir("BT");
      var svg = d3.select(element[0]);
      svg.call(d3.behavior.zoom().on("zoom", function() {
         var ev = d3.event;
         svg.select("g")
           .attr("transform",
                 "translate(" + ev.translate + ") scale(" + ev.scale + ")");
      }));

      var renderer = new dagreD3.Renderer();

      function render() {
        vis = svg.select('g');
        renderer.layout(layout).run(g, vis);

        // Customize the graph so that it holds our directives

        nodes().append(function() {
          // This is the element we append to and we created as a placeholder
          // We clear out its text content so that we can display the content
          // of our compiled token directive.
          // The placholder has an id in the format of tphXXXX where XXXX is the id.
          this.textContent = "";
          return compiledToken(scope.tokens[this.id.slice(3)]);
        });

        // Not very elegant, but we don't want marker-end arrowheads right now
        // We also place an token edge path (tep) id on these elements, so that
        // we can access them more easily later on.
        edges().each(function(d) {
          angular.element(this).attr('id', 'tep' + d);
        }).attr('marker-end', '');
      }

      angular.forEach(scope.tokens, function(token, id) {
        var childScope = scope.$new();
        childScope.token = token.id;
        childScope.head =  token.head;
        childScope.$watch('head.id', function(newVal, oldVal) {
          // Very important to do here, otherwise the tree will
          // be render a little often on startup...
          if (newVal !== oldVal) {
            updateEdge(token);
            render();
          }
        });
      });

      scope.$watch('tokens', function(newVal, oldVal) {
        createGraph();
      });

      scope.$watch('styles', function(newVal, oldVal) {
        if (newVal !== oldVal) {
          render();
          if (newVal) {
            applyCustomStyling();
          } else {
            resetEdgeStyling();
          }
        }
      });
    },
    template: '<g transform="translate(20,20)"/>'
  };
});
<commit_msg>Extract labelId and edgeId functions<commit_after>"use strict";

/* global dagreD3 */

angular.module('arethusa.depTree').directive('dependencyTree', function(state, $compile) {
  return {
    restrict: 'A',
    scope: {
      tokens: '=',
      styles: '='
    },
    link: function(scope, element, attrs) {
      // This will be needed once we manage to get this into an isolated scope
      //scope.state = state;

      function tokenPlaceholder(token) {
        return '
' + token.string + '
';
      }

      function edgePlaceholder(token) {
        var label = token.relation.label;
        var id = token.id;
        return '
' + label + '
';
      }

      function tokenHasCustomStyling(token) {
        var t = scope.styles[token.id] || {};
        return t.token;
      }

      function applyTokenStyling(childScope, token) {
        childScope.style = scope.styles[token.id].token;
      }

      // Struggling d3 a bit here...
      //
      // Right now this function is responsible for managing the label and
      // edge colors when a custom styling is available.
      //
      // Once the relation plugin is ready, the label will be handled by
      // a directive that is coming from there.
      //
      // The edges will stay the responsibility of this directive - and
      // they are really solved messy right now.
      // Guess one more look into the d3 API is needed.
      function applyCustomStyling() {
        var edges = vis.selectAll("g.edgePath path");
        angular.forEach(scope.styles, function(value, key) {
          if ('label' in value) {
            vis.select('#' + labelId(key)).style({ color: 'red' });
          }
          if ('edge' in value) {
            edges.each(function(d) {
              if (key == d) {
                angular.element(this).css({ 'stroke': 'red', 'stroke-width': '1px' });
              }
            });
          }
        });
      }

      function compiledToken(token) {
        var childScope = scope.$new();
        childScope.token = token;

        // Ugly but working...
        // We replace the colorize value in our token template string.
        // If custom styles are given, we check if one is available for
        // this token. If yes, we use it, otherwise we just pass one
        // undefined which leaves the token unstyled.
        //
        // Without custom styles we let the token itself decide what color
        // it has.
        var style;
        if (scope.styles) {
          if (tokenHasCustomStyling(token)) {
            applyTokenStyling(childScope, token);
          } // else we just stay undefined
          style = 'style';
        } else {
          style = 'true';
        }
        return $compile(tokenHtml.replace('STYLE', style))(childScope)[0];
      }

      var tokenHtml = '\
        \
        \
      ';

      // Creating the node set

      // g will hold the graph and be set when new tokens are loaded,
      // vis will be it's d3 representation
      var g;
      var vis;

      function createNodes() {
        g.addNode("0000", { label: "[-]"});
        angular.forEach(scope.tokens, function(token, index) {
          g.addNode(token.id, { label: tokenPlaceholder(token) });
        });
      }

      function createEdges() {
        angular.forEach(scope.tokens, function(token, index) {
          if (token.head) {
            drawEdge(token);
          }
        });
      }

      function edges() {
        return vis.selectAll("g.edgePath path");
      }

      function edgeId(id) {
        return 'tep' + id;
      }

      function labelId(id) {
        return 'tel' + id;
      }

      function nodes() {
        return vis.selectAll("div.node");
      }

      function drawEdge(token) {
        g.addEdge(token.id, token.id, token.head.id, { label: edgePlaceholder(token) });
      }

      function updateEdge(token) {
        g.delEdge(token.id);
        drawEdge(token);
      }

      function resetEdgeStyling() {
        edges().style({ stroke: '#333', 'stroke-width': '0.5px' });
      }

      function createGraph() {
        g = new dagreD3.Digraph();
        createNodes();
        createEdges();
        render();
      }

      // Initialize the graph

      var layout = dagreD3.layout().rankDir("BT");
      var svg = d3.select(element[0]);
      svg.call(d3.behavior.zoom().on("zoom", function() {
         var ev = d3.event;
         svg.select("g")
           .attr("transform",
                 "translate(" + ev.translate + ") scale(" + ev.scale + ")");
      }));

      var renderer = new dagreD3.Renderer();

      function render() {
        vis = svg.select('g');
        renderer.layout(layout).run(g, vis);

        // Customize the graph so that it holds our directives

        nodes().append(function() {
          // This is the element we append to and we created as a placeholder
          // We clear out its text content so that we can display the content
          // of our compiled token directive.
          // The placholder has an id in the format of tphXXXX where XXXX is the id.
          this.textContent = "";
          return compiledToken(scope.tokens[this.id.slice(3)]);
        });

        // Not very elegant, but we don't want marker-end arrowheads right now
        // We also place an token edge path (tep) id on these elements, so that
        // we can access them more easily later on.
        edges().each(function(id) {
          angular.element(this).attr('id', edgeId(id));
        }).attr('marker-end', '');
      }

      angular.forEach(scope.tokens, function(token, id) {
        var childScope = scope.$new();
        childScope.token = token.id;
        childScope.head =  token.head;
        childScope.$watch('head.id', function(newVal, oldVal) {
          // Very important to do here, otherwise the tree will
          // be render a little often on startup...
          if (newVal !== oldVal) {
            updateEdge(token);
            render();
          }
        });
      });

      scope.$watch('tokens', function(newVal, oldVal) {
        createGraph();
      });

      scope.$watch('styles', function(newVal, oldVal) {
        if (newVal !== oldVal) {
          render();
          if (newVal) {
            applyCustomStyling();
          } else {
            resetEdgeStyling();
          }
        }
      });
    },
    template: '<g transform="translate(20,20)"/>'
  };
});
<|endoftext|>


<commit_before>function main(){

    /**
     * Examples for using the parser:
     * var parser = new Parser("storagefacility.xml");
     * var parser = new Parser("sourcefacility.xml");
	 * var parser = new Parser("recipereactor.xml");
     * var parser = new Parser("file:///home/scopatz/cyclus/src/Models/Facility/StorageFacility/StorageFacility.rng");
     */
    var parser = new Parser("file:///C:/Users/Kevin/Documents/GitHub/core/src/Models/Facility/SourceFacility/SourceFacility.rng");

    var parsedObj = parser.parseObj();
    parser.printObject(parsedObj, 0);
}

function mainGather(){

    /**
     * Examples for using mainGather
     * gatherSchemas('/home/scopatz/cyclus')
     * gatherSchemas('../../cyclus')
     * gatherSchemas('http://raw.github.com/cyclus/core/master/src/Models/Facility/StorageFacility/StorageFacility.rng');
     */
    gatherSchemas('file:///C:/Users/Kevin/Documents/GitHub/core');

}

function cycicXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        var xhttp = new XMLHttpRequest()
    }

    /** IE 5/6 */
    else {
        var xhttp = new ActiveXObject("Microsoft.XMLHTTP")
    }
    return xhttp
}

/**
 * Parser Class
 */

function Parser(word){
    this.currentIndex = new Array();
    this.jsObjName = new Array();
    this.elementTrace = new Array();
    this.file = word;
}

Parser.prototype.speak = function() {
    document.write(this.word);
}

/** Take XML and convert to JS object to be printed out. */
Parser.prototype.parseObj = function() {
    if (this.file.URL == '') {
        var x = this.file.childNodes[0].childNodes;
    }
    else{
        var xhttp = cycicXMLHttpRequest()
        xhttp.open("GET", this.file, false);
        xhttp.send();
        xmlDoc=xhttp.responseXML;

        var x = xmlDoc.childNodes[0].childNodes;
    }

    /**
     * First, start looking for the main parent name by searching for the
     * 'define' tag
     */
    for(n=0; n<x.length; n++){
    /** If found, start printing out the children */
        if (x[n].nodeName === 'define'){
            var elements = x[n].childNodes[1].childNodes;
            this.jsObjName[x[n].childNodes[1].getAttribute('name')] = {};
            this.jsObjName[x[n].childNodes[1].getAttribute('name')] =
                this.parseObject(elements);
        }
    }
    return this.jsObjName;
}

Parser.prototype.parseObject = function(a){
    var spaces = new Array();
    result = {};
    for (i=0; i<a.length; i++){

        /** Extract only the element, not the text objects */
        if(a[i].nodeName != '#text'){
            if(a[i].nodeName != '#comment'){
                var currentElement = a[i];

                /** If the object has a 'name' attribute, print it */
                if(currentElement.getAttribute('name')){
                    this.currentIndex.push(i);
                    result[currentElement.getAttribute('name')] = {};
                    this.elementTrace.push(result);
                    tempList = this.parseObject(currentElement.childNodes);
                    result = this.elementTrace.pop(result);
                    result[currentElement.getAttribute('name')] = tempList;

                    i = this.currentIndex.pop(i);
				}

                /** If the object has a 'type' attribute, print it */
                else if(currentElement.getAttribute('type')){
                    this.currentIndex.push(i);

                    result[currentElement.getAttribute('type')] = {};
                    this.elementTrace.push(result);
                    tempList = this.parseObject(currentElement.childNodes);
                    result = this.elementTrace.pop(result);
                    result[currentElement.getAttribute('type')] = tempList;

                    i = this.currentIndex.pop(i);
                }
                else if(currentElement.getAttribute('name') === null){
                    if(currentElement.getAttribute('type') === null){

                        this.currentIndex.push(i);

                        result[currentElement.nodeName] = {};
                        this.elementTrace.push(result);
                        tempList = this.parseObject(currentElement.childNodes);
                        result = this.elementTrace.pop(result);
                        result[currentElement.nodeName] = tempList;

                        i = this.currentIndex.pop(i);
                    }
                }
            }
        }
    }
    return result;
}

/** Function used to recursively print the JS object */
Parser.prototype.printObject = function(parsedObject, spaces) {
    var count = 0;

    /** Loop through each element in the object */
    for (var key in parsedObject) {

        /** Keep track of the current index */
        count++;

        /**
         * If the element has more than one child, print out the parent,
         * the children and its children
         */
        if(this.getChildrenNum(parsedObject[key]) > 1){
            document.write("[\"" + key + "\",
");
            this.inputSpaces(spaces + 1);
            document.write("[
");
            this.inputSpaces(spaces + 2);
            this.printObject(parsedObject[key], spaces + 2);
            this.inputSpaces(spaces + 1);
            document.write("]
");
            this.inputSpaces(spaces);
            document.write("]
");
        }

        /**
         * If the element has exactly one child, print out the parent and its
         * single child
         */
        else if (this.getChildrenNum(parsedObject[key]) == 1){
            document.write("[\"" + key + "\", ");
            length = this.getLength(parsedObject);
            tempKey = this.getKey(parsedObject[key]);

            /**
             * If the parent's child has no children, just print out the child with
             * closing brackets
             */
            if (this.getChildrenNum(parsedObject[key][tempKey]) == 0){
                document.write("\"" + this.getKey(parsedObject[key]) + "\"");
                // Check if we are at the last element
                if(count == length){
                    document.write("]
");
                }
                else{
                    document.write("],
");
                    this.inputSpaces(spaces);
                }
            }

            /**
             * If the parent's child has children, print out everything and print the
             * children's children
             */
            else {
                document.write("
");
                this.inputSpaces(spaces +1);
                tempKey = this.getKey(parsedObject[key]);

                if (this.getChildrenNum(parsedObject[key][tempKey]) ==1){
                    document.write("[");
                    this.printObject(parsedObject[key], spaces + 1);
                    this.inputSpaces(spaces);
                    document.write("]]
");
                }
                else{
                    this.printObject(parsedObject[key], spaces + 1);
                    this.inputSpaces(spaces);
                    document.write("]
");
                }
            }
        }

        /** If the parent has no child, it is a ref, so just print out the parent */
        else if (this.getChildrenNum(parsedObject[key]) == 0){
            length = this.getLength(parsedObject);

            /**If it is the last element, print just a newline */
            if (count == length) {
                document.write("\"" + key + "\"
");
            }
            else {
                document.write("\"" + key + "\",
");
                this.inputSpaces(spaces);
            }
        }
    }
}

/** Helper function used to get the length of the elements within a parent */
Parser.prototype.getLength = function(object) {
    var length = 0;
    for (var key in object){
        length++;
    }
    return length;
}

/**
 * Helper function used to get the key value in an object
 * Only used when we know that the parent has just one child
 */
 Parser.prototype.getKey = function(object) {
    var att = "";
    for (var key in object) {
        att = key;
    }
    return att;
}

/** Helper function used to determine the number of children in a node */
Parser.prototype.getChildrenNum = function(node) {
    var count = 0;
    for (var key in node){
        if (key) {
            count++;
        }
    }
    return count;
}

/** Helper function used to print out 'num' amount of tabs for formatting purposes */
Parser.prototype.inputSpaces = function(num) {
    for(k=0; k < num; k ++){
        document.write('&nbsp&nbsp&nbsp&nbsp');
    }
}

function gatherSchemas(cyclusPath){

    /** Default arguments */
    cyclusPath = typeof cyclusPath !== 'undefined' ? cyclusPath : '';
    if (cyclusPath == ''){
        console.error("cyclusPath is empty");
    }

    /** local vars */
    var i = 0;
    var parser = null;
    var schemas = {};
    var rngRelPath = "";
    var rngFullPath = "";
    var reFac = /eFacility/;

    /** get the list of all rng files and parse them */
    var xhttp = cycicXMLHttpRequest();
    xhttp.open("GET", "rngdump.json", false);
    xhttp.send();
    var rngPaths = JSON.parse(xhttp.responseText);
    document.write(typeof(rngPaths) + "
");
    document.write(Object.prototype.toString.call(rngPaths) + "
");
    for (i in rngPaths) {
        rngRelPath = rngPaths[i]

        /** Test to see if server request works */
        rngRelPath =
            "\"https://raw.github.com/cyclus/core/master/src/Models/Facility/StorageFacility/StorageFacility.rng\""
        if (rngRelPath.slice(0,4) == '\"htt'){
            $(document).ready(function() {
                $.ajax({
                    crossDomain: true,
                    type: 'GET',
                    url: 'http://query.yahooapis.com/v1/public/yql?q=select * from xml where url=' + rngRelPath,
                    dataType: 'jsonp',
                    success: function(response){
                        if(response.results[0] != undefined){
                            var text = response.results[0];
                            if (window.ActiveXObject){
                                var doc=new ActiveXObject('Microsoft.XMLDOM');
                                doc.async='false';
                                doc.loadXML(text);
                            } else {
                            var parser=new DOMParser();
                            var doc=parser.parseFromString(text,'text/xml');
                            }

                            var parser = new Parser(doc);
                            var parsedObj = parser.parseObj();
                            parser.printObject(parsedObj, 0);
                        }
                        else{
                            alert('Response undefined; incorrect url');
                        }
                    }
                })
            });
            break;
        }
        else{
            rngFullPath = cyclusPath + '/' + rngRelPath;
            parser = new Parser(rngFullPath);
            schemas[rngRelPath] = parser.parseObj();

            /**
             * if (rngRelPath.match(reFac) !== null) {
             * schemas[rngRelPath] = new Parser(rngFullPath)
             * }
             */
        }
    }

    for (s in schemas) {
        document.write(s + ":  " + "
");
        var parser = new Parser('blah');
        parser.printObject(schemas[s],0);
    }
    return schemas;
}

/** main(); */
mainGather();

/**
 * MENTAL NOTES TO SELF
 */

/**
 * xmlDoc.childNodes[0].nodeName -- 'grammer'
 * xmlDoc.childNodes[0].childNodes[1].nodeName -- 'define'
 * xmlDoc.childNodes[0].childNodes[1].childNodes[1] --element RecipeReactor
 * xmlDoc.childNodes[0].childNodes[1].childNodes[1].childNodes[1].nodeName --oneOrMore
 *
 * for(i=0; i<elements.length; i++){
 *     document.write(elements[1].childNodes[i]);
 * }

 * print tag name and value of the name attribute. change 'name' to type to get the data type of the object
 * document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].getAttribute('name'));
 * document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].nodeName);

 * prints inrecipt.. why
 * document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].nextSibling.nextSibling.getAttribute('name'));
 */

<commit_msg>Capitalize and punctuate comments.<commit_after>/** main(); */
mainGather();

function main(){

    /**
     * Examples for using the parser:
     * var parser = new Parser("storagefacility.xml");
     * var parser = new Parser("sourcefacility.xml");
	 * var parser = new Parser("recipereactor.xml");
     * var parser = new Parser("file:///home/scopatz/cyclus/src/Models/Facility/StorageFacility/StorageFacility.rng");
     */
    var parser = new Parser(
        "file:///C:/Users/Kevin/Documents/GitHub/core/src/Models/Facility/SourceFacility/SourceFacility.rng");

    var parsedObj = parser.parseObj();
    parser.printObject(parsedObj, 0);
}

function mainGather(){

    /**
     * Examples for using mainGather
     * gatherSchemas('/home/scopatz/cyclus')
     * gatherSchemas('../../cyclus')
     * gatherSchemas('http://raw.github.com/cyclus/core/master/src/Models/Facility/StorageFacility/StorageFacility.rng');
     */
    gatherSchemas('file:///C:/Users/Kevin/Documents/GitHub/core');

}

function cycicXMLHttpRequest() {
    if (window.XMLHttpRequest) {
        var xhttp = new XMLHttpRequest()
    }

    /** IE 5/6 */
    else {
        var xhttp = new ActiveXObject("Microsoft.XMLHTTP")
    }
    return xhttp
}

/******************************************************************************
 *                             Parser Class                                   *
 ******************************************************************************/

function Parser(word){
    this.currentIndex = new Array();
    this.jsObjName = new Array();
    this.elementTrace = new Array();
    this.file = word;
}

Parser.prototype.speak = function() {
    document.write(this.word);
}

/** Take XML and convert to JS object to be printed out. */
Parser.prototype.parseObj = function() {
    if (this.file.URL == '') {
        var x = this.file.childNodes[0].childNodes;
    }
    else{
        var xhttp = cycicXMLHttpRequest()
        xhttp.open("GET", this.file, false);
        xhttp.send();
        xmlDoc=xhttp.responseXML;

        var x = xmlDoc.childNodes[0].childNodes;
    }

    /**
     * First, start looking for the main parent name by searching for the
     * 'define' tag
     */
    for(n=0; n<x.length; n++){
    /** If found, start printing out the children */
        if (x[n].nodeName === 'define'){
            var elements = x[n].childNodes[1].childNodes;
            this.jsObjName[x[n].childNodes[1].getAttribute('name')] = {};
            this.jsObjName[x[n].childNodes[1].getAttribute('name')] =
                this.parseObject(elements);
        }
    }
    return this.jsObjName;
}

Parser.prototype.parseObject = function(a){
    var spaces = new Array();
    result = {};
    for (i=0; i<a.length; i++){

        /** Extract only the element, not the text objects. */
        if(a[i].nodeName != '#text'){
            if(a[i].nodeName != '#comment'){
                var currentElement = a[i];

                /** If the object has a 'name' attribute, print it. */
                if(currentElement.getAttribute('name')){
                    this.currentIndex.push(i);
                    result[currentElement.getAttribute('name')] = {};
                    this.elementTrace.push(result);
                    tempList = this.parseObject(currentElement.childNodes);
                    result = this.elementTrace.pop(result);
                    result[currentElement.getAttribute('name')] = tempList;

                    i = this.currentIndex.pop(i);
				}

                /** If the object has a 'type' attribute, print it. */
                else if(currentElement.getAttribute('type')){
                    this.currentIndex.push(i);

                    result[currentElement.getAttribute('type')] = {};
                    this.elementTrace.push(result);
                    tempList = this.parseObject(currentElement.childNodes);
                    result = this.elementTrace.pop(result);
                    result[currentElement.getAttribute('type')] = tempList;

                    i = this.currentIndex.pop(i);
                }
                else if(currentElement.getAttribute('name') === null){
                    if(currentElement.getAttribute('type') === null){

                        this.currentIndex.push(i);

                        result[currentElement.nodeName] = {};
                        this.elementTrace.push(result);
                        tempList = this.parseObject(currentElement.childNodes);
                        result = this.elementTrace.pop(result);
                        result[currentElement.nodeName] = tempList;

                        i = this.currentIndex.pop(i);
                    }
                }
            }
        }
    }
    return result;
}

/** Function used to recursively print the JS object. */
Parser.prototype.printObject = function(parsedObject, spaces) {
    var count = 0;

    /** Loop through each element in the object. */
    for (var key in parsedObject) {

        /** Keep track of the current index. */
        count++;

        /**
         * If the element has more than one child, print out the parent,
         * the children and its children.
         */
        if(this.getChildrenNum(parsedObject[key]) > 1){
            document.write("[\"" + key + "\",
");
            this.inputSpaces(spaces + 1);
            document.write("[
");
            this.inputSpaces(spaces + 2);
            this.printObject(parsedObject[key], spaces + 2);
            this.inputSpaces(spaces + 1);
            document.write("]
");
            this.inputSpaces(spaces);
            document.write("]
");
        }

        /**
         * If the element has exactly one child, print out the parent and its
         * single child.
         */
        else if (this.getChildrenNum(parsedObject[key]) == 1){
            document.write("[\"" + key + "\", ");
            length = this.getLength(parsedObject);
            tempKey = this.getKey(parsedObject[key]);

            /**
             * If the parent's child has no children, just print out the child with
             * closing brackets.
             */
            if (this.getChildrenNum(parsedObject[key][tempKey]) == 0){
                document.write("\"" + this.getKey(parsedObject[key]) + "\"");
                // Check if we are at the last element
                if(count == length){
                    document.write("]
");
                }
                else{
                    document.write("],
");
                    this.inputSpaces(spaces);
                }
            }

            /**
             * If the parent's child has children, print out everything and print the
             * children's children.
             */
            else {
                document.write("
");
                this.inputSpaces(spaces +1);
                tempKey = this.getKey(parsedObject[key]);

                if (this.getChildrenNum(parsedObject[key][tempKey]) ==1){
                    document.write("[");
                    this.printObject(parsedObject[key], spaces + 1);
                    this.inputSpaces(spaces);
                    document.write("]]
");
                }
                else{
                    this.printObject(parsedObject[key], spaces + 1);
                    this.inputSpaces(spaces);
                    document.write("]
");
                }
            }
        }

        /** If the parent has no child, it is a ref, so just print out the parent. */
        else if (this.getChildrenNum(parsedObject[key]) == 0){
            length = this.getLength(parsedObject);

            /**If it is the last element, print just a newline. */
            if (count == length) {
                document.write("\"" + key + "\"
");
            }
            else {
                document.write("\"" + key + "\",
");
                this.inputSpaces(spaces);
            }
        }
    }
}

/** Helper function used to get the length of the elements within a parent. */
Parser.prototype.getLength = function(object) {
    var length = 0;
    for (var key in object){
        length++;
    }
    return length;
}

/**
 * Helper function used to get the key value in an object.
 * Only used when we know that the parent has just one child.
 */
 Parser.prototype.getKey = function(object) {
    var att = "";
    for (var key in object) {
        att = key;
    }
    return att;
}

/** Helper function used to determine the number of children in a node. */
Parser.prototype.getChildrenNum = function(node) {
    var count = 0;
    for (var key in node){
        if (key) {
            count++;
        }
    }
    return count;
}

/** Helper function used to print out 'num' amount of tabs for formatting purposes. */
Parser.prototype.inputSpaces = function(num) {
    for(k=0; k < num; k ++){
        document.write('&nbsp&nbsp&nbsp&nbsp');
    }
}

function gatherSchemas(cyclusPath){

    /** Default arguments. */
    cyclusPath = typeof cyclusPath !== 'undefined' ? cyclusPath : '';
    if (cyclusPath == ''){
        console.error("cyclusPath is empty");
    }

    /** Local vars. */
    var i = 0;
    var parser = null;
    var schemas = {};
    var rngRelPath = "";
    var rngFullPath = "";
    var reFac = /eFacility/;

    /** Get the list of all rng files and parse them. */
    var xhttp = cycicXMLHttpRequest();
    xhttp.open("GET", "rngdump.json", false);
    xhttp.send();
    var rngPaths = JSON.parse(xhttp.responseText);
    document.write(typeof(rngPaths) + "
");
    document.write(Object.prototype.toString.call(rngPaths) + "
");
    for (i in rngPaths) {
        rngRelPath = rngPaths[i]

        /** Test to see if server request works. */
        rngRelPath =
            "\"https://raw.github.com/cyclus/core/master/src/Models/Facility/StorageFacility/StorageFacility.rng\""
        if (rngRelPath.slice(0,4) == '\"htt'){
            $(document).ready(function() {
                $.ajax({
                    crossDomain: true,
                    type: 'GET',
                    url: 'http://query.yahooapis.com/v1/public/yql?q=select * from xml where url=' + rngRelPath,
                    dataType: 'jsonp',
                    success: function(response){
                        if(response.results[0] != undefined){
                            var text = response.results[0];
                            if (window.ActiveXObject){
                                var doc=new ActiveXObject('Microsoft.XMLDOM');
                                doc.async='false';
                                doc.loadXML(text);
                            } else {
                            var parser=new DOMParser();
                            var doc=parser.parseFromString(text,'text/xml');
                            }

                            var parser = new Parser(doc);
                            var parsedObj = parser.parseObj();
                            parser.printObject(parsedObj, 0);
                        }
                        else{
                            alert('Response undefined; incorrect url');
                        }
                    }
                })
            });
            break;
        }
        else{
            rngFullPath = cyclusPath + '/' + rngRelPath;
            parser = new Parser(rngFullPath);
            schemas[rngRelPath] = parser.parseObj();

            /**
             * if (rngRelPath.match(reFac) !== null) {
             * schemas[rngRelPath] = new Parser(rngFullPath)
             * }
             */
        }
    }

    for (s in schemas) {
        document.write(s + ":  " + "
");
        var parser = new Parser('blah');
        parser.printObject(schemas[s],0);
    }
    return schemas;
}

/**
 * MENTAL NOTES TO SELF
 */

/**
 * xmlDoc.childNodes[0].nodeName -- 'grammer'
 * xmlDoc.childNodes[0].childNodes[1].nodeName -- 'define'
 * xmlDoc.childNodes[0].childNodes[1].childNodes[1] --element RecipeReactor
 * xmlDoc.childNodes[0].childNodes[1].childNodes[1].childNodes[1].nodeName --oneOrMore
 *
 * for(i=0; i<elements.length; i++){
 *     document.write(elements[1].childNodes[i]);
 * }

 * print tag name and value of the name attribute. change 'name' to type to get the data type of the object
 * document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].getAttribute('name'));
 * document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].nodeName);

 * prints inrecipt.. why
 * document.write(xmlDoc.getElementsByTagName('element')[1].childNodes[1].nextSibling.nextSibling.getAttribute('name'));
 */<|endoftext|>


<commit_before>'use strict';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.instance.write.service', [
    require('../../services/taskExecutor.js'),
    require('../serverGroups/serverGroup.read.service.js'),
  ])
  .factory('instanceWriter', function (taskExecutor, serverGroupReader) {

    function terminateInstance(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'terminateInstances',
            instanceIds: [instance.instanceId],
            serverGroup: instance.serverGroup,
            launchTimes: [instance.launchTime],
            region: instance.region,
            zone: instance.placement.availabilityZone,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Terminate instance: ' + instance.instanceId
      });
    }

    function terminateInstanceAndShrinkServerGroup(instance, application) {
      return serverGroupReader.getServerGroup(application.name, instance.account, instance.region, instance.serverGroup).
        then(function(serverGroup) {
          var setMaxToNewDesired = serverGroup.asg.minSize === serverGroup.asg.maxSize;
          return taskExecutor.executeTask({
            job: [
              {
                type: 'terminateInstanceAndDecrementAsg',
                instance: instance.instanceId,
                asgName: instance.serverGroup,
                region: instance.region,
                credentials: instance.account,
                providerType: instance.providerType,
                adjustMinIfNecessary: true,
                setMaxToNewDesired: setMaxToNewDesired,
              }
            ],
            application: application,
            description: 'Terminate instance ' + instance.instanceId + ' and shrink ' + instance.serverGroup,
          });
        });
    }

    function rebootInstance(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'rebootInstances',
            instanceIds: [instance.instanceId],
            region: instance.region,
            zone: instance.placement.availabilityZone,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Reboot instance: ' + instance.instanceId
      });
    }

    function deregisterInstanceFromLoadBalancer(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'deregisterInstancesFromLoadBalancer',
            instanceIds: [instance.instanceId],
            loadBalancers: instance.loadBalancers,
            region: instance.region,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Deregister instance: ' + instance.instanceId
      });
    }

    function registerInstanceWithLoadBalancer(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'registerInstancesWithLoadBalancer',
            instanceIds: [instance.instanceId],
            loadBalancers: instance.loadBalancers,
            region: instance.region,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Register instance: ' + instance.instanceId
      });
    }

    function enableInstanceInDiscovery(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'enableInstancesInDiscovery',
            instanceIds: [instance.instanceId],
            region: instance.region,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Enable instance: ' + instance.instanceId
      });
    }

    function disableInstanceInDiscovery(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'disableInstancesInDiscovery',
            instanceIds: [instance.instanceId],
            region: instance.region,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Disable instance: ' + instance.instanceId
      });
    }

    return {
      terminateInstance: terminateInstance,
      rebootInstance: rebootInstance,
      registerInstanceWithLoadBalancer: registerInstanceWithLoadBalancer,
      deregisterInstanceFromLoadBalancer: deregisterInstanceFromLoadBalancer,
      enableInstanceInDiscovery: enableInstanceInDiscovery,
      disableInstanceInDiscovery: disableInstanceInDiscovery,
      terminateInstanceAndShrinkServerGroup: terminateInstanceAndShrinkServerGroup,
    };

  }).name;
<commit_msg>use loadBalancerNames instead of loadBalancers<commit_after>'use strict';

let angular = require('angular');

module.exports = angular
  .module('spinnaker.instance.write.service', [
    require('../../services/taskExecutor.js'),
    require('../serverGroups/serverGroup.read.service.js'),
  ])
  .factory('instanceWriter', function (taskExecutor, serverGroupReader) {

    function terminateInstance(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'terminateInstances',
            instanceIds: [instance.instanceId],
            serverGroup: instance.serverGroup,
            launchTimes: [instance.launchTime],
            region: instance.region,
            zone: instance.placement.availabilityZone,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Terminate instance: ' + instance.instanceId
      });
    }

    function terminateInstanceAndShrinkServerGroup(instance, application) {
      return serverGroupReader.getServerGroup(application.name, instance.account, instance.region, instance.serverGroup).
        then(function(serverGroup) {
          var setMaxToNewDesired = serverGroup.asg.minSize === serverGroup.asg.maxSize;
          return taskExecutor.executeTask({
            job: [
              {
                type: 'terminateInstanceAndDecrementAsg',
                instance: instance.instanceId,
                asgName: instance.serverGroup,
                region: instance.region,
                credentials: instance.account,
                providerType: instance.providerType,
                adjustMinIfNecessary: true,
                setMaxToNewDesired: setMaxToNewDesired,
              }
            ],
            application: application,
            description: 'Terminate instance ' + instance.instanceId + ' and shrink ' + instance.serverGroup,
          });
        });
    }

    function rebootInstance(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'rebootInstances',
            instanceIds: [instance.instanceId],
            region: instance.region,
            zone: instance.placement.availabilityZone,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Reboot instance: ' + instance.instanceId
      });
    }

    function deregisterInstanceFromLoadBalancer(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'deregisterInstancesFromLoadBalancer',
            instanceIds: [instance.instanceId],
            loadBalancerNames: instance.loadBalancers,
            region: instance.region,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Deregister instance: ' + instance.instanceId
      });
    }

    function registerInstanceWithLoadBalancer(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'registerInstancesWithLoadBalancer',
            instanceIds: [instance.instanceId],
            loadBalancerNames: instance.loadBalancers,
            region: instance.region,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Register instance: ' + instance.instanceId
      });
    }

    function enableInstanceInDiscovery(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'enableInstancesInDiscovery',
            instanceIds: [instance.instanceId],
            region: instance.region,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Enable instance: ' + instance.instanceId
      });
    }

    function disableInstanceInDiscovery(instance, application) {
      return taskExecutor.executeTask({
        job: [
          {
            type: 'disableInstancesInDiscovery',
            instanceIds: [instance.instanceId],
            region: instance.region,
            credentials: instance.account,
            providerType: instance.providerType
          }
        ],
        application: application,
        description: 'Disable instance: ' + instance.instanceId
      });
    }

    return {
      terminateInstance: terminateInstance,
      rebootInstance: rebootInstance,
      registerInstanceWithLoadBalancer: registerInstanceWithLoadBalancer,
      deregisterInstanceFromLoadBalancer: deregisterInstanceFromLoadBalancer,
      enableInstanceInDiscovery: enableInstanceInDiscovery,
      disableInstanceInDiscovery: disableInstanceInDiscovery,
      terminateInstanceAndShrinkServerGroup: terminateInstanceAndShrinkServerGroup,
    };

  }).name;
<|endoftext|>