<commit_before>context('Form', () => {
	before(() => {
		cy.login();
		cy.visit('/app/website');
		return cy.window().its('frappe').then(frappe => {
			return frappe.call("frappe.tests.ui_test_helpers.create_contact_records");
		});
	});
	it('create a new form', () => {
		cy.visit('/app/todo/new');
		cy.fill_field('description', 'this is a test todo', 'Text Editor').blur();
		cy.wait(300);
		cy.get('.page-title').should('contain', 'Not Saved');
		cy.intercept({
			method: 'POST',
			url: 'api/method/frappe.desk.form.save.savedocs'
		}).as('form_save');
		cy.get('.primary-action').click();
		cy.wait('@form_save').its('response.statusCode').should('eq', 200);
		cy.visit('/app/todo');
		cy.get('.title-text').should('be.visible').and('contain', 'To Do');
		cy.get('.list-row').should('contain', 'this is a test todo');
	});
	it('navigates between documents with child table list filters applied', () => {
		cy.visit('/app/contact');
		cy.add_filter();
		cy.get('.filter-field .input-with-feedback.form-control').type('123', { force: true });
		cy.get('.filter-popover .apply-filters').click({ force: true });
		cy.visit('/app/contact/Test Form Contact 3');
		cy.get('.prev-doc').should('be.visible').click();
		cy.get('.msgprint-dialog .modal-body').contains('No further records').should('be.visible');
		cy.hide_dialog();
		cy.get('.next-doc').click();
		cy.wait(200);
		cy.hide_dialog();
		cy.contains('Test Form Contact 2').should('not.exist');
		cy.get('.title-text').should('contain', 'Test Form Contact 3');
		// clear filters
		cy.visit('/app/contact');
		cy.clear_filters();
	});
	it('validates behaviour of Data options validations in child table', () => {
		// test email validations for set_invalid controller
		let website_input = 'website.in';
		let valid_email = 'user@email.com';
		let expectBackgroundColor = 'rgb(255, 245, 245)';

		cy.visit('/app/contact/new');
		cy.get('.frappe-control[data-fieldname="email_ids"]').as('table');
		cy.get('@table').find('button.grid-add-row').click();
		cy.get('@table').find('button.grid-add-row').click();
		cy.get('@table').find('[data-idx="1"]').as('row1');
		cy.get('@table').find('[data-idx="2"]').as('row2');
		cy.get('@row1').click();
		cy.get('@row1').find('input.input-with-feedback.form-control').as('email_input1');

		cy.get('@email_input1').type(website_input, { waitForAnimations: false });
		cy.fill_field('company_name', 'Test Company');

		cy.get('@row2').click();
		cy.get('@row2').find('input.input-with-feedback.form-control').as('email_input2');
		cy.get('@email_input2').type(valid_email, { waitForAnimations: false });

		cy.get('@row1').click();
		cy.get('@email_input1').should($div => {
			const style = window.getComputedStyle($div[0]);
			expect(style.backgroundColor).to.equal(expectBackgroundColor);
		});
		cy.get('@email_input1').should('have.class', 'invalid');

		cy.get('@row2').click();
		cy.get('@email_input2').should('not.have.class', 'invalid');
	});
});
<commit_msg>test: no need to blur text editor<commit_after>context('Form', () => {
	before(() => {
		cy.login();
		cy.visit('/app/website');
		return cy.window().its('frappe').then(frappe => {
			return frappe.call("frappe.tests.ui_test_helpers.create_contact_records");
		});
	});
	it('create a new form', () => {
		cy.visit('/app/todo/new');
		cy.fill_field('description', 'this is a test todo', 'Text Editor');
		cy.wait(300);
		cy.get('.page-title').should('contain', 'Not Saved');
		cy.intercept({
			method: 'POST',
			url: 'api/method/frappe.desk.form.save.savedocs'
		}).as('form_save');
		cy.get('.primary-action').click();
		cy.wait('@form_save').its('response.statusCode').should('eq', 200);
		cy.visit('/app/todo');
		cy.get('.title-text').should('be.visible').and('contain', 'To Do');
		cy.get('.list-row').should('contain', 'this is a test todo');
	});
	it('navigates between documents with child table list filters applied', () => {
		cy.visit('/app/contact');
		cy.add_filter();
		cy.get('.filter-field .input-with-feedback.form-control').type('123', { force: true });
		cy.get('.filter-popover .apply-filters').click({ force: true });
		cy.visit('/app/contact/Test Form Contact 3');
		cy.get('.prev-doc').should('be.visible').click();
		cy.get('.msgprint-dialog .modal-body').contains('No further records').should('be.visible');
		cy.hide_dialog();
		cy.get('.next-doc').click();
		cy.wait(200);
		cy.hide_dialog();
		cy.contains('Test Form Contact 2').should('not.exist');
		cy.get('.title-text').should('contain', 'Test Form Contact 3');
		// clear filters
		cy.visit('/app/contact');
		cy.clear_filters();
	});
	it('validates behaviour of Data options validations in child table', () => {
		// test email validations for set_invalid controller
		let website_input = 'website.in';
		let valid_email = 'user@email.com';
		let expectBackgroundColor = 'rgb(255, 245, 245)';

		cy.visit('/app/contact/new');
		cy.get('.frappe-control[data-fieldname="email_ids"]').as('table');
		cy.get('@table').find('button.grid-add-row').click();
		cy.get('@table').find('button.grid-add-row').click();
		cy.get('@table').find('[data-idx="1"]').as('row1');
		cy.get('@table').find('[data-idx="2"]').as('row2');
		cy.get('@row1').click();
		cy.get('@row1').find('input.input-with-feedback.form-control').as('email_input1');

		cy.get('@email_input1').type(website_input, { waitForAnimations: false });
		cy.fill_field('company_name', 'Test Company');

		cy.get('@row2').click();
		cy.get('@row2').find('input.input-with-feedback.form-control').as('email_input2');
		cy.get('@email_input2').type(valid_email, { waitForAnimations: false });

		cy.get('@row1').click();
		cy.get('@email_input1').should($div => {
			const style = window.getComputedStyle($div[0]);
			expect(style.backgroundColor).to.equal(expectBackgroundColor);
		});
		cy.get('@email_input1').should('have.class', 'invalid');

		cy.get('@row2').click();
		cy.get('@email_input2').should('not.have.class', 'invalid');
	});
});
<|endoftext|>


<commit_before>$(document).ready(function () {
    $('#oneModalBtn').click(function () {
        openFirstModal().done(function (val) {
            alert(val);
        });
    });

    $('#twoModalsBtn').click(function () {
        openFirstModal().done(function (val) {
            openSecondModal().done(function (val2) {
                alert(val + " sent from first window, " + val2 + " sent from second window");
            });
        });
    });
});

function myOpenWindowFn(param) {
    var deferred = $.Deferred();

    var hostIframe = "";
    var dialogDiv = $("
" + hostIframe + "
").dialog({ modal: true });

    window.addEventListener("message", msgReceived, false);

    function msgReceived(event) {
        if (event && event.data) {
            var dataObject = JSON.parse(event.data);

            if ((dataObject) && (dataObject.iframeId === param.iframeId)) {
                window.removeEventListener("message", msgReceived, false);
                dialogDiv.dialog('close');

                deferred.resolve(dataObject.result); //send response from dialog
            }
        }
    }

    return deferred.promise();
}

function openFirstModal() {
    var popupRes = myOpenWindowFn({ url: 'popup.html', iframeId: 'someIframeId' });

    return popupRes.then(function (value) {
        return ("First value : " + value);
    });
}

function openSecondModal() {
    var popupRes = myOpenWindowFn({ url: "popup2.html", iframeId: 'someIframeId2' });

    return popupRes.then(function (value) {
        return (" , second value : " + value);
    });
}<commit_msg>string fix<commit_after>$(document).ready(function () {
    $('#oneModalBtn').click(function () {
        openFirstModal().done(function (val) {
            alert(val);
        });
    });

    $('#twoModalsBtn').click(function () {
        openFirstModal().done(function (val) {
            openSecondModal().done(function (val2) {
                alert(val + " sent from first window, " + val2 + " sent from second window");
            });
        });
    });
});

function myOpenWindowFn(param) {
    var deferred = $.Deferred();

    var hostIframe = "";
    var dialogDiv = $("
" + hostIframe + "
").dialog({ modal: true });

    window.addEventListener("message", msgReceived, false);

    function msgReceived(event) {
        if (event && event.data) {
            var dataObject = JSON.parse(event.data);

            if ((dataObject) && (dataObject.iframeId === param.iframeId)) {
                window.removeEventListener("message", msgReceived, false);
                dialogDiv.dialog('close');

                deferred.resolve(dataObject.result); //send response from dialog
            }
        }
    }

    return deferred.promise();
}

function openFirstModal() {
    var popupRes = myOpenWindowFn({ url: 'popup.html', iframeId: 'someIframeId' });

    return popupRes.then(function (value) {
        return ("First value : " + value);
    });
}

function openSecondModal() {
    var popupRes = myOpenWindowFn({ url: "popup2.html", iframeId: 'someIframeId2' });

    return popupRes.then(function (value) {
        return ("second value : " + value);
    });
}<|endoftext|>


<commit_before>import React from 'react';
import Status from './Status';

export  default () => (
  <Status code={404}>

Sorry, can’t find that.

  </Status>
);<commit_msg>Add router<commit_after>import React from 'react';
import Status from './Status';

export default () => (
  <Status code={404}>

Sorry, can’t find that.

  </Status>
);<|endoftext|>


<commit_before>#!/usr/bin/env node

var fs = require('fs'),
    path = require('path'),
    wrench = require('wrench'),
    libpath = require('path'),
    glob = require("glob"),
    program = require('commander'),
    async = require('async'),
    child = require('child_process'),
    cwd = __dirname,
    pids = [],
    thePid = null,
    pidNames = {},
    thePidName = null,
    returnVal = 0,
    hostname = require('os').hostname(),
    dns = require('dns'),
    hostip,
    remoteselenium;

program.command('test')
    .description('Run unit and functional tests')
    .option('-u, --unit', 'Run unit tests')
    .option('-f, --func', 'Run functional tests')
    .option('-s, --no-selenium', 'Don\'t run arrow_selenium')
    .option('-a, --no-arrow', 'Don\'t run arrow_server')
    .option('--debugApps', 'show STDOUT and STDERR from apps')
    .option('--logLevel <value>', 'Arrow logLevel')
    .option('--testName <value>', 'Arrow testName')
    .option('--descriptor <value>', 'which descriptor to run. filename (or glob) relative to --path')
    .option('--port <value>', 'port number to run app')
    .option('--coverage', 'Arrow code coverage')
    .option('--group <value>', 'Arrow group')
    .option('--driver <value>', 'Arrow driver')
    .option('--browser <value>', 'Arrow browser')
    .option('--path <value>', 'Path to find the tests. defaults to ./func or ./unit')
    .action(test);

// report how we're called, mainly to help debug CI environments
console.log(process.argv.join(' '));
console.log();

program.parse(process.argv);

function test (cmd) {
    var series = [];
    cmd.logLevel = cmd.logLevel || 'WARN';
    // Default to all tests
    if (!cmd.unit && !cmd.func) {
        cmd.unit = true;
        cmd.func = true;
    }
    cmd.unitBrowser = cmd.unitBrowser || cmd.browser || 'firefox';
    cmd.funcBrowser = cmd.funcBrowser || cmd.browser || 'firefox';
    cmd.unitPath = path.resolve(cwd, cmd.unitPath || cmd.path || './unit');
    cmd.funcPath = path.resolve(cwd, cmd.funcPath || cmd.path || './func');

    if (process.env['SELENIUM_HUB_URL']) {
        remoteselenium = process.env['SELENIUM_HUB_URL'];
        console.log('selenium host.....' + remoteselenium);
    }

    series.push(gethostip);

    if (cmd.arrow) {
        series.push(startArrowServer);
    }
    if (cmd.unit) {
        if ('phantomjs' !== cmd.unitBrowser) {
            if (cmd.selenium) {
                series.push(function (callback) {
                    startArrowSelenium(cmd, callback);
                });
            }
        }
        series.push(function (callback) {
            runUnitTests(cmd, callback)
        });
    }
    if (cmd.func) {
        if ('phantomjs' !== cmd.funcBrowser) {
            if (cmd.selenium) {
                series.push(function (callback) {
                    startArrowSelenium(cmd, callback);
                });
            }
        }
        series.push(function (callback) {
            runFuncAppTests(cmd, callback)
        });
    }
    async.series(series, finalize);
}

function gethostip(callback){
    dns.lookup(hostname, function (err, addr, fam) {
        hostip = addr;
        console.log('App running at.....' + hostip);
    });
    callback(null);
}

function startArrowServer (callback) {
    var timeout,
        listener = function (data) {
            process.stdout.write(data);
        };
    console.log("---Starting Arrow Server---");
    var p = runCommand(cwd, "node", [cwd+"/../node_modules/yahoo-arrow/arrow_server/server.js"], function () {
        // If this command returns called, then it failed to launch
        if (timeout) {
            clearTimeout(timeout);
        }
        console.log('arrow_server failed to start. If it is already running' +
            ' use \'-a\' to skip startup of arrow_server.');
        pids.pop();
        callback(1); // Trigger failure
    });
    p.stdout.on('data', listener);
    pids.push(p.pid);
    pidNames[p.pid] = 'arrow_server';
    timeout = setTimeout(function () {
        p.stdout.removeListener('data', listener); // Stop printing output from arrow_server
        callback(null);
    }, 5000);
}

function runUnitTests (cmd, callback) {
    console.log('---Running Unit Tests---');
    var arrowReportDir = cmd.unitPath + '/artifacts/arrowreport/';
    try {
        wrench.rmdirSyncRecursive(arrowReportDir);
    } catch (e) {}
    wrench.mkdirSyncRecursive(arrowReportDir);

    var descriptor = cmd.descriptor || '**/*_descriptor.json';
    var commandArgs = [
        cwd + "/../node_modules/yahoo-arrow/index.js",
        "--descriptor=" + cmd.unitPath + '/' + descriptor,
        "--exitCode=true",
        "--report=true",
        "--reportFolder=" + arrowReportDir
    ];
    if ('phantomjs' !== cmd.unitBrowser) {
        commandArgs.push('--reuseSession');
    }
    commandArgs.push('--logLevel=' + cmd.logLevel);
    commandArgs.push('--browser=' + cmd.unitBrowser);
    cmd.driver && commandArgs.push('--driver=' + cmd.driver);
    cmd.testName && commandArgs.push('--testName=' + cmd.testName);
    cmd.group && commandArgs.push('--group=' + cmd.group);
    cmd.coverage && commandArgs.push('--coverage=' + cmd.coverage);

    var p = runCommand(
        cmd.unitPath,
        "node",
        commandArgs,
        function (code) {
            callback(code);
        }
    );
    p.stdout.on('data', function (data) {
        process.stdout.write(data);
    });
}

function build (cmd, callback) {
    console.log('---Building Apps---');
    runCommand(
        cmd.funcPath + '/applications/frameworkapp/common',
        cwd + "/../bin/mojito",
        ['build', 'html5app', cmd.funcPath + '/applications/frameworkapp/flatfile'],
        callback
    );
}

function startArrowSelenium (cmd, callback) {
    console.log("---Starting Arrow Selenium---");
    var commandArgs = [cwd+"/../node_modules/yahoo-arrow/arrow_selenium/selenium.js"];
    if (remoteselenium) {
        commandArgs.push('--seleniumHost=' + remoteselenium);
    }
    commandArgs.push("--open=" + cmd.funcBrowser);
    runCommand(cwd, "node", commandArgs, function () {
        callback(null);
    });
}

function runFuncAppTests(cmd, callback){
    var descriptor = cmd.descriptor || '**/*_descriptor.json',
        descriptors = [],
        exeSeries = [];
    if(descriptor === '**/*_descriptor.json'){
        descriptors = glob.sync(cmd.funcPath +'/' + descriptor);
    } else {
        descriptors.push(cmd.funcPath + '/' + descriptor);
    }

    var arrowReportDir = cmd.funcPath + '/../../artifacts/arrowreport/';
    try {
        wrench.rmdirSyncRecursive(arrowReportDir);
    } catch (e) {}
    wrench.mkdirSyncRecursive(arrowReportDir);

    async.forEachSeries(descriptors, function(des, callback) {
        var appConfig = JSON.parse(fs.readFileSync(des, 'utf8'));
        var app = appConfig[0].config.application,
            port = cmd.port || 8666,
            param = app.param || null,
            type = app.type || 'mojito';
        if (type === "static") {
            exeSeries.push(build(cmd, function() {
                runStaticApp(cmd.funcPath + '/applications', app.path, port, function(thispid) {
                    runFuncTests(cmd, des, port, thispid, arrowReportDir, callback);
                });
            }))
        } else {
            exeSeries.push(runMojitoApp(app, cmd, cmd.funcPath + '/applications', port, app.param, function(thispid) {
                runFuncTests(cmd, des, port, thispid, arrowReportDir, callback);
            }));
        }
    }, function(err) {
          callback(err);
    });
    async.series(exeSeries, callback);
}

function runFuncTests (cmd, desc, port, thispid, arrowReportDir, callback) {
    console.log('---Running Functional Tests---');

    var group = cmd.group || null,
        baseUrl = 'http:\/\/'+hostip+':'+port;
    var commandArgs = [
        cwd + "/../node_modules/yahoo-arrow/index.js",
        "--descriptor=" + desc,
        "--baseUrl=" + baseUrl,
        "--exitCode=true",
        "--report=true",
        "--reportFolder=" + arrowReportDir,
        "--config=" + cwd + "/config/config.js"
    ];
    if ('phantomjs' !== cmd.funcBrowser) {
        commandArgs.push('--reuseSession');
    }
    if (remoteselenium) {
        commandArgs.push('--seleniumHost=' + remoteselenium);
    }
    commandArgs.push('--logLevel=' + cmd.logLevel);
    commandArgs.push('--browser=' + cmd.funcBrowser);
    cmd.driver && commandArgs.push('--driver=' + cmd.driver);
    cmd.testName && commandArgs.push('--testName=' + cmd.testName);
    cmd.group && commandArgs.push('--group=' + cmd.group);
    cmd.coverage && commandArgs.push('--coverage=' + cmd.coverage);

    var p = runCommand(
        cmd.funcPath,
        "node",
        commandArgs,
        function (code) {
            try {
                console.log('Shutting down pid '+ thePid + ' -- ' + thePidName);
                process.kill(thePid);
                pids.pop(thePid);
            }
            catch(e) {
                console.log('FAILED to shut down pid:' + thePid);
            }
            callback(code);
        }
    );
    p.stdout.on('data', function (data) {
        process.stdout.write(data);
    });
}

function finalize (err, results) {
    console.log("---in finalize---");
    for(var i=0; i < pids.length; i++) {
        console.log('Shutting down pid ' + pids[i] + ' -- ' + pidNames[pids[i]]);
        try {
            process.kill(pids[i]);
        }
        catch(e) {
            console.log('FAILED to shut down pid ' + pids[i] + ' -- ' + pidNames[pids[i]]);
        }
    }
    if (err) {
        console.log(err);
        console.log('FAILED');
        process.exit(1);
        return;
    }
    console.log('Completed');
    process.exit(0);

}

function runCommand (path, command, argv, callback) {
    callback = callback || function () {};
    process.chdir(path);
    console.log(command + ' ' + argv.join(' '));
    var cmd = child.spawn(command, argv, {
        cwd: path,
        env: process.env
    });

    cmd.stdout.on('data', function (data) {
        // Don't care generally. But, specific commands may want a listener for this.
    });

    cmd.stderr.on('data', function (data) {
        process.stdout.write(data);
    });

    cmd.on('exit', function (code) {
        cmd.stdin.end();
        if (0 !== code) {
            callback('exit: child process exited with code ' + code);
            return;
        }
        callback(code);
    });

    cmd.on('uncaughtException', function (err) {
        process.stderr.write('uncaught exception: ' + err+'\n');
        callback(1);
    });

    return cmd;
}

function runMojitoApp (app, cliOptions, basePath, port, params, callback) {
    params = params || '';
    var cmdArgs = ['start'];
    console.log("---Starting application---");
    if (port) {
        cmdArgs.push(port);
    }
    if (params) {
        cmdArgs.push('--context');
        cmdArgs.push(params);
    }
    var p = runCommand(basePath + '/' + app.path, cwd + "/../bin/mojito", cmdArgs, function () {});
        thispid = p.pid;
    thePid = p.pid;
    thePidName = app.name + ':' + port + (params ? '?' + params : '');
    pids.push(thePid);
    pidNames[p.pid] = thePidName;
    if (cliOptions.debugApps) {
        p.stdout.on('data', function(data) {
            console.error('---DEBUG ' + port + ' STDOUT--- ' + data.toString());
        });
        p.stderr.on('data', function(data) {
            console.error('---DEBUG ' + port + ' STDERR--- ' + data.toString());
        });
    }

    var listener;
    listener = function(data) {
        if (data.toString().match(/✔ 	Mojito\(v/)) {
            p.stdout.removeListener('data', listener);
            callback(thePid);
        }
    }
    p.stdout.on('data', listener);
}

function runStaticApp (basePath, path, port, callback) {
    console.log('---Starting static server for ' + path + ' at port ' + port);
    var p = runCommand(basePath + '/' + path, cwd + "/../node_modules/.bin/static", ['-p', port, '-c', '1'], function () {});
    thePid = p.pid;
    thePidName = 'static ' + libpath.basename(path) + ':' + port;
    pids.push(p.pid);
    pidNames[p.pid] = 'static ' + libpath.basename(path) + ':' + port;

    var listener;
    listener = function(data) {
        if (data.toString().match(/serving \".\" at http:\/\//)) {
            p.stdout.removeListener('data', listener);
            callback(thePid);
        }
    }
    p.stdout.on('data', listener);
}
<commit_msg>add error checking and mv callback into the anonymous func<commit_after>#!/usr/bin/env node

var fs = require('fs'),
    path = require('path'),
    wrench = require('wrench'),
    libpath = require('path'),
    glob = require("glob"),
    program = require('commander'),
    async = require('async'),
    child = require('child_process'),
    cwd = __dirname,
    pids = [],
    thePid = null,
    pidNames = {},
    thePidName = null,
    returnVal = 0,
    hostname = require('os').hostname(),
    dns = require('dns'),
    hostip,
    remoteselenium;

program.command('test')
    .description('Run unit and functional tests')
    .option('-u, --unit', 'Run unit tests')
    .option('-f, --func', 'Run functional tests')
    .option('-s, --no-selenium', 'Don\'t run arrow_selenium')
    .option('-a, --no-arrow', 'Don\'t run arrow_server')
    .option('--debugApps', 'show STDOUT and STDERR from apps')
    .option('--logLevel <value>', 'Arrow logLevel')
    .option('--testName <value>', 'Arrow testName')
    .option('--descriptor <value>', 'which descriptor to run. filename (or glob) relative to --path')
    .option('--port <value>', 'port number to run app')
    .option('--coverage', 'Arrow code coverage')
    .option('--group <value>', 'Arrow group')
    .option('--driver <value>', 'Arrow driver')
    .option('--browser <value>', 'Arrow browser')
    .option('--path <value>', 'Path to find the tests. defaults to ./func or ./unit')
    .action(test);

// report how we're called, mainly to help debug CI environments
console.log(process.argv.join(' '));
console.log();

program.parse(process.argv);

function test (cmd) {
    var series = [];
    cmd.logLevel = cmd.logLevel || 'WARN';
    // Default to all tests
    if (!cmd.unit && !cmd.func) {
        cmd.unit = true;
        cmd.func = true;
    }
    cmd.unitBrowser = cmd.unitBrowser || cmd.browser || 'firefox';
    cmd.funcBrowser = cmd.funcBrowser || cmd.browser || 'firefox';
    cmd.unitPath = path.resolve(cwd, cmd.unitPath || cmd.path || './unit');
    cmd.funcPath = path.resolve(cwd, cmd.funcPath || cmd.path || './func');

    if (process.env['SELENIUM_HUB_URL']) {
        remoteselenium = process.env['SELENIUM_HUB_URL'];
        console.log('selenium host.....' + remoteselenium);
    }

    series.push(gethostip);

    if (cmd.arrow) {
        series.push(startArrowServer);
    }
    if (cmd.unit) {
        if ('phantomjs' !== cmd.unitBrowser) {
            if (cmd.selenium) {
                series.push(function (callback) {
                    startArrowSelenium(cmd, callback);
                });
            }
        }
        series.push(function (callback) {
            runUnitTests(cmd, callback)
        });
    }
    if (cmd.func) {
        if ('phantomjs' !== cmd.funcBrowser) {
            if (cmd.selenium) {
                series.push(function (callback) {
                    startArrowSelenium(cmd, callback);
                });
            }
        }
        series.push(function (callback) {
            runFuncAppTests(cmd, callback)
        });
    }
    async.series(series, finalize);
}

function gethostip(callback){
    dns.lookup(hostname, function (err, addr, fam) {
        if (err){
            callback(err);
            return;
        }
        hostip = addr;
        console.log('App running at.....' + hostip);
        callback(null);
    });
}

function startArrowServer (callback) {
    var timeout,
        listener = function (data) {
            process.stdout.write(data);
        };
    console.log("---Starting Arrow Server---");
    var p = runCommand(cwd, "node", [cwd+"/../node_modules/yahoo-arrow/arrow_server/server.js"], function () {
        // If this command returns called, then it failed to launch
        if (timeout) {
            clearTimeout(timeout);
        }
        console.log('arrow_server failed to start. If it is already running' +
            ' use \'-a\' to skip startup of arrow_server.');
        pids.pop();
        callback(1); // Trigger failure
    });
    p.stdout.on('data', listener);
    pids.push(p.pid);
    pidNames[p.pid] = 'arrow_server';
    timeout = setTimeout(function () {
        p.stdout.removeListener('data', listener); // Stop printing output from arrow_server
        callback(null);
    }, 5000);
}

function runUnitTests (cmd, callback) {
    console.log('---Running Unit Tests---');
    var arrowReportDir = cmd.unitPath + '/artifacts/arrowreport/';
    try {
        wrench.rmdirSyncRecursive(arrowReportDir);
    } catch (e) {}
    wrench.mkdirSyncRecursive(arrowReportDir);

    var descriptor = cmd.descriptor || '**/*_descriptor.json';
    var commandArgs = [
        cwd + "/../node_modules/yahoo-arrow/index.js",
        "--descriptor=" + cmd.unitPath + '/' + descriptor,
        "--exitCode=true",
        "--report=true",
        "--reportFolder=" + arrowReportDir
    ];
    if ('phantomjs' !== cmd.unitBrowser) {
        commandArgs.push('--reuseSession');
    }
    commandArgs.push('--logLevel=' + cmd.logLevel);
    commandArgs.push('--browser=' + cmd.unitBrowser);
    cmd.driver && commandArgs.push('--driver=' + cmd.driver);
    cmd.testName && commandArgs.push('--testName=' + cmd.testName);
    cmd.group && commandArgs.push('--group=' + cmd.group);
    cmd.coverage && commandArgs.push('--coverage=' + cmd.coverage);

    var p = runCommand(
        cmd.unitPath,
        "node",
        commandArgs,
        function (code) {
            callback(code);
        }
    );
    p.stdout.on('data', function (data) {
        process.stdout.write(data);
    });
}

function build (cmd, callback) {
    console.log('---Building Apps---');
    runCommand(
        cmd.funcPath + '/applications/frameworkapp/common',
        cwd + "/../bin/mojito",
        ['build', 'html5app', cmd.funcPath + '/applications/frameworkapp/flatfile'],
        callback
    );
}

function startArrowSelenium (cmd, callback) {
    console.log("---Starting Arrow Selenium---");
    var commandArgs = [cwd+"/../node_modules/yahoo-arrow/arrow_selenium/selenium.js"];
    if (remoteselenium) {
        commandArgs.push('--seleniumHost=' + remoteselenium);
    }
    commandArgs.push("--open=" + cmd.funcBrowser);
    runCommand(cwd, "node", commandArgs, function () {
        callback(null);
    });
}

function runFuncAppTests(cmd, callback){
    var descriptor = cmd.descriptor || '**/*_descriptor.json',
        descriptors = [],
        exeSeries = [];
    if(descriptor === '**/*_descriptor.json'){
        descriptors = glob.sync(cmd.funcPath +'/' + descriptor);
    } else {
        descriptors.push(cmd.funcPath + '/' + descriptor);
    }

    var arrowReportDir = cmd.funcPath + '/../../artifacts/arrowreport/';
    try {
        wrench.rmdirSyncRecursive(arrowReportDir);
    } catch (e) {}
    wrench.mkdirSyncRecursive(arrowReportDir);

    async.forEachSeries(descriptors, function(des, callback) {
        var appConfig = JSON.parse(fs.readFileSync(des, 'utf8'));
        var app = appConfig[0].config.application,
            port = cmd.port || 8666,
            param = app.param || null,
            type = app.type || 'mojito';
        if (type === "static") {
            exeSeries.push(build(cmd, function() {
                runStaticApp(cmd.funcPath + '/applications', app.path, port, function(thispid) {
                    runFuncTests(cmd, des, port, thispid, arrowReportDir, callback);
                });
            }))
        } else {
            exeSeries.push(runMojitoApp(app, cmd, cmd.funcPath + '/applications', port, app.param, function(thispid) {
                runFuncTests(cmd, des, port, thispid, arrowReportDir, callback);
            }));
        }
    }, function(err) {
          callback(err);
    });
    async.series(exeSeries, callback);
}

function runFuncTests (cmd, desc, port, thispid, arrowReportDir, callback) {
    console.log('---Running Functional Tests---');

    var group = cmd.group || null,
        baseUrl = 'http:\/\/'+hostip+':'+port;
    var commandArgs = [
        cwd + "/../node_modules/yahoo-arrow/index.js",
        "--descriptor=" + desc,
        "--baseUrl=" + baseUrl,
        "--exitCode=true",
        "--report=true",
        "--reportFolder=" + arrowReportDir,
        "--config=" + cwd + "/config/config.js"
    ];
    if ('phantomjs' !== cmd.funcBrowser) {
        commandArgs.push('--reuseSession');
    }
    if (remoteselenium) {
        commandArgs.push('--seleniumHost=' + remoteselenium);
    }
    commandArgs.push('--logLevel=' + cmd.logLevel);
    commandArgs.push('--browser=' + cmd.funcBrowser);
    cmd.driver && commandArgs.push('--driver=' + cmd.driver);
    cmd.testName && commandArgs.push('--testName=' + cmd.testName);
    cmd.group && commandArgs.push('--group=' + cmd.group);
    cmd.coverage && commandArgs.push('--coverage=' + cmd.coverage);

    var p = runCommand(
        cmd.funcPath,
        "node",
        commandArgs,
        function (code) {
            try {
                console.log('Shutting down pid '+ thePid + ' -- ' + thePidName);
                process.kill(thePid);
                pids.pop(thePid);
            }
            catch(e) {
                console.log('FAILED to shut down pid:' + thePid);
            }
            callback(code);
        }
    );
    p.stdout.on('data', function (data) {
        process.stdout.write(data);
    });
}

function finalize (err, results) {
    console.log("---in finalize---");
    for(var i=0; i < pids.length; i++) {
        console.log('Shutting down pid ' + pids[i] + ' -- ' + pidNames[pids[i]]);
        try {
            process.kill(pids[i]);
        }
        catch(e) {
            console.log('FAILED to shut down pid ' + pids[i] + ' -- ' + pidNames[pids[i]]);
        }
    }
    if (err) {
        console.log(err);
        console.log('FAILED');
        process.exit(1);
        return;
    }
    console.log('Completed');
    process.exit(0);

}

function runCommand (path, command, argv, callback) {
    callback = callback || function () {};
    process.chdir(path);
    console.log(command + ' ' + argv.join(' '));
    var cmd = child.spawn(command, argv, {
        cwd: path,
        env: process.env
    });

    cmd.stdout.on('data', function (data) {
        // Don't care generally. But, specific commands may want a listener for this.
    });

    cmd.stderr.on('data', function (data) {
        process.stdout.write(data);
    });

    cmd.on('exit', function (code) {
        cmd.stdin.end();
        if (0 !== code) {
            callback('exit: child process exited with code ' + code);
            return;
        }
        callback(code);
    });

    cmd.on('uncaughtException', function (err) {
        process.stderr.write('uncaught exception: ' + err+'\n');
        callback(1);
    });

    return cmd;
}

function runMojitoApp (app, cliOptions, basePath, port, params, callback) {
    params = params || '';
    var cmdArgs = ['start'];
    console.log("---Starting application---");
    if (port) {
        cmdArgs.push(port);
    }
    if (params) {
        cmdArgs.push('--context');
        cmdArgs.push(params);
    }
    var p = runCommand(basePath + '/' + app.path, cwd + "/../bin/mojito", cmdArgs, function () {});
        thispid = p.pid;
    thePid = p.pid;
    thePidName = app.name + ':' + port + (params ? '?' + params : '');
    pids.push(thePid);
    pidNames[p.pid] = thePidName;
    if (cliOptions.debugApps) {
        p.stdout.on('data', function(data) {
            console.error('---DEBUG ' + port + ' STDOUT--- ' + data.toString());
        });
        p.stderr.on('data', function(data) {
            console.error('---DEBUG ' + port + ' STDERR--- ' + data.toString());
        });
    }

    var listener;
    listener = function(data) {
        if (data.toString().match(/✔ 	Mojito\(v/)) {
            p.stdout.removeListener('data', listener);
            callback(thePid);
        }
    }
    p.stdout.on('data', listener);
}

function runStaticApp (basePath, path, port, callback) {
    console.log('---Starting static server for ' + path + ' at port ' + port);
    var p = runCommand(basePath + '/' + path, cwd + "/../node_modules/.bin/static", ['-p', port, '-c', '1'], function () {});
    thePid = p.pid;
    thePidName = 'static ' + libpath.basename(path) + ':' + port;
    pids.push(p.pid);
    pidNames[p.pid] = 'static ' + libpath.basename(path) + ':' + port;

    var listener;
    listener = function(data) {
        if (data.toString().match(/serving \".\" at http:\/\//)) {
            p.stdout.removeListener('data', listener);
            callback(thePid);
        }
    }
    p.stdout.on('data', listener);
}
<|endoftext|>


<commit_before>var l10n_file = __dirname + '/../l10n/commands/emote.yml';
var l10n = require('../src/l10n')(l10n_file);
var CommandUtil = require('../src/command_util').CommandUtil;
exports.command = function(rooms, items, players, npcs, Commands) {
  return function(args, player) {
    self = player.getName();
    if (args) {
      player.say(self + args);
      players.eachIf(function(p) {
        return otherPlayersInRoom(p);
      }, function(p) {
        p.say(self + args);
      });
      return;
    }

    player.sayL10n(l10n, 'NOTHING_EMOTED');
    return;
  }

  function otherPlayersInRoom(p) {
    if (p)
      return (p.getName() !== player.getName() && p.getLocation() === player.getLocation());
  };

};<commit_msg>Prettified message<commit_after>var l10n_file = __dirname + '/../l10n/commands/emote.yml';
var l10n = require('../src/l10n')(l10n_file);
var CommandUtil = require('../src/command_util').CommandUtil;
exports.command = function(rooms, items, players, npcs, Commands) {
  return function(args, player) {
    self = player.getName();
    if (args) {
      player.say(self + " " + args);
      players.eachIf(function(p) {
        return otherPlayersInRoom(p);
      }, function(p) {
        p.say(self + " " + args);
      });
      return;
    }

    player.sayL10n(l10n, 'NOTHING_EMOTED');
    return;
  }

  function otherPlayersInRoom(p) {
    if (p)
      return (p.getName() !== player.getName() && p.getLocation() === player.getLocation());
  };

};<|endoftext|>


<commit_before>import React, { Fragment } from 'react'
import propPath from 'crocks/Maybe/propPath'
import Maybe from 'crocks/Maybe'
import map from 'crocks/pointfree/map'
import reduce from 'crocks/pointfree/reduce'
import assoc from 'crocks/helpers/assoc'
import assign from 'crocks/helpers/assign'
import styled, { keyframes } from 'styled-components'
import { key } from 'styled-theme'
import {
  Section
} from 'Styled'
import { Navigation } from 'Components'
import {
  findSection,
  getElementsFromProps,
  getParagraphsFromProps,
  s4,
} from 'Helpers'

import { default as Header } from './ResearchHeader'
import { default as Cite } from './ResearchCite'
import { default as Description } from './ResearchDescription'

const SectionOne = Section.extend`
  justify-content:  space-between;
  align-items: center;
  height: calc(100vh - 120px);
  background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAA0SURBVHgBTYyBCQAgEAKtFmuzr8ka7ZPSSDgEFRuAJIV0sQiGiucVV5OEHA7jK85XeuHBBmGQCsVtBlV2AAAAAElFTkSuQmCC) repeat, ${({image}) => 'url(' + image + ')'} no-repeat ${key('colors.black')};
  background-size: 5px 5px, auto 105vh;
`

export default ({data}) => {
  const sort = (order, xs) =>
    order.reduce((acc, x) => acc.concat([...xs[x]]), [])

  const sections = findSection(data)
  const head = propPath([0])
  const second = propPath([1])
  const uid = propPath(['node', 'uid'])
  const body = propPath(['node', 'data', 'body'])
  const items = propPath(['items'])
  const title = propPath(['primary', 'title'])
  const header = propPath(['primary', 'header'])
  const text = propPath([0, 'text'])
  const cite = propPath(['primary', 'cite'])
  const description = propPath(['primary', 'description'])
  const image = propPath(['image', 'url'])

  const pageTitle = sections('research').chain(body).chain(head).chain(title).option([])
  const pageCite = sections('research').chain(body).chain(head).chain(cite).option([])
  const pageDescription = sections('research').chain(body).chain(head).chain(description).option([])
  const pageBackImg = sections('research').chain(body).chain(second).chain(items).chain(head).chain(image).option([])
  const pageAnchors = data.map(edge => assoc('uid', uid(edge).option({}))({}))
  const pageHeaders = data.map(edge => body(edge).chain(head).chain(header).chain(head).option({}))
  const pageNav = pageHeaders.map((header, i) => assign(header, pageAnchors[i])).filter(x => x.text)

  console.log(
  )

  return (
    <Fragment>

        <SectionOne image={pageBackImg} >

          <Description data={{ description: getParagraphsFromProps(pageDescription) }} />
          <Navigation data={ sort([4, 5, 3, 1, 2, 7, 6, 0], pageNav) } />
        </SectionOne>

        { JSON.stringify(data) }

    </Fragment>
  )
}<commit_msg>pattern<commit_after>import React, { Fragment } from 'react'
import propPath from 'crocks/Maybe/propPath'
import Maybe from 'crocks/Maybe'
import map from 'crocks/pointfree/map'
import reduce from 'crocks/pointfree/reduce'
import assoc from 'crocks/helpers/assoc'
import assign from 'crocks/helpers/assign'
import styled, { keyframes } from 'styled-components'
import { key } from 'styled-theme'
import {
  Section
} from 'Styled'
import { Navigation } from 'Components'
import {
  findSection,
  getElementsFromProps,
  getParagraphsFromProps,
  s4,
} from 'Helpers'

import { default as Header } from './ResearchHeader'
import { default as Cite } from './ResearchCite'
import { default as Description } from './ResearchDescription'

const SectionOne = Section.extend`
  justify-content:  space-between;
  align-items: center;
  height: calc(100vh - 120px);
  background: url(data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAYAAAAGCAYAAADgzO9IAAAACXBIWXMAAAsTAAALEwEAmpwYAAAAAXNSR0IArs4c6QAAAARnQU1BAACxjwv8YQUAAAAzSURBVHgBpYxRDgAgCEKfq4N1s/Lkpc0P/dYNYcAQ4FBv+xPDNWgyvx4RurFSgRms/akHyzsJj/3feW8AAAAASUVORK5CYII=) repeat, ${({image}) => 'url(' + image + ')'} no-repeat ${key('colors.black')};
  background-size: 6px 6px, auto 105vh;
`

export default ({data}) => {
  const sort = (order, xs) =>
    order.reduce((acc, x) => acc.concat([...xs[x]]), [])

  const sections = findSection(data)
  const head = propPath([0])
  const second = propPath([1])
  const uid = propPath(['node', 'uid'])
  const body = propPath(['node', 'data', 'body'])
  const items = propPath(['items'])
  const title = propPath(['primary', 'title'])
  const header = propPath(['primary', 'header'])
  const text = propPath([0, 'text'])
  const cite = propPath(['primary', 'cite'])
  const description = propPath(['primary', 'description'])
  const image = propPath(['image', 'url'])

  const pageTitle = sections('research').chain(body).chain(head).chain(title).option([])
  const pageCite = sections('research').chain(body).chain(head).chain(cite).option([])
  const pageDescription = sections('research').chain(body).chain(head).chain(description).option([])
  const pageBackImg = sections('research').chain(body).chain(second).chain(items).chain(head).chain(image).option([])
  const pageAnchors = data.map(edge => assoc('uid', uid(edge).option({}))({}))
  const pageHeaders = data.map(edge => body(edge).chain(head).chain(header).chain(head).option({}))
  const pageNav = pageHeaders.map((header, i) => assign(header, pageAnchors[i])).filter(x => x.text)

  console.log(
  )

  return (
    <Fragment>

        <SectionOne image={pageBackImg} >

          <Description data={{ description: getParagraphsFromProps(pageDescription) }} />
          <Navigation data={ sort([4, 5, 3, 1, 2, 7, 6, 0], pageNav) } />
        </SectionOne>

        { JSON.stringify(data) }

    </Fragment>
  )
}<|endoftext|>


<commit_before>"use strict";

class ColorWheel {
    /**
     * Constructs the HSV colorwheel
     * @param {string} id - The id that will be given to the div holding all the elements
     * @param {Number} size - The diameter of the colorwheel
     */
    constructor(id, size) {
        this.radius = size / 2;
        this.ringsize = size / 10;
        this.color = 0;

        this.length = Math.sqrt(2 * Math.pow(this.radius - this.ringsize, 2)); //Size of the inner square
        this.half = this.length / 2;

        this.can = $('<canvas>').attr({
            width: size,
            height: size
        });
        this.ctx = this.can.get(0).getContext('2d');

        this.outer = $('<div/>').addClass('colorwheel-outer').css({
            width: this.ringsize,
            height: this.ringsize
        });
        this.inner = $('<div/>').addClass('colorwheel-inner');

        this.holder = $('<div/>').attr('id', id).append(this.outer).append(this.inner).append(this.can);
        this.x = this.y = this.radius;

        this.setHue(this.color * (Math.PI / 180));
        this.inner.css({
            left: this.can.position().left + this.x - 2.5,
            top: this.can.position().top + this.y - 2.5
        });

        this.focusOut = false, this.focusIn = false;

        this.renderOuter();
        this.renderInner();

        var _this = this;
        $(this.holder).on('mousedown', function (evt) {
            evt.preventDefault();
            var offset = _this.getRelativePos(_this.can, evt);
            var dist = Math.sqrt(Math.pow(_this.x - offset.x, 2) + Math.pow(_this.y - offset.y, 2));
            if (dist < _this.radius && dist > _this.radius - _this.ringsize) {
                _this.focusOut = true;
                _this.updateOuter(evt);
            } else if (dist < _this.radius - _this.ringsize) {
                _this.focusIn = true;
                _this.updateInner(evt);
            }
        });
        $(document).on('mouseup', function (evt) {
            _this.focusOut = _this.focusIn = false;
        }).on('mousemove', function (evt) {
            if (_this.focusOut) {
                _this.updateOuter(evt);
            } else if (_this.focusIn) {
                _this.updateInner(evt);
            }
        });
        $('body').append(this.holder);
    }

    getRGB() {
        var x = this.inner.offset().left - this.can.offset().left + 2.5;
        var y = this.inner.offset().top - this.can.offset().top + 2.5;

        var c = this.ctx.getImageData(x, y, 1, 1).data;
        return { 'r': c[0], 'g': c[1], 'b': c[2] };
    }

    getHex() {
        var rgb = this.getRGB();
        return this.toHex(rgb.r) + this.toHex(rgb.g) + this.toHex(rgb.b);
    }

    getHSL() {
        var rgb = this.getRGB();
        return ColorConvert.RGBToHSL(rgb.r, rgb.g, rgb.b);
    }

    toHex(value) {
        var hex = value.toString(16);
        return hex.length == 1 ? '0' + hex : hex;
    }

    setHue(angle) {
        this.color = angle * 60;
        var middle = this.radius - ((this.ringsize) / 2);
        this.outer.css({
            left: Math.cos(angle) * middle + this.can.position().left + this.x - (this.ringsize / 2) - 2,
            top: Math.sin(angle) * middle + this.can.position().top + this.y - (this.ringsize / 2) - 2
        });
    }

    setColor(r, g, b) {
        var hsl = ColorConvert.RGBtoHSL(r, g, b);
        var hsv = ColorConvert.HSLToHSB(hsl.h / 60, hsl.s / 100, hsl.l / 100);
        this.setHue(hsv.h / 60);
        this.renderInner();

        this.inner.css({
            left: this.x - this.half + ((this.length) * (hsv.s / 100)) - 3,
            top: this.y + this.half - ((this.length) * (hsv.b / 100)) - (hsv.b == 0 ? 2 : 0)
        });
    }

    setColorHex(hex) {
        var rgb = ColorConvert.HexToRGB(hex);
        this.setColor(rgb.r, rgb.g, rgb.b);
    }

    renderOuter() {
        for (var i = 0; i < 360; i++) {
            this.ctx.beginPath();
            this.ctx.fillStyle = 'hsl(' + i + ', 100%, 50%)';
            this.ctx.moveTo(this.x, this.y);
            this.ctx.arc(this.x, this.y, this.radius, (i - 2) * (Math.PI / 180), (i * (Math.PI / 180)), false);
            this.ctx.lineTo(this.x, this.y);
            this.ctx.fill();
        }
        //Draw white to hide the center area
        this.ctx.beginPath();
        this.ctx.fillStyle = 'white';
        this.ctx.moveTo(this.x, this.y);
        this.ctx.arc(this.x, this.y, this.radius - this.ringsize, 0, 2 * Math.PI, false);
        this.ctx.fill();
    }

    _clean(val) {
        val = Math.round(val);
        if(val % 2 != 0) {
            val -= 1;
        }
        return val;
    }

    renderInner() {
        var startX = this.x - this.half - 1;
        startX = this._clean(startX);
        for(var i = 0; i < 100; i++) {
            var line = this.ctx.createLinearGradient(
                startX,
                this._clean(this.y - this.half + (i * (this.length / 100)) ),
                this._clean(this.x + this.half + 2),
                this._clean(this.y - this.half + (i * (this.length / 100))) + 2
            );

            var stops = 15;

            for(var j = 0; j < stops; j++) {
                var s = (j == stops - 1 ? 1 : 0) + j;
                var l = 100 - i - (i == 99 ? 1 : 0) ;
                var hsl = ColorConvert.HSBToHSL(this.color / 60, s / stops, l / 100);
                line.addColorStop(j / stops, 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)');
            }

                this.ctx.fillStyle = line;
                    this.ctx.fillRect(
                        startX,
                        this._clean((this.y - this.half) + 2 + ((i * (this.length)) / 100)),
                        this._clean(this.length + 2),
                        this._clean((this.length / 100) ) + 2
                    );
        }
    }

    updateInner(evt) {
        var offset = this.getRelativePos(this.can, evt);
        var xDiff = Math.abs(this.x - offset.x);
        var yDiff = Math.abs(this.y - offset.y);
        var dist = Math.sqrt(Math.pow(this.x - offset.x, 2) + Math.pow(this.y - offset.y, 2));
        if (dist < this.radius - this.ringsize && xDiff < this.half && yDiff < this.half - .5) {
            this.inner.css({
                left: this.can.position().left + offset.x - 2.5,
                top: this.can.position().top + offset.y - 2.5
            });
        }
    }

    updateOuter(evt) {
        var offset = this.getRelativePos(this.can, evt);
        var rawAngle = Math.atan2(offset.y - this.y, offset.x - this.x), angle = rawAngle * 180 / Math.PI;
        if (rawAngle < 0) {
            angle = 360 - (angle * -1);
        }
        this.setHue(rawAngle);
        this.color = Math.round(angle);
        this.renderInner();
    }

    getRelativePos(element, evt) {
        var parentOffset = $(element).offset();
        var eX = evt.pageX - parentOffset.left;
        var eY = evt.pageY - parentOffset.top;
        return { x: eX, y: eY };
    }
}

class ColorConvert {
    static RGBtoHSL(R, G, B) {
        var H,S,L;

        var r = R / 255;
        var g = G / 255;
        var b = B / 255;

        var cMax = Math.max(r, g, b);
        var cMin = Math.min(r, g, b);

        var dC = cMax - cMin;

        L = (cMax + cMin) / 2;

        if(cMax == cMin) {
            S = 0;
            H = 0;
        } else {
            S = L < .5 ? (cMax - cMin)/(cMax + cMin) : (cMax - cMin)/(2 - cMax - cMin);
            switch(cMax){
                case r: H = (g-b) / dC; break;
                case g: H = 2 + (b-r)/ dC; break;
                case b: H = 4 + (r - g) / dC; break;
            }
        }

        return {
            'h': Math.round(H * 60),
            's': Math.round(S * 100),
            'l': Math.round(L * 100)
        };
    }

    static HSLToHSB (H,S,L) {
        var h, s, b;
        h = H;
        b = (2 * L + S*(1 - Math.abs(2*L - 1))) / 2;

        if(b == 0) {
            return {
                'h': 0,
                's': 0,
                'b': 0
            };
        }

        s = (2 * (b - L))/b;

        return {
            'h': Math.round(h * 60),
            's': Math.round(s * 100),
            'b': Math.round(b * 100)
        };
    }

    static HSBToHSL(H,S,B) {
        var h, s, l;
        h = H;

        l = .5 * B * (2 - S);

        s = (B * S) / (1 - Math.abs(2 * l - 1));
        if((S == 0 || isNaN(s)) && B == 1) {
            return {
                'h': H * 60,
                's': 0,
                'l': 100
            };
        } else if((S == 0 || isNaN(s)) && B == 0) {
            return {
                'h': H * 60,
                's': 0,
                'l': 0
            };
        }

        return {
            'h': Math.round(h * 60),
            's': Math.round(s * 100),
            'l': Math.round(l * 100)
        };
    }

    static HexToRGB(hex) {
        hex = hex.replace('#','');
        var R = parseInt(hex.substring(0,2), 16);
        var G = parseInt(hex.substring(2,4), 16);
        var B = parseInt(hex.substring(4,6), 16);

        return { 'r': R, 'g': G, 'b': B };
    }

    //TODO: Finish
    static HSBToRGB(H,S,B) {
        var c = S * B;
        var x = c * (1 - Math.abs( H / 60) % 2 - 1)
        var m = B - c;

        var R,G,B;

    }
}<commit_msg>Added another magic number to allow #ffffff to be selected<commit_after>"use strict";

class ColorWheel {
    /**
     * Constructs the HSV colorwheel
     * @param {string} id - The id that will be given to the div holding all the elements
     * @param {Number} size - The diameter of the colorwheel
     */
    constructor(id, size) {
        this.radius = size / 2;
        this.ringsize = size / 10;
        this.color = 0;

        this.length = Math.sqrt(2 * Math.pow(this.radius - this.ringsize, 2)); //Size of the inner square
        this.half = this.length / 2;

        this.can = $('<canvas>').attr({
            width: size,
            height: size
        });
        this.ctx = this.can.get(0).getContext('2d');

        this.outer = $('<div/>').addClass('colorwheel-outer').css({
            width: this.ringsize,
            height: this.ringsize
        });
        this.inner = $('<div/>').addClass('colorwheel-inner');

        this.holder = $('<div/>').attr('id', id).append(this.outer).append(this.inner).append(this.can);
        this.x = this.y = this.radius;

        this.setHue(this.color * (Math.PI / 180));
        this.inner.css({
            left: this.can.position().left + this.x - 2.5,
            top: this.can.position().top + this.y - 2.5
        });

        this.focusOut = false, this.focusIn = false;

        this.renderOuter();
        this.renderInner();

        var _this = this;
        $(this.holder).on('mousedown', function (evt) {
            evt.preventDefault();
            var offset = _this.getRelativePos(_this.can, evt);
            var dist = Math.sqrt(Math.pow(_this.x - offset.x, 2) + Math.pow(_this.y - offset.y, 2));
            if (dist < _this.radius && dist > _this.radius - _this.ringsize) {
                _this.focusOut = true;
                _this.updateOuter(evt);
            } else if (dist < _this.radius - _this.ringsize) {
                _this.focusIn = true;
                _this.updateInner(evt);
            }
        });
        $(document).on('mouseup', function (evt) {
            _this.focusOut = _this.focusIn = false;
        }).on('mousemove', function (evt) {
            if (_this.focusOut) {
                _this.updateOuter(evt);
            } else if (_this.focusIn) {
                _this.updateInner(evt);
            }
        });
        $('body').append(this.holder);
    }

    getRGB() {
        var x = this.inner.offset().left - this.can.offset().left + 2.5;
        var y = this.inner.offset().top - this.can.offset().top + 2.5;

        var c = this.ctx.getImageData(x, y, 1, 1).data;
        return { 'r': c[0], 'g': c[1], 'b': c[2] };
    }

    getHex() {
        var rgb = this.getRGB();
        return this.toHex(rgb.r) + this.toHex(rgb.g) + this.toHex(rgb.b);
    }

    getHSL() {
        var rgb = this.getRGB();
        return ColorConvert.RGBToHSL(rgb.r, rgb.g, rgb.b);
    }

    toHex(value) {
        var hex = value.toString(16);
        return hex.length == 1 ? '0' + hex : hex;
    }

    setHue(angle) {
        this.color = angle * 60;
        var middle = this.radius - ((this.ringsize) / 2);
        this.outer.css({
            left: Math.cos(angle) * middle + this.can.position().left + this.x - (this.ringsize / 2) - 2,
            top: Math.sin(angle) * middle + this.can.position().top + this.y - (this.ringsize / 2) - 2
        });
    }

    setColor(r, g, b) {
        var hsl = ColorConvert.RGBtoHSL(r, g, b);
        var hsv = ColorConvert.HSLToHSB(hsl.h / 60, hsl.s / 100, hsl.l / 100);
        this.setHue(hsv.h / 60);
        this.renderInner();

        this.inner.css({
            left: this.x - this.half + ((this.length) * (hsv.s / 100)) - 3,
            top: this.y + this.half - ((this.length) * (hsv.b / 100)) - (hsv.b == 0 ? 2 : 0)
        });
    }

    setColorHex(hex) {
        var rgb = ColorConvert.HexToRGB(hex);
        this.setColor(rgb.r, rgb.g, rgb.b);
    }

    renderOuter() {
        for (var i = 0; i < 360; i++) {
            this.ctx.beginPath();
            this.ctx.fillStyle = 'hsl(' + i + ', 100%, 50%)';
            this.ctx.moveTo(this.x, this.y);
            this.ctx.arc(this.x, this.y, this.radius, (i - 2) * (Math.PI / 180), (i * (Math.PI / 180)), false);
            this.ctx.lineTo(this.x, this.y);
            this.ctx.fill();
        }
        //Draw white to hide the center area
        this.ctx.beginPath();
        this.ctx.fillStyle = 'white';
        this.ctx.moveTo(this.x, this.y);
        this.ctx.arc(this.x, this.y, this.radius - this.ringsize, 0, 2 * Math.PI, false);
        this.ctx.fill();
    }

    _clean(val) {
        val = Math.round(val);
        if(val % 2 != 0) {
            val -= 1;
        }
        return val;
    }

    renderInner() {
        var startX = this.x - this.half - 1;
        startX = this._clean(startX);
        for(var i = 0; i < 100; i++) {
            var line = this.ctx.createLinearGradient(
                startX,
                this._clean(this.y - this.half + (i * (this.length / 100)) ),
                this._clean(this.x + this.half + 2),
                this._clean(this.y - this.half + (i * (this.length / 100))) + 2
            );

            var stops = 15;

            for(var j = 0; j < stops; j++) {
                var s = (j == stops - 1 ? 1 : 0) + j;
                var l = 100 - i - (i == 99 ? 1 : 0) ;
                var hsl = ColorConvert.HSBToHSL(this.color / 60, s / stops, l / 100);
                line.addColorStop(j / stops, 'hsl(' + hsl.h + ',' + hsl.s + '%,' + hsl.l + '%)');
            }

                this.ctx.fillStyle = line;
                    this.ctx.fillRect(
                        startX,
                        this._clean((this.y - this.half) + 2 + ((i * (this.length)) / 100)),
                        this._clean(this.length + 2),
                        this._clean((this.length / 100) ) + 2
                    );
        }
    }

    updateInner(evt) {
        var offset = this.getRelativePos(this.can, evt);
        var xDiff = Math.abs(this.x - offset.x);
        var yDiff = Math.abs(this.y - offset.y);
        var dist = Math.sqrt(Math.pow(this.x - offset.x, 2) + Math.pow(this.y - offset.y, 2));
        if (dist < this.radius - this.ringsize && xDiff < this.half + 1 && yDiff < this.half - .5) {
            this.inner.css({
                left: this.can.position().left + offset.x - 2.5,
                top: this.can.position().top + offset.y - 2.5
            });
        }
    }

    updateOuter(evt) {
        var offset = this.getRelativePos(this.can, evt);
        var rawAngle = Math.atan2(offset.y - this.y, offset.x - this.x), angle = rawAngle * 180 / Math.PI;
        if (rawAngle < 0) {
            angle = 360 - (angle * -1);
        }
        this.setHue(rawAngle);
        this.color = Math.round(angle);
        this.renderInner();
    }

    getRelativePos(element, evt) {
        var parentOffset = $(element).offset();
        var eX = evt.pageX - parentOffset.left;
        var eY = evt.pageY - parentOffset.top;
        return { x: eX, y: eY };
    }
}

class ColorConvert {
    static RGBtoHSL(R, G, B) {
        var H,S,L;

        var r = R / 255;
        var g = G / 255;
        var b = B / 255;

        var cMax = Math.max(r, g, b);
        var cMin = Math.min(r, g, b);

        var dC = cMax - cMin;

        L = (cMax + cMin) / 2;

        if(cMax == cMin) {
            S = 0;
            H = 0;
        } else {
            S = L < .5 ? (cMax - cMin)/(cMax + cMin) : (cMax - cMin)/(2 - cMax - cMin);
            switch(cMax){
                case r: H = (g-b) / dC; break;
                case g: H = 2 + (b-r)/ dC; break;
                case b: H = 4 + (r - g) / dC; break;
            }
        }

        return {
            'h': Math.round(H * 60),
            's': Math.round(S * 100),
            'l': Math.round(L * 100)
        };
    }

    static HSLToHSB (H,S,L) {
        var h, s, b;
        h = H;
        b = (2 * L + S*(1 - Math.abs(2*L - 1))) / 2;

        if(b == 0) {
            return {
                'h': 0,
                's': 0,
                'b': 0
            };
        }

        s = (2 * (b - L))/b;

        return {
            'h': Math.round(h * 60),
            's': Math.round(s * 100),
            'b': Math.round(b * 100)
        };
    }

    static HSBToHSL(H,S,B) {
        var h, s, l;
        h = H;

        l = .5 * B * (2 - S);

        s = (B * S) / (1 - Math.abs(2 * l - 1));
        if((S == 0 || isNaN(s)) && B == 1) {
            return {
                'h': H * 60,
                's': 0,
                'l': 100
            };
        } else if((S == 0 || isNaN(s)) && B == 0) {
            return {
                'h': H * 60,
                's': 0,
                'l': 0
            };
        }

        return {
            'h': Math.round(h * 60),
            's': Math.round(s * 100),
            'l': Math.round(l * 100)
        };
    }

    static HexToRGB(hex) {
        hex = hex.replace('#','');
        var R = parseInt(hex.substring(0,2), 16);
        var G = parseInt(hex.substring(2,4), 16);
        var B = parseInt(hex.substring(4,6), 16);

        return { 'r': R, 'g': G, 'b': B };
    }

    //TODO: Finish
    static HSBToRGB(H,S,B) {
        var c = S * B;
        var x = c * (1 - Math.abs( H / 60) % 2 - 1)
        var m = B - c;

        var R,G,B;

    }
}<|endoftext|>


<commit_before>import React, { Fragment } from 'react'
import { url as apiUrl } from 'api'
import {
  Aside,
  AutoSaver,
  ConfirmClose,
  Field,
  Fieldset,
  Form,
  FormAndTableRow,
  FormWrapper,
  Submit
} from 'components/Forms'
import {
  Button,
  Container,
  Heading,
  Flex,
  LargeButton
} from '@hackclub/design-system'
import { withFormik } from 'formik'
import Link from 'gatsby-link'
import * as yup from 'yup'
import api from 'api'

export const clubApplicationSchema = yup.object().shape({
  high_school_name: yup.string().required(),
  high_school_type: yup
    .string()
    .matches(/(public_school|private_school|charter_school)/)
    .required(),
  high_school_address: yup.string().required(),
  leaders_team_origin_story: yup.string().required(),
  progress_general: yup.string().required(),
  progress_student_interest: yup.string().required(),
  progress_meeting_yet: yup.string().required(),
  idea_why: yup.string().required(),
  idea_other_coding_clubs: yup.string().required(),
  idea_other_general_clubs: yup.string().required(),
  formation_registered: yup.string().required(),
  other_surprising_or_amusing_discovery: yup.string().required(),
  point_of_contact_id: yup.number().required()
})

LargeButton.link = LargeButton.withComponent(Link)

const InnerForm = props => {
  const {
    values,
    errors,
    touched,
    handleChange,
    handleBlur,
    handleSubmit,
    isSubmitting,
    id,
    disableAutosave
  } = props
  return (
    <FormWrapper>
      <Form onSubmit={handleSubmit}>
        <Fieldset section="school">
          <Field
            name="high_school_name"
            label="Name of high school"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.high_school_name}
            error={touched.high_school_name && errors.high_school_name}
            disabled={values.submitted_at !== null}
          />
          <Field
            name="high_school_url"
            label="Link to your high school’s website, if any"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.high_school_url}
            error={touched.high_school_url && errors.high_school_url}
            disabled={values.submitted_at !== null}
            optional
          />
          <Field
            name="high_school_type"
            label="Type of school"
            type="select"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.high_school_type || 'select'}
            error={touched.high_school_type && errors.high_school_type}
            disabled={values.submitted_at !== null}
          >
            <option disabled value="select">
              Select One
            </option>
            <option value="public_school">Public school</option>
            <option value="private_school">Private school</option>
            <option value="charter_school">Charter school</option>
          </Field>
          <Field
            name="high_school_address"
            label="High school’s full address"
            hint="Please include city, state / province, country, and postal code."
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.high_school_address}
            error={touched.high_school_address && errors.high_school_address}
            type="textarea"
            disabled={values.submitted_at !== null}
          />
        </Fieldset>
        <Fieldset section="leaders">
          <Field
            name="point_of_contact_id"
            label="President / equivalent position"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.point_of_contact_id || 'select'}
            error={touched.point_of_contact_id && errors.point_of_contact_id}
            type="select"
            disabled={values.submitted_at !== null}
          >
            <option disabled value="select">
              Select One
            </option>
            {values.leader_profiles.map(profile => (
              <option value={profile.user.id} key={profile.user.id}>
                {profile.user.email}
              </option>
            ))}
          </Field>
          <Field
            name="leaders_team_origin_story"
            label="How long have you known your other club leaders and how did you meet?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leaders_team_origin_story}
            error={
              touched.leaders_team_origin_story &&
              errors.leaders_team_origin_story
            }
            type="textarea"
            disabled={values.submitted_at !== null}
          />
        </Fieldset>
        <Fieldset section="progress">
          <Field
            name="progress_general"
            label="How far along are you in starting your club?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.progress_general}
            error={touched.progress_general && errors.progress_general}
            type="textarea"
            disabled={values.submitted_at !== null}
          />
          <Field
            name="progress_student_interest"
            label="Have you already polled for interest at your school? Are students interested? If you’ve already had meetings, how many people came?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.progress_student_interest}
            error={
              touched.progress_student_interest &&
              errors.progress_student_interest
            }
            type="textarea"
            disabled={values.submitted_at !== null}
          />
          <Field
            name="progress_meeting_yet"
            label="Have you begun meeting yet?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.progress_meeting_yet}
            error={touched.progress_meeting_yet && errors.progress_meeting_yet}
            type="textarea"
            disabled={values.submitted_at !== null}
          />
        </Fieldset>
        <Fieldset section="idea">
          <Field
            name="idea_why"
            label="Why did you decide to start a Hack Club? Have you run anything like a Hack Club before? Why do you think the club is going to work?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.idea_why}
            error={touched.idea_why && errors.idea_why}
            type="textarea"
            disabled={values.submitted_at !== null}
          />
          <Field
            name="idea_other_coding_clubs"
            label="Has your school had coding clubs before? What’s going to be new about your Hack Club?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.idea_other_coding_clubs}
            error={
              touched.idea_other_coding_clubs && errors.idea_other_coding_clubs
            }
            type="textarea"
            disabled={values.submitted_at !== null}
          />
          <Field
            name="idea_other_general_clubs"
            label="What successful clubs exist at your school? What makes them successful? Why will you be just as successful, if not more, than them?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.idea_other_general_clubs}
            error={
              touched.idea_other_general_clubs &&
              errors.idea_other_general_clubs
            }
            type="textarea"
            disabled={values.submitted_at !== null}
          />
        </Fieldset>
        <Fieldset section="formation">
          <Field
            name="formation_registered"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.formation_registered}
            error={touched.formation_registered && errors.formation_registered}
            label="Have you already registered your club with your school?"
            disabled={values.submitted_at !== null}
          />
          <Field
            name="formation_misc"
            label="Please provide any other relevant information about your relationship with the school. For example, do you already have a teacher sponsor?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.formation_misc}
            error={touched.formation_misc && errors.formation_misc}
            type="textarea"
            disabled={values.submitted_at !== null}
            optional
          />
        </Fieldset>
        <Fieldset section="other">
          <Field
            name="other_surprising_or_amusing_discovery"
            label="What is something surprising or amusing you discovered?"
            hint="Doesn’t have to be about Hack Club or coding"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.other_surprising_or_amusing_discovery}
            error={
              touched.other_surprising_or_amusing_discovery &&
              errors.other_surprising_or_amusing_discovery
            }
            type="textarea"
            disabled={values.submitted_at !== null}
          />
        </Fieldset>
        <Fieldset section="curious">
          <Field
            name="curious_what_convinced"
            label="What convinced you to start a Hack Club?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.curious_what_convinced}
            error={
              touched.curious_what_convinced && errors.curious_what_convinced
            }
            type="textarea"
            disabled={values.submitted_at !== null}
            optional
          />
          <Field
            name="curious_how_did_hear"
            label="How did you hear about Hack Club? If you heard about us at an event, mention it here."
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.curious_how_did_hear}
            error={touched.curious_how_did_hear && errors.curious_how_did_hear}
            type="textarea"
            disabled={values.submitted_at !== null}
            optional
          />
        </Fieldset>
        {!disableAutosave && (
          <AutoSaver
            handleSubmit={handleSubmit}
            isSubmitting={isSubmitting}
            values={values}
          />
        )}
      </Form>
    </FormWrapper>
  )
}

const ClubApplicationForm = withFormik({
  mapPropsToValues: props => props.params,
  enableReinitialize: true,
  handleSubmit: (data, { setSubmitting, props, resetForm }) => {
    api.patch(`v1/new_club_applications/${props.id}`, { data })
      .then(json => {
        setSubmitting(false)
      })
      .catch(e => {
        console.error(e)
        alert(e)
        setSubmitting(false)
      })
  },
  displayName: 'ClubApplicationForm'
})(InnerForm)

export default ClubApplicationForm
<commit_msg>Add punctuation<commit_after>import React, { Fragment } from 'react'
import { url as apiUrl } from 'api'
import {
  Aside,
  AutoSaver,
  ConfirmClose,
  Field,
  Fieldset,
  Form,
  FormAndTableRow,
  FormWrapper,
  Submit
} from 'components/Forms'
import {
  Button,
  Container,
  Heading,
  Flex,
  LargeButton
} from '@hackclub/design-system'
import { withFormik } from 'formik'
import Link from 'gatsby-link'
import * as yup from 'yup'
import api from 'api'

export const clubApplicationSchema = yup.object().shape({
  high_school_name: yup.string().required(),
  high_school_type: yup
    .string()
    .matches(/(public_school|private_school|charter_school)/)
    .required(),
  high_school_address: yup.string().required(),
  leaders_team_origin_story: yup.string().required(),
  progress_general: yup.string().required(),
  progress_student_interest: yup.string().required(),
  progress_meeting_yet: yup.string().required(),
  idea_why: yup.string().required(),
  idea_other_coding_clubs: yup.string().required(),
  idea_other_general_clubs: yup.string().required(),
  formation_registered: yup.string().required(),
  other_surprising_or_amusing_discovery: yup.string().required(),
  point_of_contact_id: yup.number().required()
})

LargeButton.link = LargeButton.withComponent(Link)

const InnerForm = props => {
  const {
    values,
    errors,
    touched,
    handleChange,
    handleBlur,
    handleSubmit,
    isSubmitting,
    id,
    disableAutosave
  } = props
  return (
    <FormWrapper>
      <Form onSubmit={handleSubmit}>
        <Fieldset section="school">
          <Field
            name="high_school_name"
            label="Name of high school"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.high_school_name}
            error={touched.high_school_name && errors.high_school_name}
            disabled={values.submitted_at !== null}
          />
          <Field
            name="high_school_url"
            label="Link to your high school’s website, if any"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.high_school_url}
            error={touched.high_school_url && errors.high_school_url}
            disabled={values.submitted_at !== null}
            optional
          />
          <Field
            name="high_school_type"
            label="Type of school"
            type="select"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.high_school_type || 'select'}
            error={touched.high_school_type && errors.high_school_type}
            disabled={values.submitted_at !== null}
          >
            <option disabled value="select">
              Select One
            </option>
            <option value="public_school">Public school</option>
            <option value="private_school">Private school</option>
            <option value="charter_school">Charter school</option>
          </Field>
          <Field
            name="high_school_address"
            label="High school’s full address"
            hint="Please include city, state / province, country, and postal code."
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.high_school_address}
            error={touched.high_school_address && errors.high_school_address}
            type="textarea"
            disabled={values.submitted_at !== null}
          />
        </Fieldset>
        <Fieldset section="leaders">
          <Field
            name="point_of_contact_id"
            label="President / equivalent position"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.point_of_contact_id || 'select'}
            error={touched.point_of_contact_id && errors.point_of_contact_id}
            type="select"
            disabled={values.submitted_at !== null}
          >
            <option disabled value="select">
              Select One
            </option>
            {values.leader_profiles.map(profile => (
              <option value={profile.user.id} key={profile.user.id}>
                {profile.user.email}
              </option>
            ))}
          </Field>
          <Field
            name="leaders_team_origin_story"
            label="How long have you known your other club leaders and how did you meet?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.leaders_team_origin_story}
            error={
              touched.leaders_team_origin_story &&
              errors.leaders_team_origin_story
            }
            type="textarea"
            disabled={values.submitted_at !== null}
          />
        </Fieldset>
        <Fieldset section="progress">
          <Field
            name="progress_general"
            label="How far along are you in starting your club?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.progress_general}
            error={touched.progress_general && errors.progress_general}
            type="textarea"
            disabled={values.submitted_at !== null}
          />
          <Field
            name="progress_student_interest"
            label="Have you already polled for interest at your school? Are students interested? If you’ve already had meetings, how many people came?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.progress_student_interest}
            error={
              touched.progress_student_interest &&
              errors.progress_student_interest
            }
            type="textarea"
            disabled={values.submitted_at !== null}
          />
          <Field
            name="progress_meeting_yet"
            label="Have you begun meeting yet?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.progress_meeting_yet}
            error={touched.progress_meeting_yet && errors.progress_meeting_yet}
            type="textarea"
            disabled={values.submitted_at !== null}
          />
        </Fieldset>
        <Fieldset section="idea">
          <Field
            name="idea_why"
            label="Why did you decide to start a Hack Club? Have you run anything like a Hack Club before? Why do you think the club is going to work?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.idea_why}
            error={touched.idea_why && errors.idea_why}
            type="textarea"
            disabled={values.submitted_at !== null}
          />
          <Field
            name="idea_other_coding_clubs"
            label="Has your school had coding clubs before? What’s going to be new about your Hack Club?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.idea_other_coding_clubs}
            error={
              touched.idea_other_coding_clubs && errors.idea_other_coding_clubs
            }
            type="textarea"
            disabled={values.submitted_at !== null}
          />
          <Field
            name="idea_other_general_clubs"
            label="What successful clubs exist at your school? What makes them successful? Why will you be just as successful, if not more, than them?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.idea_other_general_clubs}
            error={
              touched.idea_other_general_clubs &&
              errors.idea_other_general_clubs
            }
            type="textarea"
            disabled={values.submitted_at !== null}
          />
        </Fieldset>
        <Fieldset section="formation">
          <Field
            name="formation_registered"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.formation_registered}
            error={touched.formation_registered && errors.formation_registered}
            label="Have you already registered your club with your school?"
            disabled={values.submitted_at !== null}
          />
          <Field
            name="formation_misc"
            label="Please provide any other relevant information about your relationship with the school. For example, do you already have a teacher sponsor?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.formation_misc}
            error={touched.formation_misc && errors.formation_misc}
            type="textarea"
            disabled={values.submitted_at !== null}
            optional
          />
        </Fieldset>
        <Fieldset section="other">
          <Field
            name="other_surprising_or_amusing_discovery"
            label="What is something surprising or amusing you discovered?"
            hint="Doesn’t have to be about Hack Club or coding."
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.other_surprising_or_amusing_discovery}
            error={
              touched.other_surprising_or_amusing_discovery &&
              errors.other_surprising_or_amusing_discovery
            }
            type="textarea"
            disabled={values.submitted_at !== null}
          />
        </Fieldset>
        <Fieldset section="curious">
          <Field
            name="curious_what_convinced"
            label="What convinced you to start a Hack Club?"
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.curious_what_convinced}
            error={
              touched.curious_what_convinced && errors.curious_what_convinced
            }
            type="textarea"
            disabled={values.submitted_at !== null}
            optional
          />
          <Field
            name="curious_how_did_hear"
            label="How did you hear about Hack Club? If you heard about us at an event, mention it here."
            onChange={handleChange}
            onBlur={handleBlur}
            value={values.curious_how_did_hear}
            error={touched.curious_how_did_hear && errors.curious_how_did_hear}
            type="textarea"
            disabled={values.submitted_at !== null}
            optional
          />
        </Fieldset>
        {!disableAutosave && (
          <AutoSaver
            handleSubmit={handleSubmit}
            isSubmitting={isSubmitting}
            values={values}
          />
        )}
      </Form>
    </FormWrapper>
  )
}

const ClubApplicationForm = withFormik({
  mapPropsToValues: props => props.params,
  enableReinitialize: true,
  handleSubmit: (data, { setSubmitting, props, resetForm }) => {
    api.patch(`v1/new_club_applications/${props.id}`, { data })
      .then(json => {
        setSubmitting(false)
      })
      .catch(e => {
        console.error(e)
        alert(e)
        setSubmitting(false)
      })
  },
  displayName: 'ClubApplicationForm'
})(InnerForm)

export default ClubApplicationForm
<|endoftext|>


<commit_before>if(!Draw) {
  var CENTER = "CENTER";
  var CORNER = "CORNER";
  var RADIUS = "RADIUS";
  var CORNERS = "CORNERS";

  var Draw = {
    currentRectMode: "CORNER",
    currentImageMode: "CORNER",
    currentEllipseMode: "CENTER",

    shapeOpen: false,
  };
}
<commit_msg>Update init.js<commit_after>if(!Draw || KAPhy.version !== KAPhy.current) {
  var CENTER = "CENTER";
  var CORNER = "CORNER";
  var RADIUS = "RADIUS";
  var CORNERS = "CORNERS";

  var MITER = "miter";
  var ROUND = "round";
  var BEVEL = "bevel";

  var Draw = {
    currentRectMode: "CORNER",
    currentImageMode: "CORNER",
    currentEllipseMode: "CENTER",

    shapeOpen: false,
  };
}
<|endoftext|>


<commit_before>'use strict';

angular.module('schedulerApp.controller.task-edit', [
  'ngRoute',
  'ngResource',
  'schedulerApp.db',
])
.controller('TaskEdit', ['$scope', '$location', 'db', '$routeParams', function($scope, $location, db, $routeParams) {

	$scope.actionModels = {};
	$scope.isDescriptionFrozen = false
	$scope.repeatDaily = true

	$scope.duration = ''

	$scope.thingToModel = function(thing) {
		var result = {}
		result.id = thing.id
		result.description = thing.name
		var room = db.rooms[thing.location]
		if (!room) {
			return null
		}
		result.room = room.name
		result.on = "true"
		return result
	}

	$scope.formatTime = function (date, ui) {
	    var h = date.getHours();
	    var m = date.getMinutes();
	    var s = date.getSeconds();
	    var pad = function(d) { return d <= 9 ? '0'+d : d }
	    return ''+pad(h)+":"+pad(m)+(s != 0 || !ui ?  ":"+pad(s) : "")
	}

	$scope.formatDate = function (date) {
	    var y = date.getFullYear();
	    var m = date.getMonth()+1;
	    var d = date.getDate();
	    var pad = function(d) { return d <= 9 ? '0'+d : d }
	    return ''+y+"-"+pad(m)+"-"+pad(d)
	}

	$scope.actionToModel = function(action) {
	    // {
        //    "action" : "turnOn",
        //    "thingID" : "94dc7d1a-aa67-11e4-803a-7c669d02a706",
        //     "type" : "thing-action"
        // }
        //
        // ==>
        //
	    // {
	    //	  "id": thing-id
        //    "description" : "thing description",
        //	  "room": "room description"
        //	  "on": true
        // }
        //

		var result = {}
		switch (action["action"]) {
		case "turnOn":
			result.on = "true"
			break
		case "turnOff":
			result.on = "false"
			break
		default:
			console.debug("bad action ", action)
			return null
		}

		if (action.type != "thing-action") {
			console.debug("bad type ", action)
			return null
		}

		if (!action.thingID) {
			console.debug("missing thing id", action)
			return null
		}

		result.id = action.thingID
		var thing = db.things[result.id]
		if (!thing) {
			console.debug("invalid thing id", result.id)
			return null
		}
		result.description = thing.name
		var room = db.rooms[thing.location]
		if (!room) {
			console.debug("invalid room id", thing.location)
			return null
		}
		result.room = room.name
		result.selected = true

		return result
	}

	$scope.task = function() {
		return db.tasks[$routeParams["id"]]
	}

	$scope.timestamp = function(ts) {
		var
			now = new Date(),
			ts = new Date($scope.formatDate(now)+" "+(ts ? ts : $scope.timeOfDay))
			if (ts.getFullYear() && ts < now) {
				ts.setDate(ts.getDate()+1)
			}
			return ts
	}

	$scope.save = function() {
		$scope.message = ""
		var rule, param

		switch ($scope.timeOfDay) {
		case "dawn":
		case "dusk":
		case "sunrise":
		case "sunset":
			rule = $scope.timeOfDay
			param = ""
			break
		default:
			var
				ts = $scope.timestamp()

			if (!ts.getFullYear()) {
				$scope.message = "enter a time of the form hh:mm:dd"
				return
			}

			if ($scope.repeatDaily) {
				rule = "time-of-day"
				param = $scope.formatTime(ts, false)
			} else {
				rule = "timestamp"
				param = $scope.formatDate(ts) + " " + $scope.formatTime(ts, false)
			}
			break
		}

		var desc = (($scope.description == '') ? '@ '+$scope.timeOfDay : $scope.description )

		var actions = (function() {
			var
				open=[],
				close=[]
			angular.forEach($scope.actionModels, function(m) {
				if (m.selected) {
					var obj = {
							"type": "thing-action",
							"action": (m.on == "true" ? "turnOn" : "turnOff"),
							"thingID": m.id
						}
					open.push(obj)
					obj = angular.copy(obj)
					obj.action = (m.on != "true" ? "turnOn" : "turnOff")
					close.push(obj)
				}
			})
			return [open,close]
		}())

		var
			beforeParam

		if ($scope.duration == '') {
			beforeParam = "00:01:00"
			actions[1] = []
		} else {
			beforeParam = $scope.duration
		}

		var task = {
			"id": $routeParams["id"],
			"description": desc,
			"tags": ["simple-ui"],
			"open": actions[0],
			"close": actions[1],
			"window": {
				"after": {
					"rule": rule,
					"param": param
				},
				"before": {
					"rule": "delay",
					"param": beforeParam
				}
			}
		}

		db.save(task).then(
			function() {
				$location.path('/list')
			}, function(m) {
				if (m && m.data) {
					$scope.message = m.data
				} else {
					$scope.message = "An error occurred."
				}
				console.debug(m)
			})
	}

	$scope.delete = function() {
		db.delete($routeParams["id"]).then(
			function() {
				$location.path('/list')
			}, function(m) {
				if (m && m.data) {
					$scope.message = m.data
				} else {
					$scope.message = "An error occurred."
				}
				console.debug(m)
			})
	}

	$scope.cancel = function() {
		$location.path('/list')
	}

	$scope.freezeDescription = function() {
		$scope.isDescriptionFrozen = true
	}

	$scope.toggleSelect = function(model) {
		model.selected = !model.selected
	}

	$scope.toggleActionState = function(model) {
		model.on = ! model.on
	}

	$scope.setRepeatDaily = function(value) {
		$scope.repeatDaily = value;
	}

	$scope.$watch('task()', function(task) {
		angular.forEach(db.things, function(t) {
			var m = $scope.thingToModel(t)
			if (m) {
				$scope.actionModels[t["id"]] = m
			}
		})

		$scope.isDescriptionFrozen = false
		$scope.timeOfDay = $scope.formatTime(new Date(new Date().valueOf()+(60*1000))).substring(0,5)
		$scope.description = '@ '+$scope.timeOfDay
		$scope.repeatDaily = true

		if (!task) {
			// console.debug("new task", $scope)
			return
		}

		$scope.isDescriptionFrozen = true
		$scope.description = task.description

		angular.forEach(task.open, function(action) {
			var model = $scope.actionToModel(action)
			if (model && $scope.actionModels[model.id]) {
				$scope.actionModels[model.id] = model
			} else {
				console.debug("found an action for a thing that no longer exists: ", action)
			}
		})

		if (!task.window || !task.window.before || task.window.before.rule != 'delay') {
			console.debug("invalid before rule", task)
			return
		}

		console.debug(task)
		if (task.close && task.close.length != 0) {
			$scope.duration = task.window.before.param
		}

		switch (task.window.after.rule) {
		case "sunrise":
		case "sunset":
		case "dawn":
		case "dusk":
			$scope.timeOfDay = task.window.after.rule
			break;
		case "time-of-day":
			$scope.timeOfDay = $scope.formatTime($scope.timestamp(task.window.after.param), true)
			break;
		case "timestamp":
			var ts = new Date(task.window.after.param)
			if (ts.getFullYear()) {
				$scope.timeOfDay = $scope.formatTime(ts, true)
				$scope.repeatDaily = false
			}
			break;
		default:
			console.debug("can't edit rule of type: ", task.window.after.rule)
			return
		}

		// the description is frozen iff the generated description does not match the saved description
		$scope.isDescriptionFrozen = ($scope.description != '') && ($scope.description != $scope.generatedDescription())

		// console.debug("loaded task", $scope)

	})

	$scope.generatedDescription = function() {
		var
			base = '@ '+$scope.timeOfDay,
			ts = $scope.timestamp(),
			now = new Date()

		if (!$scope.repeatDaily && ts.getFullYear()) {
			if ($scope.formatDate(now) == $scope.formatDate($scope.timestamp())) {
				return base + ' today'
			} else {
				return base + ' tomorrow'
			}
		} else {
			return base
		}
	}

	$scope.$watch('timeOfDay+repeatDaily', function() {
		if (!$scope.isDescriptionFrozen) {
			$scope.description = $scope.generatedDescription()
		}
	});

}])

<commit_msg>Don't attempt to parse '-' in a date string - use '/' instead.<commit_after>'use strict';

angular.module('schedulerApp.controller.task-edit', [
  'ngRoute',
  'ngResource',
  'schedulerApp.db',
])
.controller('TaskEdit', ['$scope', '$location', 'db', '$routeParams', function($scope, $location, db, $routeParams) {

	$scope.actionModels = {};
	$scope.isDescriptionFrozen = false
	$scope.repeatDaily = true

	$scope.duration = ''

	$scope.thingToModel = function(thing) {
		var result = {}
		result.id = thing.id
		result.description = thing.name
		var room = db.rooms[thing.location]
		if (!room) {
			return null
		}
		result.room = room.name
		result.on = "true"
		return result
	}

	$scope.formatTime = function (date, ui) {
	    var h = date.getHours();
	    var m = date.getMinutes();
	    var s = date.getSeconds();
	    var pad = function(d) { return d <= 9 ? '0'+d : d }
	    return ''+pad(h)+":"+pad(m)+(s != 0 || !ui ?  ":"+pad(s) : "")
	}

	$scope.formatDate = function (date) {
	    var y = date.getFullYear();
	    var m = date.getMonth()+1;
	    var d = date.getDate();
	    var pad = function(d) { return d <= 9 ? '0'+d : d }
	    return ''+y+"-"+pad(m)+"-"+pad(d)
	}

	$scope.actionToModel = function(action) {
	    // {
        //    "action" : "turnOn",
        //    "thingID" : "94dc7d1a-aa67-11e4-803a-7c669d02a706",
        //     "type" : "thing-action"
        // }
        //
        // ==>
        //
	    // {
	    //	  "id": thing-id
        //    "description" : "thing description",
        //	  "room": "room description"
        //	  "on": true
        // }
        //

		var result = {}
		switch (action["action"]) {
		case "turnOn":
			result.on = "true"
			break
		case "turnOff":
			result.on = "false"
			break
		default:
			console.debug("bad action ", action)
			return null
		}

		if (action.type != "thing-action") {
			console.debug("bad type ", action)
			return null
		}

		if (!action.thingID) {
			console.debug("missing thing id", action)
			return null
		}

		result.id = action.thingID
		var thing = db.things[result.id]
		if (!thing) {
			console.debug("invalid thing id", result.id)
			return null
		}
		result.description = thing.name
		var room = db.rooms[thing.location]
		if (!room) {
			console.debug("invalid room id", thing.location)
			return null
		}
		result.room = room.name
		result.selected = true

		return result
	}

	$scope.task = function() {
		return db.tasks[$routeParams["id"]]
	}

	$scope.timestamp = function(ts) {
		var
			now = new Date(),
			ts = new Date($scope.formatDate(now).replace(/-/g, '/')+" "+(ts ? ts : $scope.timeOfDay))
			if (ts.getFullYear() && ts < now) {
				ts.setDate(ts.getDate()+1)
			}
			return ts
	}

	$scope.save = function() {
		$scope.message = ""
		var rule, param

		switch ($scope.timeOfDay) {
		case "dawn":
		case "dusk":
		case "sunrise":
		case "sunset":
			rule = $scope.timeOfDay
			param = ""
			break
		default:
			var
				ts = $scope.timestamp()

			if (!ts.getFullYear()) {
				$scope.message = "enter a time of the form hh:mm:dd"
				return
			}

			if ($scope.repeatDaily) {
				rule = "time-of-day"
				param = $scope.formatTime(ts, false)
			} else {
				rule = "timestamp"
				param = $scope.formatDate(ts) + " " + $scope.formatTime(ts, false)
			}
			break
		}

		var desc = (($scope.description == '') ? '@ '+$scope.timeOfDay : $scope.description )

		var actions = (function() {
			var
				open=[],
				close=[]
			angular.forEach($scope.actionModels, function(m) {
				if (m.selected) {
					var obj = {
							"type": "thing-action",
							"action": (m.on == "true" ? "turnOn" : "turnOff"),
							"thingID": m.id
						}
					open.push(obj)
					obj = angular.copy(obj)
					obj.action = (m.on != "true" ? "turnOn" : "turnOff")
					close.push(obj)
				}
			})
			return [open,close]
		}())

		var
			beforeParam

		if ($scope.duration == '') {
			beforeParam = "00:01:00"
			actions[1] = []
		} else {
			beforeParam = $scope.duration
		}

		var task = {
			"id": $routeParams["id"],
			"description": desc,
			"tags": ["simple-ui"],
			"open": actions[0],
			"close": actions[1],
			"window": {
				"after": {
					"rule": rule,
					"param": param
				},
				"before": {
					"rule": "delay",
					"param": beforeParam
				}
			}
		}

		db.save(task).then(
			function() {
				$location.path('/list')
			}, function(m) {
				if (m && m.data) {
					$scope.message = m.data
				} else {
					$scope.message = "An error occurred."
				}
				console.debug(m)
			})
	}

	$scope.delete = function() {
		db.delete($routeParams["id"]).then(
			function() {
				$location.path('/list')
			}, function(m) {
				if (m && m.data) {
					$scope.message = m.data
				} else {
					$scope.message = "An error occurred."
				}
				console.debug(m)
			})
	}

	$scope.cancel = function() {
		$location.path('/list')
	}

	$scope.freezeDescription = function() {
		$scope.isDescriptionFrozen = true
	}

	$scope.toggleSelect = function(model) {
		model.selected = !model.selected
	}

	$scope.toggleActionState = function(model) {
		model.on = ! model.on
	}

	$scope.setRepeatDaily = function(value) {
		$scope.repeatDaily = value;
	}

	$scope.$watch('task()', function(task) {
		angular.forEach(db.things, function(t) {
			var m = $scope.thingToModel(t)
			if (m) {
				$scope.actionModels[t["id"]] = m
			}
		})

		$scope.isDescriptionFrozen = false
		$scope.timeOfDay = $scope.formatTime(new Date(new Date().valueOf()+(60*1000))).substring(0,5)
		$scope.description = '@ '+$scope.timeOfDay
		$scope.repeatDaily = true

		if (!task) {
			// console.debug("new task", $scope)
			return
		}

		$scope.isDescriptionFrozen = true
		$scope.description = task.description

		angular.forEach(task.open, function(action) {
			var model = $scope.actionToModel(action)
			if (model && $scope.actionModels[model.id]) {
				$scope.actionModels[model.id] = model
			} else {
				console.debug("found an action for a thing that no longer exists: ", action)
			}
		})

		if (!task.window || !task.window.before || task.window.before.rule != 'delay') {
			console.debug("invalid before rule", task)
			return
		}

		console.debug(task)
		if (task.close && task.close.length != 0) {
			$scope.duration = task.window.before.param
		}

		switch (task.window.after.rule) {
		case "sunrise":
		case "sunset":
		case "dawn":
		case "dusk":
			$scope.timeOfDay = task.window.after.rule
			break;
		case "time-of-day":
			$scope.timeOfDay = $scope.formatTime($scope.timestamp(task.window.after.param), true)
			break;
		case "timestamp":
			var ts = new Date(task.window.after.param)
			if (ts.getFullYear()) {
				$scope.timeOfDay = $scope.formatTime(ts, true)
				$scope.repeatDaily = false
			}
			break;
		default:
			console.debug("can't edit rule of type: ", task.window.after.rule)
			return
		}

		// the description is frozen iff the generated description does not match the saved description
		$scope.isDescriptionFrozen = ($scope.description != '') && ($scope.description != $scope.generatedDescription())

		// console.debug("loaded task", $scope)

	})

	$scope.generatedDescription = function() {
		var
			base = '@ '+$scope.timeOfDay,
			ts = $scope.timestamp(),
			now = new Date()

		if (!$scope.repeatDaily && ts.getFullYear()) {
			if ($scope.formatDate(now) == $scope.formatDate($scope.timestamp())) {
				return base + ' today'
			} else {
				return base + ' tomorrow'
			}
		} else {
			return base
		}
	}

	$scope.$watch('timeOfDay+repeatDaily', function() {
		if (!$scope.isDescriptionFrozen) {
			$scope.description = $scope.generatedDescription()
		}
	});

}])

<|endoftext|>