<commit_before>var hammerhead    = window.getTestCafeModule('hammerhead');
var browserUtils  = hammerhead.utils.browser;
var iframeSandbox = hammerhead.sandbox.iframe;

var testCafeCore  = window.getTestCafeModule('testCafeCore');
var SETTINGS      = testCafeCore.get('./settings').get();
var ERROR_TYPE    = testCafeCore.ERROR_TYPE;
var domUtils      = testCafeCore.get('./utils/dom');
var textSelection = testCafeCore.get('./utils/text-selection');

var testCafeRunner = window.getTestCafeModule('testCafeRunner');
var actionsAPI     = testCafeRunner.get('./api/actions');
var automation     = testCafeRunner.get('./automation/automation');
var StepIterator   = testCafeRunner.get('./step-iterator');

automation.init();

var stepIterator = new StepIterator();
actionsAPI.init(stepIterator);

$(document).ready(function () {
    StepIterator.prototype.asyncActionSeries = function (items, runArgumentsIterator, action) {
        var seriesActionsRun = function (elements, callback) {
            window.async.forEachSeries(
                elements,
                function (element, seriaCallback) {
                    action(element, seriaCallback);
                },
                function () {
                    callback();
                });
        };

        runArgumentsIterator(items, seriesActionsRun, asyncActionCallback);
    };

    stepIterator.on(StepIterator.ERROR_EVENT, function (err) {
        stepIterator.state.stoppedOnFail = false;
        currentErrorType                 = err.type;
        currentSourceIndex               = err.__sourceIndex;
    });

    var asyncActionCallback,
        currentErrorType   = null,
        currentSourceIndex = null,
        $input,

        //constants
        TEST_ELEMENT_CLASS = 'testElement',
        TEST_TIMEOUT       = 2000,

        //utils
        createIFrame       = function (src) {
            var $iframe = $('')
                .css({
                    width:  '600px',
                    height: '600px'
                })
                .addClass(TEST_ELEMENT_CLASS);

            $iframe[0].setAttribute('src', src);

            return $iframe[0];
        },

        runAsyncTest       = function (actions, assertions, timeout, delayBeforeAssertions) {
            var callbackFunction = function () {
                clearTimeout(timeoutId);
                assertions();
                start();
            };
            asyncActionCallback  = function () {
                window.setTimeout(callbackFunction, delayBeforeAssertions || 0);
            };
            actions();
            var timeoutId        = setTimeout(function () {
                callbackFunction = function () {
                };
                ok(false, 'Timeout is exceeded');
                start();
            }, timeout);
        };

    //tests
    QUnit.testStart(function () {
        $input              = $('<input type="text" id="input" class="input"/>').addClass(TEST_ELEMENT_CLASS).appendTo($('body'));
        $input[0].value     = 'test';
        $input[0].focus();
        textSelection.select($input[0], 4, 4);
        asyncActionCallback = function () {
        };
        iframeSandbox.on(iframeSandbox.RUN_TASK_SCRIPT, window.initIFrameTestHandler);
        iframeSandbox.off(iframeSandbox.RUN_TASK_SCRIPT, iframeSandbox.iframeReadyToInitHandler);
    });

    QUnit.testDone(function () {
        $('.' + TEST_ELEMENT_CLASS).remove();
        currentErrorType             = null;
        currentSourceIndex           = null;
        SETTINGS.ENABLE_SOURCE_INDEX = false;
        iframeSandbox.off(iframeSandbox.RUN_TASK_SCRIPT, window.initIFrameTestHandler);
    });

    module('parse keys string');

    asyncTest('press correct symbol', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('a');
            },
            function () {
                equal(currentErrorType, null);
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press correct symbol with spaces', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('a ');
            },
            function () {
                equal(currentErrorType, null);
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press correct keys combination', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('g h g+h  f t');
            },
            function () {
                equal(currentErrorType, null);
            },
            3000
        );
    });

    asyncTest('press correct keys combination with shortcuts', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('g home g+h  f t left+right');
            },
            function () {
                equal(currentErrorType, null);
            },
            3000
        );
    });

    asyncTest('press incorrect keys combination', function () {
        SETTINGS.ENABLE_SOURCE_INDEX = true;
        actionsAPI.press('incorrect', '#11');
        setTimeout(function () {
            equal(currentErrorType, ERROR_TYPE.incorrectPressActionArgument);
            equal(currentSourceIndex, 11);

            start();
        }, 300);
    });

    module('different scenarios');

    asyncTest('press a', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('left a');
            },
            function () {
                equal($input[0].value, 'tesat');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press +', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('+ shift++');
            },
            function () {
                equal($input[0].value, 'test++');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press space', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('left space');
            },
            function () {
                equal($input[0].value, 'tes t');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press shift+a', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('shift+a');
            },
            function () {
                equal($input[0].value, 'testA');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press shift+1', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('shift+1');
            },
            function () {
                equal($input[0].value, 'test!');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press tab', function () {
        domUtils.getActiveElement().blur();
        $('body').focus();
        $input.attr('tabIndex', 1);
        runAsyncTest(
            function () {
                actionsAPI.press('tab');
            },
            function () {
                deepEqual(domUtils.getActiveElement(), $input[0]);
                equal($input[0].selectionStart, 0);
                equal($input[0].selectionEnd, $input[0].value.length);
            },
            3000
        );
    });

    asyncTest('press tab with tabIndexes', function () {
        var $input2 = $('<input type="text" id="$input2" class="input"/>')
            .addClass(TEST_ELEMENT_CLASS)
            .appendTo($('body'))
            .attr('tabIndex', 1);
        $input.attr('tabIndex', 2);
        domUtils.getActiveElement().blur();
        $('body').focus();
        runAsyncTest(
            function () {
                actionsAPI.press('tab');
            },
            function () {
                deepEqual(domUtils.getActiveElement(), $input2[0]);
            },
            3000
        );
    });

    asyncTest('press tab with iframe', function () {
        var $iframe = $('')
            .addClass(TEST_ELEMENT_CLASS)
            .appendTo($('body'));

        var $iframeInput = $('<input type="text" id="iframeInput"/>')
            .addClass(TEST_ELEMENT_CLASS);

        runAsyncTest(
            function () {
                window.QUnitGlobals.waitForIframe($iframe[0])
                    .then(function () {
                        $($iframe.contents()[0]).find('body').append($iframeInput);

                        domUtils.getActiveElement().blur();
                        $input.focus();

                        actionsAPI.press('tab');
                    });
            },
            function () {
                ok(domUtils.getActiveElement() !== $input[0]);
            },
            5000
        );

    });

    module('Regression tests');

    asyncTest('B238757 - It is impossible to record and run \'press\' action with \'+\' key', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('+');
            },
            function () {
                equal($input[0].value, 'test+');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('B253200 - TestCafe doesn\'t emulate browsers behavior for press "enter" key on the focused HyperLink editor (link with href)', function () {
        var iFrameSrc = window.QUnitGlobals.getResourceUrl('../../../data/runner/iframe.html', 'runner-iframe.html');
        var linkHref  = window.QUnitGlobals.getResourceUrl('../../../data/focus-blur-change/iframe.html', 'focus-iframe.html');
        var link      = $('Link').attr('href', linkHref).addClass(TEST_ELEMENT_CLASS)[0];
        var iframe    = createIFrame(iFrameSrc);
        var clicked   = false;

        link.onclick = function () {
            clicked = true;
        };

        runAsyncTest(
            function () {
                window.QUnitGlobals.waitForIframe(iframe)
                    .then(function () {
                        equal(iframe.contentWindow.location.pathname, '/sessionId!i/https://example.com/test-resource/runner-iframe.html', 'path is correct before click on link');

                        iframe.contentDocument.body.appendChild(link);
                        link.focus();

                        //NOTE: we need setTimeout to wait for focus in IE
                        window.setTimeout(function () {
                            equal(domUtils.getActiveElement(), iframe);
                            equal(domUtils.getActiveElement(iframe.contentDocument), link);

                            actionsAPI.press('enter');
                        }, 1000);
                    });

                document.body.appendChild(iframe);
            },
            function () {
                equal(iframe.contentWindow.location.pathname, '/sessionId/https://example.com/test-resource/focus-iframe.html', 'path is correct after click on link');
                ok(clicked);
            },
            5000,
            1000
        );
    });

    asyncTest('B253200 - TestCafe doesn\'t emulate browsers behavior for press "enter" key on the focused HyperLink editor (link with javascript)', function () {
        var iFrameSrc = window.QUnitGlobals.getResourceUrl('../../../data/runner/iframe.html', 'runner-iframe.html');
        var linkHref  = window.QUnitGlobals.getResourceUrl('../../../data/focus-blur-change/iframe.html', 'focus-iframe.html');
        var link      = $('Link').attr('href', 'javascript: window.location.href = "' + linkHref + '"')[0];
        var iframe    = createIFrame(iFrameSrc);
        var clicked   = false;

        link.onclick = function () {
            clicked = true;
        };

        runAsyncTest(
            function () {
                window.QUnitGlobals.waitForIframe(iframe)
                    .then(function () {
                        equal(iframe.contentWindow.location.pathname, '/sessionId!i/https://example.com/test-resource/runner-iframe.html', 'path is correct before click on link');

                        iframe.contentWindow.document.body.appendChild(link);
                        link.focus();

                        //NOTE: we need setTimeout to wait for focus in IE
                        window.setTimeout(function () {
                            equal(domUtils.getActiveElement(), iframe);
                            equal(domUtils.getActiveElement(iframe.contentDocument), link);

                            actionsAPI.press('enter');
                        }, 1000);
                    });

                document.body.appendChild(iframe);
            },
            function () {
                equal(iframe.contentWindow.location.pathname, '/sessionId!i/https://example.com/test-resource/focus-iframe.html', 'path is correct after click on link');
                ok(clicked);
            },
            5000,
            1000
        );
    });
});
<commit_msg>Fixed QUnit test - B253200 (part of #471) (#507)<commit_after>var hammerhead    = window.getTestCafeModule('hammerhead');
var browserUtils  = hammerhead.utils.browser;
var iframeSandbox = hammerhead.sandbox.iframe;

var testCafeCore  = window.getTestCafeModule('testCafeCore');
var SETTINGS      = testCafeCore.get('./settings').get();
var ERROR_TYPE    = testCafeCore.ERROR_TYPE;
var domUtils      = testCafeCore.get('./utils/dom');
var textSelection = testCafeCore.get('./utils/text-selection');

var testCafeRunner = window.getTestCafeModule('testCafeRunner');
var actionsAPI     = testCafeRunner.get('./api/actions');
var automation     = testCafeRunner.get('./automation/automation');
var StepIterator   = testCafeRunner.get('./step-iterator');

var Promise = hammerhead.Promise;

automation.init();

var stepIterator = new StepIterator();
actionsAPI.init(stepIterator);

$(document).ready(function () {
    StepIterator.prototype.asyncActionSeries = function (items, runArgumentsIterator, action) {
        var seriesActionsRun = function (elements, callback) {
            window.async.forEachSeries(
                elements,
                function (element, seriaCallback) {
                    action(element, seriaCallback);
                },
                function () {
                    callback();
                });
        };

        runArgumentsIterator(items, seriesActionsRun, asyncActionCallback);
    };

    stepIterator.on(StepIterator.ERROR_EVENT, function (err) {
        stepIterator.state.stoppedOnFail = false;
        currentErrorType                 = err.type;
        currentSourceIndex               = err.__sourceIndex;
    });

    var asyncActionCallback,
        currentErrorType   = null,
        currentSourceIndex = null,
        $input,

        //constants
        TEST_ELEMENT_CLASS = 'testElement',
        TEST_TIMEOUT       = 2000,

        //utils
        createIFrame       = function (src) {
            var $iframe = $('')
                .css({
                    width:  '600px',
                    height: '600px'
                })
                .addClass(TEST_ELEMENT_CLASS);

            $iframe[0].setAttribute('src', src);

            return $iframe[0];
        },

        runAsyncTest       = function (actions, assertions, timeout, delayBeforeAssertions) {
            var callbackFunction = function () {
                clearTimeout(timeoutId);
                assertions();
                start();
            };
            asyncActionCallback  = function () {
                window.setTimeout(callbackFunction, delayBeforeAssertions || 0);
            };
            actions();
            var timeoutId = setTimeout(function () {
                callbackFunction = function () {
                };
                ok(false, 'Timeout is exceeded');
                start();
            }, timeout);
        };

    var waitForIframeReloaded = function (iframe) {
        var iframeUnloadPromise = new Promise(function (resolve) {
            iframe.contentWindow.addEventListener('unload', resolve);
        });

        return iframeUnloadPromise.then(function () {
            return window.QUnitGlobals.waitForIframe(iframe);
        });
    };

    var wait = function (ms) {
        return new Promise(function (resolve) {
            window.setTimeout(resolve, ms);
        });
    };

    //tests
    QUnit.testStart(function () {
        $input          = $('<input type="text" id="input" class="input"/>').addClass(TEST_ELEMENT_CLASS).appendTo($('body'));
        $input[0].value = 'test';
        $input[0].focus();
        textSelection.select($input[0], 4, 4);
        asyncActionCallback = function () {
        };
        iframeSandbox.on(iframeSandbox.RUN_TASK_SCRIPT, window.initIFrameTestHandler);
        iframeSandbox.off(iframeSandbox.RUN_TASK_SCRIPT, iframeSandbox.iframeReadyToInitHandler);
    });

    QUnit.testDone(function () {
        $('.' + TEST_ELEMENT_CLASS).remove();
        currentErrorType             = null;
        currentSourceIndex           = null;
        SETTINGS.ENABLE_SOURCE_INDEX = false;
        iframeSandbox.off(iframeSandbox.RUN_TASK_SCRIPT, window.initIFrameTestHandler);
    });

    module('parse keys string');

    asyncTest('press correct symbol', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('a');
            },
            function () {
                equal(currentErrorType, null);
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press correct symbol with spaces', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('a ');
            },
            function () {
                equal(currentErrorType, null);
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press correct keys combination', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('g h g+h  f t');
            },
            function () {
                equal(currentErrorType, null);
            },
            3000
        );
    });

    asyncTest('press correct keys combination with shortcuts', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('g home g+h  f t left+right');
            },
            function () {
                equal(currentErrorType, null);
            },
            3000
        );
    });

    asyncTest('press incorrect keys combination', function () {
        SETTINGS.ENABLE_SOURCE_INDEX = true;
        actionsAPI.press('incorrect', '#11');
        setTimeout(function () {
            equal(currentErrorType, ERROR_TYPE.incorrectPressActionArgument);
            equal(currentSourceIndex, 11);

            start();
        }, 300);
    });

    module('different scenarios');

    asyncTest('press a', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('left a');
            },
            function () {
                equal($input[0].value, 'tesat');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press +', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('+ shift++');
            },
            function () {
                equal($input[0].value, 'test++');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press space', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('left space');
            },
            function () {
                equal($input[0].value, 'tes t');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press shift+a', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('shift+a');
            },
            function () {
                equal($input[0].value, 'testA');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press shift+1', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('shift+1');
            },
            function () {
                equal($input[0].value, 'test!');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('press tab', function () {
        domUtils.getActiveElement().blur();
        $('body').focus();
        $input.attr('tabIndex', 1);
        runAsyncTest(
            function () {
                actionsAPI.press('tab');
            },
            function () {
                deepEqual(domUtils.getActiveElement(), $input[0]);
                equal($input[0].selectionStart, 0);
                equal($input[0].selectionEnd, $input[0].value.length);
            },
            3000
        );
    });

    asyncTest('press tab with tabIndexes', function () {
        var $input2 = $('<input type="text" id="$input2" class="input"/>')
            .addClass(TEST_ELEMENT_CLASS)
            .appendTo($('body'))
            .attr('tabIndex', 1);
        $input.attr('tabIndex', 2);
        domUtils.getActiveElement().blur();
        $('body').focus();
        runAsyncTest(
            function () {
                actionsAPI.press('tab');
            },
            function () {
                deepEqual(domUtils.getActiveElement(), $input2[0]);
            },
            3000
        );
    });

    asyncTest('press tab with iframe', function () {
        var $iframe = $('')
            .addClass(TEST_ELEMENT_CLASS)
            .appendTo($('body'));

        var $iframeInput = $('<input type="text" id="iframeInput"/>')
            .addClass(TEST_ELEMENT_CLASS);

        runAsyncTest(
            function () {
                window.QUnitGlobals.waitForIframe($iframe[0])
                    .then(function () {
                        $($iframe.contents()[0]).find('body').append($iframeInput);

                        domUtils.getActiveElement().blur();
                        $input.focus();

                        actionsAPI.press('tab');
                    });
            },
            function () {
                ok(domUtils.getActiveElement() !== $input[0]);
            },
            5000
        );

    });

    module('Regression tests');

    asyncTest('B238757 - It is impossible to record and run \'press\' action with \'+\' key', function () {
        runAsyncTest(
            function () {
                actionsAPI.press('+');
            },
            function () {
                equal($input[0].value, 'test+');
            },
            TEST_TIMEOUT
        );
    });

    asyncTest('B253200 - TestCafe doesn\'t emulate browsers behavior for press "enter" key on the focused HyperLink editor (link with href)', function () {
        var iFrameSrc    = window.QUnitGlobals.getResourceUrl('../../../data/runner/iframe.html', 'runner-iframe.html');
        var linkHref     = window.QUnitGlobals.getResourceUrl('../../../data/focus-blur-change/iframe.html', 'focus-iframe.html');
        var link         = $('Link').attr('href', linkHref).addClass(TEST_ELEMENT_CLASS)[0];
        var iframe       = createIFrame(iFrameSrc);
        var clicked      = false;
        var testFinished = false;

        link.onclick = function () {
            clicked = true;
        };

        var watchdog = wait(10000);

        var runTest = function () {
            return window.QUnitGlobals
                .waitForIframe(iframe)
                .then(function () {
                    equal(iframe.contentWindow.location.pathname, '/sessionId!i/https://example.com/test-resource/runner-iframe.html', 'path is correct before click on link');

                    iframe.contentDocument.body.appendChild(link);
                    link.focus();

                    // NOTE: we need setTimeout to wait for focus in IE
                    return wait(browserUtils.isIE ? 1000 : 0);
                })
                .then(function () {
                    equal(domUtils.getActiveElement(), iframe);
                    equal(domUtils.getActiveElement(iframe.contentDocument), link);

                    actionsAPI.press('enter');

                    return waitForIframeReloaded(iframe);
                })
                .then(function () {
                    equal(iframe.contentWindow.location.pathname, '/sessionId/https://example.com/test-resource/focus-iframe.html', 'path is correct before click on link');
                    ok(clicked);

                    testFinished = true;
                });
        };

        Promise
            .race([watchdog, runTest()])
            .then(function () {
                if (!testFinished)
                    ok(false, 'Test timeout is exceed');

                start();
            });

        document.body.appendChild(iframe);
    });

    asyncTest('B253200 - TestCafe doesn\'t emulate browsers behavior for press "enter" key on the focused HyperLink editor (link with javascript)', function () {
        var iFrameSrc    = window.QUnitGlobals.getResourceUrl('../../../data/runner/iframe.html', 'runner-iframe.html');
        var linkHref     = window.QUnitGlobals.getResourceUrl('../../../data/focus-blur-change/iframe.html', 'focus-iframe.html');
        var link         = $('Link').attr('href', 'javascript: window.location.href = "' + linkHref + '"')[0];
        var iframe       = createIFrame(iFrameSrc);
        var clicked      = false;
        var testFinished = false;

        link.onclick = function () {
            clicked = true;
        };

        var watchdog = wait(10000);

        var runTest = function () {
            return window.QUnitGlobals
                .waitForIframe(iframe)
                .then(function () {
                    equal(iframe.contentWindow.location.pathname, '/sessionId!i/https://example.com/test-resource/runner-iframe.html', 'path is correct before click on link');

                    iframe.contentDocument.body.appendChild(link);
                    link.focus();

                    // NOTE: we need setTimeout to wait for focus in IE
                    return wait(browserUtils.isIE ? 1000 : 0);
                })
                .then(function () {
                    equal(domUtils.getActiveElement(), iframe);
                    equal(domUtils.getActiveElement(iframe.contentDocument), link);

                    actionsAPI.press('enter');

                    return waitForIframeReloaded(iframe);
                })
                .then(function () {
                    equal(iframe.contentWindow.location.pathname, '/sessionId!i/https://example.com/test-resource/focus-iframe.html', 'path is correct after click on link');
                    ok(clicked);

                    testFinished = true;
                });
        };

        Promise
            .race([watchdog, runTest()])
            .then(function () {
                if (!testFinished)
                    ok(false, 'Test timeout is exceed');

                start();
            });

        document.body.appendChild(iframe);
    });
});
<|endoftext|>


<commit_before>'use strict';

const globalHooks = require('../../../hooks');
const hooks = require('feathers-hooks');
const auth = require('feathers-authentication');
const _ = require('lodash');
const ClassModel = require('../model').classModel;
const CourseModel = require('../model').courseModel;

const restrictToCurrentSchool = globalHooks.ifNotLocal(globalHooks.restrictToCurrentSchool);
const restrictToUsersOwnCourses = globalHooks.ifNotLocal(globalHooks.restrictToUsersOwnCourses);

/**
 * adds all students to a course when a class is added to the course
 * @param hook - contains created/patched object and request body
 */
const addWholeClassToCourse = (hook) => {
	let requestBody = hook.data;
	let course = hook.result;
	if (requestBody.classIds === undefined) {
		return hook;
	}
	if ((requestBody.classIds || []).length > 0) { // just courses do have a property "classIds"
		return Promise.all(requestBody.classIds.map(classId => {
			return ClassModel.findById(classId).exec().then(c => c.userIds);
		})).then(studentIds => {
			// flatten deep arrays and remove duplicates
			studentIds = _.uniqWith(_.flattenDeep(studentIds), (e1, e2) => JSON.stringify(e1) === JSON.stringify(e2));

			// add all students of classes to course, if not already added
			return Promise.all(studentIds.map(s => {
				if (!_.some(course.userIds, u => JSON.stringify(u) === JSON.stringify(s))) {
					return CourseModel.update({ _id: course._id }, { $push: { userIds: s } }).exec();
				} else {
					return {};
				}
			})).then(_ => hook);
		});
	} else {
		return hook;
	}
};

/**
 * deletes all students from a course when a class is removed from the course
 * this function goes into a before hook before we have to check whether there is a class missing
 * in the patch-body which was in the course before
 * @param hook - contains and request body
 */
const deleteWholeClassFromCourse = (hook) => {
	let requestBody = hook.data;
	let courseId = hook.id;
	if (requestBody.classIds === undefined) {
		return hook;
	}
	return CourseModel.findById(courseId).exec().then(course => {
		if (!course) return hook;

		let removedClasses = _.differenceBy(course.classIds, requestBody.classIds, (v) => JSON.stringify(v));
		if (removedClasses.length < 1) return hook;
		return Promise.all(removedClasses.map(classId => {
			return ClassModel.findById(classId).exec().then(c => (c || []).userIds);
		})).then(studentIds => {
			// flatten deep arrays and remove duplicates
			studentIds = _.uniqWith(_.flattenDeep(studentIds), (e1, e2) => JSON.stringify(e1) === JSON.stringify(e2));

			// remove all students of classes from course, if they are in course
			return Promise.all(studentIds.map(s => {
				if (!_.some(course.userIds, u => JSON.stringify(u) === JSON.stringify(s))) {
					return CourseModel.update({ _id: course._id }, { $pull: { userIds: s } }).exec();
				} else {
					return {};
				}
			})).then(result => {

				// also remove all students from request body for not reading them in after hook
				requestBody.userIds = _.differenceBy(requestBody.userIds, studentIds, (v) => JSON.stringify(v));
				hook.data = requestBody;
				return hook;
			});
		});
	});
};

const courseInviteHook = async context => {
	if (context.path === 'courses' && context.params.query && context.params.query.link) {
		const dbLink = await context.app.service('link').get(context.params.query.link); // link is used as "authorization"
		delete context.params.query.link;
		if (dbLink) return restrictToCurrentSchool(context);
	}

	return restrictToUsersOwnCourses(context);
}

const patchPermissionHook = async context => {
	const query = context.params.query || {};
	const defaultPermissionHook = globalHooks.hasPermission('USERGROUP_EDIT');

	if (query.link) {
		const dbLink = await context.app.service('link').get(query.link); // link is used as "authorization"
		delete context.params.query.link;
		if (dbLink) return context;
	}

	return defaultPermissionHook(context);
}

exports.before = {
	all: [auth.hooks.authenticate('jwt')],
	find: [globalHooks.hasPermission('USERGROUP_VIEW'), restrictToCurrentSchool, restrictToUsersOwnCourses],
	get: [courseInviteHook],
	create: [globalHooks.injectUserId, globalHooks.hasPermission('USERGROUP_CREATE'), restrictToCurrentSchool],
	update: [globalHooks.hasPermission('USERGROUP_EDIT'), restrictToCurrentSchool],
	patch: [patchPermissionHook, restrictToCurrentSchool, globalHooks.permitGroupOperation,
		deleteWholeClassFromCourse],
	remove: [globalHooks.hasPermission('USERGROUP_CREATE'), restrictToCurrentSchool, globalHooks.permitGroupOperation]
};

exports.after = {
	all: [],
	find: [],
	get: [globalHooks.ifNotLocal(globalHooks.denyIfNotCurrentSchool({ errorMessage: 'Die angefragte Gruppe gehört nicht zur eigenen Schule!' }))],
	create: [addWholeClassToCourse],
	update: [],
	patch: [addWholeClassToCourse],
	remove: []
};<commit_msg>optimization and linter<commit_after>const _ = require('lodash');
const auth = require('feathers-authentication');
const globalHooks = require('../../../hooks');
const ClassModel = require('../model').classModel;
const CourseModel = require('../model').courseModel;

const restrictToCurrentSchool = globalHooks.ifNotLocal(globalHooks.restrictToCurrentSchool);
const restrictToUsersOwnCourses = globalHooks.ifNotLocal(globalHooks.restrictToUsersOwnCourses);

/**
 * adds all students to a course when a class is added to the course
 * @param hook - contains created/patched object and request body
 */
const addWholeClassToCourse = (hook) => {
	const requestBody = hook.data;
	const course = hook.result;
	if (requestBody.classIds === undefined) {
		return hook;
	}
	if ((requestBody.classIds || []).length > 0) { // just courses do have a property "classIds"
		return Promise.all(requestBody.classIds.map((classId) => {
			return ClassModel.findById(classId).exec().then(c => c.userIds);
		})).then(async (studentIds) => {
			// flatten deep arrays and remove duplicates
			studentIds = _.uniqWith(_.flattenDeep(studentIds), (e1, e2) => JSON.stringify(e1) === JSON.stringify(e2));

			await CourseModel.update(
				{ _id: course._id },
				{ $addToSet: { userIds: { $each: studentIds } } },
			).exec();
			return hook;
		});
	}
	return hook;
};

/**
 * deletes all students from a course when a class is removed from the course
 * this function goes into a before hook before we have to check whether there is a class missing
 * in the patch-body which was in the course before
 * @param hook - contains and request body
 */
const deleteWholeClassFromCourse = (hook) => {
	const requestBody = hook.data;
	const courseId = hook.id;
	if (requestBody.classIds === undefined) {
		return hook;
	}
	return CourseModel.findById(courseId).exec().then((course) => {
		if (!course) return hook;

		const removedClasses = _.differenceBy(course.classIds, requestBody.classIds, v => JSON.stringify(v));
		if (removedClasses.length < 1) return hook;
		return Promise.all(removedClasses.map((classId) => {
			return ClassModel.findById(classId).exec().then(c => (c || []).userIds);
		})).then(async (studentIds) => {
			// flatten deep arrays and remove duplicates
			studentIds = _.uniqWith(_.flattenDeep(studentIds), (e1, e2) => JSON.stringify(e1) === JSON.stringify(e2));

			// remove class students from course DB and from hook body to not patch them back
			await CourseModel.update(
				{ _id: course._id },
				{ $pull: { userIds: { $in: studentIds } } },
				{ multi: true },
			).exec();
			hook.data.userIds = hook.data.userIds.filter(value => !studentIds.toString().includes(value));
			return hook;
		});
	});
};

const courseInviteHook = async context => {
	if (context.path === 'courses' && context.params.query && context.params.query.link) {
		const dbLink = await context.app.service('link').get(context.params.query.link); // link is used as "authorization"
		delete context.params.query.link;
		if (dbLink) return restrictToCurrentSchool(context);
	}

	return restrictToUsersOwnCourses(context);
}

const patchPermissionHook = async context => {
	const query = context.params.query || {};
	const defaultPermissionHook = globalHooks.hasPermission('USERGROUP_EDIT');

	if (query.link) {
		const dbLink = await context.app.service('link').get(query.link); // link is used as "authorization"
		delete context.params.query.link;
		if (dbLink) return context;
	}

	return defaultPermissionHook(context);
}

exports.before = {
	all: [auth.hooks.authenticate('jwt')],
	find: [globalHooks.hasPermission('USERGROUP_VIEW'), restrictToCurrentSchool, restrictToUsersOwnCourses],
	get: [courseInviteHook],
	create: [globalHooks.injectUserId, globalHooks.hasPermission('USERGROUP_CREATE'), restrictToCurrentSchool],
	update: [globalHooks.hasPermission('USERGROUP_EDIT'), restrictToCurrentSchool],
	patch: [patchPermissionHook, restrictToCurrentSchool, globalHooks.permitGroupOperation,
		deleteWholeClassFromCourse],
	remove: [globalHooks.hasPermission('USERGROUP_CREATE'), restrictToCurrentSchool, globalHooks.permitGroupOperation]
};

exports.after = {
	all: [],
	find: [],
	get: [globalHooks.ifNotLocal(globalHooks.denyIfNotCurrentSchool({ errorMessage: 'Die angefragte Gruppe gehört nicht zur eigenen Schule!' }))],
	create: [addWholeClassToCourse],
	update: [],
	patch: [addWholeClassToCourse],
	remove: []
};<|endoftext|>


<commit_before>console.log('Hello World!');
<commit_msg>Create a express server<commit_after>var express = require('express');
var app = express();

app.get('/', function(request, response){
    response.send('Hello World');
});

var server = app.listen(3000, function(){
    var host = server.address().address;
    var port = server.address().port;

    console.log('Listening on http://%s:%s', host, port);
});
<|endoftext|>


<commit_before>// Load in our dependencies
var _ = require('underscore');
var assert = require('assert');
var fs = require('fs');
var Papa = require('papaparse');
var logger = console;

// Define our helpers
function readVendorFile(filepath, cb) {
  // If we have already parsed our file into JSON, then load that
  // DEV: JSON loads much faster, hence our preference
  var cacheFilepath = filepath + '.json';
  try {
    var cachedStr = fs.readFileSync(cacheFilepath, 'utf8');
    var cachedRetVal = JSON.parse(cachedStr);
    return cachedRetVal;
  // When an error occurs
  } catch (err) {
    // If the error was about our file not existing
    if (err.code === 'ENOENT') {
      // Do nothing
    // Otherwise, callback with it
    } else {
      return cb(err);
    }
  }

  // Load our initial file
  fs.readFile(filepath, 'utf8', function handleReadFile (err, csvStr) {
    // If there was an error, callback with it
    if (err) {
      return cb(err);
    }

    // Parse our CSV result
    // DEV: We trim loaded data to prevent empty lines being parsed
    csvStr = csvStr.trim();
    var results = Papa.parse(csvStr, {
      header: true
    });
    if (results.errors.length) {
      console.error('Error encountered', results.errors[0]);
      throw new Error(results.errors[0].message);
    }
    var retVal = results.data;

    // Save our data to JSON as caching
    fs.writeFile(cacheFilepath, JSON.stringify(retVal), 'utf8', function handleWriteFile (err) {
      // If there was an error, callback with it
      if (err) {
        return cb(err);
      }

      // Callback with our value
      cb(null, retVal);
    });
  });
}

// Define our main function
module.exports = function (cb) {
  // Load in our stop data
  logger.info('Loading file...');
  readVendorFile(__dirname + '/../vendor/sfmta-60/stop_times.txt', function handleReadVendorFile (err, stopTimes) {
    // If there was an error, callback with it
    if (err) {
      return cb(err);
    }

    // Group our trip datas by their id
    logger.info('File loaded');
    var stopTimesMapByTripId = _.groupBy(stopTimes, function groupByTripId (stopTime) {
      return stopTime.trip_id;
    });

    // Define time parsing helper
    var TIME_STR_REGEXP = /(\d{2}):(\d{2}):(\d{2})/;
    function parseTimeStr(timeStr) {
      var timeParts = timeStr.match(TIME_STR_REGEXP);
      assert(timeParts, 'Unable to match timeStr: ' + timeStr);
      return (parseInt(timeParts[1], 10) * 60 * 60 +
              parseInt(timeParts[2], 10) * 60 +
              parseInt(timeParts[3], 10));
    }

    // Strip away data we don't need
    // DEV: We use a similar compression to Google Calendar's timezones
    //   i.e. ['trip_id', ['stop_id', 'time_to_next_stop']]
    //   This reduces us from 260kb gzipped to 170kb gzipped
    //   Due to sheer number of repeated keys/references
    var VALID_KEYS = ['stop_id'];
    var retArr = _.map(stopTimesMapByTripId, function iterateStopTimeArrs (stopTimeArr, tripId) {
      // Extract our first arrival time for serialization
      var firstStop = stopTimeArr[0];
      assert(firstStop);
      var firstArrivalTimeStr = firstStop.arrival_time;
      assert(firstArrivalTimeStr);

      // Generate our return data
      return [
        tripId,
        parseTimeStr(firstArrivalTimeStr),
        stopTimeArr.map(function stripStopTimesData (stopTime, i) {
          // Assume trips are circular
          // TODO: Figure out circular trip detection
          var nextStopTime = stopTimeArr[i + 1] || stopTimeArr[0];
          assert(nextStopTime);

          // Parse stop info
          // https://momentjs.com/docs/#/parsing/string-format/
          var currentDepartureTimeStr = stopTime.departure_time;
          assert(currentDepartureTimeStr);
          var currentDepartureTime = parseTimeStr(currentDepartureTimeStr);

          var nextArrivalTimeStr = nextStopTime.arrival_time;
          assert(nextArrivalTimeStr);
          var nextArrivalTime = parseTimeStr(nextArrivalTimeStr);

          // Resolve time to our next stop
          if (currentDepartureTime >= nextArrivalTime) {
            nextArrivalTime += 24 * 60 * 60;
          }
          assert(currentDepartureTime < nextArrivalTime,
            'Expected "' + currentDepartureTimeStr + '" to be less than "' + nextArrivalTimeStr + '" after modulo ' +
            '(trip_id: ' + stopTime.trip_id + ', stop_id: ' + stopTime.stop_id + ')');
          var timeToNextStop = nextArrivalTime - currentDepartureTime;

          // Generate and return our data
          var values = _.values(_.pick(stopTime, VALID_KEYS));
          assert.strictEqual(values.length, VALID_KEYS.length);
          return values.concat([timeToNextStop]);
        })
      ];
    });

    // Callback with our data
    cb(null, 'window.app.loadData(' + JSON.stringify(retArr) + ')');
  });
};

// If we are running our script directly, output to `stdout`
// DEV: 170kb gzipped with only stop ids bound to trip id
//   node tmp.js | gzip | wc -c
// DEV: 518kb gzipped with stop id and time to next stop
// DEV: 435kb gzipped if we remove 1 order of magnitude from time to next stop
// TODO: Save even more space by flattening array entirely and using string based delimiters
if (require.main === module) {
  module.exports(function handleGenerateJSONP (err, jsonp) {
    // If there was an error, throw it
    if (err) {
      throw err;
    }

    // Otherwise, log our result
    console.log(jsonp);
  });
}
<commit_msg>Fixed up one-offs<commit_after>// Load in our dependencies
var _ = require('underscore');
var assert = require('assert');
var fs = require('fs');
var Papa = require('papaparse');
var logger = console;

// Define our helpers
function readVendorFile(filepath, cb) {
  // If we have already parsed our file into JSON, then load that
  // DEV: JSON loads much faster, hence our preference
  var cacheFilepath = filepath + '.json';
  try {
    var cachedStr = fs.readFileSync(cacheFilepath, 'utf8');
    var cachedRetVal = JSON.parse(cachedStr);
    cb(null, cachedRetVal);
  // When an error occurs
  } catch (err) {
    // If the error was about our file not existing
    if (err.code === 'ENOENT') {
      // Do nothing
    // Otherwise, callback with it
    } else {
      return cb(err);
    }
  }

  // Load our initial file
  fs.readFile(filepath, 'utf8', function handleReadFile (err, csvStr) {
    // If there was an error, callback with it
    if (err) {
      return cb(err);
    }

    // Parse our CSV result
    // DEV: We trim loaded data to prevent empty lines being parsed
    csvStr = csvStr.trim();
    var results = Papa.parse(csvStr, {
      header: true
    });
    if (results.errors.length) {
      console.error('Error encountered', results.errors[0]);
      return cb(new Error(results.errors[0].message));
    }
    var retVal = results.data;

    // Save our data to JSON as caching
    fs.writeFile(cacheFilepath, JSON.stringify(retVal), 'utf8', function handleWriteFile (err) {
      // If there was an error, callback with it
      if (err) {
        return cb(err);
      }

      // Callback with our value
      cb(null, retVal);
    });
  });
}

// Define our main function
module.exports = function (cb) {
  // Load in our stop data
  logger.info('Loading file...');
  readVendorFile(__dirname + '/../vendor/sfmta-60/stop_times.txt', function handleReadVendorFile (err, stopTimes) {
    // If there was an error, callback with it
    if (err) {
      return cb(err);
    }

    // Group our trip datas by their id
    logger.info('File loaded');
    var stopTimesMapByTripId = _.groupBy(stopTimes, function groupByTripId (stopTime) {
      return stopTime.trip_id;
    });

    // Define time parsing helper
    var TIME_STR_REGEXP = /(\d{2}):(\d{2}):(\d{2})/;
    function parseTimeStr(timeStr) {
      var timeParts = timeStr.match(TIME_STR_REGEXP);
      assert(timeParts, 'Unable to match timeStr: ' + timeStr);
      return (parseInt(timeParts[1], 10) * 60 * 60 +
              parseInt(timeParts[2], 10) * 60 +
              parseInt(timeParts[3], 10));
    }

    // Strip away data we don't need
    // DEV: We use a similar compression to Google Calendar's timezones
    //   i.e. ['trip_id', ['stop_id', 'time_to_next_stop']]
    //   This reduces us from 260kb gzipped to 170kb gzipped
    //   Due to sheer number of repeated keys/references
    var VALID_KEYS = ['stop_id'];
    var retArr = _.map(stopTimesMapByTripId, function iterateStopTimeArrs (stopTimeArr, tripId) {
      // Extract our first arrival time for serialization
      var firstStop = stopTimeArr[0];
      assert(firstStop);
      var firstArrivalTimeStr = firstStop.arrival_time;
      assert(firstArrivalTimeStr);

      // Generate our return data
      return [
        tripId,
        parseTimeStr(firstArrivalTimeStr),
        stopTimeArr.map(function stripStopTimesData (stopTime, i) {
          // Assume trips are circular
          // TODO: Figure out circular trip detection
          var nextStopTime = stopTimeArr[i + 1] || stopTimeArr[0];
          assert(nextStopTime);

          // Parse stop info
          // https://momentjs.com/docs/#/parsing/string-format/
          var currentDepartureTimeStr = stopTime.departure_time;
          assert(currentDepartureTimeStr);
          var currentDepartureTime = parseTimeStr(currentDepartureTimeStr);

          var nextArrivalTimeStr = nextStopTime.arrival_time;
          assert(nextArrivalTimeStr);
          var nextArrivalTime = parseTimeStr(nextArrivalTimeStr);

          // Resolve time to our next stop
          if (currentDepartureTime >= nextArrivalTime) {
            nextArrivalTime += 24 * 60 * 60;
          }
          assert(currentDepartureTime < nextArrivalTime,
            'Expected "' + currentDepartureTimeStr + '" to be less than "' + nextArrivalTimeStr + '" after modulo ' +
            '(trip_id: ' + stopTime.trip_id + ', stop_id: ' + stopTime.stop_id + ')');
          var timeToNextStop = nextArrivalTime - currentDepartureTime;

          // Generate and return our data
          var values = _.values(_.pick(stopTime, VALID_KEYS));
          assert.strictEqual(values.length, VALID_KEYS.length);
          return values.concat([timeToNextStop]);
        })
      ];
    });

    // Callback with our data
    cb(null, 'window.app.loadData(' + JSON.stringify(retArr) + ')');
  });
};

// If we are running our script directly, output to `stdout`
// DEV: 170kb gzipped with only stop ids bound to trip id
//   node tmp.js | gzip | wc -c
// DEV: 518kb gzipped with stop id and time to next stop
// DEV: 435kb gzipped if we remove 1 order of magnitude from time to next stop
// TODO: Save even more space by flattening array entirely and using string based delimiters
if (require.main === module) {
  module.exports(function handleGenerateJSONP (err, jsonp) {
    // If there was an error, throw it
    if (err) {
      throw err;
    }

    // Otherwise, log our result
    console.log(jsonp);
  });
}
<|endoftext|>


<commit_before>
import { expect } from 'chai';

import runner from '../../../../client/scripts/arcademode/runner';

// Get some real challenges in
import ArcadeChallenges from '../../../../public/json/challenges-arcade.json';

const challenges = ArcadeChallenges.challenges;
const stackChallenge = challenges.find(item => item.title.match(/Queue using/));
const bookshopChallenge = challenges.find(item => item.title.match(/Bookshop/));
const gittacaChallenge = challenges.find(item => item.title.match(/Gittaca/));

const userOutputUndef = 'User output is undefined.';

// CHALLENGES for the test cases

const emptyChallenge = {
  tests: ['// No tests, message: No tests really']
};

const challengeWithTest = {
  tests: ['assert(true === true, "message: This is correct.");']
};

const challengeWithHead = {
  head: ['function seenByUser() {return 1 + 1;}'],
  tests: []
};

const challengeWithTail = {
  tail: ['function tailFunction() {return "tail function";}'],
  tests: ['assert(tailFunction() !== "right", "message: all fine");']
};

// TESTS

describe('runner()', () => {
  it('executes js using eval and returns results', () => {
    const userCode = '// no code';
    const result = runner(userCode, emptyChallenge);
    return result.then(res => {
      expect(res).to.have.property('userOutput');
      expect(res).to.have.property('errorMsgs');
      expect(res).to.have.property('testResults');
      expect(res.errorMsgs).to.have.length(0);
    });
  });

  it('catches invalid syntax correctly', () => {
    const userCode = 'syntaxError [][ = ;];';
    const result = runner(userCode, emptyChallenge);
    return result.then(res => {
      expect(res.errorMsgs).to.have.length(1);
      expect(res.userOutput).to.have.length.above(0);
      expect(res.userOutput).to.match(/SyntaxError/);
      expect(res.testResults).to.have.length(0);
    });
  });

  it('catches invalid execution, non-exec code', () => {
    const userCode = 'let myVar = NonExistingClass()';
    const result = runner(userCode, emptyChallenge);
    return result.then(res => {
      expect(res.errorMsgs).to.have.length(1);
      expect(res.userOutput).to.have.length.above(0);
      expect(res.userOutput).to.match(/Error:/);
      expect(res.testResults).to.have.length(0);
    });
  });

  it('Runs tests for correct code', () => {
    const userCode = '// Error-free code\ntrue;';
    const result = runner(userCode, challengeWithTest);
    return result.then(res => {
      expect(res.testResults).to.have.length(1);
      expect(res.errorMsgs).to.have.length(0);
      expect(res.userOutput).to.equal('true');
    });
  });

  it('adds head before executing the code', () => {
    const userCode = 'seenByUser();';
    const result = runner(userCode, challengeWithHead);
    return result.then(res => {
      expect(res.userOutput).to.equal('2');
    });
  });

  it('adds tail before running the tests', () => {
    const userCode = '// No user code really';
    const result = runner(userCode, challengeWithTail);
    return result.then(res => {
      expect(res.userOutput).to.equal(userOutputUndef);
    });
  });

  it('catches infinite loops in user code', () => {
    const userCode = 'while (true);';
    const result = runner(userCode, challengeWithHead);
    return result.then(res => {
      expect(res.errorMsgs).to.have.length(1);
      expect(res.userOutput).to.match(/infinite loop/);
    });
  });

  it('can execute queue-2-stack challenge', () => {
    let userCode = stackChallenge.solutions.join('');
    userCode = userCode.replace(/^\s*Queue/, 'const Queue');
    const result = runner(userCode, stackChallenge);
    return result.then(res => {
      expect(res.userOutput).to.equal(userOutputUndef);
      expectNoErrorsAndAllTestsRun(res, stackChallenge);
    });
  });

  it('can execute the book shop challenge', () => {
    const userCode = bookshopChallenge.solutions.join('');
    const result = runner(userCode, bookshopChallenge);
    return result.then(res => {
      expect(res.userOutput).to.equal(userOutputUndef);
      expectNoErrorsAndAllTestsRun(res, bookshopChallenge);
    });
  });

  it('can execute the gittaca challenge', () => {
    const userCode = gittacaChallenge.solutions.join('');
    const result = runner(userCode, gittacaChallenge);
    return result.then(res => {
      expect(res.userOutput).to.equal(userOutputUndef);
      expectNoErrorsAndAllTestsRun(res, gittacaChallenge);
    });
  });
});

// HELPER FUNCTIONS
function expectNoErrorsAndAllTestsRun(res, challenge) {
  expect(res.errorMsgs).to.have.length(0);
  expect(res.testResults).to.have.length(challenge.tests.length);
}
<commit_msg>add conventurist challenge test<commit_after>
import { expect } from 'chai';

import runner from '../../../../client/scripts/arcademode/runner';

// Get some real challenges in
import ArcadeChallenges from '../../../../public/json/challenges-arcade.json';

const challenges = ArcadeChallenges.challenges;
const stackChallenge = challenges.find(item => item.title.match(/Queue using/));
const bookshopChallenge = challenges.find(item => item.title.match(/Bookshop/));
const gittacaChallenge = challenges.find(item => item.title.match(/Gittaca/));
const conventuristChallenge = challenges.find(item => item.title.match(/Conventurist/));

const userOutputUndef = 'User output is undefined.';

// CHALLENGES for the test cases

const emptyChallenge = {
  tests: ['// No tests, message: No tests really']
};

const challengeWithTest = {
  tests: ['assert(true === true, "message: This is correct.");']
};

const challengeWithHead = {
  head: ['function seenByUser() {return 1 + 1;}'],
  tests: []
};

const challengeWithTail = {
  tail: ['function tailFunction() {return "tail function";}'],
  tests: ['assert(tailFunction() !== "right", "message: all fine");']
};

// TESTS

describe('runner()', () => {
  it('executes js using eval and returns results', () => {
    const userCode = '// no code';
    const result = runner(userCode, emptyChallenge);
    return result.then(res => {
      expect(res).to.have.property('userOutput');
      expect(res).to.have.property('errorMsgs');
      expect(res).to.have.property('testResults');
      expect(res.errorMsgs).to.have.length(0);
    });
  });

  it('catches invalid syntax correctly', () => {
    const userCode = 'syntaxError [][ = ;];';
    const result = runner(userCode, emptyChallenge);
    return result.then(res => {
      expect(res.errorMsgs).to.have.length(1);
      expect(res.userOutput).to.have.length.above(0);
      expect(res.userOutput).to.match(/SyntaxError/);
      expect(res.testResults).to.have.length(0);
    });
  });

  it('catches invalid execution, non-exec code', () => {
    const userCode = 'let myVar = NonExistingClass()';
    const result = runner(userCode, emptyChallenge);
    return result.then(res => {
      expect(res.errorMsgs).to.have.length(1);
      expect(res.userOutput).to.have.length.above(0);
      expect(res.userOutput).to.match(/Error:/);
      expect(res.testResults).to.have.length(0);
    });
  });

  it('Runs tests for correct code', () => {
    const userCode = '// Error-free code\ntrue;';
    const result = runner(userCode, challengeWithTest);
    return result.then(res => {
      expect(res.testResults).to.have.length(1);
      expect(res.errorMsgs).to.have.length(0);
      expect(res.userOutput).to.equal('true');
    });
  });

  it('adds head before executing the code', () => {
    const userCode = 'seenByUser();';
    const result = runner(userCode, challengeWithHead);
    return result.then(res => {
      expect(res.userOutput).to.equal('2');
    });
  });

  it('adds tail before running the tests', () => {
    const userCode = '// No user code really';
    const result = runner(userCode, challengeWithTail);
    return result.then(res => {
      expect(res.userOutput).to.equal(userOutputUndef);
    });
  });

  it('catches infinite loops in user code', () => {
    const userCode = 'while (true);';
    const result = runner(userCode, challengeWithHead);
    return result.then(res => {
      expect(res.errorMsgs).to.have.length(1);
      expect(res.userOutput).to.match(/infinite loop/);
    });
  });

  it('can execute queue-2-stack challenge', () => {
    let userCode = stackChallenge.solutions.join('');
    userCode = userCode.replace(/^\s*Queue/, 'const Queue');
    const result = runner(userCode, stackChallenge);
    return result.then(res => {
      expect(res.userOutput).to.equal(userOutputUndef);
      expectNoErrorsAndAllTestsRun(res, stackChallenge);
    });
  });

  it('can execute the book shop challenge', () => {
    const sort = Array.prototype.sort;
    const userCode = bookshopChallenge.solutions.join('');
    const result = runner(userCode, bookshopChallenge);
    Array.prototype.sort = sort;
    return result.then(res => {
      expect(res.userOutput).to.equal(userOutputUndef);
      expectNoErrorsAndAllTestsRun(res, bookshopChallenge);
    });
  });

  it('can execute the gittaca challenge', () => {
    const userCode = gittacaChallenge.solutions.join('');
    const result = runner(userCode, gittacaChallenge);
    return result.then(res => {
      expect(res.userOutput).to.equal(userOutputUndef);
      expectNoErrorsAndAllTestsRun(res, gittacaChallenge);
    });
  });

  it('can execute the conventurist challenge', () => {
    const userCode = conventuristChallenge.solutions.join('');
    const result = runner(userCode, conventuristChallenge);
    return result.then(res => {
      expect(res.userOutput).to.equal(userOutputUndef);
      expectNoErrorsAndAllTestsRun(res, conventuristChallenge);
    });
  });
});

// HELPER FUNCTIONS
function expectNoErrorsAndAllTestsRun(res, challenge) {
  expect(res.errorMsgs).to.have.length(0);
  expect(res.testResults).to.have.length(challenge.tests.length);
}
<|endoftext|>


<commit_before>'use strict';

var init = require('./config/init')()
  , config = require('./config/config')
  , mongoose = require('mongoose')
  , moment = require('moment')
  , chalk = require('chalk');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Bootstrap db connection
var db = mongoose.connect(config.db.uri, config.db.options, function(err) {
  if (err) {
    console.error(chalk.red('Could not connect to MongoDB!'));
    console.log(chalk.red(err));
  }
});
mongoose.connection.on('error', function(err) {
    console.error(chalk.red('MongoDB connection error: ' + err));
    process.exit(-1);
  }
);

// Init the express application
var app = require('./config/express')(db);

// Bootstrap passport config
require('./config/passport')();

// Start the app by listening on <port>
app.listen(config.port);

// Expose app
exports = module.exports = app;

console.log('--');
console.log(chalk.green(config.app.title + ' application started'));
console.log(chalk.green('Start Time:\t\t\t' + moment().format('DD.MM.YY HH:mm:ss')));
console.log(chalk.green('Environment:\t\t\t' + process.env.NODE_ENV));
console.log(chalk.green('Port:\t\t\t\t' + config.port));
console.log(chalk.green('Database:\t\t\t' + config.db.uri));
if (process.env.NODE_ENV === 'secure') {
  console.log(chalk.green('HTTPs:\t\t\t\ton'));
}
console.log('testy');
console.log('--');
<commit_msg>webhook test<commit_after>'use strict';

var init = require('./config/init')()
  , config = require('./config/config')
  , mongoose = require('mongoose')
  , moment = require('moment')
  , chalk = require('chalk');

/**
 * Main application entry file.
 * Please note that the order of loading is important.
 */

// Bootstrap db connection
var db = mongoose.connect(config.db.uri, config.db.options, function(err) {
  if (err) {
    console.error(chalk.red('Could not connect to MongoDB!'));
    console.log(chalk.red(err));
  }
});
mongoose.connection.on('error', function(err) {
    console.error(chalk.red('MongoDB connection error: ' + err));
    process.exit(-1);
  }
);

// Init the express application
var app = require('./config/express')(db);

// Bootstrap passport config
require('./config/passport')();

// Start the app by listening on <port>
app.listen(config.port);

// Expose app
exports = module.exports = app;

console.log('--');
console.log(chalk.green(config.app.title + ' application started'));
console.log(chalk.green('Start Time:\t\t\t' + moment().format('DD.MM.YY HH:mm:ss')));
console.log(chalk.green('Environment:\t\t\t' + process.env.NODE_ENV));
console.log(chalk.green('Port:\t\t\t\t' + config.port));
console.log(chalk.green('Database:\t\t\t' + config.db.uri));
if (process.env.NODE_ENV === 'secure') {
  console.log(chalk.green('HTTPs:\t\t\t\ton'));
}
console.log('--');
<|endoftext|>


<commit_before>var express = require('express');
var app = express();
var path = require('path');
var util = require('util');
var mongodb =  require('mongodb');
var mongoose = require('mongoose');
var fs = require('fs');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var connect = require('connect');
var engine = require('ejs-mate');
var ejs = require('ejs');
var qs = require('query-string');
var url = require('url');
var base64url = require('base64url');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var mongo = require('mongodb');
var mongostore = require('connect-mongo')(session);
var bcrypt = require('bcryptjs');
var expressValidator = require('express-validator');
var dotenv = require('dotenv');
var paypal = require('paypal-rest-sdk');
var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var Storage = require('@google-cloud/storage');
var format = require('util').format;
var now = require('moment');

var env = process.env.NODE_ENV || 'development';

var db = require('./config/setting');
var options = {
  authMechanism:'SCRAM-SHA-1'
}
var mongouri = db.getDB(env)+"?authMechanism=SCRAM-SHA-1";
mongoose.connect(mongouri)

require('./config/passport.js')(passport);

// set static folder
app.use(express.static(__dirname + '/assets'));
app.use('/bower_components',  express.static(__dirname + '/bower_components'));
app.use('/fashion/item/',  express.static(__dirname + '/assets'));
app.use('/category/',  express.static(__dirname + '/assets'));
app.use('/category/uploads',  express.static(__dirname + '/uploads'));
app.use(express.static(path.join(__dirname, 'views')));
app.use('/uploads', express.static(__dirname + '/uploads'));
app.use('/fashion/item/uploads', express.static(__dirname + '/uploads'));
app.use('/admin/blog/uploads', express.static(__dirname + '/uploads'));
app.use('/blog/item/',  express.static(__dirname + '/assets'));
app.use('/admin/product/uploads', express.static('/uploads'));
app.use('/fashion/cart/', express.static(__dirname + '/assets'));
app.use('/pay/:id', express.static(__dirname + '/assets'));
app.use('/payment/:id', express.static(__dirname + '/assets'));
app.use('/fashion/checkout/', express.static(__dirname + '/assets'));
app.use('/fashion/checkout/uploads', express.static(__dirname + '/uploads'));
app.use('/fashion', express.static(__dirname + '/assets'));

app.use(session({
  resave    : true,
  saveUninitialized:true,
  secret  :db.getSecret(env),
  store   : new mongostore({ url :db.getDB(env), autoReconnect:true}),
  cookie : { maxAge: 180*60*1000}
}));

//Create EJS Engine view
app.set('view engine', 'html');
app.engine('ejs', engine);
app.set('view engine', 'ejs');

app.use(passport.initialize());

app.use(passport.session());

//body-parser and cokie-parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false }));
app.use(expressValidator());
app.use(cookieParser());
app.use(morgan('dev'));

app.use(flash());

app.use(function(req,res,next){
  res.locals.user   = req.user;
  res.locals.message = req.flash();
  res.locals.session = req.session;
  next();
});

var routes = require('./routes/index.js');
app.use(routes);

app.set('port', (process.env.PORT || 8080));
app.listen(app.get('port'), function() {
  console.log("connected to mongo ", db.getDB(env));
  console.log('Hurray am running on port ' + app.get('port'))
});
<commit_msg>add console.log to see emails being sent from users to admin<commit_after>var express = require('express');
var app = express();
var path = require('path');
var util = require('util');
var mongodb =  require('mongodb');
var mongoose = require('mongoose');
var fs = require('fs');
var morgan = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var connect = require('connect');
var engine = require('ejs-mate');
var ejs = require('ejs');
var qs = require('query-string');
var url = require('url');
var base64url = require('base64url');
var flash = require('connect-flash');
var session = require('express-session');
var passport = require('passport');
var mongo = require('mongodb');
var mongostore = require('connect-mongo')(session);
var bcrypt = require('bcryptjs');
var expressValidator = require('express-validator');
var dotenv = require('dotenv');
var paypal = require('paypal-rest-sdk');
var google = require('googleapis');
var OAuth2 = google.auth.OAuth2;
var Storage = require('@google-cloud/storage');
var format = require('util').format;
var now = require('moment');

var env = process.env.NODE_ENV || 'development';

var db = require('./config/setting');
var options = {
  authMechanism:'SCRAM-SHA-1'
}
var mongouri = db.getDB(env)+"?authMechanism=SCRAM-SHA-1";
mongoose.connect(mongouri)

require('./config/passport.js')(passport);

// set static folder
app.use(express.static(__dirname + '/assets'));
app.use('/bower_components',  express.static(__dirname + '/bower_components'));
app.use('/fashion/item/',  express.static(__dirname + '/assets'));
app.use('/category/',  express.static(__dirname + '/assets'));
app.use('/category/uploads',  express.static(__dirname + '/uploads'));
app.use(express.static(path.join(__dirname, 'views')));
app.use('/uploads', express.static(__dirname + '/uploads'));
app.use('/fashion/item/uploads', express.static(__dirname + '/uploads'));
app.use('/admin/blog/uploads', express.static(__dirname + '/uploads'));
app.use('/blog/item/',  express.static(__dirname + '/assets'));
app.use('/admin/product/uploads', express.static('/uploads'));
app.use('/fashion/cart/', express.static(__dirname + '/assets'));
app.use('/pay/:id', express.static(__dirname + '/assets'));
app.use('/payment/:id', express.static(__dirname + '/assets'));
app.use('/fashion/checkout/', express.static(__dirname + '/assets'));
app.use('/fashion/checkout/uploads', express.static(__dirname + '/uploads'));
app.use('/fashion', express.static(__dirname + '/assets'));

app.use(session({
  resave    : true,
  saveUninitialized:true,
  secret  :db.getSecret(env),
  store   : new mongostore({ url :db.getDB(env), autoReconnect:true}),
  cookie : { maxAge: 180*60*1000}
}));

//Create EJS Engine view
app.set('view engine', 'html');
app.engine('ejs', engine);
app.set('view engine', 'ejs');

app.use(passport.initialize());

app.use(passport.session());

//body-parser and cokie-parser middleware
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false }));
app.use(expressValidator());
app.use(cookieParser());
app.use(morgan('dev'));

app.use(flash());

app.use(function(req,res,next){
  res.locals.user   = req.user;
  res.locals.message = req.flash();
  res.locals.session = req.session;
  next();
});

var routes = require('./routes/index.js');
app.use(routes);

app.set('port', (process.env.PORT || 8080));
app.listen(app.get('port'), function() {
  console.log("connected to mongo ", db.getDB(env));
  console.log('Hurray am running on port ' + app.get('port'));
  console.log("running nodemailer on email ", db.getEmail(env));
});
<|endoftext|>


<commit_before>/*
 *
 *
 */
var currentDataStyle = '';
var currentSpeciesName = '';
var currentSpeciesID = '';
var currentScenario = '';
var currentModel = '';
var currentTime = '';
var currentCombination = '';

function addSpecies(species_id,speciesName)
{
    currentDataStyle = 'CURRENT';

    currentScenario = 'CURRENT';
    currentModel = 'CURRENT';
    currentTime = '1990';

    currentCombination = currentScenario + '_' + currentModel + '_' + currentTime;

    currentSpeciesName = speciesName;
    currentSpeciesID = species_id;

    $('#datastyle_selection').removeAttr('disabled');

    disableFuturePropertySelectors();

    userSelectedLayer();

    $('#download_all').attr('href', "SpeciesSuitabilityDownload.php?species_id="+species_id);
    $('#download_all').removeAttr('disabled');
}

function selectDataStyle(src)
{
    var id = src.id.toString();
    currentDataStyle = $('#'+ id + ' option:selected').val();

    console.log('currentDataStyle = ' + currentDataStyle);

    if (currentDataStyle == "CURRENT")
    {
        currentScenario = 'CURRENT';
        currentModel = 'CURRENT';
        currentTime = '1990';

        disableFuturePropertySelectors();
    }
    else
    {
        enableFuturePropertySelectors();

    }

    setCurrentCombination();

    userSelectedLayer();

}

function selectScenario(src)
{
    var id = src.id.toString();
    currentScenario = $('#'+ id + ' option:selected').val();
    setCurrentCombination();
    userSelectedLayer();
}

function selectModel(src)
{
    var id = src.id.toString();
    currentModel = $('#'+ id + ' option:selected').val();
    setCurrentCombination();
    userSelectedLayer();
}

function selectTime(src)
{
    var id = src.id.toString();
    currentTime = $('#'+ id + ' option:selected').val();

    setCurrentCombination();
    userSelectedLayer();
}

function setCurrentCombination()
{

    if (currentDataStyle == 'CURRENT')
    {
        currentScenario = 'CURRENT';
        currentModel = 'CURRENT';
        currentTime = '1990';
        currentCombination = currentScenario + '_' + currentModel + '_' + currentTime;

        $('#information_content').attr('src','SpeciesSuitabilityInformation.php?combination=');  // call info with empty combo
    }
    else
    {
        currentScenario = $('#scenario_selection option:selected').val();
        currentModel    = $('#model_selection option:selected').val();
        currentTime     = $('#time_selection option:selected').val();

        currentCombination = currentScenario + '_' + currentModel + '_' + currentTime;

        $('#information_content').attr('src','SpeciesSuitabilityInformation.php?combination='+currentCombination);
    }

}

function userSelectedLayer()
{

    $.ajax('SpeciesSuitabilityPrep.php', {
        async: false,
        cache: false,
        dataType: 'json',
        type: 'POST',
        data: {
            UserLayer: currentCombination,
            SpeciesID: currentSpeciesID
        },
        success: function(data, testStatus, jqx) {
            console.log(['got data back:', data]);
        }
    });

/*
    // data needs to be posted at the mapserver
    $("#UserLayer").val(currentCombination);    // file_id of grid file - sets the fileid to be posted at map server
    $("#SpeciesID").val(currentSpeciesID);

    console.log('userSelectedLayer = ' + currentCombination);
    console.log('currentSpeciesID = ' + currentSpeciesID);

    var offset = $('#GUI').offset();
    var guiHeight = $('#GUI').height();
    var guiWidth = $('#GUI').width();

    var map_loading_div = '
Loading '
                        + currentSpeciesName
                        + '

';

    $('#messages_container').append(map_loading_div);

    $('#MLD')
        .width(guiWidth * 0.8).height(90)
        .offset({ top: (offset.top + (guiHeight/2) - ($('#MLD').height() / 2)), left: (offset.left + (guiWidth/2) - ($('#MLD').width() / 2)) })
        .button()
        .fadeIn(200)
        ;

    $('#GUI').contents().find('#MAP_FORM').submit();

*/
}

function enableFuturePropertySelectors()
{
    $('#scenario_selection').removeAttr('disabled');
    $('#model_selection').removeAttr('disabled');
    $('#time_selection').removeAttr('disabled');
}

function disableFuturePropertySelectors()
{

    $('#scenario_selection').attr('disabled', 'disabled');
    $('#model_selection').attr('disabled', 'disabled');
    $('#time_selection').attr('disabled', 'disabled');

}

function currentAsciiGrid()
{
    var result =    Maxent_Species_Data_folder_web
                  + currentSpeciesID + '/'
                  + 'output/'
                  + currentCombination + '.asc';

    return result;
}

function setMapOverview()
{

    var mapa = $("#GUI").contents().find("#mapa");

    if ($('#map_overview').html() == "")
    {
        $('#map_overview').html('');

    }

}

function GetZoom() {
    document.getElementById('ZoomFactor').value = parent.document.getElementById('ZoomFactor').value;
}

function map_gui_loaded()
{
    if (exists('#MLD'))
    {
        $('#MLD').fadeOut(200).remove();
        $('#MLD').remove();
    }

}

function setTools(src)
{
     $( "#" + src.id.toString() ).toggleClass( "ui-state-active", 100 );

}

function ReloadDiv(divID)
{
    document.getElementById(divID).src = document.getElementById(divID).src
}

function ReloadGUI()
{
    ReloadDiv('GUI') ;
}

function SetZoom(caller,zoom_value) {
    document.getElementById('ZoomFactor').value = zoom_value;
}

function SetFullExtent() {
    ReloadGUI();
}

$(document).ready(function(){

    $( "#species" ).autocomplete({
        source: availableSpecies,
        select: function(event, ui) {
            addSpecies(ui.item.value,ui.item.label);
            $(this).val(ui.item.label);
            return false;
        }
    });

    // add the map
    window.map = L.map('leafletmap').setView([-27, 135], 3);

    L.tileLayer('http://{s}.tile.cloudmade.com/831e24daed21488e8205aa95e2a14787/997/256/{z}/{x}/{y}.png', {
      maxZoom: 18
    }).addTo(map);
/*
    mapfileUrl = window.mapfileRoot;
    mapfileUrl += 'By' + groupLevel[0].toUpperCase() + groupLevel.slice(1);
    mapfileUrl += '/' + groupName + '/' + scenario + '_' + year + '.map';
    console.log(mapfileUrl);
    data = new L.TileLayer.WMS("http://tdh-tools-1.hpc.jcu.edu.au:81/cgi-bin/mapserv", {
      layers: 'tdh&map=' + mapfileUrl,
      format: 'image/png',
      opacity: 0.75,
      transparent: true
    }).addTo(map);
*/

/*
    $( "#ToolFullExtent")
        .button({ text: false, icons: { primary: "ui-icon-image"  } })
        .height(40)
        .css('float','none')
        .css('clear','both')
        ;

    $( "#ToolZoomOut")
        .button({ text: false, icons: { primary: "ui-icon-zoomout"} })
        .click(function() { setTools(this); })
        .height(30)
        .css('float','none')
        .css('clear','both')
        ;

    $( "#ToolCentre" )
        .button({ text: false, icons: { primary: "ui-icon-plus"   } })
        .click(function() { setTools(this); })
        .height(30)
        .css('float','none')
        .css('clear','both')
        ;

    $( "#ToolZoomIn")
        .button({ text: false, icons: { primary: "ui-icon-zoomin" } })
        .click(function() { setTools(this); })
        .height(30)
        .css('float','none')
        .css('clear','both')
        ;

    $("#species")
        .blur(function() { $(this).val(currentSpeciesName); return false; })
        .focus(function() { $(this).val(''); return false; })
        ;
*/
    disableFuturePropertySelectors();

    $('#datastyle_selection').attr('disabled', 'disabled');

/*
    $('#datastyle_selection')
        .css('float','none')
        .css('clear','both')
        .css('width','90%')
        .css('height','30px')
        .css('margin','2%')
        ;

    $('#scenario_selection')
        .css('float','none')
        .css('clear','both')
        .css('width','90%')
        .css('height','30px')
        .css('margin','2%')
        ;

    $('#model_selection')
        .css('float','none')
        .css('clear','both')
        .css('width','90%')
        .css('height','30px')
        .css('margin','2%')
        ;

    $('#time_selection')
        .css('float','none')
        .css('clear','both')
        .css('width','90%')
        .css('height','30px')
        .css('margin','2%')
        ;
*/

});

<commit_msg>maybe leaflet will work<commit_after>/*
 *
 *
 */
var currentDataStyle = '';
var currentSpeciesName = '';
var currentSpeciesID = '';
var currentScenario = '';
var currentModel = '';
var currentTime = '';
var currentCombination = '';

function addSpecies(species_id,speciesName)
{
    currentDataStyle = 'CURRENT';

    currentScenario = 'CURRENT';
    currentModel = 'CURRENT';
    currentTime = '1990';

    currentCombination = currentScenario + '_' + currentModel + '_' + currentTime;

    currentSpeciesName = speciesName;
    currentSpeciesID = species_id;

    $('#datastyle_selection').removeAttr('disabled');

    disableFuturePropertySelectors();

    userSelectedLayer();

    $('#download_all').attr('href', "SpeciesSuitabilityDownload.php?species_id="+species_id);
    $('#download_all').removeAttr('disabled');
}

function selectDataStyle(src)
{
    var id = src.id.toString();
    currentDataStyle = $('#'+ id + ' option:selected').val();

    console.log('currentDataStyle = ' + currentDataStyle);

    if (currentDataStyle == "CURRENT")
    {
        currentScenario = 'CURRENT';
        currentModel = 'CURRENT';
        currentTime = '1990';

        disableFuturePropertySelectors();
    }
    else
    {
        enableFuturePropertySelectors();

    }

    setCurrentCombination();

    userSelectedLayer();

}

function selectScenario(src)
{
    var id = src.id.toString();
    currentScenario = $('#'+ id + ' option:selected').val();
    setCurrentCombination();
    userSelectedLayer();
}

function selectModel(src)
{
    var id = src.id.toString();
    currentModel = $('#'+ id + ' option:selected').val();
    setCurrentCombination();
    userSelectedLayer();
}

function selectTime(src)
{
    var id = src.id.toString();
    currentTime = $('#'+ id + ' option:selected').val();

    setCurrentCombination();
    userSelectedLayer();
}

function setCurrentCombination()
{

    if (currentDataStyle == 'CURRENT')
    {
        currentScenario = 'CURRENT';
        currentModel = 'CURRENT';
        currentTime = '1990';
        currentCombination = currentScenario + '_' + currentModel + '_' + currentTime;

        $('#information_content').attr('src','SpeciesSuitabilityInformation.php?combination=');  // call info with empty combo
    }
    else
    {
        currentScenario = $('#scenario_selection option:selected').val();
        currentModel    = $('#model_selection option:selected').val();
        currentTime     = $('#time_selection option:selected').val();

        currentCombination = currentScenario + '_' + currentModel + '_' + currentTime;

        $('#information_content').attr('src','SpeciesSuitabilityInformation.php?combination='+currentCombination);
    }

}

function userSelectedLayer()
{

    $.ajax('SpeciesSuitabilityPrep.php', {
        cache: false,
        dataType: 'json',
        type: 'POST',
        data: {
            UserLayer: currentCombination,
            SpeciesID: currentSpeciesID
        },
        success: function(data, testStatus, jqx) {
            console.log(['got data back:', data]);

            data = new L.TileLayer.WMS("http://tdh-tools-2.hpc.jcu.edu.au/cgi-bin/mapserv", {
                layers: 'tdh&map=' + data.map_path,
                format: 'image/png',
                opacity: 0.75,
                transparent: true
            }).addTo(window.map);
        }
    });

}

function enableFuturePropertySelectors()
{
    $('#scenario_selection').removeAttr('disabled');
    $('#model_selection').removeAttr('disabled');
    $('#time_selection').removeAttr('disabled');
}

function disableFuturePropertySelectors()
{

    $('#scenario_selection').attr('disabled', 'disabled');
    $('#model_selection').attr('disabled', 'disabled');
    $('#time_selection').attr('disabled', 'disabled');

}

function currentAsciiGrid()
{
    var result =    Maxent_Species_Data_folder_web
                  + currentSpeciesID + '/'
                  + 'output/'
                  + currentCombination + '.asc';

    return result;
}

function setMapOverview()
{

    var mapa = $("#GUI").contents().find("#mapa");

    if ($('#map_overview').html() == "")
    {
        $('#map_overview').html('');

    }

}

function GetZoom() {
    document.getElementById('ZoomFactor').value = parent.document.getElementById('ZoomFactor').value;
}

function map_gui_loaded()
{
    if (exists('#MLD'))
    {
        $('#MLD').fadeOut(200).remove();
        $('#MLD').remove();
    }

}

function setTools(src)
{
     $( "#" + src.id.toString() ).toggleClass( "ui-state-active", 100 );

}

function ReloadDiv(divID)
{
    document.getElementById(divID).src = document.getElementById(divID).src
}

function ReloadGUI()
{
    ReloadDiv('GUI') ;
}

function SetZoom(caller,zoom_value) {
    document.getElementById('ZoomFactor').value = zoom_value;
}

function SetFullExtent() {
    ReloadGUI();
}

$(document).ready(function(){

    $( "#species" ).autocomplete({
        source: availableSpecies,
        select: function(event, ui) {
            addSpecies(ui.item.value,ui.item.label);
            $(this).val(ui.item.label);
            return false;
        }
    });

    // add the map
    window.map = L.map('leafletmap').setView([-27, 135], 3);

    L.tileLayer('http://{s}.tile.cloudmade.com/831e24daed21488e8205aa95e2a14787/997/256/{z}/{x}/{y}.png', {
      maxZoom: 18
    }).addTo(map);
/*
    mapfileUrl = window.mapfileRoot;
    mapfileUrl += 'By' + groupLevel[0].toUpperCase() + groupLevel.slice(1);
    mapfileUrl += '/' + groupName + '/' + scenario + '_' + year + '.map';
    console.log(mapfileUrl);
    data = new L.TileLayer.WMS("http://tdh-tools-1.hpc.jcu.edu.au:81/cgi-bin/mapserv", {
      layers: 'tdh&map=' + mapfileUrl,
      format: 'image/png',
      opacity: 0.75,
      transparent: true
    }).addTo(map);
*/

/*
    $( "#ToolFullExtent")
        .button({ text: false, icons: { primary: "ui-icon-image"  } })
        .height(40)
        .css('float','none')
        .css('clear','both')
        ;

    $( "#ToolZoomOut")
        .button({ text: false, icons: { primary: "ui-icon-zoomout"} })
        .click(function() { setTools(this); })
        .height(30)
        .css('float','none')
        .css('clear','both')
        ;

    $( "#ToolCentre" )
        .button({ text: false, icons: { primary: "ui-icon-plus"   } })
        .click(function() { setTools(this); })
        .height(30)
        .css('float','none')
        .css('clear','both')
        ;

    $( "#ToolZoomIn")
        .button({ text: false, icons: { primary: "ui-icon-zoomin" } })
        .click(function() { setTools(this); })
        .height(30)
        .css('float','none')
        .css('clear','both')
        ;

    $("#species")
        .blur(function() { $(this).val(currentSpeciesName); return false; })
        .focus(function() { $(this).val(''); return false; })
        ;
*/
    disableFuturePropertySelectors();

    $('#datastyle_selection').attr('disabled', 'disabled');

/*
    $('#datastyle_selection')
        .css('float','none')
        .css('clear','both')
        .css('width','90%')
        .css('height','30px')
        .css('margin','2%')
        ;

    $('#scenario_selection')
        .css('float','none')
        .css('clear','both')
        .css('width','90%')
        .css('height','30px')
        .css('margin','2%')
        ;

    $('#model_selection')
        .css('float','none')
        .css('clear','both')
        .css('width','90%')
        .css('height','30px')
        .css('margin','2%')
        ;

    $('#time_selection')
        .css('float','none')
        .css('clear','both')
        .css('width','90%')
        .css('height','30px')
        .css('margin','2%')
        ;
*/

});

<|endoftext|>


<commit_before>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Button = undefined;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Button = exports.Button = function Button(_ref) {
  var children = _ref.children,
      onClick = _ref.onClick,
      _ref$style = _ref.style,
      style = _ref$style === undefined ? {} : _ref$style;

  return _react2.default.createElement(
    'button',
    {
      style: {},
      onClick: onClick
    },
    children
  );
};

Button.propTypes = {
  children: _react2.default.PropTypes.string.isRequired,
  onClick: _react2.default.PropTypes.func,
  style: _react2.default.PropTypes.object
};
Button.__docgenInfo = {
  'description': '',
  'methods': [],
  'props': {
    'children': {
      'type': {
        'name': 'string'
      },
      'required': true,
      'description': ''
    },
    'onClick': {
      'type': {
        'name': 'func'
      },
      'required': false,
      'description': ''
    },
    'style': {
      'type': {
        'name': 'object'
      },
      'required': false,
      'description': '',
      'defaultValue': {
        'value': '{}',
        'computed': false
      }
    }
  }
};

if (typeof STORYBOOK_REACT_CLASSES !== 'undefined') {
  STORYBOOK_REACT_CLASSES['test/fixtures/exportedDeclaration/actual.js'] = {
    name: 'Button',
    docgenInfo: Button.__docgenInfo,
    path: 'test/fixtures/exportedDeclaration/actual.js'
  };
}<commit_msg>Fix isExported to also detect export declarations<commit_after>'use strict';

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.Button = undefined;

var _react = require('react');

var _react2 = _interopRequireDefault(_react);

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

var Button = exports.Button = function Button(_ref) {
  var children = _ref.children,
      onClick = _ref.onClick,
      _ref$style = _ref.style,
      style = _ref$style === undefined ? {} : _ref$style;

  return _react2.default.createElement(
    'button',
    {
      style: {},
      onClick: onClick
    },
    children
  );
};

Button.propTypes = {
  children: _react2.default.PropTypes.string.isRequired,
  onClick: _react2.default.PropTypes.func,
  style: _react2.default.PropTypes.object
};
Button.__docgenInfo = {
  'description': '',
  'methods': [],
  'props': {
    'children': {
      'type': {
        'name': 'string'
      },
      'required': true,
      'description': ''
    },
    'onClick': {
      'type': {
        'name': 'func'
      },
      'required': false,
      'description': ''
    },
    'style': {
      'type': {
        'name': 'object'
      },
      'required': false,
      'description': '',
      'defaultValue': {
        'value': '{}',
        'computed': false
      }
    }
  }
};

if (typeof STORYBOOK_REACT_CLASSES !== 'undefined') {
  STORYBOOK_REACT_CLASSES['test/fixtures/exportedDeclaration/actual.js'] = {
    name: 'Button',
    docgenInfo: Button.__docgenInfo,
    path: 'test/fixtures/exportedDeclaration/actual.js'
  };
}
<|endoftext|>