<commit_before>// license see http://www.openvstorage.com/licenses/opensource/
/*global define */
define([
    'jquery', 'knockout',
    'ovs/generic', 'ovs/api'
], function($, ko, generic, api) {
    "use strict";
    return function(guid) {
        var self = this;

        // Variables
        self.loadHandle       = undefined;
        self.diskHandle       = undefined;
        self.machineHandle    = undefined;

        // Observables
        self.loading           = ko.observable(false);
        self.loaded            = ko.observable(false);

        self.guid              = ko.observable(guid);
        self.name              = ko.observable();
        self.size              = ko.smoothObservable(undefined, generic.formatBytes);
        self.iops              = ko.smoothDeltaObservable(generic.formatNumber);
        self.storedData        = ko.smoothObservable(undefined, generic.formatBytes);
        self.cacheHits         = ko.smoothDeltaObservable();
        self.cacheMisses       = ko.smoothDeltaObservable();
        self.numberOfDisks     = ko.smoothObservable(undefined);
        self.numberOfMachines  = ko.smoothObservable(undefined);
        self.readSpeed         = ko.smoothDeltaObservable(generic.formatSpeed);
        self.writeSpeed        = ko.smoothDeltaObservable(generic.formatSpeed);
        self.backendWriteSpeed = ko.smoothDeltaObservable(generic.formatSpeed);
        self.backendReadSpeed  = ko.smoothDeltaObservable(generic.formatSpeed);
        self.backendReads      = ko.smoothObservable(undefined, generic.formatNumber);
        self.backendWritten    = ko.smoothObservable(undefined, generic.formatBytes);
        self.backendRead       = ko.smoothObservable(undefined, generic.formatBytes);
        self.bandwidthSaved    = ko.smoothObservable(undefined, generic.formatBytes);
        self.backendType       = ko.observable();
        self.backendConnection = ko.observable();
        self.backendLogin      = ko.observable();

        self.cacheRatio = ko.computed(function() {
            var total = (self.cacheHits.raw() || 0) + (self.cacheMisses.raw() || 0);
            if (total === 0) {
                total = 1;
            }
            return generic.formatRatio((self.cacheHits.raw() || 0) / total * 100);
        });
        self.freeSpace = ko.computed(function() {
            if (self.size.raw() === 0 || self.storedData.raw() === 0) {
                return 0;
            }
            return generic.formatRatio((self.size.raw() - self.storedData.raw()) / self.size.raw() * 100);
        });

        self._bandwidth = ko.computed(function() {
            var total = (self.readSpeed.raw() || 0) + (self.writeSpeed.raw() || 0),
                initialized = self.readSpeed.initialized() && self.writeSpeed.initialized();
            return {
                value: generic.formatSpeed(total),
                initialized: initialized
            };
        });
        self.bandwidth = ko.computed(function() {
            return self._bandwidth().value;
        });
        self.bandwidth.initialized = ko.computed(function() {
            return self._bandwidth().initialized;
        });

        self.load = function() {
            self.loading(true);
            return $.Deferred(function(deferred) {
                $.when.apply($, [
                        $.Deferred(function(mainDeferred) {
                            generic.xhrAbort(self.loadHandle);
                            self.loadHandle = api.get('vpools/' + self.guid())
                                .done(function(data) {
                                    var type = '', stats = data.statistics;
                                    if (data.backend_type) {
                                        type = $.t('ovs:vpools.backendtypes.' + data.backend_type);
                                    }
                                    self.name(data.name);
                                    self.iops(stats.write_operations + stats.read_operations);
                                    self.size(data.size);
                                    self.storedData(data.stored_data);
                                    self.cacheHits(stats.sco_cache_hits + stats.cluster_cache_hits);
                                    self.cacheMisses(stats.sco_cache_misses);
                                    self.readSpeed(stats.data_read);
                                    self.writeSpeed(stats.data_written);
                                    self.backendReadSpeed(stats.backend_data_read);
                                    self.backendWriteSpeed(stats.backend_data_written);
                                    self.backendWritten(stats.data_written);
                                    self.backendRead(stats.data_read);
                                    self.backendReads(stats.backend_read_operations);
                                    self.bandwidthSaved(stats.data_read - stats.backend_data_read);
                                    self.backendType(type);
                                    self.backendConnection(data.backend_connection);
                                    self.backendLogin(data.backend_login);
                                    mainDeferred.resolve();
                                })
                                .fail(mainDeferred.reject);
                        }).promise(),
                        $.Deferred(function(diskDeferred) {
                            generic.xhrAbort(self.diskHandle);
                            self.diskHandle = api.get('vpools/' + self.guid() + '/count_disks')
                                .done(function(data) {
                                    self.numberOfDisks(data);
                                    diskDeferred.resolve();
                                })
                                .fail(diskDeferred.reject);
                        }).promise(),
                        $.Deferred(function(machineDeferred) {
                            generic.xhrAbort(self.machineHandle);
                            self.machineHandle = api.get('vpools/' + self.guid() + '/count_machines')
                                .done(function(data) {
                                    self.numberOfMachines(data);
                                    machineDeferred.resolve();
                                })
                                .fail(machineDeferred.reject);
                        }).promise()
                    ])
                    .done(function() {
                        self.loaded(true);
                        deferred.resolve();
                    })
                    .fail(deferred.reject)
                    .always(function() {
                        self.loading(false);
                    });
            }).promise();
        };
    };
});
<commit_msg>OVS-175 - Fixed layout issue when stored_data was 0<commit_after>// license see http://www.openvstorage.com/licenses/opensource/
/*global define */
define([
    'jquery', 'knockout',
    'ovs/generic', 'ovs/api'
], function($, ko, generic, api) {
    "use strict";
    return function(guid) {
        var self = this;

        // Variables
        self.loadHandle       = undefined;
        self.diskHandle       = undefined;
        self.machineHandle    = undefined;

        // Observables
        self.loading           = ko.observable(false);
        self.loaded            = ko.observable(false);

        self.guid              = ko.observable(guid);
        self.name              = ko.observable();
        self.size              = ko.smoothObservable(undefined, generic.formatBytes);
        self.iops              = ko.smoothDeltaObservable(generic.formatNumber);
        self.storedData        = ko.smoothObservable(undefined, generic.formatBytes);
        self.cacheHits         = ko.smoothDeltaObservable();
        self.cacheMisses       = ko.smoothDeltaObservable();
        self.numberOfDisks     = ko.smoothObservable(undefined);
        self.numberOfMachines  = ko.smoothObservable(undefined);
        self.readSpeed         = ko.smoothDeltaObservable(generic.formatSpeed);
        self.writeSpeed        = ko.smoothDeltaObservable(generic.formatSpeed);
        self.backendWriteSpeed = ko.smoothDeltaObservable(generic.formatSpeed);
        self.backendReadSpeed  = ko.smoothDeltaObservable(generic.formatSpeed);
        self.backendReads      = ko.smoothObservable(undefined, generic.formatNumber);
        self.backendWritten    = ko.smoothObservable(undefined, generic.formatBytes);
        self.backendRead       = ko.smoothObservable(undefined, generic.formatBytes);
        self.bandwidthSaved    = ko.smoothObservable(undefined, generic.formatBytes);
        self.backendType       = ko.observable();
        self.backendConnection = ko.observable();
        self.backendLogin      = ko.observable();

        self.cacheRatio = ko.computed(function() {
            var total = (self.cacheHits.raw() || 0) + (self.cacheMisses.raw() || 0);
            if (total === 0) {
                total = 1;
            }
            return generic.formatRatio((self.cacheHits.raw() || 0) / total * 100);
        });
        self.freeSpace = ko.computed(function() {
            if ((self.size.raw() || 0) === 0) {
                return generic.formatRatio(0);
            }
            return generic.formatRatio((self.size.raw() - (self.storedData.raw() || 0)) / self.size.raw() * 100);
        });

        self._bandwidth = ko.computed(function() {
            var total = (self.readSpeed.raw() || 0) + (self.writeSpeed.raw() || 0),
                initialized = self.readSpeed.initialized() && self.writeSpeed.initialized();
            return {
                value: generic.formatSpeed(total),
                initialized: initialized
            };
        });
        self.bandwidth = ko.computed(function() {
            return self._bandwidth().value;
        });
        self.bandwidth.initialized = ko.computed(function() {
            return self._bandwidth().initialized;
        });

        self.load = function() {
            self.loading(true);
            return $.Deferred(function(deferred) {
                $.when.apply($, [
                        $.Deferred(function(mainDeferred) {
                            generic.xhrAbort(self.loadHandle);
                            self.loadHandle = api.get('vpools/' + self.guid())
                                .done(function(data) {
                                    var type = '', stats = data.statistics;
                                    if (data.backend_type) {
                                        type = $.t('ovs:vpools.backendtypes.' + data.backend_type);
                                    }
                                    self.name(data.name);
                                    self.iops(stats.write_operations + stats.read_operations);
                                    self.size(data.size);
                                    self.storedData(data.stored_data);
                                    self.cacheHits(stats.sco_cache_hits + stats.cluster_cache_hits);
                                    self.cacheMisses(stats.sco_cache_misses);
                                    self.readSpeed(stats.data_read);
                                    self.writeSpeed(stats.data_written);
                                    self.backendReadSpeed(stats.backend_data_read);
                                    self.backendWriteSpeed(stats.backend_data_written);
                                    self.backendWritten(stats.data_written);
                                    self.backendRead(stats.data_read);
                                    self.backendReads(stats.backend_read_operations);
                                    self.bandwidthSaved(stats.data_read - stats.backend_data_read);
                                    self.backendType(type);
                                    self.backendConnection(data.backend_connection);
                                    self.backendLogin(data.backend_login);
                                    mainDeferred.resolve();
                                })
                                .fail(mainDeferred.reject);
                        }).promise(),
                        $.Deferred(function(diskDeferred) {
                            generic.xhrAbort(self.diskHandle);
                            self.diskHandle = api.get('vpools/' + self.guid() + '/count_disks')
                                .done(function(data) {
                                    self.numberOfDisks(data);
                                    diskDeferred.resolve();
                                })
                                .fail(diskDeferred.reject);
                        }).promise(),
                        $.Deferred(function(machineDeferred) {
                            generic.xhrAbort(self.machineHandle);
                            self.machineHandle = api.get('vpools/' + self.guid() + '/count_machines')
                                .done(function(data) {
                                    self.numberOfMachines(data);
                                    machineDeferred.resolve();
                                })
                                .fail(machineDeferred.reject);
                        }).promise()
                    ])
                    .done(function() {
                        self.loaded(true);
                        deferred.resolve();
                    })
                    .fail(deferred.reject)
                    .always(function() {
                        self.loading(false);
                    });
            }).promise();
        };
    };
});
<|endoftext|>


<commit_before>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Displays a page as a modal dialog with inset appearance and overlay background
//>>label: Dialogs
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.dialog.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "../jquery.mobile.navigation" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, window, undefined ) {

$.widget( "mobile.dialog", $.mobile.widget, {
	options: {
		closeBtnText: "Close",
		overlayTheme: "a",
		initSelector: ":jqmData(role='dialog')"
	},

	_create: function() {
		var self = this,
			$el = this.element,
			headerCloseButton = $( ""+ this.options.closeBtnText + "" ),
			dialogWrap = $( "
", {
					"role" : "dialog",
					"class" : "ui-dialog-contain ui-corner-all ui-overlay-shadow"
				});

		$el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme );

		// Class the markup for dialog styling
		// Set aria role
		$el
			.wrapInner( dialogWrap )
			.children()
				.find( ":jqmData(role='header')" )
					.prepend( headerCloseButton )
				.end()
				.children( ':first-child')
					.addClass( "ui-corner-top" )
				.end()
				.children( ":last-child" )
					.addClass( "ui-corner-bottom" );

		// this must be an anonymous function so that select menu dialogs can replace
		// the close method. This is a change from previously just defining data-rel=back
		// on the button and letting nav handle it
		//
		// Use click rather than vclick in order to prevent the possibility of unintentionally
		// reopening the dialog if the dialog opening item was directly under the close button.
		headerCloseButton.bind( "click", function() {
			self.close();
		});

		/* bind events
			- clicks and submits should use the closing transition that the dialog opened with
				unless a data-transition is specified on the link/form
			- if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
		*/
		$el.bind( "vclick submit", function( event ) {
			var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
				active;

			if ( $target.length && !$target.jqmData( "transition" ) ) {

				active = $.mobile.urlHistory.getActive() || {};

				$target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
					.attr( "data-" + $.mobile.ns + "direction", "reverse" );
			}
		})
		.bind( "pagehide", function( e, ui ) {
			$( this ).find( "." + $.mobile.activeBtnClass ).not( ".ui-slider-bg" ).removeClass( $.mobile.activeBtnClass );
		})
		// Override the theme set by the page plugin on pageshow
		.bind( "pagebeforeshow", function() {
			self._isCloseable = true;
			if ( self.options.overlayTheme ) {
				self.element
					.page( "removeContainerBackground" )
					.page( "setContainerBackground", self.options.overlayTheme );
			}
		});
	},

	// Close method goes back in history
	close: function() {
		var dst;

		if ( this._isCloseable ) {
			this._isCloseable = false;
			if ( $.mobile.hashListeningEnabled ) {
				$.mobile.back();
			} else {
				dst = $.mobile.urlHistory.getActive().url;
				if ( !$.mobile.path.isPath( dst ) ) {
					dst = $.mobile.path.makeUrlAbsolute( "#" + dst );
				}

				$.mobile.changePage( dst, { changeHash: false, fromHashChange: true } );
			}
		}
	}
});

//auto self-init widgets
$( document ).delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function() {
	$.mobile.dialog.prototype.enhance( this );
});

})( jQuery, this );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<commit_msg>prevent dialogs re-using initial ui state from going back<commit_after>//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
//>>description: Displays a page as a modal dialog with inset appearance and overlay background
//>>label: Dialogs
//>>group: Widgets
//>>css.structure: ../css/structure/jquery.mobile.dialog.css
//>>css.theme: ../css/themes/default/jquery.mobile.theme.css

define( [ "jquery", "../jquery.mobile.widget", "../jquery.mobile.navigation" ], function( $ ) {
//>>excludeEnd("jqmBuildExclude");
(function( $, window, undefined ) {

$.widget( "mobile.dialog", $.mobile.widget, {
	options: {
		closeBtnText: "Close",
		overlayTheme: "a",
		initSelector: ":jqmData(role='dialog')"
	},

	_create: function() {
		var self = this,
			$el = this.element,
			headerCloseButton = $( ""+ this.options.closeBtnText + "" ),
			dialogWrap = $( "
", {
					"role" : "dialog",
					"class" : "ui-dialog-contain ui-corner-all ui-overlay-shadow"
				});

		$el.addClass( "ui-dialog ui-overlay-" + this.options.overlayTheme );

		// Class the markup for dialog styling
		// Set aria role
		$el
			.wrapInner( dialogWrap )
			.children()
				.find( ":jqmData(role='header')" )
					.prepend( headerCloseButton )
				.end()
				.children( ':first-child')
					.addClass( "ui-corner-top" )
				.end()
				.children( ":last-child" )
					.addClass( "ui-corner-bottom" );

		// this must be an anonymous function so that select menu dialogs can replace
		// the close method. This is a change from previously just defining data-rel=back
		// on the button and letting nav handle it
		//
		// Use click rather than vclick in order to prevent the possibility of unintentionally
		// reopening the dialog if the dialog opening item was directly under the close button.
		headerCloseButton.bind( "click", function() {
			self.close();
		});

		/* bind events
			- clicks and submits should use the closing transition that the dialog opened with
				unless a data-transition is specified on the link/form
			- if the click was on the close button, or the link has a data-rel="back" it'll go back in history naturally
		*/
		$el.bind( "vclick submit", function( event ) {
			var $target = $( event.target ).closest( event.type === "vclick" ? "a" : "form" ),
				active;

			if ( $target.length && !$target.jqmData( "transition" ) ) {

				active = $.mobile.urlHistory.getActive() || {};

				$target.attr( "data-" + $.mobile.ns + "transition", ( active.transition || $.mobile.defaultDialogTransition ) )
					.attr( "data-" + $.mobile.ns + "direction", "reverse" );
			}
		})
		.bind( "pagehide", function( e, ui ) {
			$( this ).find( "." + $.mobile.activeBtnClass ).not( ".ui-slider-bg" ).removeClass( $.mobile.activeBtnClass );
		})
		// Override the theme set by the page plugin on pageshow
		.bind( "pagebeforeshow", function() {
			self._isCloseable = true;
			if ( self.options.overlayTheme ) {
				self.element
					.page( "removeContainerBackground" )
					.page( "setContainerBackground", self.options.overlayTheme );
			}
		});
	},

	// Close method goes back in history
	close: function() {
		var dst;

		if ( this._isCloseable ) {
			this._isCloseable = false;
			// If the hash listening is enabled and there is at least one preceding history
			// entry it's ok to go back. Initial pages with the dialog hash state are an example
			// where the stack check is necessary
			if ( $.mobile.hashListeningEnabled && $.mobile.urlHistory.stack.length > 1 ) {
				$.mobile.back();
			} else {
				dst = $.mobile.urlHistory.getActive().url;
				if ( !$.mobile.path.isPath( dst ) ) {
					dst = $.mobile.path.makeUrlAbsolute( "#" + dst );
				}

				$.mobile.changePage( dst, { changeHash: false, fromHashChange: true } );
			}
		}
	}
});

//auto self-init widgets
$( document ).delegate( $.mobile.dialog.prototype.options.initSelector, "pagecreate", function() {
	$.mobile.dialog.prototype.enhance( this );
});

})( jQuery, this );
//>>excludeStart("jqmBuildExclude", pragmas.jqmBuildExclude);
});
//>>excludeEnd("jqmBuildExclude");
<|endoftext|>


<commit_before>import React, {Component} from "react";
import * as Survey from 'survey-react';
import questions from "../questionnaire/questions.json"
//import 'survey-react/survey.css';

class MySurvey extends Component {
  json = { title: 'Product Feedback Survey Example', showProgressBar: 'top', pages: [
      {
        questions: [{
            type: 'matrix',
            name: 'Quality',
            title: 'Please indicate if you agree or disagree with the following statements',
            columns: [{
                value: 1,
                text: 'Strongly Disagree'
              },
              {
                value: 2,
                text: 'Disagree'
              },
              {
                value: 3,
                text: 'Neutral'
              },
              {
                value: 4,
                text: 'Agree'
              },
              {
                value: 5,
                text: 'Strongly Agree'
              }
            ],
            rows: [{
                value: 'affordable',
                text: 'Product is affordable'
              },
              {
                value: 'does what it claims',
                text: 'Product does what it claims'
              },
              {
                value: 'better then others',
                text: 'Product is better than other products on the market'
              },
              {
                value: 'easy to use',
                text: 'Product is easy to use'
              }
            ]
          },
          {
            type: 'rating',
            name: 'satisfaction',
            title: 'How satisfied are you with the Product?',
            mininumRateDescription: 'Not Satisfied',
            maximumRateDescription: 'Completely satisfied'
          },
          {
            type: 'rating',
            name: 'recommend friends',
            visibleIf: '{satisfaction} > 3',
            title: 'How likely are you to recommend the Product to a friend or co-worker?',
            mininumRateDescription: 'Will not recommend',
            maximumRateDescription: 'I will recommend'
          },
          {
            type: 'comment',
            name: 'suggestions',
            title: 'What would make you more satisfied with the Product?',
          }
        ]
      }, {
        questions: [{
            type: 'radiogroup',
            name: 'price to competitors',
            title: 'Compared to our competitors, do you feel the Product is',
            choices: ['Less expensive', 'Priced about the same', 'More expensive', 'Not sure']
          },
          {
            type: 'radiogroup',
            name: 'price',
            title: 'Do you feel our current price is merited by our product?',
            choices: ['correct|Yes, the price is about right',
              'low|No, the price is too low for your product',
              'high|No, the price is too high for your product'
            ]
          },
          {
            type: 'multipletext',
            name: 'pricelimit',
            title: 'What is the... ',
            items: [{
                name: 'mostamount',
                title: 'Most amount you would every pay for a product like ours'
              },
              {
                name: 'leastamount',
                title: 'The least amount you would feel comfortable paying'
              }
            ]
          }
        ]
      }, {
        questions: [{
          type: 'text',
          name: 'email',
          title: 'Thank you for taking our survey. Please enter your email address, then press the "Submit" button.'
        }]
      }]
  };
    json = questions;
    render() {
        var model = new Survey.Model(this.json);
        return (

          <Survey.Survey model={model} />

        );
    }
}

export default MySurvey;
<commit_msg>Removed testing json<commit_after>import React, {Component} from "react";
import * as Survey from 'survey-react';
import questions from "../questionnaire/questions.json"
//import 'survey-react/survey.css';

class MySurvey extends Component {
    json = questions;
    render() {
        var model = new Survey.Model(this.json);
        return (

          <Survey.Survey model={model} />

        );
    }
}

export default MySurvey;
<|endoftext|>


<commit_before>import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { getChart } from '../helpers/backendInterface';
import { log, LOW } from '../helpers/log';
import { setDisplayChartAction } from '../actions/chartActions';
import BarPoll from './BarPoll';

class PollPage extends Component {
  constructor(props){
    super(props);
    this.updateOldChartData = this.updateOldChartData.bind(this);
  }

  updateOldChartData(id, chart, cb){
    getChart(id)
    .then(function({ info }){
      if(chart.id !== info[0].id){
        cb(info[0]);
      }
    })
    .catch(function(err){
      log('Error': err, LOW);
    });
  }

  render(){
    this.updateOldChartData(
      this.props.params.pollid,
      this.props.chart,
      this.props.setDisplayChart
    );
    const chart = this.props.chart;
    const data = Object.keys(chart.data).reduce((p, x) => {
      return [...p, {value: chart.data[x], label: x}]
    }, []);
    console.log(data);
    return(

Poll Page

        id : {chart.id}

        title: {chart.title}

        description: {chart.description}

        <BarPoll dataSet={data} yAxisLabel="Votes"/>

    );
  }
}
PollPage.propTypes = {
  params: PropTypes.object,
  chart: PropTypes.object,
  setDisplayChart: PropTypes.func
};
const mapStateToProps = (state) => {
  return {
    chart: state.chart
  };
};
const mapDispatchToProps = (dispatch) => {
  return {
    setDisplayChart: (chart) => dispatch(setDisplayChartAction(chart))
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(PollPage);
<commit_msg>Fixing code warnings<commit_after>import React, { PropTypes, Component } from 'react';
import { connect } from 'react-redux';
import { getChart } from '../helpers/backendInterface';
import { log, LOW } from '../helpers/log';
import { setDisplayChartAction } from '../actions/chartActions';
import BarPoll from './BarPoll';

class PollPage extends Component {
  constructor(props){
    super(props);
    this.updateOldChartData = this.updateOldChartData.bind(this);
  }

  updateOldChartData(id, chart, cb){
    getChart(id)
    .then(function({ info }){
      if(chart.id !== info[0].id){
        cb(info[0]);
      }
    })
    .catch(function(err){
      log('Error': err, LOW);
    });
  }

  render(){
    this.updateOldChartData(
      this.props.params.pollid,
      this.props.chart,
      this.props.setDisplayChart
    );
    const chart = this.props.chart;
    const data = Object.keys(chart.data).reduce((p, x) => {
      return [...p, {value: chart.data[x], label: x}];
    }, []);
    return(

Poll Page

        id : {chart.id}

        title: {chart.title}

        description: {chart.description}

        <BarPoll dataSet={data} yAxisLabel="Votes"/>

    );
  }
}
PollPage.propTypes = {
  params: PropTypes.object,
  chart: PropTypes.object,
  setDisplayChart: PropTypes.func
};
const mapStateToProps = (state) => {
  return {
    chart: state.chart
  };
};
const mapDispatchToProps = (dispatch) => {
  return {
    setDisplayChart: (chart) => dispatch(setDisplayChartAction(chart))
  };
};

export default connect(mapStateToProps, mapDispatchToProps)(PollPage);
<|endoftext|>


<commit_before>(function () {

function norm256(x) {
    if (x < 0)
        return 0;
    else if (x > 255)
        return 255;
    return x;
}

function rgbToS(col) {
    function pad0(s) {
        if (s.length == 1)
            s = '0' + s;
        return s;
    }

    var cols = '#';
    cols += pad0(col[0].toString(16));
    cols += pad0(col[1].toString(16));
    cols += pad0(col[2].toString(16));

    return cols;
}

function parseColor(col) {
    var m;
    if ($.isArray(col)) {
        return col;
    }
    else if (typeof(col) == 'string') {
        if (col.length > 0 && col[0] == '#') {
            var r,g,b;
            if (col.length == 7) {
                r = parseInt(col.substr(1,2), 16);
                g = parseInt(col.substr(3,2), 16);
                b = parseInt(col.substr(5,2), 16);
                if (isNaN(r) || isNaN(g) || isNaN(b))
                    assert(false, "Could not parse color '" + col + "'");
                return [r,g,b];
            }
            else if (col.length == 4) {
                r = parseInt(col.substr(1,1), 16);
                g = parseInt(col.substr(1,1), 16);
                b = parseInt(col.substr(1,1), 16)
                if (isNaN(r) || isNaN(g) || isNaN(b))
                    assert(false, "Could not parse color '" + col + "'");
                return [r,g,b];
            }
            else {
                assert(false, "Could not parse color '" + col + "'");
            }
        }
        else if (m = col.match(/\s*rgb\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\)\s*/)) {
            var r = parseFloat(m[1]);
            var g = parseFloat(m[2]);
            var b = parseFloat(m[3]);
            if (isNaN(r) || isNaN(g) || isNaN(b))
                assert(false, "Could not parse color '" + col + "'");
            r = parseInt(Math.round(r * 256.0));
            g = parseInt(Math.round(g * 256.0));
            b = parseInt(Math.round(b * 256.0));
            r = norm256(r);
            g = norm256(g);
            b = norm256(b);
            return [r,g,b];
        }
        else {
            // Support standard HTML color names.
            var map = {
                red: [255,0,0],
                green: [0,255,0],
                blue: [0,0,255],
                aqua: [0,255,255],
                black: [0,0,0],
                fuchsia: [255,0,255],
                gray: [128,128,128],
                lime: [0,255,0],
                maroon: [128,0,0],
                navy: [0,0,128],
                olive: [128,128,0],
                orange: [256,165,0],
                purple: [128,0,128],
                silver: [192,192,192],
                teal: [0, 128,128],
                white: [255,255,255],
                yellow: [255,255,0]
            };
            var u = col.toLowerCase();
            if (map[u])
                return map[u];
            assert(false, "Could not parse color '" + col + "'");
        }
    }
    else {
        assert(false, "Could not parse color '" + col + "'");
    }
}

define_ibex_controller({
name: "Scale",

jqueryWidget: {
    _init: function () {
        var self = this;

        this.cssPrefix = this.options._cssPrefix;
        this.finishedCallback = this.options._finishedCallback;

        this.html = this.options.html;
        this.decimalPlaces = (this.options.decimalPlaces == null ? 2 : this.options.decimalPlaces);
        this.startColor = this.options.startColor ? parseColor(this.options.startColor) : [255, 30, 30];
        this.endColor = this.options.endColor ? parseColor(this.options.endColor) : [120, 255, 120];

        this.startValue = this.options.startValue;
        assert(typeof(this.startValue) == "number", "'startValue' option must be a number");
        this.endValue = this.options.endValue;
        assert(typeof(this.endValue) == "number", "'endValue' option must be a number");
        this.buttonMessage = this.options.buttonMessage || "Continue";

        this.$html = htmlCodeToDOM(this.html);
        this.element.append($("<div>").addClass(this.cssPrefix + 'html').append(this.$html));

        this.currentMousePos = { x: 0, y: 0};

        var $bar = $("<div>").addClass(this.cssPrefix + 'bar');
        var $handle = $("<div>").addClass(this.cssPrefix + 'handle');
        this.$bar = $bar;
        this.$handle = $handle;

        this.scaleWidth = this.options.scaleWidth || 300;
        this.scaleHeight = this.options.scaleHeight || 20;
        this.handleWidth = this.options.handleWidth || 30;
        this.handleHeight = this.options.handleHeight || 30;
        this.scaleWidth = parseInt(this.scaleWidth);
        this.scaleHeight = parseInt(this.scaleHeight);
        this.handleWidth = parseInt(this.handleWidth);
        this.handleHeight = parseInt(this.handleWidth);
        $bar.css('width', this.scaleWidth + 'px');
        $bar.css('height', this.scaleHeight + 'px');
        $handle.css({ width: this.handleWith + 'px',
                      height: this.handleHeight + 'px' });

        $bar.append($handle);
        this.element.append($bar);

        this.handleLeft = parseInt(this.scaleWidth / 2);

        this.setHandlePos(this.handleLeft);
        $handle.css('background', rgbToS(this.getHandleColor()));

        this.setLinearGradient($bar, this.startColor, this.endColor);

        this.setupDragHandler();
        self.safeBind($bar, 'click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            self.handleBarClick(e);
        });

        this.$button = $("<div>").addClass(this.cssPrefix + 'button');
        this.$button.text(this.buttonMessage);
        this.element.append(this.$button);
        self.safeBind(this.$button, 'click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            self.handleButtonClick(e);
        });
    },

    handleButtonClick: function () {
        var fraction = this.handleLeft / this.scaleWidth;
        var val = (fraction * (this.endValue - this.startValue)) + this.startValue;
        //console.log("VAL", val);
        this.finishedCallback([[
            ["html", csv_url_encode(this.$html.innerHTML)],
            ["startValue", this.startValue.toFixed(this.decimalPlaces)],
            ["endValue", this.endValue.toFixed(this.decimalPlaces)],
            ["value", val.toFixed(this.decimalPlaces)]
        ]]);
    },

    handleBarClick: function (e) {
        var self = this;

        // Calculate handle screen position.
        var o = self.$handle.offset();
        var x = o.left;
        var y = o.top;
        x += $(window).scrollLeft();
        y += $(window).scrollTop();

        var clickedBar = false;
        if (e.pageX > x - 4 && e.pageX < x + self.handleWidth + 4) {
            if (e.pageY > y - 4 && e.pageY < y + self.handleHeight + 4)
                clickedBar = true;
        }

        if (! clickedBar) {
            // Move the handle to the position on the bar where user clicked.
            var barLeft = self.$bar.offset().left + $(window).scrollLeft();
            self.handleLeft = e.pageX - barLeft;
            if (self.handleLeft < 0)
                self.handleLeft = 0;
            else if (self.handleLeft > self.scaleWidth)
                self.handleLeft = self.scaleWidth;
            self.setHandlePos(self.handleLeft);
        }
    },

    setHandlePos: function (x) {
        var barO = this.$bar.offset();
        var barLeft = barO.left;
        var barTop = barO.top;
        barLeft += $(window).scrollLeft();
        barTop += $(window).scrollTop();
        this.$handle.css('left', (barLeft + parseInt(x) - parseInt(Math.round(this.handleWidth/2))) + 'px');
        this.$handle.css('top', (barTop - parseInt(Math.round((this.handleHeight - this.scaleHeight)/2.0))) + 'px');
        // Set color for handle.
        var col = this.getHandleColor();
        this.$handle.css('background', rgbToS(col));
    },

    getHandleColor: function () {
        var self = this;
        var frac = self.handleLeft / self.scaleWidth;
        var rd = parseInt(Math.round(frac * (self.endColor[0] - self.startColor[0])));
        var gd = parseInt(Math.round(frac * (self.endColor[1] - self.startColor[1])));
        var bd = parseInt(Math.round(frac * (self.endColor[2] - self.startColor[2])));
        var r = self.startColor[0] + rd;
        var g = self.startColor[1] + gd;
        var b = self.startColor[2] + bd;
        r = norm256(r);
        g = norm256(g);
        b = norm256(b);
        return [r,g,b];
    },

    setupDragHandler: function () {
        var self = this;

        var mouseIsDown = false;
        self.currentMousePos = { x: 0, y: 0 };
        var refMousePos = { x: 0, y: 0};
        var alreadyMoved = 0;
        self.safeBind($(document), 'mousemove', function (e) {
            self.currentMousePos.x = e.pageX;
            self.currentMousePos.y = e.pageY;

            if (mouseIsDown) {
                var offset = self.currentMousePos.x - refMousePos.x;
                self.handleLeft += offset - alreadyMoved;
                alreadyMoved = offset;
                if (self.handleLeft < 0)
                    self.handleLeft = 0;
                else if (self.handleLeft >= self.scaleWidth)
                    self.handleLeft = self.scaleWidth;
                self.setHandlePos(self.handleLeft);
            }
        });

        self.safeBind(self.$handle, 'mousedown', function (e) {
            e.preventDefault();
            e.stopPropagation();

            if (! mouseIsDown) {
                mouseIsDown = true;
                refMousePos.x = self.currentMousePos.x;
                refMousePos.y = self.currentMousePos.y;
                alreadyMoved = 0;
            }
        });
        self.safeBind($(document), 'mouseup', function () {
            mouseIsDown = false;
        });
    },

    setLinearGradient: function ($elem, startColor, endColor) {
        var scol = rgbToS(startColor);
        var ecol = rgbToS(endColor);

        $elem.css('filter', "progid:DXImageTransform.Microsoft.Gradient(startColorstr='" + scol + "', endColorstr='" + ecol + "', GradientType=1)");
        $elem.css('background-image', '-ms-linear-gradient(left,' + scol + ' 0%, ' + ecol + ' 100%)');
        $elem.css('background-image', '-webkit-gradient(linear, left rop, right top, color-stop(0, ' + scol + '), color-stop(1,' + ecol + '))');
        $elem.css('background-image', '-webkit-linear-gradient(left, ' + scol + ' 0%,' + ecol + ' 100%)');
        $elem.css('background-image', '-o-linear-gradient(left, ' + scol + ',' + ecol + ')');
        $elem.css('background-image', '-moz-linear-gradient(left, ' + scol + ',' + ecol + ')');
        $elem.css('background-image', 'linear-gradient(to right' + scol + ',' + ecol + ')');
    }
},

properties: {
    obligatory: ["html", "startValue", "endValue"],
    htmlDescription: function(opts) {
        return $(document.createElement("div")).text(opts.s || "");
    }
}
});

})();
<commit_msg>Minor fix to Scale.js<commit_after>(function () {

function norm256(x) {
    if (x < 0)
        return 0;
    else if (x > 255)
        return 255;
    return x;
}

function rgbToS(col) {
    function pad0(s) {
        if (s.length == 1)
            s = '0' + s;
        return s;
    }

    var cols = '#';
    cols += pad0(col[0].toString(16));
    cols += pad0(col[1].toString(16));
    cols += pad0(col[2].toString(16));

    return cols;
}

function parseColor(col) {
    var m;
    if ($.isArray(col)) {
        return col;
    }
    else if (typeof(col) == 'string') {
        if (col.length > 0 && col[0] == '#') {
            var r,g,b;
            if (col.length == 7) {
                r = parseInt(col.substr(1,2), 16);
                g = parseInt(col.substr(3,2), 16);
                b = parseInt(col.substr(5,2), 16);
                if (isNaN(r) || isNaN(g) || isNaN(b))
                    assert(false, "Could not parse color '" + col + "'");
                return [r,g,b];
            }
            else if (col.length == 4) {
                r = parseInt(col.substr(1,1), 16);
                g = parseInt(col.substr(1,1), 16);
                b = parseInt(col.substr(1,1), 16)
                if (isNaN(r) || isNaN(g) || isNaN(b))
                    assert(false, "Could not parse color '" + col + "'");
                return [r,g,b];
            }
            else {
                assert(false, "Could not parse color '" + col + "'");
            }
        }
        else if (m = col.match(/\s*rgb\(\s*([\d.]+)\s*,\s*([\d.]+)\s*,\s*([\d.]+)\)\s*/)) {
            var r = parseFloat(m[1]);
            var g = parseFloat(m[2]);
            var b = parseFloat(m[3]);
            if (isNaN(r) || isNaN(g) || isNaN(b))
                assert(false, "Could not parse color '" + col + "'");
            r = parseInt(Math.round(r * 256.0));
            g = parseInt(Math.round(g * 256.0));
            b = parseInt(Math.round(b * 256.0));
            r = norm256(r);
            g = norm256(g);
            b = norm256(b);
            return [r,g,b];
        }
        else {
            // Support standard HTML color names.
            var map = {
                red: [255,0,0],
                green: [0,255,0],
                blue: [0,0,255],
                aqua: [0,255,255],
                black: [0,0,0],
                fuchsia: [255,0,255],
                gray: [128,128,128],
                lime: [0,255,0],
                maroon: [128,0,0],
                navy: [0,0,128],
                olive: [128,128,0],
                orange: [256,165,0],
                purple: [128,0,128],
                silver: [192,192,192],
                teal: [0, 128,128],
                white: [255,255,255],
                yellow: [255,255,0]
            };
            var u = col.toLowerCase();
            if (map[u])
                return map[u];
            assert(false, "Could not parse color '" + col + "'");
        }
    }
    else {
        assert(false, "Could not parse color '" + col + "'");
    }
}

define_ibex_controller({
name: "Scale",

jqueryWidget: {
    _init: function () {
        var self = this;

        this.cssPrefix = this.options._cssPrefix;
        this.finishedCallback = this.options._finishedCallback;

        this.html = this.options.html;
        this.decimalPlaces = (this.options.decimalPlaces == null ? 2 : this.options.decimalPlaces);
        this.startColor = this.options.startColor ? parseColor(this.options.startColor) : [255, 30, 30];
        this.endColor = this.options.endColor ? parseColor(this.options.endColor) : [120, 255, 120];

        this.startValue = this.options.startValue;
        assert(typeof(this.startValue) == "number", "'startValue' option must be a number");
        this.endValue = this.options.endValue;
        assert(typeof(this.endValue) == "number", "'endValue' option must be a number");
        this.buttonMessage = this.options.buttonMessage || "Continue";

        this.$html = htmlCodeToDOM(this.html);
        this.element.append($("<div>").addClass(this.cssPrefix + 'html').append(this.$html));

        this.currentMousePos = { x: 0, y: 0};

        var $bar = $("<div>").addClass(this.cssPrefix + 'bar');
        var $handle = $("<div>").addClass(this.cssPrefix + 'handle');
        this.$bar = $bar;
        this.$handle = $handle;

        this.scaleWidth = this.options.scaleWidth || 300;
        this.scaleHeight = this.options.scaleHeight || 20;
        this.handleWidth = this.options.handleWidth || 30;
        this.handleHeight = this.options.handleHeight || 30;
        this.scaleWidth = parseInt(this.scaleWidth);
        this.scaleHeight = parseInt(this.scaleHeight);
        this.handleWidth = parseInt(this.handleWidth);
        this.handleHeight = parseInt(this.handleWidth);
        $bar.css('width', this.scaleWidth + 'px');
        $bar.css('height', this.scaleHeight + 'px');
        $handle.css({ width: this.handleWith + 'px',
                      height: this.handleHeight + 'px' });

        $bar.append($handle);
        this.element.append($bar);

        this.handleLeft = parseInt(this.scaleWidth / 2);

        this.setHandlePos(this.handleLeft);
        $handle.css('background', rgbToS(this.getHandleColor()));

        this.setLinearGradient($bar, this.startColor, this.endColor);

        this.setupDragHandler();
        self.safeBind($bar, 'click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            self.handleBarClick(e);
        });

        this.$button = $("<div>").addClass(this.cssPrefix + 'button');
        this.$button.text(this.buttonMessage);
        this.element.append(this.$button);
        self.safeBind(this.$button, 'click', function (e) {
            e.preventDefault();
            e.stopPropagation();
            self.handleButtonClick(e);
        });
    },

    handleButtonClick: function () {
        var fraction = this.handleLeft / this.scaleWidth;
        var val = (fraction * (this.endValue - this.startValue)) + this.startValue;
        //console.log("VAL", val);
        this.finishedCallback([[
            ["html", csv_url_encode(this.$html.innerHTML)],
            ["startValue", this.startValue.toFixed(this.decimalPlaces)],
            ["endValue", this.endValue.toFixed(this.decimalPlaces)],
            ["value", val.toFixed(this.decimalPlaces)]
        ]]);
    },

    handleBarClick: function (e) {
        var self = this;

        // Calculate handle screen position.
        var o = self.$handle.offset();
        var x = o.left;
        var y = o.top;
        x += $(window).scrollLeft();
        y += $(window).scrollTop();

        var clickedBar = false;
        if (e.pageX > x - 4 && e.pageX < x + self.handleWidth + 4) {
            if (e.pageY > y - 4 && e.pageY < y + self.handleHeight + 4)
                clickedBar = true;
        }

        if (! clickedBar) {
            // Move the handle to the position on the bar where user clicked.
            var barLeft = self.$bar.offset().left + $(window).scrollLeft();
            self.handleLeft = e.pageX - barLeft;
            if (self.handleLeft < 0)
                self.handleLeft = 0;
            else if (self.handleLeft > self.scaleWidth)
                self.handleLeft = self.scaleWidth;
            self.setHandlePos(self.handleLeft);
        }
    },

    setHandlePos: function (x) {
        var barO = this.$bar.offset();
        var barLeft = barO.left;
        var barTop = barO.top;
        barLeft += $(window).scrollLeft();
        barTop += $(window).scrollTop();
        this.$handle.css('left', (barLeft + parseInt(x) - parseInt(Math.round(this.handleWidth/2))) + 'px');
        this.$handle.css('top', (barTop - parseInt(Math.round((this.handleHeight - this.scaleHeight)/2.0))) + 'px');
        // Set color for handle.
        var col = this.getHandleColor();
        this.$handle.css('background', rgbToS(col));
    },

    getHandleColor: function () {
        var self = this;
        var frac = self.handleLeft / self.scaleWidth;
        var rd = parseInt(Math.round(frac * (self.endColor[0] - self.startColor[0])));
        var gd = parseInt(Math.round(frac * (self.endColor[1] - self.startColor[1])));
        var bd = parseInt(Math.round(frac * (self.endColor[2] - self.startColor[2])));
        var r = self.startColor[0] + rd;
        var g = self.startColor[1] + gd;
        var b = self.startColor[2] + bd;
        r = norm256(r);
        g = norm256(g);
        b = norm256(b);
        return [r,g,b];
    },

    setupDragHandler: function () {
        var self = this;

        var mouseIsDown = false;
        self.currentMousePos = { x: 0, y: 0 };
        var refMousePos = { x: 0, y: 0};
        var alreadyMoved = 0;
        self.safeBind($(document), 'mousemove', function (e) {
            self.currentMousePos.x = e.pageX;
            self.currentMousePos.y = e.pageY;

            if (mouseIsDown) {
                var offset = self.currentMousePos.x - refMousePos.x;
                self.handleLeft += offset - alreadyMoved;
                alreadyMoved = offset;
                if (self.handleLeft < 0)
                    self.handleLeft = 0;
                else if (self.handleLeft >= self.scaleWidth)
                    self.handleLeft = self.scaleWidth;
                self.setHandlePos(self.handleLeft);
            }
        });

        self.safeBind(self.$handle, 'mousedown', function (e) {
            e.preventDefault();
            e.stopPropagation();

            if (! mouseIsDown) {
                mouseIsDown = true;
                refMousePos.x = self.currentMousePos.x;
                refMousePos.y = self.currentMousePos.y;
                alreadyMoved = 0;
            }
        });
        self.safeBind($(document), 'mouseup', function () {
            mouseIsDown = false;
        });
    },

    setLinearGradient: function ($elem, startColor, endColor) {
        var scol = rgbToS(startColor);
        var ecol = rgbToS(endColor);

        $elem.css('filter', "progid:DXImageTransform.Microsoft.Gradient(startColorstr='" + scol + "', endColorstr='" + ecol + "', GradientType=1)");
        $elem.css('background-image', '-ms-linear-gradient(left,' + scol + ' 0%, ' + ecol + ' 100%)');
        $elem.css('background-image', '-webkit-gradient(linear, left rop, right top, color-stop(0, ' + scol + '), color-stop(1,' + ecol + '))');
        $elem.css('background-image', '-webkit-linear-gradient(left, ' + scol + ' 0%,' + ecol + ' 100%)');
        $elem.css('background-image', '-o-linear-gradient(left, ' + scol + ',' + ecol + ')');
        $elem.css('background-image', '-moz-linear-gradient(left, ' + scol + ',' + ecol + ')');
        $elem.css('background-image', 'linear-gradient(to right' + scol + ',' + ecol + ')');
    }
},

properties: {
    obligatory: ["html", "startValue", "endValue"],
    htmlDescription: function(opts) {
        return $(document.createElement("div")).text(opts.html || "");
    }
}
});

})();
<|endoftext|>


<commit_before>export { default as XMLAnchorNode } from './XMLAnchorNode'
export { default as XMLAnnotationNode } from './XMLAnnotationNode'
export { default as XMLContainerNode } from './XMLContainerNode'
export { default as XMLDocument } from './XMLDocument'
export { default as XMLDocumentImporter } from './XMLDocumentImporter'
export { default as XMLEditingInterface } from './XMLEditingInterface'
export { default as XMLElementNode } from './XMLElementNode'
export { default as XMLElementNodeConverter } from './XMLElementNodeConverter'
export { default as XMLExternalNode } from './XMLExternalNode'
export { default as XMLExternalNodeConverter } from './XMLExternalNodeConverter'
export { default as XMLInlineElementNode } from './XMLInlineElementNode'
export { default as XMLNodeConverter } from './XMLNodeConverter'
export { default as XMLSchema } from './XMLSchema'
export { default as XMLTextElement } from './XMLTextElement'
export { default as XMLTextElementConverter } from './XMLTextElementConverter'
export { default as checkSchema } from './checkSchema'
export { default as compileRNG } from './compileRNG'
export { default as registerSchema } from './registerSchema'
export { default as SchemaDrivenCommandManager } from './SchemaDrivenCommandManager'
export { default as loadRNG } from './_loadRNG'
export { default as validateXMLSchema } from './validateXML'
export { default as ValidatingChildNodeIterator } from './ValidatingChildNodeIterator'
export { default as prettyPrintXML } from './prettyPrintXML'
<commit_msg>Export helper to get schema reflection info.<commit_after>export { default as XMLAnchorNode } from './XMLAnchorNode'
export { default as XMLAnnotationNode } from './XMLAnnotationNode'
export { default as XMLContainerNode } from './XMLContainerNode'
export { default as XMLDocument } from './XMLDocument'
export { default as XMLDocumentImporter } from './XMLDocumentImporter'
export { default as XMLEditingInterface } from './XMLEditingInterface'
export { default as XMLElementNode } from './XMLElementNode'
export { default as XMLElementNodeConverter } from './XMLElementNodeConverter'
export { default as XMLExternalNode } from './XMLExternalNode'
export { default as XMLExternalNodeConverter } from './XMLExternalNodeConverter'
export { default as XMLInlineElementNode } from './XMLInlineElementNode'
export { default as XMLNodeConverter } from './XMLNodeConverter'
export { default as XMLSchema } from './XMLSchema'
export { default as XMLTextElement } from './XMLTextElement'
export { default as XMLTextElementConverter } from './XMLTextElementConverter'
export { default as _analyzeElementSchemas } from './_analyzeSchema'
export { default as checkSchema } from './checkSchema'
export { default as compileRNG } from './compileRNG'
export { default as registerSchema } from './registerSchema'
export { default as SchemaDrivenCommandManager } from './SchemaDrivenCommandManager'
export { default as loadRNG } from './_loadRNG'
export { default as validateXMLSchema } from './validateXML'
export { default as ValidatingChildNodeIterator } from './ValidatingChildNodeIterator'
export { default as prettyPrintXML } from './prettyPrintXML'
<|endoftext|>


<commit_before>/**
 * Deletes an element from an array by its index in the array.
 *
 * @param {Array} array The original array.
 * @param {Number} index The index of the element to delete in the original array.
 * @return {Array} A new array with the element removed.
 * @example
 *
 * const originalArray = ['a', 'b', 'c', 'd', 'e'];
 * const resultArray = immutableDelete(originalArray, 2);
 * // -> originalArray ['a', 'b', 'c', 'd', 'e']
 * // -> resultArray ['a', 'b', 'd', 'e']
 */
export default function immutableDelete(array, index) {
  return index >= 0
    ? array.slice(0, index).concat(array.slice(index + 1))
    : array.slice(0);
}
<commit_msg>use array spread operator to be more concise<commit_after>/**
 * Deletes an element from an array by its index in the array.
 *
 * @param {Array} array The original array.
 * @param {Number} index The index of the element to delete in the original array.
 * @return {Array} A new array with the element removed.
 * @example
 *
 * const originalArray = ['a', 'b', 'c', 'd', 'e'];
 * const resultArray = immutableDelete(originalArray, 2);
 * // -> originalArray ['a', 'b', 'c', 'd', 'e']
 * // -> resultArray ['a', 'b', 'd', 'e']
 */
export default function immutableDelete(array, index) {
  return index >= 0 ? [...array.slice(0, index), ...array.slice(index + 1)] : [...array];
}
<|endoftext|>


<commit_before>/* eslint-disable no-unused-expressions, no-console */

const expect = require('chai').expect;
const exec = require('child_process').exec;
const path = require('path');

const { getJHipsterCli, testInTempDir, copyFakeBlueprint, copyBlueprint, lnYeoman } = require('../utils/utils');

describe('jhipster cli test', () => {
    const cmd = getJHipsterCli();

    it('verify correct cmd format', () => {
        expect(cmd).to.match(/node (.*)\/cli\/jhipster/g);
    });

    it('--help should run without errors', done => {
        exec(`${cmd} --help`, (error, stdout, stderr) => {
            expect(error).to.be.null;
            done();
        });
    });

    it('--version should run without errors', done => {
        exec(`${cmd} --version`, (error, stdout, stderr) => {
            expect(error).to.be.null;
            done();
        });
    });

    it('should return error on unknown command', function (done) {
        this.timeout(10000);

        exec(`${cmd} junkcmd`, (error, stdout, stderr) => {
            expect(error).to.not.be.null;
            expect(error.code).to.equal(1);
            expect(stderr.includes('is not a known command')).to.be.true;
            done();
        });
    });

    it('should delegate to blueprint on blueprint command but will not find it', function (done) {
        this.timeout(10000);

        testInTempDir(tmpdir => {
            copyFakeBlueprint(tmpdir, 'bar');
            exec(`${cmd} foo --blueprint bar`, (error, stdout, stderr) => {
                expect(error).to.not.be.null;
                expect(error.code).to.equal(1);
                /* eslint-disable prettier/prettier */
                expect(stdout.includes('No custom commands found within blueprint: generator-jhipster-bar')).to.be.true;
                expect(stderr.includes('foo is not a known command')).to.be.true;
                done();
            });
        });
    });

    it('should delegate to blueprint on multiple blueprints command but will not find it', function (done) {
        this.timeout(10000);

        testInTempDir(tmpdir => {
            copyFakeBlueprint(tmpdir, 'bar', 'baz');
            exec(`${cmd} foo --blueprints bar,baz`, (error, stdout, stderr) => {
                expect(error).to.not.be.null;
                expect(error.code).to.equal(1);
                /* eslint-disable prettier/prettier */
                expect(stdout.includes('No custom commands found within blueprint: generator-jhipster-bar')).to.be.true;
                expect(stdout.includes('No custom commands found within blueprint: generator-jhipster-baz')).to.be.true;
                expect(stderr.includes('foo is not a known command')).to.be.true;
                done();
            });
        });
    });

    it('should delegate to blueprint on multiple blueprints command with sharedOptions and find it', function (done) {
        this.timeout(10000);

        testInTempDir(tmpdir => {
            copyBlueprint(path.join(__dirname, '../templates/blueprint-cli'), tmpdir, 'cli');
            lnYeoman(tmpdir);
            exec(`${cmd} foo --blueprints cli`, (error, stdout, stderr) => {
                expect(stdout.includes('Running foo')).to.be.true;
                expect(stdout.includes('Running bar')).to.be.true;
                expect(stdout.includes('barValue')).to.be.true;
                expect(stdout.includes('foorValue')).to.be.false;
                done();
            });
        });
    });

    it('should delegate to blueprint on multiple blueprints command with multiple sharedOptions and find it', function (done) {
        this.timeout(10000);

        testInTempDir(tmpdir => {
            copyBlueprint(path.join(__dirname, '../templates/blueprint-cli'), tmpdir, 'cli');
            copyBlueprint(path.join(__dirname, '../templates/blueprint-cli-shared'), tmpdir, 'cli-shared');
            lnYeoman(tmpdir);
            exec(`${cmd} foo --blueprints cli,cli-shared`, (error, stdout, stderr) => {
                expect(stdout.includes('Running foo')).to.be.true;
                expect(stdout.includes('Running bar')).to.be.true;
                expect(stdout.includes('fooValue')).to.be.true;
                expect(stdout.includes('barValue')).to.be.true;
                done();
            });
        });
    });
});
<commit_msg>Add cli tests<commit_after>/* eslint-disable no-unused-expressions, no-console */

const expect = require('chai').expect;
const exec = require('child_process').exec;
const path = require('path');
const proxyquire = require('proxyquire').noCallThru().noPreserveCache();
const sinon = require('sinon');
const Environment = require('yeoman-environment');

const { getJHipsterCli, testInTempDir, copyFakeBlueprint, copyBlueprint, lnYeoman } = require('../utils/utils');

describe('jhipster cli test', () => {
    const cmd = getJHipsterCli();

    it('verify correct cmd format', () => {
        expect(cmd).to.match(/node (.*)\/cli\/jhipster/g);
    });

    it('--help should run without errors', done => {
        exec(`${cmd} --help`, (error, stdout, stderr) => {
            expect(error).to.be.null;
            done();
        });
    });

    it('--version should run without errors', done => {
        exec(`${cmd} --version`, (error, stdout, stderr) => {
            expect(error).to.be.null;
            done();
        });
    });

    it('should return error on unknown command', function (done) {
        this.timeout(10000);

        exec(`${cmd} junkcmd`, (error, stdout, stderr) => {
            expect(error).to.not.be.null;
            expect(error.code).to.equal(1);
            expect(stderr.includes('is not a known command')).to.be.true;
            done();
        });
    });

    describe('with mocked generator command', () => {
        const commands = { mocked: {} };
        let oldArgv;
        let callback;
        before(() => {
            oldArgv = process.argv;
        });
        after(() => {
            process.argv = oldArgv;
        });
        beforeEach(() => {
            commands.mocked = { desc: 'Mocked command' };
            sinon.stub(Environment.prototype, 'run').callsFake((...args) => {
                callback(...args);
            });
            sinon.stub(Environment.prototype, 'create').returns({ _options: {} });
        });
        afterEach(() => {
            Environment.prototype.run.restore();
            Environment.prototype.create.restore();
        });

        describe('without argument', () => {
            beforeEach(() => {
                process.argv = ['jhipster', 'jhipster', 'mocked', '--foo', '--foo-bar'];
            });
            it('should forward options', done => {
                callback = (command, options) => {
                    expect(command).to.not.be.undefined;
                    expect(command).to.be.equal('jhipster:mocked');
                    expect(options).to.eql({ foo: true, 'from-cli': true, fromCli: true, fooBar: true, 'foo-bar': true });
                    done();
                };
                proxyquire('../../cli/cli', { './commands': commands });
            });
        });

        describe('with argument', () => {
            beforeEach(() => {
                commands.mocked.argument = ['name'];
                process.argv = ['jhipster', 'jhipster', 'mocked', 'Foo', '--foo', '--foo-bar'];
            });
            it('should forward argument and options', done => {
                callback = (command, options) => {
                    expect(command).to.be.equal('jhipster:mocked Foo');
                    expect(options).to.eql({ foo: true, 'from-cli': true, fromCli: true, fooBar: true, 'foo-bar': true });
                    done();
                };
                proxyquire('../../cli/cli', { './commands': commands });
            });
        });

        describe('with variable arguments', () => {
            beforeEach(() => {
                commands.mocked.argument = ['name...'];
                process.argv = ['jhipster', 'jhipster', 'mocked', 'Foo', 'Bar', '--foo', '--foo-bar'];
            });
            it('should forward argument and options', done => {
                callback = (command, options) => {
                    expect(command).to.be.equal('jhipster:mocked Foo Bar');
                    expect(options).to.eql({ foo: true, 'from-cli': true, fromCli: true, fooBar: true, 'foo-bar': true });
                    done();
                };
                proxyquire('../../cli/cli', { './commands': commands });
            });
        });
    });

    describe('with mocked cliOnly commands', () => {
        let oldArgv;
        const commands = { mocked: {} };
        before(() => {
            oldArgv = process.argv;
        });
        after(() => {
            process.argv = oldArgv;
        });
        beforeEach(() => {
            commands.mocked = { cb: () => {} };
        });

        describe('with argument', () => {
            beforeEach(() => {
                commands.mocked.desc = 'Mocked command';
                commands.mocked.argument = ['name'];
                commands.mocked.cliOnly = true;
                process.argv = ['jhipster', 'jhipster', 'mocked', 'Foo', '--foo', '--foo-bar'];
            });
            it('should forward argument and options', done => {
                const cb = (args, options, env) => {
                    expect(env).to.not.be.undefined;
                    expect(args).to.eql(['Foo']);
                    expect(options).to.eql({ foo: true, 'from-cli': true, fromCli: true, fooBar: true, 'foo-bar': true });
                    done();
                };
                proxyquire('../../cli/cli', { './commands': commands, './mocked': cb });
            });
        });

        describe('with variable arguments', () => {
            beforeEach(() => {
                commands.mocked.desc = 'Mocked command';
                commands.mocked.argument = ['name...'];
                commands.mocked.cliOnly = true;
                process.argv = ['jhipster', 'jhipster', 'mocked', 'Foo', 'Bar', '--foo', '--foo-bar'];
            });
            it('should forward argument and options', done => {
                const cb = (args, options, env) => {
                    expect(env).to.not.be.undefined;
                    expect(args).to.eql(['Foo', 'Bar']);
                    expect(options).to.eql({ foo: true, 'from-cli': true, fromCli: true, fooBar: true, 'foo-bar': true });
                    done();
                };
                proxyquire('../../cli/cli', { './commands': commands, './mocked': cb });
            });
        });

        describe('without argument', () => {
            beforeEach(() => {
                commands.mocked.desc = 'Mocked command';
                commands.mocked.cliOnly = true;
                process.argv = ['jhipster', 'jhipster', 'mocked', '--foo', '--foo-bar'];
            });
            it('should forward argument and options', done => {
                const cb = (args, options, env) => {
                    expect(env).to.not.be.undefined;
                    expect(args).to.eql([]);
                    expect(options).to.eql({ foo: true, 'from-cli': true, fromCli: true, fooBar: true, 'foo-bar': true });
                    done();
                };
                proxyquire('../../cli/cli', { './commands': commands, './mocked': cb });
            });
        });
    });

    it('should delegate to blueprint on blueprint command but will not find it', function (done) {
        this.timeout(10000);

        testInTempDir(tmpdir => {
            copyFakeBlueprint(tmpdir, 'bar');
            exec(`${cmd} foo --blueprint bar`, (error, stdout, stderr) => {
                expect(error).to.not.be.null;
                expect(error.code).to.equal(1);
                /* eslint-disable prettier/prettier */
                expect(stdout.includes('No custom commands found within blueprint: generator-jhipster-bar')).to.be.true;
                expect(stderr.includes('foo is not a known command')).to.be.true;
                done();
            });
        });
    });

    it('should delegate to blueprint on multiple blueprints command but will not find it', function (done) {
        this.timeout(10000);

        testInTempDir(tmpdir => {
            copyFakeBlueprint(tmpdir, 'bar', 'baz');
            exec(`${cmd} foo --blueprints bar,baz`, (error, stdout, stderr) => {
                expect(error).to.not.be.null;
                expect(error.code).to.equal(1);
                /* eslint-disable prettier/prettier */
                expect(stdout.includes('No custom commands found within blueprint: generator-jhipster-bar')).to.be.true;
                expect(stdout.includes('No custom commands found within blueprint: generator-jhipster-baz')).to.be.true;
                expect(stderr.includes('foo is not a known command')).to.be.true;
                done();
            });
        });
    });

    it('should delegate to blueprint on multiple blueprints command with sharedOptions and find it', function (done) {
        this.timeout(10000);

        testInTempDir(tmpdir => {
            copyBlueprint(path.join(__dirname, '../templates/blueprint-cli'), tmpdir, 'cli');
            lnYeoman(tmpdir);
            exec(`${cmd} foo --blueprints cli`, (error, stdout, stderr) => {
                expect(stdout.includes('Running foo')).to.be.true;
                expect(stdout.includes('Running bar')).to.be.true;
                expect(stdout.includes('barValue')).to.be.true;
                expect(stdout.includes('foorValue')).to.be.false;
                done();
            });
        });
    });

    it('should delegate to blueprint on multiple blueprints command with multiple sharedOptions and find it', function (done) {
        this.timeout(10000);

        testInTempDir(tmpdir => {
            copyBlueprint(path.join(__dirname, '../templates/blueprint-cli'), tmpdir, 'cli');
            copyBlueprint(path.join(__dirname, '../templates/blueprint-cli-shared'), tmpdir, 'cli-shared');
            lnYeoman(tmpdir);
            exec(`${cmd} foo --blueprints cli,cli-shared`, (error, stdout, stderr) => {
                expect(stdout.includes('Running foo')).to.be.true;
                expect(stdout.includes('Running bar')).to.be.true;
                expect(stdout.includes('fooValue')).to.be.true;
                expect(stdout.includes('barValue')).to.be.true;
                done();
            });
        });
    });
});
<|endoftext|>


<commit_before>(function(utils, undefined){

  var hasFamilyTable = $('.result-data .household-label').length > 0;

  $(document).ready(function(){
    setup();
  });

  function setup() {

    // Process the table rows of the record data
    // The first cell in each row becomes the key
    // The second cell becomes a list of the cells in that row
    // We store all the cells because the gender of
    // family members on census records is important
    var recordData = {};
    $('.result-data tr').each(function(){
      var row = $(this);
      var fieldName = $.trim( $('td:first', row).text().toLowerCase().slice(0, -1) );
      if( fieldName ) {
        recordData[fieldName] = $('td', row);
      }
    });

    var nameParts = ['',''];
    if( recordData['first name'] ) {
      nameParts = [ getCleanCellValue( recordData['first name'], 1 ) , getCleanCellValue( recordData['last name'], 1 ) ];
    }
    else if(recordData['name']) {
      nameParts = utils.splitName( getCleanCellValue( recordData['name'], 1 ) );
    }

    var personData = {
      'givenName': nameParts[0],
      'familyName': nameParts[1],
      'birthDate': checkMultipleFields( recordData, ['birth date', 'birthdate', 'estimated birth year', 'estimated birth date', 'baptism/christening date'], 1 ),
      'birthPlace': checkMultipleFields( recordData, ['birthplace', 'place of birth'], 1 ),
      'deathDate': getCleanCellValue( recordData['death date'], 1 ),
      'deathPlace': getCleanCellValue( recordData['death place'], 1 )
    };

    // Look for a spouse
    var spouseName = getSpousesName(recordData);
    if( spouseName ) {
      var spouseNameParts = utils.splitName( spouseName );
      personData['spouseGivenName'] = spouseNameParts[0];
      personData['spouseFamilyName'] = spouseNameParts[1];
    }

    // Look for a mother
    var motherName = getParentName(recordData, 'mother');
    if( motherName ) {
      var motherNameParts = utils.splitName( motherName );
      personData['motherGivenName'] = motherNameParts[0];
      personData['motherFamilyName'] = motherNameParts[1];
    }

    // Look for a father
    var fatherName = getParentName(recordData, 'father');
    if( fatherName ) {
      var fatherNameParts = utils.splitName( fatherName );
      personData['fatherGivenName'] = fatherNameParts[0];
      personData['fatherFamilyName'] = motherNameParts[1];
    }

    chrome.extension.sendRequest({
      'type': 'person_info',
      'data': personData
    });

  }

  // Check for the existence of multiple fields
  // First one found is returned
  function checkMultipleFields( recordData, fields, position ) {
    for( var i in fields ) {
      if( recordData[fields[i]] ) {
        var val = getCleanCellValue( recordData[fields[i]], position );
        if( val ) {
          return val;
        }
      }
    }
    return undefined;
  }

  function getCleanCellValue( cells, position ) {
    if( cells ) {
      return $.trim( cells.eq(position).text() );
    }
    return undefined;
  }

  function getRelationship(recordData) {
    return checkMultipleFields( recordData, ["relationship to head of household", "relationship to head of household (standardized)"], 1 ).toLowerCase();
  }

  function getSpousesName(recordData) {
    // Check to see if the "spouse's name" is set
    if( recordData["spouse's name"] ) {
      return getCleanCellValue( recordData["spouse's name"], 1 );
    }

    // If "spouse's name" isn't set do some crazy relationship jiu-jitsu
    else if( hasFamilyTable ) {
      var relationship = getRelationship(recordData);

      // The husband is always listed as the head of household
      // so we only look for the wife. If the wife is the head
      // of household it means the husband isn't there so returning
      // the wife will be undefined which means there is no spouse
      if( relationship == "head" || relationship == "self" ) {
        return getCleanCellValue( recordData['wife'], 1 );
      } else if( relationship == "wife" ) {
        return checkMultipleFields( recordData, ['head', 'self'], 1 );
      }
    }

    return undefined;
  }

  function getParentName(recordData, parent) {
    // Check to see if the "parent's name" is set
    if( recordData[parent+"'s name"] ) {
      return getCleanCellValue( recordData[parent+"'s name"], 1);
    }

    // If "parent's name" isn't set do some crazy relationship jiu-jitsu
    else if( hasFamilyTable ) {
      var relationship = getRelationship(recordData);

      if( relationship == 'son' || relationship == 'daughter' ) {
        var headGender = checkMultipleFields( recordData, ['head', 'self'], 2 );

        if( parent == 'father' ) {

          // Check to see if the gender of the head of household is male
          if( headGender == 'M' ) {
            return checkMultipleFields( recordData, ['head', 'self'], 1 );
          }
        } else if( parent == 'mother' ) {

          // If the head of household is male, return the wife's name
          // If the head of household is female, return the head's name
          if( headGender == 'F' ) {
            return checkMultipleFields( recordData, ['head', 'self'], 1 );
          } else if( headGender == 'M' ) {
            return getCleanCellValue( recordData['wife'], 1);
          }
        }
      }
    }

    return undefined;
  }

}(utils));<commit_msg>Enhanced FS record processing<commit_after>(function(utils, undefined){

  var hasFamilyTable = $('.result-data .household-label').length > 0;

  $(document).ready(function(){
    $.getJSON(window.location.href, function(data){
      setup(data);
    });
  });

  function setup(recordData) {

    // Set the name
    var nameParts = getNameParts(recordData);
    var personData = {
      'givenName': nameParts[0],
      'familyName': nameParts[1]
    };

    // Get the birth and death events
    var events = getEvents( recordData );
    if( events.birth ) {
      var birthDetails = getEventDetails( events.birth, 'birth' );
      personData.birthDate = birthDetails.date;
      personData.birthPlace = birthDetails.place;
    }
    if( events.death ) {
      var deathDetails = getEventDetails( events.death, 'death' );
      personData.deathDate = deathDetails.date;
      personData.deathPlace = deathDetails.place;
    }

    // Look for a spouse
    if( recordData.spouse.length ) {
      var spouseNameParts = utils.splitName( recordData.spouse[0].name );
      personData['spouseGivenName'] = spouseNameParts[0];
      personData['spouseFamilyName'] = spouseNameParts[1];
    }

    // Look for parents
    var parents = getParents( recordData );

    if( parents.mother ) {
      var motherNameParts = utils.splitName( parents.mother.name );
      personData['motherGivenName'] = motherNameParts[0];
      personData['motherFamilyName'] = motherNameParts[1];
    }

    if( parents.father ) {
      var fatherNameParts = utils.splitName( parents.father.name );
      personData['fatherGivenName'] = fatherNameParts[0];
      personData['fatherFamilyName'] = fatherNameParts[1];
    }

    chrome.extension.sendRequest({
      'type': 'person_info',
      'data': personData
    });

  }

  function getEventDetails( eventInfo, eventType ) {
    var eventDetails = {};
    if( eventInfo.date ) {
      eventDetails.date = checkMultipleFields(
        eventInfo.date,
        [
          ['normalized', 0, 'text'],
          ['normalized', 0, 'parts', 0, 'text']
        ]
      );
    }
    if( eventInfo.place ) {
      eventDetails.place = checkMultipleFields(
        eventInfo.place,
        [
          ['original', 'text'],
          ['normalized', 0, 'text']
        ]
      );
    }
    return eventDetails;
  }

  // Check for the existence of multiple fields
  // First one found is returned
  function checkMultipleFields( recordData, fieldLists ) {
    for( var i in fieldLists ) {
      var data = checkFields( recordData, fieldLists[i] );
      if( data !== undefined ) return data;
    }
    return undefined;
  }

  function checkFields( recordData, fieldList ) {
    var data = recordData;
    for( var i in fieldList ) {
      if( data[fieldList[i]] ) {
        data = data[fieldList[i]];
      } else {
        return undefined;
      }
    }
    return data;
  }

  function getEvents( recordData ) {
    var events = {};
    for( var i in recordData.event ) {
      if( recordData.event[i].type == "BIRTH" ) {
        events.birth = recordData.event[i];
      } else if( recordData.event[i].type == "DEATH" ) {
        events.death = recordData.event[i];
      }
    }
    return events;
  }

  function getParents( recordData ) {
    var parents = {};
    for( var i in recordData.parent ) {
      if( recordData.parent[i].gender == "MALE" ) {
        parents.father = recordData.parent[i];
      } else {
        parents.mother = recordData.parent[i];
      }
    }
    return parents;
  }

  function getNameParts( recordData ) {
    var nameParts = [undefined, undefined];

    var name = checkMultipleFields(
      recordData.name[0],
      [
        ['normalized', 0, 'text'],
        ['normalized', 0, 'parts'],
        ['original', 'text'],
        ['original', 'parts']
      ]
    );

    if( typeof name == "string" ) {
      nameParts = utils.splitName(name);
    } else {
      nameParts = processFSNameParts(name);
    }

    return nameParts;

  }

  function processFSNameParts( parts ) {
    var given = [],
        family = [];
    for( var i in parts ) {
      if( parts[i].type == "GIVEN" ) {
        given.push( parts[i].text );
      } else if( parts[i].type == "SURNAME" ) {
        family.push( parts[i].text );
      }
    }
    return [ given.join(' '), family.join(' ') ];
  }

}(utils));<|endoftext|>