<commit_before>/*!
 * ${copyright}
 */

// Provides element sap.m.FlexItemData
sap.ui.define(['./FlexBoxStylingHelper', './library', 'sap/ui/core/LayoutData'],
 function(FlexBoxStylingHelper, library, LayoutData) {
	"use strict";

	// shortcut for sap.m.BackgroundDesign
	var BackgroundDesign = library.BackgroundDesign;

	// shortcut for sap.m.FlexAlignSelf
	var FlexAlignSelf = library.FlexAlignSelf;

	/**
	 * Constructor for a new sap.m.FlexItemData.
	 *
	 * @param {string} [sId] ID for the new element, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the new element.
	 *
	 * @class
	 * Holds layout data for a FlexBox / HBox / VBox.
	 * @extends sap.ui.core.LayoutData
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @alias sap.m.FlexItemData
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var FlexItemData = LayoutData.extend("sap.m.FlexItemData", /** @lends sap.m.FlexItemData.prototype */ { metadata : {

		library : "sap.m",
		properties : {

			/**
			 * Determines cross-axis alignment of individual element (not currently supported in Internet Explorer).
			 *
			 * @see http://www.w3.org/TR/css-flexbox-1/#align-items-property
			 */
			alignSelf : {type : "sap.m.FlexAlignSelf", group : "Misc", defaultValue : FlexAlignSelf.Auto}, // TODO remove after the end of support for Internet Explorer

			/**
			 * Determines the display order of flex items independent of their source code order.
			 *
			 * @see http://www.w3.org/TR/css-flexbox-1/#order-property
			 */
			order : {type : "int", group : "Misc", defaultValue : 0},

			/**
			 * Determines the flexibility of the flex item when allocatable space is remaining.
			 *
			 * @see http://www.w3.org/TR/css-flexbox-1/#flex-grow-property
			 */
			growFactor : {type : "float", group : "Misc", defaultValue : 0},

			/**
			 * The shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed.
			 *
			 * @see http://www.w3.org/TR/css-flexbox-1/#flex-shrink-property
			 *
			 * @since 1.24.0
			 */
			shrinkFactor : {type : "float", group : "Misc", defaultValue : 1}, //This property is not supported in Internet Explorer 9, Android Native Browser/Webview <4.4, and Safari <7

			/**
			 * The base size is the initial main size of the item for the flex algorithm. If set to "auto", this will be the computed size of the item.
			 *
			 * @see http://www.w3.org/TR/css-flexbox-1/#flex-basis-property
			 *
			 * @since 1.32.0
			 */
			baseSize : {type : "sap.ui.core.CSSSize", group : "Misc", defaultValue : "auto"},

			/**
			 * The minimum height of the flex item.
			 * @since 1.36.0
			 */
			minHeight : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : 'auto'},

			/**
			 * The maximum height of the flex item.
			 * @since 1.36.0
			 */
			maxHeight : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : ''},

			/**
			 * The minimum height of the flex item.
			 * @since 1.36.0
			 */
			minWidth : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : 'auto'},

			/**
			 * The maximum height of the flex item.
			 * @since 1.36.0
			 */
			maxWidth : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : ''},

			/**
			 * The style class will be applied to the flex item and can be used for CSS selectors.
			 */
			styleClass : {type : "string", group : "Misc", defaultValue : ''},

			/**
			 * Defines the background style of the flex item.
			 *
			 * @since 1.38.5
			 */
			backgroundDesign: {type: "sap.m.BackgroundDesign", group: "Appearance", defaultValue: BackgroundDesign.Transparent}
		}
	}});

	/**
	 * Sets the alignSelf property.
	 *
	 * @public
	 * @param {string} sValue Align option.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setAlignSelf = function(sValue) {
		var sOldValue = this.getAlignSelf();
		this.setProperty("alignSelf", sValue, true);
		this.$().removeClass("sapMFlexItemAlign" + sOldValue).addClass("sapMFlexItemAlign" + this.getAlignSelf());

		return this;
	};

	/**
	 * Sets the order.
	 *
	 * @public
	 * @param {string} sValue Order in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setOrder = function(sValue) {
		this.setProperty("order", sValue, true);
		FlexBoxStylingHelper.setStyle(null, this, "order", this.getOrder());

		return this;
	};

	/**
	 * Sets the growFactor property.
	 *
	 * @public
	 * @param {string} sValue Grow factor in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setGrowFactor = function(sValue) {
		this.setProperty("growFactor", sValue, true);
		FlexBoxStylingHelper.setStyle(null, this, "flex-grow", this.getGrowFactor());

		return this;
	};

	/**
	 * Sets the shrinkFactor property.
	 *
	 * @public
	 * @param {string} sValue Shrink factor in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 * @see https://www.w3.org/TR/css-flexbox-1/#propdef-flex-shrink
	 */
	FlexItemData.prototype.setShrinkFactor = function(sValue) {
		this.setProperty("shrinkFactor", sValue, true);
		FlexBoxStylingHelper.setStyle(null, this, "flex-shrink", this.getShrinkFactor());

		return this;
	};

	/**
	 * Sets the base size for flex items.
	 *
	 * @public
	 * @param {string} sValue Base size in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setBaseSize = function(sValue) {
		this.setProperty("baseSize", sValue, true);
		FlexBoxStylingHelper.setStyle(null, this, "flex-basis", this.getBaseSize());

		return this;
	};

	/**
	 * Sets minimum height.
	 *
	 * @public
	 * @param {string} sValue Minimum height in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setMinHeight = function(sValue) {
		this.setProperty("minHeight", sValue, true);
		this.$().css("min-height", this.getMinHeight());

		return this;
	};

	/**
	 * Sets maximum height.
	 *
	 * @public
	 * @param {string} sValue Maximum height in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setMaxHeight = function(sValue) {
		this.setProperty("maxHeight", sValue, true);
		this.$().css("max-height", this.getMaxHeight());

		return this;
	};

	/**
	 * Sets minimum width.
	 *
	 * @public
	 * @param {string} sValue Minimum width in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setMinWidth = function(sValue) {
		this.setProperty("minWidth", sValue, true);
		this.$().css("min-width", this.getMinWidth());

		return this;
	};

	/**
	 * Sets maximum width.
	 *
	 * @public
	 * @param {string} sValue Maximum width in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setMaxWidth = function(sValue) {
		this.setProperty("maxWidth", sValue, true);
		this.$().css("max-width", this.getMaxWidth());

		return this;
	};

	/**
	 * Sets background design for flex items.
	 *
	 * @public
	 * @param {string} sValue Background design in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setBackgroundDesign = function(sValue) {
		var sOldValue = this.getBackgroundDesign();
		this.setProperty("backgroundDesign", sValue, true);
		this.$().removeClass("sapMFlexBoxBG" + sOldValue).addClass("sapMFlexBoxBG" + this.getBackgroundDesign());

		return this;
	};

	/**
	 * Sets style class.
	 *
	 * @public
	 * @param {string} sValue Style class.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setStyleClass = function(sValue) {
		var sOldValue = this.getStyleClass();
		this.setProperty("styleClass", sValue, true);
		this.$().removeClass(sOldValue).addClass(this.getStyleClass());

		return this;
	};

	 /**
	  * Returns the correct FlexBox item DOM reference.
	  *
	  * @param {string} [sSuffix] ID suffix to get the DOMRef for
	  * @return {Element} The Element's DOM Element sub DOM Element or null
	  * @protected
	  */
	 FlexItemData.prototype.getDomRef = function(sSuffix) {
		 var oParent,
			 oItemDomRef = LayoutData.prototype.getDomRef.call(this, sSuffix);

		 if (oItemDomRef) {
			 return oItemDomRef;
		 }

		 oParent = this.getParent();

		 if (!oParent) {
			 return null;
		 }

		 return oParent.getDomRef(sSuffix);
	 };

	 return FlexItemData;

});
<commit_msg>[INTERNAL] sap.m.FlexItemData: minWidth/maxWidth description is fixed<commit_after>/*!
 * ${copyright}
 */

// Provides element sap.m.FlexItemData
sap.ui.define(['./FlexBoxStylingHelper', './library', 'sap/ui/core/LayoutData'],
 function(FlexBoxStylingHelper, library, LayoutData) {
	"use strict";

	// shortcut for sap.m.BackgroundDesign
	var BackgroundDesign = library.BackgroundDesign;

	// shortcut for sap.m.FlexAlignSelf
	var FlexAlignSelf = library.FlexAlignSelf;

	/**
	 * Constructor for a new sap.m.FlexItemData.
	 *
	 * @param {string} [sId] ID for the new element, generated automatically if no ID is given
	 * @param {object} [mSettings] Initial settings for the new element.
	 *
	 * @class
	 * Holds layout data for a FlexBox / HBox / VBox.
	 * @extends sap.ui.core.LayoutData
	 * @version ${version}
	 *
	 * @constructor
	 * @public
	 * @alias sap.m.FlexItemData
	 * @ui5-metamodel This control/element also will be described in the UI5 (legacy) designtime metamodel
	 */
	var FlexItemData = LayoutData.extend("sap.m.FlexItemData", /** @lends sap.m.FlexItemData.prototype */ { metadata : {

		library : "sap.m",
		properties : {

			/**
			 * Determines cross-axis alignment of individual element (not currently supported in Internet Explorer).
			 *
			 * @see http://www.w3.org/TR/css-flexbox-1/#align-items-property
			 */
			alignSelf : {type : "sap.m.FlexAlignSelf", group : "Misc", defaultValue : FlexAlignSelf.Auto}, // TODO remove after the end of support for Internet Explorer

			/**
			 * Determines the display order of flex items independent of their source code order.
			 *
			 * @see http://www.w3.org/TR/css-flexbox-1/#order-property
			 */
			order : {type : "int", group : "Misc", defaultValue : 0},

			/**
			 * Determines the flexibility of the flex item when allocatable space is remaining.
			 *
			 * @see http://www.w3.org/TR/css-flexbox-1/#flex-grow-property
			 */
			growFactor : {type : "float", group : "Misc", defaultValue : 0},

			/**
			 * The shrink factor determines how much the flex item will shrink relative to the rest of the flex items in the flex container when negative free space is distributed.
			 *
			 * @see http://www.w3.org/TR/css-flexbox-1/#flex-shrink-property
			 *
			 * @since 1.24.0
			 */
			shrinkFactor : {type : "float", group : "Misc", defaultValue : 1}, //This property is not supported in Internet Explorer 9, Android Native Browser/Webview <4.4, and Safari <7

			/**
			 * The base size is the initial main size of the item for the flex algorithm. If set to "auto", this will be the computed size of the item.
			 *
			 * @see http://www.w3.org/TR/css-flexbox-1/#flex-basis-property
			 *
			 * @since 1.32.0
			 */
			baseSize : {type : "sap.ui.core.CSSSize", group : "Misc", defaultValue : "auto"},

			/**
			 * The minimum height of the flex item.
			 * @since 1.36.0
			 */
			minHeight : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : 'auto'},

			/**
			 * The maximum height of the flex item.
			 * @since 1.36.0
			 */
			maxHeight : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : ''},

			/**
			 * The minimum width of the flex item.
			 * @since 1.36.0
			 */
			minWidth : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : 'auto'},

			/**
			 * The maximum width of the flex item.
			 * @since 1.36.0
			 */
			maxWidth : {type : "sap.ui.core.CSSSize", group : "Dimension", defaultValue : ''},

			/**
			 * The style class will be applied to the flex item and can be used for CSS selectors.
			 */
			styleClass : {type : "string", group : "Misc", defaultValue : ''},

			/**
			 * Defines the background style of the flex item.
			 *
			 * @since 1.38.5
			 */
			backgroundDesign: {type: "sap.m.BackgroundDesign", group: "Appearance", defaultValue: BackgroundDesign.Transparent}
		}
	}});

	/**
	 * Sets the alignSelf property.
	 *
	 * @public
	 * @param {string} sValue Align option.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setAlignSelf = function(sValue) {
		var sOldValue = this.getAlignSelf();
		this.setProperty("alignSelf", sValue, true);
		this.$().removeClass("sapMFlexItemAlign" + sOldValue).addClass("sapMFlexItemAlign" + this.getAlignSelf());

		return this;
	};

	/**
	 * Sets the order.
	 *
	 * @public
	 * @param {string} sValue Order in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setOrder = function(sValue) {
		this.setProperty("order", sValue, true);
		FlexBoxStylingHelper.setStyle(null, this, "order", this.getOrder());

		return this;
	};

	/**
	 * Sets the growFactor property.
	 *
	 * @public
	 * @param {string} sValue Grow factor in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setGrowFactor = function(sValue) {
		this.setProperty("growFactor", sValue, true);
		FlexBoxStylingHelper.setStyle(null, this, "flex-grow", this.getGrowFactor());

		return this;
	};

	/**
	 * Sets the shrinkFactor property.
	 *
	 * @public
	 * @param {string} sValue Shrink factor in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 * @see https://www.w3.org/TR/css-flexbox-1/#propdef-flex-shrink
	 */
	FlexItemData.prototype.setShrinkFactor = function(sValue) {
		this.setProperty("shrinkFactor", sValue, true);
		FlexBoxStylingHelper.setStyle(null, this, "flex-shrink", this.getShrinkFactor());

		return this;
	};

	/**
	 * Sets the base size for flex items.
	 *
	 * @public
	 * @param {string} sValue Base size in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setBaseSize = function(sValue) {
		this.setProperty("baseSize", sValue, true);
		FlexBoxStylingHelper.setStyle(null, this, "flex-basis", this.getBaseSize());

		return this;
	};

	/**
	 * Sets minimum height.
	 *
	 * @public
	 * @param {string} sValue Minimum height in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setMinHeight = function(sValue) {
		this.setProperty("minHeight", sValue, true);
		this.$().css("min-height", this.getMinHeight());

		return this;
	};

	/**
	 * Sets maximum height.
	 *
	 * @public
	 * @param {string} sValue Maximum height in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setMaxHeight = function(sValue) {
		this.setProperty("maxHeight", sValue, true);
		this.$().css("max-height", this.getMaxHeight());

		return this;
	};

	/**
	 * Sets minimum width.
	 *
	 * @public
	 * @param {string} sValue Minimum width in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setMinWidth = function(sValue) {
		this.setProperty("minWidth", sValue, true);
		this.$().css("min-width", this.getMinWidth());

		return this;
	};

	/**
	 * Sets maximum width.
	 *
	 * @public
	 * @param {string} sValue Maximum width in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setMaxWidth = function(sValue) {
		this.setProperty("maxWidth", sValue, true);
		this.$().css("max-width", this.getMaxWidth());

		return this;
	};

	/**
	 * Sets background design for flex items.
	 *
	 * @public
	 * @param {string} sValue Background design in string format.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setBackgroundDesign = function(sValue) {
		var sOldValue = this.getBackgroundDesign();
		this.setProperty("backgroundDesign", sValue, true);
		this.$().removeClass("sapMFlexBoxBG" + sOldValue).addClass("sapMFlexBoxBG" + this.getBackgroundDesign());

		return this;
	};

	/**
	 * Sets style class.
	 *
	 * @public
	 * @param {string} sValue Style class.
	 * @returns {sap.m.FlexItemData} this FlexItemData reference for chaining.
	 */
	FlexItemData.prototype.setStyleClass = function(sValue) {
		var sOldValue = this.getStyleClass();
		this.setProperty("styleClass", sValue, true);
		this.$().removeClass(sOldValue).addClass(this.getStyleClass());

		return this;
	};

	 /**
	  * Returns the correct FlexBox item DOM reference.
	  *
	  * @param {string} [sSuffix] ID suffix to get the DOMRef for
	  * @return {Element} The Element's DOM Element sub DOM Element or null
	  * @protected
	  */
	 FlexItemData.prototype.getDomRef = function(sSuffix) {
		 var oParent,
			 oItemDomRef = LayoutData.prototype.getDomRef.call(this, sSuffix);

		 if (oItemDomRef) {
			 return oItemDomRef;
		 }

		 oParent = this.getParent();

		 if (!oParent) {
			 return null;
		 }

		 return oParent.getDomRef(sSuffix);
	 };

	 return FlexItemData;

});
<|endoftext|>


<commit_before>$(function() {
    var status = [];
    var onDataReceived = function(data) { return status = data; };
    var startNight = function(nights, night) {
        nights.push(night);
        return $("
", {"id": ""+night});
    };
    var finishNight = function(night, rows) {
        if (rows.length > 0) {
            rows.push("
");
            night.append(rows.join(""));
            night.appendTo("#content");
        }
    };
    var padExpid = function(expid) {
        var e = "" + expid;
        var z = [];
        for (var k = 0; k < 8 - e.length; k++) { z.push("0"); }
        return z.join("") + e;
    };
    var nightButton = function(n, role, success) {
        var color = success ? "btn-success" : "btn-danger";
        var up = role == "show" ? "Show" : "Hide":
        var alt = role == "show" ? "hide" : "show";
        return "<button type=\"button\" class=\"btn " + color +
            " btn-block\" id=\"" + role + n +
            "\" style=\"display:block;\" onclick=\"$('#ul" + n +
            "').css('display', 'block');$('#" + alt + n +
            "').css('display', 'block');$('#" + role + n +
            "').css('display', 'none');\">" + up + "</button>";
    };
    var display = function() {
        $("#content").empty();
        var nights = [];
        var rows = [];
        var night;
        for (var k = 0; k < status.length; k++) {
            var n = status[k][0]
            if (nights.indexOf(n) == -1) {
                //
                // Finish previous night
                //
                finishNight(night, rows);
                //
                // Start a new night
                //
                night = startNight(nights, n)
                rows = ["
Night " + n + "
",
                        nightButton(n, "show", true),
                        nightButton(n, "hide", true),
                        "
"];
            }
            //
            // Add to existing night
            //
            var p = padExpid(status[k][1]);
            var c = status[k][2] ? "bg-success" : "bg-danger";
            if (!status[k][2]) {
                rows[1] = nightButton(n, "show", false);
                rows[2] = nightButton(n, "show", false);
            }
            var l = status[k][3].length > 0 ? " Last " + status[k][3] + " exposure." : "";
            var r = "
" +
                    p + l + "
";
            // console.log(r);
            rows.push(r);
        }
        //
        // Finish the final night
        //
        finishNight(night, rows);
    };
    $.getJSON("dts_status.json", {}, onDataReceived).always(display);
    return true;
});
<commit_msg>fix syntax [skip ci]<commit_after>$(function() {
    var status = [];
    var onDataReceived = function(data) { return status = data; };
    var startNight = function(nights, night) {
        nights.push(night);
        return $("
", {"id": ""+night});
    };
    var finishNight = function(night, rows) {
        if (rows.length > 0) {
            rows.push("
");
            night.append(rows.join(""));
            night.appendTo("#content");
        }
    };
    var padExpid = function(expid) {
        var e = "" + expid;
        var z = [];
        for (var k = 0; k < 8 - e.length; k++) { z.push("0"); }
        return z.join("") + e;
    };
    var nightButton = function(n, role, success) {
        var color = success ? "btn-success" : "btn-danger";
        var up = role == "show" ? "Show" : "Hide";
        var alt = role == "show" ? "hide" : "show";
        return "<button type=\"button\" class=\"btn " + color +
            " btn-block\" id=\"" + role + n +
            "\" style=\"display:block;\" onclick=\"$('#ul" + n +
            "').css('display', 'block');$('#" + alt + n +
            "').css('display', 'block');$('#" + role + n +
            "').css('display', 'none');\">" + up + "</button>";
    };
    var display = function() {
        $("#content").empty();
        var nights = [];
        var rows = [];
        var night;
        for (var k = 0; k < status.length; k++) {
            var n = status[k][0]
            if (nights.indexOf(n) == -1) {
                //
                // Finish previous night
                //
                finishNight(night, rows);
                //
                // Start a new night
                //
                night = startNight(nights, n)
                rows = ["
Night " + n + "
",
                        nightButton(n, "show", true),
                        nightButton(n, "hide", true),
                        "
"];
            }
            //
            // Add to existing night
            //
            var p = padExpid(status[k][1]);
            var c = status[k][2] ? "bg-success" : "bg-danger";
            if (!status[k][2]) {
                rows[1] = nightButton(n, "show", false);
                rows[2] = nightButton(n, "hide", false);
            }
            var l = status[k][3].length > 0 ? " Last " + status[k][3] + " exposure." : "";
            var r = "
" +
                    p + l + "
";
            // console.log(r);
            rows.push(r);
        }
        //
        // Finish the final night
        //
        finishNight(night, rows);
    };
    $.getJSON("dts_status.json", {}, onDataReceived).always(display);
    return true;
});
<|endoftext|>


<commit_before>$(function() {
    var status = [];
    var onDataReceived = function(data) { return status = data; };
    var startNight = function(nights, night) {
        nights.push(night);
        return $("
", {"id": ""+night});
    };
    var finishNight = function(night, rows) {
        if (rows.length > 0) {
            rows.push("
");
            night.append(rows.join(""));
            night.appendTo("#container");
        }
    };
    var padExpid = function(expid) {
        var e = "" + expid;
        var z = [];
        for (var k = 0; k < 8 - e.length; k++) { z.push("0"); }
        return z.join("") + e;
    }
    var display = function() {
        $("#container").empty();
        var nights = [];
        var rows = [];
        var night;
        for (var k = 0; k < status.length; k++) {
            var n = status[k][0]
            if (nights.indexOf(n) == -1) {
                //
                // Finish previous night
                //
                finishNight(night, rows);
                //
                // Start a new night
                //
                night = startNight(nights, n)
                rows = ["
Night " + n + "
",
                        "
Show
",
                        "
Hide
",
                        "
"];
            }
            //
            // Add to existing night
            //
            var p = padExpid(status[k][1])
            var c = status[k][2] ? "success" : "failure";
            var l = status[k][3].length > 0 ? " Last " + status[k][3] + " exposure." : "";
            var r = "
" +
                    p + l + "
";
            // console.log(r);
            rows.push(r);
        }
        //
        // Finish the final night
        //
        finishNight(night, rows);
    };
    $.getJSON("dts_status.json", {}, onDataReceived).always(display);
    return true;
});
<commit_msg>show/hide buttons [skip ci]<commit_after>$(function() {
    var status = [];
    var onDataReceived = function(data) { return status = data; };
    var startNight = function(nights, night) {
        nights.push(night);
        return $("
", {"id": ""+night});
    };
    var finishNight = function(night, rows) {
        if (rows.length > 0) {
            rows.push("
");
            night.append(rows.join(""));
            night.appendTo("#container");
        }
    };
    var padExpid = function(expid) {
        var e = "" + expid;
        var z = [];
        for (var k = 0; k < 8 - e.length; k++) { z.push("0"); }
        return z.join("") + e;
    }
    var display = function() {
        $("#container").empty();
        var nights = [];
        var rows = [];
        var night;
        for (var k = 0; k < status.length; k++) {
            var n = status[k][0]
            if (nights.indexOf(n) == -1) {
                //
                // Finish previous night
                //
                finishNight(night, rows);
                //
                // Start a new night
                //
                night = startNight(nights, n)
                rows = ["
Night " + n + "
",
                        "
Show
",
                        "
Hide
",
                        "
"];
            }
            //
            // Add to existing night
            //
            var p = padExpid(status[k][1])
            var c = status[k][2] ? "success" : "failure";
            var l = status[k][3].length > 0 ? " Last " + status[k][3] + " exposure." : "";
            var r = "
" +
                    p + l + "
";
            // console.log(r);
            rows.push(r);
        }
        //
        // Finish the final night
        //
        finishNight(night, rows);
    };
    $.getJSON("dts_status.json", {}, onDataReceived).always(display);
    return true;
});
<|endoftext|>


<commit_before>(() => {
	Snakeskin.addDirective(
		'attr',

		{
			placement: 'template',
			notEmpty: true,
			text: true
		},

		function (command) {
			this.startInlineDir();
			if (this.isReady()) {
				let str = '',
					groups = this.splitAttrsGroup(command);

				for (let i = -1; ++i < groups.length;) {
					let el = groups[i];

					str += this.returnAttrDecl(
						el.attr,
						el.group,
						el.separator
					);
				}

				this.append(str);
			}
		}
	);

	var escapeEqRgxp = /===|==|([\\]+)=/g,
		escapeOrRgxp = /\|\||([\\]+)\|/g;

	var unEscapeEqRgxp = /__SNAKESKIN_EQ__(\d+)_(\d+)_/g,
		unEscapeOrRgxp = /__SNAKESKIN_OR__(\d+)_(\d+)_/g;

	function escapeEq(sstr, $1) {
		if ($1 && $1.length % 2 === 0) {
			return sstr;
		}

		return `__SNAKESKIN_EQ__${sstr.split('=').length}_${$1.length}_`;
	}

	function escapeOr(sstr, $1) {
		if ($1 && $1.length % 2 === 0) {
			return sstr;
		}

		return `__SNAKESKIN_OR__${sstr.split('|').length}_${$1.length}_`;
	}

	function unEscapeEq(sstr, $1, $2) {
		return new Array(Number($2)).join('\\') + new Array(Number($1)).join('=');
	}

	function unEscapeOr(sstr, $1, $2) {
		return new Array(Number($2)).join('\\') + new Array(Number($1)).join('|');
	}

	/**
	 * Вернуть строку декларации XML атрибутов
	 *
	 * @param {string} str - исходная строка
	 * @param {?string=} [opt_group] - название группы
	 * @param {?string=} [opt_separator='-'] - разделитель группы
	 * @param {?boolean=} [opt_classLink=false] - если true, то значения для атрибута class
	 *     будут сохраняться во временную переменную
	 *
	 * @return {string}
	 */
	DirObj.prototype.returnAttrDecl = function (str, opt_group, opt_separator, opt_classLink) {
		var rAttr = this.attr,
			rEscape = this.attrEscape;

		this.attr = true;
		this.attrEscape = true;

		opt_group = opt_group || '';
		opt_separator = opt_separator || '-';

		str = str
			.replace(escapeHTMLRgxp, escapeHTML)
			.replace(escapeOrRgxp, escapeOr);

		var parts = str.split('|'),
			res = '',
			ref = this.bemRef;

		var s = ADV_LEFT_BLOCK + LEFT_BLOCK,
			e = RIGHT_BLOCK;

		for (let i = -1; ++i < parts.length;) {
			parts[i] = parts[i]
				.replace(unEscapeOrRgxp, unEscapeOr)
				.replace(escapeEqRgxp, escapeEq);

			let arg = parts[i].split('='),
				empty = arg.length !== 2;

			if (empty) {
				arg[1] = this.doctype === 'xml' ?
					arg[0] : '';
			}

			arg[0] = arg[0].trim().replace(unEscapeEqRgxp, unEscapeEq);
			arg[1] = arg[1].trim().replace(unEscapeEqRgxp, unEscapeEq);

			res += /* cbws */`
				var __ATTR_STR__ = \'\',
					__ATTR_J__ = 0;
			`;

			if (opt_group) {
				arg[0] = opt_group + opt_separator + arg[0];

			} else {
				arg[0] = arg[0].charAt(0) === '-' ?
					`data-${arg[0].slice(1)}` : arg[0];
			}

			arg[0] = this.replaceDangerBlocks(
				`'${this.pasteTplVarBlocks(arg[0])}'`
			);

			let vals = splitBySpace(arg[1]);

			for (let j = -1; ++j < vals.length;) {
				let val = vals[j].trim();

				if (val.charAt(0) === '&' && ref) {
					val = `${s}'${this.replaceTplVars(ref, true)}'|bem '${this.replaceTplVars(val.substring('&'.length), true)}'${e}`;
					val = this.pasteDangerBlocks(this.replaceTplVars(val));
				}

				val = this.prepareOutput(
					this.replaceDangerBlocks(`'${this.pasteTplVarBlocks(val)}'`), true
				) || '';

				res += /* cbws */`
					if ((${val}) != null && (${val}) !== '') {
						__ATTR_STR__ += __ATTR_J__ ? ' ' + ${val} : ${val};
						__ATTR_J__++;
					}
				`;
			}

			res += `if ((${arg[0]}) != null && (${arg[0]}) != '' && (__ATTR_STR__ || ${empty})) {`;
			let tmp = /* cbws */`
				if (__NODE__) {
					__NODE__.setAttribute(${arg[0]}, __ATTR_STR__);

				} else {
					${this.wrap(`' ' + ${arg[0]} + (__ATTR_STR__ ? '="' + __ATTR_STR__ + '"' : '')`)}
				}
			`;

			if (opt_classLink) {
				res += /* cbws */`
					if (__ATTR_TMP__[(${arg[0]})] != null) {
						__ATTR_TMP__[(${arg[0]})] += __ATTR_STR__;

					} else {
						${tmp}
					}
				`;

			} else {
				res += tmp;
			}

			res += '}';
		}

		this.attr = rAttr;
		this.attrEscape = rEscape;

		return res;
	};

	/**
	 * Разбить строку декларации атрибута на группы
	 *
	 * @param {string} str - исходная строка
	 * @return {!Array}
	 */
	DirObj.prototype.splitAttrsGroup = function (str) {
		var rAttr = this.attr,
			rEscape = this.attrEscape;

		this.attr = true;
		this.attrEscape = true;

		str = this.replaceTplVars(str, null, true);
		var groups = [];

		var group = '',
			attr = '',
			sep = '';

		var pOpen = 0;
		var separator = {
			'-': true,
			':': true,
			'_': true
		};

		for (let i = -1; ++i < str.length;) {
			let el = str.charAt(i),
				next = str.charAt(i + 1);

			if (!pOpen) {
				if (separator[el] && next === '(') {
					pOpen++;
					i++;
					sep = el;
					continue;
				}

				if (el === '(') {
					pOpen++;
					sep = '';
					continue;
				}
			}

			if (pOpen) {
				if (el === '(') {
					pOpen++;

				} else if (el === ')') {
					pOpen--;

					if (!pOpen) {
						groups.push({
							group: Snakeskin.Filters.html(group, true).trim(),
							separator: sep,
							attr: attr.trim()
						});

						group = '';
						attr = '';
						sep = '';

						i++;
						continue;
					}
				}
			}

			if (!pOpen) {
				group += el;

			} else {
				attr += el;
			}
		}

		if (group && !attr) {
			groups.push({
				group: null,
				separator: null,
				attr: group.trim()
			});
		}

		this.attr = rAttr;
		this.attrEscape = rEscape;

		return groups;
	};
})();
<commit_msg>Рефакторинг<commit_after>(() => {
	Snakeskin.addDirective(
		'attr',

		{
			placement: 'template',
			notEmpty: true,
			text: true
		},

		function (command) {
			this.startInlineDir();
			if (this.isReady()) {
				let str = '',
					groups = this.splitAttrsGroup(command);

				for (let i = -1; ++i < groups.length;) {
					let el = groups[i];

					str += this.returnAttrDecl(
						el.attr,
						el.group,
						el.separator
					);
				}

				this.append(str);
			}
		}
	);

	var escapeEqRgxp = /===|==|([\\]+)=/g,
		escapeOrRgxp = /\|\||([\\]+)\|/g;

	var unEscapeEqRgxp = /__SNAKESKIN_EQ__(\d+)_(\d+)_/g,
		unEscapeOrRgxp = /__SNAKESKIN_OR__(\d+)_(\d+)_/g;

	function escapeEq(sstr, $1) {
		if ($1 && $1.length % 2 === 0) {
			return sstr;
		}

		return `__SNAKESKIN_EQ__${sstr.split('=').length}_${$1.length}_`;
	}

	function escapeOr(sstr, $1) {
		if ($1 && $1.length % 2 === 0) {
			return sstr;
		}

		return `__SNAKESKIN_OR__${sstr.split('|').length}_${$1.length}_`;
	}

	function unEscapeEq(sstr, $1, $2) {
		return new Array(Number($2)).join('\\') + new Array(Number($1)).join('=');
	}

	function unEscapeOr(sstr, $1, $2) {
		return new Array(Number($2)).join('\\') + new Array(Number($1)).join('|');
	}

	/**
	 * Вернуть строку декларации XML атрибутов
	 *
	 * @param {string} str - исходная строка
	 * @param {?string=} [opt_group] - название группы
	 * @param {?string=} [opt_separator='-'] - разделитель группы
	 * @param {?boolean=} [opt_classLink=false] - если true, то значения для атрибута class
	 *     будут сохраняться во временную переменную
	 *
	 * @return {string}
	 */
	DirObj.prototype.returnAttrDecl = function (str, opt_group, opt_separator, opt_classLink) {
		var rAttr = this.attr,
			rEscape = this.attrEscape;

		this.attr = true;
		this.attrEscape = true;

		opt_group = opt_group || '';
		opt_separator = opt_separator || '-';

		str = str
			.replace(escapeHTMLRgxp, escapeHTML)
			.replace(escapeOrRgxp, escapeOr);

		var parts = str.split('|'),
			res = '',
			ref = this.bemRef;

		var s = ADV_LEFT_BLOCK + LEFT_BLOCK,
			e = RIGHT_BLOCK;

		for (let i = -1; ++i < parts.length;) {
			parts[i] = parts[i]
				.replace(unEscapeOrRgxp, unEscapeOr)
				.replace(escapeEqRgxp, escapeEq);

			let arg = parts[i].split('='),
				empty = arg.length !== 2;

			if (empty) {
				arg[1] = this.doctype === 'xml' ?
					arg[0] : '';
			}

			arg[0] = arg[0].trim().replace(unEscapeEqRgxp, unEscapeEq);
			arg[1] = arg[1].trim().replace(unEscapeEqRgxp, unEscapeEq);

			res += /* cbws */`
				var __ATTR_STR__ = \'\',
					__ATTR_J__ = 0;
			`;

			if (opt_group) {
				arg[0] = opt_group + opt_separator + arg[0];

			} else {
				arg[0] = arg[0].charAt(0) === '-' ?
					`data-${arg[0].slice(1)}` : arg[0];
			}

			arg[0] = this.replaceDangerBlocks(
				`'${this.pasteTplVarBlocks(arg[0])}'`
			);

			let vals = splitBySpace(arg[1]);

			for (let j = -1; ++j < vals.length;) {
				let val = vals[j].trim();

				if (val.charAt(0) === '&' && ref) {
					val = `${s}'${this.replaceTplVars(ref)}'|bem '${this.replaceTplVars(val.substring('&'.length))}'${e}`;
					val = this.pasteDangerBlocks(this.replaceTplVars(val));
				}

				val = this.prepareOutput(
					this.replaceDangerBlocks(`'${this.pasteTplVarBlocks(val)}'`), true
				) || '';

				res += /* cbws */`
					if ((${val}) != null && (${val}) !== '') {
						__ATTR_STR__ += __ATTR_J__ ? ' ' + ${val} : ${val};
						__ATTR_J__++;
					}
				`;
			}

			res += `if ((${arg[0]}) != null && (${arg[0]}) != '' && (__ATTR_STR__ || ${empty})) {`;
			let tmp = /* cbws */`
				if (__NODE__) {
					__NODE__.setAttribute(${arg[0]}, __ATTR_STR__);

				} else {
					${this.wrap(`' ' + ${arg[0]} + (__ATTR_STR__ ? '="' + __ATTR_STR__ + '"' : '')`)}
				}
			`;

			if (opt_classLink) {
				res += /* cbws */`
					if (__ATTR_TMP__[(${arg[0]})] != null) {
						__ATTR_TMP__[(${arg[0]})] += __ATTR_STR__;

					} else {
						${tmp}
					}
				`;

			} else {
				res += tmp;
			}

			res += '}';
		}

		this.attr = rAttr;
		this.attrEscape = rEscape;

		return res;
	};

	/**
	 * Разбить строку декларации атрибута на группы
	 *
	 * @param {string} str - исходная строка
	 * @return {!Array}
	 */
	DirObj.prototype.splitAttrsGroup = function (str) {
		var rAttr = this.attr,
			rEscape = this.attrEscape;

		this.attr = true;
		this.attrEscape = true;

		str = this.replaceTplVars(str, false, true);
		var groups = [];

		var group = '',
			attr = '',
			sep = '';

		var pOpen = 0;
		var separator = {
			'-': true,
			':': true,
			'_': true
		};

		for (let i = -1; ++i < str.length;) {
			let el = str.charAt(i),
				next = str.charAt(i + 1);

			if (!pOpen) {
				if (separator[el] && next === '(') {
					pOpen++;
					i++;
					sep = el;
					continue;
				}

				if (el === '(') {
					pOpen++;
					sep = '';
					continue;
				}
			}

			if (pOpen) {
				if (el === '(') {
					pOpen++;

				} else if (el === ')') {
					pOpen--;

					if (!pOpen) {
						groups.push({
							group: Snakeskin.Filters.html(group, true).trim(),
							separator: sep,
							attr: attr.trim()
						});

						group = '';
						attr = '';
						sep = '';

						i++;
						continue;
					}
				}
			}

			if (!pOpen) {
				group += el;

			} else {
				attr += el;
			}
		}

		if (group && !attr) {
			groups.push({
				group: null,
				separator: null,
				attr: group.trim()
			});
		}

		this.attr = rAttr;
		this.attrEscape = rEscape;

		return groups;
	};
})();
<|endoftext|>


<commit_before>/*jslint node:true, browser:true */
'use strict';
/*
    Copyright 2015 Enigma Marketing Services Limited

    Licensed 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

    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.
*/

module.exports = function (app) {
    var Directive = function (Restangular, $timeout, $q) {
        var deep = require('deep-get-set'),
            directive = {},
            pendingRequests = [],
            completeRequests = {};

        deep.p = true; //hack to create empty objects

        directive.restrict = 'A';

        directive.scope = {};

        directive.controller = function ($scope) {
            var self = this;
            // expose the local scope so it can be shared on
            // the directives that require this one
            // check directives/var.js
            self.$scope = $scope;

            self.parseName = function (name) {
                var opts = {},
                    parts = name.split('.');

                opts.name = name;
                opts.entity = parts[0];
                opts.id = parts[1];
                opts.property = parts.slice(2).join('.');

                return opts;
            };

            self.getData = function (name) {
                var opts = self.parseName(name),
                    Entity = Restangular.all(opts.entity),
                    isRequestPending = (pendingRequests.indexOf(opts.entity + '.' + opts.id) !== -1),
                    hasBeenRequested = !!($scope[opts.entity] && $scope[opts.entity][opts.id]);

                if (!hasBeenRequested && !isRequestPending) {
                    // add to pending requests
                    pendingRequests.push(opts.entity + '.' + opts.id);
                    // create an empty object for that entity in the scope
                    $scope[opts.entity] = {};

                    // get data from API
                    Entity
                        .get(opts.id)
                        .then(function (data) {
                            // remove from pending requests
                            pendingRequests.splice(pendingRequests.indexOf(opts.entity + '.' + opts.id), 1);

                            $timeout(function () {
                                $scope.$apply(function () {
                                    var value;
                                    // add the API response to the $scope
                                    deep($scope, opts.entity + '.' + opts.id, data);
                                    // cache in complete requests so we can quicly access it
                                    completeRequests[opts.entity] = $scope[opts.entity];
                                    // if the requested property is missing
                                    // create it
                                    value = deep($scope, opts.name);
                                    if (value === undefined) {
                                        deep($scope, opts.name, '');
                                    }
                                });
                            });
                        }, function (err) {
                            self.$scope.$emit('error', err);
                        });
                }

                return $scope;
            };

            self.getModel = function (name) {
                return deep($scope, name);
            };

            self.saveAll = function () {
                var promisses = [];

                self.$scope.$emit('saving');

                Object.keys(completeRequests).forEach(function (entity) {
                    var Entity = completeRequests[entity];

                    Object.keys(Entity).forEach(function (id) {
                        var item = Entity[id];

                        promisses.push(item.save());
                    });
                });

                $q.all(promisses).then(function () {
                    self.$scope.$emit('saved');
                }, function (err) {
                    self.$scope.$emit('error', err);
                });
            };

            // iterates the $scope obj and applies an get to all
            // restangular objects
            self.reloadAll = function () {
                var promisses = [];

                self.$scope.$emit('reloading');

                Object.keys(completeRequests).forEach(function (entity) {
                    var Entity = completeRequests[entity];

                    Object.keys(Entity).forEach(function (id) {
                        var item = Entity[id],
                            promise;

                        promise = item.get().then(function (data) {
                            $timeout(function () {
                                $scope.$apply(function () {
                                    // add the API response to the $scope
                                    deep($scope, entity + '.' + id, data);
                                });
                            });
                        });

                        promisses.push(promise);
                    });
                });

                $q.all(promisses).then(function () {
                    self.$scope.$emit('reloaded');
                }, function (err) {
                    self.$scope.$emit('error', err);
                });
            };
        };

        return directive;
    };

    app.directive('lkEdit', ['Restangular', '$timeout', '$q', Directive]);

    return app;
};<commit_msg>fix bug preventing multiple lk-edit directives to be used on the page<commit_after>/*jslint node:true, browser:true */
'use strict';
/*
    Copyright 2015 Enigma Marketing Services Limited

    Licensed 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

    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.
*/

module.exports = function (app) {
    var Directive = function (Restangular, $timeout, $q) {
        var deep = require('deep-get-set'),
            directive = {};

        deep.p = true; //hack to create empty objects

        directive.restrict = 'A';

        directive.scope = {};

        directive.controller = function ($scope) {
            var self = this;
            // expose the local scope so it can be shared on
            // the directives that require this one
            // check directives/var.js
            self.$scope = $scope;

            $scope.pendingRequests = [];
            $scope.completeRequests = {};

            self.parseName = function (name) {
                var opts = {},
                    parts = name.split('.');

                opts.name = name;
                opts.entity = parts[0];
                opts.id = parts[1];
                opts.property = parts.slice(2).join('.');

                return opts;
            };

            self.getData = function (name) {
                var opts = self.parseName(name),
                    Entity = Restangular.all(opts.entity),
                    isRequestPending = ($scope.pendingRequests.indexOf(opts.entity + '.' + opts.id) !== -1),
                    hasBeenRequested = !!($scope[opts.entity] && $scope[opts.entity][opts.id]);

                if (!hasBeenRequested && !isRequestPending) {
                    // add to pending requests
                    $scope.pendingRequests.push(opts.entity + '.' + opts.id);
                    // create an empty object for that entity in the scope
                    $scope[opts.entity] = {};

                    // get data from API
                    Entity
                        .get(opts.id)
                        .then(function (data) {
                            // remove from pending requests
                            $scope.pendingRequests.splice($scope.pendingRequests.indexOf(opts.entity + '.' + opts.id), 1);

                            $timeout(function () {
                                $scope.$apply(function () {
                                    var value;
                                    // add the API response to the $scope
                                    deep($scope, opts.entity + '.' + opts.id, data);
                                    // cache in complete requests so we can quicly access it
                                    $scope.completeRequests[opts.entity] = $scope[opts.entity];
                                    // if the requested property is missing
                                    // create it
                                    value = deep($scope, opts.name);
                                    if (value === undefined) {
                                        deep($scope, opts.name, '');
                                    }
                                });
                            });
                        }, function (err) {
                            self.$scope.$emit('error', err);
                        });
                }

                return $scope;
            };

            self.getModel = function (name) {
                return deep($scope, name);
            };

            self.saveAll = function () {
                var promisses = [];

                self.$scope.$emit('saving');

                Object.keys($scope.completeRequests).forEach(function (entity) {
                    var Entity = $scope.completeRequests[entity];

                    Object.keys(Entity).forEach(function (id) {
                        var item = Entity[id];

                        promisses.push(item.save());
                    });
                });

                $q.all(promisses).then(function () {
                    self.$scope.$emit('saved');
                }, function (err) {
                    self.$scope.$emit('error', err);
                });
            };

            // iterates the $scope obj and applies an get to all
            // restangular objects
            self.reloadAll = function () {
                var promisses = [];

                self.$scope.$emit('reloading');

                Object.keys($scope.completeRequests).forEach(function (entity) {
                    var Entity = $scope.completeRequests[entity];

                    Object.keys(Entity).forEach(function (id) {
                        var item = Entity[id],
                            promise;

                        promise = item.get().then(function (data) {
                            $timeout(function () {
                                $scope.$apply(function () {
                                    // add the API response to the $scope
                                    deep($scope, entity + '.' + id, data);
                                });
                            });
                        });

                        promisses.push(promise);
                    });
                });

                $q.all(promisses).then(function () {
                    self.$scope.$emit('reloaded');
                }, function (err) {
                    self.$scope.$emit('error', err);
                });
            };
        };

        return directive;
    };

    app.directive('lkEdit', ['Restangular', '$timeout', '$q', Directive]);

    return app;
};<|endoftext|>


<commit_before>/**
 * Tokens are used to send back a generic key that indicates that you have been logged in in the past. Having a valid
 * token means that once you log in, through the application you will not have to do it again unless the tokens have
 * been revoked or expired. This is handy when you have to do many operations at once. You would just log in, get a token
 * and send the token around to ensure that you have access to the system.
 * @type {tokens}
 */
module.exports = function(crypto){
    "use strict";

    var self = {};
    self.tokens = [];
    self.supers = [];

    /**
     * Supers are SuperUsers, they can do anything, Only users that deserve this privilege and responsibility should
     * be granted it.
     * @param token String value returned from the "create" method.
     * @param userId String value for the User's ID
     */
    function addSuper(token, profile){
        if(self.supers[token] == null){
            self.supers[token] = crypto.encrypt(profile);
        }
    }

    /**
     * Everyone that is logged in needs to get added to the token collection.
     * @param token String value returned from the "create" method.
     * @param userId String value for the User's ID
     */
    function addToken(token, profile){
        if(self.tokens[token] == null){
            self.tokens[token] = crypto.encrypt(profile);
        }
    }

    /**
     * The validate method accepts a token value and returns back all of the details about the token from when it
     * was created.
     * @param token String value returned from the "create" method.
     * @returns {token, isValid, isSuper, userId}
     */
    self.validate = function(token){
        var obj = {};
        obj.token = token;
        obj.isValid = false;
        obj.isSuper = false;
        obj.profile = null;

        console.log(self.tokens);
        console.log(self.supers);
        if(self.tokens[token] != null){
            obj.isValid = true;
            obj.profile = crypto.decrypt(self.tokens[token]);

            if(self.supers[token] != null) {
                obj.isSuper = true;
            }
        }

        return obj;
    }

    /**
     * If you want to log out or remove access from a specific token you can call revoke.
     * @param token String value returned from the "create" method.
     */
    self.revoke = function(token){
        self.tokens[token] = null;
    };

    /**
     * Method will create a token in the system for a specific user id. It assumes that you have been logged in and
     * your permissions have been validate.
     * @param userId String value for the User's ID
     * @param isSuper Boolean, are you a superUser?
     * @returns {token|isValid|isSuper|userId}
     */
    self.create = function(token, profile){
        var profileString = JSON.stringify(profile);

        if(profile.isSuper){
            addSuper(token, profileString);
        }

        addToken(token, profileString);

        return self.validate(token);
    };

    return self;
};
<commit_msg>Duh' checked in console.log<commit_after>/**
 * Tokens are used to send back a generic key that indicates that you have been logged in in the past. Having a valid
 * token means that once you log in, through the application you will not have to do it again unless the tokens have
 * been revoked or expired. This is handy when you have to do many operations at once. You would just log in, get a token
 * and send the token around to ensure that you have access to the system.
 * @type {tokens}
 */
module.exports = function(crypto){
    "use strict";

    var self = {};
    self.tokens = [];
    self.supers = [];

    /**
     * Supers are SuperUsers, they can do anything, Only users that deserve this privilege and responsibility should
     * be granted it.
     * @param token String value returned from the "create" method.
     * @param userId String value for the User's ID
     */
    function addSuper(token, profile){
        if(self.supers[token] == null){
            self.supers[token] = crypto.encrypt(profile);
        }
    }

    /**
     * Everyone that is logged in needs to get added to the token collection.
     * @param token String value returned from the "create" method.
     * @param userId String value for the User's ID
     */
    function addToken(token, profile){
        if(self.tokens[token] == null){
            self.tokens[token] = crypto.encrypt(profile);
        }
    }

    /**
     * The validate method accepts a token value and returns back all of the details about the token from when it
     * was created.
     * @param token String value returned from the "create" method.
     * @returns {token, isValid, isSuper, userId}
     */
    self.validate = function(token){
        var obj = {};
        obj.token = token;
        obj.isValid = false;
        obj.isSuper = false;
        obj.profile = null;

        if(self.tokens[token] != null){
            obj.isValid = true;
            obj.profile = crypto.decrypt(self.tokens[token]);

            if(self.supers[token] != null) {
                obj.isSuper = true;
            }
        }

        return obj;
    }

    /**
     * If you want to log out or remove access from a specific token you can call revoke.
     * @param token String value returned from the "create" method.
     */
    self.revoke = function(token){
        self.tokens[token] = null;
    };

    /**
     * Method will create a token in the system for a specific user id. It assumes that you have been logged in and
     * your permissions have been validate.
     * @param userId String value for the User's ID
     * @param isSuper Boolean, are you a superUser?
     * @returns {token|isValid|isSuper|userId}
     */
    self.create = function(token, profile){
        var profileString = JSON.stringify(profile);

        if(profile.isSuper){
            addSuper(token, profileString);
        }

        addToken(token, profileString);

        return self.validate(token);
    };

    return self;
};
<|endoftext|>


<commit_before>(function() {
  var FrHolidays, moment, Parser;

  moment = require('moment');
  Parser = require('parser');

  Holidays = {
    // Retourne l'ensemble des vacances de l'année passée en parametre
    // Le champ zone correspond a une zone A, B, ou C, ou les 3 si non renseignée.
    by_year: function(year, zone) {
      return [

      ];
    },

    all :function(year, zone) {
      return [

      ];
    }

    // True si la date passée en parametre est dans une période de vacances scolaire dans la zone fournie en parametre.
    // Le format est le format attendu de la date
    // Si la zone n'est pas renseigné, la recherche se fait sur les zone A B et C
    isDateInHolidays: function(date, format, zone) {
      var dates = new Array();
      dates[0] = date;
      return Parser.isDatesInHolidays(dates, format, zone)[0];
    }
  };

  module.exports = Holidays;

}).call(this);
<commit_msg>définition des fonctions accessible du module<commit_after>(function() {
  var FrHolidays, moment, Parser;

  moment = require('moment');
  Parser = require('parser');

  Holidays = {
    // Retourne l'ensemble des vacances de l'année passée en parametre
    // Le champ zone correspond a une zone A, B, ou C, ou les 3 si non renseignée.
    by_year: function(year, zone) {
      return Parser.getHolidaysByYear(year, zone);
    },

    all :function(year, zone) {
      return [

      ];
    },

    // Un tableau de boolean si les dates passées en parametre est dans une période de vacances scolaire dans la zone fournie en parametre.
    // Le format est le format attendu de la date
    // Si la zone n'est pas renseigné, la recherche se fait sur les zone A B et C
    isDatesInHolidays: function(dates, format, zone) {
      return Parser.isDatesInHolidays(dates, format, zone)[0];
    },

    // True si la date passée en parametre est dans une période de vacances scolaire dans la zone fournie en parametre.
    // Le format est le format attendu de la date
    // Si la zone n'est pas renseigné, la recherche se fait sur les zone A B et C
    isDateInHolidays: function(date, format, zone) {
      var dates = new Array();
      dates[0] = date;
      return Parser.isDatesInHolidays(dates, format, zone)[0];
    }
  };

  module.exports = Holidays;

}).call(this);
<|endoftext|>


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

var templates = require('./templates')
var fs = require('fs')
var path = require('path')
var cli = require('yargs')
    .usage('Usage: $0 [options]')
    .option('max', {
        describe: 'Maximum number of generated devices',
        default: 5
    })
    .option('f', {
        boolean: true,
        alias: 'force',
        describe: 'Override existing config file'
    })
    .option('n', {
        boolean: true,
        alias: 'dry-run',
        describe: 'Don\'t write the generated config to disk',
    })
    .option('t', {
        alias: 'type',
        describe: 'Device types',
        default: 'phone',
        choices: templates.types
    })
    .version(function() {
        var pack = require('../package');
        return pack.name + " " + pack.version;
    })
    .help('help')
var argv = cli.argv

const CONFIG_FILE = path.join(process.cwd(), '/xd-testing.json')

fs.access(CONFIG_FILE, fs.F_OK, function(err) {
    var dryRun = !!argv['dry-run'];
    var fileExists = !err; // File isn't accessible, so write a new one
    var writeFile = dryRun && (!fileExists || argv.force);

    if (!writeFile && !dryRun) {
        console.log("There is already a file " + CONFIG_FILE);
    } else {
        // Generate config

        // File isn't accessible, so write a new one

        var types = argv.type || templates.types
        if (!(types instanceof Array)) {
            types = [types];
        }

        // For each setup use 2^n + 1 devices
        var setups = []
        var deviceIndices = 'ABCDEFGHJKLMNOPQRSTUVWXYZ'
        for (let t = 1; t < argv.max; t *= 2) {
            var devices = {}
            for (let i = 0; i <= t; i++) {
                devices[deviceIndices[i]] = templates.random.randomOfTypes(types)
            }
            setups.push({devices: devices})
        }
        var config = {setups: setups}

        var json = JSON.stringify(config, null, 2)

        if (writeFile) {
            fs.writeFile(CONFIG_FILE, json, err => {
                if (err) throw err
                console.log("Wrote config file to " + CONFIG_FILE)
                console.log(json)
            })
        } else if (dryRun) {
            console.log("Would write config file to " + CONFIG_FILE)
            console.log(json)
        }
    }
})
<commit_msg>Fix bug<commit_after>#!/usr/bin/env node
"use strict"

var templates = require('./templates')
var fs = require('fs')
var path = require('path')
var cli = require('yargs')
    .usage('Usage: $0 [options]')
    .option('max', {
        describe: 'Maximum number of generated devices',
        default: 5
    })
    .option('f', {
        boolean: true,
        alias: 'force',
        describe: 'Override existing config file'
    })
    .option('n', {
        boolean: true,
        alias: 'dry-run',
        describe: 'Don\'t write the generated config to disk',
    })
    .option('t', {
        alias: 'type',
        describe: 'Device types',
        default: 'phone',
        choices: templates.types
    })
    .version(function() {
        var pack = require('../package');
        return pack.name + " " + pack.version;
    })
    .help('help')
var argv = cli.argv

const CONFIG_FILE = path.join(process.cwd(), '/xd-testing.json')

fs.access(CONFIG_FILE, fs.F_OK, function(err) {
    var dryRun = !!argv['dry-run'];
    var fileExists = !err; // File isn't accessible, so write a new one
    var writeFile = !dryRun && (!fileExists || argv.force);

    if (!writeFile && !dryRun) {
        console.log("There is already a file " + CONFIG_FILE);
    } else {
        // Generate config

        // File isn't accessible, so write a new one

        var types = argv.type || templates.types
        if (!(types instanceof Array)) {
            types = [types];
        }

        // For each setup use 2^n + 1 devices
        var setups = []
        var deviceIndices = 'ABCDEFGHJKLMNOPQRSTUVWXYZ'
        for (let t = 1; t < argv.max; t *= 2) {
            var devices = {}
            for (let i = 0; i <= t; i++) {
                devices[deviceIndices[i]] = templates.random.randomOfTypes(types)
            }
            setups.push({devices: devices})
        }
        var config = {setups: setups}

        var json = JSON.stringify(config, null, 2)

        if (writeFile) {
            fs.writeFile(CONFIG_FILE, json, err => {
                if (err) throw err
                console.log("Wrote config file to " + CONFIG_FILE)
                console.log(json)
            })
        } else if (dryRun) {
            console.log("Would write config file to " + CONFIG_FILE)
            console.log(json)
        }
    }
})
<|endoftext|>


<commit_before>var presetPatterns = require('./preset-patterns');

/**
 * Given some user options, put together a config object that
 * the validators can use.
 *
 * @param {Object|String} [primaryOptions = 'suit']
 * @param {RegExp} [primaryOptions.componentName]
 * @param {RegExp} [primaryOptions.utilitySelectors]
 * @param {Object|Function} [primaryOptions.componentSelectors]
 * @param {RegExp} [primaryOptions.ignoreSelectors]
 * @param {RegExp} [primaryOptions.ignoreCustomProperties]
 * @param {String} [primaryOptions.preset] - The same as passing a string for `primaryOptions`
 * @param {Object} [primaryOptions.presetOptions] - Options that are can be used by
 *   a pattern (e.g. `namespace`)
 * @param {Object} [secondaryOptions] - The same as `primaryOptions.presetOptions`
 * @return {Object} The configuration object
 */
module.exports = function(primaryOptions, secondaryOptions) {
  var patterns = primaryOptions || 'suit';
  if (typeof patterns === 'string') {
    patterns = presetPatterns[patterns];
  } else if (patterns.preset) {
    patterns = presetPatterns[patterns.preset];

    // Enable overriding of preset patterns
    if (primaryOptions.utilitySelectors) {
      patterns.utilitySelectors = primaryOptions.utilitySelectors;
    }
    if (primaryOptions.componentName) {
      patterns.componentName = primaryOptions.componentName;
    }
    if (primaryOptions.componentSelectors) {
      patterns.componentSelectors = primaryOptions.componentSelectors;
    }
    if (primaryOptions.ignoreSelectors) {
      patterns.ignoreSelectors = primaryOptions.ignoreSelectors;
    }
    if (primaryOptions.ignoreCustomProperties) {
      patterns.ignoreCustomProperties = primaryOptions.ignoreCustomProperties;
    }
  }

  var presetOptions = secondaryOptions || {};
  if (primaryOptions && primaryOptions.presetOptions) {
    presetOptions = primaryOptions.presetOptions;
  }

  var implicitComponents = secondaryOptions && secondaryOptions.implicitComponents !== undefined ?
    secondaryOptions.implicitComponents : primaryOptions && primaryOptions.implicitComponents;
  implicitComponents = implicitComponents === undefined ? false : implicitComponents;

  if (typeof implicitComponents === 'string') {
    implicitComponents = [implicitComponents];
  }

  var implicitUtilities = secondaryOptions && secondaryOptions.implicitUtilities !== undefined ?
    secondaryOptions.implicitUtilities : primaryOptions && primaryOptions.implicitUtilities;

  if (typeof implicitUtilities === 'string') {
    implicitUtilities = [implicitUtilities];
  }

  return {
    patterns: patterns,
    presetOptions: presetOptions,
    componentNamePattern: patterns.componentName || /^[-_a-zA-Z0-9]+$/,
    implicitComponents: implicitComponents,
    implicitUtilities: implicitUtilities,
  };
}
<commit_msg>Clean up implicitComponents and implicitUtilities options<commit_after>var presetPatterns = require('./preset-patterns');

/**
 * Given some user options, put together a config object that
 * the validators can use.
 *
 * @param {Object|String} [primaryOptions = 'suit']
 * @param {RegExp} [primaryOptions.componentName]
 * @param {RegExp} [primaryOptions.utilitySelectors]
 * @param {Object|Function} [primaryOptions.componentSelectors]
 * @param {RegExp} [primaryOptions.ignoreSelectors]
 * @param {RegExp} [primaryOptions.ignoreCustomProperties]
 * @param {String} [primaryOptions.preset] - The same as passing a string for `primaryOptions`
 * @param {Object} [primaryOptions.presetOptions] - Options that are can be used by
 *   a pattern (e.g. `namespace`)
 * @param {Object} [secondaryOptions] - The same as `primaryOptions.presetOptions`
 * @return {Object} The configuration object
 */
module.exports = function(primaryOptions, secondaryOptions) {
  var patterns = primaryOptions || 'suit';
  if (typeof patterns === 'string') {
    patterns = presetPatterns[patterns];
  } else if (patterns.preset) {
    patterns = presetPatterns[patterns.preset];

    // Enable overriding of preset patterns
    if (primaryOptions.utilitySelectors) {
      patterns.utilitySelectors = primaryOptions.utilitySelectors;
    }
    if (primaryOptions.componentName) {
      patterns.componentName = primaryOptions.componentName;
    }
    if (primaryOptions.componentSelectors) {
      patterns.componentSelectors = primaryOptions.componentSelectors;
    }
    if (primaryOptions.ignoreSelectors) {
      patterns.ignoreSelectors = primaryOptions.ignoreSelectors;
    }
    if (primaryOptions.ignoreCustomProperties) {
      patterns.ignoreCustomProperties = primaryOptions.ignoreCustomProperties;
    }
  }

  var presetOptions = secondaryOptions || {};
  if (primaryOptions && primaryOptions.presetOptions) {
    presetOptions = primaryOptions.presetOptions;
  }

  var implicitComponents =
    getImplicitDefineValue('implicitComponents', primaryOptions, secondaryOptions);
  var implicitUtilities =
    getImplicitDefineValue('implicitUtilities', primaryOptions, secondaryOptions);

  return {
    patterns: patterns,
    presetOptions: presetOptions,
    componentNamePattern: patterns.componentName || /^[-_a-zA-Z0-9]+$/,
    implicitComponents: implicitComponents,
    implicitUtilities: implicitUtilities,
  };
}

function getImplicitDefineValue(key, primaryOptions, secondaryOptions) {
  var implicitValue = false;

  if (secondaryOptions && secondaryOptions[key] !== undefined) {
    implicitValue = secondaryOptions[key];
  } else if (primaryOptions && primaryOptions[key]) {
    implicitValue = primaryOptions[key]
  }

  if (typeof implicitValue === 'string') {
    implicitValue = [implicitValue];
  }

  return implicitValue;
}<|endoftext|>


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

  var path = require('path')
    , reIsLocal = /^\.{0,2}\//
    , getScript = require('./get-script').getScript
    , getRequires = require('./get-requires').getRequires
    ;

  function getModuleLeaf(pkg, prev, requireString, callback) {
    var paths
      , modulepath = ''
      , leaf = {}
      ;

    function onShownLocalDeps(err, leaf) {
      //modulepath = path.normalize(pkg.name + '/' + modulepath);

      //leaf.pathname = leaf.pathname || '.';
      leaf.require = requireString;
      leaf.modulepath = modulepath;
      leaf.name = leaf.modulepath;
      leaf.package = pkg.name;
      leaf.requires = getRequires(leaf.scriptSource || '');

      callback(null, pkg, prev, leaf);
    }

    function onReadLocalDeps(err, dir, name, src) {
      if (err) {
        leaf.error = err;
      } else {
        leaf.scriptSource = src;
        leaf.pathname = path.normalize(dir);
        leaf.filename = name;
      }

      onShownLocalDeps(null, leaf);
    }

    // handle the case that this is main
    if (null === prev || !requireString || pkg.name === requireString) {

      // TODO have one, universal way of distiguishing as main
      modulepath = pkg.name;
      getScript(pkg, pkg.main, onReadLocalDeps);

    } else if (reIsLocal.exec(requireString)) {

      // resolve the filepath to a modulepath
      leaf.filepath = path.normalize(prev.pathname + '/' + requireString);

      // TODO be a little more robust with lib removal
      // lib/blah -> blah
      // XXX hilib/blah -> hiblah
      // XXX lib/ -> (assume pkg.name)
      modulepath = pkg.name + '/' + leaf.filepath.replace(path.normalize(pkg.lib) + '/', '');

      getScript(pkg, leaf.filepath, onReadLocalDeps);

    } else if (pkg.name === requireString.split('/')[0]) {

      // resolve to a filepath
      paths = requireString.split('/');
      paths[0] = pkg.lib;
      getScript(pkg, paths.join('/'), onReadLocalDeps);
      modulepath = requireString;

    } else {

      // check for this package in npm
      modulepath = requireString.split('/')[0];
      callback(null, pkg, prev, {
          name: modulepath
        , require: requireString
        , modulepath: modulepath
      });

    }
  }

  module.exports.getModuleLeaf = getModuleLeaf;
}());
<commit_msg>Fixed regex for rewriting requires based on the package lib<commit_after>(function () {
  "use strict";

  var path = require('path')
    , reIsLocal = /^\.{0,2}\//
    , getScript = require('./get-script').getScript
    , getRequires = require('./get-requires').getRequires
    ;

  var escapeRegExpPattern = /[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g
    ;

  function escapeRegExp(str) {
    return str.replace(escapeRegExpPattern, "\\$&");
  }

  function getModuleLeaf(pkg, prev, requireString, callback) {
    var paths
      , modulepath = ''
      , leaf = {}
      , tmpVar
      , regex
      ;

    function onShownLocalDeps(err, leaf) {
      //modulepath = path.normalize(pkg.name + '/' + modulepath);

      //leaf.pathname = leaf.pathname || '.';
      leaf.require = requireString;
      leaf.modulepath = modulepath;
      leaf.name = leaf.modulepath;
      leaf.package = pkg.name;
      leaf.requires = getRequires(leaf.scriptSource || '');

      callback(null, pkg, prev, leaf);
    }

    function onReadLocalDeps(err, dir, name, src) {
      if (err) {
        leaf.error = err;
      } else {
        leaf.scriptSource = src;
        leaf.pathname = path.normalize(dir);
        leaf.filename = name;
      }

      onShownLocalDeps(null, leaf);
    }

    // handle the case that this is main
    if (null === prev || !requireString || pkg.name === requireString) {

      // TODO have one, universal way of distiguishing as main
      modulepath = pkg.name;
      getScript(pkg, pkg.main, onReadLocalDeps);

    } else if (reIsLocal.exec(requireString)) {

      // resolve the filepath to a modulepath
      leaf.filepath = path.normalize(prev.pathname + '/' + requireString);

      tmpVar = path.normalize(pkg.moduleRoot + '/' + leaf.filepath).substring(0, pkg.moduleRoot.length);
      if (tmpVar === pkg.moduleRoot) {
          regex = new RegExp('(^|\/)' + escapeRegExp(path.normalize(pkg.lib) + '/'));
          modulepath = pkg.name + '/' + leaf.filepath.replace(regex, function ($) {return $[0];});
      } else {
          modulepath = pkg.name + '/' + leaf.filepath;
      }

      getScript(pkg, leaf.filepath, onReadLocalDeps);

    } else if (pkg.name === requireString.split('/')[0]) {

      // resolve to a filepath
      paths = requireString.split('/');
      paths[0] = pkg.lib;
      getScript(pkg, paths.join('/'), onReadLocalDeps);
      modulepath = requireString;

    } else {

      // check for this package in npm
      modulepath = requireString.split('/')[0];
      callback(null, pkg, prev, {
          name: modulepath
        , require: requireString
        , modulepath: modulepath
      });

    }
  }

  module.exports.getModuleLeaf = getModuleLeaf;
}());
<|endoftext|>


<commit_before>/*******************************************************************************
 * Copyright (c) 2016 IBM Corp.
 *
 * Licensed 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
 *
 * 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.
 *******************************************************************************/
whisk = {
	'async' : function() {
		console.log("Called async");
	},
	'done' : function(output) {
		console.log("Called done " + JSON.stringify(output));
	}
}

var fs = require("fs")
var vm = require('vm')
eval(fs.readFileSync(__dirname + '/checkSite.js') + '');
var basement = {
	"id" : "df99a72468db3c9b03f5c85f05000f3a",
	"name" : "Basement",
	"connectionLocation" : "ws://127.0.0.1:9080/rooms/ws/Basement",
	"connectionType" : "websocket"
};
var recRoom = {
	"id" : "df99a72468db3c9b03f5c85f05001d29",
	"name" : "RecRoom",
	"connectionLocation" : "ws://127.0.0.1:9080/rooms/ws/RecRoom",
	"connectionType" : "websocket",
	"connectionSecret" : "kayleigh"
};
var mugRoom = {
	"id" : "df99a72468db3c9b03f5c85f05003699",
	"name" : "MugRoom",
	"connectionLocation" : "ws://127.0.0.1:9080/rooms/ws/MugRoom",
	"connectionType" : "websocket"
};
//console.log('Calling main for basement');
//main(basement);
console.log('Calling main for rec room');
main(recRoom);
//console.log('Calling main for mug room');
//main(recRoom);<commit_msg>Run tests on all standard rooms<commit_after>/*******************************************************************************
 * Copyright (c) 2016 IBM Corp.
 *
 * Licensed 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
 *
 * 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.
 *******************************************************************************/
var doneCalled = false;
whisk = {
	'async' : function() {
		console.log("Called async");
	},
	'done' : function(output) {
		console.log("Called done " + JSON.stringify(output));
		doneCalled = true;
	}
}

var fs = require("fs")
var vm = require('vm')
eval(fs.readFileSync(__dirname + '/checkSite.js') + '');
var basement = {
	"id" : "df99a72468db3c9b03f5c85f05000f3a",
	"name" : "Basement",
	"connectionLocation" : "ws://127.0.0.1:9080/rooms/ws/Basement",
	"connectionType" : "websocket"
};
var recRoom = {
	"id" : "df99a72468db3c9b03f5c85f05001d29",
	"name" : "RecRoom",
	"connectionLocation" : "ws://127.0.0.1:9080/rooms/ws/RecRoom",
	"connectionType" : "websocket",
	"connectionSecret" : "kayleigh"
};
var mugRoom = {
	"id" : "df99a72468db3c9b03f5c85f05003699",
	"name" : "MugRoom",
	"connectionLocation" : "ws://127.0.0.1:9080/rooms/ws/MugRoom",
	"connectionType" : "websocket"
};
var createTimerFunctionToWaitBeforeCheckingRoom = function(rooms) {
    setTimeout(function() {
        if (doneCalled) {
            if (rooms.length > 0) {
                var room = rooms.pop();
                console.log('Calling main for room ' + room.name);
                doneCalled = false;
                main(room);
                createTimerFunctionToWaitBeforeCheckingRoom(rooms);
            }
        } else {
            createTimerFunctionToWaitBeforeCheckingRoom(rooms);
        }
    }, 1000);
}

main(basement);
createTimerFunctionToWaitBeforeCheckingRoom([recRoom, mugRoom]);

<|endoftext|>


<commit_before>var ogr2ogr = require('ogr2ogr');

function downloadDataset(req, res) {
    var layerName = req.ogr2ogr.layerName;
    var options = layerName ? [layerName] : [];

    var ogrstream = ogr2ogr(req.ogr2ogr.src)
        .timeout(60000);

    // Projection
    if (req.query.projection === 'WGS84') {
        ogrstream.project('EPSG:4326');
    } else if (req.query.projection === 'Lambert93') {
        ogrstream.project('EPSG:2154');
    } else {
        return res.status(400).send({
            code: 400,
            message: 'No valid projection given'
        });
    }

    var fileName = req.ogr2ogr.fileName || layerName || 'dataset';

    // Format
    if (req.query.format === 'GeoJSON') {
        res.type('json');
        res.attachment(fileName + '.json');
        options.push('-explodecollections');
    } else if (req.query.format === 'KML') {
        res.type('application/vnd.google-earth.kml+xml');
        res.attachment(fileName + '.kml');
        ogrstream.format('KML');
        options.push('-explodecollections');
    } else if (req.query.format === 'SHP') {
        res.type('application/x-shapefile');
        res.attachment(fileName + '.zip');
        ogrstream.format('ESRI Shapefile');
    } else if (req.query.format === 'CSV') {
        res.type('text/csv');
        res.attachment(fileName + '.csv');
        ogrstream.format('CSV');
    } else {
        return res.status(400).send({
            code: 400,
            message: 'No valid format given'
        });
    }

    if (req.method === 'HEAD') {
        res.status(200).end();
    } else {
        ogrstream.options(options).stream().pipe(res);
    }
}

exports.downloadDataset = downloadDataset;
<commit_msg>Handle ogr2ogr errors<commit_after>var ogr2ogr = require('ogr2ogr');

function downloadDataset(req, res) {
    var layerName = req.ogr2ogr.layerName;
    var options = layerName ? [layerName] : [];

    var ogr2ogrTask = ogr2ogr(req.ogr2ogr.src)
        .timeout(60000);

    // Projection
    if (req.query.projection === 'WGS84') {
        ogr2ogrTask.project('EPSG:4326');
    } else if (req.query.projection === 'Lambert93') {
        ogr2ogrTask.project('EPSG:2154');
    } else {
        return res.status(400).send({
            code: 400,
            message: 'No valid projection given'
        });
    }

    var fileName = req.ogr2ogr.fileName || layerName || 'dataset';

    // Format
    if (req.query.format === 'GeoJSON') {
        res.type('json');
        res.attachment(fileName + '.json');
        options.push('-explodecollections');
    } else if (req.query.format === 'KML') {
        res.type('application/vnd.google-earth.kml+xml');
        res.attachment(fileName + '.kml');
        ogr2ogrTask.format('KML');
        options.push('-explodecollections');
    } else if (req.query.format === 'SHP') {
        res.type('application/x-shapefile');
        res.attachment(fileName + '.zip');
        ogr2ogrTask.format('ESRI Shapefile');
    } else if (req.query.format === 'CSV') {
        res.type('text/csv');
        res.attachment(fileName + '.csv');
        ogr2ogrTask.format('CSV');
    } else {
        return res.status(400).send({
            code: 400,
            message: 'No valid format given'
        });
    }

    if (req.method === 'HEAD') {
        res.status(200).end();
    } else {
        var ogrStream = ogr2ogrTask.options(options).stream();

        ogrStream.on('error', function (err) {
            console.error(err);
        });

        ogrStream.pipe(res);
    }
}

exports.downloadDataset = downloadDataset;
<|endoftext|>


<commit_before>const assert = require('assert');
const querystring = require('querystring');
const http = require('http');
const https = require('https');
const { once } = require('events');

const LRU = require('lru-cache');

const pkg = require('../../package.json');
const { RPError } = require('../errors');

const pick = require('./pick');
const { deep: defaultsDeep } = require('./defaults');
const { HTTP_OPTIONS } = require('./consts');

let DEFAULT_HTTP_OPTIONS;
const NQCHAR = /^[\x21\x23-\x5B\x5D-\x7E]+$/;

const allowed = [
  'agent',
  'ca',
  'cert',
  'crl',
  'headers',
  'key',
  'lookup',
  'passphrase',
  'pfx',
  'timeout',
];

const setDefaults = (props, options) => {
  DEFAULT_HTTP_OPTIONS = defaultsDeep(
    {},
    props.length ? pick(options, ...props) : options,
    DEFAULT_HTTP_OPTIONS,
  );
};

setDefaults([], {
  headers: { 'User-Agent': `${pkg.name}/${pkg.version} (${pkg.homepage})` },
  timeout: 3500,
});

function send(req, body, contentType) {
  if (contentType) {
    req.removeHeader('content-type');
    req.setHeader('content-type', contentType);
  }
  if (body) {
    req.removeHeader('content-length');
    req.setHeader('content-length', Buffer.byteLength(body));
    req.write(body);
  }
  req.end();
}

const nonces = new LRU({ max: 100 });

module.exports = async function request(options, { accessToken, mTLS = false, DPoP } = {}) {
  let url;
  try {
    url = new URL(options.url);
    delete options.url;
    assert(/^(https?:)$/.test(url.protocol));
  } catch (err) {
    throw new TypeError('only valid absolute URLs can be requested');
  }
  const optsFn = this[HTTP_OPTIONS];
  let opts = options;

  const nonceKey = `${url.origin}${url.pathname}`;
  if (DPoP && 'dpopProof' in this) {
    opts.headers = opts.headers || {};
    opts.headers.DPoP = await this.dpopProof(
      {
        htu: url.href,
        htm: options.method,
        nonce: nonces.get(nonceKey),
      },
      DPoP,
      accessToken,
    );
  }

  let userOptions;
  if (optsFn) {
    userOptions = pick(
      optsFn.call(this, url, defaultsDeep({}, opts, DEFAULT_HTTP_OPTIONS)),
      ...allowed,
    );
  }
  opts = defaultsDeep({}, userOptions, opts, DEFAULT_HTTP_OPTIONS);

  if (mTLS && !opts.pfx && !(opts.key && opts.cert)) {
    throw new TypeError('mutual-TLS certificate and key not set');
  }

  if (opts.searchParams) {
    for (const [key, value] of Object.entries(opts.searchParams)) {
      url.searchParams.delete(key);
      url.searchParams.set(key, value);
    }
  }

  let responseType;
  let form;
  let json;
  let body;
  ({ form, responseType, json, body, ...opts } = opts);

  for (const [key, value] of Object.entries(opts.headers || {})) {
    if (value === undefined) {
      delete opts.headers[key];
    }
  }

  let response;
  const req = (url.protocol === 'https:' ? https.request : http.request)(url, opts);
  return (async () => {
    if (json) {
      send(req, JSON.stringify(json), 'application/json');
    } else if (form) {
      send(req, querystring.stringify(form), 'application/x-www-form-urlencoded');
    } else if (body) {
      send(req, body);
    } else {
      send(req);
    }

    [response] = await Promise.race([once(req, 'response'), once(req, 'timeout')]);

    // timeout reached
    if (!response) {
      req.destroy();
      throw new RPError(`outgoing request timed out after ${opts.timeout}ms`);
    }

    const parts = [];

    for await (const part of response) {
      parts.push(part);
    }

    if (parts.length) {
      switch (responseType) {
        case 'json': {
          Object.defineProperty(response, 'body', {
            get() {
              let value = Buffer.concat(parts);
              try {
                value = JSON.parse(value);
              } catch (err) {
                Object.defineProperty(err, 'response', { value: response });
                throw err;
              } finally {
                Object.defineProperty(response, 'body', { value, configurable: true });
              }
              return value;
            },
            configurable: true,
          });
          break;
        }
        case undefined:
        case 'buffer': {
          Object.defineProperty(response, 'body', {
            get() {
              const value = Buffer.concat(parts);
              Object.defineProperty(response, 'body', { value, configurable: true });
              return value;
            },
            configurable: true,
          });
          break;
        }
        default:
          throw new TypeError('unsupported responseType request option');
      }
    }

    return response;
  })()
    .catch((err) => {
      if (response) Object.defineProperty(err, 'response', { value: response });
      throw err;
    })
    .finally(() => {
      const dpopNonce = response && response.headers['dpop-nonce'];
      if (dpopNonce && NQCHAR.test(dpopNonce)) {
        nonces.set(nonceKey, dpopNonce);
      }
    });
};

module.exports.setDefaults = setDefaults.bind(undefined, allowed);
<commit_msg>fix(dpop): htu without querystring<commit_after>const assert = require('assert');
const querystring = require('querystring');
const http = require('http');
const https = require('https');
const { once } = require('events');

const LRU = require('lru-cache');

const pkg = require('../../package.json');
const { RPError } = require('../errors');

const pick = require('./pick');
const { deep: defaultsDeep } = require('./defaults');
const { HTTP_OPTIONS } = require('./consts');

let DEFAULT_HTTP_OPTIONS;
const NQCHAR = /^[\x21\x23-\x5B\x5D-\x7E]+$/;

const allowed = [
  'agent',
  'ca',
  'cert',
  'crl',
  'headers',
  'key',
  'lookup',
  'passphrase',
  'pfx',
  'timeout',
];

const setDefaults = (props, options) => {
  DEFAULT_HTTP_OPTIONS = defaultsDeep(
    {},
    props.length ? pick(options, ...props) : options,
    DEFAULT_HTTP_OPTIONS,
  );
};

setDefaults([], {
  headers: { 'User-Agent': `${pkg.name}/${pkg.version} (${pkg.homepage})` },
  timeout: 3500,
});

function send(req, body, contentType) {
  if (contentType) {
    req.removeHeader('content-type');
    req.setHeader('content-type', contentType);
  }
  if (body) {
    req.removeHeader('content-length');
    req.setHeader('content-length', Buffer.byteLength(body));
    req.write(body);
  }
  req.end();
}

const nonces = new LRU({ max: 100 });

module.exports = async function request(options, { accessToken, mTLS = false, DPoP } = {}) {
  let url;
  try {
    url = new URL(options.url);
    delete options.url;
    assert(/^(https?:)$/.test(url.protocol));
  } catch (err) {
    throw new TypeError('only valid absolute URLs can be requested');
  }
  const optsFn = this[HTTP_OPTIONS];
  let opts = options;

  const nonceKey = `${url.origin}${url.pathname}`;
  if (DPoP && 'dpopProof' in this) {
    opts.headers = opts.headers || {};
    opts.headers.DPoP = await this.dpopProof(
      {
        htu: `${url.origin}${url.pathname}`,
        htm: options.method,
        nonce: nonces.get(nonceKey),
      },
      DPoP,
      accessToken,
    );
  }

  let userOptions;
  if (optsFn) {
    userOptions = pick(
      optsFn.call(this, url, defaultsDeep({}, opts, DEFAULT_HTTP_OPTIONS)),
      ...allowed,
    );
  }
  opts = defaultsDeep({}, userOptions, opts, DEFAULT_HTTP_OPTIONS);

  if (mTLS && !opts.pfx && !(opts.key && opts.cert)) {
    throw new TypeError('mutual-TLS certificate and key not set');
  }

  if (opts.searchParams) {
    for (const [key, value] of Object.entries(opts.searchParams)) {
      url.searchParams.delete(key);
      url.searchParams.set(key, value);
    }
  }

  let responseType;
  let form;
  let json;
  let body;
  ({ form, responseType, json, body, ...opts } = opts);

  for (const [key, value] of Object.entries(opts.headers || {})) {
    if (value === undefined) {
      delete opts.headers[key];
    }
  }

  let response;
  const req = (url.protocol === 'https:' ? https.request : http.request)(url, opts);
  return (async () => {
    if (json) {
      send(req, JSON.stringify(json), 'application/json');
    } else if (form) {
      send(req, querystring.stringify(form), 'application/x-www-form-urlencoded');
    } else if (body) {
      send(req, body);
    } else {
      send(req);
    }

    [response] = await Promise.race([once(req, 'response'), once(req, 'timeout')]);

    // timeout reached
    if (!response) {
      req.destroy();
      throw new RPError(`outgoing request timed out after ${opts.timeout}ms`);
    }

    const parts = [];

    for await (const part of response) {
      parts.push(part);
    }

    if (parts.length) {
      switch (responseType) {
        case 'json': {
          Object.defineProperty(response, 'body', {
            get() {
              let value = Buffer.concat(parts);
              try {
                value = JSON.parse(value);
              } catch (err) {
                Object.defineProperty(err, 'response', { value: response });
                throw err;
              } finally {
                Object.defineProperty(response, 'body', { value, configurable: true });
              }
              return value;
            },
            configurable: true,
          });
          break;
        }
        case undefined:
        case 'buffer': {
          Object.defineProperty(response, 'body', {
            get() {
              const value = Buffer.concat(parts);
              Object.defineProperty(response, 'body', { value, configurable: true });
              return value;
            },
            configurable: true,
          });
          break;
        }
        default:
          throw new TypeError('unsupported responseType request option');
      }
    }

    return response;
  })()
    .catch((err) => {
      if (response) Object.defineProperty(err, 'response', { value: response });
      throw err;
    })
    .finally(() => {
      const dpopNonce = response && response.headers['dpop-nonce'];
      if (dpopNonce && NQCHAR.test(dpopNonce)) {
        nonces.set(nonceKey, dpopNonce);
      }
    });
};

module.exports.setDefaults = setDefaults.bind(undefined, allowed);
<|endoftext|>


<commit_before>var sha1 = require('./sha1')

function wrap(/* thingToWrap, argsToWrappedFn..., wrapperFn*/) {
	var last  = arguments.length - 1,
	    modul = arguments[ last ]
	    me    = arguments[ last - 1 ],
			fn 	  = arguments[0],
			args  = [ ]

  // If we get a profiler function passed in, return it.
  // We don't end up with functions wrapped with 20 profilers
  var str   = me.toString(),
      start = str.indexOf('{')

	if (sha1.hash(str.substring(start)) === '9ad7c8cfe951569ee2466592513ffad1aa682c35')
	  return me

	for (var i = 1; i < last; i++)
		args.push(arguments[i])

	args.push(modul)

	return doWrap(me, fn, args)
}

function doWrap(me, fn, args) {
  var buffer;

	if (me instanceof Function)
	  if (me.name.search(/[A-Z]/) < 0 || me.name.search(/[A-Z]/) > 0) {
  	  buffer = wrapItem(me, fn, args)
    } else {
      buffer = me
    }
  else
    buffer = me

	iterateAndWrap(buffer, me, fn, args)

	return buffer
}

function iterateAndWrap(ctx, me, fn, args) {
  for (var p in me) {
    var last = args.pop()

    last.methd = p

    args.push(last)

		ctx[p] = wrapItem(me[p], fn, args)
	}
}

function wrapItem(i, fn, args, module) {
  args.unshift(i)

  return i instanceof Function ? fn.apply(null, args) : i
}

function alreadyExists(me) {
  return wrapped[hashes.create(me)] !== undefined
}

module.exports = wrap<commit_msg>Functions assigned as properties of prototypes are now being instrumented (or wrapped)<commit_after>var sha1 = require('./sha1')

function wrap(/* thingToWrap, argsToWrappedFn..., wrapperFn*/) {
	var last  = arguments.length - 1,
	    modul = arguments[ last ]
	    me    = arguments[ last - 1 ],
			fn 	  = arguments[0],
			args  = [ ]

  // If we get a profiler function passed in, return it.
  // We don't end up with functions wrapped with 20 profilers
  var str   = me.toString(),
      start = str.indexOf('{')

	if (sha1.hash(str.substring(start)) === '9ad7c8cfe951569ee2466592513ffad1aa682c35')
	  return me

	for (var i = 1; i < last; i++)
		args.push(arguments[i])

	args.push(modul)

	var you = doWrap(me, fn, args)

	iterateAndWrap(you.prototype, me.prototype, fn, args)

	return you
}

function doWrap(me, fn, args) {
  var buffer;

	if (me instanceof Function)
	  if (me.name.search(/[A-Z]/) < 0 || me.name.search(/[A-Z]/) > 0) {
  	  buffer = wrapItem(me, fn, args)
    } else {
      buffer = me
    }
  else
    buffer = me

	iterateAndWrap(buffer, me, fn, args)

	return buffer
}

function iterateAndWrap(ctx, me, fn, args) {
  for (var p in me) {
    var last = args.pop()

    last.methd = p

    args.push(last)

		ctx[p] = wrapItem(me[p], fn, args)
	}
}

function wrapItem(i, fn, args, module) {
  args.unshift(i)

  return i instanceof Function ? fn.apply(null, args) : i
}

function alreadyExists(me) {
  return wrapped[hashes.create(me)] !== undefined
}

module.exports = wrap<|endoftext|>