<commit_before>define(["dojo/_base/declare", "dojo/_base/lang", "./List", "dojo/dnd/Source", "xstyle/put", "dojo/on", "xstyle/css!dojo/resources/dnd.css"], function(declare, lang, List, DnDSource, put, on){
	function setupDnD(grid){
		if(grid.dndTarget){
			return;
		}
		var store = grid.store;
		// make the contents a DnD source/target
		var targetSource = grid.dndTarget = new DnDSource(grid.bodyNode,
			lang.delegate(grid.dndTargetConfig, {dropParent: grid.contentNode}));
		targetSource.getObject = function(node){
			var row = grid.row(node);
			return store.get(row.id);
		}
		targetSource.onDrop = function(sourceSource, nodes){
			// on drop, move get the objects and move them
			var targetRow = targetSource.targetAnchor && grid.row(targetSource.targetAnchor);
			dojo.when(targetRow && store.get(targetRow.id), function(target){
				nodes.forEach(function(node){
					dojo.when(sourceSource.getObject(node), function(object){
						store.put(object, {before: target});
					});
				});
			});
		};
	}
	return declare([List], {
		dndSourceType: "row",
		dndTargetConfig: {
			accept: ["row"],
			creator: function(){
				// this is used to create the content under the avatar. Not sure what we really want here
				return {
					node: put("div"),
					data: {},
					type: []
				};
			}
		},
		postCreate: function(){
			this.inherited(arguments);
			setupDnD(this);
		},
		insertRow: function(object){
			// override to add dojoDndItem class to make the rows draggable
			var row = this.inherited(arguments);
			put(row, '.dojoDndItem');
			// setup the source if it hasn't been done yet
			setupDnD(this);
			this.dndTarget.setItem(row.id, {data: object, type: [this.dndSourceType]});
			return row;
		}
	});
});
<commit_msg>Flesh out default DnD logic; put content back in avatar<commit_after>define(["dojo/_base/declare", "dojo/_base/lang", "./List", "dojo/dnd/Source", "dojo/dnd/Manager", "xstyle/put", "dojo/on", "xstyle/css!dojo/resources/dnd.css"], function(declare, lang, List, DnDSource, DnDManager, put, on){
	// TODOC: store requirements
	// * requires a store (sounds obvious, but not all Lists/Grids have stores...)
	// * must support options.before in put calls
	//   (if undefined, put at end)
	// * should support copy
	//   (copy should also support options.before as above)
	function setupDnD(grid){
		if(grid.dndTarget){
			return;
		}
		var store = grid.store;
		// make the contents a DnD source/target
		var targetSource = grid.dndTarget = new DnDSource(grid.bodyNode,
			lang.delegate(grid.dndTargetConfig, {dropParent: grid.contentNode}));
		// getObject is a method which should be defined on any source intending
		// on interfacing with dgrid DnD
		targetSource.getObject = function(node){
			var row = grid.row(node);
			return store.get(row.id);
		}
		// add cross-reference to grid for potential use in inter-grid drop logic
		targetSource.grid = grid;
		targetSource.onDrop = function(sourceSource, nodes, copy){
			// on drop, determine where to move/copy the objects
			var targetRow = targetSource.targetAnchor;
			if(!this.before && targetRow){
				// target before next node if dropped within bottom half of this node
				// (unless there's no node to target at all)
				targetRow = targetRow.nextSibling;
			}
			targetRow = targetRow && grid.row(targetRow);

			dojo.when(targetRow && store.get(targetRow.id), function(target){
				// Note: if dropping after the last row, or into an empty grid,
				// target will be undefined.  Thus, it is important for store to place
				// item last in order if options.before is undefined.

				// Delegate to onDropInternal or onDropExternal for rest of logic.
				// These are passed the target item as an additional argument.
				if(targetSource != sourceSource){
					targetSource.onDropExternal(sourceSource, nodes, copy, target);
				}else{
					targetSource.onDropInternal(nodes, copy, target);
				}
			});
		};
		targetSource.onDropInternal = function(nodes, copy, targetItem){
			nodes.forEach(function(node){
				dojo.when(targetSource.getObject(node), function(object){
					// For copy DnD operations, copy object, if supported by store;
					// otherwise settle for put anyway.
					// (put will relocate an existing item with the same id, i.e. move).
					store[copy && store.copy ? "copy" : "put"](object, {
						before: targetItem
					});
				});
			});
		};
		targetSource.onDropExternal = function(sourceSource, nodes, copy, targetItem){
			// Note: this default implementation expects that two grids do not
			// share the same store.  There may be more ideal implementations in the
			// case of two grids using the same store (perhaps differentiated by
			// query), dragging to each other.
			var sourceGrid = sourceSource.grid;
			// TODO: bail out if sourceSource.getObject isn't defined?
			// (also might want to implement default checkAcceptance for this)
			nodes.forEach(function(node){
				dojo.when(sourceSource.getObject(node), function(object){
					if(!copy){
						if(sourceGrid){
							// Remove original in the case of inter-grid move.
							dojo.when(sourceGrid.store.getIdentity(object), function(id){
								sourceGrid.store.remove(id);
							});
						}else{
							// TODO: delItem from sourceSource?
							// Potentially implement above as delItem on grid sources,
							// then merge these two branches?
							// (problem: delItem doesn't update DOM on dojo.dnd.Sources...)
						}
					}
					// Copy object, if supported by store; otherwise settle for put
					// (put will relocate an existing item with the same id).
					// Note that we use store.copy if available even for non-copy dnd:
					// since this coming from another dnd source, always behave as if
					// it is a new store item if possible, rather than replacing existing.
					store[store.copy ? "copy" : "put"](object, {
						before: targetItem
					});
				});
			});
		};
		// listen for start events to apply style change to avatar
		targetSource.onDndStart = function(source, nodes, copy){
			DnDSource.prototype.onDndStart.apply(this, arguments);
			if(source == this){
				// Set avatar width to half the grid's width.
				// Kind of a naive default, but prevents ridiculously wide avatars.
				DnDManager.manager().avatar.node.style.width =
					grid.domNode.offsetWidth / 2 + "px";
			}
		};
		// augment checkAcceptance to block drops from sources without getObject
		targetSource.checkAcceptance = function(source, nodes){
			return source.getObject &&
				DnDSource.prototype.checkAcceptance.apply(this, arguments);
		};
		// TODO: could potentially also implement copyState to jive with default
		// onDrop* implementations (checking whether store.copy is available);
		// not doing that just yet until we're sure about default impl.
	}
	return declare([List], {
		dndSourceType: "row",
		dndTargetConfig: {
			accept: ["row"]
		},
		postCreate: function(){
			this.inherited(arguments);
			setupDnD(this);
		},
		insertRow: function(object){
			// override to add dojoDndItem class to make the rows draggable
			var row = this.inherited(arguments);
			put(row, '.dojoDndItem');
			// setup the source if it hasn't been done yet
			setupDnD(this);
			this.dndTarget.setItem(row.id, {data: object, type: [this.dndSourceType]});
			return row;
		}
	});
});
<|endoftext|>


<commit_before>var EYT = { // Functions Object.
    d: document,

    // Page scroll function.
    scroll: function (i, wrpr) {
        "use strict";
        var html = EYT.d.querySelectorAll("html")[0],
            b_ody = EYT.d.body,
            b_od = b_ody.getBoundingClientRect(),
            e_lm,
            top;

        if (!isNaN(i) && wrpr) {
            e_lm = wrpr[i].getBoundingClientRect();
            top = e_lm.top - b_od.top;
        } else {
            top = 0;
        }
        html.scrollTop = top;
        b_ody.scrollTop = top;
    },

    // Main functions here.
    init: function (container, object, dimensions, HF) {
        "use strict";
        var videos = object, // The video object input.
            ids = Object.keys(videos),
            aspect_ratio = dimensions.aspectRatio,
            header_content = HF.header || "
HULK
",
            footer_content = HF.footer || "
FOOTEY
",

            // ========================================================
            // YouTube
            url_base = "https://youtu.be/", // Short YT URL base link.
            url_embed_base = "https://www.youtube.com/embed/", // YT embed URL base
            url_image_base = "https://i.ytimg.com/vi/", // YT image URL base (front)
            url_image_base_end = "/0.jpg", // YT image URL base (back)
            // ========================================================

            iframes,
            btn_on,
            btn_off,
            wrpr,
            array = [],
            yt_url,
            ctnr = EYT.d.getElementById(container), // Container element.
            timmy_outer,
            UA = navigator.userAgent,

            // ========================================
            // CONTENT (iframe, buttons, and textarea).
            half_0 = '
' +
                        '
',
            half_1 = '
' +
                        '' +
                            '
' +
                                '
' +
                                    '<button type="button" class="player_on">PLAY</button>' +
                                    '<button type="button" class="player_off" disabled="1">' +
                                    'CLEAR</button>' +
                                    '<textarea style="display:none; opacity:0" ' +
                                        'rows="1" readonly="readonly" ' +
                                        'wrap="off" title="YouTube URL" ' +
                                        'onclick="this.select()" class="yt_url"></textarea>' +
                                '
' +
                            '
' +
                        '
',
            // ========================================

            // Nodelist to Array (function).
            t_a = function (a) {
                if (EYT.d.querySelectorAll(a).length > 0) {
                    return Array.prototype.slice.call(EYT.d.querySelectorAll(a));
                }
            },

            // Video *PLAY* (function).
            player_on = function (v, i) {
                iframes[i].src = url_embed_base +
                                    videos[ids[i]] +
                                    "?wmode=transparent" +
                                    "&modestbranding=1" +
                                    "&rel=0" +
                                    "&showinfo=0" +
                                    "&fs=0" +
                                    "&autoplay=1";
                /* ======================================================== |
                |   To learn the embedded YT player PARAMETERS, go to:      |
                |       developers.google.com/youtube/player_parameters     |
                | ======================================================== */

                iframes[i].style.backgroundImage = "";
                iframes[i].style.opacity = 1;

                wrpr[i].style.background = "#000";
                wrpr[i].style.color = "#fff";

                v.disabled = 1;

                if (timmy_outer) {
                    window.clearTimeout(timmy_outer);
                }

                btn_on.forEach(function (v, ii) {
                    if (ii !== i) {
                        v.disabled = 1;
                    }
                });
            },

            // Video *CLEAR* (function).
            player_off = function (v, i, enable_btn_off) {
                var interval,
                    counter = 0,
                    limit,
                    check_btn = function () {
                        counter += 1;

                        limit = UA.match(/firefox/gi)
                            ? 25
                            : 6;

                        if (counter < limit) {
                            if (!v.disabled) {
                                v.disabled = 1;
                            }

                            // ========================================================
                            // These get buggy on Firefox, therefore I re-declare them.
                            // The removing *EventListener* part.
                            if (iframes.src) { // Making sure.
                                iframes[i].src = "";
                            }
                            // Making sure.
                            iframes[i].removeEventListener("load", enable_btn_off, 0);
                            iframes[i].removeEventListener("error", enable_btn_off, 0);
                            // ========================================================

                            if (!iframes[i].style.backgroundImage) {
                                iframes[i].style
                                    .backgroundImage = "url(" +
                                                        url_image_base +
                                                        videos[ids[i]] +
                                                        url_image_base_end +
                                                        ")";
                            }

                            if (yt_url[i].style.opacity === 1) {
                                yt_url[i].style.opacity = 0;
                            }

                            if (yt_url[i].style.display === "block") {
                                yt_url[i].style.display = "none";
                            }

                            if (!UA.match(/firefox/gi)) {
                                if (wrpr[i].style.background && wrpr[i].style.color) {
                                    wrpr[i].style.background = "";
                                    wrpr[i].style.color = "";
                                }
                            }
                        } else {
                            if (UA.match(/firefox/gi)) {
                                if (iframes[i].style.opacity === 1) {
                                    iframes[i].style.opacity = 0.5;
                                }

                                if (wrpr[i].style.background && wrpr[i].style.color) {
                                    wrpr[i].style.background = "";
                                    wrpr[i].style.color = "";
                                }

                                if (btn_on[i].disabled) {
                                    btn_on.forEach(function (v) {
                                        v.disabled = 0;
                                    });
                                }
                            }
                            if (btn_on[i].disabled) {
                                btn_on.forEach(function (v) {
                                    v.disabled = 0;
                                });
                            }
                            window.clearInterval(interval);
                        }
                    };

                iframes[i].src = "";
                iframes[i].removeEventListener("load", enable_btn_off, 0);
                iframes[i].removeEventListener("error", enable_btn_off, 0);
                iframes[i].style.opacity = 0.5;

                // Forcing button thing.
                interval = window.setInterval(check_btn, 100);
            },

            // Button click handler (function).
            clck = function (v, i) {
                var enable_btn_off = function () {
                    yt_url[i].style.display = "block";

                    timmy_outer = window.setTimeout(function () {
                        yt_url[i].style.opacity = 1;
                    }, 500);

                    btn_off[i].disabled = 0;
                };

                EYT.scroll(i, wrpr); // Page scroll.

                if (v.className === "player_on") { // *PLAY*.
                    iframes[i].addEventListener("load", enable_btn_off, 0);
                    iframes[i].addEventListener("error", enable_btn_off, 0);

                    player_on(v, i); // Go to *player_on* function.
                } else { // *CLEAR*.
                    player_off(v, i, enable_btn_off); // Go to *player_off* function.
                }
            },

            // Responsive iframes (function).
            rv = {
                w: window,
                css: function (a) {
                    return rv.w.getComputedStyle(a, null);
                },
                re_size: function (a) {
                    var all_properties,
                        height,
                        width,
                        default_height = dimensions.height + "px",
                        default_width = dimensions.width + "px",
                        window_width = rv.w.innerWidth,
                        add_30px = a.src
                            ? 30
                            : 0;

                    if (window_width < dimensions.width) {
                        a.forEach(function (v) {
                            v.style.width = "100%";
                        });

                        all_properties = rv.css(a[0]);
                        width = parseInt(all_properties.getPropertyValue("width"), 10);

                        height = Math.floor(width * (aspect_ratio)) + add_30px;
                        // The extra 30px is for the player control,
                        // only when the iframe has non-empty source attribute.

                        a.forEach(function (v) {
                            v.style.height = height + "px";
                        });
                    } else {
                        a.forEach(function (v) {
                            v.style.cssText += "height:" + default_height +
                                                ";width:" + default_width;
                        });
                    }
                }
            };

        /*|============= |*|
        |*|  INJECTION.  |*|
        |*| ============ |*/
        // [1] Header content definition.
        array.push(header_content);

        // [2] Body content (titles, iframes, buttons, and URL links) definition.
        ids.forEach(function (v) {
            array.push(half_0 + v + half_1);
        });

        // [3] Footer content definition.
        array.push(footer_content);

        // [4] Inject Header-Body-Footer into the container element.
        ctnr.innerHTML = array.join("");

        // [5] Define iframes, buttons, wrappers, and YT url containers.
        iframes = t_a(".yt_embed");
        btn_on = t_a(".player_on");
        btn_off = t_a(".player_off");
        wrpr = t_a(".yt_embed_wrap");
        yt_url = t_a(".yt_url");

        // [6] Loop using *iframes* reference.
        // The length of all 5 variables defined above are the same.
        iframes.forEach(function (v, i) {
            btn_on[i].onclick = function () { // Button *PLAY* click handler.
                clck(btn_on[i], i);
            };

            btn_off[i].onclick = function () { // Button *CLEAR* click handler.
                clck(btn_off[i], i);
            };

            // Set initial *background-image* on iframes.
            v.style.backgroundImage = 'url(https://i.ytimg.com/vi/' + videos[ids[i]] + '/0.jpg)';

            // Set value to YouTube URL textareas.
            yt_url[i].value = url_base + videos[ids[i]];
        });

        // ==============================================
        // RESPONSIVE IFRAMES MODULE INVOCATION (*rv* variable).
        rv.re_size(iframes);
        rv.w.addEventListener("resize", function () {
            rv.re_size(iframes);
        });
    }
};

/*|=========================|**
**| INITIALIZE THE FUNCTION |**
**|=========================|*/
// #[I] Initialize the main function.
EYT.init(
    // ======================= //
    // List of input arguments //
    // ======================= //

     /*| #[I.1] The container element's ID |*/
    "yt_embed_container",

    /*| #[I.2] Object                   |**
    **|    {"title": "video ID"} pairs. |**
    **|    Put as many as you want.     |*/
    {
        "Expressions": "arJtsvv6akc",
        "Dancing Zoidberg along with Minuet (Luigi Boccherini)": "ikl3hGEfSLc",
        "Knock Knock Joke": "rLwDNwkJqjY",
        "Babba's tribute to mainstream music": "8DTgMZP6f8U"
    },

    /*| #[I.3] Default dimensions and aspect ratio |*/
    {
        /*| #[I.3.a] Dimensions in pixels |*/
        "height": 360,
        "width": 640,

        /*| #[I.3.b] Aspect ratio |*/
        "aspectRatio": 9/16

        // It can be 3/4, or 1/2, up to you.
        // The largest number is the width ratio.
        // Put the smallest value in front: *small_number/big_number*.

        // This feature will work on screen which has narrower width than you define above.
    },

    /*| #[1.4] HEADER and FOOTER CONTENT |*/
    // Customize the HEADER and FOOTER CSS from the [style] tag above.
    // Header class: .header
    // Footer class: .footer
    {
        "header": "
" +
                "Multiple YouTube Embedded Videos
" +
                "Without YouTube JS API
" +
                "" +
                "For mobile player (flv), the " +
                "autoplay parameter (currently) doesn't work" +
                "" +
                "
",

        "footer": "
" +
                "
Template by Monkey Raptor
" +
                "
See page source | See source on GitHub
" +
                "
Updated May 28, 2015
" +
                "
<button type='button' class='scroller' onclick='EYT.scroll()'>" +
                "TOP</button>
" +
                "
"
    }
);

// #[II] Initialize scrolling to the top of the page.
/*| ============================================== |*|
|*|   Scroll to the top of the page on DOM load.   |*|
|*| ============================================== |*/
EYT.scroll();

// These lines below can be omitted (demo purpose only).
/*| ========================== |*|
|*|   EXTRA FUNC:              |*|
|*|     - Check if in iframe.  |*|
|*| ========================== |*/
var extra = {
        in_iframe: function () { // stackoverflow.com/a/326076
            "use strict";
            try {
                return window.self !== window.top;
            } catch (e) {
                if (e) {
                    return 1;
                }
            }
        },
        rmv_node: function (a, b) {
            "use strict";
            a.removeChild(b);
        }
    },
    footer = document.querySelectorAll(".footer")[0],
    h3_elm = footer.childNodes[0],
    vsource_elm = footer.childNodes[1];

if (extra.in_iframe()) {
    extra.rmv_node(footer, h3_elm);
    extra.rmv_node(footer, vsource_elm);
}
<commit_msg>Line 298<commit_after>var EYT = { // Functions Object.
    d: document,

    // Page scroll function.
    scroll: function (i, wrpr) {
        "use strict";
        var html = EYT.d.querySelectorAll("html")[0],
            b_ody = EYT.d.body,
            b_od = b_ody.getBoundingClientRect(),
            e_lm,
            top;

        if (!isNaN(i) && wrpr) {
            e_lm = wrpr[i].getBoundingClientRect();
            top = e_lm.top - b_od.top;
        } else {
            top = 0;
        }
        html.scrollTop = top;
        b_ody.scrollTop = top;
    },

    // Main functions here.
    init: function (container, object, dimensions, HF) {
        "use strict";
        var videos = object, // The video object input.
            ids = Object.keys(videos),
            aspect_ratio = dimensions.aspectRatio,
            header_content = HF.header || "
HULK
",
            footer_content = HF.footer || "
FOOTEY
",

            // ========================================================
            // YouTube
            url_base = "https://youtu.be/", // Short YT URL base link.
            url_embed_base = "https://www.youtube.com/embed/", // YT embed URL base
            url_image_base = "https://i.ytimg.com/vi/", // YT image URL base (front)
            url_image_base_end = "/0.jpg", // YT image URL base (back)
            // ========================================================

            iframes,
            btn_on,
            btn_off,
            wrpr,
            array = [],
            yt_url,
            ctnr = EYT.d.getElementById(container), // Container element.
            timmy_outer,
            UA = navigator.userAgent,

            // ========================================
            // CONTENT (iframe, buttons, and textarea).
            half_0 = '
' +
                        '
',
            half_1 = '
' +
                        '' +
                            '
' +
                                '
' +
                                    '<button type="button" class="player_on">PLAY</button>' +
                                    '<button type="button" class="player_off" disabled="1">' +
                                    'CLEAR</button>' +
                                    '<textarea style="display:none; opacity:0" ' +
                                        'rows="1" readonly="readonly" ' +
                                        'wrap="off" title="YouTube URL" ' +
                                        'onclick="this.select()" class="yt_url"></textarea>' +
                                '
' +
                            '
' +
                        '
',
            // ========================================

            // Nodelist to Array (function).
            t_a = function (a) {
                if (EYT.d.querySelectorAll(a).length > 0) {
                    return Array.prototype.slice.call(EYT.d.querySelectorAll(a));
                }
            },

            // Video *PLAY* (function).
            player_on = function (v, i) {
                iframes[i].src = url_embed_base +
                                    videos[ids[i]] +
                                    "?wmode=transparent" +
                                    "&modestbranding=1" +
                                    "&rel=0" +
                                    "&showinfo=0" +
                                    "&fs=0" +
                                    "&autoplay=1";
                /* ======================================================== |
                |   To learn the embedded YT player PARAMETERS, go to:      |
                |       developers.google.com/youtube/player_parameters     |
                | ======================================================== */

                iframes[i].style.backgroundImage = "";
                iframes[i].style.opacity = 1;

                wrpr[i].style.background = "#000";
                wrpr[i].style.color = "#fff";

                v.disabled = 1;

                if (timmy_outer) {
                    window.clearTimeout(timmy_outer);
                }

                btn_on.forEach(function (v, ii) {
                    if (ii !== i) {
                        v.disabled = 1;
                    }
                });
            },

            // Video *CLEAR* (function).
            player_off = function (v, i, enable_btn_off) {
                var interval,
                    counter = 0,
                    limit,
                    check_btn = function () {
                        counter += 1;

                        limit = UA.match(/firefox/gi)
                            ? 25
                            : 6;

                        if (counter < limit) {
                            if (!v.disabled) {
                                v.disabled = 1;
                            }

                            // ========================================================
                            // These get buggy on Firefox, therefore I re-declare them.
                            // The removing *EventListener* part.
                            if (iframes.src) { // Making sure.
                                iframes[i].src = "";
                            }
                            // Making sure.
                            iframes[i].removeEventListener("load", enable_btn_off, 0);
                            iframes[i].removeEventListener("error", enable_btn_off, 0);
                            // ========================================================

                            if (!iframes[i].style.backgroundImage) {
                                iframes[i].style
                                    .backgroundImage = "url(" +
                                                        url_image_base +
                                                        videos[ids[i]] +
                                                        url_image_base_end +
                                                        ")";
                            }

                            if (yt_url[i].style.opacity === 1) {
                                yt_url[i].style.opacity = 0;
                            }

                            if (yt_url[i].style.display === "block") {
                                yt_url[i].style.display = "none";
                            }

                            if (!UA.match(/firefox/gi)) {
                                if (wrpr[i].style.background && wrpr[i].style.color) {
                                    wrpr[i].style.background = "";
                                    wrpr[i].style.color = "";
                                }
                            }
                        } else {
                            if (UA.match(/firefox/gi)) {
                                if (iframes[i].style.opacity === 1) {
                                    iframes[i].style.opacity = 0.5;
                                }

                                if (wrpr[i].style.background && wrpr[i].style.color) {
                                    wrpr[i].style.background = "";
                                    wrpr[i].style.color = "";
                                }

                                if (btn_on[i].disabled) {
                                    btn_on.forEach(function (v) {
                                        v.disabled = 0;
                                    });
                                }
                            }
                            if (btn_on[i].disabled) {
                                btn_on.forEach(function (v) {
                                    v.disabled = 0;
                                });
                            }
                            window.clearInterval(interval);
                        }
                    };

                iframes[i].src = "";
                iframes[i].removeEventListener("load", enable_btn_off, 0);
                iframes[i].removeEventListener("error", enable_btn_off, 0);
                iframes[i].style.opacity = 0.5;

                // Forcing button thing.
                interval = window.setInterval(check_btn, 100);
            },

            // Button click handler (function).
            clck = function (v, i) {
                var enable_btn_off = function () {
                    yt_url[i].style.display = "block";

                    timmy_outer = window.setTimeout(function () {
                        yt_url[i].style.opacity = 1;
                    }, 500);

                    btn_off[i].disabled = 0;
                };

                EYT.scroll(i, wrpr); // Page scroll.

                if (v.className === "player_on") { // *PLAY*.
                    iframes[i].addEventListener("load", enable_btn_off, 0);
                    iframes[i].addEventListener("error", enable_btn_off, 0);

                    player_on(v, i); // Go to *player_on* function.
                } else { // *CLEAR*.
                    player_off(v, i, enable_btn_off); // Go to *player_off* function.
                }
            },

            // Responsive iframes (function).
            rv = {
                w: window,
                css: function (a) {
                    return rv.w.getComputedStyle(a, null);
                },
                re_size: function (a) {
                    var all_properties,
                        height,
                        width,
                        default_height = dimensions.height + "px",
                        default_width = dimensions.width + "px",
                        window_width = rv.w.innerWidth,
                        add_30px = a.src
                            ? 30
                            : 0;

                    if (window_width < dimensions.width) {
                        a.forEach(function (v) {
                            v.style.width = "100%";
                        });

                        all_properties = rv.css(a[0]);
                        width = parseInt(all_properties.getPropertyValue("width"), 10);

                        height = Math.floor(width * (aspect_ratio)) + add_30px;
                        // The extra 30px is for the player control,
                        // only when the iframe has non-empty source attribute.

                        a.forEach(function (v) {
                            v.style.height = height + "px";
                        });
                    } else {
                        a.forEach(function (v) {
                            v.style.cssText += "height:" + default_height +
                                                ";width:" + default_width;
                        });
                    }
                }
            };

        /*|============= |*|
        |*|  INJECTION.  |*|
        |*| ============ |*/
        // [1] Header content definition.
        array.push(header_content);

        // [2] Body content (titles, iframes, buttons, and URL links) definition.
        ids.forEach(function (v) {
            array.push(half_0 + v + half_1);
        });

        // [3] Footer content definition.
        array.push(footer_content);

        // [4] Inject Header-Body-Footer into the container element.
        ctnr.innerHTML = array.join("");

        // [5] Define iframes, buttons, wrappers, and YT url containers.
        iframes = t_a(".yt_embed");
        btn_on = t_a(".player_on");
        btn_off = t_a(".player_off");
        wrpr = t_a(".yt_embed_wrap");
        yt_url = t_a(".yt_url");

        // [6] Loop using *iframes* reference.
        // The length of all 5 variables defined above are the same.
        iframes.forEach(function (v, i) {
            btn_on[i].onclick = function () { // Button *PLAY* click handler.
                clck(btn_on[i], i);
            };

            btn_off[i].onclick = function () { // Button *CLEAR* click handler.
                clck(btn_off[i], i);
            };

            // Set initial *background-image* on iframes.
            v.style.backgroundImage = "url(" + url_image_base + videos[ids[i]] + url_image_base_end + ")";

            // Set value to YouTube URL textareas.
            yt_url[i].value = url_base + videos[ids[i]];
        });

        // ==============================================
        // RESPONSIVE IFRAMES MODULE INVOCATION (*rv* variable).
        rv.re_size(iframes);
        rv.w.addEventListener("resize", function () {
            rv.re_size(iframes);
        });
    }
};

/*|=========================|**
**| INITIALIZE THE FUNCTION |**
**|=========================|*/
// #[I] Initialize the main function.
EYT.init(
    // ======================= //
    // List of input arguments //
    // ======================= //

     /*| #[I.1] The container element's ID |*/
    "yt_embed_container",

    /*| #[I.2] Object                   |**
    **|    {"title": "video ID"} pairs. |**
    **|    Put as many as you want.     |*/
    {
        "Expressions": "arJtsvv6akc",
        "Dancing Zoidberg along with Minuet (Luigi Boccherini)": "ikl3hGEfSLc",
        "Knock Knock Joke": "rLwDNwkJqjY",
        "Babba's tribute to mainstream music": "8DTgMZP6f8U"
    },

    /*| #[I.3] Default dimensions and aspect ratio |*/
    {
        /*| #[I.3.a] Dimensions in pixels |*/
        "height": 360,
        "width": 640,

        /*| #[I.3.b] Aspect ratio |*/
        "aspectRatio": 9/16

        // It can be 3/4, or 1/2, up to you.
        // The largest number is the width ratio.
        // Put the smallest value in front: *small_number/big_number*.

        // This feature will work on screen which has narrower width than you define above.
    },

    /*| #[1.4] HEADER and FOOTER CONTENT |*/
    // Customize the HEADER and FOOTER CSS from the [style] tag above.
    // Header class: .header
    // Footer class: .footer
    {
        "header": "
" +
                "Multiple YouTube Embedded Videos
" +
                "Without YouTube JS API
" +
                "" +
                "For mobile player (flv), the " +
                "autoplay parameter (currently) doesn't work" +
                "" +
                "
",

        "footer": "
" +
                "
Template by Monkey Raptor
" +
                "
See page source | See source on GitHub
" +
                "
Updated May 28, 2015
" +
                "
<button type='button' class='scroller' onclick='EYT.scroll()'>" +
                "TOP</button>
" +
                "
"
    }
);

// #[II] Initialize scrolling to the top of the page.
/*| ============================================== |*|
|*|   Scroll to the top of the page on DOM load.   |*|
|*| ============================================== |*/
EYT.scroll();

// These lines below can be omitted (demo purpose only).
/*| ========================== |*|
|*|   EXTRA FUNC:              |*|
|*|     - Check if in iframe.  |*|
|*| ========================== |*/
var extra = {
        in_iframe: function () { // stackoverflow.com/a/326076
            "use strict";
            try {
                return window.self !== window.top;
            } catch (e) {
                if (e) {
                    return 1;
                }
            }
        },
        rmv_node: function (a, b) {
            "use strict";
            a.removeChild(b);
        }
    },
    footer = document.querySelectorAll(".footer")[0],
    h3_elm = footer.childNodes[0],
    vsource_elm = footer.childNodes[1];

if (extra.in_iframe()) {
    extra.rmv_node(footer, h3_elm);
    extra.rmv_node(footer, vsource_elm);
}
<|endoftext|>


<commit_before>/*eslint-disable no-undef*/
import "./style.css";

require("./style.css");

import("./style.css");

custom_require_function("./style.css");

Object.method("./style.css");<commit_msg>chore(examples): Add another example for removing import<commit_after>/*eslint-disable no-undef, import/no-duplicates*/
import "./style.css";
import {} from "./style.css";

require("./style.css");

import("./style.css");

custom_require_function("./style.css");

Object.method("./style.css");<|endoftext|>


<commit_before>import React from 'react';
import update from 'react-addons-update';
import CodeEditor from './CodeEditor.js';
import {Router} from 'react-router';
// Bootstrap
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon.js';
import Alert from 'react-bootstrap/lib/Alert.js';
import Tabs from 'react-bootstrap/lib/Tabs.js';
import Tab from 'react-bootstrap/lib/Tab.js';
import History from 'react-router/lib/History';

import TextBox from '../../src/components/fieldComponents/TextBox.js';
import Metaform from './../../src/MetaForm.js';
import metadataProvider from '../../src/lib/metadataProvider.js';
import CheckBox from '../../src/components/fieldComponents/CheckBox.js';
import Lookup from '../../src/components/fieldComponents/Lookup.js';
import DefaultComponentFactory from '../../src/DefaultComponentFactory.js';
import liveSchemaEditorPresetProvider from './LiveSchemaEditorPresetProvider.js';
import GitHubForkRibbon from 'react-github-fork-ribbon';
import _ from 'underscore';
import psjon from '../../package.json';

let presetsConfig = liveSchemaEditorPresetProvider.getPresets();

const LiveSchemaEditor = React.createClass({

    mixins: [History],

    getInitialState: function () {
        let initialPreset = this.props.initialPreset ? this.props.initialPreset : 'textbox';
        let presetConfig = _.find(presetsConfig, p => p.value == initialPreset);
        if (!presetConfig) {
            presetConfig = presetsConfig[0];
        }

        return {
            schema: {},
            entityName: presetConfig.entityName,
            layoutName: presetConfig.layoutName,
            model: {},
            title: presetConfig.title,
            autoUpdate: true,
            presets: presetsConfig,
            selectedPreset: initialPreset,
            text: presetConfig.code,
            // the selected key in the right tab
            formTabKey: 1
        };
    },

    onPresetChange: function (event) {
        let preset = event.value;
        let updatedState;
        let presetConfig = _.find(presetsConfig, p => p.value == preset);
        if (!presetConfig) {
            presetConfig = presetsConfig[0];
        }
        updatedState = _.extend({}, this.state);
        updatedState.selectedPreset = preset;
        updatedState.title = presetConfig.title;
        updatedState.entityName = presetConfig.entityName;
        updatedState.layoutName = presetConfig.layoutName;
        updatedState.text = presetConfig.code;
        updatedState.formTabKey = 1;
        updatedState.model = {};
        this.metaFormCache = null;
        this.setState(updatedState, () => {
            this.resetMetaform(() => {
                this.history.pushState(null, 'demo.html', {preset: preset});
            });
        });
    },

    onSelectedTabChange: function (key) {
        this.setState({formTabKey: key});
    },

    onAutoUpdateChange: function (event) {

        let setAutoupdateState = (e) => {
            let updatedState = update(this.state, {autoUpdate: {$set: e.value}});
            this.setState(updatedState);
        };

        if (!this.state.autoUpdate) {
            // if the autoUpdate option was not checked, let's update the form before setting the autoUpdate state
            this.metaFormCache = null;
            this.forceUpdate(() => {
                this.resetMetaform(() => {
                    setAutoupdateState(event);
                });
            });
        }
        else {
            // ... otherwise, let's just change the autoupdate state
            setAutoupdateState(event);
        }
    },

    onCodeChange: function (event) {
        let updatedState = update(this.state, {text: {$set: event.value}});
        this.setState(updatedState, () => {
            if (this.state.autoUpdate) {
                this.resetMetaform();
            }
        });
    },

    onMainEntityNameChanged: function (event) {
        let updatedState = update(this.state, {entityName: {$set: event.value}});
        this.setState(updatedState);
    },

    onMainLayoutNameChanged: function (event) {
        let updatedState = update(this.state, {layoutName: {$set: event.value}});
        this.setState(updatedState);
    },

    onFormTitleChanged: function (event) {
        let updatedState = update(this.state, {title: {$set: event.value}});
        this.setState(updatedState);
    },

    onUpdateClick: function () {
        this.metaFormCache = null;
        this.forceUpdate(() => this.resetMetaform());
    },

    resetMetaform: function (next) {
        if (this.refs.mf) {
            this.refs.mf.resetState(next);
        }
    },

    /**
     * Returns the schema object based on the text
     */
    buildMetaform: function () {

        try {

            if (this.state.autoUpdate || !this.metaFormCache) {

                let schema = eval('(' + this.state.text + ')');

                // the only reason why I'm getting this here, is so it's going to trigger an exception
                // when the entityName and/or the layoutName is not valid
                metadataProvider.getEntityAndLayout(schema, this.state.entityName, this.state.layoutName);

                let metaForm = <Metaform
                    schema={schema}
                    ref="mf"
                    entityName={this.state.entityName}
                    layoutName={this.state.layoutName}
                    componentFactory={DefaultComponentFactory}
                    model={this.state.model}
                    title={this.state.title}
                    />;
                this.metaFormCache = metaForm;
                return metaForm;
            }
            else {
                return this.metaFormCache;
            }

        }
        catch (ex) {
            return <Alert bsStyle='danger'>

Oh snap! The schema is not valid.

Detailed information:
                    {ex.message}

            </Alert>
        }
    },

    render: function () {
        let _this = this;
        return

            <GitHubForkRibbon href="https://github.com/gearz-lab/react-metaform"
                              target="_blank"
                              position="right"
                color="black">
                                Fork me on GitHub
            </GitHubForkRibbon>

React-metaform demo {psjon.version}

                            Check the metadata
                                documentation.
                            <Lookup name="presets" displayName="Presets" options={this.state.presets}
                                    onChange={this.onPresetChange} value={this.state.selectedPreset}/>

                            <TextBox displayName="Main entity name" value={this.state.entityName}
                                     onChange={this.onMainEntityNameChanged}/>

                            <TextBox displayName="Main layout name" value={this.state.layoutName}
                                     onChange={this.onMainLayoutNameChanged}/>

                            <TextBox displayName="Form title" value={this.state.title}
                                     onChange={this.onFormTitleChanged}/>

                    <CodeEditor
                        displayName="Schema"
                        onChange={this.onCodeChange}
                        name="liveSchemaEditor"
                        value={this.state.text ? this.state.text : ''}
                        />

                    <Tabs activeKey={this.state.formTabKey} onSelect={this.onSelectedTabChange} animation={false}>
                        <Tab eventKey={1} title="Form">

                                        <Button onClick={this.onUpdateClick}
                                                disabled={this.state.autoUpdate}><Glyphicon
                                            glyph="refresh"/>Update form</Button>

<CheckBox name="toggle-auto-update" displayName="Auto update form (toggle off if you experience errors)"
          onChange={this.onAutoUpdateChange}
          value={this.state.autoUpdate}/>

                                            {this.buildMetaform()}

                        </Tab>
                        <Tab eventKey={2} title="Model">

                                <CodeEditor
                                    displayName="Model preview (read-only)"
                                    name="model_preview"
                                    readOnly={true}
                                    value={this.state.model ? JSON.stringify(this.state.model, null, 2) : ''}
                                    />

                        </Tab>
                    </Tabs>

;
    }
});

export default LiveSchemaEditor;
<commit_msg>Removing a warning related with react-router<commit_after>import React from 'react';
import update from 'react-addons-update';
import CodeEditor from './CodeEditor.js';
import {Router} from 'react-router';
// Bootstrap
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon.js';
import Alert from 'react-bootstrap/lib/Alert.js';
import Tabs from 'react-bootstrap/lib/Tabs.js';
import Tab from 'react-bootstrap/lib/Tab.js';
import History from 'react-router/lib/History';

import TextBox from '../../src/components/fieldComponents/TextBox.js';
import Metaform from './../../src/MetaForm.js';
import metadataProvider from '../../src/lib/metadataProvider.js';
import CheckBox from '../../src/components/fieldComponents/CheckBox.js';
import Lookup from '../../src/components/fieldComponents/Lookup.js';
import DefaultComponentFactory from '../../src/DefaultComponentFactory.js';
import liveSchemaEditorPresetProvider from './LiveSchemaEditorPresetProvider.js';
import GitHubForkRibbon from 'react-github-fork-ribbon';
import _ from 'underscore';
import psjon from '../../package.json';

let presetsConfig = liveSchemaEditorPresetProvider.getPresets();

const LiveSchemaEditor = React.createClass({

    mixins: [History],

    getInitialState: function () {
        let initialPreset = this.props.initialPreset ? this.props.initialPreset : 'textbox';
        let presetConfig = _.find(presetsConfig, p => p.value == initialPreset);
        if (!presetConfig) {
            presetConfig = presetsConfig[0];
        }

        return {
            schema: {},
            entityName: presetConfig.entityName,
            layoutName: presetConfig.layoutName,
            model: {},
            title: presetConfig.title,
            autoUpdate: true,
            presets: presetsConfig,
            selectedPreset: initialPreset,
            text: presetConfig.code,
            // the selected key in the right tab
            formTabKey: 1
        };
    },

    onPresetChange: function (event) {
        let preset = event.value;
        let updatedState;
        let presetConfig = _.find(presetsConfig, p => p.value == preset);
        if (!presetConfig) {
            presetConfig = presetsConfig[0];
        }
        updatedState = _.extend({}, this.state);
        updatedState.selectedPreset = preset;
        updatedState.title = presetConfig.title;
        updatedState.entityName = presetConfig.entityName;
        updatedState.layoutName = presetConfig.layoutName;
        updatedState.text = presetConfig.code;
        updatedState.formTabKey = 1;
        updatedState.model = {};
        this.metaFormCache = null;
        this.setState(updatedState, () => {
            this.resetMetaform(() => {
                this.history.pushState(null, '/react-metaform/demo.html', {preset: preset});
            });
        });
    },

    onSelectedTabChange: function (key) {
        this.setState({formTabKey: key});
    },

    onAutoUpdateChange: function (event) {

        let setAutoupdateState = (e) => {
            let updatedState = update(this.state, {autoUpdate: {$set: e.value}});
            this.setState(updatedState);
        };

        if (!this.state.autoUpdate) {
            // if the autoUpdate option was not checked, let's update the form before setting the autoUpdate state
            this.metaFormCache = null;
            this.forceUpdate(() => {
                this.resetMetaform(() => {
                    setAutoupdateState(event);
                });
            });
        }
        else {
            // ... otherwise, let's just change the autoupdate state
            setAutoupdateState(event);
        }
    },

    onCodeChange: function (event) {
        let updatedState = update(this.state, {text: {$set: event.value}});
        this.setState(updatedState, () => {
            if (this.state.autoUpdate) {
                this.resetMetaform();
            }
        });
    },

    onMainEntityNameChanged: function (event) {
        let updatedState = update(this.state, {entityName: {$set: event.value}});
        this.setState(updatedState);
    },

    onMainLayoutNameChanged: function (event) {
        let updatedState = update(this.state, {layoutName: {$set: event.value}});
        this.setState(updatedState);
    },

    onFormTitleChanged: function (event) {
        let updatedState = update(this.state, {title: {$set: event.value}});
        this.setState(updatedState);
    },

    onUpdateClick: function () {
        this.metaFormCache = null;
        this.forceUpdate(() => this.resetMetaform());
    },

    resetMetaform: function (next) {
        if (this.refs.mf) {
            this.refs.mf.resetState(next);
        }
    },

    /**
     * Returns the schema object based on the text
     */
    buildMetaform: function () {

        try {

            if (this.state.autoUpdate || !this.metaFormCache) {

                let schema = eval('(' + this.state.text + ')');

                // the only reason why I'm getting this here, is so it's going to trigger an exception
                // when the entityName and/or the layoutName is not valid
                metadataProvider.getEntityAndLayout(schema, this.state.entityName, this.state.layoutName);

                let metaForm = <Metaform
                    schema={schema}
                    ref="mf"
                    entityName={this.state.entityName}
                    layoutName={this.state.layoutName}
                    componentFactory={DefaultComponentFactory}
                    model={this.state.model}
                    title={this.state.title}
                    />;
                this.metaFormCache = metaForm;
                return metaForm;
            }
            else {
                return this.metaFormCache;
            }

        }
        catch (ex) {
            return <Alert bsStyle='danger'>

Oh snap! The schema is not valid.

Detailed information:
                    {ex.message}

            </Alert>
        }
    },

    render: function () {
        let _this = this;
        return

            <GitHubForkRibbon href="https://github.com/gearz-lab/react-metaform"
                              target="_blank"
                              position="right"
                color="black">
                                Fork me on GitHub
            </GitHubForkRibbon>

React-metaform demo {psjon.version}

                            Check the metadata
                                documentation.
                            <Lookup name="presets" displayName="Presets" options={this.state.presets}
                                    onChange={this.onPresetChange} value={this.state.selectedPreset}/>

                            <TextBox displayName="Main entity name" value={this.state.entityName}
                                     onChange={this.onMainEntityNameChanged}/>

                            <TextBox displayName="Main layout name" value={this.state.layoutName}
                                     onChange={this.onMainLayoutNameChanged}/>

                            <TextBox displayName="Form title" value={this.state.title}
                                     onChange={this.onFormTitleChanged}/>

                    <CodeEditor
                        displayName="Schema"
                        onChange={this.onCodeChange}
                        name="liveSchemaEditor"
                        value={this.state.text ? this.state.text : ''}
                        />

                    <Tabs activeKey={this.state.formTabKey} onSelect={this.onSelectedTabChange} animation={false}>
                        <Tab eventKey={1} title="Form">

                                        <Button onClick={this.onUpdateClick}
                                                disabled={this.state.autoUpdate}><Glyphicon
                                            glyph="refresh"/>Update form</Button>

<CheckBox name="toggle-auto-update" displayName="Auto update form (toggle off if you experience errors)"
          onChange={this.onAutoUpdateChange}
          value={this.state.autoUpdate}/>

                                            {this.buildMetaform()}

                        </Tab>
                        <Tab eventKey={2} title="Model">

                                <CodeEditor
                                    displayName="Model preview (read-only)"
                                    name="model_preview"
                                    readOnly={true}
                                    value={this.state.model ? JSON.stringify(this.state.model, null, 2) : ''}
                                    />

                        </Tab>
                    </Tabs>

;
    }
});

export default LiveSchemaEditor;
<|endoftext|>


<commit_before>// The WEBSOCKET server and port the bot should connect to.
// Most of the time this isn't the same as the URL, check the `Request URL` of
// the websocket.
// If you really don't know how to do this... Run `node getserver.js URL`.
// Fill in the URL of the client where `URL` is.
// For example: `node getserver.js http://example-server.psim.us/`
exports.server = 'sim.psim.us';
exports.port = 8000;

// This is the server id.
// To know this one, you should check where the AJAX call 'goes' to when you
// log in.
// For example, on the Smogon server, it will say somewhere in the URL
// ~~showdown, meaning that the server id is 'showdown'.
// If you really don't know how to check this... run the said script above.
exports.serverid = 'showdown';

// The nick and password to log in with
// If no password is required, leave pass empty
exports.nick = 'Example bot nick';
exports.pass = '';

// The rooms that should be joined.
// Joining Smogon's Showdown's Lobby is not allowed.
exports.rooms = ['example room name', 'another example'];

// Any private rooms that should be joined.
// Private rooms will be moderated differently (since /warn doesn't work in them).
// The bot will also avoid leaking the private rooms through .seen
exports.privaterooms = [];

// The character text should start with to be seen as a command.
// Note that using / and ! might be 'dangerous' since these are used in
// Showdown itself.
// Using only alphanumeric characters and spaces is not allowed.
exports.commandcharacter = '.';

// The default rank is the minimum rank that can use a command in a room when
// no rank is specified in settings.json
exports.defaultrank = '%';

// Whether this file should be watched for changes or not.
// If you change this option, the server has to be restarted in order for it to
// take effect.
exports.watchconfig = false;

// Secondary websocket protocols should be defined here, however, Showdown
// doesn't support that yet, so it's best to leave this empty.
exports.secprotocols = [];

// What should be logged?
// 0 = error, ok, info, debug, recv, send
// 1 = error, ok, info, debug, cmdr, send
// 2 = error, ok, info, debug (recommended for development)
// 3 = error, ok, info (recommended for production)
// 4 = error, ok
// 5 = error
exports.debuglevel = 3;

// Users who can use all commands regardless of their rank. Be very cautious
// with this, especially on servers other than main.
exports.excepts = [];

// Whitelisted users are those who the bot will not enforce moderation for.
exports.whitelist = [];

// Add a link to the help for the bot here. When there is a link here, .help and .guide
// will link to it.
exports.botguide = '';

// This allows the bot to act as an automated moderator. If enabled, the bot will
// mute users who send 6 lines or more in 6 or fewer seconds for 7 minutes. NOTE: THIS IS
// BY NO MEANS A PERFECT MODERATOR OR SCRIPT. It is a bot and so cannot think for itself or
// exercise moderator discretion. In addition, it currently uses a very simple method of
// determining who to mute and so may miss people who should be muted, or mute those who
// shouldn't. Use with caution.
exports.allowmute = false;

// The punishment values system allows you to customise how you want the bot to deal with
// rulebreakers. Spamming has a points value of 2, all caps has a points value of 1, etc.
exports.punishvals = {
	1: 'warn',
	2: 'mute',
	3: 'hourmute',
	4: 'roomban',
	5: 'ban'
};

<commit_msg>Add changes from config-example.js<commit_after>// The WEBSOCKET server and port the bot should connect to.
// Most of the time this isn't the same as the URL, check the `Request URL` of
// the websocket.
// If you really don't know how to do this... Run `node getserver.js URL`.
// Fill in the URL of the client where `URL` is.
// For example: `node getserver.js http://example-server.psim.us/`
exports.server = 'pokecommunity.psim.us';
exports.port = 8000;

// This is the server id.
// To know this one, you should check where the AJAX call 'goes' to when you
// log in.
// For example, on the Smogon server, it will say somewhere in the URL
// ~~showdown, meaning that the server id is 'showdown'.
// If you really don't know how to check this... run the said script above.
exports.serverid = 'pokecommunity';

// The nick and password to log in with
// If no password is required, leave pass empty
exports.nick = 'PokeCommBot';
exports.pass = 'filler';

// The rooms that should be joined.
// Joining Smogon's Showdown's Lobby is not allowed.
exports.rooms = ['lobby', 'darkalley'];

// Any private rooms that should be joined.
// Private rooms will be moderated differently (since /warn doesn't work in them).
// The bot will also avoid leaking the private rooms through .seen
exports.privaterooms = [];

// The character text should start with to be seen as a command.
// Note that using / and ! might be 'dangerous' since these are used in
// Showdown itself.
// Using only alphanumeric characters and spaces is not allowed.
exports.commandcharacter = '.';

// The default rank is the minimum rank that can use a command in a room when
// no rank is specified in settings.json
exports.defaultrank = '%';

// Whether this file should be watched for changes or not.
// If you change this option, the server has to be restarted in order for it to
// take effect.
exports.watchconfig = true;

// Secondary websocket protocols should be defined here, however, Showdown
// doesn't support that yet, so it's best to leave this empty.
exports.secprotocols = [];

// What should be logged?
// 0 = error, ok, info, debug, recv, send
// 1 = error, ok, info, debug, cmdr, send
// 2 = error, ok, info, debug (recommended for development)
// 3 = error, ok, info (recommended for production)
// 4 = error, ok
// 5 = error
exports.debuglevel = 3;

// Users who can use all commands regardless of their rank. Be very cautious
// with this, especially on servers other than main.
exports.excepts = [];

// Whitelisted users are those who the bot will not enforce moderation for.
exports.whitelist = [];

// Add a link to the help for the bot here. When there is a link here, .help and .guide
// will link to it.
exports.botguide = '';

// This allows the bot to act as an automated moderator. If enabled, the bot will
// mute users who send 6 lines or more in 6 or fewer seconds for 7 minutes. NOTE: THIS IS
// BY NO MEANS A PERFECT MODERATOR OR SCRIPT. It is a bot and so cannot think for itself or
// exercise moderator discretion. In addition, it currently uses a very simple method of
// determining who to mute and so may miss people who should be muted, or mute those who
// shouldn't. Use with caution.
exports.allowmute = false;

// The punishment values system allows you to customise how you want the bot to deal with
// rulebreakers. Spamming has a points value of 2, all caps has a points value of 1, etc.
exports.punishvals = {
	1: 'warn',
	2: 'mute',
	3: 'hourmute',
	4: 'roomban',
	5: 'ban'
};

<|endoftext|>


<commit_before>const refresh = require('./lib/refresh');
const bot = require('./bot.js');
const settings = require('./../settings.json');
const modules = require('./modules.js');
const Message = require('./../orm/Message')
const commands = require('./commands');
const request = require('request-promise-native');
const influx = require('./../influx');
let lock = false;
bot.on('error', (err) => {
    /**
     * Catch errors here
     */
    console.log("Stack Trace: " + err.stack);
})
process.on('unhandledRejection', (err) => {
    console.log("UNHANDLED REJECTION AT " + err.stack);
    if (err.toString().includes('Request to use token, but token was unavailable to the client'))
        process.exit();//restart
});
process.on('uncaughtException', (err) => console.log("UNHANDLED EXCEPTION AT " + err.stack));
bot.on('message', async function(message) {
    /**
     * if locked, reject everything except dm
     */
    new Message({
        messageID: message.id,
        channel: message.channel.id
    }).save();
    if (message.author.bot) return;
    if (lock) {
        if (!settings.owners.includes(message.author.id))
            //  if (message.channel.guild)
            return;//not DM
    }
    /**
     * Listen to messages and convert into params
     */
    if (message.content.startsWith(settings.identifier)) {
        /**Extracting params */
        let params = message.content.substring(settings.identifier.length).trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift().trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else {
        //ignore because normal message
    }
});
bot.on('lock', () => { lock = true; });
bot.on('unlock', () => { lock = false; });
bot.on("guildMemberAdd", async function (member) {
    var user = member.user;
    if (member.guild.id === "184536578654339072") {
        if (member.user.bot) return console.log(member.user.tag + " is a bot who joined " + member.guild.name)
        user.send("Welcome to the Revive Network");
        if (! await refresh(user)) {
            await member.addRole(bot.guilds.get("184536578654339072").roles.get("317854639431221248"));
            const ma = await bot.channels.get("317859245309689856").send(user.toString() + "Type `accept` to continue. You will be kicked if you don't type `accept` within 10 minutes");
            ma.delete();
        }
    }
});
bot.on("guildMemberRemove", async function (member) {
    var user = member.user;
});
/**
bot.on('disconnect', function(event) {
    if (event.code === 0) return console.error(event);
    process.exit();//force restart
});*/

bot.on('ready', async function() {
    console.log("ReviveBot Ready");
    let dbs = await influx.getDatabaseNames();
    console.log(dbs);
    if(!dbs || dbs ===null)
        console.log("Cant connect to influx")
    if(!dbs.includes('discord'))
    {
        console.log("Creating Dicord DB");
    }
});
bot.on("guildMemberUpdate", async function (member, newMem) {
    let user = member.user;
    if (member.guild && (member.guild.id === "184536578654339072")) {
        let oldMem = member;
        if (!oldMem.roles.has("273105185566359562") && newMem.roles.has("273105185566359562")) return;
        if (!oldMem.roles.has("275317218911322112") && newMem.roles.has("275317218911322112")) return;
        if (oldMem.roles.has("317854639431221248") && !newMem.roles.has("317854639431221248"))
            await refresh(user);
        if ((!oldMem.roles.has("184684916833779712") && newMem.roles.has("184684916833779712")) || (!oldMem.roles.has("200849956796497920") && newMem.roles.has("200849956796497920")) || (!oldMem.roles.has("184676864630063104") && newMem.roles.has("184676864630063104")) || (!oldMem.roles.has("286646245198528523") && newMem.roles.has("286646245198528523"))) {
            await request('http://revive-bot-discord.revive.systems/v0/discord/reverse_link/' + user.id);
        }
    }
});
setInterval(async function(){
    const guild = bot.guilds.get("184536578654339072");
    influx.writePoints([
          {
            measurement: 'statistics',
            fields: { count: guild.memberCount},
            tags: {type:'members'}
          }
        ]).catch(console.log);
    let count = await Message.count();
    if(count)
        influx.writePoints([
          {
            measurement: 'statistics',
            fields: { count: count},
            tags: {type:'messages'}
          }
        ]).catch(console.log);
},1000)
<commit_msg>add some more statistics<commit_after>const refresh = require('./lib/refresh');
const bot = require('./bot.js');
const settings = require('./../settings.json');
const modules = require('./modules.js');
const Message = require('./../orm/Message')
const commands = require('./commands');
const request = require('request-promise-native');
const influx = require('./../influx');
let lock = false;
bot.on('error', (err) => {
    /**
     * Catch errors here
     */
    console.log("Stack Trace: " + err.stack);
})
process.on('unhandledRejection', (err) => {
    console.log("UNHANDLED REJECTION AT " + err.stack);
    if (err.toString().includes('Request to use token, but token was unavailable to the client'))
        process.exit();//restart
});
process.on('uncaughtException', (err) => console.log("UNHANDLED EXCEPTION AT " + err.stack));
bot.on('message', async function(message) {
    /**
     * if locked, reject everything except dm
     */
    new Message({
        messageID: message.id,
        channel: message.channel.id
    }).save();
    if (message.author.bot) return;
    if (lock) {
        if (!settings.owners.includes(message.author.id))
            //  if (message.channel.guild)
            return;//not DM
    }
    /**
     * Listen to messages and convert into params
     */
    if (message.content.startsWith(settings.identifier)) {
        /**Extracting params */
        let params = message.content.substring(settings.identifier.length).trim();
        params = params.split(settings.delimiter || ' ');
        let cmd = params.shift().trim();
        commands.execute(cmd.toLowerCase(), params, message)
    }
    else {
        //ignore because normal message
    }
});
bot.on('lock', () => { lock = true; });
bot.on('unlock', () => { lock = false; });
bot.on("guildMemberAdd", async function (member) {
    var user = member.user;
    if (member.guild.id === "184536578654339072") {
        if (member.user.bot) return console.log(member.user.tag + " is a bot who joined " + member.guild.name)
        user.send("Welcome to the Revive Network");
        if (! await refresh(user)) {
            await member.addRole(bot.guilds.get("184536578654339072").roles.get("317854639431221248"));
            const ma = await bot.channels.get("317859245309689856").send(user.toString() + "Type `accept` to continue. You will be kicked if you don't type `accept` within 10 minutes");
            ma.delete();
        }
    }
});
bot.on("guildMemberRemove", async function (member) {
    var user = member.user;
});
/**
bot.on('disconnect', function(event) {
    if (event.code === 0) return console.error(event);
    process.exit();//force restart
});*/

bot.on('ready', async function() {
    console.log("ReviveBot Ready");
    let dbs = await influx.getDatabaseNames();
    console.log(dbs);
    if(!dbs || dbs ===null)
        console.log("Cant connect to influx")
    if(!dbs.includes('discord'))
    {
        console.log("Creating Dicord DB");
    }
});
bot.on("guildMemberUpdate", async function (member, newMem) {
    let user = member.user;
    if (member.guild && (member.guild.id === "184536578654339072")) {
        let oldMem = member;
        if (!oldMem.roles.has("273105185566359562") && newMem.roles.has("273105185566359562")) return;
        if (!oldMem.roles.has("275317218911322112") && newMem.roles.has("275317218911322112")) return;
        if (oldMem.roles.has("317854639431221248") && !newMem.roles.has("317854639431221248"))
            await refresh(user);
        if ((!oldMem.roles.has("184684916833779712") && newMem.roles.has("184684916833779712")) || (!oldMem.roles.has("200849956796497920") && newMem.roles.has("200849956796497920")) || (!oldMem.roles.has("184676864630063104") && newMem.roles.has("184676864630063104")) || (!oldMem.roles.has("286646245198528523") && newMem.roles.has("286646245198528523"))) {
            await request('http://revive-bot-discord.revive.systems/v0/discord/reverse_link/' + user.id);
        }
    }
});
setInterval(async function(){
    const guild = bot.guilds.get("184536578654339072");
    influx.writePoints([
          {
            measurement: 'statistics',
            fields: { count: guild.memberCount},
            tags: {type:'members'}
          }
        ]).catch(console.log);
    let count = await Message.count();
    if(count)
        influx.writePoints([
          {
            measurement: 'statistics',
            fields: { count: count},
            tags: {type:'messages'}
          }
        ]).catch(console.log);
    guild.roles.map(function(r)=>{
        influx.writePoints([
          {
            measurement: 'statistics',
            fields: { count: r.members.size},
            tags: {type: role.id }
          }
        ]).catch(console.log);
    });
    influx.writePoints([
          {
            measurement: 'statistics',
            fields: { count: guild.presences.map(p => p.status != 'offline').length},
            tags: {type: "online"}
          }
        ]).catch(console.log);
},1000)
<|endoftext|>


<commit_before>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var reservedKeywords = exports.reservedKeywords = (
        '!|{|}|case|do|done|elif|else|'+
        'esac|fi|for|if|in|then|until|while|'+
        '&|;|export|local|read|typeset|unset|'+
        'elif|select|set'
    );

var languageConstructs = exports.languageConstructs = (
    '[|]|alias|bg|bind|break|builtin|'+
     'cd|command|compgen|complete|continue|'+
     'dirs|disown|echo|enable|eval|exec|'+
     'exit|fc|fg|getopts|hash|help|history|'+
     'jobs|kill|let|logout|popd|printf|pushd|'+
     'pwd|return|set|shift|shopt|source|'+
     'suspend|test|times|trap|type|ulimit|'+
     'umask|unalias|wait'
);

var ShHighlightRules = function() {
    var keywordMapper = this.createKeywordMapper({
        "keyword": reservedKeywords,
        "support.function.builtin": languageConstructs,
        "invalid.deprecated": "debugger"
    }, "identifier");

    var integer = "(?:(?:[1-9]\\d*)|(?:0))";
    // var integer = "(?:" + decimalInteger + ")";

    var fraction = "(?:\\.\\d+)";
    var intPart = "(?:\\d+)";
    var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
    var exponentFloat = "(?:(?:" + pointFloat + "|" +  intPart + ")" + ")";
    var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")";
    var fileDescriptor = "(?:&" + intPart + ")";

    var variableName = "[a-zA-Z][a-zA-Z0-9_]*";
    var variable = "(?:(?:\\$" + variableName + ")|(?:" + variableName + "=))";

    var builtinVariable = "(?:\\$(?:SHLVL|\\$|\\!|\\?))";

    var func = "(?:" + variableName + "\\s*\\(\\))";

    this.$rules = {
        "start" : [ {
            token : ["comment"],
            regex : /(?:^|\s)(#.*$)/
        }, {
            token : "string",           // " string
            regex : '"(?:[^\\\\]|\\\\.)*?"'
        }, {
            token : "variable.language",
            regex : builtinVariable
        }, {
            token : "variable",
            regex : variable
        }, {
            token : "support.function",
            regex : func
        }, {
            token : "support.function",
            regex : fileDescriptor
        }, {
            token : "string",           // ' string
            regex : "'(?:[^\\\\]|\\\\.)*?'"
        }, {
            token : "constant.numeric", // float
            regex : floatNumber
        }, {
            token : "constant.numeric", // integer
            regex : integer + "\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|~|<|>|<=|=>|=|!="
        }, {
            token : "paren.lparen",
            regex : "[\\[\\(\\{]"
        }, {
            token : "paren.rparen",
            regex : "[\\]\\)\\}]"
        }, {
            token : "text",
            regex : "\\s+"
        } ]
    };
};

oop.inherits(ShHighlightRules, TextHighlightRules);

exports.ShHighlightRules = ShHighlightRules;
});
<commit_msg>Fix comment highlighter<commit_after>/* ***** BEGIN LICENSE BLOCK *****
 * Distributed under the BSD license:
 *
 * Copyright (c) 2010, Ajax.org B.V.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Ajax.org B.V. nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL AJAX.ORG B.V. BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 * ***** END LICENSE BLOCK ***** */

define(function(require, exports, module) {
"use strict";

var oop = require("../lib/oop");
var TextHighlightRules = require("./text_highlight_rules").TextHighlightRules;

var reservedKeywords = exports.reservedKeywords = (
        '!|{|}|case|do|done|elif|else|'+
        'esac|fi|for|if|in|then|until|while|'+
        '&|;|export|local|read|typeset|unset|'+
        'elif|select|set'
    );

var languageConstructs = exports.languageConstructs = (
    '[|]|alias|bg|bind|break|builtin|'+
     'cd|command|compgen|complete|continue|'+
     'dirs|disown|echo|enable|eval|exec|'+
     'exit|fc|fg|getopts|hash|help|history|'+
     'jobs|kill|let|logout|popd|printf|pushd|'+
     'pwd|return|set|shift|shopt|source|'+
     'suspend|test|times|trap|type|ulimit|'+
     'umask|unalias|wait'
);

var ShHighlightRules = function() {
    var keywordMapper = this.createKeywordMapper({
        "keyword": reservedKeywords,
        "support.function.builtin": languageConstructs,
        "invalid.deprecated": "debugger"
    }, "identifier");

    var integer = "(?:(?:[1-9]\\d*)|(?:0))";
    // var integer = "(?:" + decimalInteger + ")";

    var fraction = "(?:\\.\\d+)";
    var intPart = "(?:\\d+)";
    var pointFloat = "(?:(?:" + intPart + "?" + fraction + ")|(?:" + intPart + "\\.))";
    var exponentFloat = "(?:(?:" + pointFloat + "|" +  intPart + ")" + ")";
    var floatNumber = "(?:" + exponentFloat + "|" + pointFloat + ")";
    var fileDescriptor = "(?:&" + intPart + ")";

    var variableName = "[a-zA-Z][a-zA-Z0-9_]*";
    var variable = "(?:(?:\\$" + variableName + ")|(?:" + variableName + "=))";

    var builtinVariable = "(?:\\$(?:SHLVL|\\$|\\!|\\?))";

    var func = "(?:" + variableName + "\\s*\\(\\))";

    this.$rules = {
        "start" : [ {
            token : ["text", "comment"],
            regex : /(^|\s)(#.*)$/
        }, {
            token : "string",           // " string
            regex : '"(?:[^\\\\]|\\\\.)*?"'
        }, {
            token : "variable.language",
            regex : builtinVariable
        }, {
            token : "variable",
            regex : variable
        }, {
            token : "support.function",
            regex : func
        }, {
            token : "support.function",
            regex : fileDescriptor
        }, {
            token : "string",           // ' string
            regex : "'(?:[^\\\\]|\\\\.)*?'"
        }, {
            token : "constant.numeric", // float
            regex : floatNumber
        }, {
            token : "constant.numeric", // integer
            regex : integer + "\\b"
        }, {
            token : keywordMapper,
            regex : "[a-zA-Z_$][a-zA-Z0-9_$]*\\b"
        }, {
            token : "keyword.operator",
            regex : "\\+|\\-|\\*|\\*\\*|\\/|\\/\\/|~|<|>|<=|=>|=|!="
        }, {
            token : "paren.lparen",
            regex : "[\\[\\(\\{]"
        }, {
            token : "paren.rparen",
            regex : "[\\]\\)\\}]"
        } ]
    };
};

oop.inherits(ShHighlightRules, TextHighlightRules);

exports.ShHighlightRules = ShHighlightRules;
});
<|endoftext|>


<commit_before>'use strict';

const storageManager = require('./../../core/blob/StorageManager'),
    js2xmlparser = require("js2xmlparser"),
    model = require('./../../xml/blob/ContainerListXmlModel');

class ListContainers {
    constructor() {
    }

    process(request, res) {
        const prefix = request.query.prefix || '',
            maxresults = request.query.maxresults || "5000",
            includeMetadata = (request.query.include === 'metadata') ? true : false,
            marker = request.query.marker || '';
        storageManager.listContainer(request, prefix, maxresults)
            .then((response) => {
                response.addHttpProperty('content-type', 'application/xml');
                res.set(response.httpProps);
                let transformedModel = this._transformContainerList(response.payload, includeMetadata, prefix, maxresults, marker);
                let xmlDoc = js2xmlparser.parse('EnumerationResults', transformedModel);
                xmlDoc = xmlDoc.replace(`<EnumerationResults>`, `<EnumerationResults ServiceEndpoint="http://localhost:10000/devstoreaccount1">`);
                xmlDoc = xmlDoc.replace(`<?xml version='1.0'?>`, `<?xml version="1.0" encoding="utf-8"?>`);
                xmlDoc = xmlDoc.replace(/\>[\s]+\</g, '><');
                // Forcing Express.js to not touch the charset of the buffer in order to remove charset=utf-8 as part of the content-type
                res.status(200).send(new Buffer(xmlDoc));
            });
    }

    _transformContainerList(containers, includeMetadata, prefix, maxresults, marker) {
        let xmlContainerListModel = new model.ContainerList();
        (prefix === '') ? delete xmlContainerListModel.Prefix : xmlContainerListModel.Prefix = prefix;
        (maxresults === '') ? delete xmlContainerListModel.MaxResults : xmlContainerListModel.MaxResults = maxresults;
        (marker === '') ? delete xmlContainerListModel.Marker : xmlContainerListModel.Marker = marker;
        // Fixme: We do not support markers yet
        delete xmlContainerListModel.NextMarker;
        for (let container of containers) {
            let modelContainer = new model.Container(container.name);
            xmlContainerListModel.Containers.Container.push(modelContainer);
            if (!includeMetadata || Object.keys(container.metaProps).length === 0) {
                delete modelContainer.Metadata;
            } else {
                modelContainer.Metadata = container.metaProps;
            }
            modelContainer.Properties['Last-Modified'] = new Date(container.meta.updated || container.meta.created).toUTCString();
            modelContainer.Properties.ETag = container.etag;
            modelContainer.Properties.LeaseStatus = (['available', 'broken', 'expired'].includes(container.leaseState)) ? 'unlocked' : 'locked';
            modelContainer.Properties.LeaseState = container.leaseState;
            if (container.leaseState === 'leased') {
                modelContainer.Properties.LeaseDuration = (container.leaseDuration === -1) ? 'infinite' : 'fixed';
            } else {
                delete modelContainer.Properties.LeaseDuration;
            }
        }
        return xmlContainerListModel;
    }
}

module.exports = new ListContainers;<commit_msg>ignore $logs container in response  #160 #155<commit_after>'use strict';

const storageManager = require('./../../core/blob/StorageManager'),
    js2xmlparser = require("js2xmlparser"),
    model = require('./../../xml/blob/ContainerListXmlModel');

class ListContainers {
    constructor() {
    }

    process(request, res) {
        const prefix = request.query.prefix || '',
            maxresults = request.query.maxresults || "5000",
            includeMetadata = (request.query.include === 'metadata') ? true : false,
            marker = request.query.marker || '';
        storageManager.listContainer(request, prefix, maxresults)
            .then((response) => {
                response.addHttpProperty('content-type', 'application/xml');
                res.set(response.httpProps);
                let transformedModel = this._transformContainerList(response.payload, includeMetadata, prefix, maxresults, marker);
                let xmlDoc = js2xmlparser.parse('EnumerationResults', transformedModel);
                xmlDoc = xmlDoc.replace(`<EnumerationResults>`, `<EnumerationResults ServiceEndpoint="http://localhost:10000/devstoreaccount1">`);
                xmlDoc = xmlDoc.replace(`<?xml version='1.0'?>`, `<?xml version="1.0" encoding="utf-8"?>`);
                xmlDoc = xmlDoc.replace(/\>[\s]+\</g, '><');
                // Forcing Express.js to not touch the charset of the buffer in order to remove charset=utf-8 as part of the content-type
                res.status(200).send(new Buffer(xmlDoc));
            });
    }

    _transformContainerList(containers, includeMetadata, prefix, maxresults, marker) {
        let xmlContainerListModel = new model.ContainerList();
        (prefix === '') ? delete xmlContainerListModel.Prefix : xmlContainerListModel.Prefix = prefix;
        (maxresults === '') ? delete xmlContainerListModel.MaxResults : xmlContainerListModel.MaxResults = maxresults;
        (marker === '') ? delete xmlContainerListModel.Marker : xmlContainerListModel.Marker = marker;
        // Fixme: We do not support markers yet
        delete xmlContainerListModel.NextMarker;
        for (let container of containers) {
            if (container.name === '$logs') {
                continue;
            }
            let modelContainer = new model.Container(container.name);
            xmlContainerListModel.Containers.Container.push(modelContainer);
            if (!includeMetadata || Object.keys(container.metaProps).length === 0) {
                delete modelContainer.Metadata;
            } else {
                modelContainer.Metadata = container.metaProps;
            }
            modelContainer.Properties['Last-Modified'] = new Date(container.meta.updated || container.meta.created).toUTCString();
            modelContainer.Properties.ETag = container.etag;
            modelContainer.Properties.LeaseStatus = (['available', 'broken', 'expired'].includes(container.leaseState)) ? 'unlocked' : 'locked';
            modelContainer.Properties.LeaseState = container.leaseState;
            if (container.leaseState === 'leased') {
                modelContainer.Properties.LeaseDuration = (container.leaseDuration === -1) ? 'infinite' : 'fixed';
            } else {
                delete modelContainer.Properties.LeaseDuration;
            }
        }
        return xmlContainerListModel;
    }
}

module.exports = new ListContainers;<|endoftext|>


<commit_before>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

$(document).ready(function () {
    $("#idformOffice").find('input, button, select').focus(function () {
        if ($('#id_divMessaje').index() !== -1) {
            $('#id_divMessaje').remove();
        }
    });
    $("#list_offices").change(insertViaAjax);
});

function insertViaAjax() {

    var id = $("#list_offices").val();
    var url = $("#rutaBase").val() + "office/edit/editOffice";
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: url,
        data: id,
        dataType: 'json',
        timeout: 100000,
        success: function (data) {
            console.log("SUCCESS: ", data);
            display(data);
        },
        error: function (e) {
            console.log("ERROR: ", e);
            display(e);
        },
        done: function (e) {
            console.log("DONE");
            enableSearchButton(true);
        }
    });

}

function display(data) {
    $('#office_name').val(data.result['name']);
    $('#office_tel').val(data.result['telephone']);
    $('#office_fax').val(data.result['fax']);
    $('#office_city').val(data.result['address']['city']);
    $('#office_street').val(data.result['address']['street']);
    $('#office_number').val(data.result['address']['number']);
    $('#office_manager').val(data.result['manager']['name']);
    $('#addressId').val(data.result['address']['id']);

    /*
     //para adicionar elementos html
     var $selec = $('<option />', {id: 'select' + this.begin + "_" + this.end + "_" + this.unit, value: this.begin + "_" + this.end + "_" + this.unit});
     $selec.appendTo("#list_offices")
     //para manipular el elemento creado
     $selec.prop('selected',true)*/
}   <commit_msg>Exception message<commit_after>/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

$(document).ready(function () {
    $("#idformOffice").find('input, button, select').focus(function () {
        //if ($('#id_divMessaje').index() !== -1) {
            $('#id_divMessaje').remove();
        //}
    });
    $("#list_offices").change(insertViaAjax);
});

function insertViaAjax() {

    var id = $("#list_offices").val();
    var url = $("#rutaBase").val() + "office/edit/editOffice";
    $.ajax({
        type: "POST",
        contentType: "application/json",
        url: url,
        data: id,
        dataType: 'json',
        timeout: 100000,
        success: function (data) {
            console.log("SUCCESS: ", data);
            display(data);
        },
        error: function (e) {
            console.log("ERROR: ", e);
            display(e);
        },
        done: function (e) {
            console.log("DONE");
            enableSearchButton(true);
        }
    });

}

function display(data) {
    $('#office_name').val(data.result['name']);
    $('#office_tel').val(data.result['telephone']);
    $('#office_fax').val(data.result['fax']);
    $('#office_city').val(data.result['address']['city']);
    $('#office_street').val(data.result['address']['street']);
    $('#office_number').val(data.result['address']['number']);
    $('#office_manager').val(data.result['manager']['name']);
    $('#addressId').val(data.result['address']['id']);

    /*
     //para adicionar elementos html
     var $selec = $('<option />', {id: 'select' + this.begin + "_" + this.end + "_" + this.unit, value: this.begin + "_" + this.end + "_" + this.unit});
     $selec.appendTo("#list_offices")
     //para manipular el elemento creado
     $selec.prop('selected',true)*/
}   <|endoftext|>