<commit_before>'use strict';
import React from 'react';
import { external_url_map } from './globals';

/**
 * Method to display either mode of inheritance with adjective,
 * or just mode of inheritance if no adjective
 * @param {object} object - A GDM or Interpretation object
 */
export function renderSelectedModeInheritance(object) {
    let moi = '', moiAdjective = '';

    if (object && object.modeInheritance) {
        moi = object.modeInheritance;
        if (object.modeInheritanceAdjective) {
            moiAdjective = object.modeInheritanceAdjective;
        }
    }
    return (
        {moi && moi.length ? renderModeInheritanceLink(moi, moiAdjective) : 'None'}
    );
}

/**
 * Method to construct mode of inheritance linkout
 */
function renderModeInheritanceLink(modeInheritance, modeInheritanceAdjective) {
    if (modeInheritance) {
        let start = modeInheritance.indexOf('(');
        let end = modeInheritance.indexOf(')');
        let hpoNumber;
        let adjective = modeInheritanceAdjective && modeInheritanceAdjective.length ? ' (' + modeInheritanceAdjective.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1] + ')' : '';
        if (start && end) {
            hpoNumber = modeInheritance.substring(start+1, end);
        }
        if (hpoNumber && hpoNumber.indexOf('HP:') > -1) {
            let hpoLink = external_url_map['HPO'] + hpoNumber;
            return (
                {modeInheritance.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1]}{adjective}
            );
        } else {
            return (
                {modeInheritance + adjective}
            );
        }
    }
}<commit_msg>fix global import path<commit_after>'use strict';
import React from 'react';
import { external_url_map } from "../components/globals";

/**
 * Method to display either mode of inheritance with adjective,
 * or just mode of inheritance if no adjective
 * @param {object} object - A GDM or Interpretation object
 */
export function renderSelectedModeInheritance(object) {
    let moi = '', moiAdjective = '';

    if (object && object.modeInheritance) {
        moi = object.modeInheritance;
        if (object.modeInheritanceAdjective) {
            moiAdjective = object.modeInheritanceAdjective;
        }
    }
    return (
        {moi && moi.length ? renderModeInheritanceLink(moi, moiAdjective) : 'None'}
    );
}

/**
 * Method to construct mode of inheritance linkout
 */
function renderModeInheritanceLink(modeInheritance, modeInheritanceAdjective) {
    if (modeInheritance) {
        let start = modeInheritance.indexOf('(');
        let end = modeInheritance.indexOf(')');
        let hpoNumber;
        let adjective = modeInheritanceAdjective && modeInheritanceAdjective.length ? ' (' + modeInheritanceAdjective.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1] + ')' : '';
        if (start && end) {
            hpoNumber = modeInheritance.substring(start+1, end);
        }
        if (hpoNumber && hpoNumber.indexOf('HP:') > -1) {
            let hpoLink = external_url_map['HPO'] + hpoNumber;
            return (
                {modeInheritance.match(/^(.*?)(?: \(HP:[0-9]*?\)){0,1}$/)[1]}{adjective}
            );
        } else {
            return (
                {modeInheritance + adjective}
            );
        }
    }
}<|endoftext|>


<commit_before>// Object.assign polyfill todo need remove.
if (!Object.assign) {
    Object.defineProperty(Object, 'assign', {
        enumerable: false,
        configurable: true,
        writable: true,
        value: function(target, firstSource) {
            'use strict';
            if (target === undefined || target === null) {
                throw new TypeError('Cannot convert first argument to object');
            }

            var to = Object(target);
            for (var i = 1; i < arguments.length; i++) {
                var nextSource = arguments[i];
                if (nextSource === undefined || nextSource === null) {
                    continue;
                }

                var keysArray = Object.keys(Object(nextSource));
                for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
                    var nextKey = keysArray[nextIndex];
                    var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
                    if (desc !== undefined && desc.enumerable) {
                        to[nextKey] = nextSource[nextKey];
                    }
                }
            }
            return to;
        }
    });
}
(function (window) {
    var utils = {
        base64_encode: function(data) {
            var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, enc = '';

            do { // pack three octets into four hexets
                o1 = data.charCodeAt(i++);
                o2 = data.charCodeAt(i++);
                o3 = data.charCodeAt(i++);

                bits = o1 << 16 | o2 << 8 | o3;

                h1 = bits >> 18 & 0x3f;
                h2 = bits >> 12 & 0x3f;
                h3 = bits >> 6 & 0x3f;
                h4 = bits & 0x3f;

                // use hexets to index into b64, and append result to encoded string
                enc += b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
            } while (i < data.length);

            switch (data.length % 3) {
                case 1:
                    enc = enc.slice(0, -2) + '==';
                    break;
                case 2:
                    enc = enc.slice(0, -1) + '=';
                    break;
            }

            return enc;
        },
        addEvent: function(event, fn, context) {
            if(context===undefined) {
                context = document;
            }
            if(context.addEventListener) {
                context.addEventListener(event, fn, false)
            } else {
                context.attachEvent("on"+event, fn);
            }
        },
        removeEvent: function(event, fn, context) {
            if(context===undefined) {
                context = document;
            }
            if(context.removeEventListener) {
                context.removeEventListener(event, fn, false)
            } else {
                context.detachEvent("on"+event, fn);
            }
        },
        getCookie: function(name) {
            var matches = document.cookie.match(new RegExp(
                "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
            ));
            return matches ? decodeURIComponent(matches[1]) : undefined;
        },
        setCookie: function(name, value, options) {
            options = options || {};

            var expires = options.expires;

            if (typeof expires == "number" && expires) {
                var d = new Date();
                d.setTime(d.getTime() + expires * 1000);
                expires = options.expires = d;
            }
            if (expires && expires.toUTCString) {
                options.expires = expires.toUTCString();
            }

            value = encodeURIComponent(value);

            var updatedCookie = name + "=" + value;

            for (var propName in options) {
                updatedCookie += "; " + propName;
                var propValue = options[propName];
                if (propValue !== true) {
                    updatedCookie += "=" + propValue;
                }
            }

            console.log(updatedCookie);

            document.cookie = updatedCookie;
        },
        makeId: function(n) {
            var id = "";
            var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            for(var i = 0; i < n; i++) {
                id += letters.charAt(Math.floor(Math.random() * letters.length))
            }
            return id;
        }
    };

    var storage = function(options) {
        this.config = Object.assign(this.config, options);

        if(this.config.useLocalStorage && this._hasLocalStorage() && this._isEmptyLocalStorage()) {
            this.data = this._data;
        }
    };

    storage.prototype = {
        config: {
            storkey: 'marker123',
            useLocalStorage: true
        },
        _data: {
            scrollY: [],
            scrollMove: 0,
            mouseXY: [],
            mouseMove: 0,
            url: location.href
        },
        get data() {
            if(this.config.useLocalStorage && this._hasLocalStorage()) {
                this._data = JSON.parse(window.localStorage.getItem(this.config.storkey));
            }
            return this._data;
        },
        set data(value) {
            this._data = value;
            if(this.config.useLocalStorage && this._hasLocalStorage()) {
                window.localStorage.setItem(this.config.storkey, JSON.stringify(this._data));
            }
        },
        constructor: storage,
        _hasLocalStorage: function() {
            return typeof window.localStorage === 'object';
        },
        _isEmptyLocalStorage: function() {
            return window.localStorage.getItem(this.config.storkey)===null;
        },
        merge: function(obj) {
            this.data = Object.assign(this.data, obj);
        },
        pushMouseData: function(x, y) {
            var data = this.data;
            if(data.mouseXY.length>0) {
                var last = data.mouseXY[data.mouseXY.length-1];
                data.mouseMove += Math.round(Math.sqrt(Math.pow(last.x - x, 2)+Math.pow(last.y - y, 2)));
            }
            data.mouseXY.push({x: x, y: y});
            this.data = data;
        },
        pushScrollData: function(y) {
            var data = this.data;
            if(data.scrollY.length>0) {
                var last = data.scrollY[data.scrollY.length-1];
                data.scrollMove += Math.max(last, y) - Math.min(last, y);
            }
            data.scrollY.push(y);
            this.data = data;
        },
        fetch: function() {
            return this.data;
        },
        clear: function() {
            var data = this.data;
            data.scrollY = [];
            data.scrollMove = 0;
            data.mouseXY = [];
            data.mouseMove = 0;
            this.data = data;
        },
        size: function() {
            var data = this.data;
            return data.scrollY.length + data.mouseXY.length;
        }
    };

    var sender = function(options) {
        this.config = Object.assign(this.config, options);
    };

    sender.prototype = {
        config: {
            iframe: true,
            url: 'http://localhost/test?param=1', // url for send data
            sendTimeout: 1000 // one sec
        },
        sending: false,
        constructor: sender,
        send: function(data) {
            if(this.sending)
                return false;

            var that = this;

            this.sending = true;
            setTimeout(function(){
                that.sending = false;
            }, this.config.sendTimeout);

            var url = this.config.url +
                '&data=' + utils.base64_encode(JSON.stringify(data));

            var el = document.createElement((this.config.iframe ? 'iframe' : 'img'));
            el.src = url;
            el.style.display = "none";
            document.body.appendChild(el);

            return true;
        }
    };

    window.marker = function (options) {
        var that = this;

        this.config = Object.assign(this.config, options.marker || {});

        this.sender = new sender(options.sender || {});
        this.storage = new storage(options.storage || {});
        this.compress = compressor();
        this._initMarker();
        this._initEvents();

        function compressor() {
            var counter = 0;
            return function (x, y) {
                if (!(counter % that.config.stepSkip)) {
                    that.storage.pushMouseData(x, y);
                }
                counter++;
            }
        }
    };

    window.marker.prototype = {
        config: {
            sizeForSend: 50, // data pack size
            stepSkip: 10, // save step for mouse move (for example every 10th will save)
            name: 'marker123',
            expire: 30 * 60  // end listen time (in seconds)
        },
        constructor: marker,
        _initMarker: function() {
            if(this._isExpire()) {
                utils.setCookie(this.config.name, utils.makeId(32), {expires: this.config.expire});
            }
            this.storage.merge({marker: utils.getCookie(this.config.name)});
        },
        _isExpire: function() {
            return utils.getCookie(this.config.name)===undefined;
        },
        _initEvents: function () {
            var that = this,
                send = that.send.bind(that),
                mouse = that.handleMouseMove.bind(that),
                scroll = that.handleScroll.bind(that),
                out = function(e) {
                    e = e ? e : window.event;
                    var from = e.relatedTarget || e.toElement;
                    if (!from || from.nodeName == "HTML") {
                        that.send();
                    }
                };

            utils.addEvent('bufferOverflow', send);
            utils.addEvent('beforeunload', send, window);
            utils.addEvent('blur', send, window);
            utils.addEvent('mouseout', out);
            utils.addEvent('mousemove', mouse);
            utils.addEvent('scroll', scroll);

            setTimeout(function () {
                utils.removeEvent('bufferOverflow', send);
                utils.removeEvent('beforeunload', send, window);
                utils.removeEvent('blur', send, window);
                utils.removeEvent('mouseout', out);
                utils.removeEvent('mousemove', mouse);
                utils.removeEvent('scroll', scroll);
                that.send();
            }, that.config.expire*1000); // in milliseconds
        },
        send: function () {
            var data = this.storage.fetch();
            if(this.sender.send(data))
                this.storage.clear();
        },
        checkBufferSize: function () {
            var over = this.storage.size() >= this.config.sizeForSend;
            if(over) {
                var e = document.createEvent('Event');
                e.initEvent('bufferOverflow', true, true);
                if(document.fireEvent) {
                    document.fireEvent('onbufferOverflow', e);
                } else {
                    document.dispatchEvent(e);
                }
            }
            return over;
        },
        handleMouseMove: function (e) {
            if(this._isExpire())
                return;

            var x, y;
            if (document.all) {
                x = event.x + document.body.scrollLeft;
                y = event.y + document.body.scrollTop;
            } else {
                x = e.pageX;
                y = e.pageY;
            }
            this.compress(x, y);
            this.checkBufferSize();
        },
        handleScroll: function (e) {
            if(this._isExpire())
                return;

            var y = Math.round(window.pageYOffset || document.documentElement.scrollTop);
            this.storage.pushScrollData(y);
            this.checkBufferSize();
        }
    };
})(window);<commit_msg>remove send timeout<commit_after>// Object.assign polyfill todo need remove.
if (!Object.assign) {
    Object.defineProperty(Object, 'assign', {
        enumerable: false,
        configurable: true,
        writable: true,
        value: function(target, firstSource) {
            'use strict';
            if (target === undefined || target === null) {
                throw new TypeError('Cannot convert first argument to object');
            }

            var to = Object(target);
            for (var i = 1; i < arguments.length; i++) {
                var nextSource = arguments[i];
                if (nextSource === undefined || nextSource === null) {
                    continue;
                }

                var keysArray = Object.keys(Object(nextSource));
                for (var nextIndex = 0, len = keysArray.length; nextIndex < len; nextIndex++) {
                    var nextKey = keysArray[nextIndex];
                    var desc = Object.getOwnPropertyDescriptor(nextSource, nextKey);
                    if (desc !== undefined && desc.enumerable) {
                        to[nextKey] = nextSource[nextKey];
                    }
                }
            }
            return to;
        }
    });
}
(function (window) {
    var utils = {
        base64_encode: function(data) {
            var b64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
            var o1, o2, o3, h1, h2, h3, h4, bits, i = 0, enc = '';

            do { // pack three octets into four hexets
                o1 = data.charCodeAt(i++);
                o2 = data.charCodeAt(i++);
                o3 = data.charCodeAt(i++);

                bits = o1 << 16 | o2 << 8 | o3;

                h1 = bits >> 18 & 0x3f;
                h2 = bits >> 12 & 0x3f;
                h3 = bits >> 6 & 0x3f;
                h4 = bits & 0x3f;

                // use hexets to index into b64, and append result to encoded string
                enc += b64.charAt(h1) + b64.charAt(h2) + b64.charAt(h3) + b64.charAt(h4);
            } while (i < data.length);

            switch (data.length % 3) {
                case 1:
                    enc = enc.slice(0, -2) + '==';
                    break;
                case 2:
                    enc = enc.slice(0, -1) + '=';
                    break;
            }

            return enc;
        },
        addEvent: function(event, fn, context) {
            if(context===undefined) {
                context = document;
            }
            if(context.addEventListener) {
                context.addEventListener(event, fn, false)
            } else {
                context.attachEvent("on"+event, fn);
            }
        },
        removeEvent: function(event, fn, context) {
            if(context===undefined) {
                context = document;
            }
            if(context.removeEventListener) {
                context.removeEventListener(event, fn, false)
            } else {
                context.detachEvent("on"+event, fn);
            }
        },
        getCookie: function(name) {
            var matches = document.cookie.match(new RegExp(
                "(?:^|; )" + name.replace(/([\.$?*|{}\(\)\[\]\\\/\+^])/g, '\\$1') + "=([^;]*)"
            ));
            return matches ? decodeURIComponent(matches[1]) : undefined;
        },
        setCookie: function(name, value, options) {
            options = options || {};

            var expires = options.expires;

            if (typeof expires == "number" && expires) {
                var d = new Date();
                d.setTime(d.getTime() + expires * 1000);
                expires = options.expires = d;
            }
            if (expires && expires.toUTCString) {
                options.expires = expires.toUTCString();
            }

            value = encodeURIComponent(value);

            var updatedCookie = name + "=" + value;

            for (var propName in options) {
                updatedCookie += "; " + propName;
                var propValue = options[propName];
                if (propValue !== true) {
                    updatedCookie += "=" + propValue;
                }
            }

            document.cookie = updatedCookie;
        },
        makeId: function(n) {
            var id = "";
            var letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
            for(var i = 0; i < n; i++) {
                id += letters.charAt(Math.floor(Math.random() * letters.length))
            }
            return id;
        }
    };

    var storage = function(options) {
        this.config = Object.assign(this.config, options);

        if(this.config.useLocalStorage && this._hasLocalStorage() && this._isEmptyLocalStorage()) {
            this.data = this._data;
        }
    };

    storage.prototype = {
        config: {
            storkey: 'marker123',
            useLocalStorage: true
        },
        _data: {
            scrollY: [],
            scrollMove: 0,
            mouseXY: [],
            mouseMove: 0,
            url: location.href
        },
        get data() {
            if(this.config.useLocalStorage && this._hasLocalStorage()) {
                this._data = JSON.parse(window.localStorage.getItem(this.config.storkey));
            }
            return this._data;
        },
        set data(value) {
            this._data = value;
            if(this.config.useLocalStorage && this._hasLocalStorage()) {
                window.localStorage.setItem(this.config.storkey, JSON.stringify(this._data));
            }
        },
        constructor: storage,
        _hasLocalStorage: function() {
            return typeof window.localStorage === 'object';
        },
        _isEmptyLocalStorage: function() {
            return window.localStorage.getItem(this.config.storkey)===null;
        },
        merge: function(obj) {
            this.data = Object.assign(this.data, obj);
        },
        pushMouseData: function(x, y) {
            var data = this.data;
            if(data.mouseXY.length>0) {
                var last = data.mouseXY[data.mouseXY.length-1];
                data.mouseMove += Math.round(Math.sqrt(Math.pow(last.x - x, 2)+Math.pow(last.y - y, 2)));
            }
            data.mouseXY.push({x: x, y: y});
            this.data = data;
        },
        pushScrollData: function(y) {
            var data = this.data;
            if(data.scrollY.length>0) {
                var last = data.scrollY[data.scrollY.length-1];
                data.scrollMove += Math.max(last, y) - Math.min(last, y);
            }
            data.scrollY.push(y);
            this.data = data;
        },
        fetch: function() {
            return this.data;
        },
        clear: function() {
            var data = this.data;
            data.scrollY = [];
            data.scrollMove = 0;
            data.mouseXY = [];
            data.mouseMove = 0;
            this.data = data;
        },
        size: function() {
            var data = this.data;
            return data.scrollY.length + data.mouseXY.length;
        }
    };

    var sender = function(options) {
        this.config = Object.assign(this.config, options);
    };

    sender.prototype = {
        config: {
            url: 'http://localhost/test?param=1' // url for send data
        },
        sending: false,
        constructor: sender,
        send: function(data) {
            var url = this.config.url +
                '&data=' + utils.base64_encode(JSON.stringify(data));

            var el = document.createElement('img');
            el.src = url;
            el.style.display = "none";
            document.body.appendChild(el);

            return true;
        }
    };

    window.marker = function (options) {
        var that = this;

        this.config = Object.assign(this.config, options.marker || {});

        this.sender = new sender(options.sender || {});
        this.storage = new storage(options.storage || {});
        this.compress = compressor();
        this._initMarker();
        this._initEvents();

        function compressor() {
            var counter = 0;
            return function (x, y) {
                if (!(counter % that.config.stepSkip)) {
                    that.storage.pushMouseData(x, y);
                }
                counter++;
            }
        }
    };

    window.marker.prototype = {
        config: {
            sizeForSend: 50, // data pack size
            stepSkip: 10, // save step for mouse move (for example every 10th will save)
            name: 'marker123',
            expire: 30 * 60  // end listen time (in seconds)
        },
        constructor: marker,
        _initMarker: function() {
            if(this._isExpire()) {
                utils.setCookie(this.config.name, utils.makeId(32), {expires: this.config.expire});
            }
            this.storage.merge({marker: utils.getCookie(this.config.name)});
        },
        _isExpire: function() {
            return utils.getCookie(this.config.name)===undefined;
        },
        _initEvents: function () {
            var that = this,
                send = that.send.bind(that),
                mouse = that.handleMouseMove.bind(that),
                scroll = that.handleScroll.bind(that),
                out = function(e) {
                    e = e ? e : window.event;
                    var from = e.relatedTarget || e.toElement;
                    if (!from || from.nodeName == "HTML") {
                        that.send();
                    }
                };

            utils.addEvent('bufferOverflow', send);
            utils.addEvent('beforeunload', send, window);
            utils.addEvent('blur', send, window);
            utils.addEvent('mouseout', out);
            utils.addEvent('mousemove', mouse);
            utils.addEvent('scroll', scroll);

            setTimeout(function () {
                utils.removeEvent('bufferOverflow', send);
                utils.removeEvent('beforeunload', send, window);
                utils.removeEvent('blur', send, window);
                utils.removeEvent('mouseout', out);
                utils.removeEvent('mousemove', mouse);
                utils.removeEvent('scroll', scroll);
                that.send();
            }, that.config.expire*1000); // in milliseconds
        },
        send: function () {
            if(this._isExpire())
                return;

            var data = this.storage.fetch();
            if(this.sender.send(data))
                this.storage.clear();
        },
        checkBufferSize: function () {
            var over = this.storage.size() >= this.config.sizeForSend;
            if(over) {
                var e = document.createEvent('Event');
                e.initEvent('bufferOverflow', true, true);
                if(document.fireEvent) {
                    document.fireEvent('onbufferOverflow', e);
                } else {
                    document.dispatchEvent(e);
                }
            }
            return over;
        },
        handleMouseMove: function (e) {
            if(this._isExpire())
                return;

            var x, y;
            if (document.all) {
                x = event.x + document.body.scrollLeft;
                y = event.y + document.body.scrollTop;
            } else {
                x = e.pageX;
                y = e.pageY;
            }
            this.compress(x, y);
            this.checkBufferSize();
        },
        handleScroll: function (e) {
            if(this._isExpire())
                return;

            var y = Math.round(window.pageYOffset || document.documentElement.scrollTop);
            this.storage.pushScrollData(y);
            this.checkBufferSize();
        }
    };
})(window);<|endoftext|>


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

var server = net.createServer(function(c) { //'connection' listener
  	console.log('server connected');
  	c.on('end', function() {
    		console.log('server disconnected');
  	});
	c.on('data', function(data){
		console.log('received: ' + data);
		var h = "id,nome,valor".split(",");
		var v = new String(data).split(",");
		if(v instanceof Array){
			for(i=0; i<v.length; i++){
				console.log(h[i] + " = " + v[i]);
			}
			console.log("-------------");
		}
		var id = v[0];
		var retVal = "reject";
		if(id%7 == 0){
			retVal = "reject";
		}
		else if(id%3 == 0){
			retVal = "3000";
		}
		else if(id%2 == 0){
			retVal = "2000";
		}
		else{
			retVal = "1000";
		}
		c.write(retVal + "\n");
	});
  	c.write('hello\r\n');
	c.pipe(c);
});

server.listen(6667, function() { //'listening' listener
  	console.log('server bound');
});

<commit_msg>added the correct string format<commit_after>var net = require('net');

var server = net.createServer(function(c) { //'connection' listener
  	console.log('server connected');
  	c.on('end', function() {
    		console.log('server disconnected');
  	});
	c.on('data', function(data){
		console.log('received: ' + data);
		var h = "Number|Gender|GivenName|Surname|StreetAddress|City|State|ZipCode|CountryFull|TelephoneNumber|Birthday|NationalID|Occupation|CCType".split("|");
		var v = new String(data).split("|");
		if(v instanceof Array){
			for(i=0; i<v.length; i++){
				console.log(h[i] + " = " + v[i]);
			}
			console.log("-------------");
		}
		var id = v[0];
		var retVal = "reject";
		if(id%7 == 0){
			retVal = "reject";
		}
		else if(id%3 == 0){
			retVal = "3000";
		}
		else if(id%2 == 0){
			retVal = "2000";
		}
		else{
			retVal = "1000";
		}
		c.write(retVal + "\n");
	});
  	c.write('hello\r\n');
	c.pipe(c);
});

server.listen(6667, function() { //'listening' listener
  	console.log('server bound');
});

<|endoftext|>


<commit_before>import { Box3 } from '../math/Box3';
import { LineSegments } from '../objects/LineSegments';
import { LineBasicMaterial } from '../materials/LineBasicMaterial';
import { BufferAttribute } from '../core/BufferAttribute';
import { BufferGeometry } from '../core/BufferGeometry';

/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / http://github.com/Mugen87
 */

function BoxHelper( object, color ) {

	this.object = object;

	if ( color === undefined ) color = 0xffff00;

	var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
	var positions = new Float32Array( 8 * 3 );

	var geometry = new BufferGeometry();
	geometry.setIndex( new BufferAttribute( indices, 1 ) );
	geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );

	LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );

	this.matrixAutoUpdate = false;

	this.update();

}

BoxHelper.prototype = Object.create( LineSegments.prototype );
BoxHelper.prototype.constructor = BoxHelper;

BoxHelper.prototype.update = ( function () {

	var box = new Box3();

	return function update( object ) {

		if ( object !== undefined ) {

			console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );

		}

		this.object.updateMatrixWorld( true );

		box.setFromObject( this.object );

		if ( box.isEmpty() ) return;

		var min = box.min;
		var max = box.max;

		/*
		  5____4
		1/___0/|
		| 6__|_7
		2/___3/

		0: max.x, max.y, max.z
		1: min.x, max.y, max.z
		2: min.x, min.y, max.z
		3: max.x, min.y, max.z
		4: max.x, max.y, min.z
		5: min.x, max.y, min.z
		6: min.x, min.y, min.z
		7: max.x, min.y, min.z
		*/

		var position = this.geometry.attributes.position;
		var array = position.array;

		array[  0 ] = max.x; array[  1 ] = max.y; array[  2 ] = max.z;
		array[  3 ] = min.x; array[  4 ] = max.y; array[  5 ] = max.z;
		array[  6 ] = min.x; array[  7 ] = min.y; array[  8 ] = max.z;
		array[  9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
		array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
		array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
		array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
		array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;

		position.needsUpdate = true;

		return this;

	};

} )();

export { BoxHelper };
<commit_msg>BoxHelper: Remove unnecessary .updateMatrixWorld() call<commit_after>import { Box3 } from '../math/Box3';
import { LineSegments } from '../objects/LineSegments';
import { LineBasicMaterial } from '../materials/LineBasicMaterial';
import { BufferAttribute } from '../core/BufferAttribute';
import { BufferGeometry } from '../core/BufferGeometry';

/**
 * @author mrdoob / http://mrdoob.com/
 * @author Mugen87 / http://github.com/Mugen87
 */

function BoxHelper( object, color ) {

	this.object = object;

	if ( color === undefined ) color = 0xffff00;

	var indices = new Uint16Array( [ 0, 1, 1, 2, 2, 3, 3, 0, 4, 5, 5, 6, 6, 7, 7, 4, 0, 4, 1, 5, 2, 6, 3, 7 ] );
	var positions = new Float32Array( 8 * 3 );

	var geometry = new BufferGeometry();
	geometry.setIndex( new BufferAttribute( indices, 1 ) );
	geometry.addAttribute( 'position', new BufferAttribute( positions, 3 ) );

	LineSegments.call( this, geometry, new LineBasicMaterial( { color: color } ) );

	this.matrixAutoUpdate = false;

	this.update();

}

BoxHelper.prototype = Object.create( LineSegments.prototype );
BoxHelper.prototype.constructor = BoxHelper;

BoxHelper.prototype.update = ( function () {

	var box = new Box3();

	return function update( object ) {

		if ( object !== undefined ) {

			console.warn( 'THREE.BoxHelper: .update() has no longer arguments.' );

		}

		box.setFromObject( this.object );

		if ( box.isEmpty() ) return;

		var min = box.min;
		var max = box.max;

		/*
		  5____4
		1/___0/|
		| 6__|_7
		2/___3/

		0: max.x, max.y, max.z
		1: min.x, max.y, max.z
		2: min.x, min.y, max.z
		3: max.x, min.y, max.z
		4: max.x, max.y, min.z
		5: min.x, max.y, min.z
		6: min.x, min.y, min.z
		7: max.x, min.y, min.z
		*/

		var position = this.geometry.attributes.position;
		var array = position.array;

		array[  0 ] = max.x; array[  1 ] = max.y; array[  2 ] = max.z;
		array[  3 ] = min.x; array[  4 ] = max.y; array[  5 ] = max.z;
		array[  6 ] = min.x; array[  7 ] = min.y; array[  8 ] = max.z;
		array[  9 ] = max.x; array[ 10 ] = min.y; array[ 11 ] = max.z;
		array[ 12 ] = max.x; array[ 13 ] = max.y; array[ 14 ] = min.z;
		array[ 15 ] = min.x; array[ 16 ] = max.y; array[ 17 ] = min.z;
		array[ 18 ] = min.x; array[ 19 ] = min.y; array[ 20 ] = min.z;
		array[ 21 ] = max.x; array[ 22 ] = min.y; array[ 23 ] = min.z;

		position.needsUpdate = true;

		return this;

	};

} )();

export { BoxHelper };
<|endoftext|>


<commit_before>const marked = require('marked');
const hbsTemplates = require('./config/handlebars');
const firebase = require('./config/firebase');
const moment = require('moment');
const writefile = require('./writefile');
const renderSass = require('./sass');
const Post = require('./models/Post');
const webpackManifest = require('./config/webpack.manifest.json');

// Create "this-is-a-post" from "This is a Post"
function slugger(str) {
  return str.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-');
}

function logoURL() {
  return `/img/logo${parseInt(Math.random() * 13, 10)}.png`;
}

function rebuildIndex() {
  return new Promise((resolve, reject) => {
    firebase
      .database()
      .ref('/posts')
      .once('value', (snapshot) => {
        const val = snapshot.val();
        const filePath = 'public/index.html';
        let posts = Object.keys(val).map(post => new Post(val[post]));

        if (posts.length === 0) return reject(new Error('There are no posts to build an overview with.'));

        // Post transforms
        posts = posts.map((post) => {
          const p = post;
          p.url = `/posts/${slugger(post.title)}`;
          p.created = moment(post.created).format('DD.MM.YYYY');
          p.lastEdited = moment(post.lastEdited).format('DD.MM.YYYY');
          p.lastSaved = moment(post.lastSaved).format('DD.MM.YYYY');
          p.lastPublished = moment(post.lastPublished).format('DD.MM.YYYY');
          p.description = marked(`${post.markdown.replace(/#+.+\n/gm, '').split(' ').slice(0, 20).join(' ')}...`);
          return p;
        });

        return renderSass()
          .then(result => hbsTemplates.index({
            posts,
            logoURL: logoURL(),
            css: result.webpath,
            webpack: webpackManifest,
          }))
          .then(html => writefile(filePath, html))
          .then(resolve);
      });
  });
}

// Fetch post data from firebase and rebuild a single post
function rebuild(id) {
  return new Promise((resolve, reject) => {
    firebase
      .database()
      .ref(`/posts/${id}`)
      .once('value', (snapshot) => {
        const post = new Post(snapshot.val());
        if (!post) return reject(new Error(`Post with id ${id} not found, can't touch this.`));
        const filePath = `public/posts/${slugger(post.title)}.html`;

        return renderSass()
          .then(result => hbsTemplates.post({
            markdown: marked(post.markdown, {
              sanitize: true,
            }),
            logoURL: logoURL(),
            css: result.webpath,
            webpack: webpackManifest,
          }))
          .then(html => writefile(filePath, html))
          .then(resolve);
      })
      .catch(reject);
  });
}

function rebuildAll() {
  const blogTasks = [];

  firebase
  .database()
  .ref('/posts')
  .once('value', (snapshot) => {
    const val = snapshot.val();
    const posts = Object.keys(val);

    for (let i = 0; i < posts.length; i += 1) {
      blogTasks.push(rebuild(posts[i]));
    }
  });

  return Promise.all(blogTasks);
}

module.exports = {
  rebuildIndex,
  rebuildAll,
  rebuild,
};
<commit_msg>Add unpublish function for the server<commit_after>const marked = require('marked');
const hbsTemplates = require('./config/handlebars');
const firebase = require('./config/firebase');
const moment = require('moment');
const writefile = require('./writefile');
const renderSass = require('./sass');
const Post = require('./models/Post');
const webpackManifest = require('./config/webpack.manifest.json');

// Create "this-is-a-post" from "This is a Post"
function slugger(str) {
  return str.toLowerCase().replace(/[^\w ]+/g, '').replace(/ +/g, '-');
}

function logoURL() {
  return `/img/logo${parseInt(Math.random() * 13, 10)}.png`;
}

function rebuildIndex() {
  return new Promise((resolve, reject) => {
    firebase
      .database()
      .ref('/posts')
      .once('value', (snapshot) => {
        const val = snapshot.val();
        const filePath = 'public/index.html';
        let posts = Object.keys(val).map(post => new Post(val[post]));

        if (posts.length === 0) return reject(new Error('There are no posts to build an overview with.'));

        // Post transforms
        posts = posts.map((post) => {
          const p = post;
          p.url = `/posts/${slugger(post.title)}`;
          p.created = moment(post.created).format('DD.MM.YYYY');
          p.lastEdited = moment(post.lastEdited).format('DD.MM.YYYY');
          p.lastSaved = moment(post.lastSaved).format('DD.MM.YYYY');
          p.lastPublished = moment(post.lastPublished).format('DD.MM.YYYY');
          p.description = marked(`${post.markdown.replace(/#+.+\n/gm, '').split(' ').slice(0, 20).join(' ')}...`);
          return p;
        });

        return renderSass()
          .then(result => hbsTemplates.index({
            posts,
            logoURL: logoURL(),
            css: result.webpath,
            webpack: webpackManifest,
          }))
          .then(html => writefile(filePath, html))
          .then(resolve);
      });
  });
}

// Fetch post data from firebase and rebuild a single post
function rebuild(id) {
  return new Promise((resolve, reject) => {
    firebase
      .database()
      .ref(`/posts/${id}`)
      .once('value', (snapshot) => {
        const post = new Post(snapshot.val());
        if (!post) return reject(new Error(`Post with id ${id} not found, can't touch this.`));
        const filePath = `public/posts/${slugger(post.title)}.html`;

        return renderSass()
          .then(result => hbsTemplates.post({
            markdown: marked(post.markdown, {
              sanitize: true,
            }),
            logoURL: logoURL(),
            css: result.webpath,
            webpack: webpackManifest,
          }))
          .then(html => writefile(filePath, html))
          .then(resolve);
      })
      .catch(reject);
  });
}

function rebuildAll() {
  const blogTasks = [];

  firebase
  .database()
  .ref('/posts')
  .once('value', (snapshot) => {
    const val = snapshot.val();
    const posts = Object.keys(val);

    for (let i = 0; i < posts.length; i += 1) {
      blogTasks.push(rebuild(posts[i]));
    }
  });

  return Promise.all(blogTasks);
}

function unPublish(id) {
  return new Promise((resolve, reject) => {
    firebase
      .database()
      .ref(`/posts/${id}`)
      .once('value', (snapshot) => {
        const val = snapshot.val();
        if (!val) return new Error('This post is deleted or something');
        const post = new Post(val);
        const filepath = `public/posts/${slugger(post.title)}.html`;
        fs.unlink(filepath, (err) => {
          if (err && err.code === 'ENOENT') return resolve();
          if (err) reject(err);
          return resolve();
        });
      });
  });
}

module.exports = {
  rebuildIndex,
  rebuildAll,
  rebuild,
  unPublish,
};
<|endoftext|>


<commit_before>/**
 * @name        jQuery FullScreen Plugin
 * @author      Martin Angelov, Morten Sjøgren
 * @version     1.2
 * @url         http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/
 * @license     MIT License
 */

/*jshint browser: true, jquery: true */
(function($){
  "use strict";

  // These helper functions available only to our plugin scope.
  function supportFullScreen(){
    var doc = document.documentElement;

    return ('requestFullscreen' in doc) ||
      ('mozRequestFullScreen' in doc && document.mozFullScreenEnabled) ||
      ('webkitRequestFullScreen' in doc);
  }

  function requestFullScreen(elem){
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullScreen) {
      elem.webkitRequestFullScreen();
    }
  }

  function fullScreenStatus(){
    return document.fullscreen ||
      document.mozFullScreen ||
      document.webkitIsFullScreen ||
      false;
  }

  function cancelFullScreen(){
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitCancelFullScreen) {
      document.webkitCancelFullScreen();
    }
  }

  function onFullScreenEvent(callback){
    $(document).on("fullscreenchange mozfullscreenchange webkitfullscreenchange", function(){
      // The full screen status is automatically
      // passed to our callback as an argument.

      // Customized for Pageflow-Background-Audio

      if(pageflow.activeBackgroundVideo) {
        setTimeout(function() {
          if(pageflow.activeBackgroundVideo.paused() && !pageflow.features.has('mobile platform')) {
            pageflow.activeBackgroundVideo.play();
          }
        }, 300);
      }
      callback(fullScreenStatus());
    });
  }

  // Adding a new test to the jQuery support object
  $.support.fullscreen = supportFullScreen();

  // Creating the plugin
  $.fn.fullScreen = function(props){
    if(!$.support.fullscreen || this.length !== 1) {
      // The plugin can be called only
      // on one element at a time

      return this;
    }

    if(fullScreenStatus()){
      // if we are already in fullscreen, exit
      cancelFullScreen();
      return this;
    }

    // You can potentially pas two arguments a color
    // for the background and a callback function

    var options = $.extend({
        'background'      : '#111',
        'callback'        : $.noop( ),
        'fullscreenClass' : 'fullScreen'
      }, props),

      elem = this,

    // This temporary div is the element that is
    // actually going to be enlarged in full screen

      fs = $('<div>', {
        'css' : {
          'overflow-y' : 'auto',
          'background' : options.background,
          'width'      : '100%',
          'height'     : '100%'
        }
      })
        .insertBefore(elem)
        .append(elem);

    // You can use the .fullScreen class to
    // apply styling to your element
    elem.addClass( options.fullscreenClass );

    // Inserting our element in the temporary
    // div, after which we zoom it in fullscreen

    requestFullScreen(fs.get(0));

    fs.click(function(e){
      if(e.target == this){
        // If the black bar was clicked
        cancelFullScreen();
      }
    });

    elem.cancel = function(){
      cancelFullScreen();
      return elem;
    };

    onFullScreenEvent(function(fullScreen){
      if(!fullScreen){
        // We have exited full screen.
        // Detach event listener
        $(document).off( 'fullscreenchange mozfullscreenchange webkitfullscreenchange' );
        // Remove the class and destroy
        // the temporary div

        elem.removeClass( options.fullscreenClass ).insertBefore(fs);
        fs.remove();
      }

      // Calling the facultative user supplied callback
      if(options.callback) {
        options.callback(fullScreen);
      }
    });

    return elem;
  };

  $.fn.cancelFullScreen = function( ) {
    cancelFullScreen();

    return this;
  };
}(jQuery));
<commit_msg>Remove unused code<commit_after>/**
 * @name        jQuery FullScreen Plugin
 * @author      Martin Angelov, Morten Sjøgren
 * @version     1.2
 * @url         http://tutorialzine.com/2012/02/enhance-your-website-fullscreen-api/
 * @license     MIT License
 */

/*jshint browser: true, jquery: true */
// We shrank the plugin so that it contains only what Pageflow needs.
(function($){
  "use strict";

  // These helper functions available only to our plugin scope.
  function supportFullScreen(){
    var doc = document.documentElement;

    return ('requestFullscreen' in doc) ||
      ('mozRequestFullScreen' in doc && document.mozFullScreenEnabled) ||
      ('webkitRequestFullScreen' in doc);
  }

  function requestFullScreen(elem){
    if (elem.requestFullscreen) {
      elem.requestFullscreen();
    } else if (elem.mozRequestFullScreen) {
      elem.mozRequestFullScreen();
    } else if (elem.webkitRequestFullScreen) {
      elem.webkitRequestFullScreen();
    }
  }

  function fullScreenStatus(){
    return document.fullscreen ||
      document.mozFullScreen ||
      document.webkitIsFullScreen ||
      false;
  }

  function cancelFullScreen(){
    if (document.exitFullscreen) {
      document.exitFullscreen();
    } else if (document.mozCancelFullScreen) {
      document.mozCancelFullScreen();
    } else if (document.webkitCancelFullScreen) {
      document.webkitCancelFullScreen();
    }
  }

  function onFullScreenEvent(callback){
    $(document).on("fullscreenchange mozfullscreenchange webkitfullscreenchange", function(){
      // The full screen status is automatically
      // passed to our callback as an argument.
      callback(fullScreenStatus());
    });
  }

  // Adding a new test to the jQuery support object
  $.support.fullscreen = supportFullScreen();

  // Creating the plugin
  $.fn.fullScreen = function(options){
    if(!$.support.fullscreen || this.length !== 1) {
      // The plugin can be called only
      // on one element at a time

      return this;
    }

    if(fullScreenStatus()){
      // if we are already in fullscreen, exit
      cancelFullScreen();
      return this;
    }

    var elem = this;

    requestFullScreen(elem.get(0));

    elem.cancel = function(){
      cancelFullScreen();
      return elem;
    };

    onFullScreenEvent(function(fullScreen){
      if(!fullScreen){
        // We have exited full screen.
        // Detach event listener
        $(document).off( 'fullscreenchange mozfullscreenchange webkitfullscreenchange' );
      }

      // Calling callback if user provided it
      if(options.callback) {
        options.callback(fullScreen);
      }
    });

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


<commit_before>// jscs:disable maximumLineLength
eg.module("infiniteGridService", [window.jQuery, eg, window, document], function($, ns, global, doc) {
	var PERSIST_KEY = "__INFINITEGRIDSERVICE_PERSISTKEY__";
	/**
	 * Infinite cascading grid layout service for infiniteGrid
	 * @ko infiniteGrid를 통한 무한 그리드 레이아웃 서비스
	 *
	 * @param {String} DOM Element to be InfiniteGrid <ko>타겟 엘리먼트</ko>
	 * @param {Object} [Options] A set of key/value pairs that configure the InfiniteGridService <ko>key/value 형태의 옵션</ko>
	 * @param {Number} [options.count=240] Count DOM count for recycle. If value is -1, DOM does increase without limit -1. <ko>재사용할 DOM 갯수. -1일 경우 DOM은 계속 늘어남</ko>
	 * @param {Number} [options.threshold=300] Threshold Scroll coordinate threshold <ko>append, prepend 이벤트가 발생하기 위한 스크롤 좌표 임계치</ko>
	 * @param {Boolean} [options.usePersist=true] usePersist Determines whether allows persist <ko>persist 사용 여부</ko>
	 */
	ns.InfiniteGridService = ns.Class.extend(ns.Component, {
		/**
		 * Constructor
		 * @param {String} element selector
		 * @param {Object} options
		 */
		construct: function(element, options) {
			this._$wrapper = $(element);

			this._prevScrollTop = 0;
			this._inserting = false;

			this._topElement = null;
			this._bottomElemment = null;

			this._EVENT_NAMESPACE = ".infiniteGridService" +
					Math.floor((Math.random() * 100000) + 1);

			this._options = $.extend({
				count: 240,
				threshold: 300,
				usePersist: true
			}, options);

			if (this._isEnablePersist()) {
				this._$wrapper.addClass("NO_TAP_HIGHLIGHT");
			}

			this._infiniteGrid = new eg.InfiniteGrid(element, this._options);

			this.activate();
		},
		_getScrollTop: function() {
			return doc.body.scrollTop || doc.documentElement.scrollTop;
		},
		_setBoundaryElements: function() {
			var element;

			if (element = this._infiniteGrid.getTopElement()) {
				this._topElement = element;
			}

			if (element = this._infiniteGrid.getBottomElement()) {
				this._bottomElemment = element;
			}
		},
		_isEnablePersist: function() {
			return (this._options.usePersist && $.persist.isNeeded());
		},
		_onScroll: function() {
			if (this._inserting || this._infiniteGrid.isProcessing()) {
				return;
			}

			var scrollTop = this._getScrollTop();

			if (eg.agent().os.name === "ios" && scrollTop === 0) {
				return;
			}

			if (this._prevScrollTop < scrollTop) {
				if (this._bottomElemment) {
					var bottomElementBoundingClientRect =
						this._bottomElemment.getBoundingClientRect();

					if (bottomElementBoundingClientRect.top <=
							doc.documentElement.clientHeight + this._options.threshold) {
						this.trigger("append");
					}
				}
			} else {
				if (this._topElement) {
					var topElementBoundingClientRect =
						this._topElement.getBoundingClientRect();

					if (topElementBoundingClientRect.bottom >=
							(0 - this._options.threshold)) {
						this._fit();
						this.trigger("prepend");
					}
				}
			}

			this._prevScrollTop = this._getScrollTop();
		},
		_onLayoutComplete: function(e) {
			if (!e.isAppend) {
				global.scrollTo(0, this._getScrollTop() + e.distance);
			}

			this._setBoundaryElements();
			this.trigger("layoutComplete", e);
			this._inserting = false;
		},
		_insertAjax: function(mode, url, options, callback) {
			if ($.isFunction(options)) {
				callback = options;
				options = undefined;
			}

			return $.ajax(url, options)
					.done($.proxy(function(data) {
						if (callback) {
							data = callback(data);
						}
						this._infiniteGrid[mode]($(data));
					}, this))
					.fail($.proxy(function() {
						this._inserting = false;
					}, this));
		},
		_fit: function() {
			var scrollTop = this._getScrollTop();
			var croppedHeight = this._infiniteGrid.fit();
			if (croppedHeight > 0) {
				global.scrollTo(0, scrollTop - croppedHeight);
			}
		},
		/**
		 * Activate
		 * @ko 활성화
		 * @method eg.InfiniteGridService#activate
		 * @return {Object} infiniteGridService Instance itself <ko>인스턴스</ko>
		 */
		activate: function() {
			$(global).on("scroll" + this._EVENT_NAMESPACE, $.proxy(this._onScroll, this));
			this._infiniteGrid.on("layoutComplete", $.proxy(this._onLayoutComplete, this));

			return this;
		},
		/**
		 * Deactivate
		 * @ko 비활성화
		 * @method eg.InfiniteGridService#deactivate
		 * @return {Object} infiniteGridService Instance itself <ko>인스턴스</ko>
		 */
		deactivate: function() {
			$(global).off("scrollend" + this._EVENT_NAMESPACE);
			this._infiniteGrid.off("layoutComplete");
			return this;
		},
		/**
		 * Append elements
		 * @ko 하단에 요소 추가
		 * @method eg.InfiniteGridService#append
		 * @param {String|jQuery} elements DOM Element to append in a target <ko>타겟요소에 추가할 DOM 엘리먼트</ko>
		 * @return {Number} Length The number of elements to prepended <ko>추가한 요소의 갯수</ko>
		 * @example
		 *    infiniteGridService.append("<li> contents </li>");
		 *    infiniteGridService.append($("<li> contents </li>"));
		 */
		append: function(elements) {
			this._inserting = true;
			return this._infiniteGrid.append($(elements));
		},
		/**
		 * Prepend elements
		 * @ko 상단에 요소 추가
		 * @method eg.InfiniteGridService#preppend
		 * @param {String|jQuery} elements DOM Element to append in a target <ko>타겟요소에 추가할 DOM 엘리먼트</ko>
		 * @return {Number} Length The number of elements to prepended <ko>추가한 요소의 갯수</ko>
		 * @example
		 *    infiniteGridService.prepend("<li> contents </li>");
		 *    infiniteGridService.prepend($("<li> contents </li>"));
		 */
		prepend: function(elements) {
			this._inserting = true;
			return this._infiniteGrid.prepend($(elements));
		},
		/**
		 * Append Ajax response elements
		 * @ko 하단에 Ajax 호출 결과 추가
		 * @method eg.InfiniteGridService#appendAjax
		 * @param {String} url URL A string containing the URL to which the request is sent <ko>요청할 URL</ko>
		 * @param {Object} [settings] A set of key/value pairs that configure the Ajax request <ko>Ajax 설정 객체</ko>
		 * @param {Function} [callback] A function to be called when the before append. The function receives one argument: data will append <ko>요청 완료 후 실행 할 콜백. 응답 데이터를 파라메터로 받음</ko>
		 * @return {Object} jqXHR
		 * @example
		 *    infiniteGridService.ajaxAppend("http://server.com/contents", function(data) {
		 *        return $(data);
		 *    } );
		 */
		appendAjax: function(url, settings, callback) {
			this._inserting = true;
			return this._insertAjax("append", url, settings, callback);
		},
		/**
		 * Prepend Ajax response elements
		 * @ko 상단에 요소 추가
		 * @method eg.InfiniteGridService#preppendAjax
		 * @param {String} url URL A string containing the URL to which the request is sent <ko>요청할 URL</ko>
		 * @param {Object} [settings] A set of key/value pairs that configure the Ajax request <ko>Ajax 설정 객체</ko>
		 * @param {Function} [callback] A function to be called when the before append. The function receives one argument: data to prepended <ko>요청 완료 후 실행 할 콜백. 응답 데이터를 파라메터로 받음</ko>
		 * @return {Object} jqXHR
		 * @example
			infiniteGridService.ajaxPrepend("http://server.com/contents", function(data) {
				return $(data);
			} );
		 */
		prependAjax: function(url, settings, callback) {
			this._inserting = true;
			return this._insertAjax("prepend", url, settings, callback);
		},
		/**
		 * Stores state
		 * @ko 상태 저장
		 * @method eg.InfiniteGridService#store
		 * @param {String} [key] The type of keys maintained <ko>저장/복원을 위해 관리하는 키</ko>
		 * @example
			infiniteGridService.store();
			infiniteGridService.store("customKey");
		*/
		store: function(key) {
			if (this._isEnablePersist()) {
				var data;

				key = key || PERSIST_KEY;

				data = {
					"infiniteGridStatus": this._infiniteGrid.getStatus(),
					"scrollTop": this._getScrollTop()
				};

				this.trigger("beforeStore", data);
				$.persist(key, data);
			}
		},
		/**
		 * Restores state
		 * @ko 상태 복원
		 * @method eg.InfiniteGridService#restore
		 * @param {String} [key] The type of keys maintained <ko>저장/복원을 위해 관리하는 키</ko>
		 * @example
			infiniteGridService.restore();
			infiniteGridService.restore("customKey");
		*/
		restore: function(key) {
			var data;
			var isRestored = false;

			if (this._isEnablePersist()) {

				key = key || PERSIST_KEY;

				data = $.persist(key);

				if (data) {
					this._infiniteGrid.setStatus(data.infiniteGridStatus);
					global.scrollTo(0, data.scrollTop);
					this._setBoundaryElements();
					isRestored = true;
				}

				this.trigger("restore", data);
			}

			return isRestored;
		},
		/**
		 * Clear elements
		 * @ko 요소를 지움
		 * @method eg.infiniteGridService#clear
		 */
		clear: function() {
			this._infiniteGrid.clear();
		},
		/**
		 * Release resources and off custom events
		 * @ko 모든 커스텀 이벤트와 자원 해제
		 * @method eg.infiniteGridService#destroy
		 */
		destroy: function() {
			if (this._infiniteGrid) {
				this.deactivate();
				this._infiniteGrid.destroy();
				this._infiniteGrid = null;
			}
		}
	});
});<commit_msg>feat: return this<commit_after>// jscs:disable maximumLineLength
eg.module("infiniteGridService", [window.jQuery, eg, window, document], function($, ns, global, doc) {
	var PERSIST_KEY = "__INFINITEGRIDSERVICE_PERSISTKEY__";
	/**
	 * Infinite cascading grid layout service for infiniteGrid
	 * @ko infiniteGrid를 통한 무한 그리드 레이아웃 서비스
	 *
	 * @param {String} DOM Element to be InfiniteGrid <ko>타겟 엘리먼트</ko>
	 * @param {Object} [Options] A set of key/value pairs that configure the InfiniteGridService <ko>key/value 형태의 옵션</ko>
	 * @param {Number} [options.count=240] Count DOM count for recycle. If value is -1, DOM does increase without limit -1. <ko>재사용할 DOM 갯수. -1일 경우 DOM은 계속 늘어남</ko>
	 * @param {Number} [options.threshold=300] Threshold Scroll coordinate threshold <ko>append, prepend 이벤트가 발생하기 위한 스크롤 좌표 임계치</ko>
	 * @param {Boolean} [options.usePersist=true] usePersist Determines whether allows persist <ko>persist 사용 여부</ko>
	 */
	ns.InfiniteGridService = ns.Class.extend(ns.Component, {
		/**
		 * Constructor
		 * @param {String} element selector
		 * @param {Object} options
		 */
		construct: function(element, options) {
			this._$wrapper = $(element);

			this._prevScrollTop = 0;
			this._inserting = false;

			this._topElement = null;
			this._bottomElemment = null;

			this._EVENT_NAMESPACE = ".infiniteGridService" +
					Math.floor((Math.random() * 100000) + 1);

			this._options = $.extend({
				count: 240,
				threshold: 300,
				usePersist: true
			}, options);

			if (this._isEnablePersist()) {
				this._$wrapper.addClass("NO_TAP_HIGHLIGHT");
			}

			this._infiniteGrid = new eg.InfiniteGrid(element, this._options);

			this.activate();
		},
		_getScrollTop: function() {
			return doc.body.scrollTop || doc.documentElement.scrollTop;
		},
		_setBoundaryElements: function() {
			var element;

			if (element = this._infiniteGrid.getTopElement()) {
				this._topElement = element;
			}

			if (element = this._infiniteGrid.getBottomElement()) {
				this._bottomElemment = element;
			}
		},
		_isEnablePersist: function() {
			return (this._options.usePersist && $.persist.isNeeded());
		},
		_onScroll: function() {
			if (this._inserting || this._infiniteGrid.isProcessing()) {
				return;
			}

			var scrollTop = this._getScrollTop();

			if (eg.agent().os.name === "ios" && scrollTop === 0) {
				return;
			}

			if (this._prevScrollTop < scrollTop) {
				if (this._bottomElemment) {
					var bottomElementBoundingClientRect =
						this._bottomElemment.getBoundingClientRect();

					if (bottomElementBoundingClientRect.top <=
							doc.documentElement.clientHeight + this._options.threshold) {
						this.trigger("append");
					}
				}
			} else {
				if (this._topElement) {
					var topElementBoundingClientRect =
						this._topElement.getBoundingClientRect();

					if (topElementBoundingClientRect.bottom >=
							(0 - this._options.threshold)) {
						this._fit();
						this.trigger("prepend");
					}
				}
			}

			this._prevScrollTop = this._getScrollTop();
		},
		_onLayoutComplete: function(e) {
			if (!e.isAppend) {
				global.scrollTo(0, this._getScrollTop() + e.distance);
			}

			this._setBoundaryElements();
			this.trigger("layoutComplete", e);
			this._inserting = false;
		},
		_insertAjax: function(mode, url, options, callback) {
			if ($.isFunction(options)) {
				callback = options;
				options = undefined;
			}

			return $.ajax(url, options)
					.done($.proxy(function(data) {
						if (callback) {
							data = callback(data);
						}
						this._infiniteGrid[mode]($(data));
					}, this))
					.fail($.proxy(function() {
						this._inserting = false;
					}, this));
		},
		_fit: function() {
			var scrollTop = this._getScrollTop();
			var croppedHeight = this._infiniteGrid.fit();
			if (croppedHeight > 0) {
				global.scrollTo(0, scrollTop - croppedHeight);
			}
		},
		/**
		 * Activate
		 * @ko 활성화
		 * @method eg.InfiniteGridService#activate
		 * @return {Object} infiniteGridService Instance itself <ko>인스턴스</ko>
		 */
		activate: function() {
			$(global).on("scroll" + this._EVENT_NAMESPACE, $.proxy(this._onScroll, this));
			this._infiniteGrid.on("layoutComplete", $.proxy(this._onLayoutComplete, this));

			return this;
		},
		/**
		 * Deactivate
		 * @ko 비활성화
		 * @method eg.InfiniteGridService#deactivate
		 * @return {Object} infiniteGridService Instance itself <ko>인스턴스</ko>
		 */
		deactivate: function() {
			$(global).off("scrollend" + this._EVENT_NAMESPACE);
			this._infiniteGrid.off("layoutComplete");
			return this;
		},
		/**
		 * Append elements
		 * @ko 하단에 요소 추가
		 * @method eg.InfiniteGridService#append
		 * @param {String|jQuery} elements DOM Element to append in a target <ko>타겟요소에 추가할 DOM 엘리먼트</ko>
		 * @return {Number} Length The number of elements to prepended <ko>추가한 요소의 갯수</ko>
		 * @example
		 *    infiniteGridService.append("<li> contents </li>");
		 *    infiniteGridService.append($("<li> contents </li>"));
		 */
		append: function(elements) {
			this._inserting = true;
			return this._infiniteGrid.append($(elements));
		},
		/**
		 * Prepend elements
		 * @ko 상단에 요소 추가
		 * @method eg.InfiniteGridService#preppend
		 * @param {String|jQuery} elements DOM Element to append in a target <ko>타겟요소에 추가할 DOM 엘리먼트</ko>
		 * @return {Number} Length The number of elements to prepended <ko>추가한 요소의 갯수</ko>
		 * @example
		 *    infiniteGridService.prepend("<li> contents </li>");
		 *    infiniteGridService.prepend($("<li> contents </li>"));
		 */
		prepend: function(elements) {
			this._inserting = true;
			return this._infiniteGrid.prepend($(elements));
		},
		/**
		 * Append Ajax response elements
		 * @ko 하단에 Ajax 호출 결과 추가
		 * @method eg.InfiniteGridService#appendAjax
		 * @param {String} url URL A string containing the URL to which the request is sent <ko>요청할 URL</ko>
		 * @param {Object} [settings] A set of key/value pairs that configure the Ajax request <ko>Ajax 설정 객체</ko>
		 * @param {Function} [callback] A function to be called when the before append. The function receives one argument: data will append <ko>요청 완료 후 실행 할 콜백. 응답 데이터를 파라메터로 받음</ko>
		 * @return {Object} jqXHR
		 * @example
		 *    infiniteGridService.ajaxAppend("http://server.com/contents", function(data) {
		 *        return $(data);
		 *    } );
		 */
		appendAjax: function(url, settings, callback) {
			this._inserting = true;
			return this._insertAjax("append", url, settings, callback);
		},
		/**
		 * Prepend Ajax response elements
		 * @ko 상단에 요소 추가
		 * @method eg.InfiniteGridService#preppendAjax
		 * @param {String} url URL A string containing the URL to which the request is sent <ko>요청할 URL</ko>
		 * @param {Object} [settings] A set of key/value pairs that configure the Ajax request <ko>Ajax 설정 객체</ko>
		 * @param {Function} [callback] A function to be called when the before append. The function receives one argument: data to prepended <ko>요청 완료 후 실행 할 콜백. 응답 데이터를 파라메터로 받음</ko>
		 * @return {Object} jqXHR
		 * @example
			infiniteGridService.ajaxPrepend("http://server.com/contents", function(data) {
				return $(data);
			} );
		 */
		prependAjax: function(url, settings, callback) {
			this._inserting = true;
			return this._insertAjax("prepend", url, settings, callback);
		},
		/**
		 * Stores state
		 * @ko 상태 저장
		 * @method eg.InfiniteGridService#store
		 * @param {String} [key] The type of keys maintained <ko>저장/복원을 위해 관리하는 키</ko>
		 * @return {Object} instance itself
		 * @example
			infiniteGridService.store();
			infiniteGridService.store("customKey");
		*/
		store: function(key) {
			if (this._isEnablePersist()) {
				var data;

				key = key || PERSIST_KEY;

				data = {
					"infiniteGridStatus": this._infiniteGrid.getStatus(),
					"scrollTop": this._getScrollTop()
				};

				this.trigger("beforeStore", data);
				$.persist(key, data);
			}

			return this;
		},
		/**
		 * Restores state
		 * @ko 상태 복원
		 * @method eg.InfiniteGridService#restore
		 * @param {String} [key] The type of keys maintained <ko>저장/복원을 위해 관리하는 키</ko>
		 * @return {Boolean} Determine if state restored
		 * @example
			infiniteGridService.restore();
			infiniteGridService.restore("customKey");
		*/
		restore: function(key) {
			var data;
			var isRestored = false;

			if (this._isEnablePersist()) {

				key = key || PERSIST_KEY;

				data = $.persist(key);

				if (data) {
					this._infiniteGrid.setStatus(data.infiniteGridStatus);
					global.scrollTo(0, data.scrollTop);
					this._setBoundaryElements();
					isRestored = true;
				}

				this.trigger("restore", data);
			}

			return isRestored;
		},
		/**
		 * Clear elements
		 * @ko 요소를 지움
		 * @method eg.infiniteGridService#clear
		 */
		clear: function() {
			this._infiniteGrid.clear();
			return this;
		},
		/**
		 * Release resources and off custom events
		 * @ko 모든 커스텀 이벤트와 자원 해제
		 * @method eg.infiniteGridService#destroy
		 */
		destroy: function() {
			if (this._infiniteGrid) {
				this.deactivate();
				this._infiniteGrid.destroy();
				this._infiniteGrid = null;
			}
		}
	});
});<|endoftext|>


<commit_before><commit_msg>rebuild<commit_after><|endoftext|>


<commit_before>'use strict';

require('./support/support');

const sinon = require('sinon');

const Option = require('./../lib/Option');

describe('Option', () => {

    let mockOption;

    beforeEach(() => {
        mockOption = new Option(yargs => yargs.transform(), (options, argv) => options.transform(argv));
    });

    describe('transformYargs', () => {

        it('should invoke the first constructor argument', () => {

            let yargs = {transform: sinon.spy()};
            mockOption.transformYargs(yargs);
            yargs.transform.should.have.been.calledOnce;
        });
    });

    describe('transformContextOptions', () => {

        it('should invoke the second constructor argument', () => {

            let argv    = {foo: 'barss'};
            let options = {transform: sinon.spy()};
            mockOption.transformContextOptions(options, argv);
            options.transform.should.have.been.calledWith(argv);
        });
    });
});<commit_msg>Add createSimpleFlag test<commit_after>'use strict';

require('./support/support');

const sinon = require('sinon');
const _     = require('lodash');

const Option = require('./../lib/Option');

describe('Option', () => {

    let mockOption;

    beforeEach(() => {
        mockOption = new Option(yargs => {
            yargs.transform();
            return yargs;
        }, (options, argv) => options.transform(argv));
    });

    describe('transformYargs', () => {

        it('should invoke the first constructor argument', () => {

            let yargs = {transform: sinon.spy()};
            mockOption.transformYargs(yargs).should.equal(yargs);
            yargs.transform.should.have.been.calledOnce;
        });
    });

    describe('transformContextOptions', () => {

        it('should invoke the second constructor argument', () => {

            let argv    = {foo: 'barss'};
            let options = {transform: sinon.spy()};
            mockOption.transformContextOptions(options, argv);
            options.transform.should.have.been.calledWith(argv);
        });
    });

    describe('createSimpleFlag', () => {

        it('should instantiate a flag-like option', () => {

            let option = Option.createSimpleFlag('foobarness', 'The degree of foobarness', 'f', true);
            let yargs  = option.transformYargs(require('yargs'));
            yargs.parse(['--foobarness']).should.have.property('foobarness', 1);
            yargs.parse(['-fff']).should.have.property('foobarness', 3);
            let options = {};
            option.transformContextOptions(options, {foobarness: 10});
            options.should.deep.equal({foobarness: 10});
        });
    });
});<|endoftext|>


<commit_before>const async = require("async");
const models = require("../../models");
const log = require('../utils/logger');
const queue = require('./queue');
const i18n = require('../utils/i18n');
const toJson = require('../utils/to_json');
const _ = require('lodash');
const fs = require('fs');
const sendCampaign = require('../engine/marketing/campaign').sendCampaign;

let airbrake = null;
if(process.env.AIRBRAKE_PROJECT_ID) {
  airbrake = require('../utils/airbrake');
}

let MarketingWorker = function () {};

MarketingWorker.prototype.process = (workPackage, callback) => {
  switch (workPackage.type) {
    case 'send-campaign':
      sendCampaign(workPackage, callback);
      break;
    default:
      callback("Unknown type for workPackage: " + workPackage.type);
  }
};

module.exports = new ReportsWorker();
<commit_msg>Work on marketing app<commit_after>const async = require("async");
const models = require("../../models");
const log = require('../utils/logger');
const queue = require('./queue');
const i18n = require('../utils/i18n');
const toJson = require('../utils/to_json');
const _ = require('lodash');
const fs = require('fs');
const sendCampaign = require('../engine/marketing/campaign').sendCampaign;

let airbrake = null;
if(process.env.AIRBRAKE_PROJECT_ID) {
  airbrake = require('../utils/airbrake');
}

let MarketingWorker = function () {};

MarketingWorker.prototype.process = (workPackage, callback) => {
  switch (workPackage.type) {
    case 'send-campaign':
      sendCampaign(workPackage, callback);
      break;
    default:
      callback("Unknown type for workPackage: " + workPackage.type);
  }
};

module.exports = new MarketingWorker();
<|endoftext|>


<commit_before>/*

container of data to be updated must have the class '.live-stream-container'

filterFunc is a function that takes one argument, the string "filter" and returns the type of filter to apply.

defaultFilter is a string of the default filter to apply

searchParams is a dictionary of additional search params to ping the server with

updateTemplate is a html string to show when new data is available. Defaults to history container code

*/
function liveStreamPing(filterFunc, defaultFilter, searchParams, updateTemplate){
    this.history = [];
    this.$container = $('.live-stream-container');
    this.pingIntervalValue = 2500;
    this.searchParams = searchParams
    this.updateTemplate = updateTemplate || "
   Load new items
"

    this.setup = function() {
        this.pingInterval = setInterval($.proxy(this.ping, this), this.pingIntervalValue);
        this.setupIdle();
        this.first();

        $(document).on('ping-new', $.proxy(this.showNotification, this));
        this.$container.on('click', '.load-new', $.proxy(this.insertHistoryItems, this));
    }

    this.setupIdle = function() {
        var that = this;
        $(window).idle(
            function() {
                clearInterval(that.pingInterval);
            },
            function() {
                that.pingInterval = setInterval($.proxy(that.ping, that), that.pingIntervalValue);
            }
        );
    }

    this.ping = function(callback){
        var filter = filterFunc('filter') || defaultFilter;
        var timestamp = $('.first .date').data('timestamp');
        var payload =  {
            'filter' : filter,
            'timestamp' : timestamp,
            'return_type' : 'list',
            'type' : 'ping',
            }
        for (var attrname in this.searchParams) {
            payload[attrname] = this.searchParams[attrname];
        }
        var that = this;
        $.getJSON('/live_stream/ping/', payload, function(res){
                that.history = res.history;
                if (callback){
                    callback(res);
                }
                if (that.history.length) {
                    $(document).trigger('ping-new');
                }
        });
    }

    this.first = function() {
        this.$container.children().first().addClass('first');
    }

    this.showNotification = function() {
        if (!$('.load-new').length){
            this.$container.prepend(this.updateTemplate);
        }
    }

    this.insertHistoryItems = function (e){
        $('.first').removeClass('first');
        var $loadNew = $('.load-new')
        $loadNew.fadeOut();
        var that = this;
        $.each(that.history.reverse(), function(index, item){
            var $toAdd = $(item);

            $toAdd.hide();
            $toAdd.css('opacity', 0);

            that.$container.prepend($toAdd);

            $toAdd.slideDown(function(){
                $toAdd.animate({opacity:1}, 150);
            });
            if (index == that.history.length -1){
                $toAdd.addClass('first');
            }
        })

        this.history = [];
        $loadNew.remove();
    }
    this.setup()
    return this
}<commit_msg>removed ugly color<commit_after>/*

container of data to be updated must have the class '.live-stream-container'

filterFunc is a function that takes one argument, the string "filter" and returns the type of filter to apply.

defaultFilter is a string of the default filter to apply

searchParams is a dictionary of additional search params to ping the server with

updateTemplate is a html string to show when new data is available. Defaults to history container code

*/
function liveStreamPing(filterFunc, defaultFilter, searchParams, updateTemplate){
    this.history = [];
    this.$container = $('.live-stream-container');
    this.pingIntervalValue = 2500;
    this.searchParams = searchParams
    this.updateTemplate = updateTemplate || "
   Load new items
"

    this.setup = function() {
        this.pingInterval = setInterval($.proxy(this.ping, this), this.pingIntervalValue);
        this.setupIdle();
        this.first();

        $(document).on('ping-new', $.proxy(this.showNotification, this));
        this.$container.on('click', '.load-new', $.proxy(this.insertHistoryItems, this));
    }

    this.setupIdle = function() {
        var that = this;
        $(window).idle(
            function() {
                clearInterval(that.pingInterval);
            },
            function() {
                that.pingInterval = setInterval($.proxy(that.ping, that), that.pingIntervalValue);
            }
        );
    }

    this.ping = function(callback){
        var filter = filterFunc('filter') || defaultFilter;
        var timestamp = $('.first .date').data('timestamp');
        var payload =  {
            'filter' : filter,
            'timestamp' : timestamp,
            'return_type' : 'list',
            'type' : 'ping',
            }
        for (var attrname in this.searchParams) {
            payload[attrname] = this.searchParams[attrname];
        }
        var that = this;
        $.getJSON('/live_stream/ping/', payload, function(res){
                that.history = res.history;
                if (callback){
                    callback(res);
                }
                if (that.history.length) {
                    $(document).trigger('ping-new');
                }
        });
    }

    this.first = function() {
        this.$container.children().first().addClass('first');
    }

    this.showNotification = function() {
        if (!$('.load-new').length){
            this.$container.prepend(this.updateTemplate);
        }
    }

    this.insertHistoryItems = function (e){
        $('.first').removeClass('first');
        var $loadNew = $('.load-new')
        $loadNew.fadeOut();
        var that = this;
        $.each(that.history.reverse(), function(index, item){
            var $toAdd = $(item);

            $toAdd.hide();
            $toAdd.css('opacity', 0);

            that.$container.prepend($toAdd);

            $toAdd.slideDown(function(){
                $toAdd.animate({opacity:1}, 150);
            });
            if (index == that.history.length -1){
                $toAdd.addClass('first');
            }
        })

        this.history = [];
        $loadNew.remove();
    }
    this.setup()
    return this
}<|endoftext|>


<commit_before>// ==UserScript==
// @name        Element Remover
// @namespace   samsquanchhunter
// @version     0.1.1
// @include     http://*
// @include     https://*
// @grant       none
// ==/UserScript==

///portions from https://github.com/pinceladasdaweb/imgur-upload and LouCypher

var body = document.body;
body.addEventListener("contextmenu", initMenu, false);

if(document.getElementsByTagName("menu").length === 0){
  var menu = document.createElement("menu");
  menu.id = "userscript-grease";
  menu.type = "context";
}else{
  menu = document.getElementsByTagName("menu")[0];
}
var menuitem = document.createElement("menuitem");
menuitem.id = "menu_elemr";
menuitem.label = "Remove Element";
menuitem.icon = "http://i.imgur.com/IeWWYDw.png";
menu.appendChild(menuitem);
body.appendChild(menu);

document.querySelector("#userscript-grease #menu_elemr")
  .addEventListener("click", rElement, false);

var child_node = null;
var parent_node = null;

var running_array = [];

function initMenu(aEvent) {
  // Executed when user right click on web page body
  // aEvent.target is the element you right click on
  body.setAttribute("contextmenu", "userscript-grease");
  child_node = aEvent.target;
  parent_node = child_node.parentNode;
  var item = document.querySelector("#userscript-grease #menu_elemr");
}

function rElement(aEvent) {
  // Executed when user click on menuitem
  // aEvent.target is the <menuitem> element
  addElement(child_node);
}

function addElement(elem) {
  running_array.push(elem);
}

window.addEventListener('load', function() { /* shit goes down in here */
   setInterval(function(){
     for(var t = 0; t < running_array.length; t++){
       var c_node = running_array[t];
       var p_node = c_node.parentNode;
       p_node.removeChild(c_node);
     }
  }, 1000);
}, false);
<commit_msg>might fix something<commit_after>// ==UserScript==
// @name        Element Remover
// @namespace   samsquanchhunter
// @version     0.1.1
// @include     http://*
// @include     https://*
// @grant       none
// ==/UserScript==

///portions from https://github.com/pinceladasdaweb/imgur-upload and LouCypher

var body = document.body;
body.addEventListener("contextmenu", initMenu, false);

if(document.getElementsByTagName("menu").length === 0){
  var menu = document.createElement("menu");
  menu.id = "userscript-grease";
  menu.type = "context";
}else{
  menu = document.getElementsByTagName("menu")[0];
}
var menuitem = document.createElement("menuitem");
menuitem.id = "menu_elemr";
menuitem.label = "Remove Element";
menuitem.icon = "http://i.imgur.com/IeWWYDw.png";
menu.appendChild(menuitem);
body.appendChild(menu);

document.querySelector("#userscript-grease #menu_elemr")
  .addEventListener("click", rElement, false);

function initMenu(aEvent) {
  // Executed when user right click on web page body
  // aEvent.target is the element you right click on
  body.setAttribute("contextmenu", "userscript-grease");
  child_node = aEvent.target;
  parent_node = child_node.parentNode;
  var item = document.querySelector("#userscript-grease #menu_elemr");
}

function rElement(aEvent) {
  // Executed when user click on menuitem
  // aEvent.target is the <menuitem> element
  console.log(child_node);
  addElement(child_node);
}

var running_array;

var child_node, parent_node;

if(running_array === undefined){
  running_array = [];
}

function addElement(elem) {
  running_array.push.apply(running_array, [elem]);
  //running_array.push(elem);
}
window.addEventListener('load', function() { /* shit goes down in here */
   setInterval(function(){
    for(var t = 0; t < (running_array.length - 1); t++){
      var c_node = running_array[t];
      var p_node = c_node.parentNode;
      p_node.removeChild(c_node);
    }
    console.log(running_array);
}, 1000);

}, false);
<|endoftext|>


<commit_before>// ---------------------------------------------------------------------------------------------------------------------
/// SceneManager - Manages BabylonJS scenes
///
/// @module sceneman.js
// ---------------------------------------------------------------------------------------------------------------------

var util = require('util');
var EventEmitter = require('events').EventEmitter;

var _ = require('lodash');
var Promise = require('bluebird');

// ---------------------------------------------------------------------------------------------------------------------

function SceneManagerFactory($rootScope, Loader, babylon)
{
    /**
     * The SceneManager is intended to be the single API for working with BabylonJS's scene and asset loader. It handles
     * all of the boilerplate required.
     *
     * @constructor
     */
    function SceneManager()
    {
        EventEmitter.call(this);
        this.meshes = {};
    } // end SceneManager

    util.inherits(SceneManager, EventEmitter);

    // -----------------------------------------------------------------------------------------------------------------
    // Public
    // -----------------------------------------------------------------------------------------------------------------

    /**
     * Sets the element that we will render into. This element must be a `<canvas>`, and is assumed to have already been
     * created by the time this is called.
     *
     * @param {Element} elem - The canvas element for us to render into.
     */
    SceneManager.prototype.setRenderTarget = function(elem)
    {
        this.canvas = elem;
        this.engine = new babylon.Engine(elem, true);
        this.loader = new Loader(this.engine);
    }; // end setRenderTarget

    /**
     * Creates a skybox, and sets up any and all special rendering callbacks required.
     *
     * @param {string} baseFileName - This is the base file name of the images to use for the skybox. It is assumed to
     * be relative to our static files path. The actual files are assumed to have the following extensions:
     *   - '_right1.png'
     *   - '_top3.png'
     *   - '_front5.png'
     *   - '_left2.png'
     *   - '_bottom4.png'
     *   - '_back6.png'
     *
     * See the `Loader` for more information.
     *
     * @returns {Promise<*>} Returns a promise that is resolved once the loader creates the skybox.
     */
    SceneManager.prototype.createSkybox = function(baseFileName)
    {
        var self = this;

        if(!this.loader)
        {
            return Promise.reject(new Error("Must set a render target before attempting to load a skybox."));
        }
        else
        {
            //TODO: There may be more work required here. We are currently reparenting the skybox's position to the
            // camera's position. We also need to change it's render order, and possibly turn off depth buffer clearing.
            return this.loader.createSkybox(this.currentScene, baseFileName);
        } // end if
    }; // end createSkybox

    /**
     * Retrieves a mesh instance for the given meshName, and modelPath. If the mesh has already been loaded, we retrieve
     * it from an internal cache, and return a new instance of the mesh. If it has not been loaded, we expect modelPath
     * to exist, and then we load the mesh, and store it.
     *
     * @param {string} meshName - The name of the mesh to create an instance of. If `""`, modelPath is required, and all
     * meshes in the model will be loaded. (These meshes will not be cached, and will be loaded every time.)
     *
     * @param {string} modelPath - The path to the model, relative to our static files path.
     *
     * @returns {Promise<Mesh>} Returns a promise that resolves with the new mesh instance.
     */
    SceneManager.prototype.loadMesh = function(meshName, modelPath)
    {
        var self = this;

        if(arguments.length == 1)
        {
            modelPath = meshName;
            meshName = "";
        } // end if

        if(!_.isEmpty(meshName) && meshName in this.meshes)
        {
            return Promise.resolve(this.meshes[meshName])
                .then(function(mesh)
                {
                    return mesh.createInstance();
                });
        }
        else
        {
            return this.loader.loadMesh(this.currentScene, meshName, modelPath)
                .then(function(loaded)
                {
                    // We only support loading a single mesh at a time
                    var mesh = loaded.meshes[0];

                    // We put all meshes (except skyboxes) in rendering group 1.
                    mesh.renderingGroupId = 1;

                    if(!_.isEmpty(meshName))
                    {
                        self.meshes[meshName] = mesh;
                    } // end if

                    return mesh;
                });
        } // end if
    }; // end loadMesh

    /**
     * Loads a scene by path.
     *
     * @param {string} scenePath - A path to the `.babylon` file for the scene. This is assumed to be relative to our
     * static content directory.
     *
     * @returns {Promise<undefined>} Returns a promise that resolves once the scene is loaded, and considers itself
     * 'ready'.
     */
    SceneManager.prototype.loadScene = function(scenePath)
    {
        var scenePromise;
        var self = this;

        if(!scenePath)
        {
            // Create an empty scene
            scenePromise = Promise.resolve(new babylon.Scene(this.engine));
        }
        else
        {
            scenePromise = this.loader.loadScene(scenePath);
        } // end if

        return scenePromise.then(function(scene)
        {
            // Set our current scene
            self.currentScene = scene;

            // Let anyone who cares know we've changed scenes
            $rootScope.$broadcast('scene loaded');

            // We always create a camera for the player's perspective.
            self.playerCamera = new babylon.ArcRotateCamera("PlayerCamera", 0, 0, 100, babylon.Vector3.Zero(),
                self.currentScene);

            return new Promise(function(resolve)
            {
                // Resolve once the scene's ready
                self.currentScene.executeWhenReady(function()
                {
                    resolve();
                });
            });
        });
    }; // end loadScene

    /**
     * Starts the render loop. Broadcasts `"engine started"` on the root scope.
     */
    SceneManager.prototype.startEngine = function()
    {
        $rootScope.$broadcast("engine started");
        this.engine.runRenderLoop(this._renderLoop.bind(this));
    }; // end startEngine

    /**
     * Stops the render loop. Broadcasts `"engine stopped"` on the root scope.
     */
    SceneManager.prototype.stopEngine = function()
    {
        $rootScope.$broadcast("engine stopped");
        this.engine.stopRenderLoop();
    }; // end stopEngine

    // -----------------------------------------------------------------------------------------------------------------
    // Private
    // -----------------------------------------------------------------------------------------------------------------

    /**
     * The render loop. Fires events `before render` and `after render`.
     *
     * @private
     */
    SceneManager.prototype._renderLoop = function()
    {
        this.emit('before render');
        this.currentScene.render();
        this.emit('after render');
    }; // end _renderLoop

    // -----------------------------------------------------------------------------------------------------------------

    return new SceneManager();
} // end SceneManagerFactory

// ---------------------------------------------------------------------------------------------------------------------

angular.module('rfi-client.services').service('SceneManager', [
    '$rootScope',
    'Loader',
    'babylon',
    SceneManagerFactory
]);

// ---------------------------------------------------------------------------------------------------------------------<commit_msg>fixed an issue with mesh creation.<commit_after>// ---------------------------------------------------------------------------------------------------------------------
/// SceneManager - Manages BabylonJS scenes
///
/// @module sceneman.js
// ---------------------------------------------------------------------------------------------------------------------

var util = require('util');
var EventEmitter = require('events').EventEmitter;

var _ = require('lodash');
var Promise = require('bluebird');

// ---------------------------------------------------------------------------------------------------------------------

function SceneManagerFactory($rootScope, Loader, babylon)
{
    /**
     * The SceneManager is intended to be the single API for working with BabylonJS's scene and asset loader. It handles
     * all of the boilerplate required.
     *
     * @constructor
     */
    function SceneManager()
    {
        EventEmitter.call(this);
        this.meshes = {};
    } // end SceneManager

    util.inherits(SceneManager, EventEmitter);

    // -----------------------------------------------------------------------------------------------------------------
    // Public
    // -----------------------------------------------------------------------------------------------------------------

    /**
     * Sets the element that we will render into. This element must be a `<canvas>`, and is assumed to have already been
     * created by the time this is called.
     *
     * @param {Element} elem - The canvas element for us to render into.
     */
    SceneManager.prototype.setRenderTarget = function(elem)
    {
        this.canvas = elem;
        this.engine = new babylon.Engine(elem, true);
        this.loader = new Loader(this.engine);
    }; // end setRenderTarget

    /**
     * Creates a skybox, and sets up any and all special rendering callbacks required.
     *
     * @param {string} baseFileName - This is the base file name of the images to use for the skybox. It is assumed to
     * be relative to our static files path. The actual files are assumed to have the following extensions:
     *   - '_right1.png'
     *   - '_top3.png'
     *   - '_front5.png'
     *   - '_left2.png'
     *   - '_bottom4.png'
     *   - '_back6.png'
     *
     * See the `Loader` for more information.
     *
     * @returns {Promise<*>} Returns a promise that is resolved once the loader creates the skybox.
     */
    SceneManager.prototype.createSkybox = function(baseFileName)
    {
        var self = this;

        if(!this.loader)
        {
            return Promise.reject(new Error("Must set a render target before attempting to load a skybox."));
        }
        else
        {
            //TODO: There may be more work required here. We are currently reparenting the skybox's position to the
            // camera's position. We also need to change it's render order, and possibly turn off depth buffer clearing.
            return this.loader.createSkybox(this.currentScene, baseFileName);
        } // end if
    }; // end createSkybox

    /**
     * Retrieves a mesh instance for the given meshName, and modelPath. If the mesh has already been loaded, we retrieve
     * it from an internal cache, and return a new instance of the mesh. If it has not been loaded, we expect modelPath
     * to exist, and then we load the mesh, and store it.
     *
     * @param {string} meshName - The name of the mesh to create an instance of. If `""`, modelPath is required, and all
     * meshes in the model will be loaded. (These meshes will not be cached, and will be loaded every time.)
     *
     * @param {string} modelPath - The path to the model, relative to our static files path.
     *
     * @returns {Promise<Mesh>} Returns a promise that resolves with the new mesh instance.
     */
    SceneManager.prototype.loadMesh = function(meshName, modelPath)
    {
        var self = this;

        if(arguments.length == 1)
        {
            modelPath = meshName;
            meshName = "";
        } // end if

        if(!_.isEmpty(meshName) && meshName in this.meshes)
        {
            return Promise.resolve(this.meshes[meshName])
                .then(function(mesh)
                {
                    var instance = mesh.createInstance();

                    // Instances reset their parent's renderingGroupId, so we need to fix it.
                    instance.renderingGroupId = 1;

                    return instance
                });
        }
        else
        {
            return this.loader.loadMesh(this.currentScene, meshName, modelPath)
                .then(function(loaded)
                {
                    // We only support loading a single mesh at a time
                    var mesh = loaded.meshes[0];

                    // We put all meshes (except skyboxes) in rendering group 1.
                    mesh.renderingGroupId = 1;

                    if(!_.isEmpty(meshName))
                    {
                        self.meshes[meshName] = mesh;
                    } // end if

                    return mesh;
                });
        } // end if
    }; // end loadMesh

    /**
     * Loads a scene by path.
     *
     * @param {string} scenePath - A path to the `.babylon` file for the scene. This is assumed to be relative to our
     * static content directory.
     *
     * @returns {Promise<undefined>} Returns a promise that resolves once the scene is loaded, and considers itself
     * 'ready'.
     */
    SceneManager.prototype.loadScene = function(scenePath)
    {
        var scenePromise;
        var self = this;

        if(!scenePath)
        {
            // Create an empty scene
            scenePromise = Promise.resolve(new babylon.Scene(this.engine));
        }
        else
        {
            scenePromise = this.loader.loadScene(scenePath);
        } // end if

        return scenePromise.then(function(scene)
        {
            // Set our current scene
            self.currentScene = scene;

            // Let anyone who cares know we've changed scenes
            $rootScope.$broadcast('scene loaded');

            // We always create a camera for the player's perspective.
            self.playerCamera = new babylon.ArcRotateCamera("PlayerCamera", 0, 0, 100, babylon.Vector3.Zero(),
                self.currentScene);

            return new Promise(function(resolve)
            {
                // Resolve once the scene's ready
                self.currentScene.executeWhenReady(function()
                {
                    resolve();
                });
            });
        });
    }; // end loadScene

    /**
     * Starts the render loop. Broadcasts `"engine started"` on the root scope.
     */
    SceneManager.prototype.startEngine = function()
    {
        $rootScope.$broadcast("engine started");
        this.engine.runRenderLoop(this._renderLoop.bind(this));
    }; // end startEngine

    /**
     * Stops the render loop. Broadcasts `"engine stopped"` on the root scope.
     */
    SceneManager.prototype.stopEngine = function()
    {
        $rootScope.$broadcast("engine stopped");
        this.engine.stopRenderLoop();
    }; // end stopEngine

    // -----------------------------------------------------------------------------------------------------------------
    // Private
    // -----------------------------------------------------------------------------------------------------------------

    /**
     * The render loop. Fires events `before render` and `after render`.
     *
     * @private
     */
    SceneManager.prototype._renderLoop = function()
    {
        this.emit('before render');
        this.currentScene.render();
        this.emit('after render');
    }; // end _renderLoop

    // -----------------------------------------------------------------------------------------------------------------

    return new SceneManager();
} // end SceneManagerFactory

// ---------------------------------------------------------------------------------------------------------------------

angular.module('rfi-client.services').service('SceneManager', [
    '$rootScope',
    'Loader',
    'babylon',
    SceneManagerFactory
]);

// ---------------------------------------------------------------------------------------------------------------------<|endoftext|>


<commit_before>import axios from 'axios';

const API_STEM = '/api/v1';

let api = {
    fetchAllPolls: () => {
        let URL = `${API_STEM}/polls`;
        return axios.get(URL)
            .then((response) => response.data)
            .catch(function(err){
                console.warn("Error in fetchAllPolls", err);
            })
    }
};

export default api;<commit_msg>added single poll api method<commit_after>import axios from 'axios';

const API_STEM = '/api/v1';

let api = {

    fetchAllPolls: () => {
        let URL = `${API_STEM}/polls`;
        return axios.get(URL)
            .then((response) => response.data)
            .catch((error) => {
                console.warn("Error in fetchAllPolls", error);
            });
    },

    fetchSinglePoll: (id) => {
        let URL = `${API_STEM}/polls/${id}`;
        return axios.get(URL)
            .then((response) => response.data)
            .catch((error) => {
                if (error.response.status === 404) {
                    return error.response.status;
                }
                else{
                    console.warn("Error in fetchAllPolls", error);
                }
            });
    }
};

export default api;<|endoftext|>