<commit_before>(function (root, factory) {
    if (typeof exports === 'object') {
        module.exports.Events = factory();
    } else if (typeof define === 'function' && define.amd) {
        define(function () {
            return {Events : factory()};
        });
    } else {
        root.Events = factory();
    }
}(this, function (){
    /**
     * @module Events
     */

    var use_dom = false,
        pseudo_regex = /([^:]+)(?:\:([^(]*)(?:\((.*)\))?)?/,
        addEvent, addEvents, fireEvent, removeEvent, addEventOnce, Events, fireLatchedEvent, removeLatchedEvent;

    try {
        use_dom = document && 'addEventListener' in document;
    }catch(e){}

    //=================
    //    UTILITIES
    //=================

    //utility function for cross-browser
    function indexOf(arr,prop){
        if (arr.indexOf) return arr.indexOf(prop);
        else return String.prototype.indexOf(arr,prop);
    }

    //handles warnings set by the library
    function warn(error){
        if (Events.strict){
            throw new Error(error);
        }else if ('console' in window){
            if (console.error) console.error(error);
            else if (console.warn) console.warn(error);
            else console.log(error);
        }
    }

    /**
     * removes the on* prefix from event names
     * @method Events.removeOn
     * @static
     *
     * @param {string} type
     *
     * @return {string}
     */
    function removeOn(string){
        return string.replace(/^on([A-Z])/, function(full, first){
            return first.toLowerCase();
        });
    }

    /**
     * returns a structured data object about a type's pseudo-events
     *
     * @method getPseudo
     * @private
     * @static
     *
     * @param {string} type
     *
     * @return {Object} data
     */
    function getPseudo(string){
        var match = string.match(pseudo_regex);

        if (string.split(':').length > 2) warn("Library does not support multiple pseudo events");

        return {
            name : match[1],
            pseudo : match[2],
            args : match[3]
        };
    }

    /**
     * proccesses an event type, returning a valid data object from that name
     * @method processType
     * @static
     * @private
     *
     * @param {string} type
     *
     * @return {Object} data
     */
    function processType(type){
        return getPseudo(removeOn(type));
    }

    /**
     * cross-browser function to create event object for fire method
     *
     * Created object will always have following properties:
     *  - dispatcher: a reference to dispatching object (since we can't use 'this')
     *  - args: arguments passed alongside the event
     *  - object_event: a flag set to true to easily check if this is an object event or a normal DOM event.
     *
     * @method Events.createEvent
     * @static
     * @private
     *
     * @param {string} type
     * @param {object} dispatcher
     * @param {mixed} args
     *
     * @return event object
     */
    function createEvent(type, dis, args){
        var ev;

        if (use_dom){
            ev = document.createEvent('UIEvents');
            ev.initUIEvent(type, false, false, window, 1);
        }else{
            ev = {};
        }

        ev.dispatcher = dis;
        ev.args = args;
        ev.object_event = true;

        return ev;
    }

    /**
     * Events Provider.
     *
     * Can function either as a standalone or a Mixin
     *
     * @class Events
     * @constructor
     *
     * @param {Element} el element to use as event target. Optional
     */
    Events = function Events(el){
        var $this = this, alias,
            destroy_names = "$event_element $latched $events $once addEvent addEvents fireEvent removeEvent addEventOnce fireLatchedEvent".split(' ');

        if (!use_dom){
            this.$events = {};
        }else{
            this.$event_element = el || document.createElement('events');
        }

        this.$has_events = true;
        this.$latched = {};
        this.$once    = {};

        this.addEvent = addEvent;
        this.addEvents = addEvents;
        this.fireEvent = fireEvent;
        this.removeEvent = removeEvent;
        this.addEventOnce = addEventOnce;
        this.fireLatchedEvent = fireLatchedEvent;
        this.removeLatchedEvent = removeLatchedEvent;

        for (alias in Events.aliases) {
            this[alias] = this[Events.aliases[alias]];
            destroy_names.push(alias);
        }

        //since this code removes the reference to the events provider,
        //we want to make sure it runs after the rest of the loop is done.
        this.addEvent('destroy:delay(0)',function(){
            var i, name;

            for (i=0; name = destroy_names[i]; i++) $this[name] = null;

            this.$events_destroyed = true;
        });
    };

    //In case someone want to use these
    Events.removeOn = removeOn;
    Events.getPseudos = getPseudo;
    Events.processType = processType;
    Events.createEvent = createEvent;
    Events.strict = false;

    /**
     * A list of aliases for Events methods. Use this to add similar syntax to other event implementations
     *
     * By default, aliases include most of EventEmitter interface
     *
     * @property aliases
     * @type object
     * @public
     * @static
     */
    Events.aliases = {
        'on' : 'addEvent',
        'addListener' : 'addEvent',
        'once' : 'addEventOnce',
        'removeListener' : 'removeEvent',
        'off' : 'removeEvent',
        'emit' : 'fireEvent'
    };

    /*
     * Events.Pesudoes allows you to add pseudo behaviors
     *
     * Each object in the collection can hold both addEvent and fireEvent Methods
     *
     * The addEvent method will be fired *instead* of the normal behavior, and will be passed
     * the event type and fn
     *
     * The fireEvent method will be fired *after* the fireEvent method, and will be passed
     * the event name and the event object created
     *
     * Look at examples to see how it can be used
     *
     * @property Events.Pseudoes
     * @type {object}
     * @static
     */
    Events.Pseudoes = {
        once : {
            addEvent : function(type,fn){
                return this.addEventOnce(type, fn);
            }
        },

        latched : {
            fireEvent : function(type, args){
                return this.fireLatchedEvent(type,args);
            }
        },

        times : {
            addEvent : function(type, fn, ammount){
                var count = 0, $this = this;

                this.addEvent(type, function times(){
                    fn.apply(null, arguments);
                    count+=1;
                    if (count == ammount) $this.removeEvent(type,times);
                });
            }
        },

        delay : {
            addEvent : function(type, fn, delay){
                this.addEvent(type, function(){
                    setTimeout(fn,delay);
                });
            },
            fireEvent : function(type, args, delay){
                var $this = this;
                setTimeout(function(){
                    $this.fireEvent(type, args);
                }, delay);
            }
        }
    };

    //========================
    // cross-browser utilities
    //========================

    function register(obj, type, fn){
        if (use_dom){
            obj.$event_element.addEventListener(type,fn,false);
        }else{
            if (!obj.$events[type]) obj.$events[type] = [fn];
            else if (indexOf(obj.$events[type],fn)==-1){
                obj.$events[type].push(fn);
            }
        }
    }

    function dispatch(obj,type, ev){
        var i, fn;

        if (use_dom){
            obj.$event_element.dispatchEvent(ev);
        }else{
            if (!obj.$events[type]) return;

            for (i=0; fn = obj.$events[type][i]; i++){
                fn.apply(null,[ev]);
            }
        }
    }

    function remove(obj, type, fn){
        var index;

        if (use_dom){
            obj.$event_element.removeEventListener(type,fn,false);
        }else{
            if (!obj.$events[type]) return;

            index = indexOf(obj.$events[type],fn);

            if (index <0) return;

            obj.$events[type].splice(index,1);
        }
    }

    //=======================
    // Function Declarations
    //=======================

    /**
     * Adds an event
     *
     * @method addEvent
     *
     * @param {String}    the event type
     * @param {Function}  a function to add
     *
     * @chainable
     */
    addEvent = function addEvent(type,fn){
        if (this.$events_destroyed) return this;

        var data = processType(type),
            pseudo_fn = Events.Pseudoes[data.pseudo] && Events.Pseudoes[data.pseudo].addEvent,
            args = this.$latched[data.name] && this.$latched[data.name].args,
            ev;

        if (pseudo_fn){
            return pseudo_fn.apply(this,[data.name,fn,data.args]);
        }

        register(this,data.name, fn);

        if (this.$latched && this.$latched[data.name]){
            ev = createEvent(data.name, this, args);
            fn.apply(null,[ev]);
        }

        return this;
     };

    /**
     * Helper to add multiple events at once
     *
     * @method addEvents
     *
     * @param {Object} literal object of event types => callbacks
     *
     * @chainable
     */
    addEvents = function addEvents(events){
        if (this.$events_destroyed) return this;
        var type;

        for (type in events) if (events.hasOwnProperty(type)){
            this.addEvent(type, events[type]);
        }

        return this;
    };

    /**
     * dispatches an event
     *
     * @method fireEvent
     *
     * @param {String} event type
     * @param {Mixed}  arguments to pass with the event
     *
     * @chainable
     */
    fireEvent = function fireEvent(type, args){
        if (this.$events_destroyed) return this;
        var data = processType(type),
            pseudo_fn = Events.Pseudoes[data.pseudo] && Events.Pseudoes[data.pseudo].fireEvent,
            ev, fn,
            once_arr,
            temp_arr;

        if (pseudo_fn){
            return pseudo_fn.call(this,data.name,args);
        }

        //in case one of the callbacks will try and add another once event,
        //we keep a reference of the once stack, and then empty it
        once_arr = this.$once[data.name];
        this.$once[data.name] = null;

        ev = createEvent(data.name, this, args);

        dispatch(this,data.name,ev);

        if (!once_arr) return this;

        while (fn = once_arr.pop()){
            this.removeEvent(data.name, fn, true);
        }

        return this;
    };

    /**
     * removes a function from an event
     *
     * @method removeEvent
     *
     * @param {String}   event type
     * @param {Function} function to remove from stack
     *
     * @chainable
     */
    removeEvent = function removeEvent(type, fn,no_once){
        if (this.$events_destroyed) return this;
        var data = processType(type),
            index;

        remove(this,data.name, fn);

        if (!no_once && this.$once[data.name] && (index = indexOf(this.$once[data.name],fn))>-1){
            this.$once[data.name].splice(index,1);
        }

        return this;
    };

    /**
     * Adds an event for one execution, then removes it
     *
     * @method addEventOnce
     *
     * @param {String}    the event type
     * @param {Function}  a function to add
     *
     * @chainable
     */
    addEventOnce = function addEventOnce(type, fn){
        if (this.$events_destroyed) return this;
        var $this = this,
            data = processType(type);

        if (!this.$once[data.name]) this.$once[data.name] = [];
        if (indexOf(this.$once[data.name],fn) == -1){
            this.$once[data.name].push(fn);
        }

        return this.addEvent(data.name, fn);
    };

    /**
     * Fires a latched event
     *
     * @method fireLatchedEvent
     *
     * @param {String} the event type
     * @param {Mixed}  arguments to pass with the event
     *
     * @chainable
     */
    fireLatchedEvent = function fireLatchedEvent(type, args){
        if (this.$events_destroyed) return this;
        if (!this.$latched) this.$latched = {};

        this.$latched[type] = {args : args};
        this.fireEvent(type,args);

        return this;
    };

    removeLatchedEvent = function removeLatchedEvent(type) {
        this.$latched[type] = null;
    };

    Events.addEvent = addEvent;
    Events.addEvents = addEvents;
    Events.addEventOnce = addEventOnce;
    Events.fireEvent = fireEvent;
    Events.fireLatchedEvent = fireLatchedEvent;
    Events.removeLatchedEvent = removeLatchedEvent;
    Events.removeEvent = removeEvent;

    //expose Mixin to provided namespace
    return Events;
}));<commit_msg>adding some more mechanisms to configure events<commit_after>(function (root, factory) {
    if (typeof exports === 'object') {
        module.exports.Events = factory();
    } else if (typeof define === 'function' && define.amd) {
        define(function () {
            return {Events : factory()};
        });
    } else {
        root.Events = factory();
    }
}(this, function (){
    /**
     * @module Events
     */

    var use_dom = false,
        pseudo_regex = /([^:]+)(?:\:([^(]*)(?:\((.*)\))?)?/,
        addEvent, addEvents, fireEvent, removeEvent, addEventOnce, Events, fireLatchedEvent;

    try {
        use_dom = document && 'addEventListener' in document;
    }catch(e){}

    //=================
    //    UTILITIES
    //=================

    //utility function for cross-browser
    function indexOf(arr,prop){
        if (arr.indexOf) return arr.indexOf(prop);
        else return String.prototype.indexOf(arr,prop);
    }

    //handles warnings set by the library
    function warn(error){
        if (Events.strict){
            throw new Error(error);
        }else if ('console' in window){
            if (console.error) console.error(error);
            else if (console.warn) console.warn(error);
            else console.log(error);
        }
    }

    /**
     * removes the on* prefix from event names
     * @method Events.removeOn
     * @static
     *
     * @param {string} type
     *
     * @return {string}
     */
    function removeOn(string){
        return string.replace(/^on([A-Z])/, function(full, first){
            return first.toLowerCase();
        });
    }

    /**
     * returns a structured data object about a type's pseudo-events
     *
     * @method getPseudo
     * @private
     * @static
     *
     * @param {string} type
     *
     * @return {Object} data
     */
    function getPseudo(string){
        var match = string.match(pseudo_regex);

        if (string.split(':').length > 2) warn("Library does not support multiple pseudo events");

        return {
            name : match[1],
            pseudo : match[2],
            args : match[3]
        };
    }

    /**
     * proccesses an event type, returning a valid data object from that name
     * @method processType
     * @static
     * @private
     *
     * @param {string} type
     *
     * @return {Object} data
     */
    function processType(type){
        return getPseudo(removeOn(type));
    }

    /**
     * cross-browser function to create event object for fire method
     *
     * Created object will always have following properties:
     *  - dispatcher: a reference to dispatching object (since we can't use 'this')
     *  - args: arguments passed alongside the event
     *  - object_event: a flag set to true to easily check if this is an object event or a normal DOM event.
     *
     * @method Events.createEvent
     * @static
     * @private
     *
     * @param {string} type
     * @param {object} dispatcher
     * @param {mixed} args
     *
     * @return event object
     */
    function createEvent(type, dis, args, bubbles){
        var ev;

        if (use_dom){
            ev = document.createEvent('UIEvents');
            ev.initUIEvent(type, bubbles, true, window, 1);
        }else{
            ev = {};
        }

        ev.dispatcher = dis;
        ev.args = args;
        ev.object_event = true;

        return ev;
    }

    /**
     * Events Provider.
     *
     * Can function either as a standalone or a Mixin
     *
     * @class Events
     * @constructor
     *
     * @param {Element} el element to use as event target. Optional
     */
    Events = function Events(el,no_destroy){
        var $this = this, alias,
            destroy_names = "$event_element $latched $events $once addEvent addEvents fireEvent removeEvent addEventOnce fireLatchedEvent".split(' ');

        if (!use_dom){
            this.$events = {};
        }else{
            this.$event_element = el || document.createElement('events');
        }

        this.$has_events = true;
        this.$latched = {};
        this.$once    = {};

        this.addEvent = addEvent;
        this.addEvents = addEvents;
        this.fireEvent = fireEvent;
        this.removeEvent = removeEvent;
        this.addEventOnce = addEventOnce;
        this.fireLatchedEvent = fireLatchedEvent;
        this.removeLatchedEvent = removeLatchedEvent;

        for (alias in Events.aliases) {
            this[alias] = this[Events.aliases[alias]];
            destroy_names.push(alias);
        }

        //since this code removes the reference to the events provider,
        //we want to make sure it runs after the rest of the loop is done.
        if (!no_destroy) this.addEvent('destroy:delay(0)',function(){
            var i, name;

            if ($this.$no_ev_destroy) return;

            for (i=0; name = destroy_names[i]; i++) $this[name] = null;

            $this.$events_destroyed = true;
        });
    };

    //In case someone want to use these
    Events.removeOn = removeOn;
    Events.getPseudos = getPseudo;
    Events.processType = processType;
    Events.createEvent = createEvent;
    Events.strict = false;

    /**
     * A list of aliases for Events methods. Use this to add similar syntax to other event implementations
     *
     * By default, aliases include most of EventEmitter interface
     *
     * @property aliases
     * @type object
     * @public
     * @static
     */
    Events.aliases = {
        'on' : 'addEvent',
        'addListener' : 'addEvent',
        'once' : 'addEventOnce',
        'removeListener' : 'removeEvent',
        'off' : 'removeEvent',
        'emit' : 'fireEvent'
    };

    /*
     * Events.Pesudoes allows you to add pseudo behaviors
     *
     * Each object in the collection can hold both addEvent and fireEvent Methods
     *
     * The addEvent method will be fired *instead* of the normal behavior, and will be passed
     * the event type and fn
     *
     * The fireEvent method will be fired *after* the fireEvent method, and will be passed
     * the event name and the event object created
     *
     * Look at examples to see how it can be used
     *
     * @property Events.Pseudoes
     * @type {object}
     * @static
     */
    Events.Pseudoes = {
        once : {
            addEvent : function(type,fn){
                return this.addEventOnce(type, fn);
            }
        },

        latched : {
            fireEvent : function(type, args){
                return this.fireLatchedEvent(type,args);
            }
        },

        times : {
            addEvent : function(type, fn, ammount){
                var count = 0, $this = this;

                this.addEvent(type, function times(){
                    fn.apply(null, arguments);
                    count+=1;
                    if (count == ammount) $this.removeEvent(type,times);
                });
            }
        },

        delay : {
            addEvent : function(type, fn, delay){
                this.addEvent(type, function(){
                    setTimeout(fn,delay);
                });
            },
            fireEvent : function(type, args, delay){
                var $this = this;
                setTimeout(function(){
                    $this.fireEvent(type, args);
                }, delay);
            }
        }
    };

    //========================
    // cross-browser utilities
    //========================

    function register(obj, type, fn){
        if (use_dom){
            obj.$event_element.addEventListener(type,fn,false);
        }else{
            if (!obj.$events[type]) obj.$events[type] = [fn];
            else if (indexOf(obj.$events[type],fn)==-1){
                obj.$events[type].push(fn);
            }
        }
    }

    function dispatch(obj,type, ev){
        var i, fn;

        if (use_dom){
            obj.$event_element.dispatchEvent(ev);
        }else{
            if (!obj.$events[type]) return;

            for (i=0; fn = obj.$events[type][i]; i++){
                fn.apply(null,[ev]);
            }
        }
    }

    function remove(obj, type, fn){
        var index;

        if (use_dom){
            obj.$event_element.removeEventListener(type,fn,false);
        }else{
            if (!obj.$events[type]) return;

            index = indexOf(obj.$events[type],fn);

            if (index <0) return;

            obj.$events[type].splice(index,1);
        }
    }

    //=======================
    // Function Declarations
    //=======================

    /**
     * Adds an event
     *
     * @method addEvent
     *
     * @param {String}    the event type
     * @param {Function}  a function to add
     *
     * @chainable
     */
    addEvent = function addEvent(type,fn){
        if (this.$events_destroyed) return this;

        var data = processType(type),
            pseudo_fn = Events.Pseudoes[data.pseudo] && Events.Pseudoes[data.pseudo].addEvent,
            args = this.$latched[data.name] && this.$latched[data.name].args,
            ev;

        if (pseudo_fn){
            return pseudo_fn.apply(this,[data.name,fn,data.args]);
        }

        register(this,data.name, fn);

        if (this.$latched && this.$latched[data.name]){
            ev = createEvent(data.name, this, args);
            fn.apply(null,[ev]);
        }

        return this;
     };

    /**
     * Helper to add multiple events at once
     *
     * @method addEvents
     *
     * @param {Object} literal object of event types => callbacks
     *
     * @chainable
     */
    addEvents = function addEvents(events){
        if (this.$events_destroyed) return this;
        var type;

        for (type in events) if (events.hasOwnProperty(type)){
            this.addEvent(type, events[type]);
        }

        return this;
    };

    /**
     * dispatches an event
     *
     * @method fireEvent
     *
     * @param {String} event type
     * @param {Mixed}  arguments to pass with the event
     *
     * @chainable
     */
    fireEvent = function fireEvent(type, args, bubbles){
        if (this.$events_destroyed) return this;
        var data = processType(type),
            pseudo_fn = Events.Pseudoes[data.pseudo] && Events.Pseudoes[data.pseudo].fireEvent,
            ev, fn,
            once_arr,
            temp_arr;

        if (bubbles == null) bubbles = true;

        if (pseudo_fn){
            return pseudo_fn.call(this,data.name,args);
        }

        //in case one of the callbacks will try and add another once event,
        //we keep a reference of the once stack, and then empty it
        once_arr = this.$once[data.name];
        this.$once[data.name] = null;

        ev = createEvent(data.name, this, args, bubbles);

        dispatch(this,data.name,ev);

        if (!once_arr) return this;

        while (fn = once_arr.pop()){
            this.removeEvent(data.name, fn, true);
        }

        return this;
    };

    /**
     * removes a function from an event
     *
     * @method removeEvent
     *
     * @param {String}   event type
     * @param {Function} function to remove from stack
     *
     * @chainable
     */
    removeEvent = function removeEvent(type, fn,no_once){
        if (this.$events_destroyed) return this;
        var data = processType(type),
            index;

        remove(this,data.name, fn);

        if (!no_once && this.$once[data.name] && (index = indexOf(this.$once[data.name],fn))>-1){
            this.$once[data.name].splice(index,1);
        }

        return this;
    };

    /**
     * Adds an event for one execution, then removes it
     *
     * @method addEventOnce
     *
     * @param {String}    the event type
     * @param {Function}  a function to add
     *
     * @chainable
     */
    addEventOnce = function addEventOnce(type, fn){
        if (this.$events_destroyed) return this;
        var $this = this,
            data = processType(type);

        if (!this.$once[data.name]) this.$once[data.name] = [];
        if (indexOf(this.$once[data.name],fn) == -1){
            this.$once[data.name].push(fn);
        }

        return this.addEvent(data.name, fn);
    };

    /**
     * Fires a latched event
     *
     * @method fireLatchedEvent
     *
     * @param {String} the event type
     * @param {Mixed}  arguments to pass with the event
     *
     * @chainable
     */
    fireLatchedEvent = function fireLatchedEvent(type, args){
        if (this.$events_destroyed) return this;
        if (!this.$latched) this.$latched = {};

        this.$latched[type] = {args : args};
        this.fireEvent(type,args);

        return this;
    };

    Events.addEvent = addEvent;
    Events.addEvents = addEvents;
    Events.addEventOnce = addEventOnce;
    Events.fireEvent = fireEvent;
    Events.fireLatchedEvent = fireLatchedEvent;
    Events.removeEvent = removeEvent;

    //expose Mixin to provided namespace
    return Events;
}));<|endoftext|>


<commit_before>function extend(BaseClass, SubClass) {
    var newClassDefinition,
        i;
    for (i in BaseClass.prototype) {
        SubClass.prototype[i] = BaseClass.prototype[i];
    }
    SubClass.prototype.uber = BaseClass.prototype;
    newClassDefinition = function () {
        var ancestor = SubClass.prototype.uber,
            inheritanceChain = [];
        while (ancestor) {
            inheritanceChain.push(ancestor.constructor);
            ancestor = ancestor.uber;
        }
        while (inheritanceChain.length) {
            inheritanceChain[inheritanceChain.length - 1].apply(this, arguments);
            inheritanceChain = inheritanceChain.slice(0, inheritanceChain.length - 1);
        }
        SubClass.apply(this, arguments);
    }
    newClassDefinition.prototype = SubClass.prototype;
    return newClassDefinition;
}
module.exports = extend;
////////////////////////////
////////////////////////////
////////////////////////////
///sample code
////////////////////////////
////////////////////////////
////////////////////////////
function Shape() {
    Log.Message('Shape Constructor ran');
};

function TwoDShape() {
    Log.Message('TwoDShape Constructor ran');
};
TwoDShape = extend(Shape, TwoDShape);

function ThreeDShape() {
    Log.Message('ThreeDShape Constructor ran');
};
ThreeDShape = extend(TwoDShape, ThreeDShape);
var a3DShape = new ThreeDShape();
//prints: "Shape Constructor ran... TwoDShape Constructor ran.... ThreeDShape Constructor ran"
//and also initializes all instance members just like they were meant by the superclass implementation
//a3DShape has access to every member-function/method in both Shape and TwoDShape and may override methods and gain access to the superclass definition in spite of the overrides. And it will also feature properties for any member variable be it an object or an array:
TwoDShape.prototype.toString = function () {
    return TwoDShape.prototype.uber.toString.call(this) + " " + this.name;
};
ThreeDShape.prototype.toString = function () {
    return ThreeDShape.prototype.uber.toString.call(this) + " " + this.name;
};<commit_msg>cleaning up<commit_after>function extend(BaseClass, SubClass) {
    var newClassDefinition,
        i;
    for (i in BaseClass.prototype) {
        SubClass.prototype[i] = BaseClass.prototype[i];
    }
    SubClass.prototype.uber = BaseClass.prototype;
    newClassDefinition = function () {
        var ancestor = SubClass.prototype.uber,
            inheritanceChain = [];
        while (ancestor) {
            inheritanceChain.push(ancestor.constructor);
            ancestor = ancestor.uber;
        }
        while (inheritanceChain.length) {
            inheritanceChain[inheritanceChain.length - 1].apply(this, arguments);
            inheritanceChain = inheritanceChain.slice(0, inheritanceChain.length - 1);
        }
        SubClass.apply(this, arguments);
    }
    newClassDefinition.prototype = SubClass.prototype;
    return newClassDefinition;
}
module.exports = extend;<|endoftext|>


<commit_before>const statuses = ["online", "idle", "invisible", "dnd"];

module.exports = {
    roles: ["[admin]"],
    descr: "Cambia el estado del bot.",
    exec: (message, args) => {
        if(statuses.includes(args[1])) {
            global.bot.user.setStatus(args[1]);
        } else {
            message.author.sendEmbed({
                description: "El estado debe ser `online`, `idle`, `invisible` o `dnd` (do not disturb).",
                color: 2527667
            });
        }
        message.delete();
    }
}
<commit_msg>Fixed - !status<commit_after>const Discord = require("discord.js");

const statuses = ["online", "idle", "invisible", "dnd"];

module.exports = {
    roles: ["[boss]"],
    descr: "Cambia el estado del bot.",
    exec: (message, args) => {
        if(statuses.includes(args[1])) {
            global.bot.user.setStatus(args[1]);
        } else {
            const embed = new Discord.RichEmbed();
            embed.setDescription("El estado debe ser `online`, `idle`, `invisible` o `dnd` (do not disturb).");
            embed.setColor(2527667);

            message.author.send('', Discord.MessageOptions = { embed: embed });
        }
        message.delete();
    }
}
<|endoftext|>


<commit_before>/**
 * @fileOverview Requirejs module containing HTML5 video and audio media wrapper
 *
 * @preserve Copyright (c) 2013 British Broadcasting Corporation
 * (http://www.bbc.co.uk) and TAL Contributors (1)
 *
 * (1) TAL Contributors are listed in the AUTHORS file and at
 *     https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
 *     not this notice.
 *
 * @license Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * All rights reserved
 * Please contact us for an alternative licence
 */

require.def(
    'antie/devices/media/html5',
    [
        'antie/devices/device',
        'antie/widgets/media',
        'antie/events/mediaevent',
        'antie/events/mediaerrorevent',
        'antie/events/mediasourceerrorevent',
        'antie/mediasource'
    ],
    function(Device, Media, MediaEvent, MediaErrorEvent, MediaSourceErrorEvent, MediaSource) {
        var currentPlayer = null;
        var isMuted = null;
        var currentVolume = -1;

        var HTML5Player = Media.extend({
            init: function(id, mediaType) {
                this._super(id);

                if (mediaType == "audio") {
                    this._mediaType = "audio";
                } else if (mediaType == "video") {
                    this._mediaType = "video";
                } else {
                    throw new Error('Unrecognised media type: ' + mediaType);
                }

                // Create the DOM element now so the wrapped functions can modify attributes
                // before it is placed in the Document during rendering.
                var device = this.getCurrentApplication().getDevice();
                this._mediaElement = device._createElement(this._mediaType, this.id, this.getClasses());

                if (currentVolume != -1) {
                    this._mediaElement.volume = currentVolume;
                } else {
                    currentVolume = this._mediaElement.volume;
                }
                if (isMuted !== null) {
                    this._mediaElement.muted = isMuted;
                } else {
                    isMuted = this._mediaElement.muted;
                }

                this._eventWrapper = null;
                this._errorEventWrapper = null;
            },
            render: function(device) {
                if (this.outputElement !== this._mediaElement) {
                    this.outputElement = this._mediaElement;

                    // Convert all media events into our internal representation and bubble them through
                    // the UI widgets
                    var self = this;
                    this._eventWrapper = function(evt) {
                        self.bubbleEvent(new MediaEvent(evt.type, self));
                    };
                    this._errorEventWrapper = function(evt) {
                        var errCode = self._mediaElement.error ? self._mediaElement.error.code : Media.MEDIA_ERR_UNKNOWN;
                        self.bubbleEvent(new MediaErrorEvent(self, errCode));
                    };
                    for (var i = 0; i < MediaEvent.TYPES.length; i++) {
                        this._mediaElement.addEventListener(MediaEvent.TYPES[i], this._eventWrapper, true);
                    }
                    this._mediaElement.addEventListener("error", this._errorEventWrapper, true);
                }

                return this._mediaElement;
            },
            // (not part of HTML5 media)
            setWindow: function(left, top, width, height) {
                if (this._mediaType == "audio") {
                    throw new Error('Unable to set window size for HTML5 audio.');
                }
                var device = this.getCurrentApplication().getDevice();
                device.setElementSize(this._mediaElement, {width:width, height:height});
                device.setElementPosition(this._mediaElement, {left:left, top:top});
            },
            // readonly attribute MediaError error;
            getError: function() {
                return this._mediaElement.error;
            },
            _supportsTypeAttribute: function() {
                return true;
            },
            _requiresWebkitMemoryLeakFix: function() {
                return false;
            },
            // Similar to src attribute or 'source' child elements:
            // attribute DOMString src;
            setSources: function(sources, tags) {
                var self = this;
                var device = this.getCurrentApplication().getDevice();
                var oldSources = this._mediaElement.getElementsByTagName('source');
                var supportsTypeAttribute = this._supportsTypeAttribute();

                while (oldSources.length) {
                    device.removeElement(oldSources[0]);
                }
                for (var i = 0; i < sources.length; i++) {
                    var source = document.createElement('source');
                    if (supportsTypeAttribute) {
                        source.type = sources[i].getContentType();
                    }
                    source.src = sources[i].getURL(tags);

                    device.appendChildElement(this._mediaElement, source);

                    (function(source) {
                        source._errorEventListener = function(evt) {
                            var errCode = self._mediaElement.error ? self._mediaElement.error.code : Media.MEDIA_ERR_UNKNOWN;
                            self.bubbleEvent(new MediaSourceErrorEvent(
                                self,
                                errCode,
                                source.src,
                                self._mediaElement.networkState === HTMLMediaElement.NETWORK_NO_SOURCE
                            ));
                            evt.stopPropagation();
                        };
                        source.addEventListener("error", source._errorEventListener, true);
                    })(source);
                }
            },
            getSources: function() {
                var sources = [];
                if (this._mediaElement.src) {
                    sources.push(new MediaSource(this._mediaElement.src, this._mediaElement.type));
                } else {
                    var sourceElements = this._mediaElement.getElementsByTagName('source');
                    for (var i = 0; i < sourceElements.length; i++) {
                        sources.push(new MediaSource(sourceElements[i].src, sourceElements[i].type));
                    }
                }
                return sources;
            },
            // readonly attribute DOMString currentSrc;
            getCurrentSource: function() {
                // Some browsers URI encode apostrophes, others don't. Make sure they're all URI encoded.
                return this._mediaElement.currentSrc.replace(/'/g, "%27");
            },
            /*
             const unsigned short NETWORK_EMPTY = 0;
             const unsigned short NETWORK_IDLE = 1;
             const unsigned short NETWORK_LOADING = 2;
             const unsigned short NETWORK_NO_SOURCE = 3;
             readonly attribute unsigned short networkState;
             */
            getNetworkState: function() {
                return this._mediaElement.networkState;
            },
            // attribute DOMString preload;
            // @returns "none", "metadata" or "auto"
            getPreload: function() {
                return this._mediaElement.preload;
            },
            setPreload: function(preload) {
                this._mediaElement.preload = preload;
            },
            // readonly attribute TimeRanges buffered;
            getBuffered: function() {
                return this._mediaElement.buffered;
            },
            // void load();
            load: function() {
                return this._mediaElement.load();
            },
            // DOMString canPlayType(in DOMString type);
            canPlayType: function(type) {
                return this._mediaElement.canPlayType(type);
            },
            /*
             const unsigned short HAVE_NOTHING = 0;
             const unsigned short HAVE_METADATA = 1;
             const unsigned short HAVE_CURRENT_DATA = 2;
             const unsigned short HAVE_FUTURE_DATA = 3;
             const unsigned short HAVE_ENOUGH_DATA = 4;
             readonly attribute unsigned short readyState;
             */
            getReadyState: function() {
                return this._mediaElement.readyState;
            },
            // readonly attribute boolean seeking;
            getSeeking: function() {
                return this._mediaElement.seeking;
            },
            // attribute double currentTime;
            setCurrentTime: function(currentTime) {
                this._mediaElement.currentTime = currentTime;
            },
            getCurrentTime: function() {
                return this._mediaElement.currentTime;
            },
            // readonly attribute double initialTime;
            getInitialTime: function() {
                return this._mediaElement.initialTime;
            },
            // readonly attribute double duration;
            getDuration: function() {
//                if( isFinite( this._mediaElement.duration ) ){
//                    return this._mediaElement.duration;
//                }else{
                {
                    var seekable = this._mediaElement.seekable;
                    var nrRanges = seekable.length;

                    var start,end;
                    try{
                        start = seekable.start( 0 );
                    }
                    catch( x ){
                        console.log( x );
                    }

                    try{
                        end = seekable.end( 0 );
                    }
                    catch( x ){
                        console.log( x );
                    }

                    return end - start;
                }
            },
            // readonly attribute Date startOffsetTime;
            getStartOffsetTime: function() {
                return this._mediaElement.startOffsetTime;
            },
            // readonly attribute boolean paused;
            getPaused: function() {
                return this._mediaElement.paused;
            },
            // attribute double defaultPlaybackRate;
            getDefaultPlaybackRate: function() {
                return this._mediaElement.defaultPlaybackRate;
            },
            // attribute double playbackRate;
            getPlaybackRate: function() {
                return this._mediaElement.playbackRate;
            },
            setPlaybackRate: function(playbackRate) {
                this._mediaElement.playbackRate = playbackRate;
            },
            // readonly attribute TimeRanges played;
            getPlayed: function() {
                return this._mediaElement.played;
            },
            // readonly attribute TimeRanges seekable;
            getSeekable: function() {
                return this._mediaElement.seekable;
            },
            // readonly attribute boolean ended;
            getEnded: function() {
                return this._mediaElement.ended;
            },
            // attribute boolean autoplay;
            getAutoPlay: function() {
                return this._mediaElement.autoplay;
            },
            setAutoPlay: function(autoplay) {
                this._mediaElement.autoplay = autoplay;
            },
            // attribute boolean loop;
            getLoop: function() {
                return this._mediaElement.loop;
            },
            setLoop: function(loop) {
                this._mediaElement.loop = loop;
            },
            // void play();
            play: function() {
                this._mediaElement.play();
            },
            stop: function() {
                this.pause();
            },
            // void pause();
            pause: function() {
				this._mediaElement.pause();
            },
            // attribute boolean controls;
            setNativeControls: function(controls) {
                this._mediaElement.controls = controls;
            },
            getNativeControls: function() {
                return this._mediaElement.controls;
            },
            destroy: function() {
                this.stop();

                var device = this.getCurrentApplication().getDevice();
                device.removeElement(this._mediaElement);

                // Remove error event listeners from each source element
                var sourceElements = this._mediaElement.getElementsByTagName("source");

                // Loop through the array backwards as we remove array elements inside the loop body
                var sourceElementsLength = sourceElements.length;
                for (var sourceElementIndex = sourceElementsLength - 1; sourceElementIndex >= 0; sourceElementIndex--) {
                    var sourceElement = sourceElements[sourceElementIndex];
                    sourceElement.removeEventListener('error', sourceElement._errorEventListener, true);
                    device.removeElement(sourceElement);

                    delete sourceElements[sourceElementIndex];
                }

                delete sourceElements;

                // Remove event listeners
                for (var i = 0; i < MediaEvent.TYPES.length; i++) {
                    this._mediaElement.removeEventListener(MediaEvent.TYPES[i], this._eventWrapper, true);
                }
                this._mediaElement.removeEventListener("error", this._errorEventWrapper, true);

                // Trick to abort browser loading threads on certain webkit devices
                if(this._requiresWebkitMemoryLeakFix()) {
                    this.webkitMemoryLeakFix();
                }

                delete this._mediaElement;
                this._mediaElement = null;
                currentPlayer = null;
            },
            webkitMemoryLeakFix : function() {
                // http://stackoverflow.com/questions/5170398/ios-safari-memory-leak-when-loading-unloading-html5-video
				this._mediaElement.removeAttribute("src");
                this._mediaElement.load();
            }
        });

        Device.prototype.createPlayer = function(id, mediaType) {
            currentPlayer = new HTML5Player(id, mediaType);
            return currentPlayer;
        };
        Device.prototype.getPlayerEmbedMode = function(mediaType) {
            return Media.EMBED_MODE_EMBEDDED;
        };
        /**
         * Check to see if volume control is supported on this device.
         * @returns Boolean true if volume control is supported.
         */
        Device.prototype.isVolumeControlSupported = function() {
            return true;
        };
        /**
         * Get the current volume.
         * @returns The current volume (0.0 to 1.0)
         */
        Device.prototype.getVolume = function() {
            if (currentPlayer) {
                return currentPlayer._mediaElement.volume;
            }
            return currentVolume;
        };
        /**
         * Set the current volume.
         * @param {Float} volume The new volume level (0.0 to 1.0).
         */
        Device.prototype.setVolume = function(volume) {
            if (volume > 1.0) {
                this.getLogger().warn("HTML5 setVolume - Invalid volume specified (" + volume + " > 1.0). Clipped to 1.0");
                volume = 1.0;
            } else if (volume < 0.0) {
                this.getLogger().warn("HTML5 setVolume - Invalid volume specified (" + volume + " < 0.0). Clipped to 0.0");
                volume = 0;
            }
            currentVolume = volume;
            if (currentPlayer) {
                currentPlayer._mediaElement.volume = volume;
            }
        };
        /**
         * Check to see if the volume is currently muted.
         * @returns Boolean true if the device is currently muted. Otherwise false.
         */
        Device.prototype.getMuted = function() {
            if (currentPlayer) {
                return currentPlayer._mediaElement.muted;
            }
            return isMuted;
        };
        /**
         * Mute or unmute the device.
         * @param {Boolean} muted The new muted state. Boolean true to mute, false to unmute.
         */
        Device.prototype.setMuted = function(muted) {
            isMuted = muted;
            if (currentPlayer) {
                currentPlayer._mediaElement.muted = muted;
            }
        };
        return HTML5Player;
    }
);
<commit_msg>removing some unwanted html5.js changes<commit_after>/**
 * @fileOverview Requirejs module containing HTML5 video and audio media wrapper
 *
 * @preserve Copyright (c) 2013 British Broadcasting Corporation
 * (http://www.bbc.co.uk) and TAL Contributors (1)
 *
 * (1) TAL Contributors are listed in the AUTHORS file and at
 *     https://github.com/fmtvp/TAL/AUTHORS - please extend this file,
 *     not this notice.
 *
 * @license Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 * All rights reserved
 * Please contact us for an alternative licence
 */

require.def(
    'antie/devices/media/html5',
    [
        'antie/devices/device',
        'antie/widgets/media',
        'antie/events/mediaevent',
        'antie/events/mediaerrorevent',
        'antie/events/mediasourceerrorevent',
        'antie/mediasource'
    ],
    function(Device, Media, MediaEvent, MediaErrorEvent, MediaSourceErrorEvent, MediaSource) {
        var currentPlayer = null;
        var isMuted = null;
        var currentVolume = -1;

        var HTML5Player = Media.extend({
            init: function(id, mediaType) {
                this._super(id);

                if (mediaType == "audio") {
                    this._mediaType = "audio";
                } else if (mediaType == "video") {
                    this._mediaType = "video";
                } else {
                    throw new Error('Unrecognised media type: ' + mediaType);
                }

                // Create the DOM element now so the wrapped functions can modify attributes
                // before it is placed in the Document during rendering.
                var device = this.getCurrentApplication().getDevice();
                this._mediaElement = device._createElement(this._mediaType, this.id, this.getClasses());

                if (currentVolume != -1) {
                    this._mediaElement.volume = currentVolume;
                } else {
                    currentVolume = this._mediaElement.volume;
                }
                if (isMuted !== null) {
                    this._mediaElement.muted = isMuted;
                } else {
                    isMuted = this._mediaElement.muted;
                }

                this._eventWrapper = null;
                this._errorEventWrapper = null;
            },
            render: function(device) {
                if (this.outputElement !== this._mediaElement) {
                    this.outputElement = this._mediaElement;

                    // Convert all media events into our internal representation and bubble them through
                    // the UI widgets
                    var self = this;
                    this._eventWrapper = function(evt) {
                        self.bubbleEvent(new MediaEvent(evt.type, self));
                    };
                    this._errorEventWrapper = function(evt) {
                        var errCode = self._mediaElement.error ? self._mediaElement.error.code : Media.MEDIA_ERR_UNKNOWN;
                        self.bubbleEvent(new MediaErrorEvent(self, errCode));
                    };
                    for (var i = 0; i < MediaEvent.TYPES.length; i++) {
                        this._mediaElement.addEventListener(MediaEvent.TYPES[i], this._eventWrapper, true);
                    }
                    this._mediaElement.addEventListener("error", this._errorEventWrapper, true);
                }

                return this._mediaElement;
            },
            // (not part of HTML5 media)
            setWindow: function(left, top, width, height) {
                if (this._mediaType == "audio") {
                    throw new Error('Unable to set window size for HTML5 audio.');
                }
                var device = this.getCurrentApplication().getDevice();
                device.setElementSize(this._mediaElement, {width:width, height:height});
                device.setElementPosition(this._mediaElement, {left:left, top:top});
            },
            // readonly attribute MediaError error;
            getError: function() {
                return this._mediaElement.error;
            },
            _supportsTypeAttribute: function() {
                return true;
            },
            _requiresWebkitMemoryLeakFix: function() {
                return false;
            },
            // Similar to src attribute or 'source' child elements:
            // attribute DOMString src;
            setSources: function(sources, tags) {
                var self = this;
                var device = this.getCurrentApplication().getDevice();
                var oldSources = this._mediaElement.getElementsByTagName('source');
                var supportsTypeAttribute = this._supportsTypeAttribute();

                while (oldSources.length) {
                    device.removeElement(oldSources[0]);
                }
                for (var i = 0; i < sources.length; i++) {
                    var source = document.createElement('source');
                    if (supportsTypeAttribute) {
                        source.type = sources[i].getContentType();
                    }
                    source.src = sources[i].getURL(tags);

                    device.appendChildElement(this._mediaElement, source);

                    (function(source) {
                        source._errorEventListener = function(evt) {
                            var errCode = self._mediaElement.error ? self._mediaElement.error.code : Media.MEDIA_ERR_UNKNOWN;
                            self.bubbleEvent(new MediaSourceErrorEvent(
                                self,
                                errCode,
                                source.src,
                                self._mediaElement.networkState === HTMLMediaElement.NETWORK_NO_SOURCE
                            ));
                            evt.stopPropagation();
                        };
                        source.addEventListener("error", source._errorEventListener, true);
                    })(source);
                }
            },
            getSources: function() {
                var sources = [];
                if (this._mediaElement.src) {
                    sources.push(new MediaSource(this._mediaElement.src, this._mediaElement.type));
                } else {
                    var sourceElements = this._mediaElement.getElementsByTagName('source');
                    for (var i = 0; i < sourceElements.length; i++) {
                        sources.push(new MediaSource(sourceElements[i].src, sourceElements[i].type));
                    }
                }
                return sources;
            },
            // readonly attribute DOMString currentSrc;
            getCurrentSource: function() {
                // Some browsers URI encode apostrophes, others don't. Make sure they're all URI encoded.
                return this._mediaElement.currentSrc.replace(/'/g, "%27");
            },
            /*
             const unsigned short NETWORK_EMPTY = 0;
             const unsigned short NETWORK_IDLE = 1;
             const unsigned short NETWORK_LOADING = 2;
             const unsigned short NETWORK_NO_SOURCE = 3;
             readonly attribute unsigned short networkState;
             */
            getNetworkState: function() {
                return this._mediaElement.networkState;
            },
            // attribute DOMString preload;
            // @returns "none", "metadata" or "auto"
            getPreload: function() {
                return this._mediaElement.preload;
            },
            setPreload: function(preload) {
                this._mediaElement.preload = preload;
            },
            // readonly attribute TimeRanges buffered;
            getBuffered: function() {
                return this._mediaElement.buffered;
            },
            // void load();
            load: function() {
                return this._mediaElement.load();
            },
            // DOMString canPlayType(in DOMString type);
            canPlayType: function(type) {
                return this._mediaElement.canPlayType(type);
            },
            /*
             const unsigned short HAVE_NOTHING = 0;
             const unsigned short HAVE_METADATA = 1;
             const unsigned short HAVE_CURRENT_DATA = 2;
             const unsigned short HAVE_FUTURE_DATA = 3;
             const unsigned short HAVE_ENOUGH_DATA = 4;
             readonly attribute unsigned short readyState;
             */
            getReadyState: function() {
                return this._mediaElement.readyState;
            },
            // readonly attribute boolean seeking;
            getSeeking: function() {
                return this._mediaElement.seeking;
            },
            // attribute double currentTime;
            setCurrentTime: function(currentTime) {
                this._mediaElement.currentTime = currentTime;
            },
            getCurrentTime: function() {
                return this._mediaElement.currentTime;
            },
            // readonly attribute double initialTime;
            getInitialTime: function() {
                return this._mediaElement.initialTime;
            },
            // readonly attribute double duration;
            getDuration: function() {
                return this._mediaElement.duration;
            },
            // readonly attribute Date startOffsetTime;
            getStartOffsetTime: function() {
                return this._mediaElement.startOffsetTime;
            },
            // readonly attribute boolean paused;
            getPaused: function() {
                return this._mediaElement.paused;
            },
            // attribute double defaultPlaybackRate;
            getDefaultPlaybackRate: function() {
                return this._mediaElement.defaultPlaybackRate;
            },
            // attribute double playbackRate;
            getPlaybackRate: function() {
                return this._mediaElement.playbackRate;
            },
            setPlaybackRate: function(playbackRate) {
                this._mediaElement.playbackRate = playbackRate;
            },
            // readonly attribute TimeRanges played;
            getPlayed: function() {
                return this._mediaElement.played;
            },
            // readonly attribute TimeRanges seekable;
            getSeekable: function() {
                return this._mediaElement.seekable;
            },
            // readonly attribute boolean ended;
            getEnded: function() {
                return this._mediaElement.ended;
            },
            // attribute boolean autoplay;
            getAutoPlay: function() {
                return this._mediaElement.autoplay;
            },
            setAutoPlay: function(autoplay) {
                this._mediaElement.autoplay = autoplay;
            },
            // attribute boolean loop;
            getLoop: function() {
                return this._mediaElement.loop;
            },
            setLoop: function(loop) {
                this._mediaElement.loop = loop;
            },
            // void play();
            play: function() {
                this._mediaElement.play();
            },
            stop: function() {
                this.pause();
            },
            // void pause();
            pause: function() {
				this._mediaElement.pause();
            },
            // attribute boolean controls;
            setNativeControls: function(controls) {
                this._mediaElement.controls = controls;
            },
            getNativeControls: function() {
                return this._mediaElement.controls;
            },
            destroy: function() {
                this.stop();

                var device = this.getCurrentApplication().getDevice();
                device.removeElement(this._mediaElement);

                // Remove error event listeners from each source element
                var sourceElements = this._mediaElement.getElementsByTagName("source");

                // Loop through the array backwards as we remove array elements inside the loop body
                var sourceElementsLength = sourceElements.length;
                for (var sourceElementIndex = sourceElementsLength - 1; sourceElementIndex >= 0; sourceElementIndex--) {
                    var sourceElement = sourceElements[sourceElementIndex];
                    sourceElement.removeEventListener('error', sourceElement._errorEventListener, true);
                    device.removeElement(sourceElement);

                    delete sourceElements[sourceElementIndex];
                }

                delete sourceElements;

                // Remove event listeners
                for (var i = 0; i < MediaEvent.TYPES.length; i++) {
                    this._mediaElement.removeEventListener(MediaEvent.TYPES[i], this._eventWrapper, true);
                }
                this._mediaElement.removeEventListener("error", this._errorEventWrapper, true);

                // Trick to abort browser loading threads on certain webkit devices
                if(this._requiresWebkitMemoryLeakFix()) {
                    this.webkitMemoryLeakFix();
                }

                delete this._mediaElement;
                this._mediaElement = null;
                currentPlayer = null;
            },
            webkitMemoryLeakFix : function() {
                // http://stackoverflow.com/questions/5170398/ios-safari-memory-leak-when-loading-unloading-html5-video
				this._mediaElement.removeAttribute("src");
                this._mediaElement.load();
            }
        });

        Device.prototype.createPlayer = function(id, mediaType) {
            currentPlayer = new HTML5Player(id, mediaType);
            return currentPlayer;
        };
        Device.prototype.getPlayerEmbedMode = function(mediaType) {
            return Media.EMBED_MODE_EMBEDDED;
        };
        /**
         * Check to see if volume control is supported on this device.
         * @returns Boolean true if volume control is supported.
         */
        Device.prototype.isVolumeControlSupported = function() {
            return true;
        };
        /**
         * Get the current volume.
         * @returns The current volume (0.0 to 1.0)
         */
        Device.prototype.getVolume = function() {
            if (currentPlayer) {
                return currentPlayer._mediaElement.volume;
            }
            return currentVolume;
        };
        /**
         * Set the current volume.
         * @param {Float} volume The new volume level (0.0 to 1.0).
         */
        Device.prototype.setVolume = function(volume) {
            if (volume > 1.0) {
                this.getLogger().warn("HTML5 setVolume - Invalid volume specified (" + volume + " > 1.0). Clipped to 1.0");
                volume = 1.0;
            } else if (volume < 0.0) {
                this.getLogger().warn("HTML5 setVolume - Invalid volume specified (" + volume + " < 0.0). Clipped to 0.0");
                volume = 0;
            }
            currentVolume = volume;
            if (currentPlayer) {
                currentPlayer._mediaElement.volume = volume;
            }
        };
        /**
         * Check to see if the volume is currently muted.
         * @returns Boolean true if the device is currently muted. Otherwise false.
         */
        Device.prototype.getMuted = function() {
            if (currentPlayer) {
                return currentPlayer._mediaElement.muted;
            }
            return isMuted;
        };
        /**
         * Mute or unmute the device.
         * @param {Boolean} muted The new muted state. Boolean true to mute, false to unmute.
         */
        Device.prototype.setMuted = function(muted) {
            isMuted = muted;
            if (currentPlayer) {
                currentPlayer._mediaElement.muted = muted;
            }
        };
        return HTML5Player;
    }
);
<|endoftext|>


<commit_before>'use strict';

const { execSync } = require( 'child_process' );

const halfMapExtent = 6378137 * Math.PI; // from EPSG:3875 definition

function runCmd( cmd ) {

	console.log( cmd );
	execSync( cmd );

}

/*
var mapSet = 'Austria';
var sourceRaster = 'dhm_lamb_10m';

var tileSet = {
	title: 'Loser',
	dtmMaxZoom: 17,
	maxZoom: 18,
	minZoom: 13,
	divisions: 128,
	directory: '',
	subdirectory: 'Loser',
	dtmScale: 64,
	minX: 4409,
	maxX: 4410,
	minY: 2857,
	maxY: 2859
};
*/

var mapSet = 'Matienzo';
var sourceRaster = 'SOURCE';

var tileSet = {
	title: 'Matienzo',
	dtmMaxZoom: 16,
	maxZoom: 18,
	minZoom: 12,
	divisions: 128,
	directory: '',
	subdirectory: 'Matienzo',
	dtmScale: 64,
	minX: 2005,
	maxX: 2008,
	minY: 1498,
	maxY: 1500
};

var n, s, e, w, zoom;

var maxTileWidth = halfMapExtent / Math.pow( 2, tileSet.minZoom - 1 );

for ( zoom = tileSet.minZoom; zoom <= tileSet.dtmMaxZoom; zoom++ ) {

	var tileWidth = halfMapExtent / Math.pow( 2, zoom - 1 );
	var resolution = tileWidth / tileSet.divisions; // note: tile area extended by resolution/2 all round giving 129 sample row & columns
	var offset = resolution / 2;

	n =   halfMapExtent - tileSet.minY * maxTileWidth + offset; //
	s =   halfMapExtent - ( tileSet.maxY + 1) * maxTileWidth - offset;

	e = - halfMapExtent + ( tileSet.maxX + 1 ) * maxTileWidth + offset;
	w = - halfMapExtent + tileSet.minX * maxTileWidth - offset;

	runCmd( 'g.region n=' + n + ' s=' + s + ' w=' +  w + ' e=' + e + ' nsres=' + resolution + ' ewres=' + resolution );

	runCmd( 'r.resamp.interp --o input=' +  sourceRaster + '@' + mapSet + ' output=DTM' + zoom + 'M@' + mapSet );

	// scale by 64 to increase resolution as a 16b integer (smaller files and type usable by OpenGL)
	runCmd( 'r.mapcalc --o "DTM' + zoom + 'X=round(DTM' + zoom + 'M@' + mapSet + ' * 64)"' );

}

// EOF<commit_msg>WIP improve tile generation<commit_after>'use strict';

var fs = require( 'fs' );
const { execSync } = require( 'child_process' );

const halfMapExtent = 6378137 * Math.PI; // from EPSG:3875 definition

function runCmd( cmd ) {

	console.log( cmd );
	execSync( cmd );

}

function createRasters( tileSet ) {

	var mapSet = 'TEST';
	var sourceRaster = 'dummy';

	var n, s, e, w, zoom;

	var maxTileWidth = halfMapExtent / Math.pow( 2, tileSet.minZoom - 1 );

	for ( zoom = tileSet.minZoom; zoom <= tileSet.dtmMaxZoom; zoom++ ) {

		var tileWidth = halfMapExtent / Math.pow( 2, zoom - 1 );
		var resolution = tileWidth / tileSet.divisions; // note: tile area extended by resolution/2 all round giving 129 sample row & columns
		var offset = resolution / 2;

		n =   halfMapExtent - tileSet.minY * maxTileWidth + offset; //
		s =   halfMapExtent - ( tileSet.maxY + 1) * maxTileWidth - offset;

		e = - halfMapExtent + ( tileSet.maxX + 1 ) * maxTileWidth + offset;
		w = - halfMapExtent + tileSet.minX * maxTileWidth - offset;

		var tempFile = 'DTM' + zoom + 'M@' + mapSet;

		// define region

		runCmd( 'g.region n=' + n + ' s=' + s + ' w=' +  w + ' e=' + e + ' nsres=' + resolution + ' ewres=' + resolution );

		// produce downres of source

		runCmd( 'r.resamp.stats --verbose --o input=' + sourceRaster + '@' + mapSet + ' output=' + tempFile );

		// scale by 64 to increase resolution as a 16b integer (smaller files and type usable by OpenGL)
		runCmd( 'r.mapcalc --o "DTM' + zoom + 'X=round(' + tempFile + ' * 64)"' );

		runCmd( 'g.remove -f type=raster name=' + tempFile );

	}

}

const setName = 'Pokljuka';

var tileSetsText = fs.readFileSync( 'tileSets.json' );
var tileSets = JSON.parse( tileSetsText );

var tileSet = tileSets.find(  function ( e ) { return e.title === setName ;} );

if ( tileSet !== undefined ) {

	console.log( 'Creating rasters' );

	createRasters( tileSet );

}

// EOF<|endoftext|>


<commit_before>/**
 * _scripts/pages/main.js
 * Loads all of the site wide snippets
 */

import analytics from '~/lib/analytics'
import jQuery from '~/lib/jquery'

import '~/external-links'
import '~/popover'
import '~/smooth-scrolling'
import '~/twitter-links'

// Send some analytic information on every page load
analytics.then((ga) => {
    ga('send', 'pageview')
    ga('send', 'event', 'Language', 'Pageload', document.documentElement.lang)
})

jQuery.then(($) => {
    $('.toast__close').on('click', function (e) {
        $(this).closest('.toast').hide()
    })
})
<commit_msg>animate toast exit (#1578)<commit_after>/**
 * _scripts/pages/main.js
 * Loads all of the site wide snippets
 */

import analytics from '~/lib/analytics'
import jQuery from '~/lib/jquery'

import '~/external-links'
import '~/popover'
import '~/smooth-scrolling'
import '~/twitter-links'

// Send some analytic information on every page load
analytics.then((ga) => {
    ga('send', 'pageview')
    ga('send', 'event', 'Language', 'Pageload', document.documentElement.lang)
})

jQuery.then(($) => {
    $('.toast__close').on('click', function (e) {
        const $overlay = $(this).closest('.overlay')

        $overlay.animate({
            top: '-10px',
            opacity: 0
        }, 120, 'linear', $overlay.hide)
    })
})
<|endoftext|>


<commit_before>import React from 'react';
import TravelObject from './TravelObject'
import AddItemButton from './AddItemButton'
import { Grid } from '@material-ui/core'
import '../styles/Trip.css'
import Map from "./Map"

// Data just for testing purposes
const testData = [
    {
        id: 0,
        finalized: true,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 1,
        finalized: false,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 2,
        finalized: false,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 3,
        finalized: false,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 125,
        finalized: true,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 87,
        finalized: true,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 231,
        finalized: true,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 5425,
        finalized: true,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 100,
        finalized: true,
        type: "hotel",
        title: "Hotel ZED",
        location: "London",
        startDate: new Date(),
        endDate: new Date(),
        description: 'description',
    }
]

export default class Trip extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            items: []
        }

        this.handleRemoveItem = this.handleRemoveItem.bind(this);
        this.handleEditItem = this.handleEditItem.bind(this);
        this.handleAddItem = this.handleAddItem.bind(this);
    }

    fetchData() {
        // TODO: fetch from datastore
        return testData;
    }

    componentDidMount() {
        let data = this.fetchData();
        this.setState({
            items: data
        })
    }

    handleRemoveItem(id) {
        this.setState({
            items: this.state.items.filter((item) => item.id !== id)
        });
    }

    handleEditItem(data) {
        this.setState({
            items: this.state.items.map((item) => {
                if (item.id !== data.id) {
                    return item;
                } else {
                    return data
                }
            })
        })
    }

    handleAddItem(data) {
        if (data === undefined) {
            console.log("please enter information")
        } else {
            // Add to database here
            // current code for testing data format etc.
            // TODO: Add item to datastore
            switch (data.type) {
                case "event":
                    console.log("adding event");
                    break;
                case "hotel":
                    this.setState({
                        items: this.state.items.concat([{
                            id: this.state.items.length,
                            finalized: data.finalized,
                            type: data.type,
                            title: data.title,
                            location: data.location,
                            startDate: data.startDate,
                            endDate: data.endDate,
                            description: data.description,

                        }])
                    })
                    break;
                case "flight":
                    this.setState({
                        items: this.state.items.concat([{
                            id: this.state.items.length,
                            finalized: data.finalized,
                            type: data.type,
                            departureAirport: data.departureAirport,
                            arrivalAirport: data.arrivalAirport,
                            departureDate: data.departureDate,
                            arrivalDate: data.arrivalDate,
                            description: data.description
                        }])
                    })
                    break;
                default: throw "Invalid input";
            }
        }
    }

    render() {
        if (this.props.items === undefined) {
            // redirect to Home page
        }
        return (

                <Grid id="map-component"><Map zoom={13} center={{ lat: 51.5, lng: 0.087 }} /></Grid>
                <Grid container className="foreground" direction="row" justify="space-between">
                    <Grid item id="finalized-component">
                        <Finalized
                            list={this.state.items.filter((item) => item.finalized)}
                            onRemoveItem={this.handleRemoveItem}
                            onEditItem={this.handleEditItem}
                            onAddItem={this.handleAddItem}
                        />
                    </Grid>
                    <Grid item id="unfinalized-component">
                        <Unfinalized
                            list={this.state.items.filter((item) => !item.finalized)}
                            onRemoveItem={this.handleRemoveItem}
                            onEditItem={this.handleEditItem}
                            onAddItem={this.handleAddItem}
                        />
                    </Grid>
                </Grid>
                <Grid id="add-button-component">
                    <AddItemButton onAddItem={this.handleAddItem} />
                </Grid>

        );
    }
}

/*
 Classes for testing UI purposes
*/
function Finalized(props) {
    return (
        <Grid>
            {
                props.list.map((item) => {
                    return <TravelObject
                        key={item.id}
                        data={item}
                        onRemoveItem={props.onRemoveItem}
                        onEditItem={props.onEditItem}
                        onAddItem={props.onAddItem}
                    />
                })
            }
        </Grid>
    )
}

function Unfinalized(props) {
    return (
        <Grid>
            {
                props.list.map((item) => {
                    return <TravelObject
                        key={item.id}
                        data={item}
                        onRemoveItem={props.onRemoveItem}
                        onEditItem={props.onEditItem}
                        onAddItem={props.handleAddItem}
                    />
                })
            }
        </Grid>
    )
}<commit_msg>Add todo comment<commit_after>import React from 'react';
import TravelObject from './TravelObject'
import AddItemButton from './AddItemButton'
import { Grid } from '@material-ui/core'
import '../styles/Trip.css'
import Map from "./Map"

// Data just for testing purposes
const testData = [
    {
        id: 0,
        finalized: true,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 1,
        finalized: false,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 2,
        finalized: false,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 3,
        finalized: false,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 125,
        finalized: true,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 87,
        finalized: true,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 231,
        finalized: true,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 5425,
        finalized: true,
        type: "flight",
        departureAirport: "BOS",
        arrivalAirport: "SFO",
        departureDate: new Date(),
        arrivalDate: new Date(),
        description: "Additional notes"
    },
    {
        id: 100,
        finalized: true,
        type: "hotel",
        title: "Hotel ZED",
        location: "London",
        startDate: new Date(),
        endDate: new Date(),
        description: 'description',
    }
]

export default class Trip extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            items: []
        }

        this.handleRemoveItem = this.handleRemoveItem.bind(this);
        this.handleEditItem = this.handleEditItem.bind(this);
        this.handleAddItem = this.handleAddItem.bind(this);
    }

    fetchData() {
        // TODO: fetch from datastore
        return testData;
    }

    componentDidMount() {
        let data = this.fetchData();
        this.setState({
            items: data
        })
    }

    handleRemoveItem(id) {
        this.setState({
            items: this.state.items.filter((item) => item.id !== id)
        });
    }

    handleEditItem(data) {
        this.setState({
            items: this.state.items.map((item) => {
                if (item.id !== data.id) {
                    return item;
                } else {
                    return data
                }
            })
        })
    }

    handleAddItem(data) {
        if (data === undefined) {
            console.log("please enter information")
        } else {
            // Add to database here
            // current code for testing data format etc.
            // TODO: Add item to datastore
            switch (data.type) {
                case "event":
                    console.log("adding event");
                    break;
                case "hotel":
                    this.setState({
                        items: this.state.items.concat([{
                            id: this.state.items.length,
                            finalized: data.finalized,
                            type: data.type,
                            title: data.title,
                            location: data.location,
                            startDate: data.startDate,
                            endDate: data.endDate,
                            description: data.description,

                        }])
                    })
                    break;
                case "flight":
                    this.setState({
                        items: this.state.items.concat([{
                            id: this.state.items.length,
                            finalized: data.finalized,
                            type: data.type,
                            departureAirport: data.departureAirport,
                            arrivalAirport: data.arrivalAirport,
                            departureDate: data.departureDate,
                            arrivalDate: data.arrivalDate,
                            description: data.description
                        }])
                    })
                    break;
                default: throw "Invalid input";
            }
        }
    }

    render() {
        if (this.props.items === undefined) {
            // TODO: redirect to Home page
        }
        return (

                <Grid id="map-component"><Map zoom={13} center={{ lat: 51.5, lng: 0.087 }} /></Grid>
                <Grid container className="foreground" direction="row" justify="space-between">
                    <Grid item id="finalized-component">
                        <Finalized
                            list={this.state.items.filter((item) => item.finalized)}
                            onRemoveItem={this.handleRemoveItem}
                            onEditItem={this.handleEditItem}
                            onAddItem={this.handleAddItem}
                        />
                    </Grid>
                    <Grid item id="unfinalized-component">
                        <Unfinalized
                            list={this.state.items.filter((item) => !item.finalized)}
                            onRemoveItem={this.handleRemoveItem}
                            onEditItem={this.handleEditItem}
                            onAddItem={this.handleAddItem}
                        />
                    </Grid>
                </Grid>
                <Grid id="add-button-component">
                    <AddItemButton onAddItem={this.handleAddItem} />
                </Grid>

        );
    }
}

/*
 Classes for testing UI purposes
*/
function Finalized(props) {
    return (
        <Grid>
            {
                props.list.map((item) => {
                    return <TravelObject
                        key={item.id}
                        data={item}
                        onRemoveItem={props.onRemoveItem}
                        onEditItem={props.onEditItem}
                        onAddItem={props.onAddItem}
                    />
                })
            }
        </Grid>
    )
}

function Unfinalized(props) {
    return (
        <Grid>
            {
                props.list.map((item) => {
                    return <TravelObject
                        key={item.id}
                        data={item}
                        onRemoveItem={props.onRemoveItem}
                        onEditItem={props.onEditItem}
                        onAddItem={props.handleAddItem}
                    />
                })
            }
        </Grid>
    )
}
<|endoftext|>