<commit_before>/*
 * Jamoma Mapping Manager
 * Tim Place
 * Copyright © 2006 Jamoma Development Group
 *
 * Input syntax:
 *	create mapping_name src_module/arg1/arg2/arg3 [optional algorithm] -> dst_module/arg1/arg2/arg3
 *	remove mapping_name
 *  modify mapping_name <message for algorithm>
 */

// GLOBALS
var mapping_names = new Array();
var mapping_sources = new Array();
var mapping_destinations = new Array();
var mapping_algorithms = new Array();

// SETUP
function setup()
{
	// set up assistance strings
	setinletassist(0, "create, remove, modify");
	setoutletassist(0, "connect to a thispatcher object");
}
setup.local = 1;
setup();

// INIT
function loadbang()
{
	//outlet(0, "script", "new", "mapping_object_r", "newex",0, 0, 200, 196617, "jcom.receive", "jcom.remote.module.to");
	//outlet(0, "script", "new", "mapping_object_s", "newex",0, 1000, 200, 196617, "jcom.send", "jcom.remote.module.from");
}

// CREATE
function create()
{
	// 0. Find the entry number for this new mapping
	var entry = 0;
	if(mapping_names){
		entry = mapping_names.length;
	}

	// 1. Error Checking
	if(arguments.length < 4){
		post("ERROR jmod.mappings: create requires at least 4 arguments (name, src, optional algorithm, arrow, dst) in order to make a mapping");post();
		return;
	}
	var arrow = arguments[arguments.length-2];
	if(arrow != '->'){
		post("ERROR jmod.mappings: create requires an arrow");post();
		return;
	}
	var name = arguments[0];
	for(var i=0; i < entry; i++){
		if(name == mapping_names[i]){
			post("ERROR jmod.mappings: mapping_name already exists, cannot create mapping");post();
			return;
		}
	}

	// 2. Record Keeping
	var src = arguments[1];
	var dst = arguments[arguments.length-1];
	var algo = null;
	if(arguments.length > 4){
		mapping_algorithms[entry] = new Array();
		for(var i=2; i < arguments.length-2; i++){
			mapping_algorithms[entry].push(arguments[i]);
		}
	}
	else{
		mapping_algorithms[entry] = null;
	}
	mapping_names[entry] = name;
	mapping_sources[entry] = src;
	mapping_destinations[entry] = dst;

	// 3. Finally Script the Patch...
//	outlet(0, "script", "new", "mapping_object_src_"+entry, "newex",50, (entry+1)*70, 200, 196617, "jcom.receive", "/jmod_from"+mapping_sources[entry]);
//	outlet(0, "script", "new", "mapping_object_dst_"+entry, "newex",50, (entry+1)*70+40, 200, 196617, "jcom.send", "/jmod_to"+mapping_destinations[entry]);
	outlet(0, "script", "new", "mapping_object_src_"+entry, "newex",50, (entry+1)*100, 200, 196617, "jcom.receive", "jcom.remote.module.from");
	outlet(0, "script", "new", "mapping_object_dst_"+entry, "newex",50, (entry+1)*100+80, 200, 196617, "jcom.send", "jcom.remote.module.to");
	outlet(0, "script", "new", "mapping_object_route_"+entry, "newex", 50, (entry+1)*100+20, 200, 196617, "route", mapping_sources[entry]);
	outlet(0, "script", "new", "mapping_object_prepend_"+entry, "newex", 50, (entry+1)*100+60, 200, 196617, "prepend", mapping_destinations[entry]);
	//outlet(0, "script", "connect", "mapping_object_r", 0, "mapping_object_osc_"+entry, 0);
	//outlet(0, "script", "connect", "mapping_object_dst_"+entry, 0, "mapping_object_s", 0);

	if(mapping_algorithms[entry] == null){
		outlet(0, "script", "connect", "mapping_object_src_"+entry, 0, "mapping_object_route_"+entry, 0);
		outlet(0, "script", "connect", "mapping_object_route_"+entry, 0, "mapping_object_prepend_"+entry, 0);
		outlet(0, "script", "connect", "mapping_object_prepend_"+entry, 0, "mapping_object_dst_"+entry, 0);
	}
	else{
		outlet(0, "script", "new", "mapping_object_alg_"+entry, "newex",50, (entry+1)*100+40, 200, 196617, mapping_algorithms[entry]);
		outlet(0, "script", "connect", "mapping_object_src_"+entry, 0, "mapping_object_route_"+entry, 0);
		outlet(0, "script", "connect", "mapping_object_route_"+entry, 0, "mapping_object_alg_"+entry, 0);
		outlet(0, "script", "connect", "mapping_object_alg_"+entry, 0, "mapping_object_prepend_"+entry, 0);
		outlet(0, "script", "connect", "mapping_object_prepend_"+entry, 0, "mapping_object_dst_"+entry, 0);
	}
}

// DELETE
function remove(mapping_name)
{
	// first, find the index number of the named mapping
	if(mapping_names.length == 0){
		post("ERROR jmod.mappings: no such mapping to remove!"); post();
		return 0;
	}
	var entry = getindex(mapping_name);

	// second, delete all of the objects that are associated with this mapping
	outlet(0, "script", "delete", "mapping_object_src_"+entry);
	outlet(0, "script", "delete", "mapping_object_dst_"+entry);
	if(mapping_algorithms[entry] != null){
		outlet(0, "script", "delete", "mapping_object_alg_"+entry);
	}

	// third, remove the entry for the mapping from the array
	mapping_names[entry] = null;
	mapping_sources[entry] = null;
	mapping_algorithms[entry] = null;
	mapping_destinations[entry] = null;

	return 1;
}

// MODIFY
// send a message to the algorithm to change its behavior
function modify()
{
	var entry = getindex(arguments[0]);
	var args = new Array();
	for(var i=1; i<arguments.length; i++){
		args[i-1] = arguments[i];
	}
	outlet(0, "script", "send", "mapping_object_alg_"+entry, args);
}

// CLEAR - erases all mappings
function clear()
{
	for(var i=0; i<mapping_names.length; i++){
		remove(mapping_names[i]);
	}
	while(mapping_names.pop());
	while(mapping_sources.pop());
	while(mapping_destinations.pop());
	while(mapping_algorithms.pop());
}

// Private method used by the others for finding the index number associated with a name
function getindex(mapping_name)
{
	var entry;
	for(var i=0; i<mapping_names.length; i++){
		if(mapping_name == mapping_names[i]){
			entry = i;
		}
	}
	return entry;
}
getindex.local = 1;
<commit_msg>Fixing SF# 1508561 -- errors in jmod.mapper when calling the /clear message<commit_after>/*
 * Jamoma Mapping Manager
 * Tim Place
 * Copyright © 2006 Jamoma Development Group
 *
 * Input syntax:
 *	create mapping_name src_module/arg1/arg2/arg3 [optional algorithm] -> dst_module/arg1/arg2/arg3
 *	remove mapping_name
 *  modify mapping_name <message for algorithm>
 */

// GLOBALS
var mapping_names = new Array();
var mapping_sources = new Array();
var mapping_destinations = new Array();
var mapping_algorithms = new Array();

// SETUP
function setup()
{
	// set up assistance strings
	setinletassist(0, "create, remove, modify");
	setoutletassist(0, "connect to a thispatcher object");
}
setup.local = 1;
setup();

// INIT
function loadbang()
{
	//outlet(0, "script", "new", "mapping_object_r", "newex",0, 0, 200, 196617, "jcom.receive", "jcom.remote.module.to");
	//outlet(0, "script", "new", "mapping_object_s", "newex",0, 1000, 200, 196617, "jcom.send", "jcom.remote.module.from");
}

// CREATE
function create()
{
	// 0. Find the entry number for this new mapping
	var entry = 0;
	if(mapping_names){
		entry = mapping_names.length;
	}

	// 1. Error Checking
	if(arguments.length < 4){
		post("ERROR jmod.mappings: create requires at least 4 arguments (name, src, optional algorithm, arrow, dst) in order to make a mapping");post();
		return;
	}
	var arrow = arguments[arguments.length-2];
	if(arrow != '->'){
		post("ERROR jmod.mappings: create requires an arrow");post();
		return;
	}
	var name = arguments[0];
	for(var i=0; i < entry; i++){
		if(name == mapping_names[i]){
			post("ERROR jmod.mappings: mapping_name already exists, cannot create mapping");post();
			return;
		}
	}

	// 2. Record Keeping
	var src = arguments[1];
	var dst = arguments[arguments.length-1];
	var algo = null;
	if(arguments.length > 4){
		mapping_algorithms[entry] = new Array();
		for(var i=2; i < arguments.length-2; i++){
			mapping_algorithms[entry].push(arguments[i]);
		}
	}
	else{
		mapping_algorithms[entry] = null;
	}
	mapping_names[entry] = name;
	mapping_sources[entry] = src;
	mapping_destinations[entry] = dst;

	// 3. Finally Script the Patch...
//	outlet(0, "script", "new", "mapping_object_src_"+entry, "newex",50, (entry+1)*70, 200, 196617, "jcom.receive", "/jmod_from"+mapping_sources[entry]);
//	outlet(0, "script", "new", "mapping_object_dst_"+entry, "newex",50, (entry+1)*70+40, 200, 196617, "jcom.send", "/jmod_to"+mapping_destinations[entry]);
	outlet(0, "script", "new", "mapping_object_src_"+entry, "newex",50, (entry+1)*100, 200, 196617, "jcom.receive", "jcom.remote.module.from");
	outlet(0, "script", "new", "mapping_object_dst_"+entry, "newex",50, (entry+1)*100+80, 200, 196617, "jcom.send", "jcom.remote.module.to");
	outlet(0, "script", "new", "mapping_object_route_"+entry, "newex", 50, (entry+1)*100+20, 200, 196617, "route", mapping_sources[entry]);
	outlet(0, "script", "new", "mapping_object_prepend_"+entry, "newex", 50, (entry+1)*100+60, 200, 196617, "prepend", mapping_destinations[entry]);
	//outlet(0, "script", "connect", "mapping_object_r", 0, "mapping_object_osc_"+entry, 0);
	//outlet(0, "script", "connect", "mapping_object_dst_"+entry, 0, "mapping_object_s", 0);

	if(mapping_algorithms[entry] == null){
		outlet(0, "script", "connect", "mapping_object_src_"+entry, 0, "mapping_object_route_"+entry, 0);
		outlet(0, "script", "connect", "mapping_object_route_"+entry, 0, "mapping_object_prepend_"+entry, 0);
		outlet(0, "script", "connect", "mapping_object_prepend_"+entry, 0, "mapping_object_dst_"+entry, 0);
	}
	else{
		outlet(0, "script", "new", "mapping_object_alg_"+entry, "newex",50, (entry+1)*100+40, 200, 196617, mapping_algorithms[entry]);
		outlet(0, "script", "connect", "mapping_object_src_"+entry, 0, "mapping_object_route_"+entry, 0);
		outlet(0, "script", "connect", "mapping_object_route_"+entry, 0, "mapping_object_alg_"+entry, 0);
		outlet(0, "script", "connect", "mapping_object_alg_"+entry, 0, "mapping_object_prepend_"+entry, 0);
		outlet(0, "script", "connect", "mapping_object_prepend_"+entry, 0, "mapping_object_dst_"+entry, 0);
	}
}

// DELETE
function remove(mapping_name)
{
	if(mapping_name == null)
		return 0;

	// first, find the index number of the named mapping
	if(mapping_names.length == 0){
		post("ERROR jmod.mappings: no such mapping to remove!"); post();
		return 0;
	}
	var entry = getindex(mapping_name);

	// second, delete all of the objects that are associated with this mapping
	outlet(0, "script", "delete", "mapping_object_src_"+entry);
	outlet(0, "script", "delete", "mapping_object_dst_"+entry);
	if(mapping_algorithms[entry] != null){
		outlet(0, "script", "delete", "mapping_object_alg_"+entry);
	}

	// third, remove the entry for the mapping from the array
	mapping_names[entry] = null;
	mapping_sources[entry] = null;
	mapping_algorithms[entry] = null;
	mapping_destinations[entry] = null;

	return 1;
}

// MODIFY
// send a message to the algorithm to change its behavior
function modify()
{
	var entry = getindex(arguments[0]);
	var args = new Array();
	for(var i=1; i<arguments.length; i++){
		args[i-1] = arguments[i];
	}
	outlet(0, "script", "send", "mapping_object_alg_"+entry, args);
}

// CLEAR - erases all mappings
function clear()
{
	var end = mapping_names.length;

	for(var i=end-1; i>=0; i--){
		remove(mapping_names[i]);
	}
	while(mapping_names.pop());
	while(mapping_sources.pop());
	while(mapping_destinations.pop());
	while(mapping_algorithms.pop());
}

// Private method used by the others for finding the index number associated with a name
function getindex(mapping_name)
{
	var entry;
	for(var i=0; i<mapping_names.length; i++){
		if(mapping_name == mapping_names[i]){
			entry = i;
		}
	}
	return entry;
}
getindex.local = 1;
<|endoftext|>


<commit_before><commit_msg>JSON.stringify(process.config, null, 4) & format output  json object<commit_after><|endoftext|>


<commit_before>document.addEventListener('DOMContentLoaded', function() {

    var

    handleKey = function(event) {
        switch (event.keyCode) {
        case 39: // right arrow
        case 13: // Enter
        case 32: // space
        case 34: // PgDn
            nextSlide();
            event.preventDefault();
            break;

        case 37: // left arrow
        case 8: // Backspace
        case 33: // PgUp
            prevSlide();
            event.preventDefault();
            break;
        }
    },

    handleUpdateSlides = function(slide_index, prev_slide, cur_slide, next_slide) {
        document.querySelector('#cur_slide_num').innerHTML = Number(slide_index) + 1;

        // make sure we have a previous and next slide to show;
        // if not add dummy placeholders
        if (!prev_slide) {
            prev_slide = '

';
        }
        if (!next_slide) {
            next_slide = '

';
        }

        document.querySelector('#slide_container').innerHTML =  prev_slide + cur_slide + next_slide;

        // Copy the presenter notes into place
        document.querySelector('#presenter_notes').innerHTML = $('article.current').find('div.admonition').html();

        var slides = document.querySelector('section.slides > article');
        for (var i=0; i < slides.length; i++) {

        }
    },

    handleMessage = function(e) {
        switch (e.data.command) {
        case 'num_slides':
            document.querySelector('#num_slides').innerHTML = e.data.content;
            break;
        case 'cur_slide':
            handleUpdateSlides(e.data.content, e.data.prev_slide, e.data.slide, e.data.next_slide);
            break;
        }
    },

    nextSlide = function(e) {
        if (e) {
            e.preventDefault();
        }
        window.opener.postMessage({command: 'nextSlide'}, '*');
    },

    prevSlide = function(e) {
        if (e) {
            e.preventDefault();
        }

        window.opener.postMessage({command: 'prevSlide'}, '*');
    },

    init = function(e) {
        window.addEventListener('message', handleMessage, false);
        document.addEventListener('keydown', handleKey, false);

        document.querySelector('#next').addEventListener('click', nextSlide);
        document.querySelector('#prev').addEventListener('click', prevSlide);

        window.opener.postMessage({command: 'register'}, '*');

    };

    init();

 }, false);
<commit_msg>Updated presenter notes to handling to only collect note admonitions<commit_after>document.addEventListener('DOMContentLoaded', function() {

    var

    handleKey = function(event) {
        switch (event.keyCode) {
        case 39: // right arrow
        case 13: // Enter
        case 32: // space
        case 34: // PgDn
            nextSlide();
            event.preventDefault();
            break;

        case 37: // left arrow
        case 8: // Backspace
        case 33: // PgUp
            prevSlide();
            event.preventDefault();
            break;
        }
    },

    handleUpdateSlides = function(slide_index, prev_slide, cur_slide, next_slide) {
        document.querySelector('#cur_slide_num').innerHTML = Number(slide_index) + 1;

        // make sure we have a previous and next slide to show;
        // if not add dummy placeholders
        if (!prev_slide) {
            prev_slide = '

';
        }
        if (!next_slide) {
            next_slide = '

';
        }

        document.querySelector('#slide_container').innerHTML =  prev_slide + cur_slide + next_slide;

        // Copy the presenter notes into place
        $('#presenter_notes').empty();
        $('article.current').find('div.admonition.note').each(
            function(i, node) {
                $('#presenter_notes').append($(node).html());
            }
        );

        var slides = document.querySelector('section.slides > article');
        for (var i=0; i < slides.length; i++) {

        }
    },

    handleMessage = function(e) {
        switch (e.data.command) {
        case 'num_slides':
            document.querySelector('#num_slides').innerHTML = e.data.content;
            break;
        case 'cur_slide':
            handleUpdateSlides(e.data.content, e.data.prev_slide, e.data.slide, e.data.next_slide);
            break;
        }
    },

    nextSlide = function(e) {
        if (e) {
            e.preventDefault();
        }
        window.opener.postMessage({command: 'nextSlide'}, '*');
    },

    prevSlide = function(e) {
        if (e) {
            e.preventDefault();
        }

        window.opener.postMessage({command: 'prevSlide'}, '*');
    },

    init = function(e) {
        window.addEventListener('message', handleMessage, false);
        document.addEventListener('keydown', handleKey, false);

        document.querySelector('#next').addEventListener('click', nextSlide);
        document.querySelector('#prev').addEventListener('click', prevSlide);

        window.opener.postMessage({command: 'register'}, '*');

    };

    init();

 }, false);
<|endoftext|>


<commit_before>var QT = (function (qt) {

    //#region Dependencies check

    qt.resources = {
        nojQuery: "jQuery was not found. Please ensure jQuery is referenced before the QuantumTunnel.Core.js file."
    };

    //#endregion

    //#region Dependencies check

    function printMessage(msg) {
        if (console && console.log) {
            console.log("QT : ", msg);
        } else {
            alert("QT info : ", msg);
        }
    };

    if (typeof ($) !== "function") {
        throw new Error(qt.resources.nojQuery);
    }

    //#endregion

    //#region init

    var qTag = $("script[quantum-tunnel]");

    //#endregion

    //#region private helpers

    function getCamelCase(str) {
        return str.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
    }

    function parseAttribute(value) {
        if (!value) return null;
        if (value === "true" || value === "false") return /^true$/i.test(value);
        if (!isNaN(value)) return parseFloat(value);
        return value;
    }

    //#endregion

    //#region public helpers

    qt.logConnection = function (msg) {
        if (qt.config.logConnectionEvents) printMessage(msg);
    };

    qt.logInternal = function (msg) {
        if (qt.config.logInternalEvents) printMessage(msg);
    };

    qt.logBroadcasting = function (msg) {
        if (qt.config.logBroadcastingEvents) printMessage(msg);
    };

    qt.logListening = function (msg) {
        if (qt.config.logListeningEvents) printMessage(msg);
    };

    qt.logError = function (err) {
        if (qt.config.logErrors) printError(err);
    };

    //#endregion

    //#region default config

    qt.config = {
        logErrors: true,
        logConnectionEvents: true,
        logInternalEvents: true,
        logBroadcastingEvents: true,
        logListeningEvents: true,

        init: true
    };

    //#endregion

    //#region config setters

    $.each(qTag.get(0).attributes, function (i, attrib) {
        try {
            var key = getCamelCase(attrib.name);
            var value = parseAttribute(attrib.value);
            qt.logInternal("setting attr config : " + key + " = " + value);
            qt.config[key] = value;
        } catch (e) {
            qt.logError("setting attributes configs" + e);
        }
    });

    //#endregion

    qt.logInternal("QT Core initialized!");
    qt.logInternal(qt.config);

    return qt;
}(QT || {}));<commit_msg>improve printMessage<commit_after>var QT = (function (qt) {

    //#region resources

    qt.resources = {
        name: "Quantum Tunnel",
        shortName: "qt",
        nojQuery: "jQuery was not found. Please ensure jQuery is referenced before the QuantumTunnel.Core.js file."
    };

    //#endregion

    //#region Dependencies check

    function printMessage(isInfo, msg, data) {
        msg = qt.resources.name + " : " + msg;
        if (typeof (window.console) === "undefined") return;

        if (window.console.debug && isInfo) {
            if (data) {
                window.console.debug(msg, data);
            } else {
                window.console.debug(msg);
            }
        } else if (window.console.error && !isInfo) {
            if (data) {
                window.console.error(msg, data);
            } else {
                window.console.error(msg);
            }
        } else if (window.console.log) {
            if (data) {
                window.console.log(msg, data);
            } else {
                window.console.log(msg);
            }
        }
    };

    if (typeof ($) !== "function") {
        printMessage(false, qt.resources.nojQuery);
        return qt;
    }

    //#endregion

    //#region init

    var qTag = $("script[quantum-tunnel]");

    //#endregion

    //#region private helpers

    function getCamelCase(str) {
        return str.replace(/-([a-z])/g, function (g) { return g[1].toUpperCase(); });
    }

    function parseAttribute(value) {
        if (!value) return null;
        if (value === "true" || value === "false") return /^true$/i.test(value);
        if (!isNaN(value)) return parseFloat(value);
        return value;
    }

    //#endregion

    //#region public helpers

    qt.logConnection = function (msg, data) {
        if (qt.config.logConnectionEvents) printMessage(true, msg, data);
    };

    qt.logInternal = function (msg, data) {
        if (qt.config.logInternalEvents) printMessage(true, msg, data);
    };

    qt.logBroadcasting = function (msg, data) {
        if (qt.config.logBroadcastingEvents) printMessage(true, msg, data);
    };

    qt.logListening = function (msg, data) {
        if (qt.config.logListeningEvents) printMessage(true, msg, data);
    };

    qt.logError = function (err, data) {
        if (qt.config.logErrors) printMessage(false, err, data);
    };

    //#endregion

    //#region default config

    qt.config = {
        logErrors: true,
        logConnectionEvents: true,
        logInternalEvents: true,
        logBroadcastingEvents: true,
        logListeningEvents: true,

        init: true
    };

    //#endregion

    //#region config setters

    $.each(qTag.get(0).attributes, function (i, attrib) {
        try {
            var key = getCamelCase(attrib.name);
            var value = parseAttribute(attrib.value);
            qt.logInternal("setting attr config : " + key + " = " + value);
            qt.config[key] = value;
        } catch (e) {
            qt.logError("setting attributes configs" + e);
        }
    });

    //#endregion

    qt.logInternal("QT Core initialized with configs", qt.config);
    return qt;
}(QT || {}));<|endoftext|>


<commit_before>import $ from 'jquery';

import { wrap } from '@girder/core/utilities/PluginUtils';
import { restRequest } from '@girder/core/rest';
import AccessWidget from '@girder/core/views/widgets/AccessWidget';
import HierarchyWidget from '@girder/core/views/widgets/HierarchyWidget';

import AnnotationModel from '../models/AnnotationModel';

wrap(HierarchyWidget, 'initialize', function (initialize, settings) {
    initialize.call(this, settings);

    this.folderListView.on('g:folderClicked', () => {
        ownAnnotation(this, this.parentModel.id);
    });
});

wrap(HierarchyWidget, 'render', function (render) {
    render.call(this);

    if (this.parentModel.get('_modelType') === 'folder') {
        ownAnnotation(this, this.parentModel.id);
    }
});

function ownAnnotation(root, folderId) {
    restRequest({
        type: 'GET',
        url: 'annotation/folder/' + folderId + '/present',
        data: {
            recurse: true
        }
    }).done((ownsAnnot) => {
        if (ownsAnnot) {
            addAccessControl(root);
        }
    });
}

function addAccessControl(root) {
    if (root.$('.g-edit-annotation-access').length === 0) {
        if (root.$('.g-folder-actions-menu > .divider').length > 0) {
            root.$('.g-folder-actions-menu > .divider').before(
                '
' +
                    '' +
                        '' +
                        'Annotation access control' +
                    '' +
                '
'
            );
        } else {
            root.$('.g-folder-actions-menu > .dropdown-header').after(
                '
' +
                    '' +
                        '' +
                        'Annotation access control' +
                    '' +
                '
' +
                '
'
            );
        }
        root.events['click .g-edit-annotation-access'] = editAnnotAccess;
        root.delegateEvents();
    }
}

function editAnnotAccess() {
    restRequest({
        type: 'GET',
        url: 'annotation/folder/' + this.parentModel.get('_id'),
        data: {
            recurse: true,
            limit: 1
        }
    }).done((resp) => {
        const model = new AnnotationModel(resp[0]);
        model.get('annotation').name = 'Your Annotations';
        model.save = () => {};
        model.updateAccess = (settings) => {
            const access = {
                access: model.get('access'),
                public: model.get('public'),
                publicFlags: model.get('publicFlags')
            };
            const defaultUpdateModel = new AnnotationModel();
            defaultUpdateModel.id = this.parentModel.get('_id');
            defaultUpdateModel.altUrl = 'annotation/folder';
            defaultUpdateModel.set(access);
            defaultUpdateModel.updateAccess(settings);
            model.trigger('g:accessListSaved');
        };
        model.fetchAccess(true)
            .done(() => {
                AccessWidget({
                    el: $('#g-dialog-container'),
                    modelType: 'annotation',
                    model,
                    hideRecurseOption: false,
                    parentView: this
                });
            });
    });
}

export default HierarchyWidget;
<commit_msg>Fix issue from lint fix<commit_after>import $ from 'jquery';

import { wrap } from '@girder/core/utilities/PluginUtils';
import { restRequest } from '@girder/core/rest';
import AccessWidget from '@girder/core/views/widgets/AccessWidget';
import HierarchyWidget from '@girder/core/views/widgets/HierarchyWidget';

import AnnotationModel from '../models/AnnotationModel';

wrap(HierarchyWidget, 'initialize', function (initialize, settings) {
    initialize.call(this, settings);

    this.folderListView.on('g:folderClicked', () => {
        ownAnnotation(this, this.parentModel.id);
    });
});

wrap(HierarchyWidget, 'render', function (render) {
    render.call(this);

    if (this.parentModel.get('_modelType') === 'folder') {
        ownAnnotation(this, this.parentModel.id);
    }
});

function ownAnnotation(root, folderId) {
    restRequest({
        type: 'GET',
        url: 'annotation/folder/' + folderId + '/present',
        data: {
            recurse: true
        }
    }).done((ownsAnnot) => {
        if (ownsAnnot) {
            addAccessControl(root);
        }
    });
}

function addAccessControl(root) {
    if (root.$('.g-edit-annotation-access').length === 0) {
        if (root.$('.g-folder-actions-menu > .divider').length > 0) {
            root.$('.g-folder-actions-menu > .divider').before(
                '
' +
                    '' +
                        '' +
                        'Annotation access control' +
                    '' +
                '
'
            );
        } else {
            root.$('.g-folder-actions-menu > .dropdown-header').after(
                '
' +
                    '' +
                        '' +
                        'Annotation access control' +
                    '' +
                '
' +
                '
'
            );
        }
        root.events['click .g-edit-annotation-access'] = editAnnotAccess;
        root.delegateEvents();
    }
}

function editAnnotAccess() {
    restRequest({
        type: 'GET',
        url: 'annotation/folder/' + this.parentModel.get('_id'),
        data: {
            recurse: true,
            limit: 1
        }
    }).done((resp) => {
        const model = new AnnotationModel(resp[0]);
        model.get('annotation').name = 'Your Annotations';
        model.save = () => {};
        model.updateAccess = (settings) => {
            const access = {
                access: model.get('access'),
                public: model.get('public'),
                publicFlags: model.get('publicFlags')
            };
            const defaultUpdateModel = new AnnotationModel();
            defaultUpdateModel.id = this.parentModel.get('_id');
            defaultUpdateModel.altUrl = 'annotation/folder';
            defaultUpdateModel.set(access);
            defaultUpdateModel.updateAccess(settings);
            model.trigger('g:accessListSaved');
        };
        model.fetchAccess(true)
            .done(() => {
                new AccessWidget({// eslint-disable-line no-new
                    el: $('#g-dialog-container'),
                    modelType: 'annotation',
                    model,
                    hideRecurseOption: false,
                    parentView: this
                });
            });
    });
}

export default HierarchyWidget;
<|endoftext|>


<commit_before>/*global define*/
define([
        './defaultValue',
        './defined',
        './DeveloperError',
        './Math'
    ], function(
        defaultValue,
        defined,
        DeveloperError,
        CesiumMath) {
    "use strict";

    var factorial = CesiumMath.factorial;

    function calculateCoefficientTerm(x, zIndices, xTable, derivOrder, termOrder, reservedIndices) {
        var result = 0;
        var reserved;
        var i;
        var j;

        if (derivOrder > 0) {
            for (i = 0; i < termOrder; i++) {
                reserved = false;
                for (j = 0; j < reservedIndices.length && !reserved; j++) {
                    if (i === reservedIndices[j]) {
                        reserved = true;
                    }
                }

                if (!reserved) {
                    reservedIndices.push(i);
                    result += calculateCoefficientTerm(x, zIndices, xTable, derivOrder - 1, termOrder, reservedIndices);
                    reservedIndices.splice(reservedIndices.length - 1, 1);
                }
            }

            return result;
        }

        result = 1;
        for (i = 0; i < termOrder; i++) {
            reserved = false;
            for (j = 0; j < reservedIndices.length && !reserved; j++) {
                if (i === reservedIndices[j]) {
                    reserved = true;
                }
            }

            if (!reserved) {
                result *= x - xTable[zIndices[i]];
            }
        }

        return result;
    }

    /**
     * An {@link InterpolationAlgorithm} for performing Hermite interpolation.
     * @exports HermitePolynomialApproximation
     */
    var HermitePolynomialApproximation = {
        type : 'Hermite'
    };

    /**
     * Given the desired degree, returns the number of data points required for interpolation.
     *
     * @param {Number} degree The desired degree of interpolation.
     * @param {Number} [inputOrder=0]  The order of the inputs (0 means just the data, 1 means the data and its derivative, etc).
     * @returns The number of required data points needed for the desired degree of interpolation.
     * @exception {DeveloperError} degree must be 0 or greater.
     * @exception {DeveloperError} inputOrder must be 0 or greater.
     */
    HermitePolynomialApproximation.getRequiredDataPoints = function(degree, inputOrder) {
        inputOrder = defaultValue(inputOrder, 0);

        //>>includeStart('debug', pragmas.debug);
        if (!defined(degree)) {
            throw new DeveloperError('degree is required.');
        }
        if (degree < 0) {
            throw new DeveloperError('degree must be 0 or greater.');
        }
        if (inputOrder < 0) {
            throw new DeveloperError('inputOrder must be 0 or greater.');
        }
        //>>includeEnd('debug');

        return Math.max(Math.floor((degree + 1) / (inputOrder + 1)), 2);
    };

    /**
     * Interpolates values using Hermite Polynomial Approximation.
     *
     * @param {Number} x The independent variable for which the dependent variables will be interpolated.
     * @param {Number[]} xTable The array of independent variables to use to interpolate.  The values
     * in this array must be in increasing order and the same value must not occur twice in the array.
     * @param {Number[]} yTable The array of dependent variables to use to interpolate.  For a set of three
     * dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
     * @param {Number} yStride The number of dependent variable values in yTable corresponding to
     * each independent variable value in xTable.
     * @param {Number[]} [result] An existing array into which to store the result.
     * @returns {Number[]} The array of interpolated values, or the result parameter if one was provided.
     */
    HermitePolynomialApproximation.interpolateOrderZero = function(x, xTable, yTable, yStride, result) {
        if (!defined(result)) {
            result = new Array(yStride);
        }

        var i;
        var j;
        var d;
        var s;
        var len;
        var index;
        var length = xTable.length;
        var coefficients = new Array(yStride);

        for (i = 0; i < yStride; i++) {
            result[i] = 0;

            var l = new Array(length);
            coefficients[i] = l;
            for (j = 0; j < length; j++) {
                l[j] = [];
            }
        }

        var zIndicesLength = length, zIndices = new Array(zIndicesLength);

        for (i = 0; i < zIndicesLength; i++) {
            zIndices[i] = i;
        }

        var highestNonZeroCoef = length - 1;
        for (s = 0; s < yStride; s++) {
            for (j = 0; j < zIndicesLength; j++) {
                index = zIndices[j] * yStride + s;
                coefficients[s][0].push(yTable[index]);
            }

            for (i = 1; i < zIndicesLength; i++) {
                var nonZeroCoefficients = false;
                for (j = 0; j < zIndicesLength - i; j++) {
                    var zj = xTable[zIndices[j]];
                    var zn = xTable[zIndices[j + i]];

                    var numerator;
                    if (zn - zj <= 0) {
                        index = zIndices[j] * yStride + yStride * i + s;
                        numerator = yTable[index];
                        coefficients[s][i].push(numerator / factorial(i));
                    } else {
                        numerator = (coefficients[s][i - 1][j + 1] - coefficients[s][i - 1][j]);
                        coefficients[s][i].push(numerator / (zn - zj));
                    }
                    nonZeroCoefficients = nonZeroCoefficients || (numerator !== 0);
                }

                if (!nonZeroCoefficients) {
                    highestNonZeroCoef = i - 1;
                }
            }
        }

        for (d = 0, len = 0; d <= len; d++) {
            for (i = d; i <= highestNonZeroCoef; i++) {
                var tempTerm = calculateCoefficientTerm(x, zIndices, xTable, d, i, []);
                for (s = 0; s < yStride; s++) {
                    var coeff = coefficients[s][i][0];
                    result[s + d * yStride] += coeff * tempTerm;
                }
            }
        }

        return result;
    };

    var arrayScratch = [];

    /**
     * Interpolates values using Hermite Polynomial Approximation.
     *
     * @param {Number} x The independent variable for which the dependent variables will be interpolated.
     * @param {Number[]} xTable The array of independent variables to use to interpolate.  The values
     * in this array must be in increasing order and the same value must not occur twice in the array.
     * @param {Number[]} yTable The array of dependent variables to use to interpolate.  For a set of three
     * dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
     * @param {Number} yStride The number of dependent variable values in yTable corresponding to
     * each independent variable value in xTable.
     * @param {Number} inputOrder The number of derivatives supplied for input.
     * @param {Number} outputOrder The number of derivatives desired for output.
     * @param {Number[]} [result] An existing array into which to store the result.
     *
     * @returns {Number[]} The array of interpolated values, or the result parameter if one was provided.
     */
    HermitePolynomialApproximation.interpolate = function(x, xTable, yTable, yStride, inputOrder, outputOrder, result) {
        var resultLength = yStride * (outputOrder + 1);
        if (!defined(result)) {
            result = new Array(resultLength);
        }
        for (var r = 0; r < resultLength; r++) {
            result[r] = 0;
        }

        var length = xTable.length;
        // The zIndices array holds copies of the addresses of the xTable values
        // in the range we're looking at. Even though this just holds information already
        // available in xTable this is a much more convenient format.
        var zIndices = new Array(length * (inputOrder + 1));
        for (var i = 0; i < length; i++) {
            for (var j = 0; j < (inputOrder + 1); j++) {
                zIndices[i * (inputOrder + 1) + j] = i;
            }
        }

        var zIndiceslength = zIndices.length;
        var coefficients = arrayScratch;
        var highestNonZeroCoef = fillCoefficientList(coefficients, zIndices, xTable, yTable, yStride, inputOrder);
        var reserviedIndices = [];

        var loopStop = Math.min(highestNonZeroCoef, outputOrder);
        for (var d = 0; d <= loopStop; d++) {
            for (i = d; i <= highestNonZeroCoef; i++) {
                reserviedIndices.length = 0;
                var tempTerm = calculateCoefficientTerm(x, zIndices, xTable, d, i, reserviedIndices);
                var dimTwo = Math.floor(i * (1 - i) / 2) + (zIndiceslength * i);

                for (var s = 0; s < yStride; s++) {
                    var dimOne = Math.floor(s * zIndiceslength * (zIndiceslength + 1) / 2);
                    var coef = coefficients[dimOne + dimTwo];
                    result[s + d * yStride] += coef * tempTerm;
                }
            }
        }

        return result;
    };

    function fillCoefficientList(coefficients, zIndices, xTable, yTable, yStride, inputOrder) {
        var j;
        var index;
        var highestNonZero = -1;
        var zIndiceslength = zIndices.length;

        for (var s = 0; s < yStride; s++) {
            var dimOne = Math.floor(s * zIndiceslength * (zIndiceslength + 1) / 2);

            for (j = 0; j < zIndiceslength; j++) {
                index = zIndices[j] * yStride * (inputOrder + 1) + s;
                coefficients[dimOne + j] = yTable[index];
            }

            for (var i = 1; i < zIndiceslength; i++) {
                var coefIndex = 0;
                var dimTwo = Math.floor(i * (1 - i) / 2) + (zIndiceslength * i);
                var nonZeroCoefficients = false;

                for (j = 0; j < zIndiceslength - i; j++) {
                    var zj = xTable[zIndices[j]];
                    var zn = xTable[zIndices[j + i]];

                    var numerator;
                    var coefficient;
                    if (zn - zj <= 0) {
                        index = zIndices[j] * yStride * (inputOrder + 1) + yStride * i + s;
                        numerator = yTable[index];
                        coefficient = (numerator / CesiumMath.factorial(i));
                        coefficients[dimOne + dimTwo + coefIndex] = coefficient;
                        coefIndex++;
                    } else {
                        var dimTwoMinusOne = Math.floor((i - 1) * (2 - i) / 2) + (zIndiceslength * (i - 1));
                        numerator = coefficients[dimOne + dimTwoMinusOne + j + 1] - coefficients[dimOne + dimTwoMinusOne + j];
                        coefficient = (numerator / (zn - zj));
                        coefficients[dimOne + dimTwo + coefIndex] = coefficient;
                        coefIndex++;
                    }
                    nonZeroCoefficients = nonZeroCoefficients || (numerator !== 0.0);
                }

                if (nonZeroCoefficients) {
                    highestNonZero = Math.max(highestNonZero, i);
                }
            }
        }

        return highestNonZero;
    }

    return HermitePolynomialApproximation;
});
<commit_msg>Move code to run outside loop.<commit_after>/*global define*/
define([
        './defaultValue',
        './defined',
        './DeveloperError',
        './Math'
    ], function(
        defaultValue,
        defined,
        DeveloperError,
        CesiumMath) {
    "use strict";

    var factorial = CesiumMath.factorial;

    function calculateCoefficientTerm(x, zIndices, xTable, derivOrder, termOrder, reservedIndices) {
        var result = 0;
        var reserved;
        var i;
        var j;

        if (derivOrder > 0) {
            for (i = 0; i < termOrder; i++) {
                reserved = false;
                for (j = 0; j < reservedIndices.length && !reserved; j++) {
                    if (i === reservedIndices[j]) {
                        reserved = true;
                    }
                }

                if (!reserved) {
                    reservedIndices.push(i);
                    result += calculateCoefficientTerm(x, zIndices, xTable, derivOrder - 1, termOrder, reservedIndices);
                    reservedIndices.splice(reservedIndices.length - 1, 1);
                }
            }

            return result;
        }

        result = 1;
        for (i = 0; i < termOrder; i++) {
            reserved = false;
            for (j = 0; j < reservedIndices.length && !reserved; j++) {
                if (i === reservedIndices[j]) {
                    reserved = true;
                }
            }

            if (!reserved) {
                result *= x - xTable[zIndices[i]];
            }
        }

        return result;
    }

    /**
     * An {@link InterpolationAlgorithm} for performing Hermite interpolation.
     * @exports HermitePolynomialApproximation
     */
    var HermitePolynomialApproximation = {
        type : 'Hermite'
    };

    /**
     * Given the desired degree, returns the number of data points required for interpolation.
     *
     * @param {Number} degree The desired degree of interpolation.
     * @param {Number} [inputOrder=0]  The order of the inputs (0 means just the data, 1 means the data and its derivative, etc).
     * @returns The number of required data points needed for the desired degree of interpolation.
     * @exception {DeveloperError} degree must be 0 or greater.
     * @exception {DeveloperError} inputOrder must be 0 or greater.
     */
    HermitePolynomialApproximation.getRequiredDataPoints = function(degree, inputOrder) {
        inputOrder = defaultValue(inputOrder, 0);

        //>>includeStart('debug', pragmas.debug);
        if (!defined(degree)) {
            throw new DeveloperError('degree is required.');
        }
        if (degree < 0) {
            throw new DeveloperError('degree must be 0 or greater.');
        }
        if (inputOrder < 0) {
            throw new DeveloperError('inputOrder must be 0 or greater.');
        }
        //>>includeEnd('debug');

        return Math.max(Math.floor((degree + 1) / (inputOrder + 1)), 2);
    };

    /**
     * Interpolates values using Hermite Polynomial Approximation.
     *
     * @param {Number} x The independent variable for which the dependent variables will be interpolated.
     * @param {Number[]} xTable The array of independent variables to use to interpolate.  The values
     * in this array must be in increasing order and the same value must not occur twice in the array.
     * @param {Number[]} yTable The array of dependent variables to use to interpolate.  For a set of three
     * dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
     * @param {Number} yStride The number of dependent variable values in yTable corresponding to
     * each independent variable value in xTable.
     * @param {Number[]} [result] An existing array into which to store the result.
     * @returns {Number[]} The array of interpolated values, or the result parameter if one was provided.
     */
    HermitePolynomialApproximation.interpolateOrderZero = function(x, xTable, yTable, yStride, result) {
        if (!defined(result)) {
            result = new Array(yStride);
        }

        var i;
        var j;
        var d;
        var s;
        var len;
        var index;
        var length = xTable.length;
        var coefficients = new Array(yStride);

        for (i = 0; i < yStride; i++) {
            result[i] = 0;

            var l = new Array(length);
            coefficients[i] = l;
            for (j = 0; j < length; j++) {
                l[j] = [];
            }
        }

        var zIndicesLength = length, zIndices = new Array(zIndicesLength);

        for (i = 0; i < zIndicesLength; i++) {
            zIndices[i] = i;
        }

        var highestNonZeroCoef = length - 1;
        for (s = 0; s < yStride; s++) {
            for (j = 0; j < zIndicesLength; j++) {
                index = zIndices[j] * yStride + s;
                coefficients[s][0].push(yTable[index]);
            }

            for (i = 1; i < zIndicesLength; i++) {
                var nonZeroCoefficients = false;
                for (j = 0; j < zIndicesLength - i; j++) {
                    var zj = xTable[zIndices[j]];
                    var zn = xTable[zIndices[j + i]];

                    var numerator;
                    if (zn - zj <= 0) {
                        index = zIndices[j] * yStride + yStride * i + s;
                        numerator = yTable[index];
                        coefficients[s][i].push(numerator / factorial(i));
                    } else {
                        numerator = (coefficients[s][i - 1][j + 1] - coefficients[s][i - 1][j]);
                        coefficients[s][i].push(numerator / (zn - zj));
                    }
                    nonZeroCoefficients = nonZeroCoefficients || (numerator !== 0);
                }

                if (!nonZeroCoefficients) {
                    highestNonZeroCoef = i - 1;
                }
            }
        }

        for (d = 0, len = 0; d <= len; d++) {
            for (i = d; i <= highestNonZeroCoef; i++) {
                var tempTerm = calculateCoefficientTerm(x, zIndices, xTable, d, i, []);
                for (s = 0; s < yStride; s++) {
                    var coeff = coefficients[s][i][0];
                    result[s + d * yStride] += coeff * tempTerm;
                }
            }
        }

        return result;
    };

    var arrayScratch = [];

    /**
     * Interpolates values using Hermite Polynomial Approximation.
     *
     * @param {Number} x The independent variable for which the dependent variables will be interpolated.
     * @param {Number[]} xTable The array of independent variables to use to interpolate.  The values
     * in this array must be in increasing order and the same value must not occur twice in the array.
     * @param {Number[]} yTable The array of dependent variables to use to interpolate.  For a set of three
     * dependent values (p,q,w) at time 1 and time 2 this should be as follows: {p1, q1, w1, p2, q2, w2}.
     * @param {Number} yStride The number of dependent variable values in yTable corresponding to
     * each independent variable value in xTable.
     * @param {Number} inputOrder The number of derivatives supplied for input.
     * @param {Number} outputOrder The number of derivatives desired for output.
     * @param {Number[]} [result] An existing array into which to store the result.
     *
     * @returns {Number[]} The array of interpolated values, or the result parameter if one was provided.
     */
    HermitePolynomialApproximation.interpolate = function(x, xTable, yTable, yStride, inputOrder, outputOrder, result) {
        var resultLength = yStride * (outputOrder + 1);
        if (!defined(result)) {
            result = new Array(resultLength);
        }
        for (var r = 0; r < resultLength; r++) {
            result[r] = 0;
        }

        var length = xTable.length;
        // The zIndices array holds copies of the addresses of the xTable values
        // in the range we're looking at. Even though this just holds information already
        // available in xTable this is a much more convenient format.
        var zIndices = new Array(length * (inputOrder + 1));
        for (var i = 0; i < length; i++) {
            for (var j = 0; j < (inputOrder + 1); j++) {
                zIndices[i * (inputOrder + 1) + j] = i;
            }
        }

        var zIndiceslength = zIndices.length;
        var coefficients = arrayScratch;
        var highestNonZeroCoef = fillCoefficientList(coefficients, zIndices, xTable, yTable, yStride, inputOrder);
        var reserviedIndices = [];

        var tmp = zIndiceslength * (zIndiceslength + 1) / 2;
        var loopStop = Math.min(highestNonZeroCoef, outputOrder);
        for (var d = 0; d <= loopStop; d++) {
            for (i = d; i <= highestNonZeroCoef; i++) {
                reserviedIndices.length = 0;
                var tempTerm = calculateCoefficientTerm(x, zIndices, xTable, d, i, reserviedIndices);
                var dimTwo = Math.floor(i * (1 - i) / 2) + (zIndiceslength * i);

                for (var s = 0; s < yStride; s++) {
                    var dimOne = Math.floor(s * tmp);
                    var coef = coefficients[dimOne + dimTwo];
                    result[s + d * yStride] += coef * tempTerm;
                }
            }
        }

        return result;
    };

    function fillCoefficientList(coefficients, zIndices, xTable, yTable, yStride, inputOrder) {
        var j;
        var index;
        var highestNonZero = -1;
        var zIndiceslength = zIndices.length;
        var tmp = zIndiceslength * (zIndiceslength + 1) / 2;

        for (var s = 0; s < yStride; s++) {
            var dimOne = Math.floor(s * tmp);

            for (j = 0; j < zIndiceslength; j++) {
                index = zIndices[j] * yStride * (inputOrder + 1) + s;
                coefficients[dimOne + j] = yTable[index];
            }

            for (var i = 1; i < zIndiceslength; i++) {
                var coefIndex = 0;
                var dimTwo = Math.floor(i * (1 - i) / 2) + (zIndiceslength * i);
                var nonZeroCoefficients = false;

                for (j = 0; j < zIndiceslength - i; j++) {
                    var zj = xTable[zIndices[j]];
                    var zn = xTable[zIndices[j + i]];

                    var numerator;
                    var coefficient;
                    if (zn - zj <= 0) {
                        index = zIndices[j] * yStride * (inputOrder + 1) + yStride * i + s;
                        numerator = yTable[index];
                        coefficient = (numerator / CesiumMath.factorial(i));
                        coefficients[dimOne + dimTwo + coefIndex] = coefficient;
                        coefIndex++;
                    } else {
                        var dimTwoMinusOne = Math.floor((i - 1) * (2 - i) / 2) + (zIndiceslength * (i - 1));
                        numerator = coefficients[dimOne + dimTwoMinusOne + j + 1] - coefficients[dimOne + dimTwoMinusOne + j];
                        coefficient = (numerator / (zn - zj));
                        coefficients[dimOne + dimTwo + coefIndex] = coefficient;
                        coefIndex++;
                    }
                    nonZeroCoefficients = nonZeroCoefficients || (numerator !== 0.0);
                }

                if (nonZeroCoefficients) {
                    highestNonZero = Math.max(highestNonZero, i);
                }
            }
        }

        return highestNonZero;
    }

    return HermitePolynomialApproximation;
});
<|endoftext|>


<commit_before>import { put, takeLatest, call, select } from 'redux-saga/effects';
import * as types from 'builder/actions/actionTypes';
import { teamValidationFetcher as fetcher } from 'builder/validations/requests/fetchers';
import { validateTeamSuccess } from 'builder/validations/actions';

import { selectAssets } from 'builder/assets/selectors';
import { selectChosenAffinities } from 'builder/affinities/selectors';
import { selectBaseRank } from 'builder/sponsors/selectors';
import { selectUnits } from 'builder/units/selectors';

function fetch(params) {
   return fetcher.fetch(params);
}

function* requestValidation(action) {
   const response = yield call(fetch, action.params);
   yield put(validateTeamSuccess(response.payload));
}

function* build(action) {
   yield put({ type: types.SET_BASE_RANK, payload: action.payload.baseRank });
   yield put({ type: types.SET_RANK, payload: action.payload.currentRank });
   yield put({ type: types.SET_TEAM_VALUE, payload: action.payload.valoration });
}

function* validateTeam() {
   const assets = yield select(selectAssets);
   const affinities = yield select(selectChosenAffinities);
   const units = yield select(selectUnits);
   const baseRank = yield select(selectBaseRank);

   const params = { affinities, units, baseRank, ...assets };
   yield call(requestValidation, { params });
}

export const validationSagas = [
   takeLatest(types.SET_CHEERLEADERS, validateTeam),
   takeLatest(types.SET_COACHING_DICE, validateTeam),
   takeLatest(types.SET_MEDIBOT, validateTeam),
   takeLatest(types.SET_NASTY_SURPRISE_CARD, validateTeam),
   takeLatest(types.SET_SPECIAL_MOVE_CARD, validateTeam),
   takeLatest(types.SET_WAGER, validateTeam),
   takeLatest(types.ADD_TEAM_UNIT, validateTeam),
   takeLatest(types.REMOVE_TEAM_UNIT, validateTeam),
   takeLatest(types.REQUEST_SUCCESS_TEAM_VALIDATION, build)
];
<commit_msg>Fixed validation parameters<commit_after>import { put, takeLatest, call, select } from 'redux-saga/effects';
import * as types from 'builder/actions/actionTypes';
import { teamValidationFetcher as fetcher } from 'builder/validations/requests/fetchers';
import { validateTeamSuccess } from 'builder/validations/actions';

import { selectAssets } from 'builder/assets/selectors';
import { selectChosenAffinities } from 'builder/affinities/selectors';
import { selectBaseRank } from 'builder/sponsors/selectors';
import { selectUnits } from 'builder/units/selectors';

function fetch(params) {
   return fetcher.fetch(params);
}

function* requestValidation(action) {
   const response = yield call(fetch, action.params);
   yield put(validateTeamSuccess(response.payload));
}

function* build(action) {
   yield put({ type: types.SET_BASE_RANK, payload: action.payload.baseRank });
   yield put({ type: types.SET_RANK, payload: action.payload.currentRank });
   yield put({ type: types.SET_TEAM_VALUE, payload: action.payload.totalCost });
}

function* validateTeam() {
   const assets = yield select(selectAssets);
   const affinities = yield select(selectChosenAffinities);
   const teamPlayers = yield select(selectUnits);
   const baseRank = yield select(selectBaseRank);

   const params = { affinities, teamPlayers, baseRank, ...assets };
   yield call(requestValidation, { params });
}

export const validationSagas = [
   takeLatest(types.SET_CHEERLEADERS, validateTeam),
   takeLatest(types.SET_COACHING_DICE, validateTeam),
   takeLatest(types.SET_MEDIBOT, validateTeam),
   takeLatest(types.SET_NASTY_SURPRISE_CARD, validateTeam),
   takeLatest(types.SET_SPECIAL_MOVE_CARD, validateTeam),
   takeLatest(types.SET_WAGER, validateTeam),
   takeLatest(types.ADD_TEAM_UNIT, validateTeam),
   takeLatest(types.REMOVE_TEAM_UNIT, validateTeam),
   takeLatest(types.REQUEST_SUCCESS_TEAM_VALIDATION, build)
];
<|endoftext|>


<commit_before>/*************************************************************************
## SnowballFight mini-game

### Description

This is a rough and ready prototype of a simple multi-player
shoot-em-up. To start a game with all players playing against one another...

    /js new Game_SnowballFight(60).start();

... this obviously works best if all of the players are in close
proximity within the same game world. Alternatively you can have team
matches...

    /js var redTeam = ['<player1>','<player2>',...etc]
    /js var blueTeam = ['<player3>','<player4>,...etc]
    /js var greenTeam = ['<player5>','<player6>,...etc]
    /js new Game_SnowballFight(60, {red: redTeam,blue: blueTeam,green: greenTeam}).start();

Or you can just have specific players play against each other...

    /js new Game_SnowballFight(60, ['player1','player2','player3']).start();

(where 'player1' etc are the names of actual players)

You specify the teams in the game as an object where each property's
name is a team name and each property's value is the list of players
on that team.  You specify the duration of the game (in seconds) You
kick off the game with the start() method.  I need to work on a
better in-game mechanism for players to choose teams and start the
game but this will do for now.

When the game starts, each player is put in survival mode and given
snowballs. The aim of the game is to hit players on opposing teams. If
you hit a player on your own team, you lose a point.

At the end of the game the scores for each team are broadcast and each
player returns to their previous mode of play (creative or
survival). Create a small arena with a couple of small buildings for
cover to make the game more fun.

***/

var bkGameMode = org.bukkit.GameMode,
  bkItemStack = org.bukkit.inventory.ItemStack,
  bkMaterial = org.bukkit.Material,
  bkSnowball = org.bukkit.entity.Snowball;

var _startGame = function( gameState ) {
  var i,
    teamName,
    team,
    player;

  // don't let game start if already in progress (wait for game to finish)
  if ( gameState.inProgress ) {
    return;
  }
  gameState.inProgress = true;
  // reset timer
  gameState.duration = gameState.originalDuration;
  // put all players in survival mode and give them each 200 snowballs
  // 64 snowballs for every 30 seconds should be more than enough
  for ( i = 10; i < gameState.duration; i += 10 ) {
    gameState.ammo.push( gameState.ammo[ 0 ] );
  }

  for ( teamName in gameState.teams ) {
    gameState.teamScores[teamName] = 0;
    team = gameState.teams[ teamName ];
    for ( i = 0; i < team.length; i++ ) {
      player = server.getPlayer( team[i] );
      gameState.savedModes[ player.name ] = player.gameMode;
      player.gameMode = bkGameMode.SURVIVAL;
      player.inventory.addItem( gameState.ammo );
    }
  }
};
/*
 end the game
 */
var _endGame = function( gameState ) {
  var scores = [],
    leaderBoard = [],
    tn,
    i,
    teamName,
    team,
    player,
    handlerList;

  leaderBoard  = [];
  for ( tn in gameState.teamScores){
    leaderBoard.push([tn,gameState.teamScores[tn]]);
  }
  leaderBoard.sort(function(a,b){ return b[1] - a[1];});

  for ( i = 0; i < leaderBoard.length; i++ ) {
    scores.push( 'Team ' + leaderBoard[i][0] + ' scored ' + leaderBoard[i][1] );
  }

  for ( teamName in gameState.teams ) {
    team = gameState.teams[teamName];
    for ( i = 0; i < team.length; i++ ) {
      // restore player's previous game mode and take back snowballs
      player = server.getPlayer( team[i] );
      player.gameMode = gameState.savedModes[ player.name ];
      player.inventory.removeItem( gameState.ammo );
      player.sendMessage( 'GAME OVER.' );
      player.sendMessage( scores );
    }
  }
  gameState.listener.unregister();
  gameState.inProgress = false;
};
/*
 get the team the player belongs to
 */
var _getTeam = function( player, pteams ) {
  var teamName,
    team,
    i;
  for ( teamName in pteams ) {
    team = pteams[ teamName ];
    for ( i = 0; i < team.length; i++ ) {
      if ( team[i] == player.name ) {
        return teamName;
      }
    }
  }
  return null;
};
/*
 construct a new game
 */
var createGame = function( duration, teams ) {
  var players,
    i,
    _snowBalls = new bkItemStack( bkMaterial.SNOW_BALL, 64 );

  var _gameState = {
    teams: teams,
    duration: duration,
    originalDuration: duration,
    inProgress: false,
    teamScores: {},
    listener: null,
    savedModes: {},
    ammo: [ _snowBalls ]
  };
  if ( typeof duration == 'undefined' ) {
    duration = 60;
  }
  if ( typeof teams == 'undefined' ) {
    /*
     wph 20130511 use all players
     */
    teams =  [];
    players = server.onlinePlayers;
    for ( i = 0; i < players.length; i++ ) {
      teams.push( players[i].name );
    }
  }
  //
  // allow for teams param to be either {red:['player1','player2'],blue:['player3']} or
  // ['player1','player2','player3'] if all players are against each other (no teams)
  //
  if ( teams instanceof Array ) {
    _gameState.teams = {};
    for ( i = 0;i < teams.length; i++ ) {
      _gameState.teams[ teams[i] ] = [ teams[i] ];
    }
  }
  /*
   this function is called every time a player is damaged by another entity/player
   */
  var _onSnowballHit = function( event ) {
    var snowball = event.damager;
    if ( !snowball || !( snowball instanceof bkSnowball ) ) {
      return;
    }
    var throwersTeam = _getTeam( snowball.shooter, _gameState.teams );
    var damageeTeam = _getTeam( event.entity, _gameState.teams);
    if ( !throwersTeam || !damageeTeam ) {
      return; // thrower/damagee wasn't in game
    }
    if ( throwersTeam != damageeTeam ) {
      _gameState.teamScores[ throwersTeam ]++;
    } else {
      _gameState.teamScores[ throwersTeam ]--;
    }
  };

  return {
    start: function( ) {
      _startGame( _gameState );
      _gameState.listener = events.entityDamageByEntity( _onSnowballHit );
      new java.lang.Thread( function( ) {
        while ( _gameState.duration-- ) {
          java.lang.Thread.sleep( 1000 ); // sleep 1,000 millisecs (1 second)
	}
        _endGame(_gameState);
      } ).start( );
    }
  };
};
exports.Game_SnowballFight = createGame;

<commit_msg>Delete SnowballFight.js<commit_after><|endoftext|>


<commit_before>'use strict';

var d           = require('d')
  , isGetter    = require('../utils/is-getter')
  , observePass = require('../utils/observe-pass-through')

  , defineProperties = Object.defineProperties
  , getPrototypeOf = Object.getPrototypeOf;

module.exports = function (descriptor, accessCollector) {
	defineProperties(descriptor, {
		_value_: d('', undefined),
		_resolveInner_: d(function () {
			if (!this._sKey_) return;
			if (this._reverse_) return this._reverse_.get(this.object);
			if (this.nested) {
				return this.object._getObject_(this._sKey_);
			}
			return this.hasOwnProperty('_value_') ? this._value_ :
					getPrototypeOf(this)._resolveInner_();
		}),
		_resolveValueValue_: d(function () {
			if (!this._sKey_) return;
			if (this.hasOwnProperty('_value_')) return this._value_;
			return getPrototypeOf(this)._resolveInner_();
		}),
		_resolveValue_: d(function (obj, sKey) {
			var value;
			if (this._sKey_) sKey = this._sKey_;
			if (this._reverse_) return this._reverse_.get(obj);
			if (this.nested) return obj._getObject_(sKey);
			value = this._resolveValueValue_();
			if (isGetter(value)) {
				if (this.multiple) return obj._resolveDynamicMultiple_(sKey, value);
				if (this.hasOwnProperty('__dynamicValues__')) {
					if (this.__dynamicValues__[sKey]) {
						return this.__dynamicValues__[sKey].resolvedValue;
					}
				}
				value = value.call(obj, observePass);
				if (value == null) return null;
				return this._normalizeValue_(value);
			}
			if (this.multiple) return obj._getMultiple_(sKey);
			if (value == null) return value;
			return this._normalizeValue_(value);
		}),
		_resolveValueGetter_: d(function () {
			var value;
			if (this._reverse_) return null;
			if (this.nested) return null;
			value = this._resolveValueValue_();
			if (isGetter(value)) return value;
			return null;
		}),
		_resolveLastEvent_: d(function (obj, sKey) {
			var property, current, value, accessed;
			if (this._sKey_) sKey = this._sKey_;
			if (this._reverse_) return this._reverse_.getLastEvent(obj, sKey);
			if (this.nested) {
				property = this._getCurrentDescriptor_('nested');
				return property ? property._lastOwnEvent_ : null;
			}
			if (this.multiple) {
				property = this._getCurrentDescriptor_('multiple');
				return property ? property._lastOwnEvent_ : null;
			}
			current = this;
			while (!current.hasOwnProperty('_value_')) {
				current = getPrototypeOf(current);
				if (!current._sKey_) break;
				if (current._reverse_) current._reverse_.getLastEvent(obj, sKey);
				if (current.nested) {
					property = current._getCurrentDescriptor_('nested');
					return property ? property._lastOwnEvent_ : null;
				}
			}
			value = current._value_;
			if (!isGetter(value)) return current._lastOwnEvent_;
			accessCollector.emit('register', accessed = []);
			value.call(obj, observePass);
			accessCollector.emit('unregister');
			if (!accessed.length) return current._lastOwnEvent_;
			return accessed.reduce(function (event, accessed) {
				var obj = accessed[0], next;
				next = obj._getCurrentDescriptor_(accessed[1]);
				if (!next) return event;
				next = next._lastEvent_;
				if (!next) return event;
				if (!event) return next;
				return (next.stamp > event.stamp) ? next : event;
			}, null);
		}),
		_resolveLastModified_: d(function (obj, sKey) {
			var event = this._resolveLastEvent_(obj, sKey);
			return event ? event.stamp : 0;
		}),
		_hasValue_: d(function (obj) {
			if (!this._sKey_) return false;
			if (this._reverse_) return this._reverse_.has(obj);
			if (this.nested) return true;
			if (this.multiple) return true;
			return (this._resolveValueValue_(obj, this._sKey_) !== undefined);
		}),
		_hasOwnValue_: d(function (obj) {
			if (!this._sKey_) return false;
			if (this._reverse_) return this._reverse_.has(obj);
			if (this.nested) return true;
			if (this.multiple) return true;
			if (this.object !== obj) return false;
			return this.hasOwnProperty('_value_') && (this._value_ !== undefined);
		}),
		_normalizeValue_: d(function (value) {
			return this.type.normalize(value, this);
		})
	});
};
<commit_msg>-- whitespace<commit_after>'use strict';

var d           = require('d')
  , isGetter    = require('../utils/is-getter')
  , observePass = require('../utils/observe-pass-through')

  , defineProperties = Object.defineProperties
  , getPrototypeOf = Object.getPrototypeOf;

module.exports = function (descriptor, accessCollector) {
	defineProperties(descriptor, {
		_value_: d('', undefined),
		_resolveInner_: d(function () {
			if (!this._sKey_) return;
			if (this._reverse_) return this._reverse_.get(this.object);
			if (this.nested) {
				return this.object._getObject_(this._sKey_);
			}
			return this.hasOwnProperty('_value_') ? this._value_ : getPrototypeOf(this)._resolveInner_();
		}),
		_resolveValueValue_: d(function () {
			if (!this._sKey_) return;
			if (this.hasOwnProperty('_value_')) return this._value_;
			return getPrototypeOf(this)._resolveInner_();
		}),
		_resolveValue_: d(function (obj, sKey) {
			var value;
			if (this._sKey_) sKey = this._sKey_;
			if (this._reverse_) return this._reverse_.get(obj);
			if (this.nested) return obj._getObject_(sKey);
			value = this._resolveValueValue_();
			if (isGetter(value)) {
				if (this.multiple) return obj._resolveDynamicMultiple_(sKey, value);
				if (this.hasOwnProperty('__dynamicValues__')) {
					if (this.__dynamicValues__[sKey]) {
						return this.__dynamicValues__[sKey].resolvedValue;
					}
				}
				value = value.call(obj, observePass);
				if (value == null) return null;
				return this._normalizeValue_(value);
			}
			if (this.multiple) return obj._getMultiple_(sKey);
			if (value == null) return value;
			return this._normalizeValue_(value);
		}),
		_resolveValueGetter_: d(function () {
			var value;
			if (this._reverse_) return null;
			if (this.nested) return null;
			value = this._resolveValueValue_();
			if (isGetter(value)) return value;
			return null;
		}),
		_resolveLastEvent_: d(function (obj, sKey) {
			var property, current, value, accessed;
			if (this._sKey_) sKey = this._sKey_;
			if (this._reverse_) return this._reverse_.getLastEvent(obj, sKey);
			if (this.nested) {
				property = this._getCurrentDescriptor_('nested');
				return property ? property._lastOwnEvent_ : null;
			}
			if (this.multiple) {
				property = this._getCurrentDescriptor_('multiple');
				return property ? property._lastOwnEvent_ : null;
			}
			current = this;
			while (!current.hasOwnProperty('_value_')) {
				current = getPrototypeOf(current);
				if (!current._sKey_) break;
				if (current._reverse_) current._reverse_.getLastEvent(obj, sKey);
				if (current.nested) {
					property = current._getCurrentDescriptor_('nested');
					return property ? property._lastOwnEvent_ : null;
				}
			}
			value = current._value_;
			if (!isGetter(value)) return current._lastOwnEvent_;
			accessCollector.emit('register', accessed = []);
			value.call(obj, observePass);
			accessCollector.emit('unregister');
			if (!accessed.length) return current._lastOwnEvent_;
			return accessed.reduce(function (event, accessed) {
				var obj = accessed[0], next;
				next = obj._getCurrentDescriptor_(accessed[1]);
				if (!next) return event;
				next = next._lastEvent_;
				if (!next) return event;
				if (!event) return next;
				return (next.stamp > event.stamp) ? next : event;
			}, null);
		}),
		_resolveLastModified_: d(function (obj, sKey) {
			var event = this._resolveLastEvent_(obj, sKey);
			return event ? event.stamp : 0;
		}),
		_hasValue_: d(function (obj) {
			if (!this._sKey_) return false;
			if (this._reverse_) return this._reverse_.has(obj);
			if (this.nested) return true;
			if (this.multiple) return true;
			return (this._resolveValueValue_(obj, this._sKey_) !== undefined);
		}),
		_hasOwnValue_: d(function (obj) {
			if (!this._sKey_) return false;
			if (this._reverse_) return this._reverse_.has(obj);
			if (this.nested) return true;
			if (this.multiple) return true;
			if (this.object !== obj) return false;
			return this.hasOwnProperty('_value_') && (this._value_ !== undefined);
		}),
		_normalizeValue_: d(function (value) {
			return this.type.normalize(value, this);
		})
	});
};
<|endoftext|>


<commit_before>(function(factory) {
    'use strict';
    require(['AbilianWidget', 'jquery'], factory);
}
 (function(Abilian, $) {
     'use strict';
     // multiple row widget
    function DynamicRowWidget(table, options) {
        var self = this;
        self.table = table;
        self.prefix = table.data('prefix');
        self.tbody = table.children("tbody");
        self.options = options;

        self.current_index = table.find("> tbody > tr").length;

        self.add_button = $("	");
        self.add_button.click(function(e) {
                                  self.addRow();
                                  e.preventDefault();
                              });

        self.minus_button = $("	");
        self.minus_button.click(function(e) {
                                    $(this).closest('tr').remove();
                                    e.preventDefault();
                                });

        table.find("> thead > tr").append(self.add_button);
        table.find("> tbody > tr").append(self.minus_button);

        self.template_row = table.find("tbody > tr:first").clone(true, true);
        self.template_row.find('input[data-short-name!="csrf_token"]').attr('value', '');
        self.template_row.find("textarea").text('');
    }

    DynamicRowWidget.prototype = {
        'addRow': function() {
            var self = this;
            var new_row = self.template_row.clone(true, true);
            new_row.find("input").each(
                function() {
                    var item  = $(this);
                    var shortName = item.data("shortName");
                    var name = self.prefix + '-' + self.current_index;
                    if (shortName) {
                        name =  name + '-' + shortName;
                    }
                    item.attr('name', name);
                    item.attr("id", name);
                });
            new_row.find("select").each(
                function() {
                    var item  = $(this);
                    var id_splitted = item.attr("id").split('-');

                    for (var i = 0; i < id_splitted.length; i++) {
                        if (!isNaN(id_splitted[i])){
                            id_splitted[i] = self.current_index
                        }
                    }
                    var name = id_splitted.join('-')
                    item.attr('name', name);
                    item.attr("id", name);
                }
            );
            self.tbody.append(new_row);
            new_row.find('.js-widget').each(Abilian.initJsWidget);
            self.current_index += 1;
        }
    };

    function dynamicRowWidget(params) {
        var table = $(this);
        return new DynamicRowWidget(table, params);
    }

    Abilian.registerWidgetCreator('dynamicRowWidget', dynamicRowWidget);

    $.fn.dynamicRowWidget = function(options) {
        var defaults = {};
        var opts = $.extend(defaults, options);
        return this.each(
            function() { dynamicRowWidget.bind(this)(opts); }
        );
    };

}));
<commit_msg>fix clone of checkboxes and radios<commit_after>(function(factory) {
    'use strict';
    require(['AbilianWidget', 'jquery'], factory);
}
 (function(Abilian, $) {
     'use strict';
     // multiple row widget
    function DynamicRowWidget(table, options) {
        var self = this;
        self.table = table;
        self.prefix = table.data('prefix');
        self.tbody = table.children("tbody");
        self.options = options;

        self.current_index = table.find("> tbody > tr").length;

        self.add_button = $("	");
        self.add_button.click(function(e) {
                                  self.addRow();
                                  e.preventDefault();
                              });

        self.minus_button = $("	");
        self.minus_button.click(function(e) {
                                    $(this).closest('tr').remove();
                                    e.preventDefault();
                                });

        table.find("> thead > tr").append(self.add_button);
        table.find("> tbody > tr").append(self.minus_button);

        self.templateRow = table.find("tbody > tr:first").clone(true, true);
        /* remove value except for specific controls that have constant (and
         * required) value
         */
        self.templateRow.find('input' +
                               '[type!="checkbox"]' +
                               '[type!="radio"]' +
                               '[data-short-name!="csrf_token"]')
            .attr('value', '');
        self.templateRow.find("textarea").text('');
    }

    DynamicRowWidget.prototype = {
        'addRow': function() {
            var self = this;
            var new_row = self.templateRow.clone(true, true);
            new_row.find("input").each(
                function() {
                    var item  = $(this);
                    var shortName = item.data("shortName");
                    var name = self.prefix + '-' + self.current_index;
                    if (shortName) {
                        name =  name + '-' + shortName;
                    }
                    item.attr('name', name);
                    item.attr("id", name);
                });
            new_row.find("select").each(
                function() {
                    var item  = $(this);
                    var id_splitted = item.attr("id").split('-');

                    for (var i = 0; i < id_splitted.length; i++) {
                        if (!isNaN(id_splitted[i])){
                            id_splitted[i] = self.current_index
                        }
                    }
                    var name = id_splitted.join('-')
                    item.attr('name', name);
                    item.attr("id", name);
                }
            );
            self.tbody.append(new_row);
            new_row.find('.js-widget').each(Abilian.initJsWidget);
            self.current_index += 1;
        }
    };

    function dynamicRowWidget(params) {
        var table = $(this);
        return new DynamicRowWidget(table, params);
    }

    Abilian.registerWidgetCreator('dynamicRowWidget', dynamicRowWidget);

    $.fn.dynamicRowWidget = function(options) {
        var defaults = {};
        var opts = $.extend(defaults, options);
        return this.each(
            function() { dynamicRowWidget.bind(this)(opts); }
        );
    };

}));
<|endoftext|>


<commit_before>class LeaguesRoute extends RcdMaterialRoute {
    constructor() {
        super({
            state: 'leagues',
            name: 'Leagues',
            //iconArea: new RcdImageIconArea(config.baseUrl + '/icons/leagues.svg').init()
        });
        this.layout = new LeaguesLayout().init();
    }

    init() {
        this.callback = (main) => {
            this.layout.refresh()
                .then(() => main.addChild(this.layout));
        }
        return this;
    }
}

class LeaguesLayout extends RcdMaterialLayout {
    constructor() {
        super();
        this.query = `{
            leagues{
                id,
                name,
                imageUrl
            }
        }`
    }

    refresh() {
        this.clear();
        return this.retrieveLeagues().then(leagues => {
            leagues.map(league => new LeagueResult(league).init())
                .forEach(leagueResult => this.addChild(leagueResult));
        });
    }

    retrieveLeagues() {
        return GraphQlService.fetch(this.query)
            .then(data => data.leagues);
    }
}

class LeagueResult extends ResultItem {
    constructor(league) {
        super({
            image: league.imageUrl,
            text: league.name,
            callback: () => RcdHistoryRouter.setState('league', {id: league.id})
        });
    }
}<commit_msg>Sort leagues<commit_after>class LeaguesRoute extends RcdMaterialRoute {
    constructor() {
        super({
            state: 'leagues',
            name: 'Leagues',
            //iconArea: new RcdImageIconArea(config.baseUrl + '/icons/leagues.svg').init()
        });
        this.layout = new LeaguesLayout().init();
    }

    init() {
        this.callback = (main) => {
            this.layout.refresh()
                .then(() => main.addChild(this.layout));
        }
        return this;
    }
}

class LeaguesLayout extends RcdMaterialLayout {
    constructor() {
        super();
        this.query = `{
            leagues(first:-1){
                id,
                name,
                imageUrl
                games(first:1 , finished:true) {
                    time
                }
            }
        }`
    }

    refresh() {
        this.clear();
        return this.retrieveLeagues().then(leagues => {
            leagues.sort(this.compareLeagues)
                .map(league => new LeagueResult(league).init())
                .forEach(leagueResult => this.addChild(leagueResult));
        });
    }

    retrieveLeagues() {
        return GraphQlService.fetch(this.query)
            .then(data => data.leagues);
    }

    compareLeagues(league1, league2) {
        if (league1.games.length === 0) {
            if (league2.games.length === 0) {
                return 0;
            } else {
                return 1;
            }
        }
        if (league2.games.length === 0) {
            return -1;
        }
        return league2.games[0].time.localeCompare(league1.games[0].time);
    }
}

class LeagueResult extends ResultItem {
    constructor(league) {
        super({
            image: league.imageUrl,
            text: league.name,
            callback: () => RcdHistoryRouter.setState('league', {id: league.id})
        });
    }
}<|endoftext|>


<commit_before>/*global defineSuite*/
defineSuite([
        'Scene/EllipsoidSurfaceAppearance',
        'Core/ColorGeometryInstanceAttribute',
        'Core/GeometryInstance',
        'Core/Rectangle',
        'Core/RectangleGeometry',
        'Renderer/ClearCommand',
        'Scene/Appearance',
        'Scene/Material',
        'Scene/Primitive',
        'Specs/createScene'
    ], function(
        EllipsoidSurfaceAppearance,
        ColorGeometryInstanceAttribute,
        GeometryInstance,
        Rectangle,
        RectangleGeometry,
        ClearCommand,
        Appearance,
        Material,
        Primitive,
        createScene) {
    'use strict';

    var scene;
    var rectangle;
    var primitive;

    beforeAll(function() {
        scene = createScene();
        scene.primitives.destroyPrimitives = false;
        scene.frameState.scene3DOnly = false;

        rectangle = Rectangle.fromDegrees(-10.0, -10.0, 10.0, 10.0);
        primitive = new Primitive({
            geometryInstances : new GeometryInstance({
                geometry : new RectangleGeometry({
                    rectangle : rectangle,
                    vertexFormat : EllipsoidSurfaceAppearance.VERTEX_FORMAT
                }),
                attributes : {
                    color : new ColorGeometryInstanceAttribute(1.0, 1.0, 0.0, 1.0)
                }
            }),
            asynchronous : false
        });
    });

    beforeEach(function() {
        scene.camera.setView({ destination : rectangle });
    });

    afterAll(function() {
        primitive = primitive && primitive.destroy();
        scene.destroyForSpecs();
    });

    it('constructor', function() {
        var a = new EllipsoidSurfaceAppearance();

        expect(a.material).toBeDefined();
        expect(a.material.type).toEqual(Material.ColorType);
        expect(a.vertexShaderSource).toBeDefined();
        expect(a.fragmentShaderSource).toBeDefined();
        expect(a.renderState).toEqual(Appearance.getDefaultRenderState(true, true));
        expect(a.vertexFormat).toEqual(EllipsoidSurfaceAppearance.VERTEX_FORMAT);
        expect(a.flat).toEqual(false);
        expect(a.faceForward).toEqual(false);
        expect(a.translucent).toEqual(true);
        expect(a.aboveGround).toEqual(false);
        expect(a.closed).toEqual(false);
    });

    it('renders', function() {
        primitive.appearance = new EllipsoidSurfaceAppearance();

        expect(scene.renderForSpecs()).toEqual([0, 0, 0, 255]);

        scene.primitives.add(primitive);
        expect(scene.renderForSpecs()).not.toEqual([0, 0, 0, 255]);
    });

}, 'WebGL');
<commit_msg>Made this test model more coherent with the others<commit_after>/*global defineSuite*/
defineSuite([
        'Scene/EllipsoidSurfaceAppearance',
        'Core/ColorGeometryInstanceAttribute',
        'Core/GeometryInstance',
        'Core/Rectangle',
        'Core/RectangleGeometry',
        'Renderer/ClearCommand',
        'Scene/Appearance',
        'Scene/Material',
        'Scene/Primitive',
        'Specs/createScene'
    ], function(
        EllipsoidSurfaceAppearance,
        ColorGeometryInstanceAttribute,
        GeometryInstance,
        Rectangle,
        RectangleGeometry,
        ClearCommand,
        Appearance,
        Material,
        Primitive,
        createScene) {
    'use strict';

    var scene;
    var rectangle;
    var primitive;

    beforeAll(function() {
        scene = createScene();
        scene.primitives.destroyPrimitives = false;
        scene.frameState.scene3DOnly = false;

        rectangle = Rectangle.fromDegrees(-10.0, -10.0, 10.0, 10.0);
    });

    beforeEach(function() {
        scene.camera.setView({ destination : rectangle });
    });

    afterAll(function() {
        scene.destroyForSpecs();
    });

    afterEach(function() {
        scene.primitives.removeAll();
        primitive = primitive && !primitive.isDestroyed() && primitive.destroy();
    });

    it('constructor', function() {
        var a = new EllipsoidSurfaceAppearance();

        expect(a.material).toBeDefined();
        expect(a.material.type).toEqual(Material.ColorType);
        expect(a.vertexShaderSource).toBeDefined();
        expect(a.fragmentShaderSource).toBeDefined();
        expect(a.renderState).toEqual(Appearance.getDefaultRenderState(true, true));
        expect(a.vertexFormat).toEqual(EllipsoidSurfaceAppearance.VERTEX_FORMAT);
        expect(a.flat).toEqual(false);
        expect(a.faceForward).toEqual(false);
        expect(a.translucent).toEqual(true);
        expect(a.aboveGround).toEqual(false);
        expect(a.closed).toEqual(false);
    });

    it('renders', function() {
        primitive = new Primitive({
            geometryInstances : new GeometryInstance({
                geometry : new RectangleGeometry({
                    rectangle : rectangle,
                    vertexFormat : EllipsoidSurfaceAppearance.VERTEX_FORMAT
                }),
                attributes : {
                    color : new ColorGeometryInstanceAttribute(1.0, 1.0, 0.0, 1.0)
                }
            }),
            asynchronous : false
        });
        primitive.appearance = new EllipsoidSurfaceAppearance();

        expect(scene.renderForSpecs()).toEqual([0, 0, 0, 255]);

        scene.primitives.add(primitive);
        expect(scene.renderForSpecs()).not.toEqual([0, 0, 0, 255]);
    });

}, 'WebGL');
<|endoftext|>


<commit_before>var Backbone = require('backbone');
var ConfigModel = require('../../../../../javascripts/cartodb3/data/config-model');
var GeocodingsCollection = require('../../../../../javascripts/cartodb3/data/background-importer/background-importer-geocodings-collection.js');
var GeocodingModel = require('../../../../../javascripts/cartodb3/data/background-importer/geocoding-model.js');
var UserModel = require('../../../../../javascripts/cartodb3/data/user-model');
var LayerTableModel = require('../../../../../javascripts/cartodb3/data/layer-table-model');
var LayerDefinitionsCollection = require('../../../../../javascripts/cartodb3/data/layer-definitions-collection');

describe('common/background-polling/geocodings-collection', function () {
  beforeEach(function () {
    this.configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.vis = new cdb.vis.Vis({
      type: 'derived',
      name: 'my name'
    });

    this.vis.map = {};

    this.layerDefinitionsCollection = new LayerDefinitionsCollection([], {
      configModel: this.configModel,
      visMap: this.vis.map,
      analysisDefinitionNodesCollection: {},
      mapId: 123
    });

    var layer = new Backbone.Model();
    layer.table = { id: 'test_table' };

    this.vis.map.layers = new Backbone.Collection([
      layer
    ]);

    GeocodingsCollection.prototype.sync = function (a, b, opts) {
      opts.success();
    };

    var user = new UserModel({
      username: 'pepe',
      actions: {
        private_tables: true
      }
    }, {
      configModel: this.configModel
    });

    this.collection = new GeocodingsCollection(undefined, {
      configModel: this.configModel,
      user: user,
      vis: this.vis
    });
  });

  describe('polling', function () {
    it('should start polling the geocoding model because visualization is defined and layer added to it', function () {
      this.collection.vis = this.vis;
      spyOn(this.collection, 'add');
      this.collection.parse({geocodings: [{ id: 1, table_name: 'test_table' }]});
      expect(this.collection.add).toHaveBeenCalled();
    });

    it('should not start polling the geocoding model because visualization is defined but layer is not on it', function () {
      this.collection.vis = this.vis;
      spyOn(this.collection, 'add');
      this.collection.parse({geocodings: [{ id: 1, table_name: 'hello' }]});
      expect(this.collection.add).not.toHaveBeenCalled();
    });

    it('should stop polling if there is an error in the poll checker request', function () {
      this.collection.sync = function (a, b, opts) {
        opts.error();
      };
      this.collection.pollCheck();
      expect(this.collection.pollTimer).not.toBeDefined();
    });
  });

  it('should determine if a new geocoding could be possible', function () {
    expect(this.collection.canGeocode()).toBeTruthy();

    var gm1 = new GeocodingModel(null, {
      configModel: this.configModel,
      startPollingAutomatically: false
    });

    var gm2 = new GeocodingModel({ state: 'failed' }, {
      configModel: this.configModel,
      startPollingAutomatically: false
    });

    this.collection.reset([gm1, gm2]);

    expect(this.collection.canGeocode()).toBeFalsy();
    this.collection.reset([gm2]);
    expect(this.collection.canGeocode()).toBeTruthy();
  });

  it('should return the failed items', function () {
    expect(this.collection.failedItems()).toEqual([]);
    var gm1 = new GeocodingModel(null, {
      configModel: this.configModel,
      startPollingAutomatically: false
    });

    var gm2 = new GeocodingModel({ state: 'failed' }, {
      configModel: this.configModel,
      startPollingAutomatically: false
    });

    var gm3 = new GeocodingModel(null, {
      configModel: this.configModel,
      startPollingAutomatically: false
    });

    this.collection.reset([gm1, gm2, gm3]);
    expect(this.collection.failedItems().length).toEqual(1);
  });
});
<commit_msg>Removes undefined variable<commit_after>var Backbone = require('backbone');
var ConfigModel = require('../../../../../javascripts/cartodb3/data/config-model');
var GeocodingsCollection = require('../../../../../javascripts/cartodb3/data/background-importer/background-importer-geocodings-collection.js');
var GeocodingModel = require('../../../../../javascripts/cartodb3/data/background-importer/geocoding-model.js');
var UserModel = require('../../../../../javascripts/cartodb3/data/user-model');
var LayerDefinitionsCollection = require('../../../../../javascripts/cartodb3/data/layer-definitions-collection');

describe('common/background-polling/geocodings-collection', function () {
  beforeEach(function () {
    this.configModel = new ConfigModel({
      base_url: '/u/pepe'
    });

    this.vis = new cdb.vis.Vis({
      type: 'derived',
      name: 'my name'
    });

    this.vis.map = {};

    this.layerDefinitionsCollection = new LayerDefinitionsCollection([], {
      configModel: this.configModel,
      visMap: this.vis.map,
      analysisDefinitionNodesCollection: {},
      mapId: 123
    });

    var layer = new Backbone.Model();
    layer.table = { id: 'test_table' };

    this.vis.map.layers = new Backbone.Collection([
      layer
    ]);

    GeocodingsCollection.prototype.sync = function (a, b, opts) {
      opts.success();
    };

    var user = new UserModel({
      username: 'pepe',
      actions: {
        private_tables: true
      }
    }, {
      configModel: this.configModel
    });

    this.collection = new GeocodingsCollection(undefined, {
      configModel: this.configModel,
      user: user,
      vis: this.vis
    });
  });

  describe('polling', function () {
    it('should start polling the geocoding model because visualization is defined and layer added to it', function () {
      this.collection.vis = this.vis;
      spyOn(this.collection, 'add');
      this.collection.parse({geocodings: [{ id: 1, table_name: 'test_table' }]});
      expect(this.collection.add).toHaveBeenCalled();
    });

    it('should not start polling the geocoding model because visualization is defined but layer is not on it', function () {
      this.collection.vis = this.vis;
      spyOn(this.collection, 'add');
      this.collection.parse({geocodings: [{ id: 1, table_name: 'hello' }]});
      expect(this.collection.add).not.toHaveBeenCalled();
    });

    it('should stop polling if there is an error in the poll checker request', function () {
      this.collection.sync = function (a, b, opts) {
        opts.error();
      };
      this.collection.pollCheck();
      expect(this.collection.pollTimer).not.toBeDefined();
    });
  });

  it('should determine if a new geocoding could be possible', function () {
    expect(this.collection.canGeocode()).toBeTruthy();

    var gm1 = new GeocodingModel(null, {
      configModel: this.configModel,
      startPollingAutomatically: false
    });

    var gm2 = new GeocodingModel({ state: 'failed' }, {
      configModel: this.configModel,
      startPollingAutomatically: false
    });

    this.collection.reset([gm1, gm2]);

    expect(this.collection.canGeocode()).toBeFalsy();
    this.collection.reset([gm2]);
    expect(this.collection.canGeocode()).toBeTruthy();
  });

  it('should return the failed items', function () {
    expect(this.collection.failedItems()).toEqual([]);
    var gm1 = new GeocodingModel(null, {
      configModel: this.configModel,
      startPollingAutomatically: false
    });

    var gm2 = new GeocodingModel({ state: 'failed' }, {
      configModel: this.configModel,
      startPollingAutomatically: false
    });

    var gm3 = new GeocodingModel(null, {
      configModel: this.configModel,
      startPollingAutomatically: false
    });

    this.collection.reset([gm1, gm2, gm3]);
    expect(this.collection.failedItems().length).toEqual(1);
  });
});
<|endoftext|>