<commit_before>$(document).ready(function() {

    // Hide template
    $('#sellermania-template').hide();

    // Retrieve data
    var sellermania_title = $('#sellermania-template-title').html();
    var sellermania_customer = $('#sellermania-template-customer').html();
    var sellermania_order_summary = $('#sellermania-template-order-summary').html();

    // Replace status order selection
    $('#content div div form #id_order_state').after(sellermania_title);
    $('#content div div form #id_order_state').hide();
    $('#content div div form input[name="submitState"]').hide();

    // Replace status order selection
    $('#content div div fieldset:first').html(sellermania_customer);

    // Replace right column
    var order_buttons = '
' + $('.button-command-prev-next').html() + '

';
    $('.button-command-prev-next').parent().html(order_buttons + sellermania_order_summary);

    // Hide address block
    $('.container-command:first').next().hide();

    // Hide "Add product" button
    $('.add_product').parent().hide();

    // Hide discount block
    $('#total_products').parent().parent().parent().next().next().hide();

    // Hide message thread customer block
    $('.add_product').parent().parent().parent().parent().next().next().hide();

    // Fill product details
    var sellermania_order_line = 0;
    $('#orderProducts tr').each(function() {
        if (sellermania_order_line > 0)
        {
            var sellermania_order_row = 0;
            $(this).find('td').each(function() {
                if (sellermania_order_row == 1 && $(this).is(':visible'))
                {
                    var sku = $(this).html().split('
');
                    sku = sku[1].split(' ');
                    sku = sku[1].replace('Ref: ', '').trim();

                    var html_order_line = $(this).html();
                    if (sellermania_products[sku].insurance_price > 0)
                        html_order_line += '
Insurance price: ' + sellermania_products[sku].insurance_price + ' ' + sellermania_products[sku].currency + '
';
                    html_order_line += '
Order item ID: ' + sellermania_products[sku].order_item_id + '
';
                    html_order_line += 'Sku: ' + sku + '
';
                    html_order_line += 'Ean: ' + sellermania_products[sku].ean + '
';
                    html_order_line += 'Condition: ' + sellermania_products[sku].item_condition + '
';
                    html_order_line += 'Status: ' + sellermania_products[sku].status + '
';
                    if (sellermania_products[sku].status_id == 6)
                    {
                        html_order_line += '<input type="radio" id="status_confirm_' + sellermania_order_line + '" name="status_' + sellermania_order_line + '" value="9" class="status_order_line" data-toggle="' + sku + '" /> Confirm ';
                        html_order_line += '<input type="radio" id="status_cancel_' + sellermania_order_line + '" name="status_' + sellermania_order_line + '" value="4" class="status_order_line" data-toggle="' + sku + '" /> Cancel ';
                    }
                    $(this).html(html_order_line);
                }
                sellermania_order_row++;
            });
        }
        sellermania_order_line++;
    });

    // Check status
    $('.status_order_line').click(function() {

        // Fill product details
        var sellermania_status_not_defined = 0;
        var sellermania_order_line = 0;

        $('#orderProducts tr').each(function() {
            if (sellermania_order_line > 0)
            {
                var sellermania_order_row = 0;
                $(this).find('td').each(function() {
                    if (sellermania_order_row == 1 && $(this).is(':visible'))
                    {
                        // Retrieve sku
                        var sku = $(this).html().split('
');
                        sku = sku[1].split(' ');
                        sku = sku[1].replace('Ref: ', '').trim();

                        // Status
                        var order_line_status = 'Not defined';
                        if ($('#status_confirm_' + sellermania_order_line).prop('checked'))
                            order_line_status = 'Confirmed';
                        if ($('#status_cancel_' + sellermania_order_line).prop('checked'))
                            order_line_status = 'Cancelled';

                        // Count not defined Status
                        if (order_line_status == 'Not defined')
                            sellermania_status_not_defined++;
                    }
                    sellermania_order_row++;
                });
            }
            sellermania_order_line++;
        });

        // Check how many not defined status there is
        if (sellermania_status_not_defined == 0)
        {
            // Display submit
            $('.add_product').parent().next().next().next().next().next().html('<input type="button" id="sellermania_register_status" value="Register status" class="button" />');

            // Generate form and submit it
            $('#sellermania_register_status').click(function() {

                // Generate form
                var html_form = '<form id="sellermania_status_form" action="" method="POST">';
                html_form += '<input type="hidden" name="sellermania_status_form_registration" value="1" />';
                $('.status_order_line').each(function() {
                    if ($(this).prop('checked'))
                    {
                        html_form += '<input type="hidden" name="' + $(this).attr('name') + '" value="' + $(this).attr('value') + '" />';
                        html_form += '<input type="hidden" name="sku_' + $(this).attr('name') + '" value="' + $(this).attr('data-toggle') + '" />';
                    }
                });
                html_form += '</form>';

                // Display form and submit
                $('.add_product').parent().next().next().next().next().next().html(html_form);
                $('#sellermania_status_form').submit();

                return false;
            });
        }
    });
});
<commit_msg>JS parsing handle other languages (such as french) part 2<commit_after>$(document).ready(function() {

    // Hide template
    $('#sellermania-template').hide();

    // Retrieve data
    var sellermania_title = $('#sellermania-template-title').html();
    var sellermania_customer = $('#sellermania-template-customer').html();
    var sellermania_order_summary = $('#sellermania-template-order-summary').html();

    // Replace status order selection
    $('#content div div form #id_order_state').after(sellermania_title);
    $('#content div div form #id_order_state').hide();
    $('#content div div form input[name="submitState"]').hide();

    // Replace status order selection
    $('#content div div fieldset:first').html(sellermania_customer);

    // Replace right column
    var order_buttons = '
' + $('.button-command-prev-next').html() + '

';
    $('.button-command-prev-next').parent().html(order_buttons + sellermania_order_summary);

    // Hide address block
    $('.container-command:first').next().hide();

    // Hide "Add product" button
    $('.add_product').parent().hide();

    // Hide discount block
    $('#total_products').parent().parent().parent().next().next().hide();

    // Hide message thread customer block
    $('.add_product').parent().parent().parent().parent().next().next().hide();

    // Fill product details
    var sellermania_order_line = 0;
    $('#orderProducts tr').each(function() {
        if (sellermania_order_line > 0)
        {
            var sellermania_order_row = 0;
            $(this).find('td').each(function() {
                if (sellermania_order_row == 1 && $(this).is(':visible'))
                {
                    var sku = $(this).html().split('
');
                    var remove = sku[1].split(' ');
                    sku = sku[1].replace(remove[0], '').trim();

                    var html_order_line = $(this).html();
                    if (sellermania_products[sku].insurance_price > 0)
                        html_order_line += '
Insurance price: ' + sellermania_products[sku].insurance_price + ' ' + sellermania_products[sku].currency + '
';
                    html_order_line += '
Order item ID: ' + sellermania_products[sku].order_item_id + '
';
                    html_order_line += 'Sku: ' + sku + '
';
                    html_order_line += 'Ean: ' + sellermania_products[sku].ean + '
';
                    html_order_line += 'Condition: ' + sellermania_products[sku].item_condition + '
';
                    html_order_line += 'Status: ' + sellermania_products[sku].status + '
';
                    if (sellermania_products[sku].status_id == 6)
                    {
                        html_order_line += '<input type="radio" id="status_confirm_' + sellermania_order_line + '" name="status_' + sellermania_order_line + '" value="9" class="status_order_line" data-toggle="' + sku + '" /> Confirm ';
                        html_order_line += '<input type="radio" id="status_cancel_' + sellermania_order_line + '" name="status_' + sellermania_order_line + '" value="4" class="status_order_line" data-toggle="' + sku + '" /> Cancel ';
                    }
                    $(this).html(html_order_line);
                }
                sellermania_order_row++;
            });
        }
        sellermania_order_line++;
    });

    // Check status
    $('.status_order_line').click(function() {

        // Fill product details
        var sellermania_status_not_defined = 0;
        var sellermania_order_line = 0;

        $('#orderProducts tr').each(function() {
            if (sellermania_order_line > 0)
            {
                var sellermania_order_row = 0;
                $(this).find('td').each(function() {
                    if (sellermania_order_row == 1 && $(this).is(':visible'))
                    {
                        // Retrieve sku
                        var sku = $(this).html().split('
');
                        var remove = sku[1].split(' ');
                        sku = sku[1].replace(remove[0], '').trim();

                        // Status
                        var order_line_status = 'Not defined';
                        if ($('#status_confirm_' + sellermania_order_line).prop('checked'))
                            order_line_status = 'Confirmed';
                        if ($('#status_cancel_' + sellermania_order_line).prop('checked'))
                            order_line_status = 'Cancelled';

                        // Count not defined Status
                        if (order_line_status == 'Not defined')
                            sellermania_status_not_defined++;
                    }
                    sellermania_order_row++;
                });
            }
            sellermania_order_line++;
        });

        // Check how many not defined status there is
        if (sellermania_status_not_defined == 0)
        {
            // Display submit
            $('.add_product').parent().next().next().next().next().next().html('<input type="button" id="sellermania_register_status" value="Register status" class="button" />');

            // Generate form and submit it
            $('#sellermania_register_status').click(function() {

                // Generate form
                var html_form = '<form id="sellermania_status_form" action="" method="POST">';
                html_form += '<input type="hidden" name="sellermania_status_form_registration" value="1" />';
                $('.status_order_line').each(function() {
                    if ($(this).prop('checked'))
                    {
                        html_form += '<input type="hidden" name="' + $(this).attr('name') + '" value="' + $(this).attr('value') + '" />';
                        html_form += '<input type="hidden" name="sku_' + $(this).attr('name') + '" value="' + $(this).attr('data-toggle') + '" />';
                    }
                });
                html_form += '</form>';

                // Display form and submit
                $('.add_product').parent().next().next().next().next().next().html(html_form);
                $('#sellermania_status_form').submit();

                return false;
            });
        }
    });
});
<|endoftext|>


<commit_before>// Game engine
var NUMBER_OF_DECKS = 4;
var suite = {
    hearts: 1,
    diamonds: 2,
    clubs: 3,
    spades: 4
};
var power = {
    A: 1,
    2: 2,
    3: 3,
    4: 4,
    5: 5,
    6: 6,
    7: 7,
    8: 8,
    9: 9,
    10: 10,
    J: 10,
    Q: 10,
    K: 10,
};

class Card {
    constructor(suite, power) {
        this.suite = suite;
        this.power = power;
    }
}

class Deck {
    constructor() {
        this.cards = [];
        for (var i = 0; i < NUMBER_OF_DECKS; i++) {
            for (var sui in suite) {
                for (var pow in power) {
                    var currCard = new Card(sui, pow);
                    this.cards.push(currCard);
                }
            }
        }
        shuffle(this.cards);
        console.log(this.cards);
    }
}

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var deckOfCards = new Deck();
<commit_msg>Added a draw method<commit_after>// Game engine
var NUMBER_OF_DECKS = 4;
var suite = {
    hearts: 1,
    diamonds: 2,
    clubs: 3,
    spades: 4
};
var power = {
    A: 1,
    2: 2,
    3: 3,
    4: 4,
    5: 5,
    6: 6,
    7: 7,
    8: 8,
    9: 9,
    10: 10,
    J: 10,
    Q: 10,
    K: 10,
};

class Card {
    constructor(suite, power) {
        this.suite = suite;
        this.power = power;
    }
}

class Deck {
    constructor() {
        this.cards = [];
        for (var i = 0; i < NUMBER_OF_DECKS; i++) {
            for (var sui in suite) {
                for (var pow in power) {
                    var currCard = new Card(sui, pow);
                    this.cards.push(currCard);
                }
            }
        }
        shuffle(this.cards);
        //console.log(this.cards);
    }

    draw() {
        console.log(this.cards[0]);
        this.cards.splice(0, 1);
    }
}

function shuffle(array) {
  var currentIndex = array.length, temporaryValue, randomIndex;

  // While there remain elements to shuffle...
  while (0 !== currentIndex) {

    // Pick a remaining element...
    randomIndex = Math.floor(Math.random() * currentIndex);
    currentIndex -= 1;

    // And swap it with the current element.
    temporaryValue = array[currentIndex];
    array[currentIndex] = array[randomIndex];
    array[randomIndex] = temporaryValue;
  }

  return array;
}

var deckOfCards = new Deck();
deckOfCards.draw();
deckOfCards.draw();
deckOfCards.draw();
deckOfCards.draw();
deckOfCards.draw();
<|endoftext|>


<commit_before>/**
 *  Copyright (C) 2021 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

const { src } = require('../../../../helper/path');

jest.mock('../../../../../../src/v5/utils/responder');
const Responder = require(`${src}/utils/responder`);
jest.mock('../../../../../../src/v5/utils/permissions/permissions');
const Permissions = require(`${src}/utils/permissions/permissions`);
const { templates } = require(`${src}/utils/responseCodes`);

jest.mock('../../../../../../src/v5/models/projects');
const Projects = require(`${src}/models/projects`);
jest.mock('../../../../../../src/v5/utils/sessions');
const Sessions = require(`${src}/utils/sessions`);
const ProjectMiddlewares = require(`${src}/middleware/permissions/components/projects`);

// Mock respond function to just return the resCode
Responder.respond.mockImplementation((req, res, errCode) => errCode);
Permissions.isTeamspaceAdmin.mockImplementation((teamspace, user) => user === 'tsAdmin');
Permissions.isProjectAdmin.mockImplementation((teamspace, project, user) => user === 'projAdmin');
Projects.getProjectById.mockImplementation(() => ({ permissions: [{ user: 'projAdmin', permissions: ['admin_project'] }] }));
Sessions.isSessionValid.mockImplementation((session) => !!session);
Sessions.getUserFromSession.mockImplementation(({ user }) => user.username);

const testIsProjectAdmin = () => {
	describe('isProjectAdmin', () => {
		test('next() should be called if the user is teamspace admin', async () => {
			const mockCB = jest.fn(() => {});
			await ProjectMiddlewares.isProjectAdmin(
				{ params: { teamspace: 'ts', project: 'p1' }, session: { user: { username: 'tsAdmin' } } },
				{},
				mockCB,
			);
			expect(mockCB.mock.calls.length).toBe(1);
		});

		test('next() should be called if the user is project admin', async () => {
			const mockCB = jest.fn(() => {});
			await ProjectMiddlewares.isProjectAdmin(
				{ params: { teamspace: 'ts', project: 'p1' }, session: { user: { username: 'projAdmin' } } },
				{},
				mockCB,
			);
			expect(mockCB.mock.calls.length).toBe(1);
		});

		test('should respond with not authorized if the user has no access', async () => {
			const mockCB = jest.fn(() => {});
			await ProjectMiddlewares.isProjectAdmin(
				{ params: { teamspace: 'ts1', project: 'p1' }, session: { user: { username: 'hi' } } },
				{},
				mockCB,
			);
			expect(mockCB.mock.calls.length).toBe(0);
			expect(Responder.respond.mock.calls.length).toBe(1);
			expect(Responder.respond.mock.results[0].value).toEqual(templates.notAuthorized);
		});
	});
};

describe('middleware/permissions/components/projects', () => {
	testIsProjectAdmin();
});
<commit_msg>ISSUE #2810 test with invalid project added to middleware project tests<commit_after>/**
 *  Copyright (C) 2021 3D Repo Ltd
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as
 *  published by the Free Software Foundation, either version 3 of the
 *  License, or (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

const { src } = require('../../../../helper/path');

jest.mock('../../../../../../src/v5/utils/responder');
const Responder = require(`${src}/utils/responder`);
jest.mock('../../../../../../src/v5/utils/permissions/permissions');
const Permissions = require(`${src}/utils/permissions/permissions`);
const { templates } = require(`${src}/utils/responseCodes`);

jest.mock('../../../../../../src/v5/models/projects');
const Projects = require(`${src}/models/projects`);
jest.mock('../../../../../../src/v5/utils/sessions');
const Sessions = require(`${src}/utils/sessions`);
const ProjectMiddlewares = require(`${src}/middleware/permissions/components/projects`);

// Mock respond function to just return the resCode
Responder.respond.mockImplementation((req, res, errCode) => errCode);
Permissions.isTeamspaceAdmin.mockImplementation((teamspace, user) => user === 'tsAdmin');
Permissions.isProjectAdmin.mockImplementation((teamspace, project, user) => user === 'projAdmin');
Projects.getProjectById.mockImplementation(() => ({ permissions: [{ user: 'projAdmin', permissions: ['admin_project'] }] }));
Projects.checkProjectExists.mockImplementation((teamspace, project) => {
	if(project === 'pr2'){
		throw templates.projectNotFound;
	}
});
Sessions.isSessionValid.mockImplementation((session) => !!session);
Sessions.getUserFromSession.mockImplementation(({ user }) => user.username);

const testIsProjectAdmin = () => {
	describe('isProjectAdmin', () => {
		test('next() should be called if the user is teamspace admin', async () => {
			const mockCB = jest.fn(() => {});
			await ProjectMiddlewares.isProjectAdmin(
				{ params: { teamspace: 'ts', project: 'p1' }, session: { user: { username: 'tsAdmin' } } },
				{},
				mockCB,
			);
			expect(mockCB.mock.calls.length).toBe(1);
		});

		test('next() should be called if the user is project admin', async () => {
			const mockCB = jest.fn(() => {});
			await ProjectMiddlewares.isProjectAdmin(
				{ params: { teamspace: 'ts', project: 'p1' }, session: { user: { username: 'projAdmin' } } },
				{},
				mockCB,
			);
			expect(mockCB.mock.calls.length).toBe(1);
		});

		test('should respond with not authorized if the user has no access', async () => {
			const mockCB = jest.fn(() => {});
			await ProjectMiddlewares.isProjectAdmin(
				{ params: { teamspace: 'ts1', project: 'p1' }, session: { user: { username: 'hi' } } },
				{},
				mockCB,
			);
			expect(mockCB.mock.calls.length).toBe(0);
			expect(Responder.respond.mock.calls.length).toBe(1);
			expect(Responder.respond.mock.results[0].value).toEqual(templates.notAuthorized);
		});

		test('should respond with project not found if the project does not exist', async () => {
			const mockCB = jest.fn(() => {});
			await ProjectMiddlewares.isProjectAdmin(
				{ params: { teamspace: 'ts1', project: 'pr2' }, session: { user: { username: 'hi' } } },
				{},
				mockCB,
			);
			expect(mockCB.mock.calls.length).toBe(0);
			expect(Responder.respond.mock.calls.length).toBe(1);
			expect(Responder.respond.mock.results[0].value).toEqual(templates.projectNotFound);
		});
	});
};

describe('middleware/permissions/components/projects', () => {
	testIsProjectAdmin();
});
<|endoftext|>


<commit_before>'use strict';
var pgpLib = require('pg-promise');
var monitor = require('pg-monitor');
var eventsActions = require('./events.js');
var userActions = require('./users.js');

// pg-promise initialization options:
var options = {

    capTX: true, // capitalize transaction commands;

    extend: function () {

        // our 'events' repository extension:
        this.events = eventsActions(this);

        // our 'users' repository extension:
        this.users = userActions(this);

    }

};

monitor.attach(options); // attaching to all events;
monitor.setTheme('matrix'); // changing default theme;

var pgp = pgpLib(options); // initializing pg-promise;

// instantiating the database:
var db = pgp(process.env.PG_URI || "postgres://mimolap@localhost:5432/gen");

module.exports = db;
<commit_msg>chore: adjust db url<commit_after>'use strict';
var pgpLib = require('pg-promise');
var monitor = require('pg-monitor');
var eventsActions = require('./events.js');
var userActions = require('./users.js');

// pg-promise initialization options:
var options = {

    capTX: true, // capitalize transaction commands;

    extend: function () {

        // our 'events' repository extension:
        this.events = eventsActions(this);

        // our 'users' repository extension:
        this.users = userActions(this);

    }

};

monitor.attach(options); // attaching to all events;
monitor.setTheme('matrix'); // changing default theme;

var pgp = pgpLib(options); // initializing pg-promise;

// instantiating the database:
var db = pgp(process.env.DATABASE_URL || "postgres://mimolap@localhost:5432/gen");

module.exports = db;
<|endoftext|>


<commit_before>/*
 *  Datastore.js
 *
 *  An interface to native/emulated database storage methods
 *  Avoids issues when browser does not have native database storage
 *
 *  @license AGPL
 *  @author Valérian Saliou <valerian@valeriansaliou.name>
 *  @url https://github.com/valeriansaliou/datastore.js
 */

// Bundle
var DataStore = (function () {

    /**
     * Alias of this
     * @private
     */
    var self = {};

    /* Variables */
    self._db_emulated = {};
    self._persistent_emulated = {};

	/**
     * Common: storage adapter
     * @public
     * @param {object} storage_native
     * @param {object} storage_emulated
     * @return {undefined}
     */
    self._adapter = function(storage_native, storage_emulated) {

        try {
            var legacy = !storage_native;

            this.key = function(key) {
                if(legacy) {
                    if(key >= this.length)
                        return null;

                    var c = 0;

                    for(var name in storage_emulated) {
                        if(c++ == key)  return name;
                    }

                    return null;
                }

                return storage_native.key(key);
            };

            this.getItem = function(key) {
                if(legacy) {
                    if(storage_emulated[key] !== undefined)
                        return storage_emulated[key];

                    return null;
                } else {
                    return storage_native.getItem(key);
                }
            };

            this.setItem = function(key, data) {
                if(legacy) {
                    if(!(key in storage_emulated))
                        this.length++;

                    storage_emulated[key] = (data + '');
                } else {
                    storage_native.setItem(key, data);
                    this.length = storage_native.length;
                }
            };

            this.removeItem = function(key) {
                if(legacy) {
                    if(key in storage_emulated) {
                        this.length--;
                        delete storage_emulated[key];
                    }
                } else {
                    storage_native.removeItem(key);
                    this.length = storage_native.length;
                }
            };

            this.clear = function() {
                if(legacy) {
                    this.length = 0;
                    storage_emulated = {};
                } else {
                    storage_native.clear();
                    this.length = storage_native.length;
                }
            };

            this.length = legacy ? 0 : storage_native.length;
        } catch(e) {
            Console.error('DataStore._adapter', e);
        }

    };

    /**
     * Temporary: sessionStorage class alias for direct access
     */
    self.storageDB = new self._adapter(
        (window.sessionStorage ? sessionStorage : null),
        self._db_emulated
    );

    /**
     * Persistent: localStorage class alias for direct access
     */
    self.storagePersistent = new self._adapter(
        (window.localStorage ? localStorage : null),
        self._persistent_emulated
    );

    /**
     * Temporary: returns whether it is available or not
     * @public
     * @return {boolean}
     */
    self.hasDB = function() {

        var has_db = false;

        try {
            self.storageDB.setItem('hasdb_check', 'ok');
            self.storageDB.removeItem('hasdb_check');

            has_db = true;
        } catch(e) {
            Console.error('DataStore.hasDB', e);
        } finally {
            return has_db;
        }

    };

    /**
     * Temporary: used to read a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {object}
     */
    self.getDB = function(dbID, type, id) {

        try {
            try {
                return self.storageDB.getItem(dbID + '_' + type + '_' + id);
            }

            catch(e) {
                Console.error('Error while getting a temporary database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);
            }

            return null;
        } catch(e) {
            Console.error('DataStore.getDB', e);
        }

    };

    /**
     * Temporary: used to update a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @param {type} value
     * @return {boolean}
     */
    self.setDB = function(dbID, type, id, value) {

        try {
            try {
                self.storageDB.setItem(dbID + '_' + type + '_' + id, value);

                return true;
            }

            catch(e) {
                Console.error('Error while writing a temporary database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);
            }

            return false;
        } catch(e) {
            Console.error('DataStore.setDB', e);
        }

    };

    /**
     * Temporary: used to remove a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {undefined}
     */
    self.removeDB = function(dbID, type, id) {

        try {
            try {
                self.storageDB.removeItem(dbID + '_' + type + '_' + id);

                return true;
            }

            catch(e) {
                Console.error('Error while removing a temporary database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);
            }

            return false;
        } catch(e) {
            Console.error('DataStore.removeDB', e);
        }

    };

	/**
     * Temporary: used to check a database entry exists
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {boolean}
     */
    self.existDB = function(dbID, type, id) {

        try {
            return self.getDB(dbID, type, id) !== null;
        } catch(e) {
            Console.error('DataStore.existDB', e);
        }

    };

    /**
     * Temporary: used to clear all the database
     * @public
     * @return {boolean}
     */
    self.resetDB = function() {

        try {
            try {
                self.storageDB.clear();

                Console.info('Temporary database cleared.');

                return true;
            }

            catch(e) {
                Console.error('Error while clearing temporary database', e);

                return false;
            }
        } catch(e) {
            Console.error('DataStore.resetDB', e);
        }

    };

    /**
     * Persistent: returns whether it is available or not
     * @public
     * @return {boolean}
     */
    self.hasPersistent = function() {

        var has_persistent = false;

        try {
            // Try to write something
            self.storagePersistent.setItem('haspersistent_check', 'ok');
            self.storagePersistent.removeItem('haspersistent_check');

            has_persistent = true;
        } catch(e) {
            Console.error('DataStore.hasPersistent', e);
        } finally {
            return has_persistent;
        }

    };

    /**
     * Persistent: used to read a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {object}
     */
    self.getPersistent = function(dbID, type, id) {

        try {
            try {
                return self.storagePersistent.getItem(dbID + '_' + type + '_' + id);
            }

            catch(e) {
                Console.error('Error while getting a persistent database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);

                return null;
            }
        } catch(e) {
            Console.error('DataStore.getPersistent', e);
        }

    };

    /**
     * Persistent: used to update a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @param {string} value
     * @return {boolean}
     */
    self.setPersistent = function(dbID, type, id, value) {

        try {
            try {
                self.storagePersistent.setItem(dbID + '_' + type + '_' + id, value);

                return true;
            }

            // Database might be full
            catch(e) {
                Console.warn('Retrying: could not write a persistent database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);

                // Flush it!
                self.resetPersistent();

                // Set the item again
                try {
                    self.storagePersistent.setItem(dbID + ' -> ' + type + '_' + id, value);

                    return true;
                }

                // New error!
                catch(_e) {
                    Console.error('Aborted: error while writing a persistent database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', _e);
                }
            }

            return false;
        } catch(e) {
            Console.error('DataStore.setPersistent', e);
        }

    };

	/**
     * Persistent: used to remove a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {boolean}
     */
    self.removePersistent = function(dbID, type, id) {

        try {
            try {
                self.storagePersistent.removeItem(dbID + '_' + type + '_' + id);

                return true;
            }

            catch(e) {
                Console.error('Error while removing a persistent database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);
            }

            return false;
        } catch(e) {
            Console.error('DataStore.removePersistent', e);
        }

    };

    /**
     * Persistent: used to check a database entry exists
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {boolean}
     */
    self.existPersistent = function(dbID, type, id) {

        try {
            return self.getPersistent(dbID, type, id) !== null;
        } catch(e) {
            Console.error('DataStore.existPersistent', e);
        }

    };

    /**
     * Persistent: used to clear all the database
     * @public
     * @param {type} name
     * @return {boolean}
     */
    self.resetPersistent = function() {

        try {
            try {
                self.storagePersistent.clear();

                Console.info('Persistent database cleared.');

                return true;
            }

            catch(e) {
                Console.error('Error while clearing persistent database', e);
            }

            return false;
        } catch(e) {
            Console.error('DataStore.resetPersistent', e);
        }

    };

    /**
     * Return class scope
     */
    return self;

})();
<commit_msg>Indenting<commit_after>/*
 *  Datastore.js
 *
 *  An interface to native/emulated database storage methods
 *  Avoids issues when browser does not have native database storage
 *
 *  @license AGPL
 *  @author Valérian Saliou <valerian@valeriansaliou.name>
 *  @url https://github.com/valeriansaliou/datastore.js
 */

// Bundle
var DataStore = (function () {

    /**
     * Alias of this
     * @private
     */
    var self = {};

    /* Variables */
    self._db_emulated = {};
    self._persistent_emulated = {};

    /**
     * Common: storage adapter
     * @public
     * @param {object} storage_native
     * @param {object} storage_emulated
     * @return {undefined}
     */
    self._adapter = function(storage_native, storage_emulated) {

        try {
            var legacy = !storage_native;

            this.key = function(key) {
                if(legacy) {
                    if(key >= this.length)
                        return null;

                    var c = 0;

                    for(var name in storage_emulated) {
                        if(c++ == key)  return name;
                    }

                    return null;
                }

                return storage_native.key(key);
            };

            this.getItem = function(key) {
                if(legacy) {
                    if(storage_emulated[key] !== undefined)
                        return storage_emulated[key];

                    return null;
                } else {
                    return storage_native.getItem(key);
                }
            };

            this.setItem = function(key, data) {
                if(legacy) {
                    if(!(key in storage_emulated))
                        this.length++;

                    storage_emulated[key] = (data + '');
                } else {
                    storage_native.setItem(key, data);
                    this.length = storage_native.length;
                }
            };

            this.removeItem = function(key) {
                if(legacy) {
                    if(key in storage_emulated) {
                        this.length--;
                        delete storage_emulated[key];
                    }
                } else {
                    storage_native.removeItem(key);
                    this.length = storage_native.length;
                }
            };

            this.clear = function() {
                if(legacy) {
                    this.length = 0;
                    storage_emulated = {};
                } else {
                    storage_native.clear();
                    this.length = storage_native.length;
                }
            };

            this.length = legacy ? 0 : storage_native.length;
        } catch(e) {
            Console.error('DataStore._adapter', e);
        }

    };

    /**
     * Temporary: sessionStorage class alias for direct access
     */
    self.storageDB = new self._adapter(
        (window.sessionStorage ? sessionStorage : null),
        self._db_emulated
    );

    /**
     * Persistent: localStorage class alias for direct access
     */
    self.storagePersistent = new self._adapter(
        (window.localStorage ? localStorage : null),
        self._persistent_emulated
    );

    /**
     * Temporary: returns whether it is available or not
     * @public
     * @return {boolean}
     */
    self.hasDB = function() {

        var has_db = false;

        try {
            self.storageDB.setItem('hasdb_check', 'ok');
            self.storageDB.removeItem('hasdb_check');

            has_db = true;
        } catch(e) {
            Console.error('DataStore.hasDB', e);
        } finally {
            return has_db;
        }

    };

    /**
     * Temporary: used to read a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {object}
     */
    self.getDB = function(dbID, type, id) {

        try {
            try {
                return self.storageDB.getItem(dbID + '_' + type + '_' + id);
            }

            catch(e) {
                Console.error('Error while getting a temporary database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);
            }

            return null;
        } catch(e) {
            Console.error('DataStore.getDB', e);
        }

    };

    /**
     * Temporary: used to update a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @param {type} value
     * @return {boolean}
     */
    self.setDB = function(dbID, type, id, value) {

        try {
            try {
                self.storageDB.setItem(dbID + '_' + type + '_' + id, value);

                return true;
            }

            catch(e) {
                Console.error('Error while writing a temporary database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);
            }

            return false;
        } catch(e) {
            Console.error('DataStore.setDB', e);
        }

    };

    /**
     * Temporary: used to remove a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {undefined}
     */
    self.removeDB = function(dbID, type, id) {

        try {
            try {
                self.storageDB.removeItem(dbID + '_' + type + '_' + id);

                return true;
            }

            catch(e) {
                Console.error('Error while removing a temporary database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);
            }

            return false;
        } catch(e) {
            Console.error('DataStore.removeDB', e);
        }

    };

    /**
     * Temporary: used to check a database entry exists
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {boolean}
     */
    self.existDB = function(dbID, type, id) {

        try {
            return self.getDB(dbID, type, id) !== null;
        } catch(e) {
            Console.error('DataStore.existDB', e);
        }

    };

    /**
     * Temporary: used to clear all the database
     * @public
     * @return {boolean}
     */
    self.resetDB = function() {

        try {
            try {
                self.storageDB.clear();

                Console.info('Temporary database cleared.');

                return true;
            }

            catch(e) {
                Console.error('Error while clearing temporary database', e);

                return false;
            }
        } catch(e) {
            Console.error('DataStore.resetDB', e);
        }

    };

    /**
     * Persistent: returns whether it is available or not
     * @public
     * @return {boolean}
     */
    self.hasPersistent = function() {

        var has_persistent = false;

        try {
            // Try to write something
            self.storagePersistent.setItem('haspersistent_check', 'ok');
            self.storagePersistent.removeItem('haspersistent_check');

            has_persistent = true;
        } catch(e) {
            Console.error('DataStore.hasPersistent', e);
        } finally {
            return has_persistent;
        }

    };

    /**
     * Persistent: used to read a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {object}
     */
    self.getPersistent = function(dbID, type, id) {

        try {
            try {
                return self.storagePersistent.getItem(dbID + '_' + type + '_' + id);
            }

            catch(e) {
                Console.error('Error while getting a persistent database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);

                return null;
            }
        } catch(e) {
            Console.error('DataStore.getPersistent', e);
        }

    };

    /**
     * Persistent: used to update a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @param {string} value
     * @return {boolean}
     */
    self.setPersistent = function(dbID, type, id, value) {

        try {
            try {
                self.storagePersistent.setItem(dbID + '_' + type + '_' + id, value);

                return true;
            }

            // Database might be full
            catch(e) {
                Console.warn('Retrying: could not write a persistent database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);

                // Flush it!
                self.resetPersistent();

                // Set the item again
                try {
                    self.storagePersistent.setItem(dbID + ' -> ' + type + '_' + id, value);

                    return true;
                }

                // New error!
                catch(_e) {
                    Console.error('Aborted: error while writing a persistent database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', _e);
                }
            }

            return false;
        } catch(e) {
            Console.error('DataStore.setPersistent', e);
        }

    };

    /**
     * Persistent: used to remove a database entry
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {boolean}
     */
    self.removePersistent = function(dbID, type, id) {

        try {
            try {
                self.storagePersistent.removeItem(dbID + '_' + type + '_' + id);

                return true;
            }

            catch(e) {
                Console.error('Error while removing a persistent database entry (' + dbID + ' -> ' + type + ' -> ' + id + ')', e);
            }

            return false;
        } catch(e) {
            Console.error('DataStore.removePersistent', e);
        }

    };

    /**
     * Persistent: used to check a database entry exists
     * @public
     * @param {string} dbID
     * @param {string} type
     * @param {string} id
     * @return {boolean}
     */
    self.existPersistent = function(dbID, type, id) {

        try {
            return self.getPersistent(dbID, type, id) !== null;
        } catch(e) {
            Console.error('DataStore.existPersistent', e);
        }

    };

    /**
     * Persistent: used to clear all the database
     * @public
     * @param {type} name
     * @return {boolean}
     */
    self.resetPersistent = function() {

        try {
            try {
                self.storagePersistent.clear();

                Console.info('Persistent database cleared.');

                return true;
            }

            catch(e) {
                Console.error('Error while clearing persistent database', e);
            }

            return false;
        } catch(e) {
            Console.error('DataStore.resetPersistent', e);
        }

    };

    /**
     * Return class scope
     */
    return self;

})();
<|endoftext|>


<commit_before>
import MultiVisualization from 'asNEAT/multiVisualization';
import NetworkVisualization from 'asNEAT/networkVisualization';
import ForceVisualization from 'asNEAT/forceVisualization';
import OfflineSpectrogram from 'asNEAT/offlineSpectrogram';
import LiveSpectrogram from 'asNEAT/liveSpectrogram';
import InstrumentVisualization from 'asNEAT/instrumentVisualization';
import RequestAnimationInstrumentVisualization from 'asNEAT/requestAnimationInstrumentVisualization';
var Visualizer = {};

Visualizer.createInstrumentVisualization = function(parameters) {
    return new InstrumentVisualization(parameters);
};

Visualizer.createRequestAnimationInstrumentVisualization = function(parameters) {
  return new RequestAnimationInstrumentVisualization(parameters);
};

Visualizer.createMultiVisualization = function(parameters) {

  // TODO: Create other visualizations and pass them in
  var visualizations = [];
  visualizations.push(Visualizer.createLiveSpectrogram(parameters));
  visualizations.push(Visualizer.createForceVisualization(parameters));
  parameters.visualizations = visualizations;

  return new MultiVisualization(parameters);
};

Visualizer.createNetworkVisualization = function(parameters) {
  return new NetworkVisualization(parameters);
};

Visualizer.createForceVisualization = function(parameters) {
  return new ForceVisualization(parameters);
};

Visualizer.createOfflineSpectrogram = function(parameters) {
	return new OfflineSpectrogram(parameters);
};

Visualizer.createLiveSpectrogram = function(parameters) {
  return new LiveSpectrogram(parameters);
};

export default Visualizer;
<commit_msg>might need  the actual requestAnymation Frame handler<commit_after>
import MultiVisualization from 'asNEAT/multiVisualization';
import NetworkVisualization from 'asNEAT/networkVisualization';
import ForceVisualization from 'asNEAT/forceVisualization';
import OfflineSpectrogram from 'asNEAT/offlineSpectrogram';
import LiveSpectrogram from 'asNEAT/liveSpectrogram';
import InstrumentVisualization from 'asNEAT/instrumentVisualization';

var oldAnimationTimestamp = null;
var requestAnimationHandlerIds = 0;
var registeredAnimationFrameHandlers = {};
function renderVisualizationFrame(timestamp) {
  if (!oldAnimationTimestamp) oldAnimationTimestamp = timestamp;
  var deltaTime = timestamp - oldAnimationTimestamp;
  _.forEach(registeredAnimationFrameHandlers, function(handler) {
    handler();
  });
  window.requestAnimationFrame(renderVisualizationFrame);
}
window.requestAnimationFrame(renderVisualizationFrame);

var Visualizer = {};

Visualizer.registerRequestAnimationHandler = function(handler) {
  var id = ++requestAnimationHandlerIds;
  registeredAnimationFrameHandlers[id] = handler;
  return id;
};
Visualizer.unregisterRequestAnimationHandler = function(id) {
  delete registeredAnimationFrameHandlers[id];
};

Visualizer.createInstrumentVisualization = function(parameters) {
    return new InstrumentVisualization(parameters);
};

Visualizer.createMultiVisualization = function(parameters) {

  // TODO: Create other visualizations and pass them in
  var visualizations = [];
  visualizations.push(Visualizer.createLiveSpectrogram(parameters));
  visualizations.push(Visualizer.createForceVisualization(parameters));
  parameters.visualizations = visualizations;

  return new MultiVisualization(parameters);
};

Visualizer.createNetworkVisualization = function(parameters) {
  return new NetworkVisualization(parameters);
};

Visualizer.createForceVisualization = function(parameters) {
  return new ForceVisualization(parameters);
};

Visualizer.createOfflineSpectrogram = function(parameters) {
	return new OfflineSpectrogram(parameters);
};

Visualizer.createLiveSpectrogram = function(parameters) {
  return new LiveSpectrogram(parameters);
};

export default Visualizer;
<|endoftext|>


<commit_before>var assert = require('assert');
var Queue = require('../lib/queue');

describe('Basic Queue', function() {

  it('should succeed', function (done) {
    var q = new Queue(function (n, cb) {
      cb(null, n+1)
    })
    q.on('task_finish', function (taskId, r) {
      assert.equal(r, 2);
      done();
    })
    q.push(1, function (err, r) {
      assert.equal(r, 2);
    })
  });

  it('should fail task if failTaskOnProcessException is true', function (done) {
    var q = new Queue(function (n, cb) {
      throw new Error("failed");
    })
    q.on('task_failed', function (taskId, msg) {
      assert.equal(msg, "failed");
      done();
    })
    q.push(1)
  });

  it('should emit an error if failTaskOnProcessException is false', function (done) {
    var q = new Queue(function (n, cb) {
      throw new Error("failed");
    }, { failTaskOnProcessException: false })
    q.on('error', function () {
      done();
    })
    q.push(1)
  });

  it('should fail', function (done) {
    var q = new Queue(function (n, cb) {
      cb('nope')
    })
    q.on('task_failed', function (taskId, msg) {
      assert.equal(msg, 'nope');
      done();
    })
    q.push(1, function (err, r) {
      assert.equal(err, 'nope');
    })
  });

  it('should run fifo', function (done) {
    var finished = 0;
    var queued = 0;
    var q = new Queue(function (num, cb) { cb() })
    q.on('task_finish', function () {
      if (finished >= 3) {
        done();
      }
    })
    q.on('task_queued', function () {
      queued++;
      if (queued >= 3) {
        q.resume();
      }
    })
    q.pause();
    q.push(1, function (err, r) {
      assert.equal(finished, 0);
      finished++;
    })
    q.push(2, function (err, r) {
      assert.equal(finished, 1);
      finished++;
    })
    q.push(3, function (err, r) {
      assert.equal(finished, 2);
      finished++;
    })
  })

  it('should prioritize', function (done) {
    var q = new Queue(function (num, cb) { cb() }, {
      priority: function (n, cb) {
        if (n === 2) return cb(null, 10);
        if (n === 1) return cb(null, 5);
        return cb(null, 1);
      }
    })
    q.pause();
    var finished = 0;
    var queued = 0;
    q.on('task_queued', function () {
      queued++;
      if (queued === 3) {
        q.resume();
      }
    })
    q.push(3, function (err, r) {
      assert.equal(finished, 2);
      finished++;
    });
    q.push(2, function (err, r) {
      assert.equal(finished, 0);
      finished++;
    });
    q.push(1, function (err, r) {
      assert.equal(finished, 1);
      finished++;
      done()
    });
  })

  it('should run filo', function (done) {
    var finished = 0;
    var queued = 0;
    var q = new Queue(function (num, cb) {
      cb();
    }, { filo: true })
    q.on('task_finish', function () {
      if (finished >= 3) {
        done();
      }
    })
    q.on('task_queued', function () {
      queued++;
      if (queued >= 3) {
        q.resume();
      }
    })
    q.pause();
    q.push(1, function (err, r) {
      assert.equal(finished, 2);
      finished++;
    })
    q.push(2, function (err, r) {
      assert.equal(finished, 1);
      finished++;
    })
    q.push(3, function (err, r) {
      assert.equal(finished, 0);
      finished++;
    })
  })

  it('should filter before process', function (done) {
    var q = new Queue(function (n, cb) { cb(null, n) }, {
      filter: function (n, cb) {
        cb(null, n === 2 ? false : n);
      }
    })
    q.push(2, function (err, r) {
      assert.equal(err, 'input_rejected');
    })
    q.push(3, function (err, r) {
      assert.equal(r, 3);
      done();
    })
  })

  it('should batch delay', function (done) {
    var batches = 0;
    var q = new Queue(function (batch, cb) {
      batches++;
      if (batches === 1) {
        assert.equal(batch.length, 2);
        return cb();
      }
      if (batches === 2) {
        assert.equal(batch.length, 1);
        cb();
        return done();
      }
    }, { batchSize: 2, batchDelay: 2 });
    q.push(1);
    q.push(2);
    q.push(3);
  })

  it('should batch 2', function (done) {
    var finished = 0;
    var q = new Queue(function (batch, cb) {
      finished++;
      assert.equal(batch.length, 1);
      if (finished >= 2) {
        done();
      }
      cb();
    }, { batchSize: 2, batchDelay: 1 });
    q.push(1)
      .on('queued', function () {
        setTimeout(function () {
          q.push(2);
        }, 2)
      })
  })

  it('should drain and empty', function (done) {
    var emptied = false;
    var q = new Queue(function (n, cb) { cb() })
    q.on('empty', function () {
      emptied = true;
    })
    q.on('drain', function () {
      assert.ok(emptied);
      done();
    });
    var queued = 0;
    q.on('task_queued', function () {
      queued++;
      if (queued >= 3) {
        q.resume();
      }
    })
    q.pause();
    q.push(1)
    q.push(2)
    q.push(3)
  })

  it('should queue 50 things', function (done) {
    var q = new Queue(function (n, cb) {
      cb(null, n+1);
    })
    var finished = 0;
    for (var i = 0; i < 50; i++) {
      (function (n) {
        q.push(n, function (err, r) {
          assert.equal(r, n+1);
          finished++;
          if (finished === 50) {
            done();
          }
        })
      })(i)
    }
  })

  it('should concurrently handle tasks', function (done) {
    var concurrent = 0;
    var ok = false;
    var q = new Queue(function (n, cb) {
      var wait = function () {
        if (concurrent === 3) {
          ok = true;
        }
        if (ok) return cb();
        setImmediate(function () {
          wait();
        })
      }
      concurrent++;
      wait();
    }, { concurrent: 3 })
    var finished = 0;
    var finish = function () {
      finished++;
      if (finished >= 4) {
        done();
      }
    }
    q.push(0, finish);
    q.push(1, finish);
    q.push(2, finish);
    q.push(3, finish);
  })

  it('should pause and resume', function (done) {
    var running = false;
    var q = new Queue(function (n, cb) {
      running = true;
      return {
        pause: function () {
          running = false;
        },
        resume: function () {
          running = true;
          cb();
          done();
        }
      }
    })
    q.pause();
    q.push(1)
      .on('started', function () {
        setTimeout(function () {
          assert.ok(running);
          q.pause();
          assert.ok(!running);
          q.resume();
        }, 1)
      })
    assert.ok(!running);
    q.resume();
  })

  it('should timeout and fail', function (done) {
    var tries = 0;
    var q = new Queue(function (n, cb) {
      tries++;
      setTimeout(function () {
        cb(null, 'done!')
      }, 3)
    }, { maxTimeout: 1, maxRetries: 2 })
    q.push(1)
      .on('finish', function (result) {
        assert.ok(false)
      })
      .on('failed', function (err) {
        assert.equal(tries, 2);
        setTimeout(function () {
          done();
        }, 5)
      })
  })

  it('should cancel while running and in queue', function (done) {
    var q = new Queue(function (task, cb) {
      assert.ok(task.n, 2)
      setTimeout(function () {
        q.cancel(1);
      }, 1)
      return {
        cancel: function () {
          done();
        }
      }
    }, {
      id: 'id',
      merge: function (a,b) {
        assert.ok(false);
      }
    })
    q.push({ id: 1, n: 1 })
      .on('queued', function () {
        q.cancel(1, function () {
          q.push({ id: 1, n: 2 });
        })
      });
  })

  it('should stop if precondition fails', function (done) {
    var retries = 0;
    var q = new Queue(function () {
      assert.equal(retries, 2);
      done();
    }, {
      precondition: function (cb) {
        console.log('called precondtiion');
        retries++;
        cb(null, retries === 2)
      },
      preconditionRetryTimeout: 1
    })
    q.push(1);
  })

})
<commit_msg>Adds a test that fails!<commit_after>var assert = require('assert');
var Queue = require('../lib/queue');

describe('Basic Queue', function() {

  it('should succeed', function (done) {
    var q = new Queue(function (n, cb) {
      cb(null, n+1)
    })
    q.on('task_finish', function (taskId, r) {
      assert.equal(r, 2);
      done();
    })
    q.push(1, function (err, r) {
      assert.equal(r, 2);
    })
  });

  it('should fail task if failTaskOnProcessException is true', function (done) {
    var q = new Queue(function (n, cb) {
      throw new Error("failed");
    })
    q.on('task_failed', function (taskId, msg) {
      assert.equal(msg, "failed");
      done();
    })
    q.push(1)
  });

  it('should emit an error if failTaskOnProcessException is false', function (done) {
    var q = new Queue(function (n, cb) {
      throw new Error("failed");
    }, { failTaskOnProcessException: false })
    q.on('error', function () {
      done();
    })
    q.push(1)
  });

  it('should fail', function (done) {
    var q = new Queue(function (n, cb) {
      cb('nope')
    })
    q.on('task_failed', function (taskId, msg) {
      assert.equal(msg, 'nope');
      done();
    })
    q.push(1, function (err, r) {
      assert.equal(err, 'nope');
    })
  });

  it('should run fifo', function (done) {
    var finished = 0;
    var queued = 0;
    var q = new Queue(function (num, cb) { cb() })
    q.on('task_finish', function () {
      if (finished >= 3) {
        done();
      }
    })
    q.on('task_queued', function () {
      queued++;
      if (queued >= 3) {
        q.resume();
      }
    })
    q.pause();
    q.push(1, function (err, r) {
      assert.equal(finished, 0);
      finished++;
    })
    q.push(2, function (err, r) {
      assert.equal(finished, 1);
      finished++;
    })
    q.push(3, function (err, r) {
      assert.equal(finished, 2);
      finished++;
    })
  })

  it('should prioritize', function (done) {
    var q = new Queue(function (num, cb) { cb() }, {
      priority: function (n, cb) {
        if (n === 2) return cb(null, 10);
        if (n === 1) return cb(null, 5);
        return cb(null, 1);
      }
    })
    q.pause();
    var finished = 0;
    var queued = 0;
    q.on('task_queued', function () {
      queued++;
      if (queued === 3) {
        q.resume();
      }
    })
    q.push(3, function (err, r) {
      assert.equal(finished, 2);
      finished++;
    });
    q.push(2, function (err, r) {
      assert.equal(finished, 0);
      finished++;
    });
    q.push(1, function (err, r) {
      assert.equal(finished, 1);
      finished++;
      done()
    });
  })

  it('should run filo', function (done) {
    var finished = 0;
    var queued = 0;
    var q = new Queue(function (num, cb) {
      cb();
    }, { filo: true })
    q.on('task_finish', function () {
      if (finished >= 3) {
        done();
      }
    })
    q.on('task_queued', function () {
      queued++;
      if (queued >= 3) {
        q.resume();
      }
    })
    q.pause();
    q.push(1, function (err, r) {
      assert.equal(finished, 2);
      finished++;
    })
    q.push(2, function (err, r) {
      assert.equal(finished, 1);
      finished++;
    })
    q.push(3, function (err, r) {
      assert.equal(finished, 0);
      finished++;
    })
  })

  it('should filter before process', function (done) {
    var q = new Queue(function (n, cb) { cb(null, n) }, {
      filter: function (n, cb) {
        cb(null, n === 2 ? false : n);
      }
    })
    q.push(2, function (err, r) {
      assert.equal(err, 'input_rejected');
    })
    q.push(3, function (err, r) {
      assert.equal(r, 3);
      done();
    })
  })

  it('should batch delay', function (done) {
    var batches = 0;
    var q = new Queue(function (batch, cb) {
      batches++;
      if (batches === 1) {
        assert.equal(batch.length, 2);
        return cb();
      }
      if (batches === 2) {
        assert.equal(batch.length, 1);
        cb();
        return done();
      }
    }, { batchSize: 2, batchDelay: 2 });
    q.push(1);
    q.push(2);
    q.push(3);
  })

  it('should batch 2', function (done) {
    var finished = 0;
    var q = new Queue(function (batch, cb) {
      finished++;
      assert.equal(batch.length, 1);
      if (finished >= 2) {
        done();
      }
      cb();
    }, { batchSize: 2, batchDelay: 1 });
    q.push(1)
      .on('queued', function () {
        setTimeout(function () {
          q.push(2);
        }, 2)
      })
  })

  it('should drain and empty', function (done) {
    var emptied = false;
    var q = new Queue(function (n, cb) { cb() })
    q.on('empty', function () {
      emptied = true;
    })
    q.on('drain', function () {
      assert.ok(emptied);
      done();
    });
    var queued = 0;
    q.on('task_queued', function () {
      queued++;
      if (queued >= 3) {
        q.resume();
      }
    })
    q.pause();
    q.push(1)
    q.push(2)
    q.push(3)
  })

  it('should drain only once the task is complete', function (done) {
    var finished_task = false;
    var q = new Queue(function (n, cb) {
        finished_task = true;
        cb();
    }, { concurrent: 2 });
    q.on('drain', function () {
      assert.ok(finished_task);
      done();
    });
    q.push(1);
  });

  it('should queue 50 things', function (done) {
    var q = new Queue(function (n, cb) {
      cb(null, n+1);
    })
    var finished = 0;
    for (var i = 0; i < 50; i++) {
      (function (n) {
        q.push(n, function (err, r) {
          assert.equal(r, n+1);
          finished++;
          if (finished === 50) {
            done();
          }
        })
      })(i)
    }
  });

  it('should concurrently handle tasks', function (done) {
    var concurrent = 0;
    var ok = false;
    var q = new Queue(function (n, cb) {
      var wait = function () {
        if (concurrent === 3) {
          ok = true;
        }
        if (ok) return cb();
        setImmediate(function () {
          wait();
        })
      }
      concurrent++;
      wait();
    }, { concurrent: 3 })
    var finished = 0;
    var finish = function () {
      finished++;
      if (finished >= 4) {
        done();
      }
    }
    q.push(0, finish);
    q.push(1, finish);
    q.push(2, finish);
    q.push(3, finish);
  })

  it('should pause and resume', function (done) {
    var running = false;
    var q = new Queue(function (n, cb) {
      running = true;
      return {
        pause: function () {
          running = false;
        },
        resume: function () {
          running = true;
          cb();
          done();
        }
      }
    })
    q.pause();
    q.push(1)
      .on('started', function () {
        setTimeout(function () {
          assert.ok(running);
          q.pause();
          assert.ok(!running);
          q.resume();
        }, 1)
      })
    assert.ok(!running);
    q.resume();
  })

  it('should timeout and fail', function (done) {
    var tries = 0;
    var q = new Queue(function (n, cb) {
      tries++;
      setTimeout(function () {
        cb(null, 'done!')
      }, 3)
    }, { maxTimeout: 1, maxRetries: 2 })
    q.push(1)
      .on('finish', function (result) {
        assert.ok(false)
      })
      .on('failed', function (err) {
        assert.equal(tries, 2);
        setTimeout(function () {
          done();
        }, 5)
      })
  })

  it('should cancel while running and in queue', function (done) {
    var q = new Queue(function (task, cb) {
      assert.ok(task.n, 2)
      setTimeout(function () {
        q.cancel(1);
      }, 1)
      return {
        cancel: function () {
          done();
        }
      }
    }, {
      id: 'id',
      merge: function (a,b) {
        assert.ok(false);
      }
    })
    q.push({ id: 1, n: 1 })
      .on('queued', function () {
        q.cancel(1, function () {
          q.push({ id: 1, n: 2 });
        })
      });
  })

  it('should stop if precondition fails', function (done) {
    var retries = 0;
    var q = new Queue(function () {
      assert.equal(retries, 2);
      done();
    }, {
      precondition: function (cb) {
        console.log('called precondtiion');
        retries++;
        cb(null, retries === 2)
      },
      preconditionRetryTimeout: 1
    })
    q.push(1);
  })

})
<|endoftext|>


<commit_before>isic.models.UserModel = girder.models.UserModel.extend({
    name: function () {
        var name;
        if (this.has('login')) {
            name = this.get('firstName') + ' ' + this.get('lastName') +
                ' (' + this.get('login') + ')';
        } else {
            name = this.get('name');
        }
        return name;
    },

    canAcceptTerms: function () {
        return this.get('permissions').acceptTerms === true;
    },
    setAcceptTerms: function (successCallback) {
        girder.restRequest({
            path: 'user/acceptTerms',
            type: 'POST'
        }).done(_.bind(function (resp) {
            if (_.has(resp, 'extra') && resp.extra === 'hasPermission') {
                // Directly update user permissions
                this.get('permissions').acceptTerms = true;
                this.trigger('change:permissions');
                successCallback(resp);
            }
            // This should not fail
        }, this));
    },
    canCreateDataset: function () {
        return this.get('permissions').createDataset;
    },
    setCanCreateDataset: function (successCallback, failureCallback) {
        girder.restRequest({
            path: 'user/requestCreateDatasetPermission',
            type: 'POST'
        }).done(_.bind(function (resp) {
            if (_.has(resp, 'extra') && resp.extra === 'hasPermission') {
                // Directly update user permissions
                this.get('permissions').createDataset = true;
                this.trigger('change:permissions');
                successCallback(resp);
            } else {
                failureCallback(resp);
            }
        }, this));
    },
    canReviewDataset: function () {
        return this.get('permissions').reviewDataset;
    },
    getSegmentationSkill: function () {
        return this.get('permissions').segmentationSkill;
    },
    canAdminStudy: function () {
        return this.get('permissions').adminStudy;
    }
}, {
    // Static methods
    currentUserCanAcceptTerms: function () {
        if (girder.currentUser) {
            return girder.currentUser.canAcceptTerms();
        } else {
            return window.localStorage.getItem('acceptTerms') === 'true';
        }
    },
    currentUserSetAcceptTerms: function (successCallback) {
        if (girder.currentUser) {
            girder.currentUser.setAcceptTerms(successCallback);
        } else {
            window.localStorage.setItem('acceptTerms', 'true');
            successCallback();
        }
    }
}

);
<commit_msg>Catch exceptions when setting Storage API<commit_after>isic.models.UserModel = girder.models.UserModel.extend({
    name: function () {
        var name;
        if (this.has('login')) {
            name = this.get('firstName') + ' ' + this.get('lastName') +
                ' (' + this.get('login') + ')';
        } else {
            name = this.get('name');
        }
        return name;
    },

    canAcceptTerms: function () {
        return this.get('permissions').acceptTerms === true;
    },
    setAcceptTerms: function (successCallback) {
        girder.restRequest({
            path: 'user/acceptTerms',
            type: 'POST'
        }).done(_.bind(function (resp) {
            if (_.has(resp, 'extra') && resp.extra === 'hasPermission') {
                // Directly update user permissions
                this.get('permissions').acceptTerms = true;
                this.trigger('change:permissions');
                successCallback(resp);
            }
            // This should not fail
        }, this));
    },
    canCreateDataset: function () {
        return this.get('permissions').createDataset;
    },
    setCanCreateDataset: function (successCallback, failureCallback) {
        girder.restRequest({
            path: 'user/requestCreateDatasetPermission',
            type: 'POST'
        }).done(_.bind(function (resp) {
            if (_.has(resp, 'extra') && resp.extra === 'hasPermission') {
                // Directly update user permissions
                this.get('permissions').createDataset = true;
                this.trigger('change:permissions');
                successCallback(resp);
            } else {
                failureCallback(resp);
            }
        }, this));
    },
    canReviewDataset: function () {
        return this.get('permissions').reviewDataset;
    },
    getSegmentationSkill: function () {
        return this.get('permissions').segmentationSkill;
    },
    canAdminStudy: function () {
        return this.get('permissions').adminStudy;
    }
}, {
    // Static methods
    currentUserCanAcceptTerms: function () {
        if (girder.currentUser) {
            return girder.currentUser.canAcceptTerms();
        } else {
            return (window.localStorage.getItem('acceptTerms') === 'true') ||
                   (isic.acceptTerms === true);
        }
    },
    currentUserSetAcceptTerms: function (successCallback) {
        if (girder.currentUser) {
            girder.currentUser.setAcceptTerms(successCallback);
        } else {
            try {
                window.localStorage.setItem('acceptTerms', 'true');
            } catch (e) {
                isic.acceptTerms = true;
            }
            successCallback();
        }
    }
}

);
<|endoftext|>


<commit_before>import addTermToQueryBuilder from './addTermToQueryBuilder'
import { curry, includes, values } from 'lodash'

export const filterAndSortPosts = curry((opts, q) => {
  const { search, sortBy = 'updated', topic, showPinnedFirst, type, boundingBox } = opts
  const sortColumns = {
    votes: 'num_votes',
    updated: 'posts.updated_at'
  }

  const sort = sortColumns[sortBy] || values(sortColumns).find(v => v === sortBy)
  if (!sort) {
    throw new Error(`Cannot sort by "${sortBy}"`)
  }

  const { DISCUSSION, REQUEST, OFFER, PROJECT, EVENT, RESOURCE } = Post.Type

  if (!type || type === 'all' || type === 'all+welcome') {
    q.where(q2 =>
      q2.where('posts.type', 'in', [DISCUSSION, REQUEST, OFFER, PROJECT, EVENT, RESOURCE])
      .orWhere('posts.type', null))
  } else if (type === DISCUSSION) {
    q.where(q2 =>
      q2.where({'posts.type': null})
      .orWhere({'posts.type': DISCUSSION}))
  } else {
    if (!includes(values(Post.Type), type)) {
      throw new Error(`unknown post type: "${type}"`)
    }
    q.where({'posts.type': opts.type})
  }

  if (search) {
    addTermToQueryBuilder(search, q, {
      columns: ['posts.name', 'posts.description']
    })
  }

  if (topic) {
    if (/^\d+$/.test(topic)) { // topic ID
      q.join('posts_tags', 'posts_tags.post_id', 'posts.id')
      q.where('posts_tags.tag_id', topic)
    } else { // topic name
      q.join('posts_tags', 'posts_tags.post_id', 'posts.id')
      q.join('tags', 'posts_tags.tag_id', 'tags.id')
      q.where('tags.name', topic)
    }
  }

  if (boundingBox) {
    q.join('locations', 'locations.id', '=', 'posts.location_id')
    q.whereRaw('locations.center && ST_MakeEnvelope(?, ?, ?, ?, 4326)', [boundingBox[0].lng, boundingBox[0].lat, boundingBox[1].lng, boundingBox[1].lat])
  }

  if (sort === 'posts.updated_at' && showPinnedFirst) {
    q.orderByRaw('communities_posts.pinned_at is null asc, communities_posts.pinned_at desc, posts.updated_at desc')
  } else if (sort) {
    q.orderBy(sort, 'desc')
  }

})

export const filterAndSortUsers = curry(({ autocomplete, boundingBox, search, sortBy }, q) => {
  if (autocomplete) {
    addTermToQueryBuilder(autocomplete, q, {
      columns: ['users.name']
    })
  }

  if (search) {
    q.where('users.id', 'in', FullTextSearch.search({
      term: search,
      type: 'person',
      subquery: true
    }))
  }

  if (sortBy && !['name', 'location', 'join'].includes(sortBy)) {
    throw new Error(`Cannot sort by "${sortBy}"`)
  }

  if (sortBy === 'join') {
    q.orderBy('group_memberships.created_at', 'desc')
  } else {
    q.orderBy(sortBy || 'name', 'asc')
  }

  if (boundingBox) {
    q.join('locations', 'locations.id', '=', 'users.location_id')
    q.whereRaw('locations.center && ST_MakeEnvelope(?, ?, ?, ?, 4326)', [boundingBox[0].lng, boundingBox[0].lat, boundingBox[1].lng, boundingBox[1].lat])
  }
})

export const filterAndSortCommunities = curry((opts, q) => {
  const { search, sortBy = 'name', boundingBox } = opts

  if (search) {
    addTermToQueryBuilder(search, q, {
      columns: ['communities.name']
    })
  }

  if (boundingBox) {
    q.join('locations', 'locations.id', '=', 'communities.location_id')
    q.whereRaw('locations.center && ST_MakeEnvelope(?, ?, ?, ?, 4326)', [boundingBox[0].lng, boundingBox[0].lat, boundingBox[1].lng, boundingBox[1].lat])
  }

  q.orderBy(sortBy)
})
<commit_msg>Add post.created_at sort option to posts search<commit_after>import addTermToQueryBuilder from './addTermToQueryBuilder'
import { curry, includes, values } from 'lodash'

export const filterAndSortPosts = curry((opts, q) => {
  const { search, sortBy = 'updated', topic, showPinnedFirst, type, boundingBox } = opts
  const sortColumns = {
    votes: 'num_votes',
    updated: 'posts.updated_at',
    created: 'posts.created_at'
  }

  const sort = sortColumns[sortBy] || values(sortColumns).find(v => v === sortBy)
  if (!sort) {
    throw new Error(`Cannot sort by "${sortBy}"`)
  }

  const { DISCUSSION, REQUEST, OFFER, PROJECT, EVENT, RESOURCE } = Post.Type

  if (!type || type === 'all' || type === 'all+welcome') {
    q.where(q2 =>
      q2.where('posts.type', 'in', [DISCUSSION, REQUEST, OFFER, PROJECT, EVENT, RESOURCE])
      .orWhere('posts.type', null))
  } else if (type === DISCUSSION) {
    q.where(q2 =>
      q2.where({'posts.type': null})
      .orWhere({'posts.type': DISCUSSION}))
  } else {
    if (!includes(values(Post.Type), type)) {
      throw new Error(`unknown post type: "${type}"`)
    }
    q.where({'posts.type': opts.type})
  }

  if (search) {
    addTermToQueryBuilder(search, q, {
      columns: ['posts.name', 'posts.description']
    })
  }

  if (topic) {
    if (/^\d+$/.test(topic)) { // topic ID
      q.join('posts_tags', 'posts_tags.post_id', 'posts.id')
      q.where('posts_tags.tag_id', topic)
    } else { // topic name
      q.join('posts_tags', 'posts_tags.post_id', 'posts.id')
      q.join('tags', 'posts_tags.tag_id', 'tags.id')
      q.where('tags.name', topic)
    }
  }

  if (boundingBox) {
    q.join('locations', 'locations.id', '=', 'posts.location_id')
    q.whereRaw('locations.center && ST_MakeEnvelope(?, ?, ?, ?, 4326)', [boundingBox[0].lng, boundingBox[0].lat, boundingBox[1].lng, boundingBox[1].lat])
  }

  if (sort === 'posts.updated_at' && showPinnedFirst) {
    q.orderByRaw('communities_posts.pinned_at is null asc, communities_posts.pinned_at desc, posts.updated_at desc')
  } else if (sort) {
    q.orderBy(sort, 'desc')
  }

})

export const filterAndSortUsers = curry(({ autocomplete, boundingBox, search, sortBy }, q) => {
  if (autocomplete) {
    addTermToQueryBuilder(autocomplete, q, {
      columns: ['users.name']
    })
  }

  if (search) {
    q.where('users.id', 'in', FullTextSearch.search({
      term: search,
      type: 'person',
      subquery: true
    }))
  }

  if (sortBy && !['name', 'location', 'join'].includes(sortBy)) {
    throw new Error(`Cannot sort by "${sortBy}"`)
  }

  if (sortBy === 'join') {
    q.orderBy('group_memberships.created_at', 'desc')
  } else {
    q.orderBy(sortBy || 'name', 'asc')
  }

  if (boundingBox) {
    q.join('locations', 'locations.id', '=', 'users.location_id')
    q.whereRaw('locations.center && ST_MakeEnvelope(?, ?, ?, ?, 4326)', [boundingBox[0].lng, boundingBox[0].lat, boundingBox[1].lng, boundingBox[1].lat])
  }
})

export const filterAndSortCommunities = curry((opts, q) => {
  const { search, sortBy = 'name', boundingBox } = opts

  if (search) {
    addTermToQueryBuilder(search, q, {
      columns: ['communities.name']
    })
  }

  if (boundingBox) {
    q.join('locations', 'locations.id', '=', 'communities.location_id')
    q.whereRaw('locations.center && ST_MakeEnvelope(?, ?, ?, ?, 4326)', [boundingBox[0].lng, boundingBox[0].lat, boundingBox[1].lng, boundingBox[1].lat])
  }

  q.orderBy(sortBy)
})
<|endoftext|>


<commit_before>var betterlink;
if(!betterlink){
  (function(d,s,id){
    var js,scripts = d.getElementsByTagName(s),fjs = scripts[0];
    if(!d.getElementById(id) && !scriptsInDomWithBetterlinkSource(scripts)){
    js=d.createElement(s); js.id = id; js.defer = true;
    js.setAttribute('data-script-source','chrome extension');
    js.src="//code.betterlink.io/betterlink.js";
    fjs.parentNode.insertBefore(js,fjs);}
  }(document,'script','betterlink-js'));

  // Chrome Extensions run in an 'isolated world' and cannot
  // interact with JavaScript variables or functions created
  // by the page.
  // http://developer.chrome.com/extensions/content_scripts.html
  // Instead, we can check against the source files for Betterlink
  function scriptsInDomWithBetterlinkSource(scripts) {
    var foundScripts = false;
    // match against a Betterlink script (ex: /betterlink-bespoke.js),
    // excluding poorly-named scripts on the Betterlink homepage
    var scriptInSource = /\/betterlink(?!-site)[^\/]*\.js/;
    for(var i = 0, len = scripts.length; i < len; i++) {
      if(scriptInSource.test(scripts[i].src)) {
        foundScripts = true;
        break;
      }
    }
    return foundScripts;
  }
}
<commit_msg>prevent injection on betterlink.io homepage<commit_after>var betterlink;
if(!betterlink){
  (function(d,s,id){
    var js,scripts = d.getElementsByTagName(s),fjs = scripts[0];
    if(!d.getElementById(id) && !scriptsInDomWithBetterlinkSource(scripts)
          && !onBetterlinkHomepage()) {
      js=d.createElement(s); js.id = id; js.defer = true;
      js.setAttribute('data-script-source','chrome extension');
      js.src="//code.betterlink.io/betterlink.js";
      fjs.parentNode.insertBefore(js,fjs);}
  }(document,'script','betterlink-js'));

  // Chrome Extensions run in an 'isolated world' and cannot
  // interact with JavaScript variables or functions created
  // by the page.
  // http://developer.chrome.com/extensions/content_scripts.html
  // Instead, we can check against the source files for Betterlink
  function scriptsInDomWithBetterlinkSource(scripts) {
    var foundScripts = false;
    // match against a Betterlink script (ex: /betterlink-bespoke.js),
    // excluding poorly-named scripts on the Betterlink homepage
    var scriptInSource = /\/betterlink(?!-site)[^\/]*\.js/;
    for(var i = 0, len = scripts.length; i < len; i++) {
      if(scriptInSource.test(scripts[i].src)) {
        foundScripts = true;
        break;
      }
    }
    return foundScripts;
  }

  // At the moment, there's a problem if we load multiple versions of
  // *different* Betterlink instances on the same page. Because the
  // betterlink.io homepage uses betterlink-bespoke.js to customize
  // the experience, injecting the vanilla betterlink.js before the
  // customized version runs may be unwanted. For now, this prevents
  // that experience specifically.
  // Using exclude_matches in the manifest would also work here, but
  // we've got added flexibility with the TLD this way.
  function onBetterlinkHomepage() {
    // Matches a betterlink host (ex: betterlink.io), but fails
    // if `betterlink` is provided as a third-level domain or
    // higher (ex: betterlink.other-site.com). Also fails for
    // any subdomains of betterlink (ex: code.betterlink.io).
    var onHomepage = /^betterlink\.[^\.]+(?!.*\.)/;
    return onHomepage.test(window.location.host);
  }
}
<|endoftext|>


<commit_before>describe('When Interceptor sends a captured request to Postman', function() {

	beforeEach(function() {
		this.chromeEventOrder = function(args) {
			onBeforeRequest(args);
			onBeforeSendHeaders(args);
			onSendHeaders(args);
		}
		sinon.stub(chrome.runtime ,'sendMessage');
	});

	it("No request should be captured to Postman by default", function() {
        var request = getNewRequest(1);
		this.chromeEventOrder(request);
		expect(chrome.runtime.sendMessage.called).toBe(false);
	});

	it("Should capture a request when Toggle is ON.", function() {
		appOptions.isCaptureStateEnabled = true;
        var request = getNewRequest(1);
		this.chromeEventOrder(request);

		expect(chrome.runtime.sendMessage.args[0][0]).toBe('POSTMAN');
		expect(chrome.runtime.sendMessage.args[0][1].postmanMessage.reqId).toBe(1);
		expect(chrome.runtime.sendMessage.args[0][1].postmanMessage.request).toBe(request);

		appOptions.isCaptureStateEnabled = false;
	});

    it("Filter should allow all domains by default", function() {
        appOptions.isCaptureStateEnabled = true;
        expect(appOptions.filterRequestUrl).toBe(".*");
        var request = getNewRequest(1);
        this.chromeEventOrder(request);

        expect(chrome.runtime.sendMessage.called).toBe(true);
        expect(chrome.runtime.sendMessage.args[0][1].postmanMessage.reqId).toBe(1);
    });

    it("Filter should block incorrect domains when enabled", function() {
        appOptions.isCaptureStateEnabled = true;
        appOptions.filterRequestUrl = "google";
        var request = getNewRequest(1);
        this.chromeEventOrder(request);

        expect(chrome.runtime.sendMessage.called).toBe(false);

        appOptions.filterRequestUrl = ".*";
    });

    it("Filter should allow correct domains when enabled", function() {
        appOptions.isCaptureStateEnabled = true;
        appOptions.filterRequestUrl = "google";
        var request = getNewRequest(2);
        request.url = "www.google.com/someXHR";
        this.chromeEventOrder(request);

        expect(chrome.runtime.sendMessage.called).toBe(true);
        expect(chrome.runtime.sendMessage.args[0][1].postmanMessage.reqId).toBe(2);

        appOptions.filterRequestUrl = ".*";
    });

    it("Postman requests should not be captured", function(){
        appOptions.isCaptureStateEnabled = true;
        var request = getNewRequest(3);
        // set a postman header to mock a postman request
        request.requestHeaders = [ { name: "Postman-Token", value: "1" } ];
        this.chromeEventOrder(request);

        expect(chrome.runtime.sendMessage.called).toBe(false);
    });

    it("clears cache on each request", function() {
    });

	afterEach(function() {
		this.chromeEventOrder = null;
        appOptions.isCaptureStateEnabled = false;
		chrome.runtime.sendMessage.restore();
	});

});

describe("When Postman sends a message to Interceptor", function() {

    it("Toggle should send correct message to interceptor", function() {
        var postmanMessage = getPostmanMessage("detectExtension");
        var sender = { id: 1 };
        var sendResponse = sinon.stub();
        onExternalMessage(postmanMessage, sender, sendResponse);

        expect(sendResponse.called).toBe(true);
        expect(sendResponse.callCount).toBe(2);
        expect(sendResponse.args[0][0].result).toBe("Ok, got your message");
    });

    it("Interceptor should recieve XHR request from Postman", function() {
        var postmanMessage = getPostmanMessage("xhrRequest");
        var sender = { id: 1 };
        var sendResponse = sinon.stub();
        sinon.stub(window, 'sendXhrRequest');
        onExternalMessage(postmanMessage, sender, sendResponse);

        expect(sendResponse.called).toBe(true);
        expect(sendResponse.calledOnce).toBe(true);
        expect(sendResponse.args[0][0].result).toBe("Ok, got your message");
        expect(sendXhrRequest.called).toBe(true);
        expect(sendXhrRequest.args[0][0].headers[0]["key"]).toBe("Postman-Token");
    });

});
<commit_msg>Removed infeasible test<commit_after>describe('When Interceptor sends a captured request to Postman', function() {

	beforeEach(function() {
		this.chromeEventOrder = function(args) {
			onBeforeRequest(args);
			onBeforeSendHeaders(args);
			onSendHeaders(args);
		}
		sinon.stub(chrome.runtime ,'sendMessage');
	});

	it("No request should be captured to Postman by default", function() {
        var request = getNewRequest(1);
		this.chromeEventOrder(request);
		expect(chrome.runtime.sendMessage.called).toBe(false);
	});

	it("Should capture a request when Toggle is ON.", function() {
		appOptions.isCaptureStateEnabled = true;
        var request = getNewRequest(1);
		this.chromeEventOrder(request);

		expect(chrome.runtime.sendMessage.args[0][0]).toBe('POSTMAN');
		expect(chrome.runtime.sendMessage.args[0][1].postmanMessage.reqId).toBe(1);
		expect(chrome.runtime.sendMessage.args[0][1].postmanMessage.request).toBe(request);

		appOptions.isCaptureStateEnabled = false;
	});

    it("Filter should allow all domains by default", function() {
        appOptions.isCaptureStateEnabled = true;
        expect(appOptions.filterRequestUrl).toBe(".*");
        var request = getNewRequest(1);
        this.chromeEventOrder(request);

        expect(chrome.runtime.sendMessage.called).toBe(true);
        expect(chrome.runtime.sendMessage.args[0][1].postmanMessage.reqId).toBe(1);
    });

    it("Filter should block incorrect domains when enabled", function() {
        appOptions.isCaptureStateEnabled = true;
        appOptions.filterRequestUrl = "google";
        var request = getNewRequest(1);
        this.chromeEventOrder(request);

        expect(chrome.runtime.sendMessage.called).toBe(false);

        appOptions.filterRequestUrl = ".*";
    });

    it("Filter should allow correct domains when enabled", function() {
        appOptions.isCaptureStateEnabled = true;
        appOptions.filterRequestUrl = "google";
        var request = getNewRequest(2);
        request.url = "www.google.com/someXHR";
        this.chromeEventOrder(request);

        expect(chrome.runtime.sendMessage.called).toBe(true);
        expect(chrome.runtime.sendMessage.args[0][1].postmanMessage.reqId).toBe(2);

        appOptions.filterRequestUrl = ".*";
    });

    it("Postman requests should not be captured", function(){
        appOptions.isCaptureStateEnabled = true;
        var request = getNewRequest(3);
        // set a postman header to mock a postman request
        request.requestHeaders = [ { name: "Postman-Token", value: "1" } ];
        this.chromeEventOrder(request);

        expect(chrome.runtime.sendMessage.called).toBe(false);
    });

	afterEach(function() {
		this.chromeEventOrder = null;
        appOptions.isCaptureStateEnabled = false;
		chrome.runtime.sendMessage.restore();
	});

});

describe("When Postman sends a message to Interceptor", function() {

    it("Toggle should send correct message to interceptor", function() {
        var postmanMessage = getPostmanMessage("detectExtension");
        var sender = { id: 1 };
        var sendResponse = sinon.stub();
        onExternalMessage(postmanMessage, sender, sendResponse);

        expect(sendResponse.called).toBe(true);
        expect(sendResponse.callCount).toBe(2);
        expect(sendResponse.args[0][0].result).toBe("Ok, got your message");
    });

    it("Interceptor should recieve XHR request from Postman", function() {
        var postmanMessage = getPostmanMessage("xhrRequest");
        var sender = { id: 1 };
        var sendResponse = sinon.stub();
        sinon.stub(window, 'sendXhrRequest');
        onExternalMessage(postmanMessage, sender, sendResponse);

        expect(sendResponse.called).toBe(true);
        expect(sendResponse.calledOnce).toBe(true);
        expect(sendResponse.args[0][0].result).toBe("Ok, got your message");
        expect(sendXhrRequest.called).toBe(true);
        expect(sendXhrRequest.args[0][0].headers[0]["key"]).toBe("Postman-Token");
    });

});
<|endoftext|>


<commit_before>/* global angular */
(function () {
    'use strict';

    angular
        .module('components.sidenav')
        .component('sideNav', {
            templateUrl: 'components/sidenav/sidenav.tmpl.html',
            controllerAs: 'vm',
            controller: sideNavController
        });

    function sideNavController($rootScope, routerHelper, semver, sideNavService) {
        var vm = this;

        var allStates = routerHelper.getStates();
        vm.close = sideNavService.close;
        vm.$onInit = activate;
        vm.isSmallMenu = isSmallMenu;
        vm.hasUpdate = hasUpdate;

        function activate() {
            getNavRoutes();
            getVersionInfo();
        }

        function getNavRoutes() {
            vm.navItems = allStates.filter(function (r) {
                return r.settings && r.settings.weight;
            }).sort(function (r1, r2) {
                return r1.settings.weight - r2.settings.weight;
            });
        }

        function getVersionInfo() {
            sideNavService.getVersionInfo().then(function (data) {
                vm.versions = data;
            });
        }

        function hasUpdate(current, latest) {
            return semver(vm.versions.latest_version, vm.versions.flexget_version);
        }

        function isSmallMenu() {
            return $rootScope.menuMini;
        }
    }
}());<commit_msg>[Fix][UI] improves version checking, fixes #1617<commit_after>/* global angular */
(function () {
    'use strict';

    angular
        .module('components.sidenav')
        .component('sideNav', {
            templateUrl: 'components/sidenav/sidenav.tmpl.html',
            controllerAs: 'vm',
            controller: sideNavController
        });

    function sideNavController($rootScope, routerHelper, semver, sideNavService) {
        var vm = this;

        var allStates = routerHelper.getStates();
        vm.close = sideNavService.close;
        vm.$onInit = activate;
        vm.isSmallMenu = isSmallMenu;
        vm.hasUpdate = hasUpdate;

        function activate() {
            getNavRoutes();
            getVersionInfo();
        }

        function getNavRoutes() {
            vm.navItems = allStates.filter(function (r) {
                return r.settings && r.settings.weight;
            }).sort(function (r1, r2) {
                return r1.settings.weight - r2.settings.weight;
            });
        }

        function getVersionInfo() {
            sideNavService.getVersionInfo().then(function (data) {
                vm.versions = data;
            });
        }

        function hasUpdate(current, latest) {
            return semver(vm.versions.latest_version, vm.versions.flexget_version) === 1;
        }

        function isSmallMenu() {
            return $rootScope.menuMini;
        }
    }
}());<|endoftext|>