<commit_before>/*jslint browser: true, nomen: true, todo: true */
(function ($, window, document) {
    'use strict';

    var P, PicPlus, loadImage,
        LoadQueue, loadQueue,
        $win = $(window),
        MQL_DATA = 'picplus-mql',
        ACTIVE_CLASS = 'picplus-active',
        Autoload = {
            IMMEDIATE: 'immediate',
            LAZY: 'lazy',
            NONE: 'none'
        };

    // The default image loader. The plugin has a list of image loaders and
    // passes each one the image attributes. The loader can choose whether it
    // wants to load the image or not. If it decides it should load the image,
    // it should return a promise which is resolved with a DOM element
    // representing the loaded image. Otherwise, it should return `null`.
    loadImage = function (attrs) {
        var deferred = $.Deferred(),
            img = new Image();
        img.onload = function () {
            deferred.resolve(img);
        };
        $.extend(img, attrs);
        return deferred.promise();
    };

    LoadQueue = function () {};
    LoadQueue.create = function () {
        var lq = new LoadQueue();
        lq.items = [];
        lq.loaders = [loadImage];
        lq._onComplete = $.proxy(LoadQueue.prototype._onComplete, lq);
        return lq;
    };
    LoadQueue.prototype = {
        simultaneous: 3,
        _loadingCount: 0,
        _loadNext: function () {
            var nextItem;
            if (!this.items.length || this._loadingCount >= this.simultaneous) {
                return;
            }
            nextItem = this.items.pop();  // Load most recently queued first.
            this._loadingCount += 1;
            nextItem();
        },
        _onComplete: function () {
            this._loadingCount -= 1;
            this._loadNext();
        },
        load: function (imgAttrs) {
            var loadNow,
                self = this,
                deferred = $.Deferred(),
                promise = deferred.promise();

            // TODO: Support timeout
            loadNow = function () {
                var p;

                // Loop through the loaders until we find one to use.
                $.each(self.loaders, function (i, loader) {
                    p = loader(imgAttrs);
                    if (p) {
                        p
                            .then(deferred.resolve)
                            .then(self._onComplete);
                        return false;
                    }
                });

                if (!p) {
                    $.error('No loader found for image.', imgAttrs)
                }
            };

            this.items.push(loadNow);
            this._loadNext();
            return promise;
        }
    };

    P = PicPlus = function () {};
    PicPlus.prototype = {

        defaultOptions: {
            // When should the image be loaded?
            autoload: Autoload.IMMEDIATE,

            // Does the image change size when the browser window does?
            responsive: false
        },

        initialize: function ($el, options) {
            this.$el = $el;
            this.options = $.extend({}, this.defaultOptions, this.getHtmlOptions(), options);

            if (this.$el.is('[data-src]')) {
                // Shorthand version
                this.$sources = this.$el;
            } else {
                this.$sources = this.$el.find('[data-src]');
            }

            this._setupMediaQueries();

            if (this.options.responsive && this.$sources.length > 1) {
                // Unfortunately, we can't use MediaQueryList.addListener
                // because if multiple sources match, we need to recalculate
                // to find the *first* match.
                this._onResize = $.proxy(this.load, this);
                $win.on('resize', this._onResize);
            }
            if (this.options.autoload === Autoload.IMMEDIATE) {
                this.load();
            }
            return this;
        },

        // Create a media query list for each source.
        _setupMediaQueries: function () {
            var $el, mql, media;
            if (!window.matchMedia) {
                return;
            }

            this.$sources.each(function (i, el) {
                $el = $(el);
                media = $el.attr('data-media');
                if (media) {
                    mql = window.matchMedia(media);
                    $el.data(MQL_DATA, mql);
                }
            });
        },

        getHtmlOptions: function () {
            var attrs = this.$el[0].attributes;
            return {
                autoload: attrs['data-autoload'],
                alt: attrs.alt
            };
        },

        // Load the appropriate source.
        load: function () {
            var $source, i, media, mql;
            // Iterate in reverse order so that later sources have higher
            // priority.
            for (i = this.$sources.length - 1; i >= 0; i -= 1) {
                $source = this.$sources.eq(i);
                media = $source.attr('data-media');
                mql = $source.data(MQL_DATA);
                if (!media || (window.matchMedia && mql.matches)) {
                    // We should load this source.
                    this._loadSource($source);
                    break;
                }
            }

            return this;
        },

        onImageLoad: function (img, $source) {
            // Make sure this is the image we were waiting for.
            if (!(this._loadingSource && this._loadingSource[0] === $source[0])) {
                return;
            }
            this._loadingSource = null;
            img.onload = null;
            this.showImage($source, img);
        },

        // Show the provided image, for the provided source element.
        showImage: function ($source, img) {
            if (this.$sources.length > 1) {
                this.$sources
                    .hide()
                    .removeClass(ACTIVE_CLASS);
            }
            if (img && !img.parentNode) {
                $source[0].appendChild(img);
            }
            $source
                .addClass(ACTIVE_CLASS)
                .show();
        },

        // Load the source represented by the provided element.
        _loadSource: function ($source) {
            var src, alt, lq,
                self = this,
                promise = $source.data('promise');

            if (promise) {
                if (promise.state() == 'resolved') {
                    this.showImage($source)
                }

                // TODO: Should promote it to top of queue.
                return;
            }

            if (!loadQueue) {
                loadQueue = LoadQueue.create();
            }

            src = $source.attr('data-src');
            alt = $source.attr('data-alt');
            if (alt === null || alt === undefined) {
                alt = this.$el.attr('data-alt');
            }

            promise = loadQueue.load({src: src, alt: alt});
            $source.data('promise', promise);
            this._loadingSource = $source;
            promise.done(function (img) {
                self.onImageLoad(img, $source);
            });
        },

        destroy: function () {
            if (this._onResize) {
                $win.off('resize', this._onResize);
            }
        }
    };

    $.extend($.fn, {
        picplus: function (optionsOrMethod) {
            var returnValue = this,
                args = arguments;
            this.each(function (i, el) {
                var $el = $(el),
                    plugin = $el.data('picplus'),
                    method = typeof optionsOrMethod === 'string' ? optionsOrMethod : null,
                    options = method === null ? optionsOrMethod || {} : {};

                if (!plugin) {
                    if (method) {
                        $.error('You can\'t call the picplus method "' + method
                                + '" without first initializing the plugin by calling '
                                + 'picplus() on the jQuery object.');
                    } else {
                        plugin = new PicPlus().initialize($el, options);
                        $el.data('picplus', plugin);
                    }
                } else if (method) {
                    if (typeof plugin[method] !== 'function') {
                        $.error('Method "' + method + '" does not exist on jQuery.picplus');
                    } else {
                        // NOTE: If you call a method that returns a value, you will only get the result from the last item in the collection.
                        returnValue = plugin[method].apply(plugin, Array.prototype.slice.call(args, 1));
                    }
                }
            });
            return returnValue;
        }
    });

    $.picplus = function (opts) {
        $('[data-picplus]').picplus(opts);
    };

    $.picplus.config = function (opts) {
        // global config opts. for example, how many images to load at once.
    };

}(this.jQuery, window, document));
<commit_msg>Add inline SVG loading<commit_after>/*jslint browser: true, nomen: true, todo: true */
(function ($, window, document) {
    'use strict';

    var P, PicPlus, loadImage, loadSvgInline,
        LoadQueue, loadQueue,
        $win = $(window),
        MQL_DATA = 'picplus-mql',
        ACTIVE_CLASS = 'picplus-active',
        Autoload = {
            IMMEDIATE: 'immediate',
            LAZY: 'lazy',
            NONE: 'none'
        };

    // The default image loader. The plugin has a list of image loaders and
    // passes each one the image attributes. The loader can choose whether it
    // wants to load the image or not. If it decides it should load the image,
    // it should return a promise which is resolved with a DOM element
    // representing the loaded image. Otherwise, it should return `null`.
    loadImage = function (attrs) {
        var deferred = $.Deferred(),
            img = new Image();
        img.onload = function () {
            deferred.resolve(img);
        };
        $.extend(img, attrs);
        return deferred.promise();
    };

    loadSvgInline = function (attrs) {
        var deferred,
            type = attrs.type,
            src = attrs.src,
            isSvg = (type == 'image/svg+xml') || (!type && /\.svg(\?.*)?(#.*)?$/i.test(src));

        if (!isSvg) {
            return;
        }

        deferred = $.Deferred();
        $.ajax({
            url: src,
            dataType: 'text',
            success: function (data) {
                var svg = $(data);
                deferred.resolve(svg);
            }
        });
        return deferred.promise();
    };

    LoadQueue = function () {};
    LoadQueue.create = function () {
        var lq = new LoadQueue();
        lq.items = [];
        lq.loaders = [loadSvgInline, loadImage];
        lq._onComplete = $.proxy(LoadQueue.prototype._onComplete, lq);
        return lq;
    };
    LoadQueue.prototype = {
        simultaneous: 3,
        _loadingCount: 0,
        _loadNext: function () {
            var nextItem;
            if (!this.items.length || this._loadingCount >= this.simultaneous) {
                return;
            }
            nextItem = this.items.pop();  // Load most recently queued first.
            this._loadingCount += 1;
            nextItem();
        },
        _onComplete: function () {
            this._loadingCount -= 1;
            this._loadNext();
        },
        load: function (imgAttrs) {
            var loadNow,
                self = this,
                deferred = $.Deferred(),
                promise = deferred.promise();

            // TODO: Support timeout
            loadNow = function () {
                var p;

                // Loop through the loaders until we find one to use.
                $.each(self.loaders, function (i, loader) {
                    p = loader(imgAttrs);
                    if (p) {
                        p
                            .then(deferred.resolve)
                            .then(self._onComplete);
                        return false;
                    }
                });

                if (!p) {
                    $.error('No loader found for image.', imgAttrs)
                }
            };

            this.items.push(loadNow);
            this._loadNext();
            return promise;
        }
    };

    P = PicPlus = function () {};
    PicPlus.prototype = {

        defaultOptions: {
            // When should the image be loaded?
            autoload: Autoload.IMMEDIATE,

            // Does the image change size when the browser window does?
            responsive: false
        },

        initialize: function ($el, options) {
            this.$el = $el;
            this.options = $.extend({}, this.defaultOptions, this.getHtmlOptions(), options);

            if (this.$el.is('[data-src]')) {
                // Shorthand version
                this.$sources = this.$el;
            } else {
                this.$sources = this.$el.find('[data-src]');
            }

            this._setupMediaQueries();

            if (this.options.responsive && this.$sources.length > 1) {
                // Unfortunately, we can't use MediaQueryList.addListener
                // because if multiple sources match, we need to recalculate
                // to find the *first* match.
                this._onResize = $.proxy(this.load, this);
                $win.on('resize', this._onResize);
            }
            if (this.options.autoload === Autoload.IMMEDIATE) {
                this.load();
            }
            return this;
        },

        // Create a media query list for each source.
        _setupMediaQueries: function () {
            var $el, mql, media;
            if (!window.matchMedia) {
                return;
            }

            this.$sources.each(function (i, el) {
                $el = $(el);
                media = $el.attr('data-media');
                if (media) {
                    mql = window.matchMedia(media);
                    $el.data(MQL_DATA, mql);
                }
            });
        },

        getHtmlOptions: function () {
            var attrs = this.$el[0].attributes;
            return {
                autoload: attrs['data-autoload'],
                alt: attrs.alt
            };
        },

        // Load the appropriate source.
        load: function () {
            var $source, i, media, mql;
            // Iterate in reverse order so that later sources have higher
            // priority.
            for (i = this.$sources.length - 1; i >= 0; i -= 1) {
                $source = this.$sources.eq(i);
                media = $source.attr('data-media');
                mql = $source.data(MQL_DATA);
                if (!media || (window.matchMedia && mql.matches)) {
                    // We should load this source.
                    this._loadSource($source);
                    break;
                }
            }

            return this;
        },

        onImageLoad: function (img, $source) {
            // Make sure this is the image we were waiting for.
            if (!(this._loadingSource && this._loadingSource[0] === $source[0])) {
                return;
            }
            this._loadingSource = null;
            img.onload = null;
            this.showImage($source, img);
        },

        // Show the provided image, for the provided source element.
        showImage: function ($source, img) {
            if (this.$sources.length > 1) {
                this.$sources
                    .hide()
                    .removeClass(ACTIVE_CLASS);
            }
            if (img && !img.parentNode) {
                $source.eq(0).append(img);
            }
            $source
                .addClass(ACTIVE_CLASS)
                .show();
        },

        // Load the source represented by the provided element.
        _loadSource: function ($source) {
            var src, alt, lq,
                self = this,
                promise = $source.data('promise');

            if (promise) {
                if (promise.state() == 'resolved') {
                    this.showImage($source)
                }

                // TODO: Should promote it to top of queue.
                return;
            }

            if (!loadQueue) {
                loadQueue = LoadQueue.create();
            }

            src = $source.attr('data-src');
            alt = $source.attr('data-alt');
            if (alt === null || alt === undefined) {
                alt = this.$el.attr('data-alt');
            }

            promise = loadQueue.load({src: src, alt: alt});
            $source.data('promise', promise);
            this._loadingSource = $source;
            promise.done(function (img) {
                self.onImageLoad(img, $source);
            });
        },

        destroy: function () {
            if (this._onResize) {
                $win.off('resize', this._onResize);
            }
        }
    };

    $.extend($.fn, {
        picplus: function (optionsOrMethod) {
            var returnValue = this,
                args = arguments;
            this.each(function (i, el) {
                var $el = $(el),
                    plugin = $el.data('picplus'),
                    method = typeof optionsOrMethod === 'string' ? optionsOrMethod : null,
                    options = method === null ? optionsOrMethod || {} : {};

                if (!plugin) {
                    if (method) {
                        $.error('You can\'t call the picplus method "' + method
                                + '" without first initializing the plugin by calling '
                                + 'picplus() on the jQuery object.');
                    } else {
                        plugin = new PicPlus().initialize($el, options);
                        $el.data('picplus', plugin);
                    }
                } else if (method) {
                    if (typeof plugin[method] !== 'function') {
                        $.error('Method "' + method + '" does not exist on jQuery.picplus');
                    } else {
                        // NOTE: If you call a method that returns a value, you will only get the result from the last item in the collection.
                        returnValue = plugin[method].apply(plugin, Array.prototype.slice.call(args, 1));
                    }
                }
            });
            return returnValue;
        }
    });

    $.picplus = function (opts) {
        $('[data-picplus]').picplus(opts);
    };

    $.picplus.config = function (opts) {
        // global config opts. for example, how many images to load at once.
    };

}(this.jQuery, window, document));
<|endoftext|>


<commit_before>// Use the web-push library to hide the implementation details of the communication
// between the application server and the push service.
// For details, see https://tools.ietf.org/html/draft-ietf-webpush-protocol-01 and
// https://tools.ietf.org/html/draft-thomson-webpush-encryption-01.
var webPush = require('web-push');

webPush.setGCMAPIKey(process.env.GCM_API_KEY);

module.exports = function(app, route) {
  app.post(route + 'register', function(req, res) {
    // A real world application would store the subscription info.
    res.sendStatus(201);
  });

  app.post(route + 'sendNotification', function(req, res) {
    setTimeout(function() {
      webPush.sendNotification(req.body.endpoint, req.body.ttl, req.body.key,
                               req.body.payload)
      .then(function() {
        res.sendStatus(201);
      });
    }, req.body.delay * 1000);
  });
};
<commit_msg>Send notification using the auth secret, if available<commit_after>// Use the web-push library to hide the implementation details of the communication
// between the application server and the push service.
// For details, see https://tools.ietf.org/html/draft-ietf-webpush-protocol-01 and
// https://tools.ietf.org/html/draft-thomson-webpush-encryption-01.
var webPush = require('web-push');

webPush.setGCMAPIKey(process.env.GCM_API_KEY);

module.exports = function(app, route) {
  app.post(route + 'register', function(req, res) {
    // A real world application would store the subscription info.
    res.sendStatus(201);
  });

  app.post(route + 'sendNotification', function(req, res) {
    setTimeout(function() {
      webPush.sendNotification(req.body.endpoint, {
        TTL: req.body.ttl,
        payload: req.body.payload,
        userPublicKey: req.body.key,
        userAuth: req.body.authSecret,
      })
      .then(function() {
        res.sendStatus(201);
      });
    }, req.body.delay * 1000);
  });
};
<|endoftext|>


<commit_before><commit_msg>Cleanup<commit_after><|endoftext|>


<commit_before>(function($){

	var methods={
		init:function(options)
		{
			return this.each(function(){
				var def={
					'el':'#primary-content'
				};
				$.extend(true,def,options);
				var sn=$(this).data('ozClient');
				$.ajax({
					url:'http://oz.st-n.ru/horoscope/',
					dataType:"text",
					success:function(s){
						//$(def.el).html(s);
					}
				});
			});
		}
	};

	$.fn.ozClientHoroscope=function(sn){
		if (!sn) { var sn={}; }
		if ( methods[sn]) {
			return methods[sn].apply(this,Array.prototype.slice.call(arguments,1));
		} else if (typeof sn==='object' || !sn) {
			return methods.init.apply(this,arguments);
		} else {
			$.error('Метод '+sn+' не существует');
		}

	};
})(jQuery);
<commit_msg>доделал гороскоп в общем заказе<commit_after>(function($){

	var methods={
		init:function(options)
		{
			return this.each(function(){
				var def={
					'el':'#primary-content'
				};
				$.extend(true,def,options);
				var sn=$(this).data('ozClient');
				$.ajax({
					url:'http://oz.st-n.ru/horoscope/',
					dataType:"json",
					success:function(s){
						if (s.hscope) {
							$.each(s.hscope,function(key,value){
								if (value.description) {
									$("#hscope-description-"+key).html(value.description);
								}
							});
						}
					}
				});
			});
		}
	};

	$.fn.ozClientHoroscope=function(sn){
		if (!sn) { var sn={}; }
		if ( methods[sn]) {
			return methods[sn].apply(this,Array.prototype.slice.call(arguments,1));
		} else if (typeof sn==='object' || !sn) {
			return methods.init.apply(this,arguments);
		} else {
			$.error('Метод '+sn+' не существует');
		}

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


<commit_before>/*
    ------------------
    Initialize Variables
    ------------------
*/

//Constants
const VERSION = 1.1;
const BOOT_TIME = new Date();
const WH_TIME = 0;
const ADMINS = ["Dino", "α|CraftSpider|Ω", "HiddenStorys"];

//Command variables
var NumWWs = 0;
var MaxWWs = 10;
var IsSleeping = 0;

//Writing Hour variables
var WHActive = false;
var WHDisactive = false;
var WHAlertOne = false;
var WHAlertTwo = false;

/*
	--------------------------
    User Commands dictionaries
    --------------------------
*/
var Commands = {
	"information": function() {
		postMessage("Hello! I'm Talos, official PtP mod-bot.\nMy Developers are CraftSpider, Dino, and HiddenStorys.\nAny suggestions or bugs can be sent to my email, talos.ptp@gmail.com.");
	},
	"seen": function(user) {
		//postMessage("Sorry, this command doesn't work yet.");
		if(user[0]) {
			var time;
			searchMessages("{V:" + user.join(" ") + "}");
			setTimeout(function() {
				var recentMessage = elementByID("X6817").childNodes[2];
				if(recentMessage.childNodes[5]) {
					time = recentMessage.childNodes[5].innerText;
				} else {
					time = recentMessage.childNodes[4].innerText;
				}
			}, 500);
			setTimeout(function() {
				if(time) {
                    postMessage("User " + user.join(" ") + " was last seen " + time);
				} else {
					postMessage("I couldn't find that user. Sorry.");
					X47();
				}
			}, 700);
			setTimeout(function() {
				X1774();
			}, 900);
		} else {
			postMessage("Sorry, I need a user to look for.");
			X47();
		}
	},
	"uptime": function() {
		postMessage("I've been online since " + BOOT_TIME.toUTCString() + ".");
	},
	"version": function() {
		postMessage("I'm currently on version " + VERSION);
	},
	"wordWar": function(length) {
		if (length[0] > 60 || length[0] <= 0) {
			postMessage("Choose a number between 1 and 60.");
		} else if (NumWWs >= MaxWWs) {
		    postMessage("Too many word wars, I can't keep up! Wait for one to finish first.");
		} else {
		    NumWWs++;
			postMessage("I'm starting a " + length[0] + " minute word war." + (length[1]? " Keyword: " + length[1]  + "." : "") + " Go!");
			setTimeout(function() {
				NumWWs--;
				if (!IsSleeping) {
					postMessage("Word War " + (length[1]? "'" + length[1] + "' " : "") + "ends. How did you do?");
				}
			}, length[0] * 60000);
		}
	},
	"help": function (args) {
	    if (!args[0]) {
		    var helpList = "Greetings. I'm Talos, chat helper. My commands are:\n";
		    for (var C in Commands) {
		    	helpList += "^" + C + "\n";
		    }
		    helpList += "\nMy Admin Commands are:\n";
		    for (var C in ADMIN_COMMANDS) {
		    	helpList += "^" + C + "\n";
		    }
		    postMessage(helpList);
	    } else {
	        switch (args[0]) {
	            case "help":
	                postMessage("Use: ^help [Command Name]\nDescription: Help command, by default gives general information about Talos and a list of available commands. Adding the name of another command as an argument will give a more detailed description of that command. Though you probably figured that out, you're here after all :P");
	                break;
	            case "information":
	            	postMessage("Use: ^information\nDescription: Gives a short blurb about Talos.");
	            	break;
	            case "kill":
	                postMessage("Use: ^kill\nDescription: Causes Talos to immediately leave the chat, and cease running. Admin only.");
	                break;
	            case "seen":
	                postMessage("Use: ^seen <Username>\nDescription: Find how long ago this user last posted a message. Returns a time or date in EST.");
	                break;
	            case "toggleSleep":
	                postMessage("Use: ^toggleSleep [time]\nDescription: Turns user commands and related features off or on. An admin only command, to prevent abuse. Also doesn't declare the finish to any active WWs that finish while I'm asleep.");
	                break;
	            case "uptime":
	            	postMessage("Use: ^uptime\nDescription: Gives the time and date, down to the second, that Talos began running.");
	            	break;
	            case "version":
	            	postMessage("Use: ^version\nDescription: The version that Talos is currently running. I always know exactly where I am.");
	            	break;
	            case "wordWar":
	                postMessage("Use: ^wordWar <time> [keyword]\nDescription: Starts a Word War, with given keyword if provided. The time is in minutes, and Talos will say when that many minutes have elapsed.");
	                break;
	            default:
	                postMessage("Sorry, no available help page for that.");
	        }
	    }
	}
};

var ADMIN_COMMANDS = {
    "toggleSleep": function() {
    	if (IsSleeping == 0) {
    		IsSleeping = 1;
    		postMessage("Good night! Going to sleep now. To wake me, type [b]^toggleSleep[/b] again.");
    	} else {
    		IsSleeping = 0;
    		postMessage("I'm awake again, and available for user commands. To have me sleep again, type [b]^toggleSleep[/b].");
    	}
	},
	"kill": function() {
		postMessage("Et Tu, Brute?");
		setTimeout(function() {leaveChat();}, 200);
		throw new Error("Talos Killed by Admin");
	},
};

/*
    -----------------
    Wrapper Functions
    -----------------
*/
function elementByID(elementID) {
    return document.getElementById(elementID);
}

function leaveChat() {
    elementByID("X2122").onclick();
}

function postMessage(message) {
    var HTMLTags = ["", "", "", "", "<s>", "</s>", "", ""];
    var ChatzyTags = ["[b]", "[/b]", "[i]", "[/i]", "[s]", "[/s]", "[u]", "[/u]"];
    for (var tag in HTMLTags) {
        message = message.replace(HTMLTags[tag],ChatzyTags[tag]);
    }
    X9646(message);
}

function closeChat() {
	postMessage("/close");
}

function openChat() {
	postMessage("/open");
}

function toggleChatLock() {
	if(X2667.X5476) { //Variable for whether the chat is locked, of course
		postMessage("/open");
	} else {
		postMessage("/close");
	}
}

function searchMessages(term) {
	postMessage("/find " + term);
}

function privateMessage(name, message) {
	postMessage("/pm \"" + name + "\" " + message);
}

function globalMessage(message) { //Note, only sends the message to online users.
	var users = X6958.split("\n");
	for (var i = 1; i <= users[0]; i++) {
		user = users[i].split("	");
		privateMessage(user[0], message);	//Replace the 0 with other numbers to grab different values. 2 is last leave/exit, 4 is status, 5 is location.
	}
}

function editRoomBoard(message, method, key) {  //Method is the style of editing to use. Options are: 0/default, overwrite. 1, append. 2, prepend. 3, replace.
    postMessage("/rb");
    setTimeout(function() {
        var BoardMessage = X17("X856");
        switch (method) {
            case 1:
                BoardMessage.value = BoardMessage.value + "\n" + message;
                break;
            case 2:
                BoardMessage.value = message + "\n" + BoardMessage.value;
                break;
            case 3:
                if (BoardMessage.value.match(new RegExp(key, "g")).length > 1) {
                    BoardMessage.value = BoardMessage.value.replace(new RegExp(key + ".+?" + key, "g"), key + message + key);
                }
                break;
            default:
                BoardMessage.value = message;
        }
        X565.onclick();
    }, 150);
}

//requires re-init of JSBot. Automate that?
function changeName(name) {
	X3132('X3221')

	setTimeout(function() {
		X2714.value = name;
		X6145.onsubmit();
	}, 1000);
}

/*
    -------------------
    Main loop functions
    -------------------
*/
function writingHour() {
    d = new Date();

    if (d.getUTCHours() == (WH_TIME == 0 ? 23 : WH_TIME - 1)  && d.getUTCMinutes() == 50 && !WHAlertOne) {
        postMessage("[b][Alert][/b] Writing Hour starts in 10 minutes!");
        WHAlertOne = true;
    } else if (d.getUTCHours() == (WH_TIME == 0 ? 23 : WH_TIME - 1) && d.getUTCMinutes() == 55 && !WHAlertTwo) {
        postMessage("[b][Alert][/b] Writing Hour starts in 5 minutes!");
        WHAlertTwo = true;
    } else if (d.getUTCHours() == WH_TIME && d.getUTCMinutes() == 0 && !WHActive) {
        postMessage("[b]Writing Hour has started.[/b] Have fun, and use it productively!");
        WHActive = true;
        WHDisactive = false;
        setTimeout(function() {closeChat();}, 500);
    } else if (d.getUTCHours() == (WH_TIME == 23 ? 0 : WH_TIME + 1) && d.getUTCMinutes() == 0 && !WHDisactive) {
        openChat();
        setTimeout(function() {postMessage("[b]Writing Hour is over.[/b] How did you do?");}, 500);
        WHDisactive = true;
        WHActive = false;
        WHAlertTwo = false;
        WHAlertOne = false;
    }
}

function readChat() {
    if (!elementByID("X6285") && elementByID("X6817").firstChild.innerHTML != "Previous messages parsed (press ESC to re-parse page)") { //First check is if we're on a page with normal chat table. Second is that that page is parsed.
        return;
    }
	var Messages = elementByID("X6817").innerHTML.split("\n");
	for (var i = 1; i < Messages.length; i++) {
		var Message = Messages[i];
		if (Message.match(/(.*)<\/b>: \^(\w+)(?:\s(.+))?(?: )/)) { //Instead of matching a set list of commands, match the word then check it against a dict?
		    var User = RegExp.$1;
			var Command = RegExp.$2;
			var Args = RegExp.$3.split(/\s/);
		    var isAdmin = false;
			for (var U in ADMINS) {
			    if (User == ADMINS[U]) {
			        isAdmin = true;
			        break;
			    }
			}
			if (window["ADMIN_COMMANDS"][Command] && isAdmin) {
			    window["ADMIN_COMMANDS"][Command](Args);
			} else if (IsSleeping == 1) {
				break;
			} else if (window["ADMIN_COMMANDS"][Command] && !isAdmin) {
			    postMessage("Sorry, that command is Admin only, and I don't recognize you!");
			} else if (window["Commands"][Command]) {
				window["Commands"][Command](Args);
			} else {
			    postMessage("Sorry, I don't understand that. May I suggest ^help?");
			}
		}
	}

	elementByID("X6817").innerHTML = '
Previous messages parsed (press ESC to re-parse page)
\n';
	X1281 = false;
}

function readPMs() {
    var ReceivedPM = elementByID("X8459").innerHTML;
    if (ReceivedPM.match(/.+>(.+)<\/em>.+X8195">\^(\w+)[\W]?(?:\s(.+))?(?:<\/div><p)/)) {
        var User = RegExp.$1;
        var Command = RegExp.$2;
		var Args = RegExp.$3.split(/\s/);
		var isAdmin = false;
		for (var U in ADMINS) {
		    if (User == ADMINS[U]) {
		        isAdmin = true;
		        break;
		    }
		}
		if (window["ADMIN_COMMANDS"][Command] && isAdmin) {
		    window["ADMIN_COMMANDS"][Command](Args);
		} else if (IsSleeping == 1) {
			X1774();
			return;
		} else if (window["ADMIN_COMMANDS"][Command] && !isAdmin) {
		    privateMessage("Sorry, that command is Admin only, and I don't recognize you!");
		} else if (window["Commands"][Command]) {
			window["Commands"][Command](Args);
		} else {
		    privateMessage("Sorry, I don't understand that. May I suggest ^help?");
		}
    }
}

function mainLoop() {
    readChat();
    writingHour();
    readPMs();

}

/*
    -------------------
    Initialization Code
    -------------------
*/
setInterval(function() {mainLoop();}, 1000);
setInterval(function() {postMessage("");}, 60000*10)
elementByID("X6817").innerHTML = '
Previous messages parsed (press ESC to re-parse page)
\n';
X1281 = false;
<commit_msg>I'm an idiot, fixed pull conflict.<commit_after>/*
    ------------------
    Initialize Variables
    ------------------
*/

//Constants
const VERSION = 1.1;
const BOOT_TIME = new Date();
const WH_TIME = 0;
const ADMINS = ["Dino", "α|CraftSpider|Ω", "HiddenStorys"];

//Command variables
var NumWWs = 0;
var MaxWWs = 10;
var IsSleeping = 0;

//Writing Hour variables
var WHActive = false;
var WHDisactive = false;
var WHAlertOne = false;
var WHAlertTwo = false;

//Generator words
var Noun = ["dog", "cat", "robot", "astronaut", "man", "woman", "person", "child", "giant", "elephant", "zebra", "animal", "box", "tree", "wizard", "mage", "swordsman", "soldier", "inventor", "doctor", "Talos", "dinosaur", "insect", "nerd", "dancer", "singer", "actor", "barista", "acrobat", "gamer", "writer", "dragon"];
var Adjective = ["happy", "sad", "athletic", "giant", "tiny", "smart", "silly", "unintelligent", "funny", "coffee-loving", "lazy", "spray-tanned", "angry", "disheveled", "annoying", "loud", "quiet", "shy", "extroverted", "jumpy", "ditzy", "strong", "weak", "smiley", "annoyed", "dextrous"];
var Goal = ["fly around the world", "go on a date", "win a race", "tell their crush how they feel", "find their soulmate", "write a chatbot", "get into university", "graduate high school", "plant a hundred trees", "find their biological parents", "fill their bucket list", "find atlantis", "learn magic", "learn to paint", "drive a car", "pilot a spaceship", "leave Earth", "go home", "redo elementary school", "not spill their beer"];
var Obstacle = ["learning to read", "fighting aliens", "saving the world", "doing algebra", "losing their hearing", "losing their sense of sight", "learning the language", "hacking the mainframe", "coming of age", "the nuclear apocalypse is happening", "incredibly drunk", "drinking coffee", "surfing", "spying on the bad guys", "smelling terrible", "having a bad hair day", "exploring the new planet", "on the moon", "on Mars"];

var Place = ["pub", "spaceship", "museum", "office", "jungle", "forest", "coffee shop", "store", "market", "station", "tree", "hut", "house", "bed", "bus", "car", "dormitory", "school", "desert", "ballroom", "cattery", "shelter", "street"];
var Place_Adjective = ["quiet", "loud", "crowded", "deserted", "bookish", "colorful", "balloon-filled", "book", "tree", "money", "video game", "cat", "dog", "busy", "apocalypse", "writer", "magic", "light", "dark", "robotic", "futuristic", "old-timey"];
var Action = ["learn to read", "jump up and down", "cry a lot", "cry a little", "smile", "spin in a circle", "get arrested", "dance to the music", "listen to your favourite song", "eat all the food", "win the lottery", "hack the mainframe", "save the world", "find atlantis", "get accepted to Hogwarts", "swim around", "defy gravity", "spy on the bad guys", "drive a car", "enter the rocket ship", "learn math", "write a lot", "do gymnastics"];
/*
	--------------------------
    User Commands dictionaries
    --------------------------
*/
var Commands = {
	"information": function() {
		postMessage("Hello! I'm Talos, official PtP mod-bot.\nMy Developers are CraftSpider, Dino, and HiddenStorys.\nAny suggestions or bugs can be sent to my email, talos.ptp@gmail.com.");
	},
	"seen": function(user) {
		//postMessage("Sorry, this command doesn't work yet.");
		if(user[0]) {
			var time;
			searchMessages("{V:" + user.join(" ") + "}");
			setTimeout(function() {
				var recentMessage = messageTable.childNodes[2];
				if(recentMessage.childNodes[5]) {
					time = recentMessage.childNodes[5].innerText;
				} else {
					time = recentMessage.childNodes[4].innerText;
				}
			}, 500);
			setTimeout(function() {
				if(time) {
                    postMessage("User " + user.join(" ") + " was last seen " + time);
				} else {
					postMessage("I couldn't find that user. Sorry.");
					X47();
				}
			}, 700);
			setTimeout(function() {
				closePopup();
			}, 900);
		} else {
			postMessage("Sorry, I need a user to look for.");
			X47();
		}
	},
	"uptime": function() {
		postMessage("I've been online since " + BOOT_TIME.toUTCString() + ".");
	},
	"version": function() {
		postMessage("I'm currently on version " + VERSION);
	},
	"wordWar": function(length) {
		if (length[0] > 60 || length[0] <= 0) {
			postMessage("Choose a number between 1 and 60.");
		} else if (NumWWs >= MaxWWs) {
		    postMessage("Too many word wars, I can't keep up! Wait for one to finish first.");
		} else {
		    NumWWs++;
			postMessage("I'm starting a " + length[0] + " minute word war." + (length[1]? " Keyword: " + length[1]  + "." : "") + " Go!");
			setTimeout(function() {
				NumWWs--;
				if (!IsSleeping) {
					postMessage("Word War " + (length[1]? "'" + length[1] + "' " : "") + "ends. How did you do?");
				}
			}, length[0] * 60000);
		}
	},
	"generate": function(type) {
		if (type[0] == "prompt") {
			postMessage("A story about a " + Adjective[randomNumber(0, Adjective.length - 1)] + " " + Noun[randomNumber(0, Noun.length - 1)] + " who must " + Goal[randomNumber(0, Goal.length - 1)] + " while " + Obstacle[randomNumber(0, Goal.length - 1)] + ".");
		} else if (type[0] == "crawl") {
			postMessage("You enter the " + Place_Adjective[randomNumber(0, Place_Adjective.length - 1)] + " " + Place[randomNumber(0, Place.length - 1)] + ". Write " + randomNumber(50, 500) + " words as you " + Action[randomNumber(0, Action.length - 1)] + ".");
		} else {
			postMessage("You can generate [b]prompt[/b]s and [b]crawl[/b] dares. Having trouble? Use ^help! :)");
		}
	},
	"help": function (args) {
	    if (!args[0]) {
		    var helpList = "Greetings. I'm Talos, chat helper. My commands are:\n";
		    for (var C in Commands) {
		    	helpList += "^" + C + "\n";
		    }
		    helpList += "\nMy Admin Commands are:\n";
		    for (var C in ADMIN_COMMANDS) {
		    	helpList += "^" + C + "\n";
		    }
		    postMessage(helpList);
	    } else {
	        switch (args[0]) {
	            case "help":
	                postMessage("Use: ^help [Command Name]\nDescription: Help command, by default gives general information about Talos and a list of available commands. Adding the name of another command as an argument will give a more detailed description of that command. Though you probably figured that out, you're here after all :P");
	                break;
	            case "information":
	            	postMessage("Use: ^information\nDescription: Gives a short blurb about Talos.");
	            	break;
	            case "kill":
	                postMessage("Use: ^kill\nDescription: Causes Talos to immediately leave the chat, and cease running. Admin only.");
	                break;
	            case "seen":
	                postMessage("Use: ^seen <Username>\nDescription: Find how long ago this user last posted a message. Returns a time or date in EST.");
	                break;
	            case "toggleSleep":
	                postMessage("Use: ^toggleSleep [time]\nDescription: Turns user commands and related features off or on. An admin only command, to prevent abuse. Also doesn't declare the finish to any active WWs that finish while I'm asleep.");
	                break;
	            case "uptime":
	            	postMessage("Use: ^uptime\nDescription: Gives the time and date, down to the second, that Talos began running.");
	            	break;
	            case "version":
	            	postMessage("Use: ^version\nDescription: The version that Talos is currently running. I always know exactly where I am.");
	            	break;
	            case "wordWar":
	                postMessage("Use: ^wordWar <time> [keyword]\nDescription: Starts a Word War, with given keyword if provided. The time is in minutes, and Talos will say when that many minutes have elapsed.");
	                break;
	            case "generate":
	            	postMessage("Use: ^generate <type>\nDescription: Generates a prompt. Currently available types are [b]prompt[/b] and [b]crawl[/b].");

	            	break;
	            default:
	                postMessage("Sorry, no available help page for that.");
	        }
	    }
	}
};

var ADMIN_COMMANDS = {
    "toggleSleep": function() {
    	if (IsSleeping == 0) {
    		IsSleeping = 1;
    		postMessage("Good night! Going to sleep now. To wake me, type [b]^toggleSleep[/b] again.");
    	} else {
    		IsSleeping = 0;
    		postMessage("I'm awake again, and available for user commands. To have me sleep again, type [b]^toggleSleep[/b].");
    	}
	},
	"kill": function() {
		postMessage("Et Tu, Brute?");
		setTimeout(function() {leaveChat();}, 200);
		throw new Error("Talos Killed by Admin");
	},
};

/*
    -----------------
    Wrapper Functions
    -----------------
*/
function elementByID(elementID) {
    return document.getElementById(elementID);
}

function leaveChat() {
    elementByID("X2122").onclick();

function closePopup() {
	X1774();
}

function postMessage(message) {
    var HTMLTags = ["", "", "", "", "<s>", "</s>", "", ""];
    var ChatzyTags = ["[b]", "[/b]", "[i]", "[/i]", "[s]", "[/s]", "[u]", "[/u]"];
    for (var tag in HTMLTags) {
        message = message.replace(HTMLTags[tag],ChatzyTags[tag]);
    }
    X9646(message);
}

function closeChat() {
	postMessage("/close");
}

function openChat() {
	postMessage("/open");
}

function toggleChatLock() {
	if(X2667.X5476) { //Variable for whether the chat is locked, of course
		postMessage("/open");
	} else {
		postMessage("/close");
	}
}

function searchMessages(term) {
	postMessage("/find " + term);
}

function privateMessage(name, message) {
	postMessage("/pm \"" + name + "\" " + message);
}

function globalMessage(message) { //Note, only sends the message to online users.
	var users = X6958.split("\n");
	for (var i = 1; i <= users[0]; i++) {
		user = users[i].split("	");
		privateMessage(user[0], message);	//Replace the 0 with other numbers to grab different values. 2 is last leave/exit, 4 is status, 5 is location.
	}
}

function editRoomBoard(message, method, key) {  //Method is the style of editing to use. Options are: 0/default, overwrite. 1, append. 2, prepend. 3, replace.
    postMessage("/rb");
    setTimeout(function() {
        var BoardMessage = X17("X856");
        switch (method) {
            case 1:
                BoardMessage.value = BoardMessage.value + "\n" + message;
                break;
            case 2:
                BoardMessage.value = message + "\n" + BoardMessage.value;
                break;
            case 3:
                if (BoardMessage.value.match(new RegExp(key, "g")).length > 1) {
                    BoardMessage.value = BoardMessage.value.replace(new RegExp(key + ".+?" + key, "g"), key + message + key);
                }
                break;
            default:
                BoardMessage.value = message;
        }
        X565.onclick();
    }, 150);
}

//requires re-init of JSBot. Automate that?
function changeName(name) {
	X3132('X3221')

	setTimeout(function() {
		X2714.value = name;
		X6145.onsubmit();
	}, 1000);
}

/*
Arbitrary functions
*/

function randomNumber(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
}

/*
/*
    -------------------
    Main loop functions
    -------------------
*/
function writingHour() {
    d = new Date();

    if (d.getUTCHours() == (WH_TIME == 0 ? 23 : WH_TIME - 1)  && d.getUTCMinutes() == 50 && !WHAlertOne) {
        postMessage("[b][Alert][/b] Writing Hour starts in 10 minutes!");
        WHAlertOne = true;
    } else if (d.getUTCHours() == (WH_TIME == 0 ? 23 : WH_TIME - 1) && d.getUTCMinutes() == 55 && !WHAlertTwo) {
        postMessage("[b][Alert][/b] Writing Hour starts in 5 minutes!");
        WHAlertTwo = true;
    } else if (d.getUTCHours() == WH_TIME && d.getUTCMinutes() == 0 && !WHActive) {
        postMessage("[b]Writing Hour has started.[/b] Have fun, and use it productively!");
        WHActive = true;
        WHDisactive = false;
        setTimeout(function() {closeChat();}, 500);
    } else if (d.getUTCHours() == (WH_TIME == 23 ? 0 : WH_TIME + 1) && d.getUTCMinutes() == 0 && !WHDisactive) {
        openChat();
        setTimeout(function() {postMessage("[b]Writing Hour is over.[/b] How did you do?");}, 500);
        WHDisactive = true;
        WHActive = false;
        WHAlertTwo = false;
        WHAlertOne = false;
    }
}

function readChat() {
    if (!elementByID("X6285") && messageTable.firstChild.innerHTML != "Previous messages parsed (press ESC to re-parse page)") { //First check is if we're on a page with normal chat table. Second is that that page is parsed.
        return;
    }
	var Messages = messageTable.innerHTML.split("\n");
	for (var i = 1; i < Messages.length; i++) {
		var Message = Messages[i];
		if (Message.match(/(.*)<\/b>: \^(\w+)(?:\s(.+))?(?: )/)) { //Instead of matching a set list of commands, match the word then check it against a dict?
		    var User = RegExp.$1;
			var Command = RegExp.$2;
			var Args = RegExp.$3.split(/\s/);
		    var isAdmin = false;
			for (var U in ADMINS) {
			    if (User == ADMINS[U]) {
			        isAdmin = true;
			        break;
			    }
			}
			if (window["ADMIN_COMMANDS"][Command] && isAdmin) {
			    window["ADMIN_COMMANDS"][Command](Args);
			} else if (IsSleeping == 1) {
				break;
			} else if (window["ADMIN_COMMANDS"][Command] && !isAdmin) {
			    postMessage("Sorry, that command is Admin only, and I don't recognize you!");
			} else if (window["Commands"][Command]) {
				window["Commands"][Command](Args);
			} else {
			    postMessage("Sorry, I don't understand that. May I suggest ^help?");
			}
		}
	}

	messageTable.innerHTML = '
Previous messages parsed (press ESC to re-parse page)
\n';
	X1281 = false;
}

function readPMs() {
    var ReceivedPM = elementByID("X8459").innerHTML;
    if (ReceivedPM.match(/.+>(.+)<\/em>.+X8195">\^(\w+)[\W]?(?:\s(.+))?(?:<\/div><p)/)) {
        var User = RegExp.$1;
        var Command = RegExp.$2;
		var Args = RegExp.$3.split(/\s/);
		var isAdmin = false;
		for (var U in ADMINS) {
		    if (User == ADMINS[U]) {
		        isAdmin = true;
		        break;
		    }
		}
		if (window["ADMIN_COMMANDS"][Command] && isAdmin) {
		    window["ADMIN_COMMANDS"][Command](Args);
		} else if (IsSleeping == 1) {
			closePopup();
			return;
		} else if (window["ADMIN_COMMANDS"][Command] && !isAdmin) {
		    privateMessage("Sorry, that command is Admin only, and I don't recognize you!");
		} else if (window["Commands"][Command]) {
			window["Commands"][Command](Args);
		} else {
		    privateMessage("Sorry, I don't understand that. May I suggest ^help?");
		}
    }
}

function mainLoop() {
    readChat();
    writingHour();
    readPMs();

}

/*
    -------------------
    Initialization Code
    -------------------
*/
var messageTable = elementByID("X6817");
messageTable.innerHTML = '
Previous messages parsed (press ESC to re-parse page)
\n';
X1281 = false;
setInterval(function() {mainLoop();}, 1000);
setInterval(function() {postMessage("");}, 60000*10);
<|endoftext|>


<commit_before>/**
 * Tabslet | tabs jQuery plugin
 *
 * @copyright Copyright 2015, Dimitris Krestos
 * @license   Apache License, Version 2.0 (http://www.opensource.org/licenses/apache2.0.php)
 * @link      http://vdw.staytuned.gr
 * @version   v1.7.0
 */

  /* Sample html structure

Tab 1

Tab 2

Tab 3

  OR

Tab 1

Tab 2

Tab 3

  */

;(function($, window, undefined) {
  "use strict";

  $.fn.tabslet = function(options) {

    var defaults = {
      mouseevent:   'click',
      attribute:    'href',
      animation:    false,
      autorotate:   false,
      deeplinking:  false,
      pauseonhover: true,
      delay:        2000,
      active:       1,
      container:    false,
      controls:     {
        prev: '.prev',
        next: '.next'
      }
    };

    var options = $.extend(defaults, options);

    return this.each(function() {

      var $this      = $(this), _cache_li = [], _cache_div = [];
      var _container = options.container ? $(options.container) : $this;
      var _tabs      = _container.find('> div');

      // Caching
      _tabs.each(function() { _cache_div.push($(this).css('display')); });

      // Autorotate
      var elements = $this.find('> ul li'), i = options.active - 1; // ungly

      if ( !$this.data( 'tabslet-init' ) ) {

        $this.data( 'tabslet-init', true );

        $this.opts = [];

        $.map( ['mouseevent', 'attribute', 'animation', 'autorotate', 'deeplinking', 'deeplinking', 'pauseonhover', 'delay', 'container'], function( val, i ) {
          $this.opts[val] = $this.data(val) || options[val];
        });

        $this.opts['active'] = $this.opts.deeplinking ? deep_link() : ( $this.data('active') || options.active )

        _tabs.hide();

        if ( $this.opts.active ) {
          _tabs.eq($this.opts.active - 1).show();
          elements.eq($this.opts.active - 1).addClass('active');
        }

        var fn = eval(

          function(e, tab) {
            var _this = tab ? elements.find('a[' + $this.opts.attribute + '=' + tab +']').parent() : $(this);

            _this.trigger('_before');

            elements.removeClass('active');
            _this.addClass('active');
            _tabs.hide();

            i = elements.index(_this);

            var currentTab = tab || _this.find('a').attr($this.opts.attribute);

            if ($this.opts.deeplinking) location.hash = currentTab;

            if ($this.opts.animation) {

              _container.find(currentTab).animate( { opacity: 'show' }, 'slow', function() {
                _this.trigger('_after');
              });

            } else {

              _container.find(currentTab).show();
              _this.trigger('_after');

            }

            return false;

          }

        );

        var init = eval("elements." + $this.opts.mouseevent + "(fn)");

        init;

        var t;

        var forward = function() {

          i = ++i % elements.length; // wrap around

          $this.opts.mouseevent == 'hover' ? elements.eq(i).trigger('mouseover') : elements.eq(i).click();

          if ($this.opts.autorotate) {

            clearTimeout(t);

            t = setTimeout(forward, $this.opts.delay);

            $this.mouseover(function () {

              if ($this.opts.pauseonhover) clearTimeout(t);

            });

          }

        }

        if ($this.opts.autorotate) {

          t = setTimeout(forward, $this.opts.delay);

          $this.hover(function() {

            if ($this.opts.pauseonhover) clearTimeout(t);

          }, function() {

            t = setTimeout(forward, $this.opts.delay);

          });

          if ($this.opts.pauseonhover) $this.on( "mouseleave", function() { clearTimeout(t); t = setTimeout(forward, $this.opts.delay); });

        }

        var deep_link = function() {

          var ids = [];

          elements.find('a').each(function() { ids.push($(this).attr($this.opts.attribute)); });

          var index = $.inArray(location.hash, ids)

          if (index > -1) {

            return index + 1

          } else {

            return ($this.data('active') || options.active)

          }

        }

        var move = function(direction) {

          if (direction == 'forward') i = ++i % elements.length; // wrap around

          if (direction == 'backward') i = --i % elements.length; // wrap around

          elements.eq(i).click();

        }

        $this.find(options.controls.next).click(function() {
          move('forward');
        });

        $this.find(options.controls.prev).click(function() {
          move('backward');
        });

        $this.on ('show', function(e, tab) {
          fn(e, tab);
        });

        $this.on ('next', function() {
          move('forward');
        });

        $this.on ('prev', function() {
          move('backward');
        });

        $this.on ('destroy', function() {
          $(this)
            .removeData()
            .find('> ul li').each( function(i) {
              $(this).removeClass('active');
            });
          _tabs.each( function(i) {
            $(this).removeAttr('style').css( 'display', _cache_div[i] );
          });
        });

      }

    });

  };

  $(document).ready(function () { $('[data-toggle="tabslet"]').tabslet(); });

})(jQuery);<commit_msg>A more precise targetting of elements.<commit_after>/**
 * Tabslet | tabs jQuery plugin
 *
 * @copyright Copyright 2015, Dimitris Krestos
 * @license   Apache License, Version 2.0 (http://www.opensource.org/licenses/apache2.0.php)
 * @link      http://vdw.staytuned.gr
 * @version   v1.7.0
 */

  /* Sample html structure

Tab 1

Tab 2

Tab 3

  OR

Tab 1

Tab 2

Tab 3

  */

;(function($, window, undefined) {
  "use strict";

  $.fn.tabslet = function(options) {

    var defaults = {
      mouseevent:   'click',
      attribute:    'href',
      animation:    false,
      autorotate:   false,
      deeplinking:  false,
      pauseonhover: true,
      delay:        2000,
      active:       1,
      container:    false,
      controls:     {
        prev: '.prev',
        next: '.next'
      }
    };

    var options = $.extend(defaults, options);

    return this.each(function() {

      var $this      = $(this), _cache_li = [], _cache_div = [];
      var _container = options.container ? $(options.container) : $this;
      var _tabs      = _container.find('> div');

      // Caching
      _tabs.each(function() { _cache_div.push($(this).css('display')); });

      // Autorotate
      var elements = $this.find('> ul > li'), i = options.active - 1; // ungly

      if ( !$this.data( 'tabslet-init' ) ) {

        $this.data( 'tabslet-init', true );

        $this.opts = [];

        $.map( ['mouseevent', 'attribute', 'animation', 'autorotate', 'deeplinking', 'deeplinking', 'pauseonhover', 'delay', 'container'], function( val, i ) {
          $this.opts[val] = $this.data(val) || options[val];
        });

        $this.opts['active'] = $this.opts.deeplinking ? deep_link() : ( $this.data('active') || options.active )

        _tabs.hide();

        if ( $this.opts.active ) {
          _tabs.eq($this.opts.active - 1).show();
          elements.eq($this.opts.active - 1).addClass('active');
        }

        var fn = eval(

          function(e, tab) {
            var _this = tab ? elements.find('a[' + $this.opts.attribute + '=' + tab +']').parent() : $(this);

            _this.trigger('_before');

            elements.removeClass('active');
            _this.addClass('active');
            _tabs.hide();

            i = elements.index(_this);

            var currentTab = tab || _this.find('a').attr($this.opts.attribute);

            if ($this.opts.deeplinking) location.hash = currentTab;

            if ($this.opts.animation) {

              _container.find(currentTab).animate( { opacity: 'show' }, 'slow', function() {
                _this.trigger('_after');
              });

            } else {

              _container.find(currentTab).show();
              _this.trigger('_after');

            }

            return false;

          }

        );

        var init = eval("elements." + $this.opts.mouseevent + "(fn)");

        init;

        var t;

        var forward = function() {

          i = ++i % elements.length; // wrap around

          $this.opts.mouseevent == 'hover' ? elements.eq(i).trigger('mouseover') : elements.eq(i).click();

          if ($this.opts.autorotate) {

            clearTimeout(t);

            t = setTimeout(forward, $this.opts.delay);

            $this.mouseover(function () {

              if ($this.opts.pauseonhover) clearTimeout(t);

            });

          }

        }

        if ($this.opts.autorotate) {

          t = setTimeout(forward, $this.opts.delay);

          $this.hover(function() {

            if ($this.opts.pauseonhover) clearTimeout(t);

          }, function() {

            t = setTimeout(forward, $this.opts.delay);

          });

          if ($this.opts.pauseonhover) $this.on( "mouseleave", function() { clearTimeout(t); t = setTimeout(forward, $this.opts.delay); });

        }

        var deep_link = function() {

          var ids = [];

          elements.find('a').each(function() { ids.push($(this).attr($this.opts.attribute)); });

          var index = $.inArray(location.hash, ids)

          if (index > -1) {

            return index + 1

          } else {

            return ($this.data('active') || options.active)

          }

        }

        var move = function(direction) {

          if (direction == 'forward') i = ++i % elements.length; // wrap around

          if (direction == 'backward') i = --i % elements.length; // wrap around

          elements.eq(i).click();

        }

        $this.find(options.controls.next).click(function() {
          move('forward');
        });

        $this.find(options.controls.prev).click(function() {
          move('backward');
        });

        $this.on ('show', function(e, tab) {
          fn(e, tab);
        });

        $this.on ('next', function() {
          move('forward');
        });

        $this.on ('prev', function() {
          move('backward');
        });

        $this.on ('destroy', function() {
          $(this)
            .removeData()
            .find('> ul li').each( function(i) {
              $(this).removeClass('active');
            });
          _tabs.each( function(i) {
            $(this).removeAttr('style').css( 'display', _cache_div[i] );
          });
        });

      }

    });

  };

  $(document).ready(function () { $('[data-toggle="tabslet"]').tabslet(); });

})(jQuery);
<|endoftext|>


<commit_before>'use strict';

const fs = require('fs-extra');
const os = require('os');
const path = require('path');
const spawnSync = require('./spawn-sync');
const template = require('lodash.template');

const CONFIG = require('../config');

module.exports = function(packagedAppPath) {
  console.log(`Creating Debian package for "${packagedAppPath}"`);
  const atomExecutableName =
    CONFIG.channel === 'stable' ? 'atom' : `atom-${CONFIG.channel}`;
  const apmExecutableName =
    CONFIG.channel === 'stable' ? 'apm' : `apm-${CONFIG.channel}`;
  const appDescription = CONFIG.appMetadata.description;
  const appVersion = CONFIG.appMetadata.version;
  let arch;
  if (process.arch === 'ia32') {
    arch = 'i386';
  } else if (process.arch === 'x64') {
    arch = 'amd64';
  } else if (process.arch === 'ppc') {
    arch = 'powerpc';
  } else {
    arch = process.arch;
  }

  const outputDebianPackageFilePath = path.join(
    CONFIG.buildOutputPath,
    `atom-${arch}.deb`
  );
  const debianPackageDirPath = path.join(
    os.tmpdir(),
    path.basename(packagedAppPath)
  );
  const debianPackageConfigPath = path.join(debianPackageDirPath, 'DEBIAN');
  const debianPackageInstallDirPath = path.join(debianPackageDirPath, 'usr');
  const debianPackageBinDirPath = path.join(debianPackageInstallDirPath, 'bin');
  const debianPackageShareDirPath = path.join(
    debianPackageInstallDirPath,
    'share'
  );
  const debianPackageAtomDirPath = path.join(
    debianPackageShareDirPath,
    atomExecutableName
  );
  const debianPackageApplicationsDirPath = path.join(
    debianPackageShareDirPath,
    'applications'
  );
  const debianPackageIconsDirPath = path.join(
    debianPackageShareDirPath,
    'pixmaps'
  );
  const debianPackageLintianOverridesDirPath = path.join(
    debianPackageShareDirPath,
    'lintian',
    'overrides'
  );
  const debianPackageDocsDirPath = path.join(
    debianPackageShareDirPath,
    'doc',
    atomExecutableName
  );

  if (fs.existsSync(debianPackageDirPath)) {
    console.log(
      `Deleting existing build dir for Debian package at "${debianPackageDirPath}"`
    );
    fs.removeSync(debianPackageDirPath);
  }
  if (fs.existsSync(`${debianPackageDirPath}.deb`)) {
    console.log(
      `Deleting existing Debian package at "${debianPackageDirPath}.deb"`
    );
    fs.removeSync(`${debianPackageDirPath}.deb`);
  }
  if (fs.existsSync(debianPackageDirPath)) {
    console.log(
      `Deleting existing Debian package at "${outputDebianPackageFilePath}"`
    );
    fs.removeSync(debianPackageDirPath);
  }

  console.log(
    `Creating Debian package directory structure at "${debianPackageDirPath}"`
  );
  fs.mkdirpSync(debianPackageDirPath);
  fs.mkdirpSync(debianPackageConfigPath);
  fs.mkdirpSync(debianPackageInstallDirPath);
  fs.mkdirpSync(debianPackageShareDirPath);
  fs.mkdirpSync(debianPackageApplicationsDirPath);
  fs.mkdirpSync(debianPackageIconsDirPath);
  fs.mkdirpSync(debianPackageLintianOverridesDirPath);
  fs.mkdirpSync(debianPackageDocsDirPath);
  fs.mkdirpSync(debianPackageBinDirPath);

  console.log(`Copying "${packagedAppPath}" to "${debianPackageAtomDirPath}"`);
  fs.copySync(packagedAppPath, debianPackageAtomDirPath);
  fs.chmodSync(debianPackageAtomDirPath, '755');

  console.log(`Copying binaries into "${debianPackageBinDirPath}"`);
  fs.copySync(
    path.join(CONFIG.repositoryRootPath, 'atom.sh'),
    path.join(debianPackageBinDirPath, atomExecutableName)
  );
  fs.symlinkSync(
    path.join(
      '..',
      'share',
      atomExecutableName,
      'resources',
      'app',
      'apm',
      'node_modules',
      '.bin',
      'apm'
    ),
    path.join(debianPackageBinDirPath, apmExecutableName)
  );

  console.log(`Writing control file into "${debianPackageConfigPath}"`);
  const packageSizeInKilobytes = spawnSync('du', ['-sk', packagedAppPath])
    .stdout.toString()
    .split(/\s+/)[0];
  const controlFileTemplate = fs.readFileSync(
    path.join(
      CONFIG.repositoryRootPath,
      'resources',
      'linux',
      'debian',
      'control.in'
    )
  );
  const controlFileContents = template(controlFileTemplate)({
    appFileName: atomExecutableName,
    version: appVersion,
    arch: arch,
    installedSize: packageSizeInKilobytes,
    description: appDescription
  });
  fs.writeFileSync(
    path.join(debianPackageConfigPath, 'control'),
    controlFileContents
  );

  console.log(
    `Writing desktop entry file into "${debianPackageApplicationsDirPath}"`
  );
  const desktopEntryTemplate = fs.readFileSync(
    path.join(
      CONFIG.repositoryRootPath,
      'resources',
      'linux',
      'atom.desktop.in'
    )
  );
  const desktopEntryContents = template(desktopEntryTemplate)({
    appName: CONFIG.appName,
    appFileName: atomExecutableName,
    description: appDescription,
    installDir: '/usr',
    iconPath: atomExecutableName
  });
  fs.writeFileSync(
    path.join(
      debianPackageApplicationsDirPath,
      `${atomExecutableName}.desktop`
    ),
    desktopEntryContents
  );

  console.log(`Copying icon into "${debianPackageIconsDirPath}"`);
  fs.copySync(
    path.join(
      packagedAppPath,
      'resources',
      'app.asar.unpacked',
      'resources',
      'atom.png'
    ),
    path.join(debianPackageIconsDirPath, `${atomExecutableName}.png`)
  );

  console.log(`Copying license into "${debianPackageDocsDirPath}"`);
  fs.copySync(
    path.join(packagedAppPath, 'resources', 'LICENSE.md'),
    path.join(debianPackageDocsDirPath, 'copyright')
  );

  console.log(
    `Copying lintian overrides into "${debianPackageLintianOverridesDirPath}"`
  );
  fs.copySync(
    path.join(
      CONFIG.repositoryRootPath,
      'resources',
      'linux',
      'debian',
      'lintian-overrides'
    ),
    path.join(debianPackageLintianOverridesDirPath, atomExecutableName)
  );

  console.log(
    `Copying polkit configuration into "${debianPackageShareDirPath}"`
  );
  fs.copySync(
    path.join(CONFIG.repositoryRootPath, 'resources', 'linux', 'atom.policy'),
    path.join(
      debianPackageShareDirPath,
      'polkit-1',
      'actions',
      `atom-${CONFIG.channel}.policy`
    )
  );

  console.log(`Generating .deb file from ${debianPackageDirPath}`);
  spawnSync('fakeroot', ['dpkg-deb', '-b', debianPackageDirPath], {
    stdio: 'inherit'
  });

  console.log(
    `Copying generated package into "${outputDebianPackageFilePath}"`
  );
  fs.copySync(`${debianPackageDirPath}.deb`, outputDebianPackageFilePath);
};
<commit_msg>Add debugging code to `create-debian-package.js`<commit_after>'use strict';

const fs = require('fs-extra');
const os = require('os');
const path = require('path');
const spawnSync = require('./spawn-sync');
const template = require('lodash.template');

const CONFIG = require('../config');

module.exports = function(packagedAppPath) {
  console.log(`Creating Debian package for "${packagedAppPath}"`);
  const atomExecutableName =
    CONFIG.channel === 'stable' ? 'atom' : `atom-${CONFIG.channel}`;
  const apmExecutableName =
    CONFIG.channel === 'stable' ? 'apm' : `apm-${CONFIG.channel}`;
  const appDescription = CONFIG.appMetadata.description;
  const appVersion = CONFIG.appMetadata.version;
  let arch;
  if (process.arch === 'ia32') {
    arch = 'i386';
  } else if (process.arch === 'x64') {
    arch = 'amd64';
  } else if (process.arch === 'ppc') {
    arch = 'powerpc';
  } else {
    arch = process.arch;
  }

  const outputDebianPackageFilePath = path.join(
    CONFIG.buildOutputPath,
    `atom-${arch}.deb`
  );
  const debianPackageDirPath = path.join(
    os.tmpdir(),
    path.basename(packagedAppPath)
  );
  const debianPackageConfigPath = path.join(debianPackageDirPath, 'DEBIAN');
  const debianPackageInstallDirPath = path.join(debianPackageDirPath, 'usr');
  const debianPackageBinDirPath = path.join(debianPackageInstallDirPath, 'bin');
  const debianPackageShareDirPath = path.join(
    debianPackageInstallDirPath,
    'share'
  );
  const debianPackageAtomDirPath = path.join(
    debianPackageShareDirPath,
    atomExecutableName
  );
  const debianPackageApplicationsDirPath = path.join(
    debianPackageShareDirPath,
    'applications'
  );
  const debianPackageIconsDirPath = path.join(
    debianPackageShareDirPath,
    'pixmaps'
  );
  const debianPackageLintianOverridesDirPath = path.join(
    debianPackageShareDirPath,
    'lintian',
    'overrides'
  );
  const debianPackageDocsDirPath = path.join(
    debianPackageShareDirPath,
    'doc',
    atomExecutableName
  );

  if (fs.existsSync(debianPackageDirPath)) {
    console.log(
      `Deleting existing build dir for Debian package at "${debianPackageDirPath}"`
    );
    fs.removeSync(debianPackageDirPath);
  }
  if (fs.existsSync(`${debianPackageDirPath}.deb`)) {
    console.log(
      `Deleting existing Debian package at "${debianPackageDirPath}.deb"`
    );
    fs.removeSync(`${debianPackageDirPath}.deb`);
  }
  if (fs.existsSync(debianPackageDirPath)) {
    console.log(
      `Deleting existing Debian package at "${outputDebianPackageFilePath}"`
    );
    fs.removeSync(debianPackageDirPath);
  }

  console.log(
    `Creating Debian package directory structure at "${debianPackageDirPath}"`
  );
  fs.mkdirpSync(debianPackageDirPath);
  fs.mkdirpSync(debianPackageConfigPath);
  fs.mkdirpSync(debianPackageInstallDirPath);
  fs.mkdirpSync(debianPackageShareDirPath);
  fs.mkdirpSync(debianPackageApplicationsDirPath);
  fs.mkdirpSync(debianPackageIconsDirPath);
  fs.mkdirpSync(debianPackageLintianOverridesDirPath);
  fs.mkdirpSync(debianPackageDocsDirPath);
  fs.mkdirpSync(debianPackageBinDirPath);

  console.log(`Copying "${packagedAppPath}" to "${debianPackageAtomDirPath}"`);
  fs.copySync(packagedAppPath, debianPackageAtomDirPath);
  fs.chmodSync(debianPackageAtomDirPath, '755');

  console.log(`Copying binaries into "${debianPackageBinDirPath}"`);
  fs.copySync(
    path.join(CONFIG.repositoryRootPath, 'atom.sh'),
    path.join(debianPackageBinDirPath, atomExecutableName)
  );
  fs.symlinkSync(
    path.join(
      '..',
      'share',
      atomExecutableName,
      'resources',
      'app',
      'apm',
      'node_modules',
      '.bin',
      'apm'
    ),
    path.join(debianPackageBinDirPath, apmExecutableName)
  );

  try {
    fs.chmodSync(
      path.join(
        debianPackageAtomDirPath,
        'chrome-sandbox'
      ),
      '4755'
    );
  } catch (ex) {
    console.log('Chmod failed');

    spawnSync('find', [debianPackageDirPath, '-name', 'chrome-sandbox'], {
      stdio: 'inherit',
    });
  }

  console.log(`Writing control file into "${debianPackageConfigPath}"`);
  const packageSizeInKilobytes = spawnSync('du', ['-sk', packagedAppPath])
    .stdout.toString()
    .split(/\s+/)[0];
  const controlFileTemplate = fs.readFileSync(
    path.join(
      CONFIG.repositoryRootPath,
      'resources',
      'linux',
      'debian',
      'control.in'
    )
  );
  const controlFileContents = template(controlFileTemplate)({
    appFileName: atomExecutableName,
    version: appVersion,
    arch: arch,
    installedSize: packageSizeInKilobytes,
    description: appDescription
  });
  fs.writeFileSync(
    path.join(debianPackageConfigPath, 'control'),
    controlFileContents
  );

  console.log(
    `Writing desktop entry file into "${debianPackageApplicationsDirPath}"`
  );
  const desktopEntryTemplate = fs.readFileSync(
    path.join(
      CONFIG.repositoryRootPath,
      'resources',
      'linux',
      'atom.desktop.in'
    )
  );
  const desktopEntryContents = template(desktopEntryTemplate)({
    appName: CONFIG.appName,
    appFileName: atomExecutableName,
    description: appDescription,
    installDir: '/usr',
    iconPath: atomExecutableName
  });
  fs.writeFileSync(
    path.join(
      debianPackageApplicationsDirPath,
      `${atomExecutableName}.desktop`
    ),
    desktopEntryContents
  );

  console.log(`Copying icon into "${debianPackageIconsDirPath}"`);
  fs.copySync(
    path.join(
      packagedAppPath,
      'resources',
      'app.asar.unpacked',
      'resources',
      'atom.png'
    ),
    path.join(debianPackageIconsDirPath, `${atomExecutableName}.png`)
  );

  console.log(`Copying license into "${debianPackageDocsDirPath}"`);
  fs.copySync(
    path.join(packagedAppPath, 'resources', 'LICENSE.md'),
    path.join(debianPackageDocsDirPath, 'copyright')
  );

  console.log(
    `Copying lintian overrides into "${debianPackageLintianOverridesDirPath}"`
  );
  fs.copySync(
    path.join(
      CONFIG.repositoryRootPath,
      'resources',
      'linux',
      'debian',
      'lintian-overrides'
    ),
    path.join(debianPackageLintianOverridesDirPath, atomExecutableName)
  );

  console.log(
    `Copying polkit configuration into "${debianPackageShareDirPath}"`
  );
  fs.copySync(
    path.join(CONFIG.repositoryRootPath, 'resources', 'linux', 'atom.policy'),
    path.join(
      debianPackageShareDirPath,
      'polkit-1',
      'actions',
      `atom-${CONFIG.channel}.policy`
    )
  );

  console.log(`Generating .deb file from ${debianPackageDirPath}`);
  spawnSync('fakeroot', ['dpkg-deb', '-b', debianPackageDirPath], {
    stdio: 'inherit'
  });

  console.log(
    `Copying generated package into "${outputDebianPackageFilePath}"`
  );
  fs.copySync(`${debianPackageDirPath}.deb`, outputDebianPackageFilePath);
};
<|endoftext|>


<commit_before>/* global describe, it, window, document, dusk, _duskImmediateSelect,
   _duskReadySelect, before, after, $ */
/* eslint func-names: 0, prefer-arrow-callback: 0, no-console: 0, no-var: 0
   prefer-template: 0 */

function err() { throw new Error(); }

describe('Dusk', function () {

  it('should exist and be a function', function () {
    if (typeof dusk !== 'function') err();
  });

  it('should accept 0 arguments', function () {
    if (dusk().constructor !== Array || dusk().length !== 0) {
      err();
    }
  });

  it('should accept \'\', null, undefined and true|false as arguments', function () {
    if (dusk('').constructor !== Array || dusk('').length !== 0) {
      err();
    }
    if (dusk(null).constructor !== Array || dusk(null).length !== 0) {
      err();
    }
    if (dusk(undefined).constructor !== Array || dusk(undefined).length !== 0) {
      err();
    }
    if (dusk(true).constructor !== Array || dusk(true).length !== 0) {
      err();
    }
    if (dusk(false).constructor !== Array || dusk(false).length !== 0) {
      err();
    }
  });

  it('should create a new instance every time it is called', function () {
    const $dusk1 = dusk();
    const $dusk2 = dusk();
    if ($dusk1 === $dusk2) {
      err();
    }
  });

  it('should fail to select before DOMReady', function () {
    if (_duskImmediateSelect.length !== 0) err();
  });

});

describe('dusk.DOMReady', function () {

  it('should run if attached before DOMReady', function () {
    if (_duskReadySelect.length !== 1) err();
  });

  it('should run if attached after DOMReady', function (done) {
    this.timeout(4000);
    // Window already loaded?
    if (document.readyState === 'complete') {
      setTimeout(function () {
        // eslint-disable-next-line new-cap
        dusk.DOMReady(done);
      }, 100);
    } else {
      window.addEventListener('load', function () {
        // eslint-disable-next-line new-cap
        dusk.DOMReady(done);
      });
    }
  });

});

describe('dusk()', function () {

  it('should select by id', function () {
    if (dusk('#demo').length !== 1) err();
  });

  it('should select by class', function () {
    if (dusk('.demo').length !== 1) err();
  });

  it('should select by tag', function () {
    if (dusk('body').length !== 1) err();
  });

  it('should select with css', function () {
    if (dusk('[id=demo]').length !== 1) err();
    if (dusk('body .demo').length !== 1) err();
  });

  it('should select a node', function () {
    if (dusk(document.querySelector('div')).length !== 1) err();
    if (dusk(document.getElementById('demo')).length !== 1) err();
  });

  it('should select window', function () {
    if (dusk(window)[0] !== window) err();
  });

  it('should select an HTMLCollection or a NodeList', function () {

    const collection = document.getElementsByTagName('div');
    if (
      dusk(collection).length !== collection.length
      || dusk(collection)[0] !== collection[0]
    ) {
      err();
    }

    const list = document.querySelectorAll('div');
    if (
      dusk(list).length !== list.length
      || dusk(list)[0] !== list[0]
    ) {
      err();
    }

  });

  it('should select itself', function () {
    const $dusked = dusk('#demo');
    if (dusk($dusked).length !== 1) err();
    if (dusk($dusked) !== $dusked) err();
  });

  it('should select with a context', function () {
    if (dusk('div', '.demo').length !== 3) err();
    if (dusk('div', '#demo').length !== 3) err();
    if (dusk('div', 'body .demo').length !== 3) err();
    if (dusk('div', dusk('#demo')).length !== 3) err();
  });

  it('should return an empty array if no element matched', function () {
    if (dusk('#nonexisting-id').length !== 0) err();
    if (dusk('nonexisting-tag').length !== 0) err();
    if (dusk('.nonexisting-class').length !== 0) err();
    if (dusk('.nonexisting .selector').length !== 0) err();
  });

  it('should return an empty array if wrong context is passed', function () {
    if (dusk('div', '#nonexisting-id').length !== 0) err();
    if (dusk('div', 'nonexisting-tag').length !== 0) err();
    if (dusk('div', '.nonexisting-class').length !== 0) err();
    if (dusk('div', '.nonexisting .selector').length !== 0) err();
  });

  it('should be able to be extended (plugins)', function (done) {
    const $demo = dusk('#demo');
    dusk.fn.plugin = function () {
      if ($demo === this) done();
      else err();
    };
    $demo.plugin();
  });

  it('should be able to be chain-extended (plugins return this)', function (done) {
    const $demo = dusk('#demo');
    dusk.fn.plugin1 = function () {
      return this;
    };
    dusk.fn.plugin2 = function () {
      if ($demo === this) done();
      else err();
    };
    $demo.plugin1().plugin2();
  });

});

describe('.-––~^performance', function () {

  var $perf;

  function performance(callback, times) {
    const init = new Date().getTime();
    var j;
    for (j = 0; j < times; j++) {
      callback(j);
    }
    return new Date().getTime() - init;
  }

  function compare(performance1, performance2, times) {
    const result = { a: 0, b: 0 };
    var i;
    for (i = 0; i < 10; i++) {
      if (i % 2) {
        result.a += performance(performance1, times);
        result.b += performance(performance2, times);
      } else {
        result.b += performance(performance2, times);
        result.a += performance(performance1, times);
      }
    }
    return result;
  }

  // Generate a big and varied 1000 elements table
  before(function () {
    $perf = dusk('.performance')[0];
    performance(function (i) {
      $perf.innerHTML += '
' +
        '				' +
        '
';
    }, 1000);
  });

  after(function () {
    $perf.parentNode.removeChild($perf);
  });

  it('should select, fast (by class, 10k/s)', function () {
    const dTime = performance(function () {
      dusk('.demo');
    }, 1000);
    console.log('[perf] by class 10k/s     - dusk: ' + dTime + 'ms');
    if (dTime > 100) err();
  });

  it('should be comparable or faster than $(\'#id\')', function () {
    const result = compare(function () {
      dusk('#demo');
    }, function () {
      $('#demo');
    }, 1000);
    const dTime = result.a;
    const $Time = result.b;
    console.log('[perf] vs jQuery #id      - dusk: ' + dTime + 'ms; $: ' + $Time + 'ms');
    if (dTime > $Time) err();
  });

  it('should be comparable or faster than $(\'tag\')', function () {
    const result = compare(function () {
      dusk('div');
    }, function () {
      $('div');
    }, 1000);
    const dTime = result.a;
    const $Time = result.b;
    console.log('[perf] vs jQuery tag      - dusk: ' + dTime + 'ms; $: ' + $Time + 'ms');
    if (dTime > $Time) err();
  });

  it('should be comparable or faster than $(\'.class\')', function () {
    const result = compare(function () {
      dusk('.demo');
    }, function () {
      $('.demo');
    }, 1000);
    const dTime = result.a;
    const $Time = result.b;
    console.log('[perf] vs jQuery .class   - dusk: ' + dTime + 'ms; $: ' + $Time + 'ms');
    if (dTime > $Time) err();
  });

  it('should be comparable or faster than $(\'table td:first-child\')', function () {
    const result = compare(function () {
      dusk('table td:first-child');
    }, function () {
      $('table td:first-child');
    }, 1000);
    const dTime = result.a;
    const $Time = result.b;
    console.log('[perf] vs jQuery complex  - dusk: ' + dTime + 'ms; $: ' + $Time + 'ms');
    if (dTime > $Time) err();
  });

});
<commit_msg>performance test tolerance<commit_after>/* global describe, it, window, document, dusk, _duskImmediateSelect,
   _duskReadySelect, before, after, $ */
/* eslint func-names: 0, prefer-arrow-callback: 0, no-console: 0, no-var: 0
   prefer-template: 0 */

function err() { throw new Error(); }

describe('Dusk', function () {

  it('should exist and be a function', function () {
    if (typeof dusk !== 'function') err();
  });

  it('should accept 0 arguments', function () {
    if (dusk().constructor !== Array || dusk().length !== 0) {
      err();
    }
  });

  it('should accept \'\', null, undefined and true|false as arguments', function () {
    if (dusk('').constructor !== Array || dusk('').length !== 0) {
      err();
    }
    if (dusk(null).constructor !== Array || dusk(null).length !== 0) {
      err();
    }
    if (dusk(undefined).constructor !== Array || dusk(undefined).length !== 0) {
      err();
    }
    if (dusk(true).constructor !== Array || dusk(true).length !== 0) {
      err();
    }
    if (dusk(false).constructor !== Array || dusk(false).length !== 0) {
      err();
    }
  });

  it('should create a new instance every time it is called', function () {
    const $dusk1 = dusk();
    const $dusk2 = dusk();
    if ($dusk1 === $dusk2) {
      err();
    }
  });

  it('should fail to select before DOMReady', function () {
    if (_duskImmediateSelect.length !== 0) err();
  });

});

describe('dusk.DOMReady', function () {

  it('should run if attached before DOMReady', function () {
    if (_duskReadySelect.length !== 1) err();
  });

  it('should run if attached after DOMReady', function (done) {
    this.timeout(4000);
    // Window already loaded?
    if (document.readyState === 'complete') {
      setTimeout(function () {
        // eslint-disable-next-line new-cap
        dusk.DOMReady(done);
      }, 100);
    } else {
      window.addEventListener('load', function () {
        // eslint-disable-next-line new-cap
        dusk.DOMReady(done);
      });
    }
  });

});

describe('dusk()', function () {

  it('should select by id', function () {
    if (dusk('#demo').length !== 1) err();
  });

  it('should select by class', function () {
    if (dusk('.demo').length !== 1) err();
  });

  it('should select by tag', function () {
    if (dusk('body').length !== 1) err();
  });

  it('should select with css', function () {
    if (dusk('[id=demo]').length !== 1) err();
    if (dusk('body .demo').length !== 1) err();
  });

  it('should select a node', function () {
    if (dusk(document.querySelector('div')).length !== 1) err();
    if (dusk(document.getElementById('demo')).length !== 1) err();
  });

  it('should select window', function () {
    if (dusk(window)[0] !== window) err();
  });

  it('should select an HTMLCollection or a NodeList', function () {

    const collection = document.getElementsByTagName('div');
    if (
      dusk(collection).length !== collection.length
      || dusk(collection)[0] !== collection[0]
    ) {
      err();
    }

    const list = document.querySelectorAll('div');
    if (
      dusk(list).length !== list.length
      || dusk(list)[0] !== list[0]
    ) {
      err();
    }

  });

  it('should select itself', function () {
    const $dusked = dusk('#demo');
    if (dusk($dusked).length !== 1) err();
    if (dusk($dusked) !== $dusked) err();
  });

  it('should select with a context', function () {
    if (dusk('div', '.demo').length !== 3) err();
    if (dusk('div', '#demo').length !== 3) err();
    if (dusk('div', 'body .demo').length !== 3) err();
    if (dusk('div', dusk('#demo')).length !== 3) err();
  });

  it('should return an empty array if no element matched', function () {
    if (dusk('#nonexisting-id').length !== 0) err();
    if (dusk('nonexisting-tag').length !== 0) err();
    if (dusk('.nonexisting-class').length !== 0) err();
    if (dusk('.nonexisting .selector').length !== 0) err();
  });

  it('should return an empty array if wrong context is passed', function () {
    if (dusk('div', '#nonexisting-id').length !== 0) err();
    if (dusk('div', 'nonexisting-tag').length !== 0) err();
    if (dusk('div', '.nonexisting-class').length !== 0) err();
    if (dusk('div', '.nonexisting .selector').length !== 0) err();
  });

  it('should be able to be extended (plugins)', function (done) {
    const $demo = dusk('#demo');
    dusk.fn.plugin = function () {
      if ($demo === this) done();
      else err();
    };
    $demo.plugin();
  });

  it('should be able to be chain-extended (plugins return this)', function (done) {
    const $demo = dusk('#demo');
    dusk.fn.plugin1 = function () {
      return this;
    };
    dusk.fn.plugin2 = function () {
      if ($demo === this) done();
      else err();
    };
    $demo.plugin1().plugin2();
  });

});

describe('.-––~^ performance', function () {

  var $perf;

  function performance(callback, times) {
    const init = new Date().getTime();
    var j;
    for (j = 0; j < times; j++) {
      callback(j);
    }
    return new Date().getTime() - init;
  }

  function compare(performance1, performance2, times) {
    const result = { a: 0, b: 0 };
    var i;
    for (i = 0; i < 10; i++) {
      if (i % 2) {
        result.a += performance(performance1, times);
        result.b += performance(performance2, times);
      } else {
        result.b += performance(performance2, times);
        result.a += performance(performance1, times);
      }
    }
    return result;
  }

  // Generate a big and varied 1000 elements table
  before(function () {
    $perf = dusk('.performance')[0];
    performance(function (i) {
      $perf.innerHTML += '
' +
        '				' +
        '
';
    }, 1000);
  });

  after(function () {
    $perf.parentNode.removeChild($perf);
  });

  it('should select, fast (by class, 10k/s)', function () {
    const dTime = performance(function () {
      dusk('.demo');
    }, 1000);
    console.log('[perf] by class 10k/s     - dusk: ' + dTime + 'ms');
    if (dTime > 100) err();
  });

  it('should be comparable or faster than $(\'#id\')', function () {
    const result = compare(function () {
      dusk('#demo');
    }, function () {
      $('#demo');
    }, 1000);
    const dTime = result.a;
    const $Time = result.b;
    console.log('[perf] vs jQuery #id      - dusk: ' + dTime + 'ms; $: ' + $Time + 'ms');
    if (dTime > $Time * 1.1) err();
  });

  it('should be comparable or faster than $(\'tag\')', function () {
    const result = compare(function () {
      dusk('div');
    }, function () {
      $('div');
    }, 1000);
    const dTime = result.a;
    const $Time = result.b;
    console.log('[perf] vs jQuery tag      - dusk: ' + dTime + 'ms; $: ' + $Time + 'ms');
    if (dTime > $Time * 1.1) err();
  });

  it('should be comparable or faster than $(\'.class\')', function () {
    const result = compare(function () {
      dusk('.demo');
    }, function () {
      $('.demo');
    }, 1000);
    const dTime = result.a;
    const $Time = result.b;
    console.log('[perf] vs jQuery .class   - dusk: ' + dTime + 'ms; $: ' + $Time + 'ms');
    if (dTime > $Time * 1.1) err();
  });

  it('should be comparable or faster than $(\'table td:first-child\')', function () {
    const result = compare(function () {
      dusk('table td:first-child');
    }, function () {
      $('table td:first-child');
    }, 1000);
    const dTime = result.a;
    const $Time = result.b;
    console.log('[perf] vs jQuery complex  - dusk: ' + dTime + 'ms; $: ' + $Time + 'ms');
    if (dTime > $Time * 1.1) err();
  });

});
<|endoftext|>


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

    function Boot() {
    }

    Boot.prototype.preload = function() {

        // Load animations before game start
        game.load.json('preload-loading-icon',
            'assets/img/preload/loading-icon.json');

        game.load.json('preload-game-name',
            'assets/img/preload/game-name.json');

        // configure game
        if (game.device.desktop) {
            game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
            game.scale.pageAlignHorizontally = true;
            game.scale.pageAlignVertically = true;
        } else {
            game.scale.scaleMode = Phaser.ScaleManager.RESIZE;
            game.scale.minWidth = 480;
            game.scale.minHeight = 260;
            game.scale.maxWidth = 640;
            game.scale.maxHeight = 480;
            // game.scale.forceOrientation(true);
            game.scale.pageAlignHorizontally = true;
            game.scale.refresh();
        }

        alert("version: 0.1");
    };

    Boot.prototype.create = function() {
        game.state.start('ladingScreen');
    }

    window['CountryLife'] = window['CountryLife'] || {};
    window['CountryLife'].Boot = Boot;
}());
<commit_msg>Update Boot.js<commit_after>(function() {
    'use strict';

    function Boot() {
    }

    Boot.prototype.preload = function() {

        // Load animations before game start
        game.load.json('preload-loading-icon',
            'assets/img/preload/loading-icon.json');

        game.load.json('preload-game-name',
            'assets/img/preload/game-name.json');

        // configure game
        if (game.device.desktop) {
            game.scale.scaleMode = Phaser.ScaleManager.SHOW_ALL;
            game.scale.pageAlignHorizontally = true;
            game.scale.pageAlignVertically = true;
        } else {
            game.scale.scaleMode = Phaser.ScaleManager.RESIZE;
            game.scale.minWidth = 480;
            game.scale.minHeight = 260;
            game.scale.maxWidth = 640;
            game.scale.maxHeight = 480;
            // game.scale.forceOrientation(true);
            // game.scale.pageAlignHorizontally = true;
            game.scale.refresh();
        }

        alert("version: 0.2");
    };

    Boot.prototype.create = function() {
        game.state.start('ladingScreen');
    }

    window['CountryLife'] = window['CountryLife'] || {};
    window['CountryLife'].Boot = Boot;
}());
<|endoftext|>