<commit_before>(function (clique, Hashes, _, Backbone) {
    "use strict";

    clique.util = {};

    clique.util.md5 = (function () {
        var md5 = new Hashes.MD5();

        return function (s) {
            return md5.hex(s);
        };
    }());

    clique.util.linkHash = function (link) {
        var source,
            target;

        source = link.source;
        if (!_.isString(source)) {
            source = source.key;
        }

        target = link.target;
        if (!_.isString(target)) {
            target = target.key;
        }

        return JSON.stringify([source, target]);
    };

    clique.util.deepCopy = function (o) {
        if (_.isUndefined(o)) {
            return undefined;
        }
        return JSON.parse(JSON.stringify(o));
    };

    clique.util.concat = function () {
        var lists = _.toArray(arguments);
        return _.reduce(lists, function (a, b) {
            return a.concat(b);
        }, []);
    };

    clique.util.jqSequence = function (reqs) {
        var helper,
            chain;

        helper = function (reqs, accum, i) {
            if (i === _.size(reqs)) {
                return accum;
            } else {
                accum = accum.then(function () {
                    return reqs[i];
                });

                return helper(reqs, accum, i+1);
            }
        };

        chain = Backbone.$.Deferred();
        chain.resolve();

        return helper(reqs, chain, 0);
    };

    clique.util.Set = function () {
        var items = {};

        return {
            add: function (item) {
                items[item] = null;
            },

            remove: function (item) {
                delete items[item];
            },

            has: function (item) {
                return _.has(items, item);
            },

            items: function (mapper) {
                var stuff = _.keys(items);
                if (mapper) {
                    stuff = _.map(stuff, mapper);
                }
                return stuff;
            },

            size: function () {
                return _.size(items);
            }
        };
    };

    clique.util.MultiTable = function () {
        var table = {};

        return {
            add: function (key, item) {
                if (!_.has(table, key)) {
                    table[key] = new clique.util.Set();
                }

                table[key].add(item);
            },

            remove: function (key, item) {
                if (_.has(table, key)) {
                    table[key].remove(item);
                }
            },

            strike: function (key) {
                delete table[key];
            },

            has: function (key, item) {
                return _.has(table, key) && (_.isUndefined(item) || table[key].has(item));
            },

            items: function (key) {
                if (_.has(table, key)) {
                    return table[key].items();
                }
            }
        };
    };

    clique.util.require = function (arg, name) {
        if (_.isUndefined(arg)) {
            throw new Error("argument '" + name + "' is required");
        }
    };

    clique.util.Accessor = function (target) {
        var disallowed = new clique.util.Set();

        target.data = target.data || {};

        _.each(["key", "source", "target"], function (d) {
            disallowed.add(d);
        });

        return _.extend({
            key: function () {
                return target.key;
            },

            source: function () {
                return target.source.key || target.source;
            },

            target: function () {
                return target.target.key || target.target;
            },

            getAttribute: function (prop) {
                if (disallowed.has(prop)) {
                    return;
                }
                return target[prop];
            },

            setAttribute: function (prop, value) {
                if (disallowed.has(prop)) {
                    return false;
                }

                target[prop] = value;
                return true;
            },

            clearAttribute: function (prop) {
                if (disallowed.has(prop)) {
                    return false;
                }

                delete target[prop];
                return true;
            },

            getAllData: function () {
                return _.pairs(target.data);
            },

            getData: function (prop) {
                return target.data[prop];
            },

            setData: function (prop, value) {
                target.data[prop] = value;
                this.trigger("changed", this, prop, value);
            },

            clearData: function (prop) {
                delete target.data[prop];
                this.trigger("cleared", this, prop);
            },

            getTarget: function () {
                return target;
            }
        }, Backbone.Events);
    };
}(window.clique, window.Hashes, window._, window.Backbone));
<commit_msg>Adding better choices than "getAllData()"<commit_after>(function (clique, Hashes, _, Backbone) {
    "use strict";

    clique.util = {};

    clique.util.md5 = (function () {
        var md5 = new Hashes.MD5();

        return function (s) {
            return md5.hex(s);
        };
    }());

    clique.util.linkHash = function (link) {
        var source,
            target;

        source = link.source;
        if (!_.isString(source)) {
            source = source.key;
        }

        target = link.target;
        if (!_.isString(target)) {
            target = target.key;
        }

        return JSON.stringify([source, target]);
    };

    clique.util.deepCopy = function (o) {
        if (_.isUndefined(o)) {
            return undefined;
        }
        return JSON.parse(JSON.stringify(o));
    };

    clique.util.concat = function () {
        var lists = _.toArray(arguments);
        return _.reduce(lists, function (a, b) {
            return a.concat(b);
        }, []);
    };

    clique.util.jqSequence = function (reqs) {
        var helper,
            chain;

        helper = function (reqs, accum, i) {
            if (i === _.size(reqs)) {
                return accum;
            } else {
                accum = accum.then(function () {
                    return reqs[i];
                });

                return helper(reqs, accum, i+1);
            }
        };

        chain = Backbone.$.Deferred();
        chain.resolve();

        return helper(reqs, chain, 0);
    };

    clique.util.Set = function () {
        var items = {};

        return {
            add: function (item) {
                items[item] = null;
            },

            remove: function (item) {
                delete items[item];
            },

            has: function (item) {
                return _.has(items, item);
            },

            items: function (mapper) {
                var stuff = _.keys(items);
                if (mapper) {
                    stuff = _.map(stuff, mapper);
                }
                return stuff;
            },

            size: function () {
                return _.size(items);
            }
        };
    };

    clique.util.MultiTable = function () {
        var table = {};

        return {
            add: function (key, item) {
                if (!_.has(table, key)) {
                    table[key] = new clique.util.Set();
                }

                table[key].add(item);
            },

            remove: function (key, item) {
                if (_.has(table, key)) {
                    table[key].remove(item);
                }
            },

            strike: function (key) {
                delete table[key];
            },

            has: function (key, item) {
                return _.has(table, key) && (_.isUndefined(item) || table[key].has(item));
            },

            items: function (key) {
                if (_.has(table, key)) {
                    return table[key].items();
                }
            }
        };
    };

    clique.util.require = function (arg, name) {
        if (_.isUndefined(arg)) {
            throw new Error("argument '" + name + "' is required");
        }
    };

    clique.util.Accessor = function (target) {
        var disallowed = new clique.util.Set();

        target.data = target.data || {};

        _.each(["key", "source", "target", "data"], function (d) {
            disallowed.add(d);
        });

        return _.extend({
            key: function () {
                return target.key;
            },

            source: function () {
                return target.source.key || target.source;
            },

            target: function () {
                return target.target.key || target.target;
            },

            getAttribute: function (prop) {
                if (disallowed.has(prop)) {
                    return;
                }
                return target[prop];
            },

            setAttribute: function (prop, value) {
                if (disallowed.has(prop)) {
                    return false;
                }

                target[prop] = value;
                return true;
            },

            clearAttribute: function (prop) {
                if (disallowed.has(prop)) {
                    return false;
                }

                delete target[prop];
                return true;
            },

            getAttributeObject: function () {
                var result = {};

                _.each(target, function (value, key) {
                    if (!disallowed.has(key)) {
                        result[key] = value;
                    }
                });

                return result;
            },

            getAllData: function () {
                return _.pairs(target.data);
            },

            getData: function (prop) {
                return target.data[prop];
            },

            setData: function (prop, value) {
                target.data[prop] = value;
                this.trigger("changed", this, prop, value);
            },

            clearData: function (prop) {
                delete target.data[prop];
                this.trigger("cleared", this, prop);
            },

            getDataObject: function () {
                var result = {};

                _.each(target.data, function (value, key) {
                    result[key] = value;
                });

                return result;
            },

            getTarget: function () {
                return target;
            }
        }, Backbone.Events);
    };
}(window.clique, window.Hashes, window._, window.Backbone));
<|endoftext|>


<commit_before>/* ========================================================================
 * ZUI: messager.js
 * http://zui.sexy
 * ========================================================================
 * Copyright (c) 2014-2016 cnezsoft.com; Licensed MIT
 * ======================================================================== */

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

    var id = 0;
    var template = '

';
    var defaultOptions = {
        type: 'default',
        placement: 'top',
        time: 4000,
        parent: 'body',
        // clear: false,
        icon: null,
        close: true,
        // actions: [{icon, name, action, title}],
        // contentClass: null,
        // cssClass: null,
        // onAction: function,
        fade: true,
        scale: true
    };
    var all = {};

    var Messager = function(message, options) {
        if($.isPlainObject(message)) {
            options = message;
            message = options.message;
        }

        var that = this;
        that.id = id++;
        options = that.options = $.extend({}, defaultOptions, options);
        that.message = (options.icon ? ' ' : '') + message;

        that.$ = $(template.format(options)).toggleClass('fade', options.fade).toggleClass('scale', options.scale).attr('id', 'messager-' + that.id);

        if(options.cssClass) that.$.addClass(options.cssClass);

        var hasCloseAction = false;
        var $actions = that.$.find('.messager-actions');
        var appendAction = function(action) {
            var $btn = $('<button type="button" class="action action-' + action.name + '"/>');
            if(action.name === 'close') $btn.addClass('close');
            if(action.html !== undefined) {
                $btn.html(action.html);
            }
            if(action.icon !== undefined) {
                $btn.append('');
            }
            if(action.text !== undefined) {
                $btn.append('' + action.text + '');
            }
            if(action.tooltip !== undefined) {
                $btn.attr('title', action.tooltip).tooltip();
            }
            $btn.data('action', action);
            $actions.append($btn);
        };
        if(options.actions) {
            $.each(options.actions, function(idx, action) {
                if(action.name === undefined) action.name = idx;
                if(action.name == 'close') hasCloseAction = true;
                appendAction(action);
            });
        }
        if(!hasCloseAction && options.close) {
            appendAction({name: 'close', html: '×'});
        }

        that.$.on('click', '.action', function(e) {
            var action = $(this).data('action'), result;
            if(options.onAction) {
                result = options.onAction.call(this, action.name, action, that);
                if(result === false) return;
            }
            if($.isFunction(action.action)) {
                result = action.action.call(this, that);
                if(result === false) return;
            }
            that.hide();
            e.stopPropagation();
        });

        that.$.on('click', function(e) {
            if(options.onAction) {
                result = options.onAction.call(this, 'content', null, that);
                if(result === true) that.hide();
            }
        });

        var $content = that.$.find('.messager-content').html(that.message);
        if(options.contentClass) $content.addClass(options.cssClass);

        that.$.data('zui.messager', that);

        if(options.show && that.message !== undefined) {
            that.show();
        }
    };

    Messager.prototype.update = function(message, newOptions) {
        var that = this;
        var options = that.options;
        that.$.removeClass('messager-' + options.type);
        if(newOptions) {
            options = $.extend(options, newOptions);
            that.$.addClass('messager-' + options.type);
        }
        if(message) {
            that.message = (options.icon ? ' ' : '') + message;
            that.$.find('.messager-content').html(that.message);
        }
    };

    Messager.prototype.show = function(message, callback) {
        var that = this,
            options = this.options;

        if(that.isShow) {
            that.hide(function() {
                that.show(message, callback);
            });
            return;
        }

        if(that.hiding) {
            clearTimeout(that.hiding);
            that.hiding = null;
        }

        if($.isFunction(message)) {
            var oldCallback = callback;
            callback = message;
            if(oldCallback !== undefined) {
                message = oldCallback;
            }
        }

        that.update(message);

        var placement = options.placement;
        var $parent = $(options.parent);
        var $holder = $parent.children('.messagers-holder.' + placement);
        if(!$holder.length) {
            $holder = $('
').attr('class', 'messagers-holder ' + placement).appendTo($parent);
        }
        $holder.append(that.$);
        if(placement === 'center') {
            var offset = $(window).height() - $holder.height();
            $holder.css('top', Math.max(-offset, offset/2));
        }

        that.$.show().addClass('in');

        if(options.time) {
            that.hiding = setTimeout(function() {
                that.hide();
            }, options.time);
        }

        that.isShow = true;
        callback && callback();
        return that;
    };

    Messager.prototype.hide = function(callback) {
        var that = this;
        if(that.$.hasClass('in')) {
            that.$.removeClass('in');
            setTimeout(function() {
                var $parent = that.$.parent();
                that.$.detach();
                if(!$parent.children().length) $parent.remove();
                callback && callback(true);
            }, 200);
        } else {
            callback && callback(false);
        }

        that.isShow = false;
    };

    Messager.prototype.destory = function() {
        that.$.remove();
        that.$ = null;
    };

    var showMessage = function(message, options) {
        if(typeof options === 'string') {
            options = {
                type: options
            };
        }
        var msg = new Messager(message, options);
        msg.show();
        return msg;
    };

    var hideMessage = function() {
        $('.messager').each(function() {
            var msg = $(this).data('zui.messager');
            if(msg && msg.hide) msg.hide();
        });
    };

    var getOptions = function(options) {
        return(typeof options === 'string') ? {
            placement: options
        } : options;
    };

    $.zui({
        Messager: Messager,
        showMessager: showMessage,
        messager: {
            show: showMessage,
            hide: hideMessage,
            primary: function(message, options) {
                return showMessage(message, $.extend({
                    type: 'primary'
                }, getOptions(options)));
            },
            success: function(message, options) {
                return showMessage(message, $.extend({
                    type: 'success',
                    icon: 'ok-sign'
                }, getOptions(options)));
            },
            info: function(message, options) {
                return showMessage(message, $.extend({
                    type: 'info',
                    icon: 'info-sign'
                }, getOptions(options)));
            },
            warning: function(message, options) {
                return showMessage(message, $.extend({
                    type: 'warning',
                    icon: 'warning-sign'
                }, getOptions(options)));
            },
            danger: function(message, options) {
                return showMessage(message, $.extend({
                    type: 'danger',
                    icon: 'exclamation-sign'
                }, getOptions(options)));
            },
            important: function(message, options) {
                return showMessage(message, $.extend({
                    type: 'important'
                }, getOptions(options)));
            },
            special: function(message, options) {
                return showMessage(message, $.extend({
                    type: 'special'
                }, getOptions(options)));
            }
        }
    });
}(jQuery, window, undefined));

<commit_msg> * improve messsager.<commit_after>/* ========================================================================
 * ZUI: messager.js
 * http://zui.sexy
 * ========================================================================
 * Copyright (c) 2014-2016 cnezsoft.com; Licensed MIT
 * ======================================================================== */

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

    var id = 0;
    var template = '

';
    var defaultOptions = {
        type: 'default',
        placement: 'top',
        time: 4000,
        parent: 'body',
        // clear: false,
        icon: null,
        close: true,
        // actions: [{icon, name, action, title}],
        // contentClass: null,
        // cssClass: null,
        // onAction: function,
        fade: true,
        scale: true
    };
    var all = {};

    var Messager = function(message, options) {
        if($.isPlainObject(message)) {
            options = message;
            message = options.message;
        }

        var that = this;
        that.id = options.id || (id++);
        var oldMessager = all[that.id];
        if(oldMessager) oldMessager.destory();
        all[that.id] = that;
        options = that.options = $.extend({}, defaultOptions, options);
        that.message = (options.icon ? ' ' : '') + message;

        that.$ = $(template.format(options)).toggleClass('fade', options.fade).toggleClass('scale', options.scale).attr('id', 'messager-' + that.id);

        if(options.cssClass) that.$.addClass(options.cssClass);

        var hasCloseAction = false;
        var $actions = that.$.find('.messager-actions');
        var appendAction = function(action) {
            var $btn = $('<button type="button" class="action action-' + action.name + '"/>');
            if(action.name === 'close') $btn.addClass('close');
            if(action.html !== undefined) {
                $btn.html(action.html);
            }
            if(action.icon !== undefined) {
                $btn.append('');
            }
            if(action.text !== undefined) {
                $btn.append('' + action.text + '');
            }
            if(action.tooltip !== undefined) {
                $btn.attr('title', action.tooltip).tooltip();
            }
            $btn.data('action', action);
            $actions.append($btn);
        };
        if(options.actions) {
            $.each(options.actions, function(idx, action) {
                if(action.name === undefined) action.name = idx;
                if(action.name == 'close') hasCloseAction = true;
                appendAction(action);
            });
        }
        if(!hasCloseAction && options.close) {
            appendAction({name: 'close', html: '×'});
        }

        that.$.on('click', '.action', function(e) {
            var action = $(this).data('action'), result;
            if(options.onAction) {
                result = options.onAction.call(this, action.name, action, that);
                if(result === false) return;
            }
            if($.isFunction(action.action)) {
                result = action.action.call(this, that);
                if(result === false) return;
            }
            that.hide();
            e.stopPropagation();
        });

        that.$.on('click', function(e) {
            if(options.onAction) {
                result = options.onAction.call(this, 'content', null, that);
                if(result === true) that.hide();
            }
        });

        var $content = that.$.find('.messager-content').html(that.message);
        if(options.contentClass) $content.addClass(options.cssClass);

        that.$.data('zui.messager', that);

        if(options.show && that.message !== undefined) {
            that.show();
        }
    };

    Messager.prototype.update = function(message, newOptions) {
        var that = this;
        var options = that.options;
        that.$.removeClass('messager-' + options.type);
        if(newOptions) {
            options = $.extend(options, newOptions);
        }
        that.$.addClass('messager-' + options.type);
        if(message) {
            that.message = (options.icon ? ' ' : '') + message;
            that.$.find('.messager-content').html(that.message);
        }
    };

    Messager.prototype.show = function(message, callback) {
        var that = this,
            options = this.options;

        if(that.isShow) {
            that.hide(function() {
                that.show(message, callback);
            });
            return;
        }

        if(that.hiding) {
            clearTimeout(that.hiding);
            that.hiding = null;
        }

        if($.isFunction(message)) {
            var oldCallback = callback;
            callback = message;
            if(oldCallback !== undefined) {
                message = oldCallback;
            }
        }

        that.update(message);

        var placement = options.placement;
        var $parent = $(options.parent);
        var $holder = $parent.children('.messagers-holder.' + placement);
        if(!$holder.length) {
            $holder = $('
').attr('class', 'messagers-holder ' + placement).appendTo($parent);
        }
        $holder.append(that.$);
        if(placement === 'center') {
            var offset = $(window).height() - $holder.height();
            $holder.css('top', Math.max(-offset, offset/2));
        }

        that.$.show().addClass('in');

        if(options.time) {
            that.hiding = setTimeout(function() {
                that.hide();
            }, options.time);
        }

        that.isShow = true;
        callback && callback();
        return that;
    };

    Messager.prototype.hide = function(callback, immediately) {
        if(callback === true) {
            immediately = true;
            callback = null;
        }
        var that = this;
        if(that.$.hasClass('in')) {
            that.$.removeClass('in');
            var removeMessager = function() {
                var $parent = that.$.parent();
                that.$.detach();
                if(!$parent.children().length) $parent.remove();
                callback && callback(true);
            };
            if(immediately) removeMessager();
            else setTimeout(removeMessager, 200);
        } else {
            callback && callback(false);
        }

        that.isShow = false;
    };

    Messager.prototype.destory = function() {
        var that = this;
        that.hide(true);
        that.$.remove();
        that.$ = null;
        delete all[that.id];
    };

    Messager.all = all;

    var hideMessage = function() {
        $('.messager').each(function() {
            var msg = $(this).data('zui.messager');
            if(msg && msg.hide) msg.hide(true);
        });
    };

    var showMessage = function(message, options) {
        if(typeof options === 'string') {
            options = {
                type: options
            };
        }
        options = $.extend({}, options);
        if(options.id === undefined) hideMessage();
        var msg = all[options.id] || new Messager(message, options);
        msg.show();
        return msg;
    };

    var getOptions = function(options) {
        return(typeof options === 'string') ? {
            placement: options
        } : options;
    };

    var zuiMessager = {
        show: showMessage,
        hide: hideMessage
    };

    $.each({
        primary  : 0,
        success  : 'ok-sign',
        info     : 'info-sign',
        warning  : 'warning-sign',
        danger   : 'exclamation-sign',
        important: 0,
        special  : 0
    }, function(name, icon){
        zuiMessager[name] = function(message, options) {
            return showMessage(message, $.extend({
                type: name,
                icon: icon || null
            }, getOptions(options)));
        };
    });

    $.zui({
        Messager: Messager,
        showMessager: showMessage,
        messager: zuiMessager
    });
}(jQuery, window, undefined));

<|endoftext|>


<commit_before>// this list is a WIP
// i - instamine
// m - mineable
// n - not mineable
// p - premined
// s - significantly premined

var mineable = {
	ADK: "n",
	ADT: "n",
	ADX: "n",
	AE: "n",
	AMP: "n",
	ANT: "n",
	ARDR: "n",
	ARK: "n",
	BAT: "n",
	BCC: "p",    // >1m BCC sold in ICO
	BCH: "m",
	BCN: "s",    // 82% premined
	BDL: "p",    // ICO, looks like a scam. http://archive.is/Cv46i
	BLOCK: "n",
	BNB: "n",
	BNT: "n",
	BQX: "n",
	BTC: "m",
	BTCD: "p",   // 1.5% premined for bounties
	BTM: "n",
	BTS: "n",
	CDT: "n",
	CFI: "n",
	CLOAK: "n",
	CVC: "n",
	DASH: "i",   // 2m DASH was mined in 48h
	DCR: "p",    // 8% premined
	DCT: "n",
	DGB: "p",    // 100m premined
	DGD: "n",
	DICE: "n"
	DLT: "n",
	DNT: "n",
	DOGE: "m",
	EB3: "s",    // Looks like a scam http://archive.is/7rjAz
	EDG: "n",
	EMC: "m",
	EOS: "n",
	ETC: "s",    // same as Ethereum
	ETH: "s",    // the genesis block contained 60.2m eth going to crowdsale participants + 11.9m split between early contributors and foundation,
	ETP: "p",    // ICO
	FAIR: "n",   // Switched from PoW to PoS
	FCT: "n",
	FRST: "s",   // 109.9m/110m premined? Looks like a scammy coin
	FUN: "n",
	GAME: "m",
	GAS: "n",
	GBYTE: "n",
	GNO: "n",
	GNT: "n",
	GXS: "n",
	HMQ: "n",
	HSR: "n",
	ICN: "n",
	ICO: "n",
	IOC: "n",
	ION: "n",
	KMD: "s",    // Initial supply of 100m for ICO and devs
	LBC: "p",
	LEO: "p",    // 50m premined
	LKK: "n",
	LRC: "n",
	LSK: "n",
	LTC: "m",
	LUN: "n",
	MAID: "n",
	MCAP: "n",
	MCO: "n",
	MGO: "n",
	MIOTA: "n",
	MLN: "n",
	MTH: "n",
	MTL: "n",
	MYST: "n",
	NAV: "n",
	NEO: "n",
	NLC2: "n",
	NLG: "p",     // 170m premined
	NMC: "m",
	NMR: "n",
	NXS: "m",
	NXT: "n",
	OAX: "n",
	OK: "",
	OMG: "n",
	PART: "n",
	PAY: "n",
	PIVX: "n",
	PLR: "n",
	PPC: "m",
	PPT: "n",
	PPY: "n",
	PTOY: "n",
	QRL: "n",
	QTUM: "n",
	RDD: "n",
	REP: "n",
	RISE: "n",
	RLC: "n",
	ROUND: "n",
	SAFEX: "n",
	SC: "m",
	SNGLS: "n",
	SNT: "n",
	STEEM: "m",
	STORJ: "n",
	STRAT: "n",
	STX: "n",
	SYS: "p",     // 18% premined
	TAAS: "n",
	TKN: "n",
	TNT: "n",
	TRIG: "n",
	UBQ: "m",
	USDT: "n",
	VERI: "n",
	VIA: "p",     // ICO
	VSL: "n",
	VTC: "m",
	WAVES: "n",
	WINGS: "n",
	WTC: "n",
	XAS: "p",     // ICO
	XCP: "n",
	XEL: "n",
	XEM: "n",
	XLM: "n",
	XMR: "m",
	XRL: "n",
	XRP: "n",
	XVG: "m",
	XZC: "m",
	ZEC: "m",
	ZRX: "n"
}

mineable["1ST"] = "n";
<commit_msg>fix missing value in mineable<commit_after>// this list is a WIP
// i - instamine
// m - mineable
// n - not mineable
// p - premined
// s - significantly premined

var mineable = {
	ADK: "n",
	ADT: "n",
	ADX: "n",
	AE: "n",
	AMP: "n",
	ANT: "n",
	ARDR: "n",
	ARK: "n",
	BAT: "n",
	BCC: "p",    // >1m BCC sold in ICO
	BCH: "m",
	BCN: "s",    // 82% premined
	BDL: "p",    // ICO, looks like a scam. http://archive.is/Cv46i
	BLOCK: "n",
	BNB: "n",
	BNT: "n",
	BQX: "n",
	BTC: "m",
	BTCD: "p",   // 1.5% premined for bounties
	BTM: "n",
	BTS: "n",
	CDT: "n",
	CFI: "n",
	CLOAK: "n",
	CVC: "n",
	DASH: "i",   // 2m DASH was mined in 48h
	DCR: "p",    // 8% premined
	DCT: "n",
	DGB: "p",    // 100m premined
	DGD: "n",
	DICE: "n"
	DLT: "n",
	DNT: "n",
	DOGE: "m",
	EB3: "s",    // Looks like a scam http://archive.is/7rjAz
	EDG: "n",
	EMC: "m",
	EOS: "n",
	ETC: "s",    // same as Ethereum
	ETH: "s",    // the genesis block contained 60.2m eth going to crowdsale participants + 11.9m split between early contributors and foundation,
	ETP: "p",    // ICO
	FAIR: "n",   // Switched from PoW to PoS
	FCT: "n",
	FRST: "s",   // 109.9m/110m premined? Looks like a scammy coin
	FUN: "n",
	GAME: "m",
	GAS: "n",
	GBYTE: "n",
	GNO: "n",
	GNT: "n",
	GXS: "n",
	HMQ: "n",
	HSR: "n",
	ICN: "n",
	ICO: "n",
	IOC: "n",
	ION: "n",
	KMD: "s",    // Initial supply of 100m for ICO and devs
	LBC: "p",
	LEO: "p",    // 50m premined
	LKK: "n",
	LRC: "n",
	LSK: "n",
	LTC: "m",
	LUN: "n",
	MAID: "n",
	MCAP: "n",
	MCO: "n",
	MGO: "n",
	MIOTA: "n",
	MLN: "n",
	MTH: "n",
	MTL: "n",
	MYST: "n",
	NAV: "n",
	NEO: "n",
	NLC2: "n",
	NLG: "p",     // 170m premined
	NMC: "m",
	NMR: "n",
	NXS: "m",
	NXT: "n",
	OAX: "n",
	OK: "n",
	OMG: "n",
	PART: "n",
	PAY: "n",
	PIVX: "n",
	PLR: "n",
	PPC: "m",
	PPT: "n",
	PPY: "n",
	PTOY: "n",
	QRL: "n",
	QTUM: "n",
	RDD: "n",
	REP: "n",
	RISE: "n",
	RLC: "n",
	ROUND: "n",
	SAFEX: "n",
	SC: "m",
	SNGLS: "n",
	SNT: "n",
	STEEM: "m",
	STORJ: "n",
	STRAT: "n",
	STX: "n",
	SYS: "p",     // 18% premined
	TAAS: "n",
	TKN: "n",
	TNT: "n",
	TRIG: "n",
	UBQ: "m",
	USDT: "n",
	VERI: "n",
	VIA: "p",     // ICO
	VSL: "n",
	VTC: "m",
	WAVES: "n",
	WINGS: "n",
	WTC: "n",
	XAS: "p",     // ICO
	XCP: "n",
	XEL: "n",
	XEM: "n",
	XLM: "n",
	XMR: "m",
	XRL: "n",
	XRP: "n",
	XVG: "m",
	XZC: "m",
	ZEC: "m",
	ZRX: "n"
}

mineable["1ST"] = "n";
<|endoftext|>


<commit_before>var readline = require("readline");
var cluster = require("cluster");
var message = require("../process/message");
var fs = require("fs");
var path = require("path");
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var counter = 0;
var quitting = [];
var workers = [];
var cpus = require('os').cpus().map(a => 0);
if (process.env.IN_TEST_MODE) {
    cpus = [0];
}
var end = function () {
    quitting = quitting.concat(workers);
    if (!quitting.length) {
        console.info("正在退出..");
        afterend();
    }
    workers = [];
    exit();
};
rl.addListener("SIGINT", end);
var afterend = function () {
    process.removeAllListeners();
    watch.close();
    rl.removeAllListeners();
    rl.pause();
};
var exit = function () {
    quitting.splice(0).forEach(function (worker) {
        var timeout = setTimeout(function () {
            worker.kill();
        }, !workers.length ? 100 : 24 * 60 * 60 * 1000);
        worker.on("disconnect", function () {
            clearTimeout(timeout);
        });
        worker.send("quit");
    });
};
var broadcast = function (value) {
    var index = value.indexOf(":");
    var key = value.slice(0, index);
    var data = value.slice(index + 1);
    quitting.concat(workers).forEach(function (worker) {
        worker.send([key, data].join(":"));
    });
};
var run = function () {
    if (quitting.length) return;
    if (run.ing) {
        run.ing = 2;
        return;
    }
    run.ing = true;
    quitting = quitting.concat(workers);
    if (quitting.length) console.info(`${quitting.length}个子进程准备退出:${quitting.map(a => a.id)}`);
    var workking = 0;
    workers = cpus.map(function () {
        counter++;
        var worker = cluster.fork();
        worker.on("listening", function () {
            workking++;
            if (workking === cpus.length) {
                console.info(`${workers.length}个子进程已启动:${workers.map(a => a.id)}`);
                run.ing = false;
                exit();
            }
        });
        worker.on("exit", function () {
            if (worker.exitedAfterDisconnect !== true) {
                for (var cx = workers.length - 1; cx >= 0; cx--) {
                    if (workers[cx] === worker) workers.splice(cx, 1);
                }
            }
            counter--;
            if (!counter && !workers.length) {
                afterend();
            }
        });
        worker.on("message", message);
        return worker;
    });
};
var watch = {
    close: function (watchs) {
        watchs.forEach(a => a.close());
    }.bind(null, [
        fs.watch(__dirname, { recursive: true }, run),
        fs.watch(path.join(__dirname, "../process"), { recursive: true }, run)
    ])
};
message.quit = end;
message.broadcast = broadcast;
process.on("SIGINT", end);
process.on("SIGTERM", end);
run();
process.on("uncaughtException", function () {
    console.error.apply(console, arguments);
});
process.on("unhandledRejection", function () {
    console.error.apply(console, arguments);
});
<commit_msg>如果按两次ctrl+c，立即退出<commit_after>var readline = require("readline");
var cluster = require("cluster");
var message = require("../process/message");
var fs = require("fs");
var path = require("path");
var rl = readline.createInterface({
    input: process.stdin,
    output: process.stdout
});
var counter = 0;
var quitting = [], notkilled = [];
var workers = [];
var cpus = require('os').cpus().map(a => 0);
if (process.env.IN_TEST_MODE) {
    cpus = [0];
}
var end = function () {
    quitting = quitting.concat(workers);
    if (!quitting.length) {
        console.info("正在退出..");
        afterend();
    }
    workers = [];
    exit();
};
rl.addListener("SIGINT", end);
var afterend = function () {
    process.removeAllListeners();
    watch.close();
    rl.removeAllListeners();
    rl.pause();
    notkilled.forEach(a => a.kill());
};
var exit = function () {
    if (!workers.length) var isQuit = true;
    quitting.splice(0).forEach(function (worker) {
        var timeout = setTimeout(function () {
            worker.kill();
        }, isQuit ? 100 : 24 * 60 * 60 * 1000);
        worker.on("disconnect", function () {
            clearTimeout(timeout);
            var index = notkilled.indexOf(worker);
            notkilled.splice(index);
        });
        worker.send("quit");
        notkilled.push(worker);
    });
};
var broadcast = function (value) {
    var index = value.indexOf(":");
    var key = value.slice(0, index);
    var data = value.slice(index + 1);
    quitting.concat(workers).forEach(function (worker) {
        worker.send([key, data].join(":"));
    });
};
var run = function () {
    if (quitting.length) return;
    if (run.ing) {
        run.ing = 2;
        return;
    }
    run.ing = true;
    quitting = quitting.concat(workers);
    if (quitting.length) console.info(`${quitting.length}个子进程准备退出:${quitting.map(a => a.id)}`);
    var workking = 0;
    workers = cpus.map(function () {
        counter++;
        var worker = cluster.fork();
        worker.on("listening", function () {
            workking++;
            if (workking === cpus.length) {
                console.info(`${workers.length}个子进程已启动:${workers.map(a => a.id)}`);
                run.ing = false;
                exit();
            }
        });
        worker.on("exit", function () {
            if (worker.exitedAfterDisconnect !== true) {
                for (var cx = workers.length - 1; cx >= 0; cx--) {
                    if (workers[cx] === worker) workers.splice(cx, 1);
                }
            }
            counter--;
            if (!counter && !workers.length) {
                afterend();
            }
        });
        worker.on("message", message);
        return worker;
    });
};
var watch = {
    close: function (watchs) {
        watchs.forEach(a => a.close());
    }.bind(null, [
        fs.watch(__dirname, { recursive: true }, run),
        fs.watch(path.join(__dirname, "../process"), { recursive: true }, run)
    ])
};
message.quit = end;
message.broadcast = broadcast;
process.on("SIGINT", end);
process.on("SIGTERM", end);
run();
process.on("uncaughtException", function () {
    console.error.apply(console, arguments);
});
process.on("unhandledRejection", function () {
    console.error.apply(console, arguments);
});
<|endoftext|>


<commit_before>/*
 * gui-builder - A simple WYSIWYG HTML5 app creator
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */
"use strict";

// In order to get the very first instance of page change events,
// the bind must occur in the jQM mobileinit event handler
$(document).bind('mobileinit', function() {
    $.mobile.defaultPageTransition = 'none';
    $.mobile.loadingMessage = false;

    // Make sure to sync up the ADM anytime the page changes in jQM
    $('div').live('pageshow', function(e) {
        var pageId = $(this).data('uid'),
            node = (window.parent !== window)?window.parent.ADM.getDesignRoot().findNodeByUid(pageId):null,
            currentPage = (window.parent !== window)?window.parent.ADM.getActivePage():null;

        // No change so do nothing
        if (currentPage && currentPage.getUid() === pageId) {
            return;
        }

        if (node) {
            window.parent.ADM.setActivePage(node);
        }
    });
});

$(function() {
    var handleSelect = function (e, ui){
        if ($(ui).data('role') === 'content' ||
            $(ui).data('role') === 'page') {
            setSelected(null);
        } else if (!$(ui).hasClass('ui-selected')) {
            setSelected(ui);
        } else if (e.ctrlKey) {
            setSelected(null);
        }
        e.stopPropagation();
        return false;  // Stop event bubbling
    }
    $('div:jqmData(role="page")').live('pagebeforecreate', function(e) {
        var selects = $('select.adm-node[data-role!="slider"]');
        // Configure "select" handlers on all nodes added from the ADM
        // except for pages and content
        $('.adm-node[data-role!="slider"]').not('select').click( function (e) {
            return handleSelect(e, this);
        });
        selects.focus( function (e) {
            return handleSelect(e, this);
        });
        selects.click( function (e) {
            e.stopPropagation();
            return false;
        });
        selects.change( function (e) {
            return handleSelect(e, $(this).children(':selected')[0]);
        });

        // Configure "sortable" behaviors
        var targets = $('.nrc-sortable-container');
        console.log("Found ["+targets.length+"] sortable targets: ");

        targets
            .sortable({
                distance: 5,
                iframeFix: true,
                greedy: true,
                forceHelperSize: true,
                forcePlaceholderSize: true,
                placeholder: 'nrc-dragging',
                appendTo: 'body',
                connectWith: '.nrc-sortable-container',
                items: '> *.adm-node',
                // TODO: add connectWith option to allow movement into
                //       other sortables
                start: function(event, ui){
                    var stylesToCopy = [
                            'width', 'height',
                            'padding-top', 'padding-left',
                            'padding-right', 'padding-bottom',
                            'margin-top', 'margin-left',
                            'margin-right', 'margin-bottom',
                            'border-top-left-radius',
                            'border-top-right-radius',
                            'border-bottom-left-radius',
                            'border-bottom-right-radius'],
                        attrMap = {};
                    console.log('sortable:start() on "'+this.id+'"');
                    if (ui.placeholder) {
                        // Try our best to make the placeholder occupy the
                        // same space as the Element that it represents
                        if (ui.item) {
                            $.each(stylesToCopy, function (key, val) {
                                attrMap[val] = ui.item.css(val);
                            });
                            $(ui.placeholder).css(attrMap);
                        }
                    }
                },
                stop: function(event, ui){
                    console.log('sortable:stop() on "'+this.id+'"');
                    if (ui.item) {
                        var idx = ui.item.index(),
                            cid = $(ui.item).attr('data-uid'),
                            pid = $(ui.item).parent().attr('data-uid'),
                            msg = 'childMoved:',
                            off = $(ui.item).parent().children().length -
                                  $(ui.item).parent().find('.adm-node').length;

                        // Account for possible non-ADM children in the parent
                        idx = idx-off;
                        console.log(ui.item[0].id+' @ '+idx);

                        // Notify the ADM that element has been moved
                        moveChild(cid, pid, idx);
                        $(ui.item).triggerHandler('click');
                    } else {
                        console.warn('ui.item undefined after sort...');
                    }
                },
            })
            .disableSelection();

        var inputs = targets.find('input');
        $(inputs).disableSelection();

        // Populate empty nodes with a "hint" to drop things there
        $('.nrc-empty').each( function() {
            if ($('.nrc-hint-text', this).length === 0) {
                $(this).append('
Drop target...
');
            }
        });
    });

    // Allow for deletion of selected widget
    $(document).keyup(function(e) {
        if (e.which === 46) {
            $('.ui-selected').each( function () {
                var id = $(this).attr('data-uid');
                window.parent.ADM.removeChild(id);
            });
        }
    });
    // Watch our parent document also
    $(top.document).keyup(function(e) {
        if (e.which === 46) {
            $('.ui-selected').each( function () {
                var id = $(this).attr('data-uid');
                window.parent.ADM.removeChild(id);
            });
        }
    });

    function messageHandler(e) {
        console.log('iframe received message "'+e.data+'"');

        switch (e.data) {
            case 'reload':
                reloadPage();
                break;
            case 'refresh':
                refreshPage();
                break;
            default:
                console.log('Unknown request: '+e.data);
                break;
        }
    }

    window.addEventListener('message', messageHandler, false);

    function reloadPage() {
        $('.nrc-dropped-widget').each( function () {
            // Hide the hint text
            $(this).parent().children('.nrc-hint-text').remove();

            // Remove this class to prevent "create"ing more than once
            $(this).removeClass('nrc-dropped-widget');

            // TODO: Add better and more complete handling of this
            // Disable Text widgets so they are selectable but not editable
            if (this.nodeName == "INPUT" && this.type == "text") {
                this.readOnly=true;
            }
        });
        var aPage = top.ADM.getActivePage();
        if (aPage) {
            $.mobile.changePage($('#' + aPage.getProperty('id')));
        } else {
            $.mobile.initializePage();
        }
        var flipToggleSwithes = $('[data-role="slider"]');
        flipToggleSwithes.bind("change", function(e){
            return handleSelect(e, this);
        });
        flipToggleSwithes.next().click( function(e) {
            return handleSelect(e, $(this).prev()[0]);
        });
    }

    function refreshPage() {
        $('.nrc-dropped-widget').each( function () {
            // Hide the hint text
            $(this).parent().children('.nrc-hint-text').fadeOut();

            // Force jQM to call the init on the dropped widget
            // letting it determined styling, not us!
            $(this).closest('.ui-page').page();

            // Remove this class to prevent "create"ing more than once
            $(this).removeClass('nrc-dropped-widget');

            // TODO: Add better and more complete handling of this
            // Disable Text widgets so they are selectable but not editable
            if (this.nodeName == "INPUT" && this.type == "text") {
                this.readOnly=true;
            }
        });
    }

    function setSelected(item) {
        var selectedItems = $('.ui-selected'),
            adm = window.parent.ADM;
        /*
           In the context of this "onclick()" handler, the following
           rules are being applied:

           IF any items are selected THEN
               DESELECT all of them
           SELECT the clicked item

           TODO: Figure out how we want to UNSELECT all without making
                 any selection, or by making "click" toggle the items
                 selection state
         */

        if (selectedItems.length) {
            // Mark all selectees as unselect{ed,ing}
            $(selectedItems).removeClass('ui-selected')
                            .removeClass('ui-selecting')
                            .removeClass('ui-unselecting');
        }

        // Mark this selectee element as being selecting
        $(item).removeClass('ui-unselecting')
               .removeClass('ui-selecting')
               .addClass('ui-selected');

        adm.setSelected((item?$(item).attr('data-uid'):item));
    }

    function moveChild(child, parent, index) {
        var adm = window.parent.ADM,
            bw = window.parent.BWidget,
            root, node, zones,
            oldZone, oldIndex, oldParent,
            newZone, newIndex, newParent;

        root = adm.getDesignRoot();
        newParent = root.findNodeByUid(parent);
        zones = bw.getZones(newParent.getType());

        if ((zones.length === 1 && zones[0].cardinality !== '1') ||
            (newParent.getType() === 'Header')) {
            node = root.findNodeByUid(child);
            oldParent = node.getParent();
            oldZone = node.getZone();
            newIndex = index;

            if (oldParent.getUid() === newParent.getUid()) {
                console.log('Moving node '+node.getUid()+
                      ' with in its parent to position '+newIndex);
                top.moveADMNode(node, zones[0], newIndex);
            } else {
                console.log('Moving node '+node.getUid()+
                      ' from old parent('+oldParent.getUid()+
                      ') to new parent('+newParent.getUid()+
                      ') at position '+newIndex);
                top.reparentADMNode(node, newParent, zones[0], newIndex);
            }
        }
    }
});
<commit_msg>[Design View] Fix dragging of flip toggle & select menus<commit_after>/*
 * gui-builder - A simple WYSIWYG HTML5 app creator
 * Copyright (c) 2011, Intel Corporation.
 *
 * This program is licensed under the terms and conditions of the
 * Apache License, version 2.0.  The full text of the Apache License is at
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 */
"use strict";

// In order to get the very first instance of page change events,
// the bind must occur in the jQM mobileinit event handler
$(document).bind('mobileinit', function() {
    $.mobile.defaultPageTransition = 'none';
    $.mobile.loadingMessage = false;

    // Make sure to sync up the ADM anytime the page changes in jQM
    $('div').live('pageshow', function(e) {
        var pageId = $(this).data('uid'),
            node = (window.parent !== window)?window.parent.ADM.getDesignRoot().findNodeByUid(pageId):null,
            currentPage = (window.parent !== window)?window.parent.ADM.getActivePage():null;

        // No change so do nothing
        if (currentPage && currentPage.getUid() === pageId) {
            return;
        }

        if (node) {
            window.parent.ADM.setActivePage(node);
        }
    });
});

$(function() {
    var handleSelect = function (e, ui){
        if ($(ui).data('role') === 'content' ||
            $(ui).data('role') === 'page') {
            setSelected(null);
        } else if (!$(ui).hasClass('ui-selected')) {
            setSelected(ui);
        } else if (e.ctrlKey) {
            setSelected(null);
        }
        e.stopPropagation();
        return false;  // Stop event bubbling
    }
    $('div:jqmData(role="page")').live('pagebeforecreate', function(e) {
        var selects = $('select.adm-node[data-role!="slider"]');
        // Configure "select" handlers on all nodes added from the ADM
        // except for pages and content
        $('.adm-node[data-role!="slider"]').not('select').click( function (e) {
            return handleSelect(e, this);
        });
        selects.focus( function (e) {
            return handleSelect(e, this);
        });
        selects.click( function (e) {
            e.stopPropagation();
            return false;
        });
        selects.change( function (e) {
            return handleSelect(e, $(this).children(':selected')[0]);
        });

        // Configure "sortable" behaviors
        var targets = $('.nrc-sortable-container');
        console.log("Found ["+targets.length+"] sortable targets: ");

        targets
            .sortable({
                distance: 5,
                iframeFix: true,
                greedy: true,
                forceHelperSize: true,
                forcePlaceholderSize: true,
                placeholder: 'nrc-dragging',
                appendTo: 'body',
                connectWith: '.nrc-sortable-container',
                items: '> *.adm-node',
                // TODO: add connectWith option to allow movement into
                //       other sortables
                start: function(event, ui){
                    var stylesToCopy = [
                            'width', 'height',
                            'padding-top', 'padding-left',
                            'padding-right', 'padding-bottom',
                            'margin-top', 'margin-left',
                            'margin-right', 'margin-bottom',
                            'border-top-left-radius',
                            'border-top-right-radius',
                            'border-bottom-left-radius',
                            'border-bottom-right-radius'],
                        attrMap = {};
                    console.log('sortable:start() on "'+this.id+'"');
                    if (ui.placeholder) {
                        // Try our best to make the placeholder occupy the
                        // same space as the Element that it represents
                        if (ui.item) {
                            $.each(stylesToCopy, function (key, val) {
                                attrMap[val] = ui.item.css(val);
                            });
                            $(ui.placeholder).css(attrMap);
                        }
                    }
                },
                stop: function(event, ui){
                    console.log('sortable:stop() on "'+this.id+'"');
                    if (ui.item) {
                        var idx = $(ui.item).parent().children('.adm-node').index(ui.item),
                            cid = $(ui.item).attr('data-uid'),
                            pid = $(ui.item).parent().attr('data-uid'),
                            msg = 'childMoved:';
                        console.log(ui.item[0].id+' @ '+idx);

                        // Notify the ADM that element has been moved
                        moveChild(cid, pid, idx);
                        $(ui.item).triggerHandler('click');
                    } else {
                        console.warn('ui.item undefined after sort...');
                    }
                },
            })
            .disableSelection();

        var inputs = targets.find('input');
        $(inputs).disableSelection();

        // Populate empty nodes with a "hint" to drop things there
        $('.nrc-empty').each( function() {
            if ($('.nrc-hint-text', this).length === 0) {
                $(this).append('
Drop target...
');
            }
        });
    });
    $('div:jqmData(role="page")').live('pageinit', function(e) {
        // jQM generates an div next to the slider, which is the actually clicked item when users try to click the flip toggle switch.
        var flipToggleSwithes = $('[data-role="slider"]'),
            clickable = flipToggleSwithes.next();
        flipToggleSwithes.bind("change", function(e){
            return handleSelect(e, this);
        });

        //Move the adm-node class to the clickable and assign data-uid to it so that in sortable.stop we can always get it from ui.item.
        clickable.addClass('adm-node');
        flipToggleSwithes.removeClass('adm-node');
        clickable.attr('data-uid', flipToggleSwithes.attr('data-uid'));
        clickable.click( function(e) {
            return handleSelect(e,$(this).prev());
        });

        //jQM generates two levels of divs for a select, the topmost one is what is clicked.
        var selects = $('select.adm-node'),
            selectClickable = selects.parent().parent();

        selectClickable.addClass('adm-node');
        selects.removeClass('adm-node');
        selectClickable.attr('data-uid', selects.attr('data-uid'));
    });

    // Allow for deletion of selected widget
    $(document).keyup(function(e) {
        if (e.which === 46) {
            $('.ui-selected').each( function () {
                var id = $(this).attr('data-uid');
                window.parent.ADM.removeChild(id);
            });
        }
    });
    // Watch our parent document also
    $(top.document).keyup(function(e) {
        if (e.which === 46) {
            $('.ui-selected').each( function () {
                var id = $(this).attr('data-uid');
                window.parent.ADM.removeChild(id);
            });
        }
    });

    function messageHandler(e) {
        console.log('iframe received message "'+e.data+'"');

        switch (e.data) {
            case 'reload':
                reloadPage();
                break;
            case 'refresh':
                refreshPage();
                break;
            default:
                console.log('Unknown request: '+e.data);
                break;
        }
    }

    window.addEventListener('message', messageHandler, false);

    function reloadPage() {
        $('.nrc-dropped-widget').each( function () {
            // Hide the hint text
            $(this).parent().children('.nrc-hint-text').remove();

            // Remove this class to prevent "create"ing more than once
            $(this).removeClass('nrc-dropped-widget');

            // TODO: Add better and more complete handling of this
            // Disable Text widgets so they are selectable but not editable
            if (this.nodeName == "INPUT" && this.type == "text") {
                this.readOnly=true;
            }
        });
        var aPage = top.ADM.getActivePage();
        if (aPage) {
            $.mobile.changePage($('#' + aPage.getProperty('id')));
        } else {
            $.mobile.initializePage();
        }
    }

    function refreshPage() {
        $('.nrc-dropped-widget').each( function () {
            // Hide the hint text
            $(this).parent().children('.nrc-hint-text').fadeOut();

            // Force jQM to call the init on the dropped widget
            // letting it determined styling, not us!
            $(this).closest('.ui-page').page();

            // Remove this class to prevent "create"ing more than once
            $(this).removeClass('nrc-dropped-widget');

            // TODO: Add better and more complete handling of this
            // Disable Text widgets so they are selectable but not editable
            if (this.nodeName == "INPUT" && this.type == "text") {
                this.readOnly=true;
            }
        });
    }

    function setSelected(item) {
        var selectedItems = $('.ui-selected'),
            adm = window.parent.ADM;
        /*
           In the context of this "onclick()" handler, the following
           rules are being applied:

           IF any items are selected THEN
               DESELECT all of them
           SELECT the clicked item

           TODO: Figure out how we want to UNSELECT all without making
                 any selection, or by making "click" toggle the items
                 selection state
         */

        if (selectedItems.length) {
            // Mark all selectees as unselect{ed,ing}
            $(selectedItems).removeClass('ui-selected')
                            .removeClass('ui-selecting')
                            .removeClass('ui-unselecting');
        }

        // Mark this selectee element as being selecting
        $(item).removeClass('ui-unselecting')
               .removeClass('ui-selecting')
               .addClass('ui-selected');

        adm.setSelected((item?$(item).attr('data-uid'):item));
    }

    function moveChild(child, parent, index) {
        var adm = window.parent.ADM,
            bw = window.parent.BWidget,
            root, node, zones,
            oldZone, oldIndex, oldParent,
            newZone, newIndex, newParent;

        root = adm.getDesignRoot();
        newParent = root.findNodeByUid(parent);
        zones = bw.getZones(newParent.getType());

        if ((zones.length === 1 && zones[0].cardinality !== '1') ||
            (newParent.getType() === 'Header')) {
            node = root.findNodeByUid(child);
            oldParent = node.getParent();
            oldZone = node.getZone();
            newIndex = index;

            if (oldParent.getUid() === newParent.getUid()) {
                console.log('Moving node '+node.getUid()+
                      ' with in its parent to position '+newIndex);
                top.moveADMNode(node, zones[0], newIndex);
            } else {
                console.log('Moving node '+node.getUid()+
                      ' from old parent('+oldParent.getUid()+
                      ') to new parent('+newParent.getUid()+
                      ') at position '+newIndex);
                top.reparentADMNode(node, newParent, zones[0], newIndex);
            }
        }
    }
});
<|endoftext|>


<commit_before>const debug = require('../debug').sub('voting', 'condorcets')
const EE    = require('events').EventEmitter

const ndarray = require('ndarray')
ndarray.zeros = require('zeros')
ndarray.show  = require('ndarray-show')
ndarray.ops   = require('ndarray-ops')

function baseMatrix(movies) {
	const matrix = ndarray.zeros([ movies.length, movies.length ])
	for(var x = 0; x < matrix.shape[0]; x++) {
		for(var y = 0; y < matrix.shape[1]; y++) {
			matrix.set(x, y, 0)
		}
	}
	return matrix
}

module.exports = function(data) {
	const voting = new EE

	var titles

	function updateTitles() {
		titles = data.movies.map(function(movie) {
			return movie.name.replace(/a|an|and|the|\s+/gi, '').replace(/[^A-Z:]/g, '')
		})

		titles.maxLength = Math.max.apply(Math, [0].concat(titles.map(function(title) {
			return title.length
		})))
	}
	updateTitles()

	function renderMatrix(matrix, numbers) {
		if(titles.length == 0)
			return ''

		var res = new Array(titles.maxLength + 2).join(' ') + titles.join(' ')
		for(var y = 0; y < matrix.shape[1]; y++) {
			res += '\n' + titles[y] + new Array(titles.maxLength - titles[y].length + 2).join(' ')
			for(var x = 0; x < matrix.shape[0]; x++) {
				var num = matrix.get(x, y)
				var content = num ? '<' : ' '
				if(numbers && num)
					content = num + ''
				res += content + new Array(Math.max(titles[x].length + 1 - content.length, 0)).join(' ') + ' '
			}
			res = res.slice(0, res.length - 1)
		}
		return res
	}

	function generateMatrix(person) {
		const vote = person.vote

		const moviesOrder = {}
		data.movies.forEach(function(movie, id) {
			moviesOrder[id] = Infinity
		})
		vote.forEach(function(id, i) {
			moviesOrder[id] = i
		})
		debug('movies order:', moviesOrder)

		const matrix = baseMatrix(data.movies)
		var val
		for(var x = 0; x < matrix.shape[0]; x++) {
			for(var y = 0; y < matrix.shape[1]; y++) {
				if(moviesOrder[y] < moviesOrder[x]) {
					val = 1
				} else {
					val = 0
				}
				matrix.set(x, y, val)
				debug.trace('setting %d (%d), %d (%d) to %d', x, moviesOrder[x], y, moviesOrder[y], val)
			}
		}
		debug('generated matrix for %s (%d):', person.name, person.id)
		if(debug.enabled) console.log(renderMatrix(matrix))
		return matrix
	}

	function update() {
		updateTitles()

		voting.matrix = baseMatrix(data.movies)
		voting.people.forEach(function(matrix) {
			ndarray.ops.add(voting.matrix, voting.matrix, matrix)
		})

		debug('matrix:')
		if(debug.enabled) console.log(renderMatrix(voting.matrix, true))

		voting.results = []

		const wins = {}
		data.movies.forEach(function(movie, id) {
			wins[id] = 0
		})

		for(var y = 0; y < voting.matrix.shape[1]; y++) {
			for(var x = 0; x < voting.matrix.shape[0]; x++) {
				if(x <= y) continue

				var runner   = voting.matrix.get(x, y)
				var opponent = voting.matrix.get(y, x)

				if(runner > opponent)
					wins[y] += 1
				else if(opponent > runner)
					wins[x] += 1

				debug.trace('%s (%d): %d | %s (%d): %d', data.movies[y].name, y, runner, data.movies[x].name, x, opponent)
			}
		}

		(function() {
			var maxWins = 0
			for(var id = 0; id < data.movies.length; id++) {
				/*if(wins[id] >= data.movies.length - 1) {
					voting.results = [ id ]
					return
				} else */
				if(wins[id] >= maxWins) {
					debug('adding %s (%d) - %d to the tie %s at %d', data.movies[id].name, id, wins[id], voting.results.map(function(id) {
						return data.movies[id].name
					}).join(', '), maxWins)
					if(wins[id] > maxWins) {
						maxWins = wins[id]
						voting.results = []
					}

					voting.results.push(id)
				}
			}
		})()

		debug('wins:', wins)

		if(voting.results.length == data.movies.length)
			voting.results = []

		voting.debugInfo = 'Result:\n' + renderMatrix(voting.matrix, true).split('\n').map(function(line) {
			return '  ' + line
		}).join('\n') + '\n\n' + voting.people.map(function(matrix, i) {
			const person = data.people[i]
			if(!person)
				return "Deleted: " + i
			return person.name + ': ' + person.vote.map(function(i) {
				return titles[i]
			}).join(' ') + '\n' + renderMatrix(matrix).split('\n').map(function(line) {
				return '  ' + line
			}).join('\n')
		}).join('\n\n')

		debug('results: %s', voting.results.map(function(id) {
			return data.movies[id].name
		}).join(', '))

		voting.emit('update')
	}

	voting.update = function(person) { return function(cb) {
		if(!cb) cb = function(err) { if(err) throw err }

		voting.people[person.id] = generateMatrix(person)
		update()

		process.nextTick(function() { cb(null) })
	} }

	voting.delete = function(person) { return function(cb) {
		if(!cb) cb = function(err) { if(err) throw err }

		voting.people[person.id] = baseMatrix(data.movies)

		update()

		process.nextTick(function() { cb(null) })
	} }

	voting.reset = function() { return function(cb) {
		if(!cb) cb = function(err) { if(err) throw err }

		voting.people = []
		voting.matrix = baseMatrix(data.movies)
		voting.results = []
		debug('reseting')

		process.nextTick(function() { cb(null) })
	} }

	return voting
}<commit_msg>Add some code to debug the condorcets results debug<commit_after>const debug = require('../debug').sub('voting', 'condorcets')
const EE    = require('events').EventEmitter
const util  = require('util')

const ndarray = require('ndarray')
ndarray.zeros = require('zeros')
ndarray.show  = require('ndarray-show')
ndarray.ops   = require('ndarray-ops')

function baseMatrix(movies) {
	const matrix = ndarray(new Int8Array(movies.length * movies.length), [ movies.length, movies.length ])
	for(var x = 0; x < matrix.shape[0]; x++) {
		for(var y = 0; y < matrix.shape[1]; y++) {
			matrix.set(x, y, 0)
		}
	}
	return matrix
}

module.exports = function(data) {
	const voting = new EE

	var titles

	function updateTitles() {
		titles = data.movies.map(function(movie) {
			return movie.name.replace(/a|an|and|the|\s+/gi, '').replace(/[^A-Z:]/g, '')
		})

		titles.maxLength = Math.max.apply(Math, [0].concat(titles.map(function(title) {
			return title.length
		})))
	}
	updateTitles()

	function renderMatrix(matrix, numbers) {
		if(titles.length == 0)
			return ''

		var res = new Array(titles.maxLength + 2).join(' ') + titles.join(' ')
		for(var y = 0; y < matrix.shape[1]; y++) {
			res += '\n' + titles[y] + new Array(titles.maxLength - titles[y].length + 2).join(' ')
			for(var x = 0; x < matrix.shape[0]; x++) {
				var num = matrix.get(x, y)
				var content = num ? '<' : ' '
				if(numbers && num)
					content = num + ''
				console.log(x, content)
				console.log(titles[x])
				if(titles[x])
					res += content + new Array(Math.max(titles[x].length + 1 - content.length, 0)).join(' ') + ' '
				else
					res += 'titles[' + x + '] = ' + util.inspect(titles[x]) + ' '
			}
			res = res.slice(0, res.length - 1)
		}
		return res
	}

	function generateMatrix(person) {
		const vote = person.vote

		const moviesOrder = {}
		data.movies.forEach(function(movie, id) {
			moviesOrder[id] = Infinity
		})
		vote.forEach(function(id, i) {
			moviesOrder[id] = i
		})
		debug('movies order:', moviesOrder)

		const matrix = baseMatrix(data.movies)
		var val
		for(var x = 0; x < matrix.shape[0]; x++) {
			for(var y = 0; y < matrix.shape[1]; y++) {
				if(moviesOrder[y] < moviesOrder[x]) {
					val = 1
				} else {
					val = 0
				}
				matrix.set(x, y, val)
				debug.trace('setting %d (%d), %d (%d) to %d', x, moviesOrder[x], y, moviesOrder[y], val)
			}
		}
		debug('generated matrix for %s (%d):', person.name, person.id)
		if(debug.enabled) console.log(renderMatrix(matrix))
		return matrix
	}

	function update() {
		updateTitles()

		voting.matrix = baseMatrix(data.movies)
		voting.people.forEach(function(matrix) {
			ndarray.ops.add(voting.matrix, voting.matrix, matrix)
		})

		debug('matrix:')
		if(debug.enabled) console.log(renderMatrix(voting.matrix, true))

		voting.results = []

		const wins = {}
		data.movies.forEach(function(movie, id) {
			wins[id] = 0
		})

		for(var y = 0; y < voting.matrix.shape[1]; y++) {
			for(var x = 0; x < voting.matrix.shape[0]; x++) {
				if(x <= y) continue

				var runner   = voting.matrix.get(x, y)
				var opponent = voting.matrix.get(y, x)

				if(runner > opponent)
					wins[y] += 1
				else if(opponent > runner)
					wins[x] += 1

				debug.trace('%s (%d): %d | %s (%d): %d', data.movies[y].name, y, runner, data.movies[x].name, x, opponent)
			}
		}

		(function() {
			var maxWins = 0
			for(var id = 0; id < data.movies.length; id++) {
				/*if(wins[id] >= data.movies.length - 1) {
					voting.results = [ id ]
					return
				} else */
				if(wins[id] >= maxWins) {
					debug('adding %s (%d) - %d to the tie %s at %d', data.movies[id].name, id, wins[id], voting.results.map(function(id) {
						return data.movies[id].name
					}).join(', '), maxWins)
					if(wins[id] > maxWins) {
						maxWins = wins[id]
						voting.results = []
					}

					voting.results.push(id)
				}
			}
		})()

		debug('wins:', wins)

		if(voting.results.length == data.movies.length)
			voting.results = []

		voting.debugInfo = 'Result:\n' + renderMatrix(voting.matrix, true).split('\n').map(function(line) {
			return '  ' + line
		}).join('\n') + '\n\n' + voting.people.map(function(matrix, i) {
			const person = data.people[i]
			if(!person)
				return "Deleted: " + i
			return person.name + ': ' + person.vote.map(function(i) {
				return titles[i]
			}).join(' ') + '\n' + renderMatrix(matrix).split('\n').map(function(line) {
				return '  ' + line
			}).join('\n')
		}).join('\n\n')

		debug('results: %s', voting.results.map(function(id) {
			return data.movies[id].name
		}).join(', '))

		voting.emit('update')
	}

	voting.update = function(person) { return function(cb) {
		if(!cb) cb = function(err) { if(err) throw err }

		voting.people[person.id] = generateMatrix(person)
		update()

		process.nextTick(function() { cb(null) })
	} }

	voting.delete = function(person) { return function(cb) {
		if(!cb) cb = function(err) { if(err) throw err }

		voting.people[person.id] = baseMatrix(data.movies)

		update()

		process.nextTick(function() { cb(null) })
	} }

	voting.reset = function() { return function(cb) {
		if(!cb) cb = function(err) { if(err) throw err }

		voting.people = []
		voting.matrix = baseMatrix(data.movies)
		voting.results = []
		debug('reseting')

		process.nextTick(function() { cb(null) })
	} }

	return voting
}<|endoftext|>


<commit_before>import Job from './handlers/job'
import Ping from './handlers/ping'

export default [
  { method: 'GET', path: '/ping', config: { auth: false, handler: Ping } },

  { method: 'POST', path: '/jobs', config: Job.create },
  { method: 'GET', path: '/jobs/{id}', config: Job.get },
  { method: 'GET', path: '/jobs', config: Job.getAll },
  { method: 'DELETE', path: '/jobs/{id}', config: Job.remove }
]
<commit_msg>add update job route<commit_after>import Job from './handlers/job'
import Ping from './handlers/ping'

export default [
  { method: 'GET', path: '/ping', config: { auth: false, handler: Ping } },

  { method: 'POST', path: '/jobs', config: Job.create },
  { method: 'GET', path: '/jobs/{id}', config: Job.get },
  { method: 'GET', path: '/jobs', config: Job.getAll },
  { method: 'DELETE', path: '/jobs/{id}', config: Job.remove },
  { method: 'PUT', path: '/jobs/{id}', config: Job.update }
]
<|endoftext|>


<commit_before> /**
  * JSSpeedTest
  *
  * Copyright (c) 2011 Brian Antonelli (http://brianantonelli.com)
  * Freely distributable under the terms of an MIT-style license.
  * http://www.opensource.org/licenses/mit-license.php
*/

(function($){
    var size = "145121",
        image = "speed_test.jpg",
        runCount = 4,
        totalRuns = 0,
        results = [],
        poller = null,
        progressCallback = null,
        completeCallback = null;

    function poll(){
        if(results.length === runCount){
            window.clearInterval(poller);
            poller = null;

            var totalDuration = 0;
            for(var i=0; i<runCount; i++){
                totalDuration += results[i];
            }

            var averageRun = totalDuration / runCount;

            completeCallback.call(this, {
                kbps: (size * 8 / 1024 / (averageRun / 1000)).toFixed(0),
                KBps: (size / 1024 / (averageRun / 1000)).toFixed(0)
            });
        }
    };

    function performTest(){
        var startedAt = new Date().getTime();
        totalRuns++;

        $("<img/>")
            .load(function(){
                results.push(new Date().getTime() - startedAt);
                if(totalRuns < runCount){
                    performTest();
                    if(progressCallback != null && typeof progressCallback === "function"){
                        progressCallback.call(this, totalRuns / runCount*100);
                    }
                }
            })
            .attr("src", image + "?" + new Date().getTime());
    };

    $.jsSpeedTest = function(myRunCount, myProgressCallback, myCompleteCallback){
        progressCallback = myProgressCallback;
        completeCallback = myCompleteCallback;
        results = [];
        totalRuns = 0;
        runCount = myRunCount;

        var regexp = /JSSpeedTest\.js(\?.*)?$/;

        $("script").each(function(i,s){
            if($(s).attr("src").match(regexp)){
                image = $(s).attr("src").replace(regexp, "") + image;
                return;
            }
        });

        poller = window.setInterval(function(){ poll(); }, 100);
        performTest();
    };

    return this;
})(jQuery);<commit_msg>change js name<commit_after> /**
  * JSSpeedTest
  *
  * Copyright (c) 2011 Brian Antonelli (http://brianantonelli.com)
  * Freely distributable under the terms of an MIT-style license.
  * http://www.opensource.org/licenses/mit-license.php
*/

(function($){
    var size = "145121",
        image = "speed_test.jpg",
        runCount = 4,
        totalRuns = 0,
        results = [],
        poller = null,
        progressCallback = null,
        completeCallback = null;

    function poll(){
        if(results.length === runCount){
            window.clearInterval(poller);
            poller = null;

            var totalDuration = 0;
            for(var i=0; i<runCount; i++){
                totalDuration += results[i];
            }

            var averageRun = totalDuration / runCount;

            completeCallback.call(this, {
                kbps: (size * 8 / 1024 / (averageRun / 1000)).toFixed(0),
                KBps: (size / 1024 / (averageRun / 1000)).toFixed(0)
            });
        }
    };

    function performTest(){
        var startedAt = new Date().getTime();
        totalRuns++;

        $("<img/>")
            .load(function(){
                results.push(new Date().getTime() - startedAt);
                if(totalRuns < runCount){
                    performTest();
                    if(progressCallback != null && typeof progressCallback === "function"){
                        progressCallback.call(this, totalRuns / runCount*100);
                    }
                }
            })
            .attr("src", image + "?" + new Date().getTime());
    };

    $.jsSpeedTest = function(myRunCount, myProgressCallback, myCompleteCallback){
        progressCallback = myProgressCallback;
        completeCallback = myCompleteCallback;
        results = [];
        totalRuns = 0;
        runCount = myRunCount;

        var regexp = /jsSpeedTest\.js(\?.*)?$/i;

        $("script").each(function(i,s){
            if($(s).attr("src").match(regexp)){
                image = $(s).attr("src").replace(regexp, "") + image;
                return;
            }
        });

        poller = window.setInterval(function(){ poll(); }, 100);
        performTest();
    };

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


<commit_before>/**
 * @author Alexey Kuzmin <alex.s.kuzmin@gmail.com>
 * @fileoverview JavaScript implementation of JSON Pointer.
 * @see http://tools.ietf.org/html/rfc6901
 */

;(function() {
  'use strict';

  /**
   * List of special characters and their escape sequences.
   * Special characters will be unescaped in order they are listed.
   * Section 3 of spec.
   * @type {Array.<Array.<string>>}
   * @const
   */
  var SPECIAL_CHARACTERS = [
    ['/', '~1'],
    ['~', '~0']
  ];

  /**
   * Tokens' separator in JSON pointer string.
   * Section 3 of spec.
   * @type {string}
   * @const
   */
  var TOKENS_SEPARATOR = '/';

  /**
   * Prefix for error messages.
   * @type {string}
   * @const
   */
  var ERROR_MESSAGE_PREFIX = 'JSON Pointer: ';

  /**
   * Validates non-empty pointer string.
   * @type {RegExp}
   * @const
   */
  var NON_EMPTY_POINTER_REGEXP = /(\/[^\/]*)+/;

  /**
   * List of error messages.
   * Please keep it in alphabetical order.
   * @enum {string}
   */
  var ErrorMessage = {
    HYPHEN_IS_NOT_SUPPORTED_IN_ARRAY_CONTEXT:
        'Implementation does not support "-" token for arrays.',
    INVALID_DOCUMENT: 'JSON document is not valid.',
    INVALID_DOCUMENT_TYPE: 'JSON document must be a string.',
    INVALID_POINTER: 'Pointer is not valid.',
    NON_NUMBER_TOKEN_IN_ARRAY_CONTEXT:
        'Non-number tokens cannot be used in array context.',
    TOKEN_WITH_LEADING_ZERO_IN_ARRAY_CONTEXT:
        'Token with leading zero cannot be used in array context.'
  };

  /**
   * Returns |target| object's value pointed by |pointer|, returns undefined
   * if |pointer| points to non-existing value.
   * @param {!string} target JSON document.
   * @param {!string} pointer JSON Pointer string.
   * @return {*} Some value.
   */
  function getPointedValue(target, pointer) {

    if (!isString(target)) {
      throw getError(ErrorMessage.INVALID_DOCUMENT_TYPE);
    }
    if (!isValidJSONPointer(pointer)) {
      throw getError(ErrorMessage.INVALID_POINTER);
    }
    try {
      target = JSON.parse(target);
    }
    catch (e) {
      throw getError(ErrorMessage.INVALID_DOCUMENT);
    }

    var tokensList = parsePointer(pointer);
    var token;
    var value = target;

    while (!isUndefined(value) && !isUndefined(token = tokensList.pop())) {
      value = getValue(value, token);
    }

    return value;
  }

  /**
   * Returns true if given |pointer| is valid, returns false otherwise.
   * @param {string} pointer
   * @returns {boolean} Whether pointer is valid.
   */
  function isValidJSONPointer(pointer) {
    switch (true) {
      case !isString(pointer):
        return false;

      case '' === pointer:
        return true;

      case NON_EMPTY_POINTER_REGEXP.test(pointer):
        return true;

      default:
        return false;
    }
  }

  /**
   * Returns tokens list for given |pointer|. List is reversed, e.g.
   *     '/simple/path' -> ['path', 'simple']
   * @param {!string} pointer JSON pointer string.
   * @returns {Array} List of tokens.
   */
  function parsePointer(pointer) {
    var tokens = pointer.split(TOKENS_SEPARATOR).reverse();
    tokens.pop();  // Last item is always an empty string in any valid pointer.
    return tokens;
  }

  /**
   * Decodes all escape sequences in given |rawReferenceToken|.
   * @param {!string} rawReferenceToken
   * @returns {string} Unescaped reference token.
   */
  function unescapeReferenceToken(rawReferenceToken) {
    var referenceToken = rawReferenceToken;
    var character;
    var escapeSequence;
    var replaceRegExp;

    SPECIAL_CHARACTERS.forEach(function(pair) {
      character = pair[0];
      escapeSequence = pair[1];
      replaceRegExp = new RegExp(escapeSequence, 'g');
      referenceToken = referenceToken.replace(replaceRegExp, character);
    });

    return referenceToken;
  }

  /**
   * Returns value pointed by |token| in evaluation |context|.
   * Throws an exception if any error occurs.
   * @param {*} context Current evaluation context.
   * @param {!string} token Unescaped reference token.
   * @returns {*} Some value of undefined if value if not found.
   */
  function getValue(context, token) {
    // Section 4 of spec.

    token = unescapeReferenceToken(token);

    if (isArray(context)) {
      if ('-' === token) {
        throw getError(ErrorMessage.HYPHEN_IS_NOT_SUPPORTED_IN_ARRAY_CONTEXT);
      }
      if (!isNumber(token)) {
        throw getError(ErrorMessage.NON_NUMBER_TOKEN_IN_ARRAY_CONTEXT);
      }
      if (token.length > 1 && '0' === token[0]) {
        throw getError(ErrorMessage.TOKEN_WITH_LEADING_ZERO_IN_ARRAY_CONTEXT);
      }
      return context[token];
    }

    if (isObject(context)) {
      return context[token];
    }

    // Context is not an array and is not an object.
    // Token evaluation is not possible.
    return;  // undefined
  }

  /**
   * Returns Error instance for throwing.
   * @param {string} message Error message.
   * @returns {Error}
   */
  function getError(message) {
    return new Error(ERROR_MESSAGE_PREFIX + message);
  }

  function isObject(o) {
    return 'object' === typeof o && null !== o;
  }

  function isArray(a) {
    return Array.isArray(a);
  }

  function isNumber(n) {
    return !isNaN(Number(n));
  }

  function isString(s) {
    return 'string' === typeof s || s instanceof String;
  }

  function isUndefined(v) {
    return 'undefined' === typeof v;
  }

  // Expose API

  var jsonpointer = {
    get: getPointedValue
  };

  if ('object' === typeof exports) {
    // Node.js
    module.exports = jsonpointer;
  } else if ('function' === typeof define && define.amd) {
    // AMD
    define(function() {
      return jsonpointer;
    });
  } else {
    // Browser
    this.jsonpointer = jsonpointer;
  }

}).call((function() {
  'use strict';
  return this || (typeof window !== 'undefined' ? window : global);
})());
<commit_msg>Fix JSDoc<commit_after>/**
 * @author Alexey Kuzmin <alex.s.kuzmin@gmail.com>
 * @fileoverview JavaScript implementation of JSON Pointer.
 * @see http://tools.ietf.org/html/rfc6901
 */

;(function() {
  'use strict';

  /**
   * List of special characters and their escape sequences.
   * Special characters will be unescaped in order they are listed.
   * Section 3 of spec.
   * @type {Array.<Array.<string>>}
   * @const
   */
  var SPECIAL_CHARACTERS = [
    ['/', '~1'],
    ['~', '~0']
  ];

  /**
   * Tokens' separator in JSON pointer string.
   * Section 3 of spec.
   * @type {string}
   * @const
   */
  var TOKENS_SEPARATOR = '/';

  /**
   * Prefix for error messages.
   * @type {string}
   * @const
   */
  var ERROR_MESSAGE_PREFIX = 'JSON Pointer: ';

  /**
   * Validates non-empty pointer string.
   * @type {RegExp}
   * @const
   */
  var NON_EMPTY_POINTER_REGEXP = /(\/[^\/]*)+/;

  /**
   * List of error messages.
   * Please keep it in alphabetical order.
   * @enum {string}
   */
  var ErrorMessage = {
    HYPHEN_IS_NOT_SUPPORTED_IN_ARRAY_CONTEXT:
        'Implementation does not support "-" token for arrays.',
    INVALID_DOCUMENT: 'JSON document is not valid.',
    INVALID_DOCUMENT_TYPE: 'JSON document must be a string.',
    INVALID_POINTER: 'Pointer is not valid.',
    NON_NUMBER_TOKEN_IN_ARRAY_CONTEXT:
        'Non-number tokens cannot be used in array context.',
    TOKEN_WITH_LEADING_ZERO_IN_ARRAY_CONTEXT:
        'Token with leading zero cannot be used in array context.'
  };

  /**
   * Returns |target| object's value pointed by |pointer|, returns undefined
   * if |pointer| points to non-existing value.
   * @param {!string} target JSON document.
   * @param {!string} pointer JSON Pointer string.
   * @returns {*} Some value.
   */
  function getPointedValue(target, pointer) {

    if (!isString(target)) {
      throw getError(ErrorMessage.INVALID_DOCUMENT_TYPE);
    }
    if (!isValidJSONPointer(pointer)) {
      throw getError(ErrorMessage.INVALID_POINTER);
    }
    try {
      target = JSON.parse(target);
    }
    catch (e) {
      throw getError(ErrorMessage.INVALID_DOCUMENT);
    }

    var tokensList = parsePointer(pointer);
    var token;
    var value = target;

    while (!isUndefined(value) && !isUndefined(token = tokensList.pop())) {
      value = getValue(value, token);
    }

    return value;
  }

  /**
   * Returns true if given |pointer| is valid, returns false otherwise.
   * @param {string} pointer
   * @returns {boolean} Whether pointer is valid.
   */
  function isValidJSONPointer(pointer) {
    switch (true) {
      case !isString(pointer):
        return false;

      case '' === pointer:
        return true;

      case NON_EMPTY_POINTER_REGEXP.test(pointer):
        return true;

      default:
        return false;
    }
  }

  /**
   * Returns tokens list for given |pointer|. List is reversed, e.g.
   *     '/simple/path' -> ['path', 'simple']
   * @param {!string} pointer JSON pointer string.
   * @returns {Array} List of tokens.
   */
  function parsePointer(pointer) {
    var tokens = pointer.split(TOKENS_SEPARATOR).reverse();
    tokens.pop();  // Last item is always an empty string in any valid pointer.
    return tokens;
  }

  /**
   * Decodes all escape sequences in given |rawReferenceToken|.
   * @param {!string} rawReferenceToken
   * @returns {string} Unescaped reference token.
   */
  function unescapeReferenceToken(rawReferenceToken) {
    var referenceToken = rawReferenceToken;
    var character;
    var escapeSequence;
    var replaceRegExp;

    SPECIAL_CHARACTERS.forEach(function(pair) {
      character = pair[0];
      escapeSequence = pair[1];
      replaceRegExp = new RegExp(escapeSequence, 'g');
      referenceToken = referenceToken.replace(replaceRegExp, character);
    });

    return referenceToken;
  }

  /**
   * Returns value pointed by |token| in evaluation |context|.
   * Throws an exception if any error occurs.
   * @param {*} context Current evaluation context.
   * @param {!string} token Unescaped reference token.
   * @returns {*} Some value or undefined if value if not found.
   */
  function getValue(context, token) {
    // Section 4 of spec.

    token = unescapeReferenceToken(token);

    if (isArray(context)) {
      if ('-' === token) {
        throw getError(ErrorMessage.HYPHEN_IS_NOT_SUPPORTED_IN_ARRAY_CONTEXT);
      }
      if (!isNumber(token)) {
        throw getError(ErrorMessage.NON_NUMBER_TOKEN_IN_ARRAY_CONTEXT);
      }
      if (token.length > 1 && '0' === token[0]) {
        throw getError(ErrorMessage.TOKEN_WITH_LEADING_ZERO_IN_ARRAY_CONTEXT);
      }
      return context[token];
    }

    if (isObject(context)) {
      return context[token];
    }

    // Context is not an array and is not an object.
    // Token evaluation is not possible.
    return;  // undefined
  }

  /**
   * Returns Error instance for throwing.
   * @param {string} message Error message.
   * @returns {Error}
   */
  function getError(message) {
    return new Error(ERROR_MESSAGE_PREFIX + message);
  }

  function isObject(o) {
    return 'object' === typeof o && null !== o;
  }

  function isArray(a) {
    return Array.isArray(a);
  }

  function isNumber(n) {
    return !isNaN(Number(n));
  }

  function isString(s) {
    return 'string' === typeof s || s instanceof String;
  }

  function isUndefined(v) {
    return 'undefined' === typeof v;
  }

  // Expose API

  var jsonpointer = {
    get: getPointedValue
  };

  if ('object' === typeof exports) {
    // Node.js
    module.exports = jsonpointer;
  } else if ('function' === typeof define && define.amd) {
    // AMD
    define(function() {
      return jsonpointer;
    });
  } else {
    // Browser
    this.jsonpointer = jsonpointer;
  }

}).call((function() {
  'use strict';
  return this || (typeof window !== 'undefined' ? window : global);
})());
<|endoftext|>


<commit_before>'use strict';   // dont touch
const fs = require('fs');
var auth = require('./auth.js');
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch

// [General]
this.name = "Auth"; // Name of plugin REQUIRED
this.author = "andrews54757"; // author REQUIRED
this.description = 'An auth plugin'; // Desciprtion
this.compatVersion = ''; // compatable with
this.version = '1.0.0'; // version REQUIRED

// [Extra Commands]
this.commandName[0] = "auth"; // plugin add-on command names
this.addToHelp[0] = "auth     : Auth plugin command"; // help command add-on (adds this string to the help command)
this.command[0] = require('./command.js'); // extra command location

// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location

// [Configs]
this.config = {
requirelogin: 0,
plugin: 1,
allowregister: 1,
recordint: 100,
}
this.configfile = 'config.ini'

// [Functions]
this.init = function (gameServer, config) {
  this.config = config;
  auth.init(this, gameServer);
  gameServer.beforespawn = function(player) {

   return auth.beforespawn(player,gameServer);
  };
  gameServer.beforeq = function(player) {
    return auth.beforeq(player, gameServer);

  };
  gameServer.beforeeject = function(player) {return auth.beforeeject(player,gameServer);};
  gameServer.beforesplit = function(player) {return auth.beforesplit(player,gameServer);};
  gameServer.account = JSON.parse(fs.readFileSync('accounts.json'));
  gameServer.auon = this.config.plugin;
  console.log("[Auth] Auth loaded")
  // init, Used to do stuff such as overriding things

};

this.onSecond = function (gameServer) {
if (!this.up) this.up = 0;
if (this.up < this.config.recordint) {
  this.up ++;

} else {
  this.up = 0;
  fs.writeFileSync('accounts.json',JSON.stringify(gameServer.account, null, 2));
}

  // called every second
};

module.exports = this; // dont touch
<commit_msg>Update index.js<commit_after>'use strict';   // dont touch
const fs = require('fs');
var auth = require('./auth.js');
this.command = []; // dont touch
this.commandName = []; // dont touch
this.gamemodeId = []; // dont touch
this.gamemode = []; // dont touch
this.addToHelp = []; // dont touch

// [General]
this.name = "Auth"; // Name of plugin REQUIRED
this.author = "andrews54757"; // author REQUIRED
this.description = 'An auth plugin'; // Desciprtion
this.compatVersion = ''; // compatable with
this.version = '1.0.0'; // version REQUIRED

// [Extra Commands]
this.commandName[0] = "auth"; // plugin add-on command names
this.addToHelp[0] = "auth     : Auth plugin command"; // help command add-on (adds this string to the help command)
this.command[0] = require('./command.js'); // extra command location

// [Extra Gamemodes]
this.gamemodeId[0] = ''; // gamemodeids of extra plugin gamemodes
this.gamemode[0] = ''; // gamemode location

// [Configs]
this.config = {
requirelogin: 0,
plugin: 1,
allowregister: 1,
recordint: 100,
}
this.configfile = 'config.ini'

// [Functions]
this.init = function (gameServer, config) {
  this.config = config;
  auth.init(this, gameServer);
  gameServer.beforespawn = function(player) {

   return auth.beforespawn(player,gameServer);
  };
  gameServer.beforeq = function(player) {
    return auth.beforeq(player, gameServer);

  };
  gameServer.beforeeject = function(player) {return auth.beforeeject(player,gameServer);};
  gameServer.beforesplit = function(player) {return auth.beforesplit(player,gameServer);};
  gameServer.account = JSON.parse(fs.readFileSync('accounts.json'));
  gameServer.auon = this.config.plugin;
  console.log("[Auth] Auth loaded. Accounts located in accounts.json")
  // init, Used to do stuff such as overriding things

};

this.onSecond = function (gameServer) {
if (!this.up) this.up = 0;
if (this.up < this.config.recordint) {
  this.up ++;

} else {
  this.up = 0;
  fs.writeFileSync('accounts.json',JSON.stringify(gameServer.account, null, 2));
}

  // called every second
};

module.exports = this; // dont touch
<|endoftext|>


<commit_before>module.exports = {
  webpack: function (config) {
    config.resolve.alias = {
      'react': 'preact-compat',
      'react-dom': 'preact-compat'
    }
    return config
  }
}
<commit_msg>Use the preact-compat dist version. (#760)<commit_after>module.exports = {
  webpack: function (config) {
    config.resolve.alias = {
      'react': 'preact-compat/dist/preact-compat',
      'react-dom': 'preact-compat/dist/preact-compat'
    }
    return config
  }
}
<|endoftext|>