<commit_before>/*
 * Meetup prize-drawing-winner picker JavaScript file.
 *
 */

/**
 * @callback parseAttendeesCallback
 * @param {Object[]} attendees
 */
/**
 * Query the Meetup API and get a list of attendees,
 * given an API key.
 *
 * @param {int} eventid The Meetup Event ID to be used for gathering a list.
 * @param {parseAttendeesCallback} callback A function to execute after successful ajax request.
 */
function get_attendees(eventid, callback) {

    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            event_id: eventid
        },
        success: callback,
        dataType: 'json'
    })
        .fail(function (xhr, status, error) {
            $("#winner-container").html("There was an error with the ajax request. Check your internet connection and the console for more information.");
            console.log("Status: " + status + " Error Thrown: " + error);
        });

}

/**
 * Put attendee list in the proper format, so the program can select a winner.
 *
 * Also, do some basic error checking to see if we got a response or error.
 *
 * @param {Object[]} attendees The response from the Meetup API.
 * @param {Object} attendees[].member The individual object that contains details about the member.
 * @param {string} attendees[].member_photo.photo_link A URL to the member's photo.
 * @return null
 */
function parse_attendees(attendees) {

    // Check to see if we have results or an error.

    if (attendees) {
        var rsvps = [];
        if (!$.isEmptyObject(attendees)) {

            for (var i = 0; i < attendees.length; i++) {

                if (attendees[i].response == "yes") {
                    var obj = {};
                    obj.name = attendees[i].member.name;
                    attendees[i].member_photo ? obj.photo = attendees[i].member_photo.photo_link : obj.photo = "";
                    rsvps.push(obj);
                }

            }

            select_winner(rsvps);

        }

        else {

            $("#winner-container").html("No RSVP's were found. Most likely, you didn't put in the right event ID. Reload the page and try again.");

        }

    }

    else {

        $("#winner-container").html(
            data.status + "

" +
            data.problem + "

" +
            "Most likely, you didn't put in the right API key. Reload the page and try again."
        );
    }
}

/**
 * Pick a winner and do something special for them.
 *
 * @param {Object[]} rsvps The RSVP's in the proper format.
 * @return null
 */
function select_winner(rsvps) {

    $('#winner-banner').text('Choosing winner in...');

    var start_time, seconds_to_run, seconds, interval;
    start_time = new Date().getTime();
    seconds_to_run = 5000;
    seconds = 0;
    interval = setInterval(function () {

        seconds = new Date().getTime() - start_time;

        //noinspection JSJQueryEfficiency
        $('#countdown-timer').text(Math.round(Math.abs((seconds - seconds_to_run) / 1000)));

        if (seconds > seconds_to_run) {

            // If the code inside here runs, then display a picture of the chosen winner!
            clearInterval(interval);
            $('#winner-photo').html('

<button id="again" class="btn btn-danger btn-lg">Run again?</button> <button class="btn btn-default btn-lg">Reload?</button>');
            $('#countdown-timer').empty();
            $('#winner-banner').text('WINNER!!!').css({'font-size': '3em', 'color': 'blue', 'font-weight': 'bold'});

            $('#again').click(function () {

                $('#winner-banner').empty().css({'font-size': '', 'color': '', 'font-weight': ''});
                $('#countdown-timer').empty();
                $('#winner-name').empty();
                $('#winner-photo').empty();

                select_winner(rsvps);
            });

            // Shoot off some fireworks.
            var r = 4 + parseInt(Math.random() * 16);
            for (var i = r; i--;) {
                setTimeout(
                    'createFirework(8,14,2,null,null,null,null,null,Math.random()>0.5,true)',
                    (i + 1) * (1 + parseInt(Math.random() * 1000)));
            }

            return; // End the program.

        }

        shuffle(rsvps);

        $('#winner-name').text(rsvps[0].name);

    }, 50);

}

/**
 * Randomize a given array
 *
 * @param {Array} array The array to be randomized.
 * @return {Array} The randomized array.
 */
function shuffle(array) {
    var currentIndex = array.length,
        temporaryValue,
        randomIndex;

    // While elements remain...
    while (0 !== currentIndex) {

        // Pick one of the elements...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;

    }

    return array;
}

/**
 * Finally, bind an event handler to the submit button click event.
 */
$(document).ready(function () {

    $('#submit').click(function () {
        var event = $('#meetingid').val();

        if (event) {
            $('#form-container').slideUp();
            get_attendees(event, parse_attendees);
        }
    });

});
<commit_msg>Remove call to undefined data variable<commit_after>/*
 * Meetup prize-drawing-winner picker JavaScript file.
 *
 */

/**
 * @callback parseAttendeesCallback
 * @param {Object[]} attendees
 */
/**
 * Query the Meetup API and get a list of attendees,
 * given an API key.
 *
 * @param {int} eventid The Meetup Event ID to be used for gathering a list.
 * @param {parseAttendeesCallback} callback A function to execute after successful ajax request.
 */
function get_attendees(eventid, callback) {

    $.ajax({
        type: 'POST',
        url: 'ajax.php',
        data: {
            event_id: eventid
        },
        success: callback,
        dataType: 'json'
    })
        .fail(function (xhr, status, error) {
            $("#winner-container").html("There was an error with the ajax request. Check your internet connection and the console for more information.");
            console.log("Status: " + status + " Error Thrown: " + error);
        });

}

/**
 * Put attendee list in the proper format, so the program can select a winner.
 *
 * Also, do some basic error checking to see if we got a response or error.
 *
 * @param {Object[]} attendees The response from the Meetup API.
 * @param {Object} attendees[].member The individual object that contains details about the member.
 * @param {string} attendees[].member_photo.photo_link A URL to the member's photo.
 * @return null
 */
function parse_attendees(attendees) {

    // Check to see if we have results or an error.

    if (attendees) {
        var rsvps = [];
        if (!$.isEmptyObject(attendees)) {

            for (var i = 0; i < attendees.length; i++) {

                if (attendees[i].response == "yes") {
                    var obj = {};
                    obj.name = attendees[i].member.name;
                    attendees[i].member_photo ? obj.photo = attendees[i].member_photo.photo_link : obj.photo = "";
                    rsvps.push(obj);
                }

            }

            select_winner(rsvps);

        }

        else {

            $("#winner-container").html("No RSVP's were found. Most likely, you didn't put in the right event ID. Reload the page and try again.");

        }

    }

    else {

        $("#winner-container").html(
            "Most likely, you didn't put in the right API key. Reload the page and try again."
        );
    }
}

/**
 * Pick a winner and do something special for them.
 *
 * @param {Object[]} rsvps The RSVP's in the proper format.
 * @return null
 */
function select_winner(rsvps) {

    $('#winner-banner').text('Choosing winner in...');

    var start_time, seconds_to_run, seconds, interval;
    start_time = new Date().getTime();
    seconds_to_run = 5000;
    seconds = 0;
    interval = setInterval(function () {

        seconds = new Date().getTime() - start_time;

        //noinspection JSJQueryEfficiency
        $('#countdown-timer').text(Math.round(Math.abs((seconds - seconds_to_run) / 1000)));

        if (seconds > seconds_to_run) {

            // If the code inside here runs, then display a picture of the chosen winner!
            clearInterval(interval);
            $('#winner-photo').html('

<button id="again" class="btn btn-danger btn-lg">Run again?</button> <button class="btn btn-default btn-lg">Reload?</button>');
            $('#countdown-timer').empty();
            $('#winner-banner').text('WINNER!!!').css({'font-size': '3em', 'color': 'blue', 'font-weight': 'bold'});

            $('#again').click(function () {

                $('#winner-banner').empty().css({'font-size': '', 'color': '', 'font-weight': ''});
                $('#countdown-timer').empty();
                $('#winner-name').empty();
                $('#winner-photo').empty();

                select_winner(rsvps);
            });

            // Shoot off some fireworks.
            var r = 4 + parseInt(Math.random() * 16);
            for (var i = r; i--;) {
                setTimeout(
                    'createFirework(8,14,2,null,null,null,null,null,Math.random()>0.5,true)',
                    (i + 1) * (1 + parseInt(Math.random() * 1000)));
            }

            return; // End the program.

        }

        shuffle(rsvps);

        $('#winner-name').text(rsvps[0].name);

    }, 50);

}

/**
 * Randomize a given array
 *
 * @param {Array} array The array to be randomized.
 * @return {Array} The randomized array.
 */
function shuffle(array) {
    var currentIndex = array.length,
        temporaryValue,
        randomIndex;

    // While elements remain...
    while (0 !== currentIndex) {

        // Pick one of the elements...
        randomIndex = Math.floor(Math.random() * currentIndex);
        currentIndex -= 1;

        // And swap it with the current element.
        temporaryValue = array[currentIndex];
        array[currentIndex] = array[randomIndex];
        array[randomIndex] = temporaryValue;

    }

    return array;
}

/**
 * Finally, bind an event handler to the submit button click event.
 */
$(document).ready(function () {

    $('#submit').click(function () {
        var event = $('#meetingid').val();

        if (event) {
            $('#form-container').slideUp();
            get_attendees(event, parse_attendees);
        }
    });

});
<|endoftext|>


<commit_before>'use strict';

var noop     = require('es5-ext/lib/Function/noop')
  , d        = require('es5-ext/lib/Object/descriptor')
  , map      = require('es5-ext/lib/Object/map')
  , Base     = require('dbjs').Base
  , DOMInput = require('./_controls/input')

  , Input;

module.exports = Input = function (rel, inputs, rels, dom) {
	this.inputs = inputs;
	this.relations = rels;
	this.fnValue = rel._value;
	this._name = rel.name;
	this.required = rel.__required.__value;
	this.dom = dom;
};

Input.prototype = Object.create(DOMInput.prototype, {
	constructor: d(Input),
	value: d.gs(function () {
		return this.fnValue(map(this.inputs,
			function (input) { return input.value; }));
	}, noop)
});

Object.defineProperty(Base, 'DOMInputComponent', d(Input));
<commit_msg>Bind change listeners<commit_after>'use strict';

var noop     = require('es5-ext/lib/Function/noop')
  , d        = require('es5-ext/lib/Object/descriptor')
  , forEach  = require('es5-ext/lib/Object/for-each')
  , map      = require('es5-ext/lib/Object/map')
  , Base     = require('dbjs').Base
  , DOMInput = require('./_controls/input')

  , Input;

module.exports = Input = function (rel, inputs, rels, dom) {
	this.inputs = inputs;
	this.relations = rels;
	this.fnValue = rel._value;
	this._name = rel.name;
	this.required = rel.__required.__value;
	this.dom = dom;
	this.onchange = this.onchange.bind(this);
	forEach(this.inputs, function (input) {
		input.on('change', this.onchange);
	}, this);
	this.onchange();
};

Input.prototype = Object.create(DOMInput.prototype, {
	constructor: d(Input),
	value: d.gs(function () {
		return this.fnValue(map(this.inputs,
			function (input) { return input.value; }));
	}, noop)
});

Object.defineProperty(Base, 'DOMInputComponent', d(Input));
<|endoftext|>


<commit_before>'use strict';

var copy             = require('es5-ext/object/copy')
  , assign           = require('es5-ext/object/assign')
  , isEmpty          = require('es5-ext/object/is-empty')
  , filter           = require('es5-ext/object/filter')
  , forEach          = require('es5-ext/object/for-each')
  , normalizeOptions = require('es5-ext/object/normalize-options')
  , isSet            = require('es6-set/is-set')
  , d                = require('d')
  , castAttribute    = require('dom-ext/element/#/cast-attribute')
  , isNestedObject   = require('dbjs/is-dbjs-nested-object')
  , PropObserv       = require('dbjs/_setup/1.property/observable')
  , DescPropObserv   = require('dbjs/_setup/3.descriptor-property/observable')
  , htmlAttributes   = require('./_html-attributes')
  , componentRender  = require('./utils/get-component-render')('div')
  , resolveOptions   = require('./utils/resolve-options')

  , toDOM = function () { return this.dom; };

var hasOwn = function (obj, desc, sKey) {
	if (desc.multiple) {
		if (typeof desc._value_ === 'function') return false;
		return obj._hasOwnMultiple_(sKey);
	}
	return obj._hasOwn_(sKey);
};

Object.defineProperties(PropObserv.prototype, {
	DOMInput: d(null),
	toDOMInput: d(function (document/*, options*/) {
		var input, options = normalizeOptions(arguments[1]), type, value, onChange, desc, isMap = false
		  , db;

		desc = this.descriptor;
		db = desc.database;
		if (desc.nested) {
			isMap = this.object.database.isObjectType(this.value.__descriptorPrototype__.type);
		}
		// Setup input options
		if (options.multiple == null) {
			if (isMap) {
				options.multiple = true;
			} else {
				options.multiple = desc.multiple;
			}
		}
		if (options.name == null) options.name = this.dbId;
		options.dbOptions = desc;
		options.observable = this;

		// Initialize input
		type = isMap ? this.value.__descriptorPrototype__.type : desc.type;
		options = resolveOptions(options, type);
		if (options.DOMInput) input = new options.DOMInput(document, type, options);
		else if (desc.DOMInput) input = new desc.DOMInput(document, type, options);
		else input = type.toDOMInput(document, options);
		input.observable = this;

		// Set input value
		value = this.value;
		if (isSet(value) && !options.multiple) value = value.values().next().value || null;
		if ((value === undefined) && (options.value != null)) value = options.value;
		input.value = value;

		// Attach listeners
		onChange = function () {
			var nuValue = this.value;
			if (isSet(nuValue)) {
				if (!options.multiple) nuValue = nuValue.values().next().value || null;
			}
			if ((isMap || isSet(nuValue)) && (nuValue !== value)) {
				if (value && (typeof value.off === 'function')) value.off('change', onChange);
				value = nuValue;
				if (nuValue && (typeof nuValue.on === 'function')) nuValue.on('change', onChange);
			}
			input.value = nuValue;
		}.bind(this);
		this.on('change', onChange);
		if (isMap || isSet(value)) value.on('change', onChange);
		if (isNestedObject(value)) {
			if (db.NestedMap && this.value.key === 'map' && (this.value.owner instanceof db.NestedMap)) {
				this.value.owner.ordered._size.on('change', onChange);
			} else if (typeof value.getDescriptor('resolvedValue')._value_ === 'function') {
				value._resolvedValue.on('change', onChange);
			}
		}

		input.once('destroy', function () {
			delete input.observable;
			if (isSet(value)) value.off('change', onChange);
			this.off('change', onChange);
		}.bind(this));

		type.emit('dominput', input);
		desc.emit('dominput', input);
		return input;
	}),
	toDOMInputComponent: d(function (document/*, options*/) {
		var options, input, inputOptions, dom, cb
		  , desc = this.ownDescriptor, db = desc.database, isRequired;

		options = normalizeOptions(arguments[1], desc.type.fieldOptions, desc.fieldOptions);
		inputOptions = filter(options, function (value, name) {
			if (name === 'render') return false;
			return !htmlAttributes[name];
		});
		if (options.modelRequired != null) {
			isRequired = inputOptions.required = options.modelRequired;
		} else {
			isRequired = desc.required;
		}
		if (options.input) {
			assign(inputOptions, options.input);
			delete inputOptions.input;
		}
		input = this.toDOMInput(document, inputOptions);

		if (options.label == null) {
			options.label = desc.dynamicLabelKey ? desc.object.getObservable(desc.dynamicLabelKey)
				: desc.label;
		} else if (options.label === false) {
			options.label = null;
		}

		if (options.hint == null) options.hint = desc.inputHint;
		if (options.optionalInfo == null) options.optionalInfo = desc.inputOptionalInfo;

		dom = (options.render || componentRender)(input, options);
		if (!dom._dbjsInput) dom._dbjsInput = input;
		forEach(options, function (value, name) {
			if (htmlAttributes[name]) castAttribute.call(dom, name, value);
		}, this);

		dom.classList.add('dbjs-input-component');

		// Required
		dom.classList[isRequired ? 'add' : 'remove']('dbjs-required');
		dom.classList[isRequired ? 'remove' : 'add']('dbjs-optional');

		// Changed
		input.on('change:changed', cb = function (value) {
			dom.classList[value ? 'add' : 'remove']('changed');
			dom.classList[value ? 'remove' : 'add']('not-changed');
		});
		cb(input.changed);

		// Valid
		input.on('change:valid', cb = function (value) {
			dom.classList[value ? 'add' : 'remove']('valid');
			dom.classList[value ? 'remove' : 'add']('invalid');
		});
		cb(input.valid);

		// DBJS valid/invalid & empty/filled
		this.on('change', cb = function () {
			var isInvalid, value, isEmpty, isOwn;
			if (isRequired) {
				if (this.value == null) {
					isInvalid = true;
				} else if (db.NestedMap && isNestedObject(this.value) && (this.value.key === 'map') &&
						(this.value.owner instanceof db.NestedMap)) {
					isEmpty = isInvalid = !this.value.owner.ordered.size;
					this.value.owner.ordered._size.once('change', cb);
				} else if (db.File && (this.value instanceof db.File) && isNestedObject(this.value)) {
					isEmpty = isInvalid = !this.value.name;
					this.value._name.once('change', cb);
				} else if (isNestedObject(this.value) &&
						(typeof this.value.getDescriptor('resolvedValue')._value_ === 'function')) {
					isEmpty = isInvalid = (this.value.resolvedValue == null);
					this.value._resolvedValue.once('change', cb);
				} else {
					isInvalid = false;
				}
			} else {
				isInvalid = false;
			}
			dom.classList[isInvalid ? 'add' : 'remove']('dbjs-invalid');
			dom.classList[isInvalid ? 'remove' : 'add']('dbjs-valid');
			value = this.value;
			if (isEmpty == null) {
				if (isSet(value)) isEmpty = !value.size;
				else isEmpty = value == null;
			}
			dom.classList[isEmpty ? 'add' : 'remove']('dbjs-empty');
			dom.classList[isEmpty ? 'remove' : 'add']('dbjs-filled');
			if (input.isComposite) return;
			isOwn = hasOwn(this.object, this.descriptor, this.__sKey__);
			dom.classList[isOwn ? 'add' : 'remove']('dbjs-own');
			dom.classList[isOwn ? 'remove' : 'add']('dbjs-not-own');
		}.bind(this));
		desc.on('selfupdate', cb);
		cb();
		if (input.isComposite) {
			(function () {
				var defined = {};
				var update = function () {
					var isOwn = !isEmpty(defined);
					dom.classList[isOwn ? 'add' : 'remove']('dbjs-own');
					dom.classList[isOwn ? 'remove' : 'add']('dbjs-not-own');
				};
				forEach(input.items, function (input) {
					var observable = input.observable, cb, object, sKey, desc;
					if (!observable) return;
					object = observable.object;
					desc = observable.descriptor;
					sKey = observable.__sKey__;
					if (hasOwn(object, desc, sKey)) defined[sKey] = true;
					observable.on('change', cb = function (event) {
						if (hasOwn(object, desc, sKey)) defined[sKey] = true;
						else delete defined[sKey];
						update();
					});
					observable.ownDescriptor.on('selfupdate', cb);
					input.on('destroy', function () {
						observable.off('change', cb);
						observable.ownDescriptor.off('selfupdate', cb);
					});
				});
				update();
			}());
		}
		if (isSet(this.value)) this.value.on('change', cb);
		input.on('destroy', function (cb) { this.off('change', cb); }.bind(this, cb));

		return { dom: dom, input: input, toDOM: toDOM };
	})
});

Object.defineProperties(DescPropObserv.prototype, {
	DOMInput: d(null),
	toDOMInput: d(function (document/*, options*/) {
		var input, initOptions = Object(arguments[1]), options = copy(initOptions)
		  , type, onChange, descDesc = this.descriptor;

		// Setup input options
		if (options.name == null) options.name = this.dbId;

		// Initialize input
		type = descDesc.type;
		if (options.DOMInput) input = new options.DOMInput(document, type, options);
		else if (this.DOMInput) input = new this.DOMInput(document, type, options);
		else input = type.toDOMInput(document, options);
		input.observable = this;

		// Set input value
		input.value = this.value;

		// Attach listeners
		onChange = function () { input.value = this.value; }.bind(this);
		this.on('change', onChange);

		input.once('destroy', function () {
			delete input.observable;
			this.off('change', onChange);
		}.bind(this));

		type.emit('dominput', input);
		descDesc.emit('dominput', input);
		return input;
	})
});
<commit_msg>Do not override observable if there is one<commit_after>'use strict';

var copy             = require('es5-ext/object/copy')
  , assign           = require('es5-ext/object/assign')
  , isEmpty          = require('es5-ext/object/is-empty')
  , filter           = require('es5-ext/object/filter')
  , forEach          = require('es5-ext/object/for-each')
  , normalizeOptions = require('es5-ext/object/normalize-options')
  , isSet            = require('es6-set/is-set')
  , d                = require('d')
  , castAttribute    = require('dom-ext/element/#/cast-attribute')
  , isNestedObject   = require('dbjs/is-dbjs-nested-object')
  , PropObserv       = require('dbjs/_setup/1.property/observable')
  , DescPropObserv   = require('dbjs/_setup/3.descriptor-property/observable')
  , htmlAttributes   = require('./_html-attributes')
  , componentRender  = require('./utils/get-component-render')('div')
  , resolveOptions   = require('./utils/resolve-options')

  , toDOM = function () { return this.dom; };

var hasOwn = function (obj, desc, sKey) {
	if (desc.multiple) {
		if (typeof desc._value_ === 'function') return false;
		return obj._hasOwnMultiple_(sKey);
	}
	return obj._hasOwn_(sKey);
};

Object.defineProperties(PropObserv.prototype, {
	DOMInput: d(null),
	toDOMInput: d(function (document/*, options*/) {
		var input, options = normalizeOptions(arguments[1]), type, value, onChange, desc, isMap = false
		  , db;

		desc = this.descriptor;
		db = desc.database;
		if (desc.nested) {
			isMap = this.object.database.isObjectType(this.value.__descriptorPrototype__.type);
		}
		// Setup input options
		if (options.multiple == null) {
			if (isMap) {
				options.multiple = true;
			} else {
				options.multiple = desc.multiple;
			}
		}
		if (options.name == null) options.name = this.dbId;
		options.dbOptions = desc;
		options.observable = this;

		// Initialize input
		type = isMap ? this.value.__descriptorPrototype__.type : desc.type;
		options = resolveOptions(options, type);
		if (options.DOMInput) input = new options.DOMInput(document, type, options);
		else if (desc.DOMInput) input = new desc.DOMInput(document, type, options);
		else input = type.toDOMInput(document, options);
		if (!input.observable) input.observable = this;

		// Set input value
		value = this.value;
		if (isSet(value) && !options.multiple) value = value.values().next().value || null;
		if ((value === undefined) && (options.value != null)) value = options.value;
		input.value = value;

		// Attach listeners
		onChange = function () {
			var nuValue = this.value;
			if (isSet(nuValue)) {
				if (!options.multiple) nuValue = nuValue.values().next().value || null;
			}
			if ((isMap || isSet(nuValue)) && (nuValue !== value)) {
				if (value && (typeof value.off === 'function')) value.off('change', onChange);
				value = nuValue;
				if (nuValue && (typeof nuValue.on === 'function')) nuValue.on('change', onChange);
			}
			input.value = nuValue;
		}.bind(this);
		this.on('change', onChange);
		if (isMap || isSet(value)) value.on('change', onChange);
		if (isNestedObject(value)) {
			if (db.NestedMap && this.value.key === 'map' && (this.value.owner instanceof db.NestedMap)) {
				this.value.owner.ordered._size.on('change', onChange);
			} else if (typeof value.getDescriptor('resolvedValue')._value_ === 'function') {
				value._resolvedValue.on('change', onChange);
			}
		}

		input.once('destroy', function () {
			delete input.observable;
			if (isSet(value)) value.off('change', onChange);
			this.off('change', onChange);
		}.bind(this));

		type.emit('dominput', input);
		desc.emit('dominput', input);
		return input;
	}),
	toDOMInputComponent: d(function (document/*, options*/) {
		var options, input, inputOptions, dom, cb
		  , desc = this.ownDescriptor, db = desc.database, isRequired;

		options = normalizeOptions(arguments[1], desc.type.fieldOptions, desc.fieldOptions);
		inputOptions = filter(options, function (value, name) {
			if (name === 'render') return false;
			return !htmlAttributes[name];
		});
		if (options.modelRequired != null) {
			isRequired = inputOptions.required = options.modelRequired;
		} else {
			isRequired = desc.required;
		}
		if (options.input) {
			assign(inputOptions, options.input);
			delete inputOptions.input;
		}
		input = this.toDOMInput(document, inputOptions);

		if (options.label == null) {
			options.label = desc.dynamicLabelKey ? desc.object.getObservable(desc.dynamicLabelKey)
				: desc.label;
		} else if (options.label === false) {
			options.label = null;
		}

		if (options.hint == null) options.hint = desc.inputHint;
		if (options.optionalInfo == null) options.optionalInfo = desc.inputOptionalInfo;

		dom = (options.render || componentRender)(input, options);
		if (!dom._dbjsInput) dom._dbjsInput = input;
		forEach(options, function (value, name) {
			if (htmlAttributes[name]) castAttribute.call(dom, name, value);
		}, this);

		dom.classList.add('dbjs-input-component');

		// Required
		dom.classList[isRequired ? 'add' : 'remove']('dbjs-required');
		dom.classList[isRequired ? 'remove' : 'add']('dbjs-optional');

		// Changed
		input.on('change:changed', cb = function (value) {
			dom.classList[value ? 'add' : 'remove']('changed');
			dom.classList[value ? 'remove' : 'add']('not-changed');
		});
		cb(input.changed);

		// Valid
		input.on('change:valid', cb = function (value) {
			dom.classList[value ? 'add' : 'remove']('valid');
			dom.classList[value ? 'remove' : 'add']('invalid');
		});
		cb(input.valid);

		// DBJS valid/invalid & empty/filled
		this.on('change', cb = function () {
			var isInvalid, value, isEmpty, isOwn;
			if (isRequired) {
				if (this.value == null) {
					isInvalid = true;
				} else if (db.NestedMap && isNestedObject(this.value) && (this.value.key === 'map') &&
						(this.value.owner instanceof db.NestedMap)) {
					isEmpty = isInvalid = !this.value.owner.ordered.size;
					this.value.owner.ordered._size.once('change', cb);
				} else if (db.File && (this.value instanceof db.File) && isNestedObject(this.value)) {
					isEmpty = isInvalid = !this.value.name;
					this.value._name.once('change', cb);
				} else if (isNestedObject(this.value) &&
						(typeof this.value.getDescriptor('resolvedValue')._value_ === 'function')) {
					isEmpty = isInvalid = (this.value.resolvedValue == null);
					this.value._resolvedValue.once('change', cb);
				} else {
					isInvalid = false;
				}
			} else {
				isInvalid = false;
			}
			dom.classList[isInvalid ? 'add' : 'remove']('dbjs-invalid');
			dom.classList[isInvalid ? 'remove' : 'add']('dbjs-valid');
			value = this.value;
			if (isEmpty == null) {
				if (isSet(value)) isEmpty = !value.size;
				else isEmpty = value == null;
			}
			dom.classList[isEmpty ? 'add' : 'remove']('dbjs-empty');
			dom.classList[isEmpty ? 'remove' : 'add']('dbjs-filled');
			if (input.isComposite) return;
			isOwn = hasOwn(this.object, this.descriptor, this.__sKey__);
			dom.classList[isOwn ? 'add' : 'remove']('dbjs-own');
			dom.classList[isOwn ? 'remove' : 'add']('dbjs-not-own');
		}.bind(this));
		desc.on('selfupdate', cb);
		cb();
		if (input.isComposite) {
			(function () {
				var defined = {};
				var update = function () {
					var isOwn = !isEmpty(defined);
					dom.classList[isOwn ? 'add' : 'remove']('dbjs-own');
					dom.classList[isOwn ? 'remove' : 'add']('dbjs-not-own');
				};
				forEach(input.items, function (input) {
					var observable = input.observable, cb, object, sKey, desc;
					if (!observable) return;
					object = observable.object;
					desc = observable.descriptor;
					sKey = observable.__sKey__;
					if (hasOwn(object, desc, sKey)) defined[sKey] = true;
					observable.on('change', cb = function (event) {
						if (hasOwn(object, desc, sKey)) defined[sKey] = true;
						else delete defined[sKey];
						update();
					});
					observable.ownDescriptor.on('selfupdate', cb);
					input.on('destroy', function () {
						observable.off('change', cb);
						observable.ownDescriptor.off('selfupdate', cb);
					});
				});
				update();
			}());
		}
		if (isSet(this.value)) this.value.on('change', cb);
		input.on('destroy', function (cb) { this.off('change', cb); }.bind(this, cb));

		return { dom: dom, input: input, toDOM: toDOM };
	})
});

Object.defineProperties(DescPropObserv.prototype, {
	DOMInput: d(null),
	toDOMInput: d(function (document/*, options*/) {
		var input, initOptions = Object(arguments[1]), options = copy(initOptions)
		  , type, onChange, descDesc = this.descriptor;

		// Setup input options
		if (options.name == null) options.name = this.dbId;

		// Initialize input
		type = descDesc.type;
		if (options.DOMInput) input = new options.DOMInput(document, type, options);
		else if (this.DOMInput) input = new this.DOMInput(document, type, options);
		else input = type.toDOMInput(document, options);
		input.observable = this;

		// Set input value
		input.value = this.value;

		// Attach listeners
		onChange = function () { input.value = this.value; }.bind(this);
		this.on('change', onChange);

		input.once('destroy', function () {
			delete input.observable;
			this.off('change', onChange);
		}.bind(this));

		type.emit('dominput', input);
		descDesc.emit('dominput', input);
		return input;
	})
});
<|endoftext|>


<commit_before>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const { classes: Cc, interfaces: Ci, utils: Cu } = Components;

Cu.import("resource://gre/modules/Home.jsm");
Cu.import("resource://gre/modules/HomeProvider.jsm");
Cu.import("resource://gre/modules/Prompt.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

// Pref used to persist feed panel data between app runs.
const FEEDS_PREF = "home.page.feeds";

XPCOMUtils.defineLazyGetter(this, "Strings", function() {
  return Services.strings.createBundle("chrome://feeds/locale/feeds.properties");
});

XPCOMUtils.defineLazyGetter(this, "FeedHelper", function() {
  let sandbox = {};
  Services.scriptloader.loadSubScript("chrome://feeds/content/FeedHelper.js", sandbox);
  return sandbox["FeedHelper"];
});

function reportErrors(e) {
  if (!e.errors) {
    return;
  }
  if (e.message) {
    Cu.reportError(e.message);
  }
  e.errors.forEach(error => Cu.reportError(error.message));
}

/**
 * @return optionsCallback function for a basic list panel.
 */
function getOptionsCallback(panelId, title, datasetId) {
  return function() {
    return {
      title: title,
      views: [{
        type: Home.panels.View.LIST,
        dataset: datasetId
      }],
      onuninstall: function() {
        // Unregister the panel and delete its data if the user
        // chooses to remove it in settings.
        removeFeedPanel(panelId, datasetId);
        unstoreFeed(panelId);
      }
    };
  };
}

/**
 * Monkey-patched version of FeedHandler.loadFeed.
 *
 * @param feed object created by DOMLinkAdded handler in browser.js
 */
function loadFeed(feed) {
  let chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
  let BrowserApp = chromeWin.BrowserApp;

  // Get the default feed handlers from FeedHandler.
  let handlers = chromeWin.FeedHandler.getContentHandlers(this.TYPE_MAYBE_FEED);

  handlers = handlers.map(function(handler) {
    return {
      name: handler.name,
      action: function defaultHandlerAction(feed) {
        // Merge the handler URL and the feed URL.
        let readerURL = handler.uri;
        readerURL = readerURL.replace(/%s/gi, encodeURIComponent(feed.href));

        // Open the resultant URL in a new tab.
        BrowserApp.addTab(readerURL, { parentId: BrowserApp.selectedTab.id });
      }
    }
  });

  // Add our own custom handler.
  handlers.push({
    name: Strings.GetStringFromName("prompt.firefoxHomepage"),
    action: addFeedPanel
  });

  // JSON for Prompt.
  let p = new Prompt({
    window: chromeWin,
    // XXX: In Firefox 31+, we can get this string from browser.properties.
    title: Strings.GetStringFromName("prompt.subscribeWith")
  });
  p.setSingleChoiceItems(handlers.map(function (handler) {
    return { label: handler.name };
  }));
  p.show(function (data) {
    if (data.button == -1) {
      return;
    }
    // Call the action callback for the feed handler.
    handlers[data.button].action(feed);
  });
}

/**
 * @param feed object created by DOMLinkAdded handler in browser.js
 */
function addFeedPanel(feed) {
  let uuidgen = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
  let panelId = uuidgen.generateUUID().toString();
  let datasetId = uuidgen.generateUUID().toString();

  // Immediately fetch and parse the feed to get title for panel.
  FeedHelper.parseFeed(feed.href, function (parsedFeed) {
    let title = parsedFeed.title.plainText();

    Home.panels.register(panelId, getOptionsCallback(panelId, title, datasetId));
    Home.panels.install(panelId);

    saveFeedItems(parsedFeed, datasetId);
    storeFeed(feed.href, title, panelId, datasetId);

    let chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
    chromeWin.NativeWindow.toast.show(Strings.GetStringFromName("toast.addedToFirefoxHomepage"), "short");
  });

  // Add periodic sync to update feed once per hour.
  HomeProvider.addPeriodicSync(datasetId, 3600, function () {
    FeedHelper.parseFeed(feed.href, function(parsedFeed) {
      saveFeedItems(parsedFeed, datasetId);
    });
  });
}

/**
 * Uninstalls and unregisters panel, and deletes all feed data.
 */
function removeFeedPanel(panelId, datasetId) {
  Home.panels.uninstall(panelId);
  Home.panels.unregister(panelId);

  HomeProvider.removePeriodicSync(datasetId);
  Task.spawn(function deleteAll() {
    let storage = HomeProvider.getStorage(datasetId);
    yield storage.deleteAll();
  }).then(null, reportErrors);
}

/**
 * @param parsedFeed nsIFeed
 */
function saveFeedItems(parsedFeed, datasetId) {
  let items = FeedHelper.feedToItems(parsedFeed);

  Task.spawn(function () {
    let storage = HomeProvider.getStorage(datasetId);
    yield storage.deleteAll();
    yield storage.save(items);
  }).then(null, reportErrors);
}

/**
 * Stores feed panel data that we need to persist between app runs.
 */
function storeFeed(url, title, panelId, datasetId) {
  let feeds;
  try {
    feeds = JSON.parse(Services.prefs.getCharPref(FEEDS_PREF));
  } catch (e) {
    feeds = [];
  }

  feeds.push({
    url: url,
    title: title,
    panelId: panelId,
    datasetId: datasetId
  });

  Services.prefs.setCharPref(FEEDS_PREF, JSON.stringify(feeds));
}

/**
 * Removes feed from array that persists between app runs.
 */
function unstoreFeed(panelId) {
  try {
    let feeds = JSON.parse(Services.prefs.getCharPref(FEEDS_PREF));
    for (let i = 0; i < feeds.length; i++) {
      if (feeds[i].panelId === panelId) {
        feeds.splice(i, 0);
        break;
      }
    }
    Services.prefs.setCharPref(FEEDS_PREF, JSON.stringify(feeds));
  } catch (e) {
    // We should never call unstoreFeed if the FEEDS_PREF doesn't exist.
    Cu.reportError(e);
  }
}

let gPageActionIcon;
let gPageActionId;
let gOriginalLoadFeed;

function onPageShow(event) {
  let chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
  if (!chromeWin) {
    return;
  }

  let selectedTab = chromeWin.BrowserApp.selectedTab;

  // Ignore load events on frames and other documents.
  // selectedTab may be null during startup.
  if (!selectedTab || event.target != selectedTab.browser.contentDocument) {
    return;
  }

  // Remove any current page action item.
  if (gPageActionId) {
    chromeWin.NativeWindow.pageactions.remove(gPageActionId);
    gPageActionId = null;
  }

  let feeds = selectedTab.browser.feeds;

  // Bail if there are no feeds for this page.
  if (!feeds || feeds.length == 0) {
    return;
  }

  gPageActionId = chromeWin.NativeWindow.pageactions.add({
    icon: gPageActionIcon,
    title: Strings.GetStringFromName("pageAction.subscribeToPage"),
    clickCallback: function onSubscribeClicked() {
      // Follow the regular "Subscribe" menu button action.
      let args = JSON.stringify({ tabId: selectedTab.id });
      Services.obs.notifyObservers(null, "Feeds:Subscribe", args);
    }
  });
}

function loadIntoWindow(window) {
  window.BrowserApp.deck.addEventListener("pageshow", onPageShow, false);

  // Monkey-patch FeedHandler to add option to subscribe menu.
  gOriginalLoadFeed = window.FeedHandler.loadFeed;
  window.FeedHandler.loadFeed = loadFeed;

  if (window.devicePixelRatio <= 1) {
    gPageActionIcon = "chrome://feeds/skin/icon_urlbar_mdpi.png";
  } else if (window.devicePixelRatio <= 1.5) {
    gPageActionIcon = "chrome://feeds/skin/icon_urlbar_hdpi.png";
  } else {
    gPageActionIcon = "chrome://feeds/skin/icon_urlbar_xhdpi.png";
  }
}

function unloadFromWindow(window) {
  window.BrowserApp.deck.removeEventListener("pageshow", onPageShow);
  window.FeedHandler.loadFeed = gOriginalLoadFeed;
}

/**
 * bootstrap.js API
 */
function install(aData, aReason) {}

function uninstall(aData, aReason) {}

let gWindowListener = {
  onOpenWindow: function(aWindow) {
    // Stop listening after the window has been opened.
    Services.wm.removeListener(gWindowListener);

    // Wait for startup to finish before interacting with the UI.
    let win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
    win.addEventListener("UIReady", function onLoad() {
      win.removeEventListener("UIReady", onLoad, false);
      loadIntoWindow(win);
    }, false);
  },
  onCloseWindow: function(aWindow) {},
  onWindowTitleChange: function(aWindow, aTitle) {}
};

function startup(aData, aReason) {
  let win = Services.wm.getMostRecentWindow("navigator:browser");
  if (win) {
    // Load into the browser window if it already exists.
    loadIntoWindow(win);
  } else {
    // Otherwise, listen for it to open.
    Services.wm.addListener(gWindowListener);
  }

  try {
    let feeds = JSON.parse(Services.prefs.getCharPref(FEEDS_PREF));
    feeds.forEach(function(feed) {
      // Register any existing panels.
      Home.panels.register(feed.panelId, getOptionsCallback(feed.panelId, feed.title, feed.datasetId));

      // Add periodic sync for existing feeds.
      HomeProvider.addPeriodicSync(feed.datasetId, 3600, function() {
        FeedHelper.parseFeed(feed.url, function(parsedFeed) {
          saveFeedItems(parsedFeed, feed.datasetId);
        });
      });
    });
  } catch (e) {}
}

function shutdown(aData, aReason) {
  // When the application is shutting down we normally don't have to clean any changes made.
  if (aReason == APP_SHUTDOWN) {
    return;
  }

  unloadFromWindow(Services.wm.getMostRecentWindow("navigator:browser"));

  // If the add-on is being uninstalled, also remove all panel data.
  if (aReason == ADDON_UNINSTALL) {
    try {
      let feeds = JSON.parse(Services.prefs.getCharPref(FEEDS_PREF));
      feeds.forEach(function (feed) {
        removeFeedPanel(feed.panelId, feed.datasetId);
      });

      // Clear the stored feeds.
      Services.prefs.clearUserPref(FEEDS_PREF);
    } catch (e) {}
  }
}
<commit_msg>use data uris for page action icons<commit_after>/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

const { classes: Cc, interfaces: Ci, utils: Cu } = Components;

Cu.import("resource://gre/modules/Home.jsm");
Cu.import("resource://gre/modules/HomeProvider.jsm");
Cu.import("resource://gre/modules/Prompt.jsm");
Cu.import("resource://gre/modules/Services.jsm");
Cu.import("resource://gre/modules/Task.jsm");
Cu.import("resource://gre/modules/XPCOMUtils.jsm");

// Pref used to persist feed panel data between app runs.
const FEEDS_PREF = "home.page.feeds";

// XXX: Using data URIs as a workaround until bug 993698 is fixed.
//const URLBAR_ICON_MDPI = "chrome://feeds/skin/icon_urlbar_mdpi.png";
//const URLBAR_ICON_HDPI = "chrome://feeds/skin/icon_urlbar_hdpi.png";
//const URLBAR_ICON_XHDPI = "chrome://feeds/skin/icon_urlbar_xhdpi.png";

const URLBAR_ICON_MDPI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABgAAAAYCAYAAADgdz34AAABDUlEQVR42u3VsUpCYRiHcTUNqSEvoEtoCUdbgyCEhraIM0hg4Obi5OLQJegVBCHODuIVZEvRIgUei8ocpAvovD7DO7x80PAdTxDk8BvO/wwP53UwJSK/ah34o4GgUn3CDH00cYBMkgGBK0Qd20kEBvj6IfSKo7gBN7SLAH18m0iE5qoBN7aPO4jRiHuiFzzjGmfI676JnvMlp3ECEcT4xCXSGhk67wq+gQBt3DuhG2yggKnZWz4BN1bEyN5d97LZ5sj5BmxkB48QLLCl+62JHPqc6BgzvOFEtxJEnetWM9uVTyC0P6LZH3Tr6vMeRA2SCHR0C/U5C1Efvid6tyfS/QIRFmYbQzBZ/+H808ASnTUiP4oxmJUAAAAASUVORK5CYII=";
const URLBAR_ICON_HDPI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAACQAAAAkCAYAAADhAJiYAAABm0lEQVR42u3XPyjEYRjA8TtxHSkL3XAiyWiyGChuUc5A2Q0UubJcyZ8sbBILx05IksFiZZGMZDDJnwzKHYd03Otre3rqzuX3+12Gd/hMz/B8631/73U+Y8y/YoNskA2yQdLA4Mg+3nCBdYyiGSXw/YHjoAwMtEesob3YQaYAZ+iFvxhBdzAFOkKj10Fh9COOTVz9EpXGkAdBeSMbMIWbPGFzXgfpqB8BxJDKETXhxZFFMY0oqmSQUI9jGCWLEbeD0mLBJ04RR7VaFMQBjPKB1mJ89u9YVmEVOIFRLlDmVtAtTB4P6BBR4RyXPeZWUA26MIZtvOQ4loiI6kQWRrhGqeMg6MByDONRLXxCWEStwih9Xn729dCP5IYICiGt5jtev0NNamkGdSJqRQW9IOj0DgWwhCSesYZysXRcLZ0VsxYYJeI0aB5GSYilleqlPhczP/SP84zToHsY5Rk+YUvNQ2K2q2Z7XgSlVFBMzXvEbEHNLr04skUV1K3mcTGbVLNXty91AkEVVCte9C8MiFkbkiLo0P4NskE2yAYp32bgEC3fNWtgAAAAAElFTkSuQmCC";
const URLBAR_ICON_XHDPI = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADAAAAAwCAYAAABXAvmHAAACK0lEQVR42u3YzUvUURSA4RmRkRBahC0kCcKBwCiEXLRIMLACC9pEtKtQyFVIK5FqYRtByE2IUZAFFQQV6vQPZEUQIrQSWgSZCPaBnyNp4/HdtDncM5chfh/SXTy7A8PL3HuuTkZEdrQQEAJCQAgIASEgBOyIgEud3f1YxzdMYgRXcQRVyPyDWAJ+Qgzf8RTnkEtrQBHiRSiGcTBtAVKhEp7hcLqPkN8WHmBP0gFnUMAnLEIqNI/2+APsoAZcwF3MVnCsricXYMdU4Tge4jfEYyC5ADvir/0YxZYnojf2AD4oVy5AacOs53J3x3mJhyGYxyv04CiyzgBgLz54Is7GFbAOcfiKQeSNiFpPxCIa0vCQlTCGJuOb+AwxvI4joASBzyYGUa0i8liAGDqiDhhyrkjbG9SpiFb8MeankY16C2WxDyfRh7eedTmNWhVxG2I4HV2AHZXHozJHbFQF1GDGmB1P8iE7hR/GqmxVEefL3J+6JF/iZuMPvfcqIIspI+JKcgHARYjDMRVx2TpGUV7iRrzEKooo4JDjJZ6AKI/VzC4sQZQVVEexRg8Ye3zJ8Xi1GC9ujZp7DnFoiSLgCcQwgYzyEaK0qZkuiMO1KALmIIY1R8ANiHJLzTRDHO6nIeCE64Kqmd0Qh3dpOEL1EOWLY24DoswlcomVnON13nTMLUOUYpRr9AVWsIYCmsr8Q3MPv7AKwaRj5iaK6oexO+HH3RAQAkJACAgB/0XANnPCwNEB3RTGAAAAAElFTkSuQmCC";

XPCOMUtils.defineLazyGetter(this, "Strings", function() {
  return Services.strings.createBundle("chrome://feeds/locale/feeds.properties");
});

XPCOMUtils.defineLazyGetter(this, "FeedHelper", function() {
  let sandbox = {};
  Services.scriptloader.loadSubScript("chrome://feeds/content/FeedHelper.js", sandbox);
  return sandbox["FeedHelper"];
});

function reportErrors(e) {
  if (!e.errors) {
    return;
  }
  if (e.message) {
    Cu.reportError(e.message);
  }
  e.errors.forEach(error => Cu.reportError(error.message));
}

/**
 * @return optionsCallback function for a basic list panel.
 */
function getOptionsCallback(panelId, title, datasetId) {
  return function() {
    return {
      title: title,
      views: [{
        type: Home.panels.View.LIST,
        dataset: datasetId
      }],
      onuninstall: function() {
        // Unregister the panel and delete its data if the user
        // chooses to remove it in settings.
        removeFeedPanel(panelId, datasetId);
        unstoreFeed(panelId);
      }
    };
  };
}

/**
 * Monkey-patched version of FeedHandler.loadFeed.
 *
 * @param feed object created by DOMLinkAdded handler in browser.js
 */
function loadFeed(feed) {
  let chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
  let BrowserApp = chromeWin.BrowserApp;

  // Get the default feed handlers from FeedHandler.
  let handlers = chromeWin.FeedHandler.getContentHandlers(this.TYPE_MAYBE_FEED);

  handlers = handlers.map(function(handler) {
    return {
      name: handler.name,
      action: function defaultHandlerAction(feed) {
        // Merge the handler URL and the feed URL.
        let readerURL = handler.uri;
        readerURL = readerURL.replace(/%s/gi, encodeURIComponent(feed.href));

        // Open the resultant URL in a new tab.
        BrowserApp.addTab(readerURL, { parentId: BrowserApp.selectedTab.id });
      }
    }
  });

  // Add our own custom handler.
  handlers.push({
    name: Strings.GetStringFromName("prompt.firefoxHomepage"),
    action: addFeedPanel
  });

  // JSON for Prompt.
  let p = new Prompt({
    window: chromeWin,
    // XXX: In Firefox 31+, we can get this string from browser.properties.
    title: Strings.GetStringFromName("prompt.subscribeWith")
  });
  p.setSingleChoiceItems(handlers.map(function (handler) {
    return { label: handler.name };
  }));
  p.show(function (data) {
    if (data.button == -1) {
      return;
    }
    // Call the action callback for the feed handler.
    handlers[data.button].action(feed);
  });
}

/**
 * @param feed object created by DOMLinkAdded handler in browser.js
 */
function addFeedPanel(feed) {
  let uuidgen = Cc["@mozilla.org/uuid-generator;1"].getService(Ci.nsIUUIDGenerator);
  let panelId = uuidgen.generateUUID().toString();
  let datasetId = uuidgen.generateUUID().toString();

  // Immediately fetch and parse the feed to get title for panel.
  FeedHelper.parseFeed(feed.href, function (parsedFeed) {
    let title = parsedFeed.title.plainText();

    Home.panels.register(panelId, getOptionsCallback(panelId, title, datasetId));
    Home.panels.install(panelId);

    saveFeedItems(parsedFeed, datasetId);
    storeFeed(feed.href, title, panelId, datasetId);

    let chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
    chromeWin.NativeWindow.toast.show(Strings.GetStringFromName("toast.addedToFirefoxHomepage"), "short");
  });

  // Add periodic sync to update feed once per hour.
  HomeProvider.addPeriodicSync(datasetId, 3600, function () {
    FeedHelper.parseFeed(feed.href, function(parsedFeed) {
      saveFeedItems(parsedFeed, datasetId);
    });
  });
}

/**
 * Uninstalls and unregisters panel, and deletes all feed data.
 */
function removeFeedPanel(panelId, datasetId) {
  Home.panels.uninstall(panelId);
  Home.panels.unregister(panelId);

  HomeProvider.removePeriodicSync(datasetId);
  Task.spawn(function deleteAll() {
    let storage = HomeProvider.getStorage(datasetId);
    yield storage.deleteAll();
  }).then(null, reportErrors);
}

/**
 * @param parsedFeed nsIFeed
 */
function saveFeedItems(parsedFeed, datasetId) {
  let items = FeedHelper.feedToItems(parsedFeed);

  Task.spawn(function () {
    let storage = HomeProvider.getStorage(datasetId);
    yield storage.deleteAll();
    yield storage.save(items);
  }).then(null, reportErrors);
}

/**
 * Stores feed panel data that we need to persist between app runs.
 */
function storeFeed(url, title, panelId, datasetId) {
  let feeds;
  try {
    feeds = JSON.parse(Services.prefs.getCharPref(FEEDS_PREF));
  } catch (e) {
    feeds = [];
  }

  feeds.push({
    url: url,
    title: title,
    panelId: panelId,
    datasetId: datasetId
  });

  Services.prefs.setCharPref(FEEDS_PREF, JSON.stringify(feeds));
}

/**
 * Removes feed from array that persists between app runs.
 */
function unstoreFeed(panelId) {
  try {
    let feeds = JSON.parse(Services.prefs.getCharPref(FEEDS_PREF));
    for (let i = 0; i < feeds.length; i++) {
      if (feeds[i].panelId === panelId) {
        feeds.splice(i, 0);
        break;
      }
    }
    Services.prefs.setCharPref(FEEDS_PREF, JSON.stringify(feeds));
  } catch (e) {
    // We should never call unstoreFeed if the FEEDS_PREF doesn't exist.
    Cu.reportError(e);
  }
}

let gPageActionIcon;
let gPageActionId;
let gOriginalLoadFeed;

function onPageShow(event) {
  let chromeWin = Services.wm.getMostRecentWindow("navigator:browser");
  if (!chromeWin) {
    return;
  }

  let selectedTab = chromeWin.BrowserApp.selectedTab;

  // Ignore load events on frames and other documents.
  // selectedTab may be null during startup.
  if (!selectedTab || event.target != selectedTab.browser.contentDocument) {
    return;
  }

  // Remove any current page action item.
  if (gPageActionId) {
    chromeWin.NativeWindow.pageactions.remove(gPageActionId);
    gPageActionId = null;
  }

  let feeds = selectedTab.browser.feeds;

  // Bail if there are no feeds for this page.
  if (!feeds || feeds.length == 0) {
    return;
  }

  gPageActionId = chromeWin.NativeWindow.pageactions.add({
    icon: gPageActionIcon,
    title: Strings.GetStringFromName("pageAction.subscribeToPage"),
    clickCallback: function onSubscribeClicked() {
      // Follow the regular "Subscribe" menu button action.
      let args = JSON.stringify({ tabId: selectedTab.id });
      Services.obs.notifyObservers(null, "Feeds:Subscribe", args);
    }
  });
}

function loadIntoWindow(window) {
  window.BrowserApp.deck.addEventListener("pageshow", onPageShow, false);

  // Monkey-patch FeedHandler to add option to subscribe menu.
  gOriginalLoadFeed = window.FeedHandler.loadFeed;
  window.FeedHandler.loadFeed = loadFeed;

  if (window.devicePixelRatio <= 1) {
    gPageActionIcon = URLBAR_ICON_MDPI;
  } else if (window.devicePixelRatio <= 1.5) {
    gPageActionIcon = URLBAR_ICON_HDPI;
  } else {
    gPageActionIcon = URLBAR_ICON_XHDPI;
  }
}

function unloadFromWindow(window) {
  window.BrowserApp.deck.removeEventListener("pageshow", onPageShow);
  window.FeedHandler.loadFeed = gOriginalLoadFeed;
}

/**
 * bootstrap.js API
 */
function install(aData, aReason) {}

function uninstall(aData, aReason) {}

let gWindowListener = {
  onOpenWindow: function(aWindow) {
    // Stop listening after the window has been opened.
    Services.wm.removeListener(gWindowListener);

    // Wait for startup to finish before interacting with the UI.
    let win = aWindow.QueryInterface(Ci.nsIInterfaceRequestor).getInterface(Ci.nsIDOMWindowInternal || Ci.nsIDOMWindow);
    win.addEventListener("UIReady", function onLoad() {
      win.removeEventListener("UIReady", onLoad, false);
      loadIntoWindow(win);
    }, false);
  },
  onCloseWindow: function(aWindow) {},
  onWindowTitleChange: function(aWindow, aTitle) {}
};

function startup(aData, aReason) {
  let win = Services.wm.getMostRecentWindow("navigator:browser");
  if (win) {
    // Load into the browser window if it already exists.
    loadIntoWindow(win);
  } else {
    // Otherwise, listen for it to open.
    Services.wm.addListener(gWindowListener);
  }

  try {
    let feeds = JSON.parse(Services.prefs.getCharPref(FEEDS_PREF));
    feeds.forEach(function(feed) {
      // Register any existing panels.
      Home.panels.register(feed.panelId, getOptionsCallback(feed.panelId, feed.title, feed.datasetId));

      // Add periodic sync for existing feeds.
      HomeProvider.addPeriodicSync(feed.datasetId, 3600, function() {
        FeedHelper.parseFeed(feed.url, function(parsedFeed) {
          saveFeedItems(parsedFeed, feed.datasetId);
        });
      });
    });
  } catch (e) {}
}

function shutdown(aData, aReason) {
  // When the application is shutting down we normally don't have to clean any changes made.
  if (aReason == APP_SHUTDOWN) {
    return;
  }

  unloadFromWindow(Services.wm.getMostRecentWindow("navigator:browser"));

  // If the add-on is being uninstalled, also remove all panel data.
  if (aReason == ADDON_UNINSTALL) {
    try {
      let feeds = JSON.parse(Services.prefs.getCharPref(FEEDS_PREF));
      feeds.forEach(function (feed) {
        removeFeedPanel(feed.panelId, feed.datasetId);
      });

      // Clear the stored feeds.
      Services.prefs.clearUserPref(FEEDS_PREF);
    } catch (e) {}
  }
}
<|endoftext|>


<commit_before>'use strict';

/**
 * Return array containing numbers from start to end, including. Increment by 1.
 * @param {int} start The first element of the array.
 * @param {int} end The last element of the array.
 * @param {int} step Step between elements of array. Optional. Defaults to 1.
 * @return {array} Array containing numbers from start to end.
 */
function range(start, end, step) {
	if (step === undefined) {
		step = 1;
	}
	let array = [];
	for(let i = start; i <= end; i += step) {
		array.push(i);
	}
	return array;
}

/**
 * Sum contents of an array.
 * @param {array} array The array.
 * @return {int} Sum of the contents of an array.
 */
function sum(array) {
	let sum = 0;
	array.forEach(function(element) {
		sum += element;
	});
	return sum;
}

let array = range(1, 10);
console.log(array);
console.log(sum(array));
console.log(range(1, 10, 2));
<commit_msg>4: step can be negative<commit_after>'use strict';

/**
 * Return array containing numbers from start to end, including. Increment by 1.
 * @param {int} start The first element of the array.
 * @param {int} end The last element of the array.
 * @param {int} step Step between elements of array. Optional. Defaults to 1.
 * @return {array} Array containing numbers from start to end.
 */
function range(start, end, step) {
	if (step === undefined) {
		step = 1;
	}
	let array = [];
	if (step > 0) {
		for(let i = start; i <= end; i += step) {
			array.push(i);
		}
	} else {
		for(let i = start; i >= end; i += step) {
			array.push(i);
		}
	}
	return array;
}

/**
 * Sum contents of an array.
 * @param {array} array The array.
 * @return {int} Sum of the contents of an array.
 */
function sum(array) {
	let sum = 0;
	array.forEach(function(element) {
		sum += element;
	});
	return sum;
}

let array = range(1, 10);
console.log(array);
console.log(sum(array));
console.log(range(1, 10, 2));
console.log(range(5, 2, -1));
<|endoftext|>


<commit_before>document.getElementById("navMenu").innerHTML =
'
'+
    '
'+
        '
'+
            'About Us' + ''+ ''+ ''+
    '
' +
    '
' + ' Executive Board'+ '
'+
    '
' +
        '
'+
        '
'+
            'Membership'+
        '
'+
        '
'+
            'Events'+
        '
'+
        '
'+
            'AIMS Lab'+
        '
'+
        '
'+
            'Contact'+
        '
'+
    '
'+
'
';
<commit_msg>Update nav.js<commit_after>document.getElementById("navMenu").innerHTML =
'
'+
    '
'+
        '
'+
            'About Us' + '' + ''+ '' +
    '
' +
    '
' + 'Executive Board'+ '
' +
    '
' + '
' +
        '
'+
            'Membership'+
        '
'+
        '
'+
            'Events'+
        '
'+
        '
'+
            'AIMS Lab'+
        '
'+
        '
'+
            'Contact'+
        '
'+
    '
'+
'
';
<|endoftext|>


<commit_before>#!/usr/bin/env node
'use strict';

/*
  Finds all UMLS entries between two given numbers (i.e. C0120000 - C0130000)
  in the Semantic Types defined below, that have at least one SNOWMED description.

  For each entry matching this criteria, it will lookup alternative, but unique,
  variants in english and dutch.
*/

var semanticTypes = [
  "Pharmacologic Substance",
  "Antibiotic",

  "Organic Chemical",

  "Sign or Symptom",
  "Disease or Syndrome",
    "Mental or Behavioral Dysfunction",
    "Neoplastic Process",

  "Cell or Molecular Dysfunction",
  "Injury or Poisoning"
];

var DEBUG = true || process.argv[4] === "debug";
var config  = require('../config/config.js');
var wrapper = require('co-mysql');
var mysql   = require('mysql');
var co      = require('co');

try {
  var connection = mysql.createConnection(config.mysql);
      connection.connect();

  var client = wrapper(connection);
***REMOVED***
catch (err) {
  console.log("MySQL database connection is down");
  process.exit(0);
***REMOVED***

var elastic = require('elasticsearch');
var _       = require('lodash');
var sugar   = require('sugar');

// Custom lib functions
var getUnique  = require('./lib/getUnique.js');
var digitToCUI = require('./lib/digitToCUI.js');

var elasticClient = new elastic.Client({
  "apiVersion" : "1.3"
***REMOVED***);

var between = digitToCUI(process.argv[2]) +"\" AND \"" + digitToCUI(process.argv[3]);
var preferredQuery = [
  "SELECT DISTINCT(a.CUI), b.STY FROM MRCONSO a INNER JOIN MRSTY b ON (a.CUI = b.CUI)",
  "WHERE a.CUI BETWEEN \""+ between + "\"",
    "AND b.STY in (\"" + semanticTypes.join("\",\"") + "\")"
].join(" ");

co(function *() {
  var recordCounter = 0;
  var cuiCodes = yield client.query(preferredQuery);

  if (! cuiCodes || cuiCodes.length === 0) {
    console.log("Could not find any CUI codes!");
    process.exit(0);
  ***REMOVED***

  var bulk = [];

  // Get all records for single CUI
  for (var i=0, N=cuiCodes.length; i<N; i++) {
***REMOVED*** Alternate/Different spellings
    var englishQuery = [
      "SELECT STR",
      "FROM MRCONSO",
      "WHERE CUI='" + cuiCodes[i].CUI + "'",
      "AND SAB IN ('SNOMEDCT_US')",
      "LIMIT 20"
    ].join(" ");

    var dutchQuery = [
      "SELECT STR",
      "FROM MRCONSO",
      "WHERE CUI='" + cuiCodes[i].CUI + "'",
      "AND SAB IN ('MDRDUT', 'MSHDUT', 'ICD10DUT', 'ICD9')",
      "LIMIT 30"
    ].join(" ");

    var englishTerms = yield client.query(englishQuery);
        englishTerms = _.pluck(englishTerms, 'STR');

    if (DEBUG) {
      console.log(cuiCodes[i].CUI);
  ***REMOVED***console.log(englishTerms);
***REMOVED***

    if (englishTerms.length === 0) {
      continue;
***REMOVED***

    var dutchTerms = yield client.query(dutchQuery);
        dutchTerms = _.pluck(dutchTerms, 'STR')

***REMOVED*** Now make the terms unique-ish for elasticsearch
    englishTerms = getUnique(englishTerms);
    dutchTerms   = getUnique(dutchTerms);

    if (DEBUG) {
      console.log("Unique\n", englishTerms.concat(dutchTerms));
  ***REMOVED***console.log("Unique dut", dutchTerms);
      console.log("----------");
***REMOVED***

    /*
***REMOVED*** Add document as a whole for expanding queries.
    bulk.push({
      "index" : {
        "_index" : "expander",
        "_type"  : "records",
  ***REMOVED***
***REMOVED***);

    bulk.push({
      "cui"  : cuiCodes[i].CUI,
      "type" : cuiCodes[i].STY,
      "str"  : englishTerms.concat(dutchTerms)
***REMOVED***);

    if (DEBUG) {
      console.log("Added expander doc");
***REMOVED***

***REMOVED*** For each english term add a document for autocompletions
    for (var j=0, L=englishTerms.length; j<L; j++) {
      recordCounter++;

      bulk.push({
        "index" : {
          "_index" : "autocomplete",
          "_type"  : "records",
    ***REMOVED***
  ***REMOVED***);

      bulk.push({
        "cui"   : cuiCodes[i].CUI,
        "str"   : englishTerms[j]
  ***REMOVED***);
***REMOVED***
    */
  ***REMOVED***

  connection.end();

  /*
  // No entries with usable CUI codes found
  if (bulk.length === 0) {
    process.exit(0);
  ***REMOVED***

  // Insert preffered in Elasticsearch
  elasticClient.bulk({'body' : bulk ***REMOVED***, function(err, body) {
    if (err) {
      console.log(err);
***REMOVED***
    ***REMOVED***
      console.log("Inserted " + recordCounter + " records between \"" + between + "\"");
***REMOVED***

    process.exit(0);
  ***REMOVED***);
  */
***REMOVED***);
<commit_msg>Added populate<commit_after>#!/usr/bin/env node
'use strict';

/*
  Finds all UMLS entries between two given numbers (i.e. C0120000 - C0130000)
  in the Semantic Types defined below, that have at least one SNOWMED description.

  For each entry matching this criteria, it will lookup alternative, but unique,
  variants in english and dutch.
*/

var semanticTypes = [
  "Pharmacologic Substance",
  "Antibiotic",

  "Organic Chemical",

  "Sign or Symptom",
  "Disease or Syndrome",
    "Mental or Behavioral Dysfunction",
    "Neoplastic Process",

  "Cell or Molecular Dysfunction",
  "Injury or Poisoning"
];

var DEBUG   = false || process.argv[4] === "debug";
var config  = require('../config/config.js');
var wrapper = require('co-mysql');
var mysql   = require('mysql');
var co      = require('co');

try {
  var connection = mysql.createConnection(config.mysql);
      connection.connect();

  var client = wrapper(connection);
***REMOVED***
catch (err) {
  console.log("MySQL database connection is down");
  process.exit(0);
***REMOVED***

var elastic = require('elasticsearch');
var _       = require('lodash');
var sugar   = require('sugar');

// Custom lib functions
var getUnique  = require('./lib/getUnique.js');
var digitToCUI = require('./lib/digitToCUI.js');

var elasticClient = new elastic.Client({
  "apiVersion" : "1.3"
***REMOVED***);

var between = digitToCUI(process.argv[2]) +"\" AND \"" + digitToCUI(process.argv[3]);
var preferredQuery = [
  "SELECT DISTINCT(a.CUI), b.STY FROM MRCONSO a INNER JOIN MRSTY b ON (a.CUI = b.CUI)",
  "WHERE a.CUI BETWEEN \""+ between + "\"",
    "AND b.STY in (\"" + semanticTypes.join("\",\"") + "\")"
].join(" ");

co(function *() {
  var recordCounter = 0;
  var cuiCodes = yield client.query(preferredQuery);

  if (! cuiCodes || cuiCodes.length === 0) {
    console.log("Could not find any CUI codes!");
    process.exit(0);
  ***REMOVED***

  var bulk = [];

  // Get all records for single CUI
  for (var i=0, N=cuiCodes.length; i<N; i++) {
***REMOVED*** Alternate/Different spellings
    var englishQuery = [
      "SELECT STR",
      "FROM MRCONSO",
      "WHERE CUI='" + cuiCodes[i].CUI + "'",
      "AND SAB IN ('SNOMEDCT_US')",
      "LIMIT 20"
    ].join(" ");

    var dutchQuery = [
      "SELECT STR",
      "FROM MRCONSO",
      "WHERE CUI='" + cuiCodes[i].CUI + "'",
      "AND SAB IN ('MDRDUT', 'MSHDUT', 'ICD10DUT', 'ICD9')",
      "LIMIT 30"
    ].join(" ");

    var englishTerms = yield client.query(englishQuery);
        englishTerms = _.pluck(englishTerms, 'STR');

    if (DEBUG) {
      console.log(cuiCodes[i].CUI);
  ***REMOVED***console.log(englishTerms);
***REMOVED***

    if (englishTerms.length === 0) {
      continue;
***REMOVED***

    var dutchTerms = yield client.query(dutchQuery);
        dutchTerms = _.pluck(dutchTerms, 'STR')

***REMOVED*** Now make the terms unique-ish for elasticsearch
    englishTerms = getUnique(englishTerms);
    dutchTerms   = getUnique(dutchTerms);

    if (DEBUG) {
      console.log("Unique\n", englishTerms.concat(dutchTerms));
      console.log("Unique dut", dutchTerms);
      console.log("----------");
***REMOVED***

***REMOVED*** Add document as a whole for expanding queries.
    bulk.push({
      "index" : {
        "_index" : "expander",
        "_type"  : "records",
  ***REMOVED***
***REMOVED***);

    bulk.push({
      "cui"  : cuiCodes[i].CUI,
      "type" : cuiCodes[i].STY,
      "str"  : englishTerms.concat(dutchTerms)
***REMOVED***);

    if (DEBUG) {
      console.log("Added expander doc");
***REMOVED***

***REMOVED*** For each english term add a document for autocompletions
    for (var j=0, L=englishTerms.length; j<L; j++) {
      recordCounter++;

      bulk.push({
        "index" : {
          "_index" : "autocomplete",
          "_type"  : "records",
    ***REMOVED***
  ***REMOVED***);

      bulk.push({
        "cui"   : cuiCodes[i].CUI,
        "str"   : englishTerms[j]
  ***REMOVED***);
***REMOVED***
  ***REMOVED***

  connection.end();

  // No entries with usable CUI codes found
  if (bulk.length === 0) {
    process.exit(0);
  ***REMOVED***

  // Insert preffered in Elasticsearch
  elasticClient.bulk({'body' : bulk ***REMOVED***, function(err, body) {
    if (err) {
      console.log(err);
***REMOVED***
    ***REMOVED***
      console.log("Inserted " + recordCounter + " records between \"" + between + "\"");
***REMOVED***

    process.exit(0);
  ***REMOVED***);
***REMOVED***);
<|endoftext|>


<commit_before>
function getJsonFromUrl(hashBased) {
    'use strict'
    var query;
        if (hashBased) {
            var pos = location.href.indexOf("?");
            if (pos == -1) return [];
            query = location.href.substr(pos + 1);
        } else {
            query = location.search.substr(1);
        }
        var result = {};
        query.split("&").forEach(function(part) {
            if (!part) return;
            part = part.split("+").join(" "); // replace every + with space, regexp-free version
            var eq = part.indexOf("=");
            var key = eq > -1 ? part.substr(0, eq) : part;
            var val = eq > -1 ? decodeURIComponent(part.substr(eq + 1)) : "";
            var from = key.indexOf("[");
            if (from == -1) result[decodeURIComponent(key)] = val;
            else {
                var to = key.indexOf("]");
                var index = decodeURIComponent(key.substring(from + 1, to));
                key = decodeURIComponent(key.substring(0, from));
                if (!result[key]) result[key] = [];
                if (!index) result[key].push(val);
                else result[key][index] = val;
            }
        });
        return result;
    }

var resultado = [];

resultado = JSON.parse(getJsonFromUrl().test);

var text1 = "Como " + resultado.lambA + " = " + '\\(c=\\frac{2}{3x}\\) ' + " = " + resultado.lambpA
MathJax.Hub.Queue(["Typeset",MathJax.Hub, text1])

$(document).ready(function() {
    $(".project").html(resultado.project);
    $("#text1").html(text1);

});

// MathJax.Hub.Queue(["Typeset",MathJax.Hub, text1])
<commit_msg>Update reportCS.js<commit_after>// Start of parsing results
function getJsonFromUrl(hashBased) {
    'use strict'
    var query;
    if (hashBased) {
        var pos = location.href.indexOf("?");
        if (pos === -1) return [];
        query = location.href.substr(pos + 1);
    } else {
        query = location.search.substr(1);
    }
    var result = {};
    query.split("&").forEach(function(part) {
        if (!part) return;
        part = part.split("+").join(" "); // replace every + with space, regexp-free version
        var eq = part.indexOf("=");
        var key = eq > -1 ? part.substr(0, eq) : part;
        var val = eq > -1 ? decodeURIComponent(part.substr(eq + 1)) : "";
        var from = key.indexOf("[");
        if (from == -1) result[decodeURIComponent(key)] = val;
        else {
            var to = key.indexOf("]");
            var index = decodeURIComponent(key.substring(from + 1, to));
            key = decodeURIComponent(key.substring(0, from));
            if (!result[key]) result[key] = [];
            if (!index) result[key].push(val);
            else result[key][index] = val;
        }
    });
    return result;
}

var resultado = [];
resultado = JSON.parse(getJsonFromUrl().test);
//End of parsing results

//Variables

var textV1, textV2, textV3;
var textA1, textA2, textA3;
var textM1, textM2, textM3;
var textT1, textT2, textT3;

// Building variable texts

textV1 = "
 Como " + resultado.lambV + "≤ " + resultado.lambpV + ", " + "\\(λ\\)" + " ≤ " + "\\(λ_p\\)" + ", o esforço cortante resistente é dado por:
" + " \\(V_{Rd}=\frac{V_{pl}}{{\\gamma }_{a1}}\\) = " + resultado.vrd + " KN " + "
 Sendo:
 \\(V_{pl}=0,5\\times A_w\\times f_y\\) = " + resultado.vpl + "KN
 \\(A_w=\\ \\textrm{\\'{a}}rea\\ da\\ alma=d\\times t_w\\] = " + resultado.aw + "\\({cm}^4\\)
";
MathJax.Hub.Queue(["Typeset", MathJax.Hub, textV1]);

var text1 = "Como " + resultado.lambA + " = " + '\\(c=\\frac{2}{3x}\\) ' + " = " + resultado.lambpA
MathJax.Hub.Queue(["Typeset", MathJax.Hub, text1]);

$(document).ready(function () {
    // Header
    $(".project").html(resultado.project);
    $(".beam").html(resultado.beam);
    $(".lbForm").html(resultado.lbForm);
    $(".steel").html(resultado.steel);
    $(".fyForm").html(resultado.fyForm);
    $(".fuForm").html(resultado.fuForm);
    $(".E").html(resultado.EForm);
    $(".vk").html(resultado.vk);
    $(".mk").html(resultado.mk);
    $(".gama").html(resultado.gama);
    $(".gama1").html(resultado.gama1);
    $(".cb").html(resultado.cb);
    $(".a").html(resultado.a);

    // Section
    $("#section").html(resultado.section);
    $("#ml").html(resultado.ml);
    $("#d").html(resultado.d);
    $("#bf").html(resultado.bf);
    $(".tw").html(resultado.tw);
    $("#tf").html(resultado.tf);
    $(".h").html(resultado.h);
    $("#dl").html(resultado.dl);
    $("#area").html(resultado.area);
    $("#ix").html(resultado.ix);
    $("#wx").html(resultado.wx);
    $("#rx").html(resultado.rx);
    $("#zx").html(resultado.zx);
    $("#iy").html(resultado.iy);
    $("#wy").html(resultado.wy);
    $("#ry").html(resultado.ry);
    $("#zy").html(resultado.zy);
    $("#rt").html(resultado.rt);
    $("#it").html(resultado.it);
    $("#aba").html(resultado.aba);
    $("#alma").html(resultado.alma);
    $("#cw").html(resultado.cw);
    $("#u").html(resultado.u);

    // Lambs V
    $("#lambV").html(resultado.lambV);
    $("#lambpV").html(resultado.lambpV);
    $("#kv").html(resultado.kv);
    $("#lambrV").html(resultado.lambrV);

    // Situation V
    switch (resultado.situationV) {
        case "Caso 1":
            $(#textV).html(textV1);
            break;
        case "Caso 2":
            $(#textV).html(textV2);
            break;
        case "Caso 3":
            $(#textV).html(textV3);
            break;
    }

    $("#text1").html(text1);

});
<|endoftext|>


<commit_before>/*jslint white: true, vars: true, sloppy: true, devel: true, plusplus: true, browser: true */

/**	THIS COMMENT MUST NOT BE REMOVED
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0  or see LICENSE.txt

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
*/

/**
 * @author Isabella Nake
 * @author Evangelia Mitsopoulou
 * @author Dijan Helbling
 */

/**
 * @Class QuestionView
 * View for displaying questions
 * @constructor
 * - it sets the tag ID for the settings view
 * - assigns event handler when taping on various elements of the question view
 *   such as title, body, done button
 * - bind 2 events, that are related with the loading of statistics and
 *   the calculation of all the statistics metrics. We want to prevent the loading of
 *   statistics view in this case, and we load the question text
 * - it resizes the button's height when it detects orientation change
 * @param {String} controller
 */
function QuestionView() {
    var self = this;

    this.tagID = this.app.viewId;
    var featuredContentId = FEATURED_CONTENT_ID;

    /**
     * It is triggered after statistics are loaded locally from the server. This can happen during the
     * authentication or if we had clicked on the statistics icon and moved to the questions.
     * @event loadstatisticsfromserver
     * @param: a callback function that displays the question text and preventing the display of the statistics view
     */
    $(document).bind("loadstatisticsfromserver", function () {
        if (self.app.isActiveView(self.tagID) && self.app.getLoginState()) {
            console.log("enters load statistics from server is done in question view");
            self.showQuestionBody();
        }
    });

    /**
     * It is triggered when the calculation of all the statistics metrics is done
     * @event allstatisticcalculationsdone
     * @param: a callback function that displays the answer body and preventing the display of the statistics view
     */
    $(document).bind("allstatisticcalculationsdone", function () {
        console.log("enters in calculations done in question view1 ");

        if ((self.app.isActiveView(self.tagID)) && self.app.getLoginState()) {
            console.log("enters in calculations done in question view 2 ");
            self.showQuestionBody();
        }
    });
}

/**
 * Call 'showQuestionTitle()' and 'showQuestionBody()'.
 * Start the timer.
 * @prototype
 * @function prepare
 * @param {NONE}
 */
QuestionView.prototype.prepare = function () {
    var featuredContentId = FEATURED_CONTENT_ID;

    this.showQuestionTitle();
    this.showQuestionBody();

    // TODO Ensure that this timer is working correctly.
    if (!this.app.models.answer.hasStarted()) {
        if (featuredContentId) {
            this.app.models.answer.startTimer(featuredContentId);
        } else {
            this.app.models.answer.startTimer(this.app.models.questionpool.getId());
        }
    }
};

/**
 * Handles action when a tap occurs.
 * @protoype
 * @function tap
 * @param {object} event - contains all the information for the touch interaction.
 */
QuestionView.prototype.tap = function (event) {
    var id = event.target.id;
    console.log(">>>>> [tap registered] ** " + id + " ** <<<<<");

    switch (id) {
        case "questioncross": // Close the question view.
            this.app.models.answer.resetTimer();
            if (this.app.getLoginState()) {
                this.app.changeView("course");
            }
            else {
                this.app.changeView("landing");
            }
            break;
        default: // If anything besides the close button is taped, move to the answer view.
            if (this.app.models.answer.answerScore > -1) {
                this.app.changeView("feedback");
            }
            else {
                this.app.changeView("answer");
            }
            break;
    }
};

/**
 * Shows the current question title and the corresponding icon.
 * @prototype
 * @function showQuestionTitle
 * @param {NONE}
 */
QuestionView.prototype.showQuestionTitle = function () {
    var currentQuestionType = this.app.models.questionpool.getQuestionType();

//    $("#questiondynamicicon").removeClass();
    $("#questiondynamicicon").addClass(jQuery.i18n.prop('msg_' + currentQuestionType + '_icon'));
};

/**
 * Shows the current question text.
 * @prototype
 * @function showQuestionBody
 * @param {NONE}
 */
QuestionView.prototype.showQuestionBody = function () {
    var currentQuestionBody = this.app.models.questionpool.getQuestionBody();

    $("#questionlisttext").html(currentQuestionBody);
};
<commit_msg>question view title icon fix<commit_after>/*jslint white: true, vars: true, sloppy: true, devel: true, plusplus: true, browser: true */

/**	THIS COMMENT MUST NOT BE REMOVED
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements.  See the NOTICE file
distributed with this work for additional information
regarding copyright ownership.  The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License.  You may obtain a copy of the License at

http://www.apache.org/licenses/LICENSE-2.0  or see LICENSE.txt

Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied.  See the License for the
specific language governing permissions and limitations
under the License.
*/

/**
 * @author Isabella Nake
 * @author Evangelia Mitsopoulou
 * @author Dijan Helbling
 */

/**
 * @Class QuestionView
 * View for displaying questions
 * @constructor
 * - it sets the tag ID for the settings view
 * - assigns event handler when taping on various elements of the question view
 *   such as title, body, done button
 * - bind 2 events, that are related with the loading of statistics and
 *   the calculation of all the statistics metrics. We want to prevent the loading of
 *   statistics view in this case, and we load the question text
 * - it resizes the button's height when it detects orientation change
 * @param {String} controller
 */
function QuestionView() {
    var self = this;

    this.tagID = this.app.viewId;
    var featuredContentId = FEATURED_CONTENT_ID;

    /**
     * It is triggered after statistics are loaded locally from the server. This can happen during the
     * authentication or if we had clicked on the statistics icon and moved to the questions.
     * @event loadstatisticsfromserver
     * @param: a callback function that displays the question text and preventing the display of the statistics view
     */
    $(document).bind("loadstatisticsfromserver", function () {
        if (self.app.isActiveView(self.tagID) && self.app.getLoginState()) {
            console.log("enters load statistics from server is done in question view");
            self.showQuestionBody();
        }
    });

    /**
     * It is triggered when the calculation of all the statistics metrics is done
     * @event allstatisticcalculationsdone
     * @param: a callback function that displays the answer body and preventing the display of the statistics view
     */
    $(document).bind("allstatisticcalculationsdone", function () {
        console.log("enters in calculations done in question view1 ");

        if ((self.app.isActiveView(self.tagID)) && self.app.getLoginState()) {
            console.log("enters in calculations done in question view 2 ");
            self.showQuestionBody();
        }
    });
}

/**
 * Call 'showQuestionTitle()' and 'showQuestionBody()'.
 * Start the timer.
 * @prototype
 * @function prepare
 * @param {NONE}
 */
QuestionView.prototype.prepare = function () {
    var featuredContentId = FEATURED_CONTENT_ID;

    this.showQuestionTitle();
    this.showQuestionBody();

    // TODO Ensure that this timer is working correctly.
    if (!this.app.models.answer.hasStarted()) {
        if (featuredContentId) {
            this.app.models.answer.startTimer(featuredContentId);
        } else {
            this.app.models.answer.startTimer(this.app.models.questionpool.getId());
        }
    }
};

/**
 * Handles action when a tap occurs.
 * @protoype
 * @function tap
 * @param {object} event - contains all the information for the touch interaction.
 */
QuestionView.prototype.tap = function (event) {
    var id = event.target.id;
    console.log(">>>>> [tap registered] ** " + id + " ** <<<<<");

    switch (id) {
        case "questioncross": // Close the question view.
            this.app.models.answer.resetTimer();
            if (this.app.getLoginState()) {
                this.app.changeView("course");
            }
            else {
                this.app.changeView("landing");
            }
            break;
        default: // If anything besides the close button is taped, move to the answer view.
            if (this.app.models.answer.answerScore > -1) {
                this.app.changeView("feedback");
            }
            else {
                this.app.changeView("answer");
            }
            break;
    }
};

/**
 * Shows the current question title and the corresponding icon.
 * @prototype
 * @function showQuestionTitle
 * @param {NONE}
 */
QuestionView.prototype.showQuestionTitle = function () {
    var currentQuestionType = this.app.models.questionpool.getQuestionType();

    $("#questiondynamicicon").removeClass();
    $("#questiondynamicicon").addClass(jQuery.i18n.prop('msg_' + currentQuestionType + '_icon'));
};

/**
 * Shows the current question text.
 * @prototype
 * @function showQuestionBody
 * @param {NONE}
 */
QuestionView.prototype.showQuestionBody = function () {
    var currentQuestionBody = this.app.models.questionpool.getQuestionBody();

    $("#questionlisttext").html(currentQuestionBody);
};
<|endoftext|>


<commit_before>var test = require('tape')

var Account = require('../../index')

var store = require('humble-localstorage')

test('new Account(options)', function (t) {
  store.clear()
  var account = new Account({
    url: 'http://localhost:3000/session/account'
  })

  t.is(typeof account, 'object', 'Account is a constructor')
  t.ok(account.hasOwnProperty('username'), 'has account.username')
  t.is(account.username, undefined, 'account.username is undefined')
  t.is(typeof account.fetch, 'function', 'has "fetch()"')
  t.is(typeof account.get, 'function', 'has "get()"')
  t.is(typeof account.isSignedIn, 'function', 'has "isSignedIn()"')
  t.is(typeof account.profile.fetch, 'function', 'has "profile.fetch()"')
  t.is(typeof account.profile.get, 'function', 'has "profile.get()"')
  t.is(typeof account.profile.update, 'function', 'has "profile.update()"')
  t.is(typeof account.signIn, 'function', 'has "signIn()"')
  t.is(typeof account.signOut, 'function', 'has "signOut()"')
  t.is(typeof account.signUp, 'function', 'has "signUp()"')
  t.is(typeof account.on, 'function', 'has "on()"')
  t.is(typeof account.one, 'function', 'has "one()"')
  t.is(typeof account.off, 'function', 'has "off()"')

  t.end()
})

test('Account(options) w/o new', function (t) {
  var account = Account({
    url: 'http://localhost:3000/session/account'
  })

  t.is(typeof account, 'object', 'Account is a constructor')

  t.end()
})

test('new Account() w/o options', function (t) {
  t.throws(Account, 'throws error')

  t.end()
})

test('new Account() w/o options.url', function (t) {
  t.throws(Account.bind(null, { validate: function () {} }), 'throws error')

  t.end()
})
<commit_msg>test: fix url in constructor<commit_after>var test = require('tape')

var Account = require('../../index')

var store = require('humble-localstorage')

test('new Account(options)', function (t) {
  store.clear()
  var account = new Account({
    url: 'http://localhost:3000'
  })

  t.is(typeof account, 'object', 'Account is a constructor')
  t.ok(account.hasOwnProperty('username'), 'has account.username')
  t.is(account.username, undefined, 'account.username is undefined')
  t.is(typeof account.fetch, 'function', 'has "fetch()"')
  t.is(typeof account.get, 'function', 'has "get()"')
  t.is(typeof account.isSignedIn, 'function', 'has "isSignedIn()"')
  t.is(typeof account.profile.fetch, 'function', 'has "profile.fetch()"')
  t.is(typeof account.profile.get, 'function', 'has "profile.get()"')
  t.is(typeof account.profile.update, 'function', 'has "profile.update()"')
  t.is(typeof account.signIn, 'function', 'has "signIn()"')
  t.is(typeof account.signOut, 'function', 'has "signOut()"')
  t.is(typeof account.signUp, 'function', 'has "signUp()"')
  t.is(typeof account.on, 'function', 'has "on()"')
  t.is(typeof account.one, 'function', 'has "one()"')
  t.is(typeof account.off, 'function', 'has "off()"')

  t.end()
})

test('Account(options) w/o new', function (t) {
  var account = Account({
    url: 'http://localhost:3000/session/account'
  })

  t.is(typeof account, 'object', 'Account is a constructor')

  t.end()
})

test('new Account() w/o options', function (t) {
  t.throws(Account, 'throws error')

  t.end()
})

test('new Account() w/o options.url', function (t) {
  t.throws(Account.bind(null, { validate: function () {} }), 'throws error')

  t.end()
})
<|endoftext|>