<commit_before>var AudioNetworkDevice = (function () {
    'use strict';

    _AudioNetworkDevice.$inject = [];

    function _AudioNetworkDevice() {
        var
            analyser,
            analyserChart,
            channelTransmitManager,
            channelReceiveManager,
            mapping = {
                baseFrequency1000: {
                    index: 0,
                    constellationDiagram: [],
                    queue: []
                },
                baseFrequency3000: {
                    index: 1,
                    constellationDiagram: [],
                    queue: []
                },
                baseFrequency5000: {
                    index: 2,
                    constellationDiagram: [],
                    queue: []
                }
            }
        ;

        function notifyHandler(baseFrequency, carrierData) {
            var state, i, cd, spaces, _, q, powerNormalized;

            _ = mapping['baseFrequency' + baseFrequency];

            spaces = "        ";
            state = (spaces + baseFrequency).slice(-6) + 'Hz | ';
            for (i = 0; i < carrierData.length; i++) {
                q = _.queue[i];

                cd = carrierData[i];
                if (cd.powerDecibel === -Infinity) {
                    cd.powerDecibel = -999;
                }
                if (q) {
                    powerNormalized = (cd.powerDecibel + 20) / 20;
                    powerNormalized = powerNormalized < 0 ? 0 : powerNormalized;
                    if (q.isFull()) {
                        q.pop();
                        q.pop();
                    }
                    q.push(powerNormalized * Math.cos(2 * Math.PI * cd.phase));
                    q.push(powerNormalized * Math.sin(2 * Math.PI * cd.phase));
                }
                state += (
                    (spaces + Math.round(cd.powerDecibel)).slice(-4) + 'dB ' +
                    (spaces + Math.round(cd.phase * 360)).slice(-3) + 'deg ' +
                    ' | '
                );
            }

            document.getElementById('receive-' + _.index).innerHTML = state;
        }

        function configureNodes() {
            var
                queue,
                dftSize = Audio.getSampleRate() * 0.05,
                notificationPerSecond = 25,
                notifyInterval = Audio.getSampleRate() * (1 / notificationPerSecond);

            channelTransmitManager = ChannelTransmitManagerBuilder.build([
                { baseFrequency: 1000, ofdmSize: 1, ofdmFrequencySpacing: 100 },
                { baseFrequency: 3000, ofdmSize: 1, ofdmFrequencySpacing: 100 }
            ]);
            channelReceiveManager = ChannelReceiveManagerBuilder.build([
                {
                    baseFrequency: 1000, ofdmSize: 1, ofdmFrequencySpacing: 100,
                    dftSize: dftSize, notifyInterval: notifyInterval, notifyHandler: notifyHandler
                },
                {
                    baseFrequency: 3000, ofdmSize: 1, ofdmFrequencySpacing: 100,
                    dftSize: dftSize, notifyInterval: notifyInterval, notifyHandler: notifyHandler
                }
            ]);

            queue = QueueBuilder.build(2 * 10);
            mapping.baseFrequency1000.queue.push(queue);
            mapping.baseFrequency1000.constellationDiagram.push(new ConstellationDiagram(document.getElementById('receive-0-cd-0'), queue, 200, 200));

            /*
            queue = QueueBuilder.build(2 * 10);
            mapping.baseFrequency1000.queue.push(queue);
            mapping.baseFrequency1000.constellationDiagram.push(new ConstellationDiagram(document.getElementById('receive-0-cd-1'), queue, 200, 200));
            */

            queue = QueueBuilder.build(2 * 10);
            mapping.baseFrequency3000.queue.push(queue);
            mapping.baseFrequency3000.constellationDiagram.push(new ConstellationDiagram(document.getElementById('receive-1-cd-0'), queue, 200, 200));

            analyser = Audio.createAnalyser();
            analyser.fftSize = 1 * 1024;
            // analyser.minDecibels = -80;
            // analyser.maxDecibels = -40;

            channelTransmitManager.getOutputNode().connect(Audio.destination);

            if (1) {
                Audio.getMicrofoneNode().connect(analyser);
                Audio.getMicrofoneNode().connect(channelReceiveManager.getInputNode());
            } else {
                channelTransmitManager.getOutputNode().connect(analyser);
                channelTransmitManager.getOutputNode().connect(channelReceiveManager.getInputNode());
            }

            document.getElementById('sampling-frequency').innerHTML = Audio.getSampleRate() + 'Hz';

            analyserChart = AnalyserChartBuilder.build(document.getElementById('test'), analyser);
        }

        function addQueueTest(channelIndex, offset) {
            var sd = Math.round(Audio.getSampleRate() * 1.500);

            switch (channelIndex) {
                case 0:
                    channelTransmitManager.getChannel(channelIndex).addToQueue([
                        [{ amplitude: +1.00, duration: sd, phase: +0.000 + offset }]//,
                        //[{ amplitude: +0.25, duration: sd, phase: +0.250 + offset }]
                    ]);
                    break;
                case 1:
                    channelTransmitManager.getChannel(channelIndex).addToQueue([
                        [{ amplitude: +1.00, duration: sd, phase: +0.000 + offset }]
                    ]);
                    break;
            }

        }

        function getChannelTransmit(channelIndex) {
            return channelTransmitManager.getChannel(channelIndex);
        }

        function getChannelReceive(channelIndex) {
            return channelReceiveManager.getChannel(channelIndex);
        }

        function init() {
            configureNodes();
        }

        init();

        return {
            getChannelTransmit: getChannelTransmit,
            getChannelReceive: getChannelReceive,
            addQueueTest: addQueueTest  // temporary test method
        };
    }

    return new _AudioNetworkDevice();        // TODO change it to dependency injection

})();
<commit_msg>increase dB range at constellation diagram<commit_after>var AudioNetworkDevice = (function () {
    'use strict';

    _AudioNetworkDevice.$inject = [];

    function _AudioNetworkDevice() {
        var
            analyser,
            analyserChart,
            channelTransmitManager,
            channelReceiveManager,
            mapping = {
                baseFrequency1000: {
                    index: 0,
                    constellationDiagram: [],
                    queue: []
                },
                baseFrequency3000: {
                    index: 1,
                    constellationDiagram: [],
                    queue: []
                },
                baseFrequency5000: {
                    index: 2,
                    constellationDiagram: [],
                    queue: []
                }
            }
        ;

        function notifyHandler(baseFrequency, carrierData) {
            var state, i, cd, spaces, _, q, powerNormalized;

            _ = mapping['baseFrequency' + baseFrequency];

            spaces = "        ";
            state = (spaces + baseFrequency).slice(-6) + 'Hz | ';
            for (i = 0; i < carrierData.length; i++) {
                q = _.queue[i];

                cd = carrierData[i];
                if (cd.powerDecibel === -Infinity) {
                    cd.powerDecibel = -999;
                }
                if (q) {
                    powerNormalized = (cd.powerDecibel + 40) / 40;
                    powerNormalized = powerNormalized < 0 ? 0 : powerNormalized;
                    if (q.isFull()) {
                        q.pop();
                        q.pop();
                    }
                    q.push(powerNormalized * Math.cos(2 * Math.PI * cd.phase));
                    q.push(powerNormalized * Math.sin(2 * Math.PI * cd.phase));
                }
                state += (
                    (spaces + Math.round(cd.powerDecibel)).slice(-4) + 'dB ' +
                    (spaces + Math.round(cd.phase * 360)).slice(-3) + 'deg ' +
                    ' | '
                );
            }

            document.getElementById('receive-' + _.index).innerHTML = state;
        }

        function configureNodes() {
            var
                queue,
                dftSize = Audio.getSampleRate() * 0.05,
                notificationPerSecond = 25,
                notifyInterval = Audio.getSampleRate() * (1 / notificationPerSecond);

            channelTransmitManager = ChannelTransmitManagerBuilder.build([
                { baseFrequency: 1000, ofdmSize: 1, ofdmFrequencySpacing: 100 },
                { baseFrequency: 3000, ofdmSize: 1, ofdmFrequencySpacing: 100 }
            ]);
            channelReceiveManager = ChannelReceiveManagerBuilder.build([
                {
                    baseFrequency: 1000, ofdmSize: 1, ofdmFrequencySpacing: 100,
                    dftSize: dftSize, notifyInterval: notifyInterval, notifyHandler: notifyHandler
                },
                {
                    baseFrequency: 3000, ofdmSize: 1, ofdmFrequencySpacing: 100,
                    dftSize: dftSize, notifyInterval: notifyInterval, notifyHandler: notifyHandler
                }
            ]);

            queue = QueueBuilder.build(2 * 10);
            mapping.baseFrequency1000.queue.push(queue);
            mapping.baseFrequency1000.constellationDiagram.push(new ConstellationDiagram(document.getElementById('receive-0-cd-0'), queue, 200, 200));

            /*
            queue = QueueBuilder.build(2 * 10);
            mapping.baseFrequency1000.queue.push(queue);
            mapping.baseFrequency1000.constellationDiagram.push(new ConstellationDiagram(document.getElementById('receive-0-cd-1'), queue, 200, 200));
            */

            queue = QueueBuilder.build(2 * 10);
            mapping.baseFrequency3000.queue.push(queue);
            mapping.baseFrequency3000.constellationDiagram.push(new ConstellationDiagram(document.getElementById('receive-1-cd-0'), queue, 200, 200));

            analyser = Audio.createAnalyser();
            analyser.fftSize = 1 * 1024;
            // analyser.minDecibels = -80;
            // analyser.maxDecibels = -40;

            channelTransmitManager.getOutputNode().connect(Audio.destination);

            if (1) {
                Audio.getMicrofoneNode().connect(analyser);
                Audio.getMicrofoneNode().connect(channelReceiveManager.getInputNode());
            } else {
                channelTransmitManager.getOutputNode().connect(analyser);
                channelTransmitManager.getOutputNode().connect(channelReceiveManager.getInputNode());
            }

            document.getElementById('sampling-frequency').innerHTML = Audio.getSampleRate() + 'Hz';

            analyserChart = AnalyserChartBuilder.build(document.getElementById('test'), analyser);
        }

        function addQueueTest(channelIndex, offset) {
            var sd = Math.round(Audio.getSampleRate() * 1.500);

            switch (channelIndex) {
                case 0:
                    channelTransmitManager.getChannel(channelIndex).addToQueue([
                        [{ amplitude: +1.00, duration: sd, phase: +0.000 + offset }]//,
                        //[{ amplitude: +0.25, duration: sd, phase: +0.250 + offset }]
                    ]);
                    break;
                case 1:
                    channelTransmitManager.getChannel(channelIndex).addToQueue([
                        [{ amplitude: +1.00, duration: sd, phase: +0.000 + offset }]
                    ]);
                    break;
            }

        }

        function getChannelTransmit(channelIndex) {
            return channelTransmitManager.getChannel(channelIndex);
        }

        function getChannelReceive(channelIndex) {
            return channelReceiveManager.getChannel(channelIndex);
        }

        function init() {
            configureNodes();
        }

        init();

        return {
            getChannelTransmit: getChannelTransmit,
            getChannelReceive: getChannelReceive,
            addQueueTest: addQueueTest  // temporary test method
        };
    }

    return new _AudioNetworkDevice();        // TODO change it to dependency injection

})();
<|endoftext|>


<commit_before>/**
 * @see https://developers.google.com/youtube/js_api_reference
 */
function onYouTubePlayerReady(player){
    var YT_PLAYERSTATE_CUED = 5;
    var setHighestQuality = function(player) {
        // We need to be little bit stubborn about setting playback quality, because:
        // a) half the time between onYouTubePlayerReady call and actual playback
        // the quality can't be changed. And there is no event that would guarantee
        // it to be ready before playback starts. Setting quality during playback
        // won't prevent player to buffer low quality video at the beginning.
        // b) video ads block the settings too.
        // c) cued video may begin with video ad (see b).
        var intervalId = window.setInterval(function() {
            var highestQuality = player.getAvailableQualityLevels()[0] || "highres";
            player.setPlaybackQuality(highestQuality);
            if (player.getPlaybackQuality() === highestQuality) {
                window.clearInterval(intervalId);
            }
        }, 100);
    };

    // The onYouTubePlayerReady() is called twice. During first call the 'player'
    // parameter equals to player ID string. On the second call it equals to
    // the player object. Make sure we respond to the second call only.
    if (player && typeof player === "object") {
        setHighestQuality(player);
        player.addEventListener("onStateChange", function(event) {
            if (event === YT_PLAYERSTATE_CUED) {
                // Player has changed the video (without page reload).
                setHighestQuality(player);
            }
        });
    }
}
<commit_msg>Minor: listen to "unstarted" event instead of "cue" event<commit_after>/**
 * @see https://developers.google.com/youtube/js_api_reference
 */
function onYouTubePlayerReady(player){
    var YT_PLAYERSTATE_UNSTARTED = -1;
    var setHighestQuality = function(player) {
        // We need to be little bit stubborn about setting playback quality, because:
        // a) half the time between onYouTubePlayerReady call and actual playback
        // the quality can't be changed. And there is no event that would guarantee
        // it to be ready before playback starts. Setting quality during playback
        // won't prevent player to buffer low quality video at the beginning.
        // b) video ads block the settings too.
        // c) changing video may result in video ad (see b).
        var intervalId = window.setInterval(function() {
            var highestQuality = player.getAvailableQualityLevels()[0] || "highres";
            player.setPlaybackQuality(highestQuality);
            if (player.getPlaybackQuality() === highestQuality) {
                window.clearInterval(intervalId);
            }
        }, 100);
    };

    // The onYouTubePlayerReady() is called twice. During first call the 'player'
    // parameter equals to player ID string. On the second call it equals to
    // the player object. Make sure we respond to the second call only.
    if (player && typeof player === "object") {
        setHighestQuality(player);
        player.addEventListener("onStateChange", function(event) {
            if (event === YT_PLAYERSTATE_UNSTARTED) {
                // Player has changed the video (without page reload).
                setHighestQuality(player);
            }
        });
    }
}
<|endoftext|>


<commit_before>// emulate Object.defineProperty
if (!Object.defineProperty && document.__defineGetter__) {
    Object.defineProperty = function(obj, prop, desc) {
	if (desc.get)
	    obj.__defineGetter__(prop, desc.get);
	if (desc.set)
	    obj.__defineSetter__(prop, desc.set);
    };
}

// emulate Element.textContent
if (typeof document.documentElement.textContent == 'undefined') {
    Object.defineProperty(Element.prototype, 'textContent',
	{
	    get: function() {
		return this.innerText;
	    },
	    set: function(val) {
		this.innerText = val;
	    }
	});
}

// utility functions

function splitTokens(s) {
    if (s && /\S/.test(s)) return s.split(/\s+/);
    return [];
}

function inList(item, list) {
    for (var i = 0; i < list.length; i++) {
	if (item == list[i])
	    return true;
    }
    return false;
}

// http://ejohn.org/blog/comparing-document-position/
function contains(a, b){
    return a.contains ?
	a != b && a.contains(b) :
	!!(a.compareDocumentPosition(b) & 16);
}

function fakeCollection(rootElem, incFilter, recFilter) {
    var elems = [];
    elems.item = function(idx){return this[idx];};

    function update(_incFilter, _recFilter) {
	while (elems.length)
	    elems.pop();
	function pushElements(elem) {
	    if (_incFilter(elem))
		elems.push(elem);
	    if (!_recFilter || _recFilter(elem)) {
		for (var child = elem.firstChild; child; child = child.nextSibling) {
		    if (child.nodeType == 1) {
			pushElements(child);
		    }
		}
	    }
	}
	pushElements(rootElem);
    }

    function updateSimple() {
	update(incFilter, recFilter);
    }

    function afterUpdate() {
	if (typeof elems.__onchange__ == 'function') {
	    elems.__onchange__();
	}
    }

    function updateHandler() {
	updateSimple();
	afterUpdate();
    }

    // keep collection up to date if possible
    if (rootElem.addEventListener) {
	rootElem.addEventListener('DOMAttrModified', updateHandler, false);
	rootElem.addEventListener('DOMNodeInserted', updateHandler, false);
	rootElem.addEventListener('DOMNodeRemoved',
	    function(ev) {
		update(function(e){return e != ev.target && incFilter(e);},
		       function(e){return e != ev.target;});
		afterUpdate();
	    }, false);
    }

    updateSimple();

    return elems;
}

function map(list, func) {
    var ret = [];
    for (var i = 0; i < list.length; i++) {
	ret.push(func(list[i]));
    }
    return ret;
}

function filter(list, pred) {
    var ret = [];
    for (var i = 0; i < list.length; i++) {
	if (pred(list[i]))
	    ret.push(list[i]);
    }
    return ret;
}

// Element attribute<->property reflection

function reflectBoolean(attr, prop) {
    Object.defineProperty(Element.prototype, prop,
	{ get: function () { return this.hasAttribute(attr); },
	  set: function (val) { if (val) this.setAttribute(attr, attr);
				else this.removeAttribute(attr); } });
}

function reflectString(attr, prop) {
    Object.defineProperty(Element.prototype, prop,
	{ get: function () { return this.getAttribute(attr) || ""; },
	  set: function (val) { this.setAttribute(attr, val); }});
}

reflectBoolean('itemscope', 'itemScope');
reflectString('itemtype', 'itemType');
reflectString('itemid', 'itemId');
reflectString('itemprop', 'itemProp');
reflectString('itemref', 'itemRef');
// FIXME: only if not browser-implemented
reflectString('datetime', 'dateTime');

function getItemValueProperty(e) {
    var tag = e.tagName.toUpperCase();
    if (tag == 'META')
	return 'content';
    if (tag == 'AUDIO' || tag == 'EMBED' ||
	tag == 'IFRAME' || tag == 'IMG' ||
	tag == 'SOURCE' || tag == 'VIDEO')
	return 'src';
    if (tag == 'A' || tag == 'AREA' || tag == 'LINK')
	return 'href';
    if (tag == 'OBJECT')
	return 'data';
    if (tag == 'TIME' && e.hasAttribute('datetime'))
	return 'dateTime';
    return 'textContent';
}

Object.defineProperty(Element.prototype, 'itemValue',
{
    get: function() {
	if (!this.hasAttribute('itemprop'))
	    return null;
	if (this.hasAttribute('itemscope'))
	    return this;
	return this[getItemValueProperty(this)];
    },
    set: function(val) {
	if (!this.hasAttribute('itemprop') || this.hasAttribute('itemscope'))
	    throw new Error('INVALID_ACCESS_ERR');
	this[getItemValueProperty(this)] = val;
    }
});

// Element.properties

Object.defineProperty(Element.prototype, 'properties', { get:
function() {
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#the-properties-of-an-item
    var itemElem = this;

    var props = [];
    function updateProperties(elemFilter) {
	var root = itemElem;

	props.length = 0;

	// when the root isn't a item in the document, match nothing
	// FIXME: the spec doesn't actually say this.
	if (!root.itemScope || !contains(document.documentElement, root))
	    return;

	var pending = [];
	function pushChildren(e) {
	    for (var child = e.lastChild; child; child = child.previousSibling) {
		if (child.nodeType == 1 && elemFilter(child)) {
		    pending.push(child);
		}
	    }
	}
	pushChildren(root);

	function getScopeNode(e) {
	    var scope = e.parentNode;
	    while (scope && !scope.itemScope)
		scope = scope.parentNode;
	    return scope;
	}
	var refIds = splitTokens(root.itemRef);
	idloop: for (var i=0; i<refIds.length; i++) {
	    var candidate = document.getElementById(refIds[i]);
	    if (!candidate || !elemFilter(candidate))
		continue;
	    var scope = getScopeNode(candidate);
	    for (var j=0; j<pending.length; j++) {
		if (candidate == pending[j])
		    continue idloop;
		if (contains(pending[j], candidate) &&
		    (pending[j] == scope ||
		     getScopeNode(pending[j]) == scope))
		    continue idloop;
	    }
	    pending.push(candidate);
	}

	// from http://www.quirksmode.org/dom/getElementsByTagNames.html
	pending.sort(function (a,b){return (a.compareDocumentPosition(b)&6)-3;});

	while (pending.length) {
	    var current = pending.pop();
	    if (current.hasAttribute('itemprop'))
		props.push(current);
	    if (!current.hasAttribute('itemscope'))
		pushChildren(current);
	}
    }

    props.names = [];
    function updateNames() {
	while (props.names.length)
	    props.names.pop();
	for (var i = 0; i < props.length; i++) {
	    var propNames = splitTokens(props[i].getAttribute('itemprop'));
	    for (var j = 0; j < propNames.length; j++) {
		if (!inList(propNames[j], props.names))
		    props.names.push(propNames[j]);
	    }
	}
    }

    function updatePropertyNodeList(pnl, name) {
	while (pnl.length)
	    pnl.pop();
	while (pnl.values.length)
	    pnl.values.pop();
	for (var i=0; i<props.length; i++) {
	    if (inList(name, splitTokens(props[i].getAttribute('itemprop')))) {
		pnl.push(props[i]);
		pnl.values.push(props[i].itemValue);
	    }
	}
    }

    props.item = function(idx){return this[idx];};

    var pnlCache = {};
    props.namedItem = function (name) {
	if (!pnlCache[name]) {
	    // fake PropertyNodeList
	    var pnl = [];
	    pnl.item = function(idx){return this[idx];};
	    pnl.values = [];
	    updatePropertyNodeList(pnl, name);
	    pnlCache[name] = pnl;
	}
	return pnlCache[name];
    };

    function updateHandler(elemFilter) {
	updateProperties(function(e){return typeof elemFilter != 'function' || elemFilter(e);});
	updateNames();
	for (name in pnlCache)
	    updatePropertyNodeList(pnlCache[name], name);
    }

    // keep collection up to date if possible
    if (document.documentElement.addEventListener) {
	document.documentElement.addEventListener('DOMAttrModified', updateHandler, false);
	document.documentElement.addEventListener('DOMNodeInserted', updateHandler, false);
	document.documentElement.addEventListener('DOMNodeRemoved',
	    function(ev) {
		updateHandler(function(e){return (e != ev.target) && !contains(ev.target, e);});
	    }, false);
    }

    updateHandler();
    return props;
}});

// document.getItems

document.getItems = function(typeNames) {
    var types = splitTokens(typeNames);

    function isTopLevelItem(e) {
	return e.hasAttribute('itemscope') &&
	    !e.hasAttribute('itemprop') &&
	    (types.length == 0 ||
	     inList(e.getAttribute('itemtype'), types));
    }

    return fakeCollection(this.documentElement, isTopLevelItem);
};
<commit_msg>minor code cleanup<commit_after>// emulate Object.defineProperty
if (!Object.defineProperty && document.__defineGetter__) {
    Object.defineProperty = function(obj, prop, desc) {
	if (desc.get)
	    obj.__defineGetter__(prop, desc.get);
	if (desc.set)
	    obj.__defineSetter__(prop, desc.set);
    };
}

// emulate Element.textContent
if (typeof document.documentElement.textContent == 'undefined') {
    Object.defineProperty(Element.prototype, 'textContent',
	{
	    get: function() {
		return this.innerText;
	    },
	    set: function(val) {
		this.innerText = val;
	    }
	});
}

// utility functions

function splitTokens(s) {
    if (s && /\S/.test(s))
	return s.replace(/^\s+|\s+$/g,'').split(/\s+/);
    return [];
}

function inList(item, list) {
    for (var i = 0; i < list.length; i++) {
	if (item == list[i])
	    return true;
    }
    return false;
}

// http://ejohn.org/blog/comparing-document-position/
function contains(a, b){
    return a.contains ?
	a != b && a.contains(b) :
	!!(a.compareDocumentPosition(b) & 16);
}

function fakeCollection(rootElem, incFilter, recFilter) {
    var elems = [];
    elems.item = function(idx){return this[idx];};

    function update(_incFilter, _recFilter) {
	elems.length = 0;
	function pushElements(elem) {
	    if (_incFilter(elem))
		elems.push(elem);
	    if (!_recFilter || _recFilter(elem)) {
		for (var child = elem.firstChild; child; child = child.nextSibling) {
		    if (child.nodeType == 1) {
			pushElements(child);
		    }
		}
	    }
	}
	pushElements(rootElem);
    }

    function updateSimple() {
	update(incFilter, recFilter);
    }

    function afterUpdate() {
	if (typeof elems.__onchange__ == 'function') {
	    elems.__onchange__();
	}
    }

    function updateHandler() {
	updateSimple();
	afterUpdate();
    }

    // keep collection up to date if possible
    if (rootElem.addEventListener) {
	rootElem.addEventListener('DOMAttrModified', updateHandler, false);
	rootElem.addEventListener('DOMNodeInserted', updateHandler, false);
	rootElem.addEventListener('DOMNodeRemoved',
	    function(ev) {
		update(function(e){return e != ev.target && incFilter(e);},
		       function(e){return e != ev.target;});
		afterUpdate();
	    }, false);
    }

    updateSimple();

    return elems;
}

function map(list, func) {
    var ret = [];
    for (var i = 0; i < list.length; i++) {
	ret.push(func(list[i]));
    }
    return ret;
}

function filter(list, pred) {
    var ret = [];
    for (var i = 0; i < list.length; i++) {
	if (pred(list[i]))
	    ret.push(list[i]);
    }
    return ret;
}

// Element attribute<->property reflection

function reflectBoolean(attr, prop) {
    Object.defineProperty(Element.prototype, prop,
	{ get: function () { return this.hasAttribute(attr); },
	  set: function (val) { if (val) this.setAttribute(attr, attr);
				else this.removeAttribute(attr); } });
}

function reflectString(attr, prop) {
    Object.defineProperty(Element.prototype, prop,
	{ get: function () { return this.getAttribute(attr) || ""; },
	  set: function (val) { this.setAttribute(attr, val); }});
}

reflectBoolean('itemscope', 'itemScope');
// FIXME: should be URL?
reflectString('itemtype', 'itemType');
// FIXME: should be URL?
reflectString('itemid', 'itemId');
reflectString('itemprop', 'itemProp');
reflectString('itemref', 'itemRef');
// FIXME: only if not browser-implemented
reflectString('datetime', 'dateTime');

function getItemValueProperty(e) {
    var tag = e.tagName.toUpperCase();
    if (tag == 'META')
	return 'content';
    if (tag == 'AUDIO' || tag == 'EMBED' ||
	tag == 'IFRAME' || tag == 'IMG' ||
	tag == 'SOURCE' || tag == 'VIDEO')
	return 'src';
    if (tag == 'A' || tag == 'AREA' || tag == 'LINK')
	return 'href';
    if (tag == 'OBJECT')
	return 'data';
    if (tag == 'TIME' && e.hasAttribute('datetime'))
	return 'dateTime';
    return 'textContent';
}

Object.defineProperty(Element.prototype, 'itemValue',
{
    get: function() {
	if (!this.hasAttribute('itemprop'))
	    return null;
	if (this.hasAttribute('itemscope'))
	    return this;
	return this[getItemValueProperty(this)];
    },
    set: function(val) {
	if (!this.hasAttribute('itemprop') || this.hasAttribute('itemscope'))
	    throw new Error('INVALID_ACCESS_ERR');
	this[getItemValueProperty(this)] = val;
    }
});

// Element.properties

Object.defineProperty(Element.prototype, 'properties', { get:
function() {
    // http://www.whatwg.org/specs/web-apps/current-work/multipage/microdata.html#the-properties-of-an-item
    var itemElem = this;

    var props = [];
    function updateProperties(elemFilter) {
	var root = itemElem;

	props.length = 0;

	// when the root isn't a item in the document, match nothing
	// FIXME: the spec doesn't actually say this.
	if (!root.itemScope || !contains(document.documentElement, root))
	    return;

	var pending = [];
	function pushChildren(e) {
	    for (var child = e.lastChild; child; child = child.previousSibling) {
		if (child.nodeType == 1 && elemFilter(child)) {
		    pending.push(child);
		}
	    }
	}
	pushChildren(root);

	function getScopeNode(e) {
	    var scope = e.parentNode;
	    while (scope && !scope.itemScope)
		scope = scope.parentNode;
	    return scope;
	}
	var refIds = splitTokens(root.itemRef);
	idloop: for (var i=0; i<refIds.length; i++) {
	    var candidate = document.getElementById(refIds[i]);
	    if (!candidate || !elemFilter(candidate))
		continue;
	    var scope = getScopeNode(candidate);
	    for (var j=0; j<pending.length; j++) {
		if (candidate == pending[j])
		    continue idloop;
		if (contains(pending[j], candidate) &&
		    (pending[j] == scope ||
		     getScopeNode(pending[j]) == scope))
		    continue idloop;
	    }
	    pending.push(candidate);
	}

	// from http://www.quirksmode.org/dom/getElementsByTagNames.html
	pending.sort(function (a,b){return (a.compareDocumentPosition(b)&6)-3;});

	while (pending.length) {
	    var current = pending.pop();
	    if (current.hasAttribute('itemprop'))
		props.push(current);
	    if (!current.hasAttribute('itemscope'))
		pushChildren(current);
	}
    }

    props.names = [];
    function updateNames() {
	props.names.length = 0;
	for (var i = 0; i < props.length; i++) {
	    var propNames = splitTokens(props[i].getAttribute('itemprop'));
	    for (var j = 0; j < propNames.length; j++) {
		if (!inList(propNames[j], props.names))
		    props.names.push(propNames[j]);
	    }
	}
    }

    function updatePropertyNodeList(pnl, name) {
	pnl.length = 0;
	pnl.values.length = 0;
	for (var i=0; i<props.length; i++) {
	    if (inList(name, splitTokens(props[i].getAttribute('itemprop')))) {
		pnl.push(props[i]);
		pnl.values.push(props[i].itemValue);
	    }
	}
    }

    props.item = function(idx){return this[idx];};

    var pnlCache = {};
    props.namedItem = function (name) {
	if (!pnlCache[name]) {
	    // fake PropertyNodeList
	    var pnl = [];
	    pnl.item = function(idx){return this[idx];};
	    pnl.values = [];
	    updatePropertyNodeList(pnl, name);
	    pnlCache[name] = pnl;
	}
	return pnlCache[name];
    };

    function updateHandler(elemFilter) {
	updateProperties(function(e){return typeof elemFilter != 'function' || elemFilter(e);});
	updateNames();
	for (name in pnlCache)
	    updatePropertyNodeList(pnlCache[name], name);
    }

    // keep collection up to date if possible
    if (document.documentElement.addEventListener) {
	document.documentElement.addEventListener('DOMAttrModified', updateHandler, false);
	document.documentElement.addEventListener('DOMNodeInserted', updateHandler, false);
	document.documentElement.addEventListener('DOMNodeRemoved',
	    function(ev) {
		updateHandler(function(e){return (e != ev.target) && !contains(ev.target, e);});
	    }, false);
    }

    updateHandler();
    return props;
}});

// document.getItems

document.getItems = function(typeNames) {
    var types = splitTokens(typeNames);

    function isTopLevelItem(e) {
	return e.hasAttribute('itemscope') &&
	    !e.hasAttribute('itemprop') &&
	    (types.length == 0 ||
	     inList(e.getAttribute('itemtype'), types));
    }

    return fakeCollection(this.documentElement, isTopLevelItem);
};
<|endoftext|>


<commit_before>export { inputTensorPlaceholder_creator };

import * as ActivationEscaping from "../ActivationEscaping.js";
import * as TensorPlaceholder from "../TensorPlaceholder.js";

/**
 * A helper for preparing input TensorPlaceholder of Block.Base (especially for ShuffleNetV2_ByMopbileNetV1's head/body/tail).
 *
 *
 */
class inputTensorPlaceholder_creator {

  /**
   *
   * @param {ActivationEscaping.ScaleBoundsArray|TensorPlaceholder.Base} input_ScaleBoundsArray_or_TensorPlaceholder
   *   The input's information.
   *     - If it is an ActivationEscaping.ScaleBoundsArray object, a new TensorPlaceholder will be created and returned.
   *     - If it is a TensorPlaceholder.Base object, it will be returned (not cloned) directly.
   *
   * @return {TensorPlaceholder.Base}
   *   Return either a newly created TensorPlaceholder or input_ScaleBoundsArray_or_TensorPlaceholder directly.
   */
  static create_or_check_TensorPlaceholder_by(
    input_height, input_width, input_channelCount,
    input_channelCount_lowerHalf, input_channelCount_higherHalf,
    input_ScaleBoundsArray_or_TensorPlaceholder
  ) {

    // 1.
    if ( input_ScaleBoundsArray_or_TensorPlaceholder instanceof ActivationEscaping.ScaleBoundsArray ) {
      let inputScaleBoundsArray = input_ScaleBoundsArray_or_TensorPlaceholder;

      if ( inputScaleBoundsArray.length != input_channelCount )
        throw Error( `Block.inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(): `
          + `inputScaleBoundsArray's length ( ${inputScaleBoundsArray.length} ) should be the same as `
          + `input's channel count ( ${input_channelCount} ).`
        );

      let inputTensorPlaceholder = TensorPlaceholder.Base.Pool.get_or_create_by();
      inputTensorPlaceholder.set_height_width_channelCount_scaleBoundsArray(
        input_height, input_width,
        input_channelCount, input_channelCount_lowerHalf, input_channelCount_higherHalf,
        inputScaleBoundsArray );

      return inputTensorPlaceholder;

    // 2.
    } else if ( input_ScaleBoundsArray_or_TensorPlaceholder instanceof TensorPlaceholder.Base ) {

      let inputTensorPlaceholder = input_ScaleBoundsArray_or_TensorPlaceholder;
      let inputScaleBoundsArray = inputTensorPlaceholder.scaleBoundsArray;

      if (   ( inputTensorPlaceholder.height != input_height )
          && ( inputTensorPlaceholder.width != input_width )
          && ( inputTensorPlaceholder.channelCount != input_channelCount )
          && ( inputTensorPlaceholder.channelCount_lowerHalf != input_channelCount_lowerHalf )
          && ( inputTensorPlaceholder.channelCount_higherHalf != input_channelCount_higherHalf )
         )
        throw Error( `Block.inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(): `
          + `inputTensorPlaceholder's ( height, width, channelCount, channelCount_lowerHalf, channelCount_higherHalf ) = `
          + `( ${inputTensorPlaceholder.height}, ${inputTensorPlaceholder.width}, ${inputTensorPlaceholder.channelCount}, `
            + `${inputTensorPlaceholder.channelCount_lowerHalf}, ${inputTensorPlaceholder.channelCount_higherHalf} ) `
          + `should be `
          + `( ${input_height}, ${input_width}, ${input_channelCount}, ${input_channelCount_lowerHalf}, ${input_channelCount_higherHalf} ).`
        );

      if ( inputScaleBoundsArray.length != input_channelCount )
        throw Error( `Block.inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(): `
          + `inputScaleBoundsArray's length ( ${inputScaleBoundsArray.length} ) should be the same as `
          + `input's channel count ( ${input_channelCount} ).`
        );

      return inputTensorPlaceholder;

    // 3.
    } else {
      throw Error( `Block.inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(): `
        + `input_ScaleBoundsArray_or_TensorPlaceholder shoulde be an instance of either `
        + `ActivationEscaping.ScaleBoundsArray or TensorPlaceholder.Base.`
      );
    }
  }

  /**
   * Determine the following properties:
   *   - this.input0
   *   - this.input0_bOwned
   *   - this.input1
   *   - this.input1_bOwned
   *
   * @param {ActivationEscaping.ScaleBoundsArray|TensorPlaceholder.Base} input0_ScaleBoundsArray_or_TensorPlaceholder
   *   The input0's information.
   *
   *     - If it is an ActivationEscaping.ScaleBoundsArray object, a new TensorPlaceholder will be created.
   *         .input0_bOwned will be true (which means caller is responsible for releasing it).
   *
   *     - If it is a TensorPlaceholder.Base object, it will be used (not cloned) as input0's TensorPlaceholder directly.
   *         .input0_bOwned will be false.
   *
   * @param {ActivationEscaping.ScaleBoundsArray|TensorPlaceholder.Base} input1_ScaleBoundsArray_or_TensorPlaceholder
   *   The input1's information.
   *
   *     - If it is an ActivationEscaping.ScaleBoundsArray object, a new TensorPlaceholder will be created.
   *         .input1_bOwned will be true (which means caller is responsible for releasing it).
   *
   *     - If it is a TensorPlaceholder.Base object, it will be used (not cloned) as input1's TensorPlaceholder directly.
   *         .input1_bOwned will be false.
   *
   */
  static set_input0_input1_TensorPlaceholder_by(
    inputTensorCount,
    input0_height, input0_width, input0_channelCount, input0_ScaleBoundsArray_or_TensorPlaceholder,
    input1_height, input1_width, input1_channelCount, input1_ScaleBoundsArray_or_TensorPlaceholder,
    pointwise1_inputChannelCount_lowerHalf, pointwise1_inputChannelCount_higherHalf
  ) {

    // 1. input0
    this.input0 = inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(
      input0_height, input0_width, input0_channelCount,
      pointwise1_inputChannelCount_lowerHalf, pointwise1_inputChannelCount_higherHalf,
      input0_ScaleBoundsArray_or_TensorPlaceholder
    );

    if ( this.input0 == input0_ScaleBoundsArray_or_TensorPlaceholder )
      this.input0_bOwned = false;
    else
      this.input0_bOwned = true; // Because it is created here.

    // 2. input1
    //
    // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BODY (3) )
    // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_TAIL (4) )
    // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_POINTWISE21_BODY (10) )
    // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_POINTWISE21_TAIL (11) )
    //
    if ( inputTensorCount > 1 ) {

      this.input1 = inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(
        input1_height, input1_width, input1_channelCount,
        undefined, undefined, // channelCount_lowerHalf, channelCount_higherHalf
        input1_ScaleBoundsArray_or_TensorPlaceholder
      );

      if ( this.input1 == input1_ScaleBoundsArray_or_TensorPlaceholder )
        this.input1_bOwned = false;
      else
        this.input1_bOwned = true; // Because it is created here.
    }
  }

}

<commit_msg>Update Block_inputTensorPlaceholder_creator.js<commit_after>export { inputTensorPlaceholder_creator };

import * as ActivationEscaping from "../ActivationEscaping.js";
import * as TensorPlaceholder from "../TensorPlaceholder.js";

/**
 * A helper for preparing input TensorPlaceholder of Block.Base (especially for ShuffleNetV2_ByMopbileNetV1's head/body/tail).
 *
 *
 */
class inputTensorPlaceholder_creator {

  /**
   *
   * @param {ActivationEscaping.ScaleBoundsArray|TensorPlaceholder.Base} input_ScaleBoundsArray_or_TensorPlaceholder
   *   The input's information.
   *     - If it is an ActivationEscaping.ScaleBoundsArray object, a new TensorPlaceholder will be created and returned.
   *     - If it is a TensorPlaceholder.Base object, it will be returned (not cloned) directly.
   *
   * @return {TensorPlaceholder.Base}
   *   Return either a newly created TensorPlaceholder or input_ScaleBoundsArray_or_TensorPlaceholder directly.
   */
  static create_or_check_TensorPlaceholder_by(
    input_height, input_width, input_channelCount,
    input_channelCount_lowerHalf, input_channelCount_higherHalf,
    input_ScaleBoundsArray_or_TensorPlaceholder
  ) {

    // 1.
    if ( input_ScaleBoundsArray_or_TensorPlaceholder instanceof ActivationEscaping.ScaleBoundsArray ) {
      let inputScaleBoundsArray = input_ScaleBoundsArray_or_TensorPlaceholder;

      if ( inputScaleBoundsArray.length != input_channelCount )
        throw Error( `Block.inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(): `
          + `inputScaleBoundsArray's length ( ${inputScaleBoundsArray.length} ) should be the same as `
          + `input's channel count ( ${input_channelCount} ).`
        );

      let inputTensorPlaceholder = TensorPlaceholder.Base.Pool.get_or_create_by();
      inputTensorPlaceholder.set_height_width_channelCount_scaleBoundsArray(
        input_height, input_width,
        input_channelCount, input_channelCount_lowerHalf, input_channelCount_higherHalf,
        inputScaleBoundsArray );

      return inputTensorPlaceholder;

    // 2.
    } else if ( input_ScaleBoundsArray_or_TensorPlaceholder instanceof TensorPlaceholder.Base ) {

      let inputTensorPlaceholder = input_ScaleBoundsArray_or_TensorPlaceholder;
      let inputScaleBoundsArray = inputTensorPlaceholder.scaleBoundsArray;

      if (   ( inputTensorPlaceholder.height != input_height )
          && ( inputTensorPlaceholder.width != input_width )
          && ( inputTensorPlaceholder.channelCount != input_channelCount )
          && ( inputTensorPlaceholder.channelCount_lowerHalf != input_channelCount_lowerHalf )
          && ( inputTensorPlaceholder.channelCount_higherHalf != input_channelCount_higherHalf )
         )
        throw Error( `Block.inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(): `
          + `inputTensorPlaceholder's ( height, width, channelCount, channelCount_lowerHalf, channelCount_higherHalf ) = `
          + `( ${inputTensorPlaceholder.height}, ${inputTensorPlaceholder.width}, ${inputTensorPlaceholder.channelCount}, `
            + `${inputTensorPlaceholder.channelCount_lowerHalf}, ${inputTensorPlaceholder.channelCount_higherHalf} ) `
          + `should be `
          + `( ${input_height}, ${input_width}, ${input_channelCount}, ${input_channelCount_lowerHalf}, ${input_channelCount_higherHalf} ).`
        );

      if ( inputScaleBoundsArray.length != input_channelCount )
        throw Error( `Block.inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(): `
          + `inputScaleBoundsArray's length ( ${inputScaleBoundsArray.length} ) should be the same as `
          + `input's channel count ( ${input_channelCount} ).`
        );

      return inputTensorPlaceholder;

    // 3.
    } else {
      throw Error( `Block.inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(): `
        + `input_ScaleBoundsArray_or_TensorPlaceholder shoulde be an instance of either `
        + `ActivationEscaping.ScaleBoundsArray or TensorPlaceholder.Base.`
      );
    }
  }

  /**
   * Determine the following properties:
   *   - this.input0
   *   - this.input0_bOwned
   *   - this.input1
   *   - this.input1_bOwned
   *
   * @param {ActivationEscaping.ScaleBoundsArray|TensorPlaceholder.Base} input0_ScaleBoundsArray_or_TensorPlaceholder
   *   The input0's information.
   *
   *     - If it is an ActivationEscaping.ScaleBoundsArray object, a new TensorPlaceholder will be created.
   *         .input0_bOwned will be true (which means caller is responsible for releasing it).
   *
   *     - If it is a TensorPlaceholder.Base object, it will be used (not cloned) as input0's TensorPlaceholder directly.
   *         .input0_bOwned will be false.
   *
   * @param {ActivationEscaping.ScaleBoundsArray|TensorPlaceholder.Base} input1_ScaleBoundsArray_or_TensorPlaceholder
   *   The input1's information.
   *
   *     - If it is an ActivationEscaping.ScaleBoundsArray object, a new TensorPlaceholder will be created.
   *         .input1_bOwned will be true (which means caller is responsible for releasing it).
   *
   *     - If it is a TensorPlaceholder.Base object, it will be used (not cloned) as input1's TensorPlaceholder directly.
   *         .input1_bOwned will be false.
   *
   */
  static set_input0_input1_TensorPlaceholder_by(
    inputTensorCount,
    input0_height, input0_width, input0_channelCount, input0_ScaleBoundsArray_or_TensorPlaceholder,
    input1_height, input1_width, input1_channelCount, input1_ScaleBoundsArray_or_TensorPlaceholder,
    pointwise1_inputChannelCount_lowerHalf, pointwise1_inputChannelCount_higherHalf
  ) {

    // 1. input0
    this.input0 = inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(
      input0_height, input0_width, input0_channelCount,
      pointwise1_inputChannelCount_lowerHalf, pointwise1_inputChannelCount_higherHalf,
      input0_ScaleBoundsArray_or_TensorPlaceholder
    );

    if ( this.input0 == input0_ScaleBoundsArray_or_TensorPlaceholder )
      this.input0_bOwned = false;
    else
      this.input0_bOwned = true; // Because it is created here.

    // 2. input1
    //
    // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BODY (3) )
    // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_TAIL (4) )
    // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_POINTWISE21_BODY (10) )
    // (i.e. ValueDesc.ConvBlockType.Singleton.Ids.SHUFFLE_NET_V2_BY_POINTWISE21_TAIL (11) )
    //
    if ( inputTensorCount > 1 ) {

      this.input1 = inputTensorPlaceholder_creator.create_or_check_TensorPlaceholder_by(
        input1_height, input1_width, input1_channelCount,
        undefined, undefined, // channelCount_lowerHalf, channelCount_higherHalf
        input1_ScaleBoundsArray_or_TensorPlaceholder
      );

      if ( this.input1 == input1_ScaleBoundsArray_or_TensorPlaceholder )
        this.input1_bOwned = false;
      else
        this.input1_bOwned = true; // Because it is created here.

    } else {
      if ( input1_ScaleBoundsArray_or_TensorPlaceholder != null )
        throw Error( `Block.inputTensorPlaceholder_creator.set_input0_input1_TensorPlaceholder_by(): `
          + `input1_ScaleBoundsArray_or_TensorPlaceholder ( ${input1_ScaleBoundsArray_or_TensorPlaceholder} ) should null `
          + `when ( inputTensorCount ( ${inputTensorCount} ) <= 1 ).`
        );
    }
  }

}

<|endoftext|>


<commit_before>/* NODE MODULES */
var eventerface = require('eventerface')
    EventEmitter = require('events').EventEmitter,
    zoneProperties = require('./properties'),
    zoneEvents = require('./events'),
    servers = require('../servers');

/** MODULE INTERFACE
 *@method {function} create -
 */
module.exports = {
    create: create
};

/*----------------------------------------------------------------------------*/

/** Creates a zone object
 * @param {object} properties - The properties of the zone to be created
 * @returns {object} zone - The created zone object
 */
function create(properties) {
    var zone = Object.create({}),
        globalNamespace = 'zone_' + properties.id,
        apiNamespace = eventerface.create(),
        apiEmitter = apiNamespace.emitter(),
        localNamespace = eventerface.create();

    // Create event emitters in the same namespace to communicate with the module user
    Object.defineProperties(zone, {
        moduleapi: { value: apiNamespace.emitter() },
        on:     { value: apiEmitter.on },
        emit:   { value: apiEmitter.emit }
    });

    // Configure the servers that will be used by the zone
    Object.defineProperties(zone, {
        servers: {
            value: servers.create.zoneServer(zone, globalNamespace)
        }
    });

    // Join the created zone namespace and define the properties of the zone object
    eventerface.find(globalNamespace, function (globalNamespace) {
        properties = zoneProperties.define(properties, globalNamespace, localNamespace);
        Object.defineProperties(zone, properties);
        zoneEvents.watchProperties(zone, localNamespace.emitter());
        zone.moduleapi.emit('ready');
    });

    return zone;
}
/*----------------------------------------------------------------------------*/<commit_msg>Passed the globalNamespace parameter to the zoneEvents module<commit_after>/* NODE MODULES */
var eventerface = require('eventerface')
    EventEmitter = require('events').EventEmitter,
    zoneProperties = require('./properties'),
    zoneEvents = require('./events'),
    servers = require('../servers');

/** MODULE INTERFACE
 *@method {function} create -
 */
module.exports = {
    create: create
};

/*----------------------------------------------------------------------------*/

/** Creates a zone object
 * @param {object} properties - The properties of the zone to be created
 * @returns {object} zone - The created zone object
 */
function create(properties) {
    var zone = Object.create({}),
        globalNamespace = 'zone_' + properties.id,
        apiNamespace = eventerface.create(),
        apiEmitter = apiNamespace.emitter(),
        localNamespace = eventerface.create();

    // Create event emitters in the same namespace to communicate with the module user
    Object.defineProperties(zone, {
        moduleapi: { value: apiNamespace.emitter() },
        on:     { value: apiEmitter.on },
        emit:   { value: apiEmitter.emit }
    });

    // Configure the servers that will be used by the zone
    Object.defineProperties(zone, {
        servers: {
            value: servers.create.zoneServer(zone, globalNamespace)
        }
    });

    // Join the created zone namespace and define the properties of the zone object
    eventerface.find(globalNamespace, function (globalNamespace) {
        properties = zoneProperties.define(properties, globalNamespace, localNamespace);
        Object.defineProperties(zone, properties);
        zoneEvents.watchProperties(zone, globalNamespace, localNamespace.emitter());
        zone.moduleapi.emit('ready');
    });

    return zone;
}
/*----------------------------------------------------------------------------*/<|endoftext|>


<commit_before>const DrawCard = require('../../../drawcard.js');

class RedCloaks extends DrawCard {
    constructor(owner, cardData) {
        super(owner, cardData);

        this.registerEvents(['onAttackersDeclared', 'onAfterTaxation']);

        this.menu.push({ text: 'Move 1 gold from your gold pool to this card', command: 'card', method: 'addGold' });

        this.tokens['gold'] = 0;
        this.usedThisRound = false;
    }

    addGold(player) {
        if(!this.inPlay || this.controller !== player || this.usedThisRound || player.gold <= 0) {
            return;
        }

        this.addToken('gold', 1);
        this.controller.gold--;

        this.game.addMessage('{0} moves 1 gold from their gold pool to {1}', this.controller, this);

        this.usedThisRound = true;
    }

    onAfterTaxation() {
        // XXX this should be per phase, will change this when the new phase stuff is done and have a phase change event
        this.usedThisRound = false;
    }

    onAttackersDeclared(e, challenge) {
        if(!this.inPlay || this.controller !== challenge.attackingPlayer || challenge.challengeType !== 'intrigue') {
            return;
        }

        this.strengthModifier += this.tokens['gold'];
    }

    onChallengeFinished(e, challenge) {
        if(challenge.challengeType === 'intrigue') {
            this.strengthModifier -= this.tokens['gold'];
        }
    }
}

RedCloaks.code = '02070';

module.exports = RedCloaks;
<commit_msg>fix red cloaks to be once per phase instead of once per round<commit_after>const DrawCard = require('../../../drawcard.js');

class RedCloaks extends DrawCard {
    constructor(owner, cardData) {
        super(owner, cardData);

        this.registerEvents(['onAttackersDeclared', 'onPhaseEnd']);

        this.menu.push({ text: 'Move 1 gold from your gold pool to this card', command: 'card', method: 'addGold' });

        this.tokens['gold'] = 0;
        this.usedThisPhase = false;
    }

    addGold(player) {
        if(!this.inPlay || this.controller !== player || this.usedThisPhase || player.gold <= 0) {
            return;
        }

        this.addToken('gold', 1);
        this.controller.gold--;

        this.game.addMessage('{0} moves 1 gold from their gold pool to {1}', this.controller, this);

        this.usedThisPhase = true;
    }

    onPhaseEnd() {
        this.usedThisPhase = false;
    }

    onAttackersDeclared(e, challenge) {
        if(!this.inPlay || this.controller !== challenge.attackingPlayer || challenge.challengeType !== 'intrigue') {
            return;
        }

        this.strengthModifier += this.tokens['gold'];
    }

    onChallengeFinished(e, challenge) {
        if(challenge.challengeType === 'intrigue') {
            this.strengthModifier -= this.tokens['gold'];
        }
    }
}

RedCloaks.code = '02070';

module.exports = RedCloaks;
<|endoftext|>


<commit_before>var app = angular.module('appRoutes',['ngRoute'])

.config(function($routeProvider,$locationProvider){

	$routeProvider

		.when('/',{
			templateUrl: 'app/views/pages/home.html'
		})

		.when('/about',{
			templateUrl: 'app/views/pages/about.html'
		})

		.when('/login', {
			templateUrl: 'app/views/pages/login.html'
		})

		.when('/register', {
			templateUrl: 'app/views/pages/users/register.html',
			controller: 'regCtrl',
			controllerAs: 'register'
		})

		.when('/login', {
			templateUrl: 'app/views/pages/users/login.html'
		})

		.when('/logout', {
			templateUrl: 'app/views/pages/users/logout.html'
		})

		.when('/profile', {
			templateUrl: 'app/views/pages/users/profile.html',
			isteacher: true
		})
		.when('/facebook/:token', {
			templateUrl: 'app/views/pages/users/social/social.html'
		})

		.when('/google/:token', {
			templateUrl: 'app/views/pages/users/social/social.html',
			controller: 'twitterCtrl',
			controllerAs: 'twitter'
		})

		.when('/googleerror', {
			templateUrl: 'app/views/pages/users/login.html',
			controller: 'googleCtrl',
			controllerAs: 'google'
		})

		.when('/syllabus', {
			templateUrl: 'app/views/pages/users/syllabus.html'
		})

		.when('/management', {
			templateUrl: 'app/views/pages/users/management.html',
			conoller: 'managementCtrl',
			controllerAs: 'management',
			permission: ['teacher', 'admin']

		})

	.otherwise({redirectTo: '/'});

	$locationProvider.html5Mode({
	enabled: true,
 	requireBase: false
 });

})

app.run(['$rootScope','Auth', 'User', '$location', function($rootScope, Auth, User, $location){

	$rootScope.$on('$routeChangeStart', function(event,next,current){

		if(next.$$route.permission){
			User.getPermission().then(function(data){
				if(next.$$route.permission[0] !== data.data.permission){
					if(next.$$route.permission[1] !== data.data.permission){
						event.preventDefault();
						$location.path('/');
					}
				}
			});
		}

	});

}]);
<commit_msg>Updated the route to include addHomework<commit_after>var app = angular.module('appRoutes',['ngRoute'])

.config(function($routeProvider,$locationProvider){

	$routeProvider

		.when('/',{
			templateUrl: 'app/views/pages/home.html'
		})

		.when('/about',{
			templateUrl: 'app/views/pages/about.html'
		})

		.when('/login', {
			templateUrl: 'app/views/pages/login.html'
		})

		.when('/register', {
			templateUrl: 'app/views/pages/users/register.html',
			controller: 'regCtrl',
			controllerAs: 'register'
		})

		.when('/login', {
			templateUrl: 'app/views/pages/users/login.html'
		})

		.when('/addHomework', {
		templateUrl: 'app/views/pages/homework/addHomeWork.html',
		controller: 'addHwCtrl',
		controllerAs: 'addHomework'
	})

		.when('/logout', {
			templateUrl: 'app/views/pages/users/logout.html'
		})

		.when('/profile', {
			templateUrl: 'app/views/pages/users/profile.html',
			isteacher: true
		})
		.when('/facebook/:token', {
			templateUrl: 'app/views/pages/users/social/social.html'
		})

		.when('/google/:token', {
			templateUrl: 'app/views/pages/users/social/social.html',
			controller: 'twitterCtrl',
			controllerAs: 'twitter'
		})

		.when('/googleerror', {
			templateUrl: 'app/views/pages/users/login.html',
			controller: 'googleCtrl',
			controllerAs: 'google'
		})

		.when('/syllabus', {
			templateUrl: 'app/views/pages/users/syllabus.html'
		})

		.when('/management', {
			templateUrl: 'app/views/pages/users/management.html',
			conoller: 'managementCtrl',
			controllerAs: 'management',
			permission: ['teacher', 'admin']

		})

	.otherwise({redirectTo: '/'});

	$locationProvider.html5Mode({
	enabled: true,
 	requireBase: false
 });

})

app.run(['$rootScope','Auth', 'User', '$location', function($rootScope, Auth, User, $location){

	$rootScope.$on('$routeChangeStart', function(event,next,current){

		if(next.$$route.permission){
			User.getPermission().then(function(data){
				if(next.$$route.permission[0] !== data.data.permission){
					if(next.$$route.permission[1] !== data.data.permission){
						event.preventDefault();
						$location.path('/');
					}
				}
			});
		}

	});

}]);
<|endoftext|>


<commit_before>const DrawCard = require('../../../drawcard.js');

class BearIsland extends DrawCard {
    setupCardAbilities(ability) {
        this.reaction({
            when: {
                onCardEntersPlay: (event, card) => card.controller === this.controller && card.isLoyal() && this.game.currentPhase === 'marshal'
            },
            limit: ability.limit.perPhase(2),
            handler: () => {
                this.game.addGold(this.controller, 1);
                this.game.addMessage('{0} uses {1} to gain 1 gold', this.controller, this);
            }
        });
    }
}

BearIsland.code = '04042';

module.exports = BearIsland;
<commit_msg>Stop bear island triggering on plots and crashing.  We need to rethink whether or not we should be raising cardEntersPlay for plots<commit_after>const DrawCard = require('../../../drawcard.js');

class BearIsland extends DrawCard {
    setupCardAbilities(ability) {
        this.reaction({
            when: {
                onCardEntersPlay: (event, card) => card.getType() !== 'plot' && card.controller === this.controller && card.isLoyal() && this.game.currentPhase === 'marshal'
            },
            limit: ability.limit.perPhase(2),
            handler: () => {
                this.game.addGold(this.controller, 1);
                this.game.addMessage('{0} uses {1} to gain 1 gold', this.controller, this);
            }
        });
    }
}

BearIsland.code = '04042';

module.exports = BearIsland;
<|endoftext|>


<commit_before>import { iff, isProvider } from 'feathers-hooks-common';
import { associateCurrentUser, queryWithCurrentUser } from 'feathers-authentication-hooks';
import { hooks } from 'mostly-feathers-mongoose';
import { cache } from 'mostly-feathers-cache';
import { authorize } from 'playing-permissions';

import * as content from '../../hooks';

export default function (options = {}) {
  return {
    before: {
      all: [
        hooks.authenticate('jwt', options.auth),
        authorize('document', { ancestors: { field: 'ancestors', service: 'documents' } }),
        cache(options.cache, { headers: ['enrichers-document'] })
      ],
      get: [
        // queryWithCurrentUser({ idField: 'id', as: 'creator' })
      ],
      find: [
        // queryWithCurrentUser({ idField: 'id', as: 'creator' })
      ],
      create: [
        iff(isProvider('external'),
          associateCurrentUser({ idField: 'id', as: 'creator' })),
        content.computePath(),
        content.computeAncestors(),
        content.fetchBlobs({ xpath: 'file', xpaths: 'files' })
      ],
      update: [
        iff(isProvider('external'),
          associateCurrentUser({ idField: 'id', as: 'creator' })),
        hooks.depopulate('parent'),
        hooks.discardFields('metadata', 'ancestors', 'createdAt', 'updatedAt', 'destroyedAt'),
        content.computePath(),
        content.computeAncestors(),
        content.fetchBlobs({ xpath: 'file', xpaths: 'files' })
      ],
      patch: [
        iff(isProvider('external'),
          associateCurrentUser({ idField: 'id', as: 'creator' })),
        hooks.depopulate('parent'),
        hooks.discardFields('metadata', 'ancestors', 'createdAt', 'updatedAt', 'destroyedAt'),
        content.computePath(),
        content.computeAncestors(),
        content.fetchBlobs({ xpath: 'file', xpaths: 'files' })
      ]
    },
    after: {
      all: [
        // only populate with document type to avoid duplicated process
        iff(content.isDocumentType('document'),
          hooks.populate('parent', { service: 'folders' })),
        iff(content.isDocumentType('document'),
          hooks.populate('ancestors')), // with typed id
        iff(content.isDocumentType('document'),
          hooks.populate('creator', { service: 'users' })),
        iff(content.isDocumentType('document'),
          hooks.assoc('permissions', { service: 'user-permissions', field: 'subject', typeField: 'type' })),
        iff(content.isDocumentType('document'),
          content.documentEnrichers(options)),
        cache(options.cache, { headers: ['enrichers-document'] }),
        iff(content.isDocumentType('document'),
          content.presentDocument(options)),
        hooks.responder()
      ],
      create: [
        iff(content.isDocumentType('document'),
          content.documentNotifier('document.create'))
      ]
    }
  };
}<commit_msg>authorize with documents subject service<commit_after>import { iff, isProvider } from 'feathers-hooks-common';
import { associateCurrentUser, queryWithCurrentUser } from 'feathers-authentication-hooks';
import { hooks } from 'mostly-feathers-mongoose';
import { cache } from 'mostly-feathers-cache';
import { authorize } from 'playing-permissions';

import * as content from '../../hooks';

export default function (options = {}) {
  return {
    before: {
      all: [
        hooks.authenticate('jwt', options.auth),
        authorize('documents', { ancestors: { field: 'ancestors', service: 'documents' } }),
        cache(options.cache, { headers: ['enrichers-document'] })
      ],
      get: [
        // queryWithCurrentUser({ idField: 'id', as: 'creator' })
      ],
      find: [
        // queryWithCurrentUser({ idField: 'id', as: 'creator' })
      ],
      create: [
        iff(isProvider('external'),
          associateCurrentUser({ idField: 'id', as: 'creator' })),
        content.computePath(),
        content.computeAncestors(),
        content.fetchBlobs({ xpath: 'file', xpaths: 'files' })
      ],
      update: [
        iff(isProvider('external'),
          associateCurrentUser({ idField: 'id', as: 'creator' })),
        hooks.depopulate('parent'),
        hooks.discardFields('metadata', 'ancestors', 'createdAt', 'updatedAt', 'destroyedAt'),
        content.computePath(),
        content.computeAncestors(),
        content.fetchBlobs({ xpath: 'file', xpaths: 'files' })
      ],
      patch: [
        iff(isProvider('external'),
          associateCurrentUser({ idField: 'id', as: 'creator' })),
        hooks.depopulate('parent'),
        hooks.discardFields('metadata', 'ancestors', 'createdAt', 'updatedAt', 'destroyedAt'),
        content.computePath(),
        content.computeAncestors(),
        content.fetchBlobs({ xpath: 'file', xpaths: 'files' })
      ]
    },
    after: {
      all: [
        // only populate with document type to avoid duplicated process
        iff(content.isDocumentType('document'),
          hooks.populate('parent', { service: 'folders' })),
        iff(content.isDocumentType('document'),
          hooks.populate('ancestors')), // with typed id
        iff(content.isDocumentType('document'),
          hooks.populate('creator', { service: 'users' })),
        iff(content.isDocumentType('document'),
          hooks.assoc('permissions', { service: 'user-permissions', field: 'subject', typeField: 'type' })),
        iff(content.isDocumentType('document'),
          content.documentEnrichers(options)),
        cache(options.cache, { headers: ['enrichers-document'] }),
        iff(content.isDocumentType('document'),
          content.presentDocument(options)),
        hooks.responder()
      ],
      create: [
        iff(content.isDocumentType('document'),
          content.documentNotifier('document.create'))
      ]
    }
  };
}<|endoftext|>


<commit_before>var pull = require('pull-stream')
var pullPushable = require('pull-pushable')
var pullNext = require('pull-next')
var SortedArray = require('sorted-array-functions')
var nest = require('depnest')

exports.gives = nest({
  'feed.pull': [ 'summary' ]
})

exports.create = function () {
  return nest({
    'feed.pull': { summary }
  })
}

function summary (source, opts, cb) {
  var bumpFilter = opts && opts.bumpFilter
  var windowSize = opts && opts.windowSize || 1000
  var last = null
  var returned = false
  var done = false
  return pullNext(() => {
    if (!done) {
      var next = {reverse: true, limit: windowSize, live: false}
      if (last) {
        next.lt = last.timestamp || last.value.sequence
      }
      var pushable = pullPushable()
      pull(
        source(next),
        pull.collect((err, values) => {
          if (err) throw err
          if (!values.length) {
            done = true
            pushable.end()
            if (!returned) cb && cb()
            returned = true
          } else {
            var fromTime = last && last.timestamp || Date.now()
            last = values[values.length - 1]
            groupMessages(values, fromTime, bumpFilter, (err, result) => {
              if (err) throw err
              result.forEach(v => pushable.push(v))
              pushable.end()
              if (!returned) cb && cb()
              returned = true
            })
          }
        })
      )
    }
    return pushable
  })
}

function groupMessages (messages, fromTime, bumpFilter, cb) {
  var follows = {}
  var messageUpdates = {}
  reverseForEach(messages, function (msg) {
    if (!msg.value) return
    var c = msg.value.content
    if (c.type === 'contact') {
      updateContact(msg, follows)
    } else if (c.type === 'vote') {
      if (c.vote && c.vote.link) {
        // only show likes of posts added in the current window
        // and only for the main post
        const group = messageUpdates[c.vote.link]
        if (group) {
          if (c.vote.value > 0) {
            group.lastUpdateType = 'like'
            group.likes.add(msg.value.author)
            // only bump when filter passes
            if (!bumpFilter || bumpFilter(msg, group)) {
              group.updated = msg.timestamp
            }
          } else {
            group.likes.delete(msg.value.author)
            if (group.lastUpdateType === 'like' && !group.likes.size && !group.replies.length) {
              group.lastUpdateType = 'reply'
            }
          }
        }
      }
    } else {
      if (c.root || (c.type === 'git-update' && c.repo)) {
        const group = ensureMessage(c.root || c.repo, messageUpdates)
        group.fromTime = fromTime
        group.lastUpdateType = 'reply'
        group.repliesFrom.add(msg.value.author)
        SortedArray.add(group.replies, msg, compareUserTimestamp)
        //group.replies.push(msg)
        group.channel = group.channel || msg.value.content.channel

        // only bump when filter passes
        if (!bumpFilter || bumpFilter(msg, group)) {
          group.updated = msg.timestamp || msg.value.sequence
        }
      } else {
        const group = ensureMessage(msg.key, messageUpdates)
        group.fromTime = fromTime
        group.lastUpdateType = 'post'
        group.updated = msg.timestamp || msg.value.sequence
        group.author = msg.value.author
        group.channel = msg.value.content.channel
        group.message = msg
        group.boxed = typeof msg.value.content === 'string'
      }
    }
  }, () => {
    var result = []
    Object.keys(follows).forEach((key) => {
      if (follows[key].updated) {
        SortedArray.add(result, follows[key], compareUpdated)
      }
    })
    Object.keys(messageUpdates).forEach((key) => {
      if (messageUpdates[key].updated) {
        SortedArray.add(result, messageUpdates[key], compareUpdated)
      }
    })
    cb(null, result)
  })
}

function compareUpdated (a, b) {
  return b.updated - a.updated
}

function reverseForEach (items, fn, cb) {
  var i = items.length - 1
  nextBatch()

  function nextBatch () {
    var start = Date.now()
    while (i >= 0) {
      fn(items[i], i)
      i -= 1
      if (Date.now() - start > 10) break
    }

    if (i > 0) {
      setImmediate(nextBatch)
    } else {
      cb && cb()
    }
  }
}

function updateContact (msg, groups) {
  var c = msg.value.content
  var id = msg.value.author
  var group = groups[id]
  if (c.contact) {
    if (c.following) {
      if (!group) {
        group = groups[id] = {
          type: 'follow',
          lastUpdateType: null,
          contacts: new Set(),
          updated: 0,
          author: id,
          id: id
        }
      }
      group.contacts.add(c.contact)
      group.updated = msg.timestamp || msg.value.sequence
    } else {
      if (group) {
        group.contacts.delete(c.contact)
        if (!group.contacts.size) {
          delete groups[id]
        }
      }
    }
  }
}

function ensureMessage (id, groups) {
  var group = groups[id]
  if (!group) {
    group = groups[id] = {
      type: 'message',
      repliesFrom: new Set(),
      replies: [],
      message: null,
      messageId: id,
      likes: new Set(),
      updated: 0
    }
  }
  return group
}

function compareUserTimestamp (a, b) {
  var isClose = !a.timestamp || !b.timestamp || Math.abs(a.timestamp - b.timestamp) < (10 * 60e3)
  if (isClose) {
    // recieved close together, use provided timestamps
    return a.value.timestamp - b.value.timestamp
  } else {
    return a.timestamp - b.timestamp
  }
}
<commit_msg>summary: use deferred instead of pull-pushable<commit_after>var pull = require('pull-stream')
var pullDefer = require('pull-defer')
var pullNext = require('pull-next')
var SortedArray = require('sorted-array-functions')
var nest = require('depnest')

exports.gives = nest({
  'feed.pull': [ 'summary' ]
})

exports.create = function () {
  return nest({
    'feed.pull': { summary }
  })
}

function summary (source, opts, cb) {
  var bumpFilter = opts && opts.bumpFilter
  var windowSize = opts && opts.windowSize || 1000
  var last = null
  var returned = false
  var done = false
  return pullNext(() => {
    if (!done) {
      var next = {reverse: true, limit: windowSize, live: false}
      if (last) {
        next.lt = last.timestamp || last.value.sequence
      }
      var deferred = pullDefer.source()
      pull(
        source(next),
        pull.collect((err, values) => {
          if (err) throw err
          if (!values.length) {
            done = true
            deferred.resolve(pull.values([]))
            if (!returned) cb && cb()
            returned = true
          } else {
            var fromTime = last && last.timestamp || Date.now()
            last = values[values.length - 1]
            groupMessages(values, fromTime, bumpFilter, (err, result) => {
              if (err) throw err
              deferred.resolve(
                pull.values(result)
              )
              if (!returned) cb && cb()
              returned = true
            })
          }
        })
      )
    }
    return deferred
  })
}

function groupMessages (messages, fromTime, bumpFilter, cb) {
  var follows = {}
  var messageUpdates = {}
  reverseForEach(messages, function (msg) {
    if (!msg.value) return
    var c = msg.value.content
    if (c.type === 'contact') {
      updateContact(msg, follows)
    } else if (c.type === 'vote') {
      if (c.vote && c.vote.link) {
        // only show likes of posts added in the current window
        // and only for the main post
        const group = messageUpdates[c.vote.link]
        if (group) {
          if (c.vote.value > 0) {
            group.lastUpdateType = 'like'
            group.likes.add(msg.value.author)
            // only bump when filter passes
            if (!bumpFilter || bumpFilter(msg, group)) {
              group.updated = msg.timestamp
            }
          } else {
            group.likes.delete(msg.value.author)
            if (group.lastUpdateType === 'like' && !group.likes.size && !group.replies.length) {
              group.lastUpdateType = 'reply'
            }
          }
        }
      }
    } else {
      if (c.root || (c.type === 'git-update' && c.repo)) {
        const group = ensureMessage(c.root || c.repo, messageUpdates)
        group.fromTime = fromTime
        group.lastUpdateType = 'reply'
        group.repliesFrom.add(msg.value.author)
        SortedArray.add(group.replies, msg, compareUserTimestamp)
        //group.replies.push(msg)
        group.channel = group.channel || msg.value.content.channel

        // only bump when filter passes
        if (!bumpFilter || bumpFilter(msg, group)) {
          group.updated = msg.timestamp || msg.value.sequence
        }
      } else {
        const group = ensureMessage(msg.key, messageUpdates)
        group.fromTime = fromTime
        group.lastUpdateType = 'post'
        group.updated = msg.timestamp || msg.value.sequence
        group.author = msg.value.author
        group.channel = msg.value.content.channel
        group.message = msg
        group.boxed = typeof msg.value.content === 'string'
      }
    }
  }, () => {
    var result = []
    Object.keys(follows).forEach((key) => {
      if (follows[key].updated) {
        SortedArray.add(result, follows[key], compareUpdated)
      }
    })
    Object.keys(messageUpdates).forEach((key) => {
      if (messageUpdates[key].updated) {
        SortedArray.add(result, messageUpdates[key], compareUpdated)
      }
    })
    cb(null, result)
  })
}

function compareUpdated (a, b) {
  return b.updated - a.updated
}

function reverseForEach (items, fn, cb) {
  var i = items.length - 1
  nextBatch()

  function nextBatch () {
    var start = Date.now()
    while (i >= 0) {
      fn(items[i], i)
      i -= 1
      if (Date.now() - start > 10) break
    }

    if (i > 0) {
      setImmediate(nextBatch)
    } else {
      cb && cb()
    }
  }
}

function updateContact (msg, groups) {
  var c = msg.value.content
  var id = msg.value.author
  var group = groups[id]
  if (c.contact) {
    if (c.following) {
      if (!group) {
        group = groups[id] = {
          type: 'follow',
          lastUpdateType: null,
          contacts: new Set(),
          updated: 0,
          author: id,
          id: id
        }
      }
      group.contacts.add(c.contact)
      group.updated = msg.timestamp || msg.value.sequence
    } else {
      if (group) {
        group.contacts.delete(c.contact)
        if (!group.contacts.size) {
          delete groups[id]
        }
      }
    }
  }
}

function ensureMessage (id, groups) {
  var group = groups[id]
  if (!group) {
    group = groups[id] = {
      type: 'message',
      repliesFrom: new Set(),
      replies: [],
      message: null,
      messageId: id,
      likes: new Set(),
      updated: 0
    }
  }
  return group
}

function compareUserTimestamp (a, b) {
  var isClose = !a.timestamp || !b.timestamp || Math.abs(a.timestamp - b.timestamp) < (10 * 60e3)
  if (isClose) {
    // recieved close together, use provided timestamps
    return a.value.timestamp - b.value.timestamp
  } else {
    return a.timestamp - b.timestamp
  }
}
<|endoftext|>


<commit_before>import App from "./App";

export default class Action {
    dispatchAction(...args) {
        return App.dispatchAction(...args);
    }

    get logger() {
        return App.logger(this.ns);
    }

    get events() {
        return App.events;
    }

    publish(ev, ...args) {
        return App.events.publish(`${this.ns}.${ev}`, ...args);
    }

    get ns() {
        return this._ns || "app";
    }
    set ns(namespace) {
        this._ns = namespace;
    }

    static ns(key) { // Decorator for easily adding namespace.
        return (ActionWithNS) => {
            ActionWithNS.prototype.ns = key;
        };
    }
}
<commit_msg>Allow actions to use `publish.when`.<commit_after>import App from "./App";

export default class Action {
    constructor() {
        // Need to save publishers on this instance so we can mutate the publish w/ when.
        this.publish = this.publish.bind(this);
        this.publish.when = this.publishWhen.bind(this);
    }

    dispatchAction(...args) {
        return App.dispatchAction(...args);
    }

    get logger() {
        return App.logger(this.ns);
    }

    get events() {
        return App.events;
    }

    publish(...args) {
        return this._publishWith(App.events.publish, ...args);
    }

    publishWhen(...args) {
        return this._publishWith(App.events.publish.when, ...args);
    }

    _publishWith(publish, ev, ...args) {
        return publish(`${this.ns}.${ev}`, ...args);
    }

    get ns() {
        return this._ns || "app";
    }
    set ns(namespace) {
        this._ns = namespace;
    }

    static ns(key) { // Decorator for easily adding namespace.
        return (ActionWithNS) => {
            ActionWithNS.prototype.ns = key;
        };
    }
}
<|endoftext|>


<commit_before>var walk = require('acorn/util/walk');

module.exports = function (tree) {
  walk.recursive(tree.data.cfg, {}, {
    CallExpression: function (node, state, c) {
      if(node.callee.type === 'MemberExpression'
        && node.callee.name === 'document'){
        if(node.callee.property.name === 'getElementById'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Output",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'getElementByName'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Output",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'getElementByTagName'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Output",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'documentElement'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Output",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'images'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Output",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'domain'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Output",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'body'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Output",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'createAttribute'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Input",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'createComment'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Input",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'createDocumentFragment'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Input",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'createElement'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Input",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
        if(node.callee.property.name === 'createTextNode'){
          tree.data.problems.push({
            "type": "warning",
            "message": "Input",
            "weight": 5,
            "position": {
              "start": node.start,
              "end": node.end
            }
          });
        }
      }
    }
  });    //graph.domio = "success";
};<commit_msg>clean up<commit_after>var walk = require('acorn/util/walk');

module.exports = function (tree) {
  walk.recursive(tree.data.cfg, {}, {
    CallExpression: function (node, state, c) {
      if(node.callee.type === 'MemberExpression'
        && node.callee.name === 'document'){
        if(node.callee.property.name === 'getElementById'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Output',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'getElementByName'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Output',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'getElementByTagName'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Output',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'documentElement'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Output',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'images'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Output',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'domain'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Output',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'body'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Output',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'createAttribute'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Input',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'createComment'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Input',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'createDocumentFragment'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Input',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'createElement'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Input',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'createTextNode'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Input',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'createTextNode'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Input',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
        if(node.callee.property.name === 'createTextNode'){
          tree.data.problems.push({
            'type': 'warning',
            'message': 'Input',
            'weight': 5,
            'position': {
              'start': node.start,
              'end': node.end
            }
          });
        }
      }
    }
  });    //graph.domio = 'success';
};<|endoftext|>


<commit_before>var Sequencer = require('./Sequencer');
var _super = Sequencer.prototype;
var npath = require('path');
var _ = require('lodash');

var Config = require('./Config');

module.exports = Sequencer.extend({

  'publicMethods': [
    'on',
    'once',
    'trigger',
    'use',
    'start',
    'addSequence',
    'runSequence',
    'register',
    'config',
    'logPending',
    'logSince',
    'error',
    'paths'
  ],

  'config': {},

  'initialize': function () {

    var self = this;
    _super.initialize.apply(self, arguments);

    if (self.options.muteLog) {
      process.env.MUTE = true;
    }

    self.logAsimovHeader();

    self.config = _.merge(self.getConfig(), self.config);

    self._publicInterface = {};

    self.addSequence('initializer', 'init');
    self.addSequence('postinit');

    self.publicMethods.forEach(function (name) {
      self.register(name, self[name]);
    });

    self._publicInterface.fs = self.filesystem;
  },

  'start': function (next) {

    var self = this;
    self.started = new Date();

    self.logger.pending('start', 'Loading asimov.js @ ' + self.options.meta.version);
    self.logger.log('start', 'The time is ' + self.started);
    self.logger.pending('start', 'Starting "' + self.options.pkg.name + '" @ ' + self.options.pkg.version);

    var amount = self.getSequence('initializer').length + self.getSequence('postinit').length;

    if (!amount) {
      return self.error('No initializers found');
    }

    self.runSequence('initializer').done(function () {
      self.runSequence('postinit').done(function () {
        if (typeof next === 'function') next();
      }).fail(self.error);
    }).fail(self.error);

    return self.publicInterface();
  },

  'getConfig': function () {

    var self = this;

    var config = self._config = new Config(self.options);
    var json = config.json;

    return {
      'paths': json.paths,
      'outputPath': json.paths.outputDir,
      'meta': json.meta,
      'pkg': json.pkg,
      'defaultLangCode': json.defaultLangCode
    };
  },

  'use': function (plugin, options) {

    var self = this;
    self.assert('function', plugin, 'Invalid plugin constructor function');

    plugin(self.publicInterface());

    return self.publicInterface();
  },

  'addedSequence': function (namespace, method) {

    var self = this;
    return self.register(method, self[method]);
  },

  'paths': function (type, namespace) {

    var self = this;
    var name = type + 'Path';

    self.config.paths = self.config.paths || {};
    self.config.paths[type] = self.config.paths[type] || [];

    self.register(name, function (path, namespace) {
      namespace = namespace || 'pages';
      self.logPending(namespace, 'Adding path for asimov.' + type + ' @ ' + path);
      self.config.paths[type].push(path);
    }, namespace);
  },

  'register': function (name, target, namespace) {

    var self = this;

    self.assert('string', name, 'Invalid register namespace');
    self.assert('defined', target, 'Invalid register target "' + name + '"');

    self.log('Adding public interface @ asimov.' + name, namespace);

    self._publicInterface[name] = target;

    return self.publicInterface();
  },

  'logAsimovHeader': function () {

    var self = this;

    if (self.options.muteLog) return;

    console.log(self.lineDelimiter);
    self.logLines(self.signature);
    console.log(self.lineDelimiter);
  },

  'log': function (message, namespace) {

    var self = this;
    self.logger.low(namespace || self.namespace, message);
  },

  'error': function (message) {

    var self = this;
    var messages = _.toArray(arguments);
    var pattern = 'Error: ';

    if (_.isArray(message)) {
      self.error.apply(self, message);
    }
    else if (_.isArray(messages)) {
      messages.forEach(function (message) {
        message = message.toString();
        if (message.indexOf(pattern) === 0) {
          message = message.replace(pattern, '');
        }
        self.logger.log('error', message, 'red');
      });
    }
  },

  'logPending': function (namespace, message) {
    if (!message) {
      message = namespace;
      namespace = 'asimov';
    }
    return this.logger.low(namespace, message);
  },

  'logSince': function (namespace, message, date) {

    if (!date) {
      date = message;
      message = namespace;
      namespace = 'asimov';
    }
    return this.logger.lowSince(namespace, message, date);
  }
});
<commit_msg>make sure to continue the sequence, specifically for the test command<commit_after>var Sequencer = require('./Sequencer');
var _super = Sequencer.prototype;
var npath = require('path');
var _ = require('lodash');

var Config = require('./Config');

module.exports = Sequencer.extend({

  'publicMethods': [
    'on',
    'once',
    'trigger',
    'use',
    'start',
    'addSequence',
    'runSequence',
    'register',
    'config',
    'logPending',
    'logSince',
    'error',
    'paths'
  ],

  'config': {},

  'initialize': function () {

    var self = this;
    _super.initialize.apply(self, arguments);

    if (self.options.muteLog) {
      process.env.MUTE = true;
    }

    self.logAsimovHeader();

    self.config = _.merge(self.getConfig(), self.config);

    self._publicInterface = {};

    self.addSequence('initializer', 'init');
    self.addSequence('postinit');

    self.publicMethods.forEach(function (name) {
      self.register(name, self[name]);
    });

    self._publicInterface.fs = self.filesystem;
  },

  'start': function (next) {

    var self = this;
    self.started = new Date();

    self.logger.pending('start', 'Loading asimov.js @ ' + self.options.meta.version);
    self.logger.log('start', 'The time is ' + self.started);
    self.logger.pending('start', 'Starting "' + self.options.pkg.name + '" @ ' + self.options.pkg.version);

    var amount = self.getSequence('initializer').length + self.getSequence('postinit').length;

    if (!amount) {
      self.error('No initializers found');
      return next();
    }

    self.runSequence('initializer').done(function () {
      self.runSequence('postinit').done(function () {
        if (typeof next === 'function') next();
      }).fail(self.error);
    }).fail(self.error);

    return self.publicInterface();
  },

  'getConfig': function () {

    var self = this;

    var config = self._config = new Config(self.options);
    var json = config.json;

    return {
      'paths': json.paths,
      'outputPath': json.paths.outputDir,
      'meta': json.meta,
      'pkg': json.pkg,
      'defaultLangCode': json.defaultLangCode
    };
  },

  'use': function (plugin, options) {

    var self = this;
    self.assert('function', plugin, 'Invalid plugin constructor function');

    plugin(self.publicInterface());

    return self.publicInterface();
  },

  'addedSequence': function (namespace, method) {

    var self = this;
    return self.register(method, self[method]);
  },

  'paths': function (type, namespace) {

    var self = this;
    var name = type + 'Path';

    self.config.paths = self.config.paths || {};
    self.config.paths[type] = self.config.paths[type] || [];

    self.register(name, function (path, namespace) {
      namespace = namespace || 'pages';
      self.logPending(namespace, 'Adding path for asimov.' + type + ' @ ' + path);
      self.config.paths[type].push(path);
    }, namespace);
  },

  'register': function (name, target, namespace) {

    var self = this;

    self.assert('string', name, 'Invalid register namespace');
    self.assert('defined', target, 'Invalid register target "' + name + '"');

    self.log('Adding public interface @ asimov.' + name, namespace);

    self._publicInterface[name] = target;

    return self.publicInterface();
  },

  'logAsimovHeader': function () {

    var self = this;

    if (self.options.muteLog) return;

    console.log(self.lineDelimiter);
    self.logLines(self.signature);
    console.log(self.lineDelimiter);
  },

  'log': function (message, namespace) {

    var self = this;
    self.logger.low(namespace || self.namespace, message);
  },

  'error': function (message) {

    var self = this;
    var messages = _.toArray(arguments);
    var pattern = 'Error: ';

    if (_.isArray(message)) {
      self.error.apply(self, message);
    }
    else if (_.isArray(messages)) {
      messages.forEach(function (message) {
        message = message.toString();
        if (message.indexOf(pattern) === 0) {
          message = message.replace(pattern, '');
        }
        self.logger.log('error', message, 'red');
      });
    }
  },

  'logPending': function (namespace, message) {
    if (!message) {
      message = namespace;
      namespace = 'asimov';
    }
    return this.logger.low(namespace, message);
  },

  'logSince': function (namespace, message, date) {

    if (!date) {
      date = message;
      message = namespace;
      namespace = 'asimov';
    }
    return this.logger.lowSince(namespace, message, date);
  }
});
<|endoftext|>