<commit_before>(function () {
	'use strict';

	window.Cosmoz = window.Cosmoz || {};

	var translationElements = [];
	/**
	 * Translation behavior using the I18next internationalization framework.
	 *
	 * @polymerBehavior */
	Cosmoz.TranslatableBehavior = {
		properties: {
			t: {
				type: Object,
				value: function () {
					return {};
				}
			}
		},

		_argumentsToObject: function (args, skipnum) {
			var argsArray = Array.prototype.slice.call(args, skipnum);
			return this._arrayToObject(argsArray);
		},

		_arrayToObject: function (array) {
			var ctx = this,
				object = {};

			array.forEach(function (item, index) {
				if (object.count === undefined && typeof item === 'number') {
					object.count = item;
				}
				// Don't send the 't' kicker to i18n for arguments
				if (item !== ctx.t) {
					object[index] = item;
				}
			});
			return object;
		},

		_ensureInitialized: function () {
			if (!i18n.isInitialized()) {
				// default i18n init, to ensure translate function will return something
				// even when there is no <i18next> element in the page.
				i18n.init({lng: 'en', resStore: { en: {}}, fallbackLng: false});
			}
		},

		/**
		 * Convenience method for gettext. Translate a text.
		 *
		 * @param {string} key Translation key.
		 * @returns {string} Translated text.
		 */
		_: function (key) {
			this._ensureInitialized();

			var args = this._argumentsToObject(arguments, 1);
			// Don't make i18next fetch more translations
			delete args.count;
			return i18n.t(key, args);
		},

		attached: function () {
			translationElements.push(this);
		},

		detached: function () {
			var i = translationElements.indexOf(this);
			if (i >= 0) {
				translationElements.splice(i, 1);
			}
		},

		/**
		 * Translate a text.
		 *
		 * Example of basic translation:
		 * `_(string, t)`
		 *
{{ _(‘My translation’, t) }}

		 *
		 * Example of basic translation with interpolation:
		 * `_(string, [args], t)`
		 *
{{ _(‘Hello {0}’, user.name, t) }}

		 *
		 * @param {string} key Text to translate.
		 * @param {object} t Behavior t object.
		 * @return {string} Translated text.
		 */
		gettext: function (key) {
			this._ensureInitialized();

			var args = this._argumentsToObject(arguments, 1);
			// Don't make i18next fetch more translations
			delete args.count;
			return i18n.t(key, args);
		},

		/**
		 * Plural version of gettext. Translate a text to the current locale
		 * using the first numeric argument after the two first arguments to
		 * determine if output should be singular or plural.
		 *
		 * Example of translation in singular or plural:
		 * `ngettext(singular, plural, count, t)`
		 *
{{ ngettext(‘My translation’,
		 *   ‘My translations’, count, t) }}

		 *
		 * Example of translation in singular or plural with interpolation:
		 * `ngettext(singular, plural, [count and other args], t)`
		 *
{{ ngettext(‘My translation for “{1}”’,
		 *   ‘My {0} translations for “{1}”’, count, ‘hello’, t) }}

		 *
		 * @param {string} singular Singular text variant.
		 * @param {string} plural Plural text variant.
		 * @return {string} Translated text.
		 */
		ngettext: function (singular, plural) {
			this._ensureInitialized();

			var
				args = this._argumentsToObject(arguments, 2),
				n = args.count,
				key;

			delete args.count;

			if (i18n.pluralExtensions.needsPlural(i18n.lng(), n)) {
				args.defaultValue = plural;
				key = i18n.options.ns.defaultNs + i18n.options.nsseparator + singular + i18n.options.pluralSuffix;
			} else {
				key = singular;
				args.defaultValue = singular;
			}
			return i18n.t(key, args);
		},

		/**
		 * Translate a text using a specific context.
		 *
		 * Example of translation with context:
		 * `pgettext(context, ‘text’, t)`
		 *
{{ pgettext(‘Cancel Invoice’, ‘Cancel’, t) }}

		 *
		 * Example of translation including context with interpolation:
		 * `pgettext(context, ‘text’, [args], t)`
		 *
{{ pgettext(‘Cancel Invoice’, ‘Cancel {0}’,
		 *   document.type, t) }}

		 *
		 * @param {string} context Context text.
		 * @param {string} key Text to translate.
		 * @return {string} Translated text.
		 */
		pgettext: function (context, key) {
			this._ensureInitialized();

			var args = this._argumentsToObject(arguments, 2);
			args.context = context;
			// Don't make i18next fetch more translations
			delete args.count;
			return i18n.t(key, args);
		},

		/**
		 * Translate a text in singular or plural with a specific context.
		 *
		 * Example of translation in singular or plural with context:
		 * `npgettext(context, singular, plural, count, t)`
		 *
{{ npgettext('Cancel invoice', ‘My cancellation’,
		 *   ‘My {0} cancellations’, count, t) }}

		 *
		 * Example of translation in singular or plural with context and
		 * interpolation:
		 * `npgettext(context, singular, plural, count, t)`
		 *
{{ npgettext('Cancel invoice', ‘My {1} cancellation’,
		 *   ‘My {0} {1} cancellations’, count, document.type, t) }}

		 *
		 * @param {string} context Context text.
		 * @param {string} singular Singular text variant.
		 * @param {string} plural Plural text variant.
		 * @return {string} Translated text.
		 */
		npgettext: function (context, singular, plural) {
			this._ensureInitialized();

			var
				args = this._argumentsToObject(arguments, 3),
				n = args.count,
				key = singular,
				contextKeyPart = context
					? '_' + context
					: '';

			delete args.count;

			if (i18n.pluralExtensions.needsPlural(i18n.lng(), n)) {
				args.defaultValue = plural;
				key = i18n.options.ns.defaultNs + i18n.options.nsseparator + singular + contextKeyPart + i18n.options.pluralSuffix;
			} else {
				key = singular;
				args.context = context;
			}

			return i18n.t(key, args);
		}
	};

	Polymer({
		is: 'cosmoz-i18next',
		properties: {
			domain: {
				type: String,
				value: 'messages'
			},
			interpolationPrefix: {
				type: String,
				value: '__'
			},
			interpolationSuffix: {
				type: String,
				value: '__'
			},
			language: {
				type: String,
				value: 'en'
			},
			namespace: {
				type: String,
				value: 'translation'
			},
			translations: {
				type: Object,
				observer: '_setTranslations'
			},
			keySeparator: {
				type: String,
				value: '.'
			},
			nsSeparator: {
				type: String,
				value: ':'
			}
		},
		_setTranslations: function () {
			i18n.removeResourceBundle(this.language, this.namespace);
			i18n.addResources(this.language, this.namespace, this.translations);
			translationElements.forEach(function (element) {
				element.set('t', {});
			});
		},
		ready: function () {
			i18n.init({
				interpolationPrefix: this.interpolationPrefix,
				interpolationSuffix: this.interpolationSuffix,
				keyseparator: this.keySeparator,
				lng: this.language,
				nsseparator: this.nsSeparator,
				resStore: {}
			});
		}
	});
}());
<commit_msg>Translatable behavior, updating documentation continued.<commit_after>(function () {
	'use strict';

	window.Cosmoz = window.Cosmoz || {};

	var translationElements = [];
	/**
	 * Translation behavior using the I18next internationalization framework.
	 *
	 * @polymerBehavior */
	Cosmoz.TranslatableBehavior = {
		properties: {
			t: {
				type: Object,
				value: function () {
					return {};
				}
			}
		},

		_argumentsToObject: function (args, skipnum) {
			var argsArray = Array.prototype.slice.call(args, skipnum);
			return this._arrayToObject(argsArray);
		},

		_arrayToObject: function (array) {
			var ctx = this,
				object = {};

			array.forEach(function (item, index) {
				if (object.count === undefined && typeof item === 'number') {
					object.count = item;
				}
				// Don't send the 't' kicker to i18n for arguments
				if (item !== ctx.t) {
					object[index] = item;
				}
			});
			return object;
		},

		_ensureInitialized: function () {
			if (!i18n.isInitialized()) {
				// default i18n init, to ensure translate function will return something
				// even when there is no <i18next> element in the page.
				i18n.init({lng: 'en', resStore: { en: {}}, fallbackLng: false});
			}
		},

		/**
		 * Convenience method for gettext. Translates a text.
		 *
		 * @param {string} key Translation key.
		 * @returns {string} Translated text.
		 */
		_: function (key) {
			this._ensureInitialized();

			var args = this._argumentsToObject(arguments, 1);
			// Don't make i18next fetch more translations
			delete args.count;
			return i18n.t(key, args);
		},

		attached: function () {
			translationElements.push(this);
		},

		detached: function () {
			var i = translationElements.indexOf(this);
			if (i >= 0) {
				translationElements.splice(i, 1);
			}
		},

		/**
		 * Translates a text.
		 *
		 * Example of basic translation:
		 * `_(string, t)`
		 *
{{ _(‘My translation’, t) }}

		 *
		 * Example of basic translation with interpolation:
		 * `_(string, [args], t)`
		 *
{{ _(‘Hello {0}’, user.name, t) }}

		 *
		 * @param {string} key Text to translate.
		 * @param {object} t Behavior t object.
		 * @return {string} Translated text.
		 */
		gettext: function (key) {
			this._ensureInitialized();

			var args = this._argumentsToObject(arguments, 1);
			// Don't make i18next fetch more translations
			delete args.count;
			return i18n.t(key, args);
		},

		/**
		 * Plural version of gettext. Translates a text to the current locale
		 * using the first numeric argument after the two first arguments to
		 * determine if output should be singular or plural.
		 *
		 * Example of translation in singular or plural:
		 * `ngettext(singular, plural, count, t)`
		 *
{{ ngettext(‘My translation’,
		 *   ‘My translations’, count, t) }}

		 *
		 * Example of translation in singular or plural with interpolation:
		 * `ngettext(singular, plural, [count and other args], t)`
		 *
{{ ngettext(‘My translation for “{1}”’,
		 *   ‘My {0} translations for “{1}”’, count, ‘hello’, t) }}

		 *
		 * @param {string} singular Singular text variant.
		 * @param {string} plural Plural text variant.
		 * @return {string} Translated text.
		 */
		ngettext: function (singular, plural) {
			this._ensureInitialized();

			var
				args = this._argumentsToObject(arguments, 2),
				n = args.count,
				key;

			delete args.count;

			if (i18n.pluralExtensions.needsPlural(i18n.lng(), n)) {
				args.defaultValue = plural;
				key = i18n.options.ns.defaultNs + i18n.options.nsseparator + singular + i18n.options.pluralSuffix;
			} else {
				key = singular;
				args.defaultValue = singular;
			}
			return i18n.t(key, args);
		},

		/**
		 * Translates a text using a specific context.
		 *
		 * Example of translation with context:
		 * `pgettext(context, ‘text’, t)`
		 *
{{ pgettext(‘Cancel Invoice’, ‘Cancel’, t) }}

		 *
		 * Example of translation including context with interpolation:
		 * `pgettext(context, ‘text’, [args], t)`
		 *
{{ pgettext(‘Cancel Invoice’, ‘Cancel {0}’,
		 *   document.type, t) }}

		 *
		 * @param {string} context Context text.
		 * @param {string} key Text to translate.
		 * @return {string} Translated text.
		 */
		pgettext: function (context, key) {
			this._ensureInitialized();

			var args = this._argumentsToObject(arguments, 2);
			args.context = context;
			// Don't make i18next fetch more translations
			delete args.count;
			return i18n.t(key, args);
		},

		/**
		 * Translates a text in singular or plural with a specific context.
		 *
		 * Example of translation in singular or plural with context:
		 * `npgettext(context, singular, plural, count, t)`
		 *
{{ npgettext('Cancel invoice', ‘My cancellation’,
		 *   ‘My {0} cancellations’, count, t) }}

		 *
		 * Example of translation in singular or plural with context and
		 * interpolation:
		 * `npgettext(context, singular, plural, count, t)`
		 *
{{ npgettext('Cancel invoice', ‘My {1} cancellation’,
		 *   ‘My {0} {1} cancellations’, count, document.type, t) }}

		 *
		 * @param {string} context Context text.
		 * @param {string} singular Singular text variant.
		 * @param {string} plural Plural text variant.
		 * @return {string} Translated text.
		 */
		npgettext: function (context, singular, plural) {
			this._ensureInitialized();

			var
				args = this._argumentsToObject(arguments, 3),
				n = args.count,
				key = singular,
				contextKeyPart = context
					? '_' + context
					: '';

			delete args.count;

			if (i18n.pluralExtensions.needsPlural(i18n.lng(), n)) {
				args.defaultValue = plural;
				key = i18n.options.ns.defaultNs + i18n.options.nsseparator + singular + contextKeyPart + i18n.options.pluralSuffix;
			} else {
				key = singular;
				args.context = context;
			}

			return i18n.t(key, args);
		}
	};

	Polymer({
		is: 'cosmoz-i18next',
		properties: {
			domain: {
				type: String,
				value: 'messages'
			},
			interpolationPrefix: {
				type: String,
				value: '__'
			},
			interpolationSuffix: {
				type: String,
				value: '__'
			},
			language: {
				type: String,
				value: 'en'
			},
			namespace: {
				type: String,
				value: 'translation'
			},
			translations: {
				type: Object,
				observer: '_setTranslations'
			},
			keySeparator: {
				type: String,
				value: '.'
			},
			nsSeparator: {
				type: String,
				value: ':'
			}
		},
		_setTranslations: function () {
			i18n.removeResourceBundle(this.language, this.namespace);
			i18n.addResources(this.language, this.namespace, this.translations);
			translationElements.forEach(function (element) {
				element.set('t', {});
			});
		},
		ready: function () {
			i18n.init({
				interpolationPrefix: this.interpolationPrefix,
				interpolationSuffix: this.interpolationSuffix,
				keyseparator: this.keySeparator,
				lng: this.language,
				nsseparator: this.nsSeparator,
				resStore: {}
			});
		}
	});
}());
<|endoftext|>


<commit_before>import React                    from 'react';
import {RouteHandler, Link} from 'react-router';
import moment from 'moment-timezone';
import _ from 'lodash';

class Main extends React.Component {
    constructor(props) {
        super(props);
        this.first = this.first.bind(this);
        this.second = this.second.bind(this);
        this.third = this.third.bind(this);
        this.save = this.save.bind(this);
    }

    componentDidMount() {
        var sorted = _.sortBy(moment.tz.names(), function (name) {
            return name;
        });
        var filter = [];
        _.each(sorted, function (name) {
            var f = name.split('/')[0];
            if (filter.indexOf(f) == -1) {
                filter.push(f);
            }
        });
        this.setState({
            firstChoice: filter,
            secondChoice: [],
            thirdChoice: [],
            first: null,
            second: null,
            third: null
        });
    }

    first(e) {
        e.preventDefault();
        var copy = this.state;
        copy.first = e.target.value;
        copy.second = null;
        copy.third = null;
        var sc = [];
        _.each(moment.tz.names(), function (name) {
            var elem = name.split('/');
            if (copy.first == elem[0] && elem.length > 1 && sc.indexOf(elem[1]) == -1) {
                sc.push(elem[1]);
            }
        });
        copy.secondChoice = sc;
        copy.thirdChoice = [];
        this.setState(copy);
    }

    second(e) {
        e.preventDefault();
        var copy = this.state;
        copy.second = e.target.value;
        copy.third = null;
        var tc = [];
        _.each(moment.tz.names(), function (name) {
            var elem = name.split('/');
            if (copy.first == elem[0] && elem.length > 2 && copy.second == elem[1] && tc.indexOf(elem[2]) == -1) {
                tc.push(elem[2]);
            }
        });
        copy.thirdChoice = tc;
        this.setState(copy);
    }

    third(e) {
        e.preventDefault();
        var copy = this.state;
        copy.third = e.target.value;
        this.setState(copy);
    }

    save(e) {
        e.preventDefault();
        if (this.state.thirdChoice.length > 0 && this.state.third != null) {
            localStorage.tz = this.state.first + '/' + this.state.second + '/' + this.state.third;
            $.notify('Region settings set.', {type: 'success'});
            this.props.history.push('/');
        } else if (this.state.secondChoice.length > 0 && this.state.second != null && this.state.thirdChoice.length == 0) {
            localStorage.tz = this.state.first + '/' + this.state.second;
            $.notify('Region settings set.', {type: 'success'});
            this.props.history.push('/');
        } else if (this.state.first != null && this.state.secondChoice.legnth == 0) {
            localStorage.tz = this.state.first;
            $.notify('Region settings set.', {type: 'success'});
            this.props.history.push('/');
        } else {
            $.notify('Not able to set regions, make sure all selected boxes have a value', {type: 'danger'});
        }
    }

    render() {
        var first = ' ';
        var second = ' ';
        if (this.state) {
            if (this.state.first == null) {
                first = <select value=" " name="region1" onChange={this.first}>
                    <option value=" "> </option>
                    {_.map(this.state.firstChoice, function (val, i) {
                        return (
                            <option value={val} key={i}>{val}</option>
                        )
                    })}
                </select>
            } else {
                first = <select value={this.state.first} name="region1" onChange={this.first}>
                    {_.map(this.state.firstChoice, function (val, i) {
                        return (
                            <option value={val} key={i}>{val}</option>
                        )
                    })}
                </select>
            }
            if (this.state.secondChoice.length > 0) {
                if (this.state.second == null) {
                    second =

                            <fieldset className="form-group col-sm-12">
                                Sub Region:
                            </fieldset>
                            <fieldset className="form-group col-sm-12">
                                <select value=" " name="region2" onChange={this.second}>
                                    <option value=" "> </option>
                                    {_.map(this.state.secondChoice, function (val, i) {
                                        return (
                                            <option value={val} key={i}>{val}</option>
                                        )
                                    })}
                                </select>
                            </fieldset>

                } else {
                    second =

                            <fieldset className="form-group col-sm-12">
                                Sub Region:
                            </fieldset>
                            <fieldset className="form-group col-sm-12">
                                <select value={this.state.second} name="region2" onChange={this.second}>
                                    {_.map(this.state.secondChoice, function (val, i) {
                                        return (
                                            <option value={val} key={i}>{val}</option>
                                        )
                                    })}
                                </select>
                            </fieldset>

                }
            }
            var third = ' ';
            if (this.state.thirdChoice.length > 0) {
                if (this.state.third == null) {
                    third =

                            <fieldset className="form-group col-sm-12">
                                Sub Sub Region:
                            </fieldset>
                            <fieldset className="form-group col-sm-12">
                                <select value=" " name="region3" onChange={this.third}>
                                    <option value=" "> </option>
                                    {_.map(this.state.thirdChoice, function (val, i) {
                                        return (
                                            <option value={val} key={i}>{val}</option>
                                        )
                                    })}
                                </select>
                            </fieldset>

                } else {
                    third =

                            <fieldset className="form-group col-sm-12">
                                Sub Sub Region:
                            </fieldset>
                            <fieldset className="form-group col-sm-12">
                                <select value={this.state.third} name="region2" onChange={this.third}>
                                    {_.map(this.state.thirdChoice, function (val, i) {
                                        return (
                                            <option value={val} key={i}>{val}</option>
                                        )
                                    })}
                                </select>
                            </fieldset>

                }
            }
        }
        return (

Settings

                                <form>
                                    <fieldset className="form-group col-sm-12">
                                        Region:
                                    </fieldset>
                                    <fieldset className="form-group col-sm-12">
                                        {first}
                                    </fieldset>
                                    {second}
                                    {third}
                                    <button className="btn btn-success" onClick={this.save}>Submit</button>
                                    <Link to="home">
                                        <button className="btn btn-danger">Cancel</button>
                                    </Link>
                                </form>

        );
    }
}

export default Main;
<commit_msg>fixed bug in cancel on settings and sets the value to the current tz setting or america/chicago if nothing is present in localStorage<commit_after>import React                    from 'react';
import {RouteHandler, Link} from 'react-router';
import moment from 'moment-timezone';
import _ from 'lodash';

class Main extends React.Component {
    constructor(props) {
        super(props);
        this.first = this.first.bind(this);
        this.second = this.second.bind(this);
        this.third = this.third.bind(this);
        this.save = this.save.bind(this);
    }

    componentDidMount() {
        var sorted = _.sortBy(moment.tz.names(), function (name) {
            return name;
        });
        var filter = [];
        _.each(sorted, function (name) {
            var f = name.split('/')[0];
            if (filter.indexOf(f) == -1) {
                filter.push(f);
            }
        });
        var first = null;
        var second = null;
        var third = null;
        if (localStorage.tz != null) {
            var split = localStorage.tz.split('/');
            first = split[0];
            if (split[1] != undefined) {
                second = split[1];
                if (split[2] != undefined) {
                    third = split[2];
                }
            }
        } else {
            first = 'America';
            second = 'Chicago';
        }
        this.setState({
            firstChoice: filter,
            secondChoice: [],
            thirdChoice: [],
            first: first,
            second: second,
            third: third
        }, function() {
            if (second != null) {
                var dummy = {target: {value: first, reset: false}};
                var self = this;
                this.first(dummy, function() {
                    if (third != null) {
                        dummy = {target: {value: second, reset: false}};
                        self.second(dummy);
                    }
                });
            }
        });
    }

    first(e, cb) {
        var copy = this.state;
        copy.first = e.target.value;
        if (e.target.reset != false) {
            copy.second = null;
            copy.third = null;
        }
        var sc = [];
        _.each(moment.tz.names(), function (name) {
            var elem = name.split('/');
            if (copy.first == elem[0] && elem.length > 1 && sc.indexOf(elem[1]) == -1) {
                sc.push(elem[1]);
            }
        });
        copy.secondChoice = sc;
        copy.thirdChoice = [];
        this.setState(copy, function() {
            if (cb != undefined) {
                cb();
            }
        });
    }

    second(e) {
        var copy = this.state;
        copy.second = e.target.value;
        if (e.target.reset != false) {
            copy.third = null;
        }
        var tc = [];
        _.each(moment.tz.names(), function (name) {
            var elem = name.split('/');
            if (copy.first == elem[0] && elem.length > 2 && copy.second == elem[1] && tc.indexOf(elem[2]) == -1) {
                tc.push(elem[2]);
            }
        });
        copy.thirdChoice = tc;
        this.setState(copy);
    }

    third(e) {
        var copy = this.state;
        copy.third = e.target.value;
        this.setState(copy);
    }

    save(e) {
        e.preventDefault();
        if (this.state.thirdChoice.length > 0 && this.state.third != null) {
            localStorage.tz = this.state.first + '/' + this.state.second + '/' + this.state.third;
            $.notify('Region settings set.', {type: 'success'});
            this.props.history.push('/');
        } else if (this.state.secondChoice.length > 0 && this.state.second != null && this.state.thirdChoice.length == 0) {
            localStorage.tz = this.state.first + '/' + this.state.second;
            $.notify('Region settings set.', {type: 'success'});
            this.props.history.push('/');
        } else if (this.state.first != null && this.state.secondChoice.legnth == 0) {
            localStorage.tz = this.state.first;
            $.notify('Region settings set.', {type: 'success'});
            this.props.history.push('/');
        } else {
            $.notify('Not able to set regions, make sure all selected boxes have a value', {type: 'danger'});
        }
    }

    render() {
        var first = ' ';
        var second = ' ';
        if (this.state) {
            if (this.state.first == null) {
                first = <select value=" " name="region1" onChange={this.first}>
                    <option value=" "> </option>
                    {_.map(this.state.firstChoice, function (val, i) {
                        return (
                            <option value={val} key={i}>{val}</option>
                        )
                    })}
                </select>
            } else {
                first = <select value={this.state.first} name="region1" onChange={this.first}>
                    {_.map(this.state.firstChoice, function (val, i) {
                        return (
                            <option value={val} key={i}>{val}</option>
                        )
                    })}
                </select>
            }
            if (this.state.secondChoice.length > 0) {
                if (this.state.second == null) {
                    second =

                            <fieldset className="form-group col-sm-12">
                                Sub Region:
                            </fieldset>
                            <fieldset className="form-group col-sm-12">
                                <select value=" " name="region2" onChange={this.second}>
                                    <option value=" "> </option>
                                    {_.map(this.state.secondChoice, function (val, i) {
                                        return (
                                            <option value={val} key={i}>{val}</option>
                                        )
                                    })}
                                </select>
                            </fieldset>

                } else {
                    second =

                            <fieldset className="form-group col-sm-12">
                                Sub Region:
                            </fieldset>
                            <fieldset className="form-group col-sm-12">
                                <select value={this.state.second} name="region2" onChange={this.second}>
                                    {_.map(this.state.secondChoice, function (val, i) {
                                        return (
                                            <option value={val} key={i}>{val}</option>
                                        )
                                    })}
                                </select>
                            </fieldset>

                }
            }
            var third = ' ';
            if (this.state.thirdChoice.length > 0) {
                if (this.state.third == null) {
                    third =

                            <fieldset className="form-group col-sm-12">
                                Sub Sub Region:
                            </fieldset>
                            <fieldset className="form-group col-sm-12">
                                <select value=" " name="region3" onChange={this.third}>
                                    <option value=" "> </option>
                                    {_.map(this.state.thirdChoice, function (val, i) {
                                        return (
                                            <option value={val} key={i}>{val}</option>
                                        )
                                    })}
                                </select>
                            </fieldset>

                } else {
                    third =

                            <fieldset className="form-group col-sm-12">
                                Sub Sub Region:
                            </fieldset>
                            <fieldset className="form-group col-sm-12">
                                <select value={this.state.third} name="region2" onChange={this.third}>
                                    {_.map(this.state.thirdChoice, function (val, i) {
                                        return (
                                            <option value={val} key={i}>{val}</option>
                                        )
                                    })}
                                </select>
                            </fieldset>

                }
            }
        }
        return (

Settings

                                <form>
                                    <fieldset className="form-group col-sm-12">
                                        Region:
                                    </fieldset>
                                    <fieldset className="form-group col-sm-12">
                                        {first}
                                    </fieldset>
                                    {second}
                                    {third}
                                    <button className="btn btn-success" onClick={this.save}>Submit</button>
                                    <Link to="/">
                                        <button className="btn btn-danger">Cancel</button>
                                    </Link>
                                </form>

        );
    }
}

export default Main;
<|endoftext|>


<commit_before>//la classe Window est l'objet de base.
//il permet de contenir les view. Ce sont ces memes Views qui contiennent les sprites.
//le constructeur de la view prend en parametre la width la height et le context
//(le context est le context2d du canvas sur lequel la window dessinera)
function Window(width, height, context)
{
 this.width = width;
 this.height = height;
 this.viewList = new Array();
 this.rotation = 0;
 this.x_center = 0;
 this.y_center = 0;
 this.x = 0;
 this.y = 0;
 this.scale_x = 1.0;
 this.scale_y = 1.0;
 this.context = context;
}

//Permet de definir la scale
Window.prototype.setScale = function(x, y)
{
 this.scale_x = x;
 this.scale_y = y;
}

//Permet de recuperer la scale
Window.prototype.getScale = function()
{
 return {x: this.scale_x, y: this.scale_y};
}

//Permet de definir la position x de la window
Window.prototype.setX = function(x)
{
 this.x = x;
}

//Permet de recuperer la valeur x de la window
Window.prototype.getX = function()
{
 return this.x;
}

//Permet de recuperer la valeur y de la window
Window.prototype.getY = function()
{
 return this.y;
}

//Permet de definir la position y de la window
Window.prototype.setY = function(y)
{
 this.y = y;
}

//Permet de definir l'angle de la rotation de la window
Window.prototype.setRotation = function(angle)
{
 this.rotation = angle / 180.0 * Math.PI;
}

//Permet de definir le point central de la window
Window.prototype.setCenterPoint = function(x, y)
{
 this.x_center = x;
 this.y_center = y;
}

//Permet de recuperer le point central de la view
Window.prototype.getCenterPoint = function()
{
 return {x: this.x_center, y: this.y_center};
}

//permet de recuperer l'angle de rotation
Window.prototype.getRotation = function()
{
 return this.rotation;
}

//permet de dessiner les objets sur la window
//la fonction de dessin dessine tous les sprites de toutes les views
Window.prototype.draw = function (context)
{
 var viewListLength = this.viewList.length;
 var i = 0;
 var ctx_tmp = context || 1;

 if (ctx_tmp == 1)
  ctx_tmp = this.context;

 ctx_tmp.save();
 ctx_tmp.clearRect(0,0,this.width, this.height);
 ctx_tmp.transform(1, 0, 0, 1, this.x + this.x_center, this.y + this.y_center);
 ctx_tmp.transform(Math.cos(this.rotation), -Math.sin(this.rotation), Math.sin(this.rotation), Math.cos(this.rotation), 0, 0);
 ctx_tmp.transform(this.scale_x, 0, 0, this.scale_y, 0, 0);
 ctx_tmp.transform(1, 0, 0, 1, -this.x_center, -this.y_center);
 while (i < viewListLength)
 {
  if (this.viewList[i].getX() < this.width && this.viewList[i].getX() + this.viewList[i].getWidth() >= 0 &&
      this.viewList[i].getY() < this.height && this.viewList[i].getY() + this.viewList[i].getHeight() >= 0)
    this.viewList[i].draw(ctx_tmp);
  i++;
 }
 ctx_tmp.restore();
}

//permet de recuperer la largeur de la window
Window.prototype.getWidth = function ()
{
 return this.width;
}

//permet de recuperer la height de la window
Window.prototype.getHeight = function ()
{
 return this.height;
}

//permet de recuperer le contexte de la window
Window.prototype.getContext = function ()
{
 return this.context;
}

//permet de set le context de la window
Window.prototype.setContext = function (context)
{
 this.context = context;
}

//permet d'ajouter une view pour pouvoir dessiner son contenu
Window.prototype.pushView = function(view)
{
 view.setWindow(this);
 this.viewList.push(view);
}

//permet de retirer une view de la window
Window.prototype.popView = function(ref)
{
 var size = this.viewList.length;
 var i = 0;

 while (i < size)
 {
  if (this.viewList[i] === ref)
   {
    this.viewList.splice(i, 1);
   }
  else
   {
    i++;
   }
 }
}<commit_msg>Window doc added<commit_after>/**
* @module Graphic
*/

/**
The Window class allow you to define an object who can hold Views. Views are likes layers. You can rotate, scale, and set the position of the window.
@class Window
@constructor
@param {integer} width the width of the window, if a View is out of bounds of the window's width object then it will not be drawn
@param {integer} height the height of the window, if a View is out of bounds of the window's height object then it will not be drawn
@param {graphicalContext2d} context the canvas' context on which Views will be drawn
*/
function Window(width, height, context)
{
 this.width = width;
 this.height = height;
 this.viewList = new Array();
 this.rotation = 0;
 this.x_center = 0;
 this.y_center = 0;
 this.x = 0;
 this.y = 0;
 this.scale_x = 1.0;
 this.scale_y = 1.0;
 this.context = context;
}

/**
The setScale method allow you to set the scales factor of the Window, note that you can scale each axis independently.
@method setScale
@param {float} x scale factor
@param {float} y scale factor
*/
Window.prototype.setScale = function(x, y)
{
 this.scale_x = x;
 this.scale_y = y;
}

/**
The getScale method allow you to get the scales factors of the Window object.
@method getScale
@return {Object} returns an Object containing the x scale factor and the y scale factor like this one {x: scale_x, y: scale_y}.
*/
Window.prototype.getScale = function()
{
 return {x: this.scale_x, y: this.scale_y};
}

/**
The setX method allow you to set the x coordinate of the Window object.
@method setX
@param {integer} x the x coordinate of the window
*/
Window.prototype.setX = function(x)
{
 this.x = x;
}

/**
The getX method allow you to get the x coordinate of the Window object.
@method getX
@return {integer} returns the  x coordinate of the Window object
*/
Window.prototype.getX = function()
{
 return this.x;
}

/**
The getY method allow you to get the y coordinate of the Window object.
@method getY
@return {integer} returns the y coordinate of the Window object
*/
Window.prototype.getY = function()
{
 return this.y;
}

/**
The setY method allow you to set the y coordinate of the window object
@method setY
@param {integer} y the y coordinate of the window
*/
Window.prototype.setY = function(y)
{
 this.y = y;
}

/**
The setRotation method allow you to set the angle of rotation of the window object
@method setRotation
@param {integer} angle the angle expressed in degree of the window object
*/
Window.prototype.setRotation = function(angle)
{
 this.rotation = angle / 180.0 * Math.PI;
}

/**
The setCenterPoint method allow you to set the center point (the center of rotation, scale, and translation) of the window object
@method setCenterPoint
@param {integer} x the x coordinate of the center point of the window object.
@param {integer} y the y coordinate of the center point of the window object.
*/
Window.prototype.setCenterPoint = function(x, y)
{
 this.x_center = x;
 this.y_center = y;
}

/**
The getCenterPoint method allow you to get the center point of the window object
@method getCenterPoint
@return {Object} returns an object that contains the [x; y] coordinate of the center point of the window object.
*/
Window.prototype.getCenterPoint = function()
{
 return {x: this.x_center, y: this.y_center};
}

/**
The getRotation method allow you to get the rotation angle of the window object
@method getRotation
@return {integer} returns the rotation angle of the window object expressed in degree.
*/
Window.prototype.getRotation = function()
{
 return this.rotation * 180.0 / Math.PI;
}

/**
The draw method allow you to draw all the views contained into the Window object, note that draw function will draw recursively all the Views and apply every transformations recursively too.
@method draw
@param {graphicalContext2d} context the canvas's context on which draw method will draw.
*/
Window.prototype.draw = function (context)
{
 var viewListLength = this.viewList.length;
 var i = 0;
 var ctx_tmp = context || 1;

 if (ctx_tmp == 1)
  ctx_tmp = this.context;

 ctx_tmp.save();
 ctx_tmp.clearRect(0,0,this.width, this.height);
 ctx_tmp.transform(1, 0, 0, 1, this.x + this.x_center, this.y + this.y_center);
 ctx_tmp.transform(Math.cos(this.rotation), -Math.sin(this.rotation), Math.sin(this.rotation), Math.cos(this.rotation), 0, 0);
 ctx_tmp.transform(this.scale_x, 0, 0, this.scale_y, 0, 0);
 ctx_tmp.transform(1, 0, 0, 1, -this.x_center, -this.y_center);
 while (i < viewListLength)
 {
  if (this.viewList[i].getX() < this.width && this.viewList[i].getX() + this.viewList[i].getWidth() >= 0 &&
      this.viewList[i].getY() < this.height && this.viewList[i].getY() + this.viewList[i].getHeight() >= 0)
    this.viewList[i].draw(ctx_tmp);
  i++;
 }
 ctx_tmp.restore();
}

/**
The getWidth method allow you to get the width of the window.
@method getWidth
@return {integer} returns the width of the window
*/
Window.prototype.getWidth = function ()
{
 return this.width;
}

/**
The getHeight method allow you to get the height of the Window
@method getHeight
@return {integer} returns the height of the window
*/
Window.prototype.getHeight = function ()
{
 return this.height;
}

/**
The getContext method allow you to get the context of the Window
@method getContext
@return {graphicalContext2d} canvas' context of the window.
*/
Window.prototype.getContext = function ()
{
 return this.context;
}

/**
The setContext method allow you to set the context of the window
@method setContext
@param {graphicalContext2d} context the canvas' context to set on the window object.
*/
Window.prototype.setContext = function (context)
{
 this.context = context;
}

/**
The pushView method allow you to add a View to the Window object.
@method pushView
@param {View} view the View object to add to the Window object
*/
Window.prototype.pushView = function(view)
{
 view.setWindow(this);
 this.viewList.push(view);
}

/**
The popView method allow you to suppress a View from the Window object.
@method popView
@param {View} ref the reference of the View object to suppress from the current Window object.
*/
Window.prototype.popView = function(ref)
{
 var size = this.viewList.length;
 var i = 0;

 while (i < size)
 {
  if (this.viewList[i] === ref)
   {
    this.viewList.splice(i, 1);
   }
  else
   {
    i++;
   }
 }
}
<|endoftext|>


<commit_before>'use strict'

const pipe = require('multipipe')
const data = require('vbb-trips')
const through = require('through2')
const ndjson = require('ndjson')
const fs = require('fs')

pipe(
	  data.routes('all')
	, through.obj(function (route, _, cb) {
		for (let i = 0; i < (route.stops.length - 1); i++) {
			const stop = route.stops[i]
			const next = route.stops[i + 1]
			for (let j = 0; j < route.when.length; j++) {
				const timestamp = route.when[j]
				this.push([stop.s, next.s, (stop.t + timestamp) / 1000])
			}
		}
		cb()
	})
	, ndjson.stringify()
	, fs.createWriteStream('data.ndjson')
	, (err) => {
		if (!err) return console.info('done')
		console.error('err', err.stack || err.message)
	}
)
<commit_msg>expose line id, gzip :package:<commit_after>'use strict'

const pipe = require('multipipe')
const data = require('vbb-trips')
const through = require('through2')
const ndjson = require('ndjson')
const zlib = require('zlib')
const fs = require('fs')

pipe(
	  data.routes('all')
	, through.obj(function (route, _, cb) {
		for (let i = 0; i < (route.stops.length - 1); i++) {
			const stop = route.stops[i]
			const next = route.stops[i + 1]
			for (let j = 0; j < route.when.length; j++) {
				const timestamp = route.when[j]
				this.push([
					stop.s, next.s,
					route.lineId,
					(stop.t + timestamp) / 1000
				])
			}
		}
		cb()
	})
	, ndjson.stringify()
	, zlib.createGzip()
	, fs.createWriteStream('data.ndjson.gz')
	, (err) => {
		if (!err) return console.info('done')
		console.error('err', err.stack || err.message)
	}
)
<|endoftext|>


<commit_before>let version = require('./package.json').devDependencies['electron-prebuilt'];
version = version.startsWith('^') ? version.substr(1) : version;

let ignore = ['icon.icns'];
if(process.platform!='win32') ignore.push('icon.ico');
if(process.platform!='darwin') ignore.push('tray_mac.png');
if(process.platform!='linux') {
    ignore.push('icon.png');
    ignore.push('tray_linux.png');
}

const packager = require('electron-packager');
const options = {
    name: 'SyncClick',
    platform: process.platform,
    arch: 'x64',
    dir: 'src',
    version: version,
    out: './releases',
    overwrite: true,
    tmpdir: false,
    icon: process.platform == 'win32' ? 'src/icon.ico' : (process.platform == 'darwin' ? 'src/icon.icns' : null ),
    ignore: ignore
};

packager(options, (err) => {
    if(err) {
        console.log(err);
    } else {
        console.log('Build successful!');
    }
});<commit_msg>Use asar<commit_after>let version = require('./package.json').devDependencies['electron-prebuilt'];
version = version.startsWith('^') ? version.substr(1) : version;

let ignore = ['icon.icns'];
if(process.platform!='win32') ignore.push('icon.ico');
if(process.platform!='darwin') ignore.push('tray_mac.png');
if(process.platform!='linux') {
    ignore.push('icon.png');
    ignore.push('tray_linux.png');
}

const packager = require('electron-packager');
const options = {
    name: 'SyncClick',
    asar: true,
    platform: process.platform,
    arch: 'x64',
    dir: 'src',
    version: version,
    out: './releases',
    overwrite: true,
    tmpdir: false,
    icon: process.platform == 'win32' ? 'src/icon.ico' : (process.platform == 'darwin' ? 'src/icon.icns' : null ),
    ignore: ignore
};

packager(options, (err) => {
    if(err) {
        console.log(err);
    } else {
        console.log('Build successful!');
    }
});<|endoftext|>


<commit_before>//
// angular-file-uploader factory
// ===========================
//
// Factory to support file upload with progress status on Angular.js.
//
// You can upload files with `$http.post` and a `FormData` object but
// don't get progress update on it.
//
(function() {
  'use strict';

  angular.module('angular-file-uploader', [])

    .factory('angularFileUploader', [
      '$q',
      '$rootScope',
      function($q, $rootScope) {
        return {
          //
          // Upload a file
          // -------------
          //
          // ### Arguments
          //
          // + `url` - `String` with the URI end-point.
          // + `files` - HTML file object, can be an `Array`
          // + `data` - (Optional) `JSON` with extra data to be sent
          // + `config` - (Optional) `Object` with extra stuff to be added to
          // request. Right now supports `headers` and `withCredentials`.
          //
          // ### E.g
          //
          // ```
          // var data = {'random': 'field'}; /* optional field */
          //
          // var config = { /* optional field */
          //   'headers': {
          //     'Authentication': 'Bearer randomasdasdas'
          //   },
          //   'withCredentials: true
          // };
          //
          // ngUpload.send('/end-point', fileArray);
          // ```
          //
          send: function(url, files, data, config) {

            var deferred = $q.defer();

            var xhr = new XMLHttpRequest();

            xhr.upload.onprogress = function (event) {
              $rootScope.$apply(function () {
                var percent;

                if (event.lengthComputable) {
                  percent = Math.round(event.loaded / (event.total * 100));

                  deferred.notify(percent);
                }
              });
            };

            xhr.onload = function () {
              $rootScope.$apply(function () {
                deferred.resolve({
                  files: files,
                  data: angular.fromJson(xhr.responseText)
                });
              });
            };

            xhr.upload.onerror = function () {
              var msg = xhr.responseText ? xhr.responseText : 'Error occurred uploading to ' + url;

              $rootScope.$apply(function () {
                deferred.reject(msg);
              });
            };

            var fd = new FormData();

            //
            // If there are no files then `$http.post` should
            // be used instead.
            //
            if (files == null)
              deferred.reject('There\'s no files to upload');

            //
            // There's data to be added to the payload on this upload?
            //
            if (data) {
              Object.keys(data).forEach(function (element) {
                fd.append(element, data[element]);
              });
            }

            //
            // Load the files in the formData object
            //
            //
            if (files.length) {
              for (var i = 0; i < files.length; i++) {
                fd.append(files[i].name, files[i]);
              }
            } else {
              fd.append(files.name, files);
            }

            //
            // Send the files
            //
            xhr.open('POST', url);

            //
            // Adding configs
            // --------------
            //
            // ### Any config for headers?
            //
            if (config && config.headers != null) {
              Object.keys(config.headers).forEach(function (element) {
                xhr.setRequestHeader(element, config.headers[element]);
              });
            }

            //
            // ### With Credentials
            //
            if (config && config.withCredentials != null) {
              xhr.withCredentials = config.withCredentials;
            }

            xhr.send(fd);

            return deferred.promise;

          }
        };
      }
    ]);
})();
<commit_msg>config holds data now and supports Objects and Strings<commit_after>//
// angular-file-uploader factory
// ===========================
//
// Factory to support file upload with progress status on Angular.js.
//
// You can upload files with `$http.post` and a `FormData` object but
// don't get progress update on it.
//
(function() {
  'use strict';

  angular.module('angular-file-uploader', [])

    .factory('angularFileUploader', [
      '$q',
      '$rootScope',
      function($q, $rootScope) {
        return {
          //
          // Upload a file
          // -------------
          //
          // ### Arguments
          //
          // + `url` - `String` with the URI end-point.
          // + `files` - HTML file object, can be an `Array`
          // + `data` - (Optional) `JSON` with extra data to be sent
          // + `config` - (Optional) `Object` with extra stuff to be added to
          // request. Right now supports `headers` and `withCredentials`.
          //
          // ### E.g
          //
          // ```
          // var data = {'random': 'field'}; /* optional field */
          //
          // var config = { /* optional field */
          //   'headers': {
          //     'Authentication': 'Bearer randomasdasdas'
          //   },
          //   'withCredentials: true
          // };
          //
          // ngUpload.send('/end-point', fileArray);
          // ```
          //
          send: function(url, files, data, config) {

            var deferred = $q.defer();

            var xhr = new XMLHttpRequest();

            xhr.upload.onprogress = function (event) {
              $rootScope.$apply(function () {
                var percent;

                if (event.lengthComputable) {
                  percent = Math.round(event.loaded / (event.total * 100));

                  deferred.notify(percent);
                }
              });
            };

            xhr.onload = function () {
              $rootScope.$apply(function () {
                deferred.resolve({
                  files: files,
                  data: angular.fromJson(xhr.responseText)
                });
              });
            };

            xhr.upload.onerror = function () {
              var msg = xhr.responseText ? xhr.responseText : 'Error occurred uploading to ' + url;

              $rootScope.$apply(function () {
                deferred.reject(msg);
              });
            };

            var fd = new FormData();

            //
            // If there are no files then `$http.post` should
            // be used instead.
            //
            if (files == null)
              deferred.reject('There\'s no files to upload');

            //
            // There's data to be added to the payload on this upload?
            //
            if (config && config.data != null) {
              // If it's an Object then run over it, if not add it as `data` field.
              if (typeof config.data === 'object') {
                Object
                  .keys(config.data)
                  .forEach(function (element) {
                    fd.append(element, config.data[element]);
                  }
                );
              } else {
                fd.append('data', config.data);
              }
            }

            //
            // Load the files in the formData object
            //
            //
            if (files.length) {
              for (var i = 0; i < files.length; i++) {
                fd.append(files[i].name, files[i]);
              }
            } else {
              fd.append(files.name, files);
            }

            //
            // Send the files
            //
            xhr.open('POST', url);

            //
            // Adding configs
            // --------------
            //
            // ### Any config for headers?
            //
            if (config && config.headers != null) {
              Object.keys(config.headers).forEach(function (element) {
                xhr.setRequestHeader(element, config.headers[element]);
              });
            }

            //
            // ### With Credentials
            //
            if (config && config.withCredentials != null) {
              xhr.withCredentials = config.withCredentials;
            }

            xhr.send(fd);

            return deferred.promise;

          }
        };
      }
    ]);
})();
<|endoftext|>


<commit_before>'use strict';

const glob = require('fast-glob');
const { promisify } = require('util');
const { build } = require('esbuild');
const fs = require('fs');
const copyFiles = promisify( require('copyfiles'));
const path = require('path');
const exec = promisify(require('child_process').exec);

const rmdir = promisify(fs.rmdir);
const stat = promisify(fs.stat);

// if this script is moved, this will need to be adjusted
const rootDir = __dirname;
const outdir = path.join(rootDir, 'dist');

const nodeMajorVersion = Number(process.version.match(/(?<=^v)\d+/));

async function rmDistDir() {
  try {
    await stat(outdir);
    if (nodeMajorVersion >= 12) {
      await rmdir(outdir, { recursive: true });
    } else {
      await rmdir(outdir);
    }
  } catch {
    /* no-op */
  }
}

async function main() {
  console.log('Compiling sequelize...');
  const [declarationFiles, filesToCompile] = await Promise.all([
    // Find all .d.ts files from types/
    glob('./types/**/*.d.ts', { onlyFiles: true, absolute: false }),
    // Find all .js and .ts files from lib/
    glob('./lib/**/*.[tj]s', { onlyFiles: true, absolute: false }),
    // Delete dist/ for a full rebuild.
    rmDistDir()
  ]);

  // copy .d.ts files prior to generating them from the .ts files
  // so the .ts files in lib/ will take priority..
  await copyFiles(
    // The last path in the list is the output directory
    declarationFiles.concat(outdir),
    { up: 1 }
  );

  await Promise.all([
    build({
      // Adds source mapping
      sourcemap: true,
      // The compiled code should be usable in node v10
      target: 'node10',
      // The source code's format is commonjs.
      format: 'cjs',

      outdir,
      entryPoints: filesToCompile
        .concat('./index.js')
        .map(file => path.resolve(file))
    }),

    exec('tsc', {
      env: {
        // binaries installed from modules have symlinks in
        // <pkg root>/node_modules/.bin.
        PATH: `${process.env.PATH || ''}:${path.join(
          rootDir,
          'node_modules/.bin'
        )}`
      },
      cwd: rootDir
    })
  ]);
}

main().catch(console.error).finally(process.exit);

<commit_msg>refactor(build): use rm instead of rmdir for Node 14 and up (#13702)<commit_after>'use strict';

const glob = require('fast-glob');
const { promisify } = require('util');
const { build } = require('esbuild');
const fs = require('fs');
const copyFiles = promisify( require('copyfiles'));
const path = require('path');
const exec = promisify(require('child_process').exec);

const stat = promisify(fs.stat);

// if this script is moved, this will need to be adjusted
const rootDir = __dirname;
const outdir = path.join(rootDir, 'dist');

const nodeMajorVersion = Number(process.version.match(/(?<=^v)\d+/));

async function rmDistDir() {
  try {
    await stat(outdir);
    if (nodeMajorVersion >= 14) {
      const rm = promisify(fs.rm);
      await rm(outdir, { recursive: true });
    } else {
      const rmdir = promisify(fs.rmdir);
      if (nodeMajorVersion >= 12) {
        await rmdir(outdir, { recursive: true });
      } else {
        await rmdir(outdir);
      }}
  } catch {
    /* no-op */
  }
}

async function main() {
  console.log('Compiling sequelize...');
  const [declarationFiles, filesToCompile] = await Promise.all([
    // Find all .d.ts files from types/
    glob('./types/**/*.d.ts', { onlyFiles: true, absolute: false }),
    // Find all .js and .ts files from lib/
    glob('./lib/**/*.[tj]s', { onlyFiles: true, absolute: false }),
    // Delete dist/ for a full rebuild.
    rmDistDir()
  ]);

  // copy .d.ts files prior to generating them from the .ts files
  // so the .ts files in lib/ will take priority..
  await copyFiles(
    // The last path in the list is the output directory
    declarationFiles.concat(outdir),
    { up: 1 }
  );

  await Promise.all([
    build({
      // Adds source mapping
      sourcemap: true,
      // The compiled code should be usable in node v10
      target: 'node10',
      // The source code's format is commonjs.
      format: 'cjs',

      outdir,
      entryPoints: filesToCompile
        .concat('./index.js')
        .map(file => path.resolve(file))
    }),

    exec('tsc', {
      env: {
        // binaries installed from modules have symlinks in
        // <pkg root>/node_modules/.bin.
        PATH: `${process.env.PATH || ''}:${path.join(
          rootDir,
          'node_modules/.bin'
        )}`
      },
      cwd: rootDir
    })
  ]);
}

main().catch(console.error).finally(process.exit);

<|endoftext|>


<commit_before>/* eslint camelcase: "off" */

'use strict'

const fs = require('fs')
const path = require('path')
const del = require('del')
const globby = require('globby')
const regenerate = require('regenerate')
const babel = require('babel-core')
const browserify = require('browserify')

const srcDir = 'src'
const libDir = 'lib'
const distDir = 'dist'

function clean () {
	del.sync(libDir)
	del.sync(distDir)
}

function buildUnicode () {
	const Space_Separator = regenerate()
		.add(require('unicode-9.0.0/General_Category/Space_Separator/code-points'))
		.remove('\t', '\v', '\f', ' ', '\u00A0', '\uFEFF')

	const ID_Start = regenerate()
		.add(require('unicode-9.0.0/Binary_Property/ID_Start/code-points'))
		.remove('$', '_')
		.removeRange('A', 'Z')
		.removeRange('a', 'z')

	const ID_Continue = regenerate()
		.add(require('unicode-9.0.0/Binary_Property/ID_Continue/code-points'))
		.remove('$', '_')
		.removeRange('0', '9')
		.removeRange('A', 'Z')
		.removeRange('a', 'z')

	const outDir = libDir
	const outPath = path.join(outDir, 'unicode.js')

	if (!fs.existsSync(outDir)) {
		fs.mkdirSync(outDir)
	}

	write({
		Space_Separator,
		ID_Start,
		ID_Continue,
	})

	function write (data) {
		fs.writeFileSync(outPath, 'module.exports = {\n')
		for (const key in data) {
			fs.appendFileSync(outPath, `${key}: /${data[key]}/,\n`)
		}

		fs.appendFileSync(outPath, '}\n')
	}
}

function buildBabel () {
	const inDir = srcDir
	const outDir = libDir

	if (!fs.existsSync(outDir)) {
		fs.mkdirSync(outDir)
	}

	const inPaths = globby.sync('*.js', {cwd: inDir})
	for (const inPath of inPaths) {
		const code = babel.transformFileSync(path.join(inDir, inPath)).code
		fs.writeFileSync(path.join(outDir, inPath), code)
	}
}

function buildBrowserify () {
	const inPath = path.join(srcDir, 'index.js')
	const outDir = distDir
	const outPath = path.join(outDir, 'jsonext.js')

	if (!fs.existsSync(outDir)) {
		fs.mkdirSync(outDir)
	}

	browserify(inPath)
		.transform('babelify', {presets: ['es2015']})
		.bundle()
		.pipe(fs.createWriteStream(outPath))
}

clean()
buildUnicode()
buildBabel()
buildBrowserify()
<commit_msg>Set JSONext globally in browsers<commit_after>/* eslint camelcase: "off" */

'use strict'

const fs = require('fs')
const path = require('path')
const del = require('del')
const globby = require('globby')
const regenerate = require('regenerate')
const babel = require('babel-core')
const browserify = require('browserify')

const srcDir = 'src'
const libDir = 'lib'
const distDir = 'dist'

function clean () {
	del.sync(libDir)
	del.sync(distDir)
}

function buildUnicode () {
	const Space_Separator = regenerate()
		.add(require('unicode-9.0.0/General_Category/Space_Separator/code-points'))
		.remove('\t', '\v', '\f', ' ', '\u00A0', '\uFEFF')

	const ID_Start = regenerate()
		.add(require('unicode-9.0.0/Binary_Property/ID_Start/code-points'))
		.remove('$', '_')
		.removeRange('A', 'Z')
		.removeRange('a', 'z')

	const ID_Continue = regenerate()
		.add(require('unicode-9.0.0/Binary_Property/ID_Continue/code-points'))
		.remove('$', '_')
		.removeRange('0', '9')
		.removeRange('A', 'Z')
		.removeRange('a', 'z')

	const outDir = libDir
	const outPath = path.join(outDir, 'unicode.js')

	if (!fs.existsSync(outDir)) {
		fs.mkdirSync(outDir)
	}

	write({
		Space_Separator,
		ID_Start,
		ID_Continue,
	})

	function write (data) {
		fs.writeFileSync(outPath, 'module.exports = {\n')
		for (const key in data) {
			fs.appendFileSync(outPath, `${key}: /${data[key]}/,\n`)
		}

		fs.appendFileSync(outPath, '}\n')
	}
}

function buildBabel () {
	const inDir = srcDir
	const outDir = libDir

	if (!fs.existsSync(outDir)) {
		fs.mkdirSync(outDir)
	}

	const inPaths = globby.sync('*.js', {cwd: inDir})
	for (const inPath of inPaths) {
		const code = babel.transformFileSync(path.join(inDir, inPath)).code
		fs.writeFileSync(path.join(outDir, inPath), code)
	}
}

function buildBrowserify () {
	const inPath = path.join(srcDir, 'index.js')
	const outDir = distDir
	const outPath = path.join(outDir, 'jsonext.js')

	if (!fs.existsSync(outDir)) {
		fs.mkdirSync(outDir)
	}

	browserify(inPath, {standalone: 'JSONext'})
		.transform('babelify', {presets: ['es2015']})
		.bundle()
		.pipe(fs.createWriteStream(outPath))
}

clean()
buildUnicode()
buildBabel()
buildBrowserify()
<|endoftext|>


<commit_before>var fs = require('fs'),
	PEG = require('pegjs');
var rmDir = function(dirPath) {
	try { var files = fs.readdirSync(dirPath); }
	catch(e) { return; }
	if (files.length > 0)
		for (var i = 0; i < files.length; i++) {
			var filePath = dirPath + '/' + files[i];
			if (fs.statSync(filePath).isFile())
				fs.unlinkSync(filePath);
			else
				rmDir(filePath);
		}
	fs.rmdirSync(dirPath);
};
try {
	fs.unlinkSync('src/parser.js');
	fs.unlinkSync('src/LineTerminator.js');
	fs.unlinkSync('extras/mammouth.js');
	fs.unlinkSync('extras/mammouth-nodejs.js');
} catch(e) {
	console.log(err);
}
try {
	var data = '';
	data += 'var mammouth = {};' + "\n";
	rf = fs.readFileSync('src/parser.pegjs', 'utf8')
	r = PEG.buildParser(rf, {})._source;
	fs.writeFile('src/parser.js', 'mammouth.parser' + " = " + r + ';', function () {
	});
	data += 'mammouth.parser' + " = " + r + ';';
	rf = fs.readFileSync('src/LineTerminator.pegjs', 'utf8')
	r = PEG.buildParser(rf, {})._source;
	fs.writeFile('src/LineTerminator.js', 'mammouth.LineTerminatorParser' + " = " + r + ';', function () {
	});
	data += 'mammouth.LineTerminatorParser' + " = " + r + ';';
	data += fs.readFileSync('src/tokens.js').toString() + '\n';
	data += fs.readFileSync('src/compiler.js').toString() + '\n';
	fs.appendFileSync("extras/mammouth.js", data + "\n");
} catch(err) {
	console.log(err);
}
try {
	var data = '';
	data += fs.readFileSync('extras/mammouth.js').toString() + '\n';
	data += 'module.exports = mammouth;' + "\n";
	fs.appendFileSync("extras/mammouth-nodejs.js", data);
} catch(err) {
	console.log(err);
}<commit_msg>FIX: error throwing<commit_after>var fs = require('fs'),
	PEG = require('pegjs');
var rmDir = function(dirPath) {
	try { var files = fs.readdirSync(dirPath); }
	catch(e) { return; }
	if (files.length > 0)
		for (var i = 0; i < files.length; i++) {
			var filePath = dirPath + '/' + files[i];
			if (fs.statSync(filePath).isFile())
				fs.unlinkSync(filePath);
			else
				rmDir(filePath);
		}
	fs.rmdirSync(dirPath);
};
try {
	fs.unlinkSync('src/parser.js');
	fs.unlinkSync('src/LineTerminator.js');
	fs.unlinkSync('extras/mammouth.js');
	fs.unlinkSync('extras/mammouth-nodejs.js');
} catch(err) {
	console.log(err);
}
try {
	var data = '';
	data += 'var mammouth = {};' + "\n";
	rf = fs.readFileSync('src/parser.pegjs', 'utf8')
	r = PEG.buildParser(rf, {})._source;
	fs.writeFile('src/parser.js', 'mammouth.parser' + " = " + r + ';', function () {
	});
	data += 'mammouth.parser' + " = " + r + ';';
	rf = fs.readFileSync('src/LineTerminator.pegjs', 'utf8')
	r = PEG.buildParser(rf, {})._source;
	fs.writeFile('src/LineTerminator.js', 'mammouth.LineTerminatorParser' + " = " + r + ';', function () {
	});
	data += 'mammouth.LineTerminatorParser' + " = " + r + ';';
	data += fs.readFileSync('src/tokens.js').toString() + '\n';
	data += fs.readFileSync('src/compiler.js').toString() + '\n';
	fs.appendFileSync("extras/mammouth.js", data + "\n");
} catch(err) {
	console.log(err);
}
try {
	var data = '';
	data += fs.readFileSync('extras/mammouth.js').toString() + '\n';
	data += 'module.exports = mammouth;' + "\n";
	fs.appendFileSync("extras/mammouth-nodejs.js", data);
} catch(err) {
	console.log(err);
}<|endoftext|>


<commit_before>
var rooms = [];
var greenColorMin = 0;
var greenColorMax = 0;
var yellowColorMax = 0;
var yellowColorMin = 0;
var redColorMin = 0;
var redColorMax = 0;

var maxDayBars = 12;
var maxWeekBars = 7;

var minNumber = 1;
var maxNumber = 100;

var greenColor = '#4fc14e';
var redColor = '#FF5454';
var yellowColor = '#FFAA54';

var procentageScaleConverter = 148/100;

var randomNumber = 0;

var roomID = "";

function getRandomNumber () {
randomNumber = Math.floor((Math.random() * maxNumber) + minNumber);
return randomNumber;
}

function setTemperatureGraphMonth () {

minNumber = 45;
maxNumber = 50;

for (var i = maxDayBars; i >= 1; i--) {

var myID = "Temp-Graph-Day-" + i;

if (i === 1) {
var myTemperature = rooms[roomID].temp * procentageScaleConverter; //Does not show up 100% accuratly
document.getElementById(myID).style.height = myTemperature + 'px';
}
else {
document.getElementById(myID).style.height = getRandomNumber() + 'px';
}
}
}

function setHumidityGraphs () {

minNumber = 40;
maxNumber = 80;

greenColorMin = 41;
greenColorMax = 59;
yellowColorMin = 0;
yellowColorMax = 40;
redColorMin = 60;
redColorMax = 100;

var roomConvertedHumidity = rooms[roomID].humidity;

//Set the humidity status text
if (roomConvertedHumidity > redColorMin) {
setStatusAndImprovementDescription("red");
//console.log("Status - Red color");
}
else if (roomConvertedHumidity > yellowColorMax && roomConvertedHumidity < redColorMin) {
setStatusAndImprovementDescription("green");
//console.log("Status - green color");
}
else {
setStatusAndImprovementDescription("yellow");
//console.log("Status - Yellow color");
}

//console.log("Status" + rooms[roomID].humidity);

//Set the graph bars
for (var i = maxWeekBars; i >= 1; i--) {

var myID = "Humidity-Graph-" + i;

//onsole.log(myID);

if (i === 1) {
var myHumidity = rooms[roomID].humidity * procentageScaleConverter; //Does not show up 100% accuratly
document.getElementById(myID).style.height = myHumidity + 'px';
document.getElementById(myID).style.backgroundColor = setHumidityGtaphBarColor(myHumidity);

}
else {
var randomHumidity = getRandomNumber();// * procentageScaleConverter;
console.log("My random humidity is: ", randomHumidity);
document.getElementById(myID).style.height = randomHumidity + 'px';
console.log("My random graph hight is : ", document.getElementById(myID).style.height);
document.getElementById(myID).style.backgroundColor = setHumidityGtaphBarColor();
console.log("My random color hight is : ", document.getElementById(myID).style.backgroundColor);
}
}

}

//Setup the detail text
//Status ID: detail-status-description
//Solution ID: detail-status-solution
function setStatusAndImprovementDescription (status) {
//Humidity
var humidityDescriptionText = "";

	//console.log("The status is: ", status);

// Red status
if (status === "red") {
humidityDescriptionText = "This room has a very high humidity of " + rooms[roomID].humidity + "%. This can cause mould and fongus if the temperature gets too low. Make sure that you ventilate the room to bring the humidity down.";
}
// Yellow status
else if (status === "yellow") {
humidityDescriptionText = "This room has a low humidity level of " + rooms[roomID].humidity + "%. This can cause irritation for the loungs and allergies.";
}
// Green Status
else if (status === "green") {
humidityDescriptionText = "This room has a great humidity level of " + rooms[roomID].humidity + "%. Keep up the good work!";
}
//Set the text description on the DOM
document.getElementById("detail-status-description").innerHTML = humidityDescriptionText;
}

function setAirQualityGraphs () {

minNumber = 40;
maxNumber = 80;

greenColorMin = 0 * procentageScaleConverter;
greenColorMax = 59 * procentageScaleConverter;
yellowColorMin = 60;
yellowColorMax = 89 * procentageScaleConverter;
redColorMin = 90 * procentageScaleConverter;
redColorMax = 200 * procentageScaleConverter;

getRandomNumber()
document.getElementById("AirQuality-Graph-1").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-1").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-2").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-2").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-3").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-3").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-4").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-4").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-5").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-5").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-6").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-6").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-7").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-7").style.backgroundColor = setAirGtaphBarColor();
}

function setHumidityGtaphBarColor (value)
{

if (!value) {
	value = randomNumber;
	//console.log("The random number is not here!");
}

if (value > redColorMin)
{
//console.log('RedColor ', randomNumber);
return redColor;
}
else if (value > yellowColorMax && value < redColorMin) {
//console.log('GreenColor ', randomNumber);
return greenColor;
}
else {
//console.log('YellowColor ', randomNumber);
return yellowColor;
}
}

function setAirGtaphBarColor ()
{
if (randomNumber > redColorMin)
{
//console.log('RedColor ', randomNumber);
return redColor;
}
else if (randomNumber > greenColorMax && randomNumber < redColorMin) {
//console.log('YellowColor ', randomNumber);
return yellowColor;
}
else {
//console.log('GreenColor ', randomNumber);
return greenColor;
}
}

//Link parsing function
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function getRoomsDataFromStorage () {
// Retrieve the object from storage
rooms = JSON.parse(localStorage.getItem("rooms"));
//console.log('retrievedObject: ', rooms);

roomID = getParameterByName("roomid");
//console.log("Room ide is: ", roomID);

var roomName = document.getElementById("detail-title");
roomName.innerHTML = rooms[roomID].name.toUpperCase();

//Set teh room icon
var roomIcon = document.getElementsByClassName("details-header-status-image")[0];
roomIcon.src = rooms[roomID].icon;

//Set the back arrow url link so that the rooms will be loaded from memory

var backArrowLink = document.getElementById("back-arrow-link");
backArrowLink.href += "?loaded=1";
//console.log("The new link is: ", backArrowLink.href);

var currentStatus = getRoomStatus(rooms[roomID]);
//console.log("The current room status is: ", currentStatus);
//If the status is 3 or above
if (currentStatus >= 3) {
    redStatus();
}
//Else If the status is above 2
else if (currentStatus > 2) {
  yellowStatus();
}
//Else
else  {
  greenStatus();
}
}

/*WARNING !!! THE FOLLOWING 4 METHODS ARE DIRECT DUBLICATES FROM MAIN.js - THEY SHOULD BE SEPERATED INTO SEPERATE JS FUNCTIONS --- */
function getRoomStatus (room) {

    var midResult = 0;
    var hum = returnHumidityStatus(room.humidity);
    var air = returnAirQualStatus(room.airqual)
    midResult += hum + air;

    return midResult;
}

function returnHumidityStatus (value) {

var greenColorMin = 41;
var greenColorMax = 59;
var yellowColorMin = 0;
var yellowColorMax = 40;
var redColorMin = 60;
var redColorMax = 100;

if (value > redColorMin)
{
//console.log('RedColor ', value);
return 3;
}
else if (value > yellowColorMax && value < redColorMin) {
//console.log('GreenColor ', value);
return 0;
}
else {
//console.log('YellowColor ', value);
return 2;
}

}

function returnAirQualStatus (value) {

var greenColorMin = 0;
var greenColorMax = 999;
var yellowColorMin = 1000;
var yellowColorMax = 1299;
var redColorMin = 1300;
var redColorMax = 1600;

if (value > redColorMin)
{
//console.log('RedColor ', value);
return 3;
}
else if (value > greenColorMax && value < redColorMin) {
//console.log('YellowColor ', value);
return 2;
}
else {
//console.log('GreenColor ', value);
return 0;
}
}

function greenStatus () {
//Green status
    document.getElementById("status-back-div").style.backgroundColor = greenColor;
   // document.getElementById("Status-Image").src = greenStatusImage;
    //document.getElementById("Status-Heading").innerHTML = "GREAT INDOOR CLIMATE";
    //document.getElementById("Status-Heading").style.color = greenColor;
    //document.getElementById("Status-Heading-Text").innerHTML = "Your home has a great overall indoor climate.";
}

function yellowStatus () {
    document.getElementById("status-back-div").style.backgroundColor = yellowColor;
   // document.getElementById("Status-Image").src = yellowStatusImage;
    //document.getElementById("Status-Heading").innerHTML = "COULD BE IMPROVED";
    //document.getElementById("Status-Heading").style.color = yellowColor;
    //document.getElementById("Status-Heading-Text").innerHTML = "Your home needs ventilation in your " + rooms[0].name + ", and in " + rooms[1].name + ".";
}

function redStatus () {
    document.getElementById("status-back-div").style.backgroundColor = redColor;
   // document.getElementById("Status-Image").src = redStatusImage;
   // document.getElementById("Status-Heading").innerHTML = "CRITICAL INDOOR CLIMATE";
   // document.getElementById("Status-Heading").style.color = redColor;
   // document.getElementById("Status-Heading-Text").innerHTML = "Your home needs ventilation in your " + rooms[0].name + ", and in " + rooms[1].name + ".";
}

getRoomsDataFromStorage();
setHumidityGraphs();
setTemperatureGraphMonth();
setAirQualityGraphs();

$(window).load(function() {

  var loadingDiv = document.getElementsByClassName("loading")[0];
  //console.log("Div is: ", loadingDiv);
  //loadingDiv.style.display = "none"
  $(".loading").fadeOut();
});
<commit_msg>Big changes to air graphs<commit_after>
var rooms = [];
var greenColorMin = 0;
var greenColorMax = 0;
var yellowColorMax = 0;
var yellowColorMin = 0;
var redColorMin = 0;
var redColorMax = 0;

var maxDayBars = 12;
var maxWeekBars = 7;

//var minNumber = 1;
//var maxNumber = 100;

var greenColor = '#4fc14e';
var redColor = '#FF5454';
var yellowColor = '#FFAA54';

var procentageScaleConverter = 148/100;

//var randomNumber = 0;

var roomID = "";

function getRandomNumber (minNumber, maxNumber) {
var randomNumber = Math.floor((Math.random() * maxNumber) + minNumber);
return randomNumber;
}

function setTemperatureGraphMonth () {

var minNumber = 45;
var maxNumber = 50;

for (var i = maxDayBars; i >= 1; i--) {

var myID = "Temp-Graph-Day-" + i;

if (i === 1) {
var myTemperature = rooms[roomID].temp * procentageScaleConverter; //Does not show up 100% accuratly
document.getElementById(myID).style.height = myTemperature + 'px';
}
else {
document.getElementById(myID).style.height = getRandomNumber(minNumber, maxNumber) + 'px';
}
}
}

function setHumidityGraphs () {

var minNumber = 40;
var maxNumber = 80;

greenColorMin = 41;
greenColorMax = 59;
yellowColorMin = 0;
yellowColorMax = 40;
redColorMin = 60;
redColorMax = 100;

var roomConvertedHumidity = rooms[roomID].humidity;

//Set the humidity status text
if (roomConvertedHumidity > redColorMin) {
setStatusAndImprovementDescription("red");
//console.log("Status - Red color");
}
else if (roomConvertedHumidity > yellowColorMax && roomConvertedHumidity < redColorMin) {
setStatusAndImprovementDescription("green");
//console.log("Status - green color");
}
else {
setStatusAndImprovementDescription("yellow");
//console.log("Status - Yellow color");
}

//console.log("Status" + rooms[roomID].humidity);

//Set the graph bars
for (var i = maxWeekBars; i >= 1; i--) {

var myID = "Humidity-Graph-" + i;

//onsole.log(myID);

if (i === 1) {
var myHumidity = rooms[roomID].humidity * procentageScaleConverter; //Does not show up 100% accuratly
document.getElementById(myID).style.height = myHumidity + 'px';
document.getElementById(myID).style.backgroundColor = setHumidityGtaphBarColor(myHumidity);

}
else {
var randomHumidity = getRandomNumber(minNumber, maxNumber);// * procentageScaleConverter;
console.log("My random humidity is: ", randomHumidity);
document.getElementById(myID).style.height = randomHumidity + 'px';
console.log("My random graph hight is : ", document.getElementById(myID).style.height);
document.getElementById(myID).style.backgroundColor = setHumidityGtaphBarColor();
console.log("My random color hight is : ", document.getElementById(myID).style.backgroundColor);
}
}

}

//Setup the detail text
//Status ID: detail-status-description
//Solution ID: detail-status-solution
function setStatusAndImprovementDescription (status) {
//Humidity
var humidityDescriptionText = "";

	//console.log("The status is: ", status);

// Red status
if (status === "red") {
humidityDescriptionText = "This room has a very high humidity of " + rooms[roomID].humidity + "%. This can cause mould and fongus if the temperature gets too low. Make sure that you ventilate the room to bring the humidity down.";
}
// Yellow status
else if (status === "yellow") {
humidityDescriptionText = "This room has a low humidity level of " + rooms[roomID].humidity + "%. This can cause irritation for the loungs and allergies.";
}
// Green Status
else if (status === "green") {
humidityDescriptionText = "This room has a great humidity level of " + rooms[roomID].humidity + "%. Keep up the good work!";
}
//Set the text description on the DOM
document.getElementById("detail-status-description").innerHTML = humidityDescriptionText;
}

function setAirQualityGraphs () {

var minNumber = 40;
var maxNumber = 80;

greenColorMin = 0 * procentageScaleConverter;
greenColorMax = 59 * procentageScaleConverter;
yellowColorMin = 60;
yellowColorMax = 89 * procentageScaleConverter;
redColorMin = 90 * procentageScaleConverter;
redColorMax = 200 * procentageScaleConverter;

	/*
getRandomNumber(minNumber, maxNumber)
document.getElementById("AirQuality-Graph-1").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-1").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-2").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-2").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-3").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-3").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-4").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-4").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-5").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-5").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-6").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-6").style.backgroundColor = setAirGtaphBarColor();
getRandomNumber()
document.getElementById("AirQuality-Graph-7").style.height = randomNumber + 'px';
document.getElementById("AirQuality-Graph-7").style.backgroundColor = setAirGtaphBarColor();
	*/

	//Set the graph bars
for (var i = maxWeekBars; i >= 1; i--) {

var myID = "AirQuality-Graph-" + i;

//onsole.log(myID);

if (i === 1) {
var myAirQual = rooms[roomID].airQual * procentageScaleConverter; //Does not show up 100% accuratly
document.getElementById(myID).style.height = myAirQual + 'px';
document.getElementById(myID).style.backgroundColor = setAirGtaphBarColor(myAirQual);

}
else {
var randomAirQual = getRandomNumber(minNumber, maxNumber);// * procentageScaleConverter;
console.log("My random air qual is: ", randomAirQual);
document.getElementById(myID).style.height = randomAirQual + 'px';
console.log("My random graph hight is : ", document.getElementById(myID).style.height);
document.getElementById(myID).style.backgroundColor = setAirGtaphBarColor(randomAirQual);
console.log("My random color hight is : ", document.getElementById(myID).style.backgroundColor);
}
}

}
}

function setHumidityGtaphBarColor (value)
{

if (!value) {
console.log("Error - The random number is not here!");
return;
}

if (value > redColorMin)
{
//console.log('RedColor ', randomNumber);
return redColor;
}
else if (value > yellowColorMax && value < redColorMin) {
//console.log('GreenColor ', randomNumber);
return greenColor;
}
else {
//console.log('YellowColor ', randomNumber);
return yellowColor;
}
}

function setAirGtaphBarColor (value)
{

if (!value) {
console.log("Error - The random number is not here!");
return;
}

if (value > redColorMin)
{
//console.log('RedColor ', randomNumber);
return redColor;
}
else if (value > greenColorMax && value < redColorMin) {
//console.log('YellowColor ', randomNumber);
return yellowColor;
}
else {
//console.log('GreenColor ', randomNumber);
return greenColor;
}
}

//Link parsing function
function getParameterByName(name, url) {
    if (!url) url = window.location.href;
    name = name.replace(/[\[\]]/g, "\\$&");
    var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
        results = regex.exec(url);
    if (!results) return null;
    if (!results[2]) return '';
    return decodeURIComponent(results[2].replace(/\+/g, " "));
}

function getRoomsDataFromStorage () {
// Retrieve the object from storage
rooms = JSON.parse(localStorage.getItem("rooms"));
//console.log('retrievedObject: ', rooms);

roomID = getParameterByName("roomid");
//console.log("Room ide is: ", roomID);

var roomName = document.getElementById("detail-title");
roomName.innerHTML = rooms[roomID].name.toUpperCase();

//Set teh room icon
var roomIcon = document.getElementsByClassName("details-header-status-image")[0];
roomIcon.src = rooms[roomID].icon;

//Set the back arrow url link so that the rooms will be loaded from memory

var backArrowLink = document.getElementById("back-arrow-link");
backArrowLink.href += "?loaded=1";
//console.log("The new link is: ", backArrowLink.href);

var currentStatus = getRoomStatus(rooms[roomID]);
//console.log("The current room status is: ", currentStatus);
//If the status is 3 or above
if (currentStatus >= 3) {
    redStatus();
}
//Else If the status is above 2
else if (currentStatus > 2) {
  yellowStatus();
}
//Else
else  {
  greenStatus();
}
}

/*WARNING !!! THE FOLLOWING 4 METHODS ARE DIRECT DUBLICATES FROM MAIN.js - THEY SHOULD BE SEPERATED INTO SEPERATE JS FUNCTIONS --- */
function getRoomStatus (room) {

    var midResult = 0;
    var hum = returnHumidityStatus(room.humidity);
    var air = returnAirQualStatus(room.airqual)
    midResult += hum + air;

    return midResult;
}

function returnHumidityStatus (value) {

var greenColorMin = 41;
var greenColorMax = 59;
var yellowColorMin = 0;
var yellowColorMax = 40;
var redColorMin = 60;
var redColorMax = 100;

if (value > redColorMin)
{
//console.log('RedColor ', value);
return 3;
}
else if (value > yellowColorMax && value < redColorMin) {
//console.log('GreenColor ', value);
return 0;
}
else {
//console.log('YellowColor ', value);
return 2;
}

}

function returnAirQualStatus (value) {

var greenColorMin = 0;
var greenColorMax = 999;
var yellowColorMin = 1000;
var yellowColorMax = 1299;
var redColorMin = 1300;
var redColorMax = 1600;

if (value > redColorMin)
{
//console.log('RedColor ', value);
return 3;
}
else if (value > greenColorMax && value < redColorMin) {
//console.log('YellowColor ', value);
return 2;
}
else {
//console.log('GreenColor ', value);
return 0;
}
}

function greenStatus () {
//Green status
    document.getElementById("status-back-div").style.backgroundColor = greenColor;
   // document.getElementById("Status-Image").src = greenStatusImage;
    //document.getElementById("Status-Heading").innerHTML = "GREAT INDOOR CLIMATE";
    //document.getElementById("Status-Heading").style.color = greenColor;
    //document.getElementById("Status-Heading-Text").innerHTML = "Your home has a great overall indoor climate.";
}

function yellowStatus () {
    document.getElementById("status-back-div").style.backgroundColor = yellowColor;
   // document.getElementById("Status-Image").src = yellowStatusImage;
    //document.getElementById("Status-Heading").innerHTML = "COULD BE IMPROVED";
    //document.getElementById("Status-Heading").style.color = yellowColor;
    //document.getElementById("Status-Heading-Text").innerHTML = "Your home needs ventilation in your " + rooms[0].name + ", and in " + rooms[1].name + ".";
}

function redStatus () {
    document.getElementById("status-back-div").style.backgroundColor = redColor;
   // document.getElementById("Status-Image").src = redStatusImage;
   // document.getElementById("Status-Heading").innerHTML = "CRITICAL INDOOR CLIMATE";
   // document.getElementById("Status-Heading").style.color = redColor;
   // document.getElementById("Status-Heading-Text").innerHTML = "Your home needs ventilation in your " + rooms[0].name + ", and in " + rooms[1].name + ".";
}

getRoomsDataFromStorage();
setHumidityGraphs();
setTemperatureGraphMonth();
setAirQualityGraphs();

$(window).load(function() {

  var loadingDiv = document.getElementsByClassName("loading")[0];
  //console.log("Div is: ", loadingDiv);
  //loadingDiv.style.display = "none"
  $(".loading").fadeOut();
});
<|endoftext|>