<commit_before>workersActions = {

    maybeHarvest: function(creep) {
        if(creep.memory.state != 'harvesting' && creep.carry.energy == 0) {
            creep.memory.state = 'harvesting';
        }
    },

    harvest: function(creep) {
        if(creep.memory.state == 'harvesting' && creep.carry.energy == creep.carryCapacity) {
            _.pull(Memory.energySources[creep.memory.targetEnergy], creep.name);
            creep.memory.targetEnergy = null;
            creep.memory.state = 'deciding';
        }
        if(creep.memory.state == 'harvesting') {
            if(!('targetEnergy' in creep.memory) || creep.memory.targetEnergy == null) {
                workersActions.selectResource(creep);
            }
            var source = Game.getObjectById(creep.memory.targetEnergy);
            if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
                console.log(creep.name + ' moving to source ' + source)
                creep.moveTo(source);
            }
        }
    },

    selectResource: function(creep) {

        // initialize the global registration if it has not been already
        if(!('energySources' in Memory)) {
            Memory.energySources = {};
            sources = creep.room.find(FIND_SOURCES);
            for (var i=0; i < sources.length; i++) {
                Memory.energySources[sources[i].id] = [];
            }
        }

        // pick by two criteria, the one with least users or in the case of a tie closest
        var lowestCount = Infinity;
        var lowestSources = [];
        for (var source in Memory.energySources) {
            var currentLength = Memory.energySources[source].length;
            if(currentLength < lowestCount) {
                lowestCount = currentLength;
                lowestSources = [source];
            } else if(currentLength == lowestCount) {
                lowestSources.push(source)
            }
        }

        // register the creep on the source
        if(lowestSources.length == 1) {
            var source = lowestSources[0];
            Memory.energySources[source].push(creep.name)
            creep.memory.targetEnergy = source;
            return source;
        } else {
            // todo : replace this random decision with picking the closest
            var source = _.shuffle(lowestSources)[0];
            Memory.energySources[source].push(creep.name)
            creep.memory.targetEnergy = source;
            return source;
        }

    },

    upgrade: function(creep) {
        if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
            creep.moveTo(creep.room.controller);
        }
    },

    build: function(creep) {
        var targets = creep.room.find(FIND_CONSTRUCTION_SITES);
        if(targets.length) {
            if(creep.build(targets[0]) == ERR_NOT_IN_RANGE) {
                creep.moveTo(targets[0]);
            }
        } else {
            creep.memory.state = 'deciding';
        }
    },

    store: function(creep) {
        var targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return (structure.structureType == STRUCTURE_EXTENSION ||
                    structure.structureType == STRUCTURE_SPAWN ||
                    structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
            }
        });
        if(targets.length > 0) {
            if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                creep.moveTo(targets[0]);
            }
        } else {
            creep.memory.state = 'deciding';
        }
    }
};

module.exports = workersActions;
<commit_msg>removing noisy log<commit_after>workersActions = {

    maybeHarvest: function(creep) {
        if(creep.memory.state != 'harvesting' && creep.carry.energy == 0) {
            creep.memory.state = 'harvesting';
        }
    },

    harvest: function(creep) {
        if(creep.memory.state == 'harvesting' && creep.carry.energy == creep.carryCapacity) {
            _.pull(Memory.energySources[creep.memory.targetEnergy], creep.name);
            creep.memory.targetEnergy = null;
            creep.memory.state = 'deciding';
        }
        if(creep.memory.state == 'harvesting') {
            if(!('targetEnergy' in creep.memory) || creep.memory.targetEnergy == null) {
                workersActions.selectResource(creep);
            }
            var source = Game.getObjectById(creep.memory.targetEnergy);
            if(creep.harvest(source) == ERR_NOT_IN_RANGE) {
                creep.moveTo(source);
            }
        }
    },

    selectResource: function(creep) {

        // initialize the global registration if it has not been already
        if(!('energySources' in Memory)) {
            Memory.energySources = {};
            sources = creep.room.find(FIND_SOURCES);
            for (var i=0; i < sources.length; i++) {
                Memory.energySources[sources[i].id] = [];
            }
        }

        // pick by two criteria, the one with least users or in the case of a tie closest
        var lowestCount = Infinity;
        var lowestSources = [];
        for (var source in Memory.energySources) {
            var currentLength = Memory.energySources[source].length;
            if(currentLength < lowestCount) {
                lowestCount = currentLength;
                lowestSources = [source];
            } else if(currentLength == lowestCount) {
                lowestSources.push(source)
            }
        }

        // register the creep on the source
        if(lowestSources.length == 1) {
            var source = lowestSources[0];
            Memory.energySources[source].push(creep.name)
            creep.memory.targetEnergy = source;
            return source;
        } else {
            // todo : replace this random decision with picking the closest
            var source = _.shuffle(lowestSources)[0];
            Memory.energySources[source].push(creep.name)
            creep.memory.targetEnergy = source;
            return source;
        }

    },

    upgrade: function(creep) {
        if(creep.upgradeController(creep.room.controller) == ERR_NOT_IN_RANGE) {
            creep.moveTo(creep.room.controller);
        }
    },

    build: function(creep) {
        var targets = creep.room.find(FIND_CONSTRUCTION_SITES);
        if(targets.length) {
            if(creep.build(targets[0]) == ERR_NOT_IN_RANGE) {
                creep.moveTo(targets[0]);
            }
        } else {
            creep.memory.state = 'deciding';
        }
    },

    store: function(creep) {
        var targets = creep.room.find(FIND_STRUCTURES, {
            filter: (structure) => {
                return (structure.structureType == STRUCTURE_EXTENSION ||
                    structure.structureType == STRUCTURE_SPAWN ||
                    structure.structureType == STRUCTURE_TOWER) && structure.energy < structure.energyCapacity;
            }
        });
        if(targets.length > 0) {
            if(creep.transfer(targets[0], RESOURCE_ENERGY) == ERR_NOT_IN_RANGE) {
                creep.moveTo(targets[0]);
            }
        } else {
            creep.memory.state = 'deciding';
        }
    }
};

module.exports = workersActions;
<|endoftext|>


<commit_before>var _ = require('lodash'),
    async = require('async'),
    sdk = require('postman-collection'),

    // we need to access tough-cookie if no external cookie jar is provided. however, the `request` module does not work
    // with vanilla tough-cookie and needs a flavour of tough-cookie returned by itself. Hence we depend on
    // `postman-request` here.
    postmanRequest = require('postman-request'),

    helpers = require('../pre'),

    Requester = require('../../requester').Requester;

module.exports = {
    init: function (done) {
        var timeout = _.min([
                _.get(this.options, 'timeout.request'),
                _.get(this.options, 'timeout.global')
            ]),
            cookieJar;

        // @todo - remove this when requester creation is offloaded to runner
        if (this.options.requester && this.options.requester.external === true) {
            this.requester = this.options.requester.instance;
            // Just so we don't break the App, pull the file resolver out of the requester
            this.options.fileResolver = _.get(this.requester, 'fileResolver');
            return done();
        }

        !_.isFinite(timeout) && (timeout = undefined);
        cookieJar = _.get(this.options, 'requester.cookieJar');
        if (!cookieJar) {
            cookieJar = postmanRequest.jar();
        }

        // @todo: get requester options and maybe store per-protocol requester
        !this.requester && (this.requester = new Requester(_.merge(this.options.requester || {}, {
            timeout: timeout || undefined,
            cookieJar: cookieJar || undefined
        })));

        done();
    },

    triggers: ['beforeRequest', 'request'],

    process: {
        /**
         * @param {Object} payload
         * @param {Item} payload.item
         * @param {Object} payload.data
         * @param {VariableScope} payload.globals
         * @param {VariableScope} payload.environment
         * @param {Cursor} payload.coords
         * @param {Function} next
         *
         * @todo  validate payload
         */
        request: function (payload, next) {
            var abortOnError = _.has(payload, 'abortOnError') ? payload.abortOnError : this.options.abortOnError,
                self = this;

            async.waterfall([
                // Run the helper functions
                // todo - move this to the right place
                function (cb) {
                    async.series(
                        _.invokeMap(helpers, Function.prototype.bind, self, payload),
                        function (err) { // swallow up the second argument here
                            cb(err);
                        }
                    );
                },
                // Send the request
                function (cb) {
                    var xhr,
                        item,
                        aborted;

                    item = payload.item;

                    // Trigger the beforeRequest callback
                    // todo: ensure that the correct item and other params are bubbled up
                    self.triggers.beforeRequest(null, payload.coords, item.request, payload.item, {
                        abort: function () {
                            !aborted && xhr && xhr.abort();
                            aborted = true;
                        }
                    });

                    if (aborted) {
                        return cb(new Error('runtime: request aborted'));
                    }

                    xhr = self.requester.request(item, cb, self);
                }
            ], function (err, legacyResponse, legacyRequest, response) {
                err = err || null;

                var item = payload.item;

                // todo: ensure that the correct item and other params are bubbled up
                this.triggers.request(err, payload.coords, new sdk.Response(response),
                    item.request, payload.item,
                    // todo: remove these asap
                    legacyResponse, legacyRequest);

                next((err && abortOnError) ? err : null, {
                    response: response,
                    request: item.request,
                    legacyResponse: legacyResponse,
                    legacyRequest: legacyRequest
                }, err);
            }.bind(this));
        }
    }
};
<commit_msg>added a comment<commit_after>var _ = require('lodash'),
    async = require('async'),
    sdk = require('postman-collection'),

    // we need to access tough-cookie if no external cookie jar is provided. however, the `request` module does not work
    // with vanilla tough-cookie and needs a flavour of tough-cookie returned by itself. Hence we depend on
    // `postman-request` here.
    postmanRequest = require('postman-request'),

    helpers = require('../pre'),

    Requester = require('../../requester').Requester;

module.exports = {
    init: function (done) {
        var timeout = _.min([
                _.get(this.options, 'timeout.request'),
                _.get(this.options, 'timeout.global')
            ]),
            cookieJar;

        // @todo - remove this when requester creation is offloaded to runner
        if (this.options.requester && this.options.requester.external === true) {
            this.requester = this.options.requester.instance;
            // Just so we don't break the App, pull the file resolver out of the requester
            this.options.fileResolver = _.get(this.requester, 'fileResolver');
            return done();
        }

        !_.isFinite(timeout) && (timeout = undefined);
        cookieJar = _.get(this.options, 'requester.cookieJar');
        if (!cookieJar) {
            cookieJar = postmanRequest.jar();
        }

        // @todo: get requester options and maybe store per-protocol requester
        !this.requester && (this.requester = new Requester(_.merge(this.options.requester || {}, {
            timeout: timeout || undefined,
            cookieJar: cookieJar || undefined
        })));

        done();
    },

    triggers: ['beforeRequest', 'request'],

    process: {
        /**
         * @param {Object} payload
         * @param {Item} payload.item
         * @param {Object} payload.data
         * @param {VariableScope} payload.globals
         * @param {VariableScope} payload.environment
         * @param {Cursor} payload.coords
         * @param {Function} next
         *
         * @todo  validate payload
         */
        request: function (payload, next) {
            var abortOnError = _.has(payload, 'abortOnError') ? payload.abortOnError : this.options.abortOnError,
                self = this;

            async.waterfall([
                // Run the helper functions
                // todo - move this to the right place
                function (cb) {
                    async.series(
                        // binds each helper to self, and adds a default first parameter of "payload"
                        // todo - update eslint to not groan if we don't use invokeMap.
                        _.invokeMap(helpers, Function.prototype.bind, self, payload),
                        function (err) { // swallow up the second argument here
                            cb(err);
                        }
                    );
                },
                // Send the request
                function (cb) {
                    var xhr,
                        item,
                        aborted;

                    item = payload.item;

                    // Trigger the beforeRequest callback
                    // todo: ensure that the correct item and other params are bubbled up
                    self.triggers.beforeRequest(null, payload.coords, item.request, payload.item, {
                        abort: function () {
                            !aborted && xhr && xhr.abort();
                            aborted = true;
                        }
                    });

                    if (aborted) {
                        return cb(new Error('runtime: request aborted'));
                    }

                    xhr = self.requester.request(item, cb, self);
                }
            ], function (err, legacyResponse, legacyRequest, response) {
                err = err || null;

                var item = payload.item;

                // todo: ensure that the correct item and other params are bubbled up
                this.triggers.request(err, payload.coords, new sdk.Response(response),
                    item.request, payload.item,
                    // todo: remove these asap
                    legacyResponse, legacyRequest);

                next((err && abortOnError) ? err : null, {
                    response: response,
                    request: item.request,
                    legacyResponse: legacyResponse,
                    legacyRequest: legacyRequest
                }, err);
            }.bind(this));
        }
    }
};
<|endoftext|>


<commit_before>'use babel';
'use strict';

import database from '../database/characters';
import config from '../config';
import paginate from '../util/pagination';
import * as nbsp from '../util/nbsp';

export default class ListCharactersCommand {
	static get information() {
		return {
			label: 'characters',
			aliases: ['listcharacters', 'chars'],
			description: 'Lists/searches characters in the database.',
			usage: '!characters [search] [page]',
			details: 'If no search string is specified, all characters will be listed. If the search string is only one letter long, characters that start with that character will be listed. If the search string is more than one letter, all characters that contain that string will be listed.',
			examples: ['!characters', '!characters c', '!characters bill']
		};
	}

	static get triggers() {
		return [
			/^!(?:characters|listcharacters|chars)(?:\s+(.+?))??(?:\s+([0-9]+))?\s*$/i
		];
	}

	static isRunnable(message) {
		return !!message.server;
	}

	static run(message, matches) {
		let characters = database.findCharactersInServer(message.server, matches[1], false);
		if(characters.length > 0) {
			characters.sort((a, b) => a.name < b.name ? -1 : (a.name > b.name ? 1 : 0));
			const paginated = paginate(characters, matches[2] ? parseInt(matches[2]) : 1, Math.floor(config.paginationItems));
			characters = paginated.items;

			let messageText = matches[1] ? (matches[1].length === 1 ? 'Characters that begin with' : 'Characters that contain') + '"' + matches[1] + '"' : 'Character list';
			messageText += ', ' + paginated.pageText + ' (Use ';
			if(paginated.maxPage > 1) messageText += nbsp.convert('`!characters' + (matches[1] ? ' ' + matches[1] : '') + ' <page>`') + ' to view a specific page, or ';
			messageText += '`!character' + nbsp.character + '<name>` to view information about a character):';
			messageText += '\n\n' + characters.map(element => element.name).join('\n');
			message.client.reply(message, messageText);
		} else {
			const messageText = 'There are no characters ' + (matches[1] ? (matches[1].length === 1 ? 'that start with' : 'that contain') + ' "' + matches[1] + '".' : 'in the database.');
			message.client.reply(message, messageText);
		}
	}
}
<commit_msg>Added a missing space<commit_after>'use babel';
'use strict';

import database from '../database/characters';
import config from '../config';
import paginate from '../util/pagination';
import * as nbsp from '../util/nbsp';

export default class ListCharactersCommand {
	static get information() {
		return {
			label: 'characters',
			aliases: ['listcharacters', 'chars'],
			description: 'Lists/searches characters in the database.',
			usage: '!characters [search] [page]',
			details: 'If no search string is specified, all characters will be listed. If the search string is only one letter long, characters that start with that character will be listed. If the search string is more than one letter, all characters that contain that string will be listed.',
			examples: ['!characters', '!characters c', '!characters bill']
		};
	}

	static get triggers() {
		return [
			/^!(?:characters|listcharacters|chars)(?:\s+(.+?))??(?:\s+([0-9]+))?\s*$/i
		];
	}

	static isRunnable(message) {
		return !!message.server;
	}

	static run(message, matches) {
		let characters = database.findCharactersInServer(message.server, matches[1], false);
		if(characters.length > 0) {
			characters.sort((a, b) => a.name < b.name ? -1 : (a.name > b.name ? 1 : 0));
			const paginated = paginate(characters, matches[2] ? parseInt(matches[2]) : 1, Math.floor(config.paginationItems));
			characters = paginated.items;

			let messageText = matches[1] ? (matches[1].length === 1 ? 'Characters that begin with' : 'Characters that contain') + ' "' + matches[1] + '"' : 'Character list';
			messageText += ', ' + paginated.pageText + ' (Use ';
			if(paginated.maxPage > 1) messageText += nbsp.convert('`!characters' + (matches[1] ? ' ' + matches[1] : '') + ' <page>`') + ' to view a specific page, or ';
			messageText += '`!character' + nbsp.character + '<name>` to view information about a character):';
			messageText += '\n\n' + characters.map(element => element.name).join('\n');
			message.client.reply(message, messageText);
		} else {
			const messageText = 'There are no characters ' + (matches[1] ? (matches[1].length === 1 ? 'that start with' : 'that contain') + ' "' + matches[1] + '".' : 'in the database.');
			message.client.reply(message, messageText);
		}
	}
}
<|endoftext|>


<commit_before>import FlatButton from 'material-ui/FlatButton';
import Paper from 'material-ui/Paper';
import RaisedButton from 'material-ui/RaisedButton';
import { Toolbar, ToolbarGroup } from 'material-ui/Toolbar';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import React from 'react';
import Relay from 'react-relay';
import theme from '../theme';
import EventItem from './EventItem';

const itemsPerPage = 10;

class Events extends React.Component {
    static contextTypes = {
        relay: Relay.PropTypes.Environment,
    };

    static propTypes = {
        organization: React.PropTypes.object,
        relay: React.PropTypes.object,
    }

    static childContextTypes = {
        muiTheme: React.PropTypes.object.isRequired,
    }

    constructor(props) {
        super(props);
        this.muiTheme = getMuiTheme(theme);
    }

    getChildContext() {
        return { muiTheme: this.muiTheme };
    }

    loadMoreEvents = () => {
        const events = this.props.organization.events;
        this.props.relay.setVariables({
            showItems: events.edges.length + itemsPerPage,
        });
    }

    render() {
        const org = this.props.organization;
        const events = org.events;
        return (
            <Paper className="row">

Aktiviteter

                    <Toolbar style={{ backgroundColor: theme.palette.fullWhite }}>
                        <ToolbarGroup lastChild>
                            <FlatButton
                                label="Kalenderfil"
                                href="/events/public.ics"
                            />
                        </ToolbarGroup>
                    </Toolbar>

                    {events.edges.map((edge) => {
                        return (
                            <EventItem
                                key={edge.node.id}
                                event={edge.node}
                            />
                        );
                    })}

                {events.pageInfo.hasNextPage
                        ? <RaisedButton
                            primary
                            onClick={this.loadMoreEvents}
                            label="Mer"
                        />
                        : null
                }
            </Paper>
        );
    }
}

export default Relay.createContainer(Events, {
    initialVariables: {
        showItems: itemsPerPage,
    },
    fragments: {
        organization: () => {
            return Relay.QL`
            fragment on Organization {
                id
                memberGroup {
                    id
                }
                events(first:$showItems) {
                    edges {
                        node {
                            id
                            ${EventItem.getFragment('event')}
                        }
                    }
                    pageInfo {
                        hasNextPage
                    }
                }
            }`;
        },
    },
});
<commit_msg>Use "webcal://" to make calendar stuff work<commit_after>import FlatButton from 'material-ui/FlatButton';
import Paper from 'material-ui/Paper';
import RaisedButton from 'material-ui/RaisedButton';
import { Toolbar, ToolbarGroup } from 'material-ui/Toolbar';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import React from 'react';
import Relay from 'react-relay';
import theme from '../theme';
import EventItem from './EventItem';

const itemsPerPage = 10;

class Events extends React.Component {
    static contextTypes = {
        relay: Relay.PropTypes.Environment,
    };

    static propTypes = {
        organization: React.PropTypes.object,
        relay: React.PropTypes.object,
    }

    static childContextTypes = {
        muiTheme: React.PropTypes.object.isRequired,
    }

    constructor(props) {
        super(props);
        this.muiTheme = getMuiTheme(theme);
    }

    getChildContext() {
        return { muiTheme: this.muiTheme };
    }

    loadMoreEvents = () => {
        const events = this.props.organization.events;
        this.props.relay.setVariables({
            showItems: events.edges.length + itemsPerPage,
        });
    }

    render() {
        const org = this.props.organization;
        const events = org.events;
        return (
            <Paper className="row">

Aktiviteter

                    <Toolbar style={{ backgroundColor: theme.palette.fullWhite }}>
                        <ToolbarGroup lastChild>
                            <FlatButton
                                label="Kalenderfil"
                                href={`webcal://${org.webdomain}/events/public.ics`}
                            />
                        </ToolbarGroup>
                    </Toolbar>

                    {events.edges.map((edge) => {
                        return (
                            <EventItem
                                key={edge.node.id}
                                event={edge.node}
                            />
                        );
                    })}

                {events.pageInfo.hasNextPage
                        ? <RaisedButton
                            primary
                            onClick={this.loadMoreEvents}
                            label="Mer"
                        />
                        : null
                }
            </Paper>
        );
    }
}

export default Relay.createContainer(Events, {
    initialVariables: {
        showItems: itemsPerPage,
    },
    fragments: {
        organization: () => {
            return Relay.QL`
            fragment on Organization {
                id
                memberGroup {
                    id
                }
                webdomain
                events(first:$showItems) {
                    edges {
                        node {
                            id
                            ${EventItem.getFragment('event')}
                        }
                    }
                    pageInfo {
                        hasNextPage
                    }
                }
            }`;
        },
    },
});
<|endoftext|>


<commit_before>var path = require("path"),
fs = require("fs"),
args = process.argv.slice(2);

var haveCljsTest = function () {
    return (typeof cljs !== "undefined" &&
            typeof cljs.test !== "undefined" &&
            typeof doo !== "undefined" &&
            typeof doo.runner.run_BANG_ === "function");
};

var failIfCljsTestUndefined = function () {
    if (!haveCljsTest()) {
        var messageLines = [
            "",
            "ERROR: cljs.test was not required.",
            "",
            "You can resolve this issue by ensuring [cljs.test] appears",
            "in the :require clause of your test suite namespaces.",
            "Also make sure that your build has actually included any test files.",
            "",
            "Also remember that Node.js can be only used with simple/advanced ",
            "optimizations, not with none/whitespace.",
            ""
        ];
        console.error(messageLines.join("\n"));
        process.exit(1);
    }
};

args.forEach(function (arg) {
    var file = path.join(process.cwd(), arg);
    global.require = require;
    global.process = process;
    if (fs.existsSync(file)) {
        try {
            // using eval instead of require here so that `this` is the "real"
            // top-level scope, not the module

            global.eval(  fs.readFileSync(file, {encoding: "UTF-8"}) );
            // check this before trying to call set_print_fn_BANG_
            failIfCljsTestUndefined();
        } catch (e) {
            console.log("Error in file: \"" + file + "\"");
            console.log(e);
            failIfCljsTestUndefined();
        }
    } else {
        try {
            global.eval("(function () {" + arg + "})()");
        } catch (e) {
            console.log("Could not evaluate expression: \"" + arg + "\"");
            console.log(e);
        }
    }
});

doo.runner.set_print_fn_BANG_(function(x) {
    // since console.log *itself* adds a newline
    var x = x.replace(/\n$/, "");
    if (x.length > 0) console.log(x);
});

doo.runner.set_exit_point_BANG_(function (isSuccess) {
    process.exit(isSuccess ? 0 : 1);
});

var results = doo.runner.run_BANG_();
<commit_msg>Node support for relative or absolute paths<commit_after>var path = require("path"),
fs = require("fs"),
args = process.argv.slice(2);

var haveCljsTest = function () {
    return (typeof cljs !== "undefined" &&
            typeof cljs.test !== "undefined" &&
            typeof doo !== "undefined" &&
            typeof doo.runner.run_BANG_ === "function");
};

var failIfCljsTestUndefined = function () {
    if (!haveCljsTest()) {
        var messageLines = [
            "",
            "ERROR: cljs.test was not required.",
            "",
            "You can resolve this issue by ensuring [cljs.test] appears",
            "in the :require clause of your test suite namespaces.",
            "Also make sure that your build has actually included any test files.",
            "",
            "Also remember that Node.js can be only used with simple/advanced ",
            "optimizations, not with none/whitespace.",
            ""
        ];
        console.error(messageLines.join("\n"));
        process.exit(1);
    }
};

args.forEach(function (arg) {
    var file = path.isAbsolute(arg) ? arg : path.join(process.cwd(), arg);
    global.require = require;
    global.process = process;
    if (fs.existsSync(file)) {
        try {
            // using eval instead of require here so that `this` is the "real"
            // top-level scope, not the module

            global.eval(  fs.readFileSync(file, {encoding: "UTF-8"}) );
            // check this before trying to call set_print_fn_BANG_
            failIfCljsTestUndefined();
        } catch (e) {
            console.log("Error in file: \"" + file + "\"");
            console.log(e);
            failIfCljsTestUndefined();
        }
    } else {
        try {
            global.eval("(function () {" + arg + "})()");
        } catch (e) {
            console.log("Could not evaluate expression: \"" + arg + "\"");
            console.log(e);
        }
    }
});

doo.runner.set_print_fn_BANG_(function(x) {
    // since console.log *itself* adds a newline
    var x = x.replace(/\n$/, "");
    if (x.length > 0) console.log(x);
});

doo.runner.set_exit_point_BANG_(function (isSuccess) {
    process.exit(isSuccess ? 0 : 1);
});

var results = doo.runner.run_BANG_();
<|endoftext|>


<commit_before>import AvatarImageField from 'rmw-shell/lib/components/ReduxFormFields/AvatarImageField'
import Business from '@material-ui/icons/Business'
import React, { Component } from 'react'
import TextField from 'rmw-shell/lib/components/ReduxFormFields/TextField'
import { Field, reduxForm, formValueSelector } from 'redux-form'
import { ImageCropDialog } from 'rmw-shell/lib/containers/ImageCropDialog'
import { connect } from 'react-redux'
import { injectIntl } from 'react-intl'
import { setDialogIsOpen } from 'rmw-shell/lib/store/dialogs/actions'
import { withRouter } from 'react-router-dom'
import { withTheme } from '@material-ui/core/styles'

class Form extends Component {
  render() {
    const {
      handleSubmit,
      intl,
      initialized,
      setDialogIsOpen,
      dialogs,
      match,
      change,
    } = this.props

    const uid = match.params.uid

    return (
      <form
        onSubmit={handleSubmit}
        style={{
          height: '100%',
          width: '100%',
          alignItems: 'strech',
          display: 'flex',
          flexWrap: 'wrap',
          justifyContent: 'center',
        }}
      >
        <button type="submit" style={{ display: 'none' }} />

          <AvatarImageField
            name="photoURL"
            disabled={!initialized}
            uid={uid}
            change={change}
            initialized={initialized}
            icon={<Business fontSize="large" />}
            intl={intl}
            path={'companies'}
          />

            <Field
              name="name"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'name_hint' })}
              label={intl.formatMessage({ id: 'name_label' })}
            />

            <Field
              name="full_name"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'full_name_hint' })}
              label={intl.formatMessage({ id: 'full_name_label' })}
            />

            <Field
              name="vat"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'vat_hint' })}
              label={intl.formatMessage({ id: 'vat_label' })}
            />

            <Field
              name="workers"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'workers_hint' })}
              label={intl.formatMessage({ id: 'workers_label' })}
              type="number"
            />

            <Field
              name="worth"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'worth_hint' })}
              label={intl.formatMessage({ id: 'worth_label' })}
            />

            <Field
              name="description"
              disabled={!initialized}
              component={TextField}
              multiline
              rows={2}
              placeholder={intl.formatMessage({ id: 'description_hint' })}
              label={intl.formatMessage({ id: 'description_label' })}
            />

          <ImageCropDialog
            path={`companies/${uid}`}
            fileName={'photoURL'}
            onUploadSuccess={s => {
              this.handlePhotoUploadSuccess(s)
            }}
            open={dialogs.new_company_photo !== undefined}
            src={dialogs.new_company_photo}
            handleClose={() => {
              setDialogIsOpen('new_company_photo', undefined)
            }}
            title={intl.formatMessage({ id: 'change_photo' })}
          />

      </form>
    )
  }
}

Form = reduxForm({ form: 'company' })(Form)
const selector = formValueSelector('company')

const mapStateToProps = state => {
  const { intl, vehicleTypes, users, dialogs } = state

  return {
    intl,
    vehicleTypes,
    users,
    dialogs,
    photoURL: selector(state, 'photoURL'),
  }
}

export default connect(mapStateToProps, { setDialogIsOpen })(
  injectIntl(withRouter(withTheme(Form)))
)
<commit_msg>Added select field<commit_after>import AvatarImageField from 'rmw-shell/lib/components/ReduxFormFields/AvatarImageField'
import Business from '@material-ui/icons/Business'
import MenuItem from '@material-ui/core/MenuItem'
import renderSelectField from '../Select'
import React, { Component } from 'react'
import TextField from 'rmw-shell/lib/components/ReduxFormFields/TextField'
import { Field, reduxForm, formValueSelector } from 'redux-form'
import { ImageCropDialog } from 'rmw-shell/lib/containers/ImageCropDialog'
import { connect } from 'react-redux'
import { injectIntl } from 'react-intl'
import { setDialogIsOpen } from 'rmw-shell/lib/store/dialogs/actions'
import { withRouter } from 'react-router-dom'
import { withTheme } from '@material-ui/core/styles'

class Form extends Component {
  render() {
    const {
      handleSubmit,
      intl,
      initialized,
      setDialogIsOpen,
      dialogs,
      match,
      change,
    } = this.props

    const uid = match.params.uid

    return (
      <form
        onSubmit={handleSubmit}
        style={{
          height: '100%',
          width: '100%',
          alignItems: 'strech',
          display: 'flex',
          flexWrap: 'wrap',
          justifyContent: 'center',
        }}
      >
        <button type="submit" style={{ display: 'none' }} />

          <AvatarImageField
            name="photoURL"
            disabled={!initialized}
            uid={uid}
            change={change}
            initialized={initialized}
            icon={<Business fontSize="large" />}
            intl={intl}
            path={'companies'}
          />

            <Field
              name="name"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'name_hint' })}
              label={intl.formatMessage({ id: 'name_label' })}
            />

         <Field
          id="color"
          disabled={!initialized}
          label={intl.formatMessage({ id: 'color_label' })}
          name="color"
          component={renderSelectField}>
           <MenuItem value={'amber'}> {intl.formatMessage({ id: 'amber_label' })} </MenuItem>
           <MenuItem value={'black'}> {intl.formatMessage({ id: 'black_label' })} </MenuItem>
           <MenuItem value={'blue'}> {intl.formatMessage({ id: 'blue_label' })} </MenuItem>
           <MenuItem value={'gray'}> {intl.formatMessage({ id: 'gray_label' })} </MenuItem>
          <MenuItem value={'green'}> {intl.formatMessage({ id: 'green_label' })} </MenuItem>
          </Field>

         <Field
          id="dress"
          label={intl.formatMessage({ id: 'dress_label' })}
          name="dress"
          component={renderSelectField}>
        <MenuItem value={'XS'}> XS </MenuItem>
        <MenuItem value={'S'}> S </MenuItem>
        <MenuItem value={'S/M'}> S/M </MenuItem>
        <MenuItem value={'M'}> M </MenuItem>
        <MenuItem value={'M/L'}> M/L </MenuItem>
        <MenuItem value={'L'}> L </MenuItem>
        <MenuItem value={'XL'}> XL </MenuItem>
        <MenuItem value={'XXL'}> XXL </MenuItem>
        </Field>

            <Field
              name="full_name"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'full_name_hint' })}
              label={intl.formatMessage({ id: 'full_name_label' })}
            />

            <Field
              name="vat"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'vat_hint' })}
              label={intl.formatMessage({ id: 'vat_label' })}
            />

            <Field
              name="workers"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'workers_hint' })}
              label={intl.formatMessage({ id: 'workers_label' })}
              type="number"
            />

            <Field
              name="worth"
              disabled={!initialized}
              component={TextField}
              placeholder={intl.formatMessage({ id: 'worth_hint' })}
              label={intl.formatMessage({ id: 'worth_label' })}
            />

            <Field
              name="description"
              disabled={!initialized}
              component={TextField}
              multiline
              rows={2}
              placeholder={intl.formatMessage({ id: 'description_hint' })}
              label={intl.formatMessage({ id: 'description_label' })}
            />

          <ImageCropDialog
            path={`companies/${uid}`}
            fileName={'photoURL'}
            onUploadSuccess={s => {
              this.handlePhotoUploadSuccess(s)
            }}
            open={dialogs.new_company_photo !== undefined}
            src={dialogs.new_company_photo}
            handleClose={() => {
              setDialogIsOpen('new_company_photo', undefined)
            }}
            title={intl.formatMessage({ id: 'change_photo' })}
          />

      </form>
    )
  }
}

Form = reduxForm({ form: 'company' })(Form)
const selector = formValueSelector('company')

const mapStateToProps = state => {
  const { intl, vehicleTypes, users, dialogs } = state

  return {
    intl,
    vehicleTypes,
    users,
    dialogs,
    photoURL: selector(state, 'photoURL'),
  }
}

export default connect(mapStateToProps, { setDialogIsOpen })(
  injectIntl(withRouter(withTheme(Form)))
)
<|endoftext|>


<commit_before>'use strict';

/*
    MusicBrainz Release Crawl Seeder

    Executes seeder query and dispatches crawl jobs to the job queue.
    Job processors will use MixRadio Artist Name, and Release Name to
    query the MusicBrainz Release API.

    SCRIPT Data Columns
    ===================================
    mr_release_id: 1321422,
    mr_release_name: "I Should Coco",
    mr_release_cardinality: "13",
    mr_artist_id: "10055880",
    mr_artist_name: "Remember Me Soundtrack",
    mb_release_id: "NULL",
    mr_release_tracks: [{
        "mr_track_id": "1321455",
        "mr_track_name": "Lenny",
        "mr_track_position": "6",
        "mb_track_id": "NULL"
    }]
    ===================================
*/

/* Constants */
const namespace = "musicbrainz:release";

/* Parse Job Metadata from text line */
const lineParser = (line) => {

    const attrs = line.split('\t');

    const data = {
        mr_release_id: attrs[0],
        mr_release_name: attrs[1],
        mr_release_cardinality: attrs[2],
        mr_artist_id: attrs[3],
        mr_artist_name: attrs[4],
        mb_release_id: attrs[5],
        mr_release_tracks: JSON.parse(attrs[6])
    };

    if (data.mb_release_id) {
        return { namespace: "musicbrainz:release:id", data };
    }

    return { namespace: "musicbrainz:release:name", data };
};

module.exports = { namespace, lineParser };<commit_msg>Updated seed loader for MusicBrainz Release<commit_after>'use strict';

/*
    MusicBrainz Release Crawl Seeder

    Executes seeder query and dispatches crawl jobs to the job queue.
    Job processors will use MixRadio Artist Name, and Release Name to
    query the MusicBrainz Release API.

    SCRIPT Data Columns
    ===================================
    mr_release_id: 1321422,
    mr_release_name: "I Should Coco",
    mr_release_cardinality: "13",
    mr_artist_id: "10055880",
    mr_artist_name: "Remember Me Soundtrack",
    mb_release_id: "NULL",
    mr_release_tracks: [{
        "mr_track_id": "1321455",
        "mr_track_name": "Lenny",
        "mr_track_position": "6",
        "mb_track_id": "NULL"
    }]
    ===================================
*/

/* Constants */
const namespace = "musicbrainz:release";

/* Parse Job Metadata from text line */
const lineParser = (line) => {

    const attrs = line.split('\t');

    const data = {
        mr_release_id: attrs[0],
        mr_release_name: attrs[1],
        mr_release_cardinality: attrs[2],
        mr_artist_id: attrs[3],
        mr_artist_name: attrs[4],
        mb_release_id: attrs[5],
        mr_release_tracks: JSON.parse(attrs[6])
    };

    // NOTE: Force all release jobs to query by name
    // if (data.mb_release_id) {
    //     return { namespace: "musicbrainz:release:id", data };
    // }

    return { namespace: "musicbrainz:release:name", data };
};

module.exports = { namespace, lineParser };<|endoftext|>


<commit_before>var processing = {
  intensities: function(imagedata) {
    if (!imagedata.data) {
      // it's a canvas, extract the imagedata
      var canvas = imagedata;
      var context = canvas.getContext("2d");
      imagedata = context.getImageData(0, 0, canvas.width, canvas.height);
    }

    var lumas = new Array(imagedata.height);
    for (var y = 0; y < imagedata.height; y++) {
      lumas[y] = new Array(imagedata.width);

      for (var x = 0; x < imagedata.height; x++) {
        var i = x * 4 + y * 4 * imagedata.width;
        var r = imagedata.data[i],
            g = imagedata.data[i + 1],
            b = imagedata.data[i + 2],
            a = imagedata.data[i + 3];

        var luma = a == 0 ? 1 : (r * 299/1000 + g * 587/1000
          + b * 114/1000) / 255;

        lumas[y][x] = luma;
      }
    }
    return lumas;
  },

  gradients: function(canvas) {
    var intensities = this.intensities(canvas);
    return this._gradients(intensities);
  },

  _gradients: function(intensities) {
    var height = intensities.length;
    var width = intensities[0].length;

    var gradX = new Array(height);
    var gradY = new Array(height);

    for (var y = 0; y < height; y++) {
      gradX[y] = new Array(width);
      gradY[y] = new Array(height);

      var row = intensities[y];

      for (var x = 0; x < width; x++) {
        var prevX = x == 0 ? 0 : intensities[y][x - 1];
        var nextX = x == width - 1 ? 0 : intensities[y][x + 1];
        var prevY = y == 0 ? 0 : intensities[y - 1][x];
        var nextY = y == height - 1 ? 0 : intensities[y + 1][x];

        // kernel [-1, 0, 1]
        gradX[y][x] = -prevX + nextX;
        gradY[y][x] = -prevY + nextY;
      }
    }

    return {
      x: gradX,
      y: gradY
    };
  },

  gradientVectors: function(canvas) {
    var intensities = this.intensities(canvas);
    return this._gradientVectors(intensities);
  },

  _gradientVectors: function(intensities) {
    var height = intensities.length;
    var width = intensities[0].length;

    var vectors = new Array(height);

    for (var y = 0; y < height; y++) {
      vectors[y] = new Array(width);

      for (var x = 0; x < width; x++) {
        var prevX = x == 0 ? 0 : intensities[y][x - 1];
        var nextX = x == width - 1 ? 0 : intensities[y][x + 1];
        var prevY = y == 0 ? 0 : intensities[y - 1][x];
        var nextY = y == height - 1 ? 0 : intensities[y + 1][x];

        // kernel [-1, 0, 1]
        var gradX = -prevX + nextX;
        var gradY = -prevY + nextY;

        vectors[y][x] = {
          mag: Math.sqrt(Math.pow(gradX, 2) + Math.pow(gradY, 2)),
          orient: Math.atan2(gradY, gradX)
        }
      }
    }
    return vectors;
  },

  drawGreyscale: function(canvas) {
    var ctx = canvas.getContext('2d');
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    var intensities = this.intensities(canvas);

    for (var y = 0; y < imageData.height; y++) {
      for (var x = 0; x < imageData.width; x++) {
        var i = (y * 4) * imageData.width + x * 4;
        var luma = intensities[y][x] * 255;

        imageData.data[i] = luma;
        imageData.data[i + 1] = luma;
        imageData.data[i + 2] = luma;
        imageData.data[i + 3] = 255;
      }
    }
    ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);
    return canvas;
  },

  drawGradient: function(canvas, dir) {
    var ctx = canvas.getContext("2d");
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    var gradients = this.gradients(canvas);
    var grads = gradients[dir || "x"];

    for (var y = 0; y < imageData.height; y++) {
      for (var x = 0; x < imageData.width; x++) {
        var i = (y * 4) * imageData.width + x * 4;
        var grad = Math.abs(grads[y][x]) * 255;

        imageData.data[i] = grad;
        imageData.data[i + 1] = grad;
        imageData.data[i + 2] = grad;
        imageData.data[i + 3] = 255;
      }
    }
    ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);
    return canvas;
  },

  drawMagnitude: function(canvas) {
    var ctx = canvas.getContext("2d");
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    var vectors = processing.gradientVectors(canvas);

    for (var y = 0; y < imageData.height; y++) {
      for (var x = 0; x < imageData.width; x++) {
        var i = (y * 4) * imageData.width + x * 4;
        var mag = Math.abs(vectors[y][x].mag) * 255;

        imageData.data[i] = mag;
        imageData.data[i + 1] = mag;
        imageData.data[i + 2] = mag;
        imageData.data[i + 3] = 255;
      }
    }
    ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);
    return canvas;
  },

  drawOrients: function(canvas) {
    var ctx = canvas.getContext("2d");
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    var vectors = processing.gradientVectors(canvas);

    for (var y = 0; y < imageData.height; y++) {
      for (var x = 0; x < imageData.width; x++) {
        var i = (y * 4) * imageData.width + x * 4;
        var orient = Math.abs(vectors[y][x].orient);
        orient *= (180 / Math.PI);
        if (orient < 0) {
          orient += 180;
        }
        orient /= 180 * 255;

        imageData.data[i] = orient;
        imageData.data[i + 1] = orient;
        imageData.data[i + 2] = orient;
        imageData.data[i + 3] = 255;
      }
    }
    ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);
    return canvas;
  }
}

module.exports = processing;
<commit_msg>fix incorrect gradient array dimensions<commit_after>var processing = {
  intensities: function(imagedata) {
    if (!imagedata.data) {
      // it's a canvas, extract the imagedata
      var canvas = imagedata;
      var context = canvas.getContext("2d");
      imagedata = context.getImageData(0, 0, canvas.width, canvas.height);
    }

    var lumas = new Array(imagedata.height);
    for (var y = 0; y < imagedata.height; y++) {
      lumas[y] = new Array(imagedata.width);

      for (var x = 0; x < imagedata.height; x++) {
        var i = x * 4 + y * 4 * imagedata.width;
        var r = imagedata.data[i],
            g = imagedata.data[i + 1],
            b = imagedata.data[i + 2],
            a = imagedata.data[i + 3];

        var luma = a == 0 ? 1 : (r * 299/1000 + g * 587/1000
          + b * 114/1000) / 255;

        lumas[y][x] = luma;
      }
    }
    return lumas;
  },

  gradients: function(canvas) {
    var intensities = this.intensities(canvas);
    return this._gradients(intensities);
  },

  _gradients: function(intensities) {
    var height = intensities.length;
    var width = intensities[0].length;

    var gradX = new Array(height);
    var gradY = new Array(height);

    for (var y = 0; y < height; y++) {
      gradX[y] = new Array(width);
      gradY[y] = new Array(width);

      var row = intensities[y];

      for (var x = 0; x < width; x++) {
        var prevX = x == 0 ? 0 : intensities[y][x - 1];
        var nextX = x == width - 1 ? 0 : intensities[y][x + 1];
        var prevY = y == 0 ? 0 : intensities[y - 1][x];
        var nextY = y == height - 1 ? 0 : intensities[y + 1][x];

        // kernel [-1, 0, 1]
        gradX[y][x] = -prevX + nextX;
        gradY[y][x] = -prevY + nextY;
      }
    }

    return {
      x: gradX,
      y: gradY
    };
  },

  gradientVectors: function(canvas) {
    var intensities = this.intensities(canvas);
    return this._gradientVectors(intensities);
  },

  _gradientVectors: function(intensities) {
    var height = intensities.length;
    var width = intensities[0].length;

    var vectors = new Array(height);

    for (var y = 0; y < height; y++) {
      vectors[y] = new Array(width);

      for (var x = 0; x < width; x++) {
        var prevX = x == 0 ? 0 : intensities[y][x - 1];
        var nextX = x == width - 1 ? 0 : intensities[y][x + 1];
        var prevY = y == 0 ? 0 : intensities[y - 1][x];
        var nextY = y == height - 1 ? 0 : intensities[y + 1][x];

        // kernel [-1, 0, 1]
        var gradX = -prevX + nextX;
        var gradY = -prevY + nextY;

        vectors[y][x] = {
          mag: Math.sqrt(Math.pow(gradX, 2) + Math.pow(gradY, 2)),
          orient: Math.atan2(gradY, gradX)
        }
      }
    }
    return vectors;
  },

  drawGreyscale: function(canvas) {
    var ctx = canvas.getContext('2d');
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    var intensities = this.intensities(canvas);

    for (var y = 0; y < imageData.height; y++) {
      for (var x = 0; x < imageData.width; x++) {
        var i = (y * 4) * imageData.width + x * 4;
        var luma = intensities[y][x] * 255;

        imageData.data[i] = luma;
        imageData.data[i + 1] = luma;
        imageData.data[i + 2] = luma;
        imageData.data[i + 3] = 255;
      }
    }
    ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);
    return canvas;
  },

  drawGradient: function(canvas, dir) {
    var ctx = canvas.getContext("2d");
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    var gradients = this.gradients(canvas);
    var grads = gradients[dir || "x"];

    for (var y = 0; y < imageData.height; y++) {
      for (var x = 0; x < imageData.width; x++) {
        var i = (y * 4) * imageData.width + x * 4;
        var grad = Math.abs(grads[y][x]) * 255;

        imageData.data[i] = grad;
        imageData.data[i + 1] = grad;
        imageData.data[i + 2] = grad;
        imageData.data[i + 3] = 255;
      }
    }
    ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);
    return canvas;
  },

  drawMagnitude: function(canvas) {
    var ctx = canvas.getContext("2d");
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    var vectors = processing.gradientVectors(canvas);

    for (var y = 0; y < imageData.height; y++) {
      for (var x = 0; x < imageData.width; x++) {
        var i = (y * 4) * imageData.width + x * 4;
        var mag = Math.abs(vectors[y][x].mag) * 255;

        imageData.data[i] = mag;
        imageData.data[i + 1] = mag;
        imageData.data[i + 2] = mag;
        imageData.data[i + 3] = 255;
      }
    }
    ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);
    return canvas;
  },

  drawOrients: function(canvas) {
    var ctx = canvas.getContext("2d");
    var imageData = ctx.getImageData(0, 0, canvas.width, canvas.height);

    var vectors = processing.gradientVectors(canvas);

    for (var y = 0; y < imageData.height; y++) {
      for (var x = 0; x < imageData.width; x++) {
        var i = (y * 4) * imageData.width + x * 4;
        var orient = Math.abs(vectors[y][x].orient);
        orient *= (180 / Math.PI);
        if (orient < 0) {
          orient += 180;
        }
        orient /= 180 * 255;

        imageData.data[i] = orient;
        imageData.data[i + 1] = orient;
        imageData.data[i + 2] = orient;
        imageData.data[i + 3] = 255;
      }
    }
    ctx.putImageData(imageData, 0, 0, 0, 0, imageData.width, imageData.height);
    return canvas;
  }
}

module.exports = processing;
<|endoftext|>


<commit_before>import React, { Component } from 'react'

export default class extends Component {
  render() {
    return (

              Ubuntu JE

               / JE Classic

               mirror

              떠돌이님이 제작하신 Ubuntu JE의 비공식 미러입니다.

    )
  }
}
<commit_msg>Add warning on niceb5y mirror<commit_after>import React, { Component } from 'react'

export default class extends Component {
  render() {
    return (

              Ubuntu JE

               / JE Classic

               mirror

              떠돌이님이 제작하신 Ubuntu JE의 비공식 미러입니다.

              niceb5y mirror 서비스가 2018년 2월 1일에 종료됩니다.

    )
  }
}
<|endoftext|>


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

const MenuComponent = ({
    active_tool, tool_list, select_tool, search_tools, on_submit
}) => (

GeoTIFF.io

            <form onSubmit={on_submit}>
                <input
                    id='search-input'
                    className='gt-input'
                    type='text'
                    placeholder='Search Tools'
                    onChange={search_tools}
                />
            </form>

            {
                active_tool
                ? React.createElement(active_tool)
                :

                    {
                        tool_list.map(tool => {
                            return <ToolButtonComponent
                                key={tool[0]}
                                name={tool[0]}
                                icon={tool[1]}
                                component={tool[3]}
                                select={select_tool}
                            />
                        })
                    }

            }

)

export default MenuComponent;<commit_msg>updated placeholder text to make it more inviting to users<commit_after>import React from 'react';
import ToolButtonComponent from './ToolButtonComponent';

const MenuComponent = ({
    active_tool, tool_list, select_tool, search_tools, on_submit
}) => (

GeoTIFF.io

            <form onSubmit={on_submit}>
                <input
                    id='search-input'
                    className='gt-input'
                    type='text'
                    placeholder='Search Here for Your Tool'
                    onChange={search_tools}
                />
            </form>

            {
                active_tool
                ? React.createElement(active_tool)
                :

                    {
                        tool_list.map(tool => {
                            return <ToolButtonComponent
                                key={tool[0]}
                                name={tool[0]}
                                icon={tool[1]}
                                component={tool[3]}
                                select={select_tool}
                            />
                        })
                    }

            }

)

export default MenuComponent;<|endoftext|>


<commit_before>const React = require('react');
const {
  getFocusableNodesInElement,
  reconcileNodeArrays,
  setNodeAttributes
} = require('utils/FocusManagement');

module.exports = class RestrictFocus extends React.Component {
  constructor (props, context) {
    super(props, context);

    this._wrapper = React.createRef();
    this.focusableDOMNodes = [];
  }

  componentDidMount () {
    const focusableNodesInDocument = getFocusableNodesInElement(document);
    const focusableNodesInWrapper = getFocusableNodesInElement(this._wrapper);

    this.focusableDOMNodes = reconcileNodeArrays(
      focusableNodesInDocument,
      focusableNodesInWrapper
    );

    this.focusableDOMNodes.forEach(node => {
      setNodeAttributes(node, { tabindex: -1, 'aria-hidden': true });
    });

    console.log('DidMount Test', {
      focusableNodesInDocument,
      focusableNodesInWrapper,
      focusableDOMNodes: this.focusableDOMNodes
    });
  }

  componentWillUnmount () {
    this.focusableDOMNodes.forEach(node => {
      setNodeAttributes(node, { tabindex: 0, 'aria-hidden': false });
    });
  }

  render () {
    return (

 this._wrapper = ref}>
        {this.props.children}

    );
  }
};<commit_msg>Remove console.log<commit_after>const React = require('react');
const {
  getFocusableNodesInElement,
  reconcileNodeArrays,
  setNodeAttributes
} = require('utils/FocusManagement');

module.exports = class RestrictFocus extends React.Component {
  constructor (props, context) {
    super(props, context);

    this._wrapper = React.createRef();
    this.focusableDOMNodes = [];
  }

  componentDidMount () {
    const focusableNodesInDocument = getFocusableNodesInElement(document);
    const focusableNodesInWrapper = getFocusableNodesInElement(this._wrapper);

    this.focusableDOMNodes = reconcileNodeArrays(
      focusableNodesInDocument,
      focusableNodesInWrapper
    );

    this.focusableDOMNodes.forEach(node => {
      setNodeAttributes(node, { tabindex: -1, 'aria-hidden': true });
    });
  }

  componentWillUnmount () {
    this.focusableDOMNodes.forEach(node => {
      setNodeAttributes(node, { tabindex: 0, 'aria-hidden': false });
    });
  }

  render () {
    return (

 this._wrapper = ref}>
        {this.props.children}

    );
  }
};<|endoftext|>


<commit_before>var utility = require('./utility');
var retrievers = (process.env.RETRIEVER_HOST || "http://localhost:5100").split(",");
var async = require('async');
var db = utility.db;
var logger = utility.logger;
var fs = require('fs');
var moment = require('moment');
var getData = utility.getData;
var request = require('request');
var insertPlayer = utility.insertPlayer;
var insertMatch = utility.insertMatch;
var spawn = require('child_process').spawn;
var replay_dir = process.env.REPLAY_DIR || "./replays/";
var domain = require('domain');

function processParse(job, cb) {
    var t1 = new Date();
    var match_id = job.data.payload.match_id;
    var noRetry = job.toJSON().attempts.remaining <= 1;
    async.waterfall([
        async.apply(checkLocal, job),
        getReplayUrl,
        streamReplay,
    ], function(err, job2) {
        logger.info("[PARSER] parse time: %s", (new Date() - t1) / 1000);
        if (err === "replay expired" || noRetry) {
            logger.info("error %s, not retrying", err);
            return db.matches.update({
                match_id: match_id
            }, {
                $set: {
                    parse_status: 1
                }
            }, function(err2) {
                //nullify error if replay expired
                err = err === "replay expired" ? null : err;
                cb(err || err2);
            });
        }
        else if (err) {
            logger.info("error %s, retrying", err);
            return cb(err);
        }
        else {
            return cb(err);
        }
    });
}

function checkLocal(job, cb) {
    var match_id = job.data.payload.match_id;
    var fileName = job.data.fileName || replay_dir + match_id + ".dem";
    if (fs.existsSync(fileName)) {
        logger.info("[PARSER] %s, found local replay", match_id);
        job.data.fileName = fileName;
        job.update();
    }
    cb(null, job);
}

function getReplayUrl(job, cb) {
    if (job.data.url || job.data.fileName) {
        logger.info("has url or fileName");
        return cb(null, job);
    }
    var match = job.data.payload;
    if (match.start_time > moment().subtract(7, 'days').format('X')) {
        logger.info("requesting match from dota2");
        var urls = [];
        for (var i = 0; i < retrievers.length; i++) {
            urls[i] = retrievers[i] + "?match_id=" + job.data.payload.match_id;
        }
        getData(urls, function(err, body) {
            if (err || !body || !body.match) {
                return cb("invalid body or error");
            }
            var url = "http://replay" + body.match.cluster + ".valve.net/570/" + match.match_id + "_" + body.match.replaySalt + ".dem.bz2";
            job.data.url = url;
            job.update();
            return cb(null, job);
        });
    }
    /*
    else if (process.env.AWS_S3_BUCKET) {
        getS3Url(match.match_id, function(err, url) {
            if (!url) {
                return cb("replay expired");
            }
            job.data.url = url;
            job.update();
            return cb(err, job);
        });
    }
    */
    else {
        cb("replay expired");
    }
}

function streamReplay(job, cb) {
    //var fileName = replay_dir + match_id + ".dem";
    //var archiveName = fileName + ".bz2";
    var match_id = job.data.payload.match_id;
    logger.info("[PARSER] streaming from %s", job.data.url || job.data.fileName);
    var parser = utility.runParse(function(err, output) {
        if (err) {
            return cb(err);
        }
        db.matches.update({
            match_id: match_id
        }, {
            $set: {
                parsed_data: output,
                parse_status: 2
            }
        }, function(err) {
            cb(err, job);
        });
    });
    var d = domain.create();
    if (job.data.fileName) {
        d.on('error', function(err) {
            parser.kill();
            return cb(err);
        });
        d.run(function() {
            fs.createReadStream(job.data.fileName).pipe(parser.stdin);
        });
    }
    else {
        var bz = spawn("bzcat");
        d.on('error', function(err) {
            bz.kill();
            parser.kill();
            return cb(err);
        });
        d.run(function() {
            var downStream = request.get({
                url: job.data.url,
                encoding: null,
                timeout: 120000
            });
            downStream.pipe(bz.stdin);
            bz.stdout.pipe(parser.stdin);
        });
    }
}

function processApi(job, cb) {
    //process an api request
    var payload = job.data.payload;
    getData(job.data.url, function(err, data) {
        if (err) {
            return cb(err);
        }
        if (data.response) {
            logger.info("summaries response");
            async.map(data.response.players, insertPlayer, function(err) {
                cb(err);
            });
        }
        else if (payload.match_id) {
            logger.info("details response");
            var match = data.result;
            //join payload with match
            for (var prop in payload) {
                match[prop] = match[prop] ? match[prop] : payload[prop];
            }
            insertMatch(match, function(err) {
                cb(err);
            });
        }
        else {
            return cb("unknown response");
        }
    });
}

module.exports = {
    processParse: processParse,
    processApi: processApi
};
<commit_msg>detect response error<commit_after>var utility = require('./utility');
var retrievers = (process.env.RETRIEVER_HOST || "http://localhost:5100").split(",");
var async = require('async');
var db = utility.db;
var logger = utility.logger;
var fs = require('fs');
var moment = require('moment');
var getData = utility.getData;
var request = require('request');
var insertPlayer = utility.insertPlayer;
var insertMatch = utility.insertMatch;
var spawn = require('child_process').spawn;
var replay_dir = process.env.REPLAY_DIR || "./replays/";
var domain = require('domain');

function processParse(job, cb) {
    var t1 = new Date();
    var match_id = job.data.payload.match_id;
    var noRetry = job.toJSON().attempts.remaining <= 1;
    async.waterfall([
        async.apply(checkLocal, job),
        getReplayUrl,
        streamReplay,
    ], function(err, job2) {
        logger.info("[PARSER] parse time: %s", (new Date() - t1) / 1000);
        if (err === "replay expired" || noRetry) {
            logger.info("error %s, not retrying", err);
            return db.matches.update({
                match_id: match_id
            }, {
                $set: {
                    parse_status: 1
                }
            }, function(err2) {
                //nullify error if replay expired
                err = err === "replay expired" ? null : err;
                cb(err || err2);
            });
        }
        else if (err) {
            logger.info("error %s, retrying", err);
            return cb(err);
        }
        else {
            return cb(err);
        }
    });
}

function checkLocal(job, cb) {
    var match_id = job.data.payload.match_id;
    var fileName = job.data.fileName || replay_dir + match_id + ".dem";
    if (fs.existsSync(fileName)) {
        logger.info("[PARSER] %s, found local replay", match_id);
        job.data.fileName = fileName;
        job.update();
    }
    cb(null, job);
}

function getReplayUrl(job, cb) {
    if (job.data.url || job.data.fileName) {
        logger.info("has url or fileName");
        return cb(null, job);
    }
    var match = job.data.payload;
    if (match.start_time > moment().subtract(7, 'days').format('X')) {
        logger.info("requesting match from dota2");
        var urls = [];
        for (var i = 0; i < retrievers.length; i++) {
            urls[i] = retrievers[i] + "?match_id=" + job.data.payload.match_id;
        }
        getData(urls, function(err, body) {
            if (err || !body || !body.match) {
                return cb("invalid body or error");
            }
            var url = "http://replay" + body.match.cluster + ".valve.net/570/" + match.match_id + "_" + body.match.replaySalt + ".dem.bz2";
            job.data.url = url;
            job.update();
            return cb(null, job);
        });
    }
    /*
    else if (process.env.AWS_S3_BUCKET) {
        getS3Url(match.match_id, function(err, url) {
            if (!url) {
                return cb("replay expired");
            }
            job.data.url = url;
            job.update();
            return cb(err, job);
        });
    }
    */
    else {
        cb("replay expired");
    }
}

function streamReplay(job, cb) {
    //var fileName = replay_dir + match_id + ".dem";
    //var archiveName = fileName + ".bz2";
    var match_id = job.data.payload.match_id;
    logger.info("[PARSER] streaming from %s", job.data.url || job.data.fileName);
    var parser = utility.runParse(function(err, output) {
        if (err) {
            return cb(err);
        }
        db.matches.update({
            match_id: match_id
        }, {
            $set: {
                parsed_data: output,
                parse_status: 2
            }
        }, function(err) {
            cb(err, job);
        });
    });
    var d = domain.create();
    if (job.data.fileName) {
        d.on('error', function(err) {
            parser.kill();
            return cb(err);
        });
        d.run(function() {
            fs.createReadStream(job.data.fileName).pipe(parser.stdin);
        });
    }
    else {
        var bz = spawn("bzcat");
        d.on('error', function(err) {
            bz.kill();
            parser.kill();
            return cb(err);
        });
        d.run(function() {
            var downStream = request.get({
                url: job.data.url,
                encoding: null,
                timeout: 120000
            });
            downStream.on('response', function(err, resp) {
                if (err || resp.statusCode !== 200) {
                    throw "download error";
                }
            });
            downStream.pipe(bz.stdin);
            bz.stdout.pipe(parser.stdin);
        });
    }
}

function processApi(job, cb) {
    //process an api request
    var payload = job.data.payload;
    getData(job.data.url, function(err, data) {
        if (err) {
            return cb(err);
        }
        if (data.response) {
            logger.info("summaries response");
            async.map(data.response.players, insertPlayer, function(err) {
                cb(err);
            });
        }
        else if (payload.match_id) {
            logger.info("details response");
            var match = data.result;
            //join payload with match
            for (var prop in payload) {
                match[prop] = match[prop] ? match[prop] : payload[prop];
            }
            insertMatch(match, function(err) {
                cb(err);
            });
        }
        else {
            return cb("unknown response");
        }
    });
}

module.exports = {
    processParse: processParse,
    processApi: processApi
};
<|endoftext|>


<commit_before>
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Menu, Icon } from 'antd';
import Logout from 'components/Logout';
import routerStore from 'stores/routerStore';

const { SubMenu, Item: MenuItem } = Menu;

const border = '1px solid rgb(233, 233, 233)';
const styles = {
	container: {
		width: 240,
		position: 'fixed',
		left: 0,
		top: 0,
		bottom: 0,
		display: 'flex',
		flexDirection: 'column',
		zIndex: 9,
		borderRight: border,
	},
	title: {
		height: 64,
		display: 'flex',
		justifyContent: 'center',
		alignItems: 'center',
		fontSize: 20,
		borderBottom: border,
		backgroundColor: '#fff',
	},
	menu: {
		flexGrow: 1,
		overflowY: 'scroll',
		borderRightWidth: 0,
	},
	link: {
		display: 'inline',
	},
	footer: {
		display: 'flex',
		justifyContent: 'center',
		alignItems: 'center',
		height: 44,
		fontSize: 14,
		borderTop: border,
	},
};

export default class Sidebar extends Component {
	static contextTypes = {
		appConfig: PropTypes.object,
	};

	static isPrivate = true;

	state = {
		openKeys: [],
	};

	componentWillMount() {
		this._defaultSelectedKeys = [routerStore.location.pathname];
		this._defaultOpenKeys = this._findDefaultOpenKeys();
	}

	_findDefaultOpenKeys() {
		const { menus } = this.context.appConfig.navigator;
		const { pathname } = routerStore.location;

		const findMenuTree = (menus, paths = []) => {
			if (!menus) { return; }
			if (Array.isArray(menus)) {
				for (const menu of menus) {
					const matched = findMenuTree(
						menu.children,
						paths.concat(menu.menuKey),
					);
					if (matched) { return matched; }
					if (menu.path === pathname) { return paths; }
				}
			}
		};

		return findMenuTree(menus);
	}

	_renderMenu(menus) {
		if (!menus) { return; }

		return menus.map((menu) =>
			menu.children && menu.children.length ?
				<SubMenu
					key={menu.menuKey}
					title={

							{menu.icon && <Icon type={menu.icon} />}
							{menu.title}

					}
				>
					{this._renderMenu(menu.children)}
				</SubMenu> :
				<MenuItem key={menu.menuKey}>
					{menu.icon &&
						<Icon type={menu.icon} />
					}
					<Link to={menu.path} style={styles.link}>
						{menu.title}
					</Link>
				</MenuItem>
		);
	}

	render() {
		const {
			context: { appConfig: { navigator, title } },
			_defaultSelectedKeys,
			_defaultOpenKeys,
		} = this;

		return (

{title}

				<Menu
					style={styles.menu}
					mode="inline"
					defaultSelectedKeys={_defaultSelectedKeys}
					defaultOpenKeys={_defaultOpenKeys}
				>
					{this._renderMenu(navigator.menus)}
				</Menu>
				<Logout style={styles.footer} />

		);
	}

}

<commit_msg>fix Sidebar defaultOpenKeys bug<commit_after>
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { Menu, Icon } from 'antd';
import Logout from 'components/Logout';
import routerStore from 'stores/routerStore';
import { isObservableArray } from 'mobx';

const { SubMenu, Item: MenuItem } = Menu;

const border = '1px solid rgb(233, 233, 233)';
const styles = {
	container: {
		width: 240,
		position: 'fixed',
		left: 0,
		top: 0,
		bottom: 0,
		display: 'flex',
		flexDirection: 'column',
		zIndex: 9,
		borderRight: border,
	},
	title: {
		height: 64,
		display: 'flex',
		justifyContent: 'center',
		alignItems: 'center',
		fontSize: 20,
		borderBottom: border,
		backgroundColor: '#fff',
	},
	menu: {
		flexGrow: 1,
		overflowY: 'scroll',
		borderRightWidth: 0,
	},
	link: {
		display: 'inline',
	},
	footer: {
		display: 'flex',
		justifyContent: 'center',
		alignItems: 'center',
		height: 44,
		fontSize: 14,
		borderTop: border,
	},
};

export default class Sidebar extends Component {
	static contextTypes = {
		appConfig: PropTypes.object,
	};

	static isPrivate = true;

	componentWillMount() {
		this._defaultSelectedKeys = [routerStore.location.pathname];
		this._defaultOpenKeys = this._findDefaultOpenKeys();
	}

	_findDefaultOpenKeys() {
		const { menus } = this.context.appConfig.navigator;
		const { pathname } = routerStore.location;
		const findMenuTree = (menus, paths = []) => {
			if (!menus) { return; }
			if (Array.isArray(menus) || isObservableArray(menus)) {
				for (const menu of menus) {
					const matched = findMenuTree(
						menu.children,
						paths.concat(menu.menuKey),
					);
					if (matched) { return matched; }
					if (menu.path === pathname) { return paths; }
				}
			}
		};

		return findMenuTree(menus);
	}

	_renderMenu(menus) {
		if (!menus) { return; }

		return menus.map((menu) =>
			menu.children && menu.children.length ?
				<SubMenu
					key={menu.menuKey}
					title={

							{menu.icon && <Icon type={menu.icon} />}
							{menu.title}

					}
				>
					{this._renderMenu(menu.children)}
				</SubMenu> :
				<MenuItem key={menu.menuKey}>
					{menu.icon &&
						<Icon type={menu.icon} />
					}
					<Link to={menu.path} style={styles.link}>
						{menu.title}
					</Link>
				</MenuItem>
		);
	}

	render() {
		const {
			context: { appConfig: { navigator, title } },
			_defaultSelectedKeys,
			_defaultOpenKeys,
		} = this;

		return (

{title}

				<Menu
					style={styles.menu}
					mode="inline"
					defaultSelectedKeys={_defaultSelectedKeys}
					defaultOpenKeys={_defaultOpenKeys}
				>
					{this._renderMenu(navigator.menus)}
				</Menu>
				<Logout style={styles.footer} />

		);
	}

}

<|endoftext|>


<commit_before>export { Sidebar, SidebarHeader, SidebarScroll, SidebarBackButton } from './Sidebar';
<commit_msg>docs(sidebar): sidebar export resolved<commit_after>import Sidebar from './Sidebar';

export default from './Sidebar';
export { SidebarHeader, SidebarScroll, SidebarBackButton } from './Sidebar';
<|endoftext|>


<commit_before>/*
* imfs.js
* Copyright (C) 2017 sabertazimi <sabertazimi@gmail.com>
*
* Distributed under terms of the MIT license.
*/

'use strict';

const path = require('path');   // utils for resolve path

class Imfs {
    constructor(data) {
        this.data = data || {};
        this.cwd = '/';
    }

    /**
    * change path string to path array
    *
    * @method resolvePath
    * @param  {string} _path path string for target
    * @return {array}       path array
    */
    resolvePath(_path) {
        if ()
    }

    /**
    * change current working directory
    *
    * @method chdir
    * @param  {string}  _path path string for target
    * @return {object}      reference to imfs (this)
    */
    chdir(_path) {
    }

    /**
    * judge a dir/file whether exists or not
    *
    * @method isExist
    * @param  {string}  _path path string for target
    * @return {Boolean}       true stand for existance
    */
    isExist(_path) {
    }

    /**
    * read content of directory
    *
    * @method readdir
    * @param  {string} _path path string for target
    * @return {array}       string array of file/subdir name
    */
    readdir(_path) {
    }

    /**
    * make new directory
    *
    * @method mkdir
    * @param  {string} _path path string for target
    * @return {object}      reference to imfs (this)
    */
    mkdir(_path) {
        return this;
    }

    /**
    * delete directory/file
    *
    * @method rmdir
    * @param  {string} _path path string for target
    * @return {object}      reference to imfs (this)
    */
    rmdir(_path) {
        return this;
    }

    /**
    * read content of file
    *
    * @method readFile
    * @param  {string} _path path string for target
    * @return {string}       content of file
    */
    readFile(_path) {
    }

    /**
    * write content to file
    *
    * @method writeFile
    * @param  {string} _path path string for target
    * @param  {string} content content to write
    * @return {object}      reference to imfs (this)
    */
    writeFile(_path, content) {
        return this;
    }
}

module.exports = Imfs;
<commit_msg>feat(os-final proj5-path): impl path resolve utils<commit_after>/*
* imfs.js
* Copyright (C) 2017 sabertazimi <sabertazimi@gmail.com>
*
* Distributed under terms of the MIT license.
*/

'use strict';

const path = require('path');   // utils for resolve path

class Imfs {
    constructor(data) {
        this.data = data || {};
        this.cwd = '/';
    }

    /**
    * change path string to path array
    *
    * @method resolvePath
    * @param  {string} _path path string for target
    * @return {string}       normalized absolute path
    */
    resolvePath(_path) {
        let formatPath = _path;

        // combine path to absolute path
        if (!path.isAbsolute(formatPath)) {
            formatPath = path.join(this.cwd, formatPath);
        }

        formatPath = path.normalize(formatPath);

        return formatPath;
    }

    /**
     * change normalized absolute path to array
     *
     * @param  {string} formatPath normalized absolute path
     * @return {array}            path array
     */
    path2arr(formatPath) {
        let patharr = fromatPath.substr(1).split("/");

        // remove tail '/'
        if (!patharr[patharr.length - 1]) {
            patharr.pop();
        }

        return patharr;
    }

    /**
    * change current working directory
    *
    * @method chdir
    * @param  {string}  _path path string for target
    * @return {object}      reference to imfs (this)
    */
    chdir(_path) {
        const formatPath = this.resolvePath(_path);
    }

    /**
    * judge a dir/file whether exists or not
    *
    * @method isExist
    * @param  {string}  _path path string for target
    * @return {Boolean}       true stand for existance
    */
    isExist(_path) {
    }

    /**
    * read content of directory
    *
    * @method readdir
    * @param  {string} _path path string for target
    * @return {array}       string array of file/subdir name
    */
    readdir(_path) {
    }

    /**
    * make new directory
    *
    * @method mkdir
    * @param  {string} _path path string for target
    * @return {object}      reference to imfs (this)
    */
    mkdir(_path) {
        return this;
    }

    /**
    * delete directory/file
    *
    * @method rmdir
    * @param  {string} _path path string for target
    * @return {object}      reference to imfs (this)
    */
    rmdir(_path) {
        return this;
    }

    /**
    * read content of file
    *
    * @method readFile
    * @param  {string} _path path string for target
    * @return {string}       content of file
    */
    readFile(_path) {
    }

    /**
    * write content to file
    *
    * @method writeFile
    * @param  {string} _path path string for target
    * @param  {string} content content to write
    * @return {object}      reference to imfs (this)
    */
    writeFile(_path, content) {
        return this;
    }
}

module.exports = Imfs;
<|endoftext|>


<commit_before>import {keyCodes, defaultClassNames, NATIVELY_FOCUSABLE_ELEMENTS} from '../../constants';

import createEl from '../../utils/createEl';
import defer from '../../utils/defer';
import qa from '../../utils/qa';
import trapFocus from '../../utils/trapFocus';

/**
 * @function VUIDialog
 * @version 0.0.2
 * @desc Main VUIDialog function. Creates instances of the dialog based on
 * parameters passed in.
 * @param {object} settings
 */
const VUIDialog = ({
        dialog = '.js-dialog',
        openBtn = '.js-dialog-btn-open',
        closeBtn = '.js-dialog-btn-close',
        isModal = false,
        isAlert = false,
        readyClass = defaultClassNames.IS_READY,
        activeClass = defaultClassNames.IS_ACTIVE,
        showBackdrop = true
    } = {}) => {

    // Stores all the constant dom nodes for the component regardless of instance.
    let DOM = {
        dialogs: qa(dialog)
    };

    // Keeps track of current instance of dialog.
    let state = {
        currentOpenButton: null,
        currentDialog: null,
        focusableElements: null
    };

    /**
     * @function bindBackdropEvents
     * @desc Adds event listener for clicking on backdrop
     */
    function bindBackdropEvents() {
        DOM.backdrop.addEventListener('click', handleBackdropClick);
    }

    /**
     * @function unbindBackdropEvents
     * @desc Removes event listener for clicking on backdrop
     */
    function unbindBackdropEvents() {
        DOM.backdrop.removeEventListener('click', handleBackdropClick);
    }

    /**
     * @function handleBackdropClick
     * @desc If backdrop has been clicked, dismiss dialog
     * @param {Event} e
     */
    function handleBackdropClick(e) {
        if (e.target === DOM.backdrop) {
            closeDialog(state.currentDialog);
        }
    }

    /**
     * @function createBackdrop
     * @desc Creates the dialog backdrop
     */
    function createBackdrop() {
        // Create the backdrop
        DOM.backdrop = createEl({className: defaultClassNames.BACKDROP});
    }

    /**
     * @function bindOpenEvents
     * @desc Finds all open buttons and attaches click event listener
     * @param {node} dialog
     */
    function bindOpenEvents(dialog) {
        const id = dialog.getAttribute('id');

        // Grab all buttons which open this instance of the dialog
        const openButtons = qa(`${openBtn}[data-controls-dialog="${id}"]`);

        openButtons.forEach(button => button.addEventListener('click', openDialog));
    }

    /**
     * @function openDialog
     * @desc Sets up dialog and state ready to be shown. Is triggered by user clicking on open
     * button. Also sets up focusable elements, close and key events and displays dialog
     * @param {Event} e
     */
    function openDialog(e) {
        // Get trigger button so focus can be returned to it later
        const button = e.target;
        // Get dialog that should be opened
        const dialog = document.getElementById(button.getAttribute('data-controls-dialog'));

        // Update State
        state.currentOpenButton = button;
        state.currentDialog = dialog;

        // Focus the dialog and remove aria attributes
        dialog.setAttribute('tabindex', 1);
        dialog.setAttribute('aria-hidden', false);

        // Bind events
        defer(bindKeyCodeEvents);
        defer(bindCloseEvents);
        if (!isModal && DOM.backdrop) {
            defer(bindBackdropEvents);
        }

        // Add backdrop if needed
        if (DOM.backdrop) {
            DOM.page.appendChild(DOM.backdrop);
        }

        // Grabs elements that are focusable inside this dialog instance.
        state.focusableElements = qa(NATIVELY_FOCUSABLE_ELEMENTS.join(), dialog);

        // Add class to make dialog visible. Needs to occur before focus.
        dialog.classList.add(activeClass);

        // Set focus to first element, fallback to Dialog.
        if (state.focusableElements.length) {
            state.focusableElements[0].focus();
        } else {
            dialog.focus();
        }
    }

    /**
     * @function bindCloseEvents
     * @desc Finds all close buttons and attaches click event listener
     * @param {node} dialog
     */
    function bindCloseEvents(dialog = state.currentDialog) {
        // Grab all buttons which open this instance of the dialog
        const closeButtons = qa(closeBtn);

        closeButtons.forEach(button => button.addEventListener('click', closeDialog));
    }

    /**
     * @function closeDialog
     * @desc adds aria attributes and hides dialog, removing backdrop if needed
     * @param {node} dialog
     */
    function closeDialog() {

        const dialog = state.currentDialog;

        // Hide dialog for screenreaders and make untabbable
        dialog.setAttribute('aria-hidden', true);
        dialog.removeAttribute('tabindex');

        // Unbind events
        unbindKeyCodeEvents();
        if (!isModal && DOM.backdrop) {
            unbindBackdropEvents();
        }

        // Remove active state hook class
        dialog.classList.remove(activeClass);

        // Remove backdrop if needed
        if (DOM.backdrop) {
            DOM.page.removeChild(DOM.backdrop);
        }

        // Reset state and return focus to button that opened the dialog
        state.currentOpenButton.focus();
        state.currentOpenButton = null;
        state.currentDialog = null;
    }

    /**
     * @function bindKeyCodeEvents
     * @desc Adds event listener for keydown on the document
     */
    function bindKeyCodeEvents() {
        document.addEventListener('keydown', handleKeyPress);
    }

    /**
     * @function unbindKeyCodeEvents
     * @desc Removes event listener for keydown on the document
     */
    function unbindKeyCodeEvents() {
        document.removeEventListener('keydown', handleKeyPress);
    }

    /**
     * @function handleKeyPress
     * @desc Checks to if Esc or Tab key have been pressed
     * @param {Event} e
     */
    function handleKeyPress(e) {
<<<<<<< Updated upstream
        if (e.keyCode === keyCodes.ESCAPE && !isModal && !isAlert) {
            hideDialog(state.currentDialog);
=======
        if (e.keyCode === KEYCODES.escape && !isModal && !isAlert) {
            closeDialog(state.currentDialog);
>>>>>>> Stashed changes
        }

        if (e.keyCode === keyCodes.TAB && !isModal) {
            trapFocus(e, state.focusableElements);
        }
    }

    /**
     * @function init
     * @desc Initialises the dialog
     */
    function init() {

        // Check if any dialogs exist, return if not
        if (DOM.dialogs === undefined) {
            return false;
        }

        // Add body element to the DOM object
        DOM.page = qa('body')[0];

        if (showBackdrop) {
            createBackdrop();
        }

        DOM.dialogs.forEach(dialog => {

            // Add aria roles and attributes
            const role = isAlert ? 'alertdialog' : 'dialog';

            dialog.setAttribute('aria-hidden', 'true');
            dialog.setAttribute('role', role);

            // Set up event listeners for opening dialog
            bindOpenEvents(dialog);

            dialog.classList.add(readyClass);
        });
    }

    // Initialise VUIDialog component
    init();
};

export default VUIDialog;
<commit_msg>update comments<commit_after>import {keyCodes, defaultClassNames, NATIVELY_FOCUSABLE_ELEMENTS} from '../../constants';

import createEl from '../../utils/createEl';
import defer from '../../utils/defer';
import qa from '../../utils/qa';
import trapFocus from '../../utils/trapFocus';

/**
 * @function VUIDialog
 * @version 0.0.2
 * @desc Main VUIDialog function. Creates instances of the dialog based on
 * parameters passed in.
 * @param {object} settings
 */
const VUIDialog = ({
        dialog = '.js-dialog',
        openBtn = '.js-dialog-btn-open',
        closeBtn = '.js-dialog-btn-close',
        isModal = false,
        isAlert = false,
        readyClass = defaultClassNames.IS_READY,
        activeClass = defaultClassNames.IS_ACTIVE,
        showBackdrop = true
    } = {}) => {

    // Stores all the constant dom nodes for the component regardless of instance.
    let DOM = {
        dialogs: qa(dialog)
    };

    // Keeps track of current instance of dialog.
    let state = {
        currentOpenButton: null,
        currentDialog: null,
        focusableElements: null
    };

    /**
     * @function bindBackdropEvents
     * @desc Adds event listener for clicking on backdrop
     */
    function bindBackdropEvents() {
        DOM.backdrop.addEventListener('click', handleBackdropClick);
    }

    /**
     * @function unbindBackdropEvents
     * @desc Removes event listener for clicking on backdrop
     */
    function unbindBackdropEvents() {
        DOM.backdrop.removeEventListener('click', handleBackdropClick);
    }

    /**
     * @function handleBackdropClick
     * @desc If backdrop has been clicked, dismiss dialog
     * @param {Event} e
     */
    function handleBackdropClick(e) {
        if (e.target === DOM.backdrop) {
            closeDialog(state.currentDialog);
        }
    }

    /**
     * @function createBackdrop
     * @desc Creates the dialog backdrop
     */
    function createBackdrop() {
        // Create the backdrop
        DOM.backdrop = createEl({className: defaultClassNames.BACKDROP});
    }

    /**
     * @function bindOpenEvents
     * @desc Finds all open buttons and attaches click event listener
     * @param {node} dialog
     */
    function bindOpenEvents(dialog) {
        const id = dialog.getAttribute('id');

        // Grab all buttons which open this instance of the dialog
        const openButtons = qa(`${openBtn}[data-controls-dialog="${id}"]`);

        openButtons.forEach(button => button.addEventListener('click', openDialog));
    }

    /**
     * @function openDialog
     * @desc Sets up dialog and state ready to be shown. Is triggered by user clicking on open
     * button. Also sets up focusable elements, close and key events and displays dialog
     * @param {Event} e
     */
    function openDialog(e) {
        // Get trigger button so focus can be returned to it later
        const button = e.target;

        // Get dialog that should be opened
        const dialog = document.getElementById(button.getAttribute('data-controls-dialog'));

        // Update State
        state.currentOpenButton = button;
        state.currentDialog = dialog;

        // Focus the dialog and remove aria attributes
        dialog.setAttribute('tabindex', 1);
        dialog.setAttribute('aria-hidden', false);

        // Bind events
        defer(bindKeyCodeEvents);
        defer(bindCloseEvents);
        if (!isModal && DOM.backdrop) {
            defer(bindBackdropEvents);
        }

        // Add backdrop if needed
        if (DOM.backdrop) {
            DOM.page.appendChild(DOM.backdrop);
        }

        // Grabs elements that are focusable inside this dialog instance.
        state.focusableElements = qa(NATIVELY_FOCUSABLE_ELEMENTS.join(), dialog);

        // Add class to make dialog visible. Needs to occur before focus.
        dialog.classList.add(activeClass);

        // Set focus to first element, fallback to Dialog.
        if (state.focusableElements.length) {
            state.focusableElements[0].focus();
        } else {
            dialog.focus();
        }
    }

    /**
     * @function bindCloseEvents
     * @desc Finds all close buttons and attaches click event listener
     */
    function bindCloseEvents() {
        // Grab all buttons which open this instance of the dialog
        const closeButtons = qa(closeBtn);

        closeButtons.forEach(button => button.addEventListener('click', closeDialog));
    }

    /**
     * @function closeDialog
     * @desc Triggered by user interacting with a close button or in some cases clicking backdrop.
     * Adds aria attributes and hides dialog, removing backdrop if needed
     */
    function closeDialog() {

        const dialog = state.currentDialog;

        // Hide dialog for screenreaders and make untabbable
        dialog.setAttribute('aria-hidden', true);
        dialog.removeAttribute('tabindex');

        // Unbind events
        unbindKeyCodeEvents();
        if (!isModal && DOM.backdrop) {
            unbindBackdropEvents();
        }

        // Remove active state hook class
        dialog.classList.remove(activeClass);

        // Remove backdrop if needed
        if (DOM.backdrop) {
            DOM.page.removeChild(DOM.backdrop);
        }

        // Reset state and return focus to button that opened the dialog
        state.currentOpenButton.focus();
        state.currentOpenButton = null;
        state.currentDialog = null;
    }

    /**
     * @function bindKeyCodeEvents
     * @desc Adds event listener for keydown on the document
     */
    function bindKeyCodeEvents() {
        document.addEventListener('keydown', handleKeyPress);
    }

    /**
     * @function unbindKeyCodeEvents
     * @desc Removes event listener for keydown on the document
     */
    function unbindKeyCodeEvents() {
        document.removeEventListener('keydown', handleKeyPress);
    }

    /**
     * @function handleKeyPress
     * @desc Checks to if Esc or Tab key have been pressed
     * @param {Event} e
     */
    function handleKeyPress(e) {
<<<<<<< Updated upstream
        if (e.keyCode === keyCodes.ESCAPE && !isModal && !isAlert) {
            hideDialog(state.currentDialog);
=======
        if (e.keyCode === KEYCODES.escape && !isModal && !isAlert) {
            closeDialog(state.currentDialog);
>>>>>>> Stashed changes
        }

        if (e.keyCode === keyCodes.TAB && !isModal) {
            trapFocus(e, state.focusableElements);
        }
    }

    /**
     * @function init
     * @desc Initialises the dialog
     */
    function init() {

        // Check if any dialogs exist, return if not
        if (DOM.dialogs === undefined) {
            return false;
        }

        // Add body element to the DOM object
        DOM.page = qa('body')[0];

        if (showBackdrop) {
            createBackdrop();
        }

        DOM.dialogs.forEach(dialog => {

            // Add aria roles and attributes
            const role = isAlert ? 'alertdialog' : 'dialog';

            dialog.setAttribute('aria-hidden', 'true');
            dialog.setAttribute('role', role);

            // Set up event listeners for opening dialog
            bindOpenEvents(dialog);

            dialog.classList.add(readyClass);
        });
    }

    // Initialise VUIDialog component
    init();
};

export default VUIDialog;
<|endoftext|>