<commit_before>/* eslint-disable @typescript-eslint/explicit-function-return-type */
const { resolve, parse, join } = require('path');
const { existsSync } = require('fs');
const GroupHelper = require('./utils/group-helper');
const Compiler = require('./utils/compiler');

const webpackMerge = require('webpack-merge');

const defaultCommands = {
    create: 'init',
    loader: 'generate-loader',
    plugin: 'generate-plugin',
    info: 'info',
    migrate: 'migrate',
};

class WebpackCLI extends GroupHelper {
    constructor() {
        super();
        this.groupMap = new Map();
        this.groups = [];
        this.processingMessageBuffer = [];
    }
    setMappedGroups(args, yargsOptions) {
        const { _all } = args;
        Object.keys(_all).forEach(key => {
            this.setGroupMap(key, _all[key], yargsOptions);
        });
    }
    setGroupMap(key, val, yargsOptions) {
        const opt = yargsOptions.find(opt => opt.name === key);
        const groupName = opt.group;
        const namePrefix = groupName.slice(0, groupName.length - 9).toLowerCase();
        if (this.groupMap.has(namePrefix)) {
            const pushToMap = this.groupMap.get(namePrefix);
            pushToMap.push({ [opt.name]: val });
        } else {
            this.groupMap.set(namePrefix, [{ [opt.name]: val }]);
        }
    }

    checkDefaults(options, outputOptions) {
        if (Array.isArray(options)) {
            return options.map(opt => this.checkDefaults(opt, outputOptions));
        }
        const defaultEntry = 'index';
        const possibleFileNames = [`./${defaultEntry}`, `./${defaultEntry}.js`, `${defaultEntry}.js`, defaultEntry, `./src/${defaultEntry}`, `./src/${defaultEntry}.js`, `src/${defaultEntry}.js`];
        if (options.entry && possibleFileNames.includes(options.entry)) {
            const absFilename = parse(options.entry);
            let tmpFileName = options.entry;
            if (absFilename.ext !== '.js') {
                tmpFileName += '.js';
            }
            const normalizedEntry = resolve(tmpFileName);
            if (!existsSync(normalizedEntry)) {
                const parsedPath = parse(normalizedEntry);
                const possibleEntries = possibleFileNames
                    .map(f => {
                        return resolve(parsedPath.dir, f);
                    })
                    .filter(e => existsSync(e));

                if (possibleEntries.length) {
                    options.entry = possibleEntries[0];
                }
            }
        }
        if (outputOptions.devtool) {
            options.devtool = outputOptions.devtool;
        }
        return options;
    }

    resolveGroups() {
        let mode;
        for (const [key, value] of this.groupMap.entries()) {
            const fileName = join(__dirname, 'groups', key);
            const GroupClass = require(fileName);
            if (key === 'config') {
                value.push({ mode });
            }
            const GroupInstance = new GroupClass(value);
            if (key === 'basic') {
                if (GroupInstance.opts.outputOptions.dev) {
                    mode = 'dev';
                } else {
                    mode = 'prod';
                }
                this.groups.push(GroupInstance);
            } else {
                this.groups.push(GroupInstance);
            }
        }
    }

    async runOptionGroups() {
        const groupResult = {
            options: {},
            outputOptions: {},
            processingMessageBuffer: [],
        };

        const tmpGroupResult = this.groups.map(Group => Group.run()).filter(e => e);
        const resolvedResults = await Promise.all(tmpGroupResult);
        resolvedResults.forEach((e, idx) => {
            let groupObject = resolvedResults[idx + 1];
            if (e.processingMessageBuffer) {
                groupResult.processingMessageBuffer = groupResult.processingMessageBuffer.concat(...e.processingMessageBuffer);
            }
            if (!groupObject) {
                groupObject = {
                    outputOptions: {},
                    options: {},
                };
            }
            if (!groupObject.outputOptions) {
                groupObject.outputOptions = {};
            }

            groupResult.outputOptions = Object.assign(groupObject.outputOptions, e.outputOptions);
            if (Array.isArray(e.options)) {
                const defaultArrayOptions = e.options.map(arrayConfigObject => {
                    return webpackMerge(groupResult.options, arrayConfigObject);
                });
                groupResult.options = defaultArrayOptions;
                return;
            }
            if (Array.isArray(groupResult.options)) {
                const defaultArrayOptions = groupResult.options.map(arrayConfigObject => {
                    return webpackMerge(e.options, arrayConfigObject);
                });
                groupResult.options = defaultArrayOptions;
                return;
            }
            groupResult.options = webpackMerge(groupResult.options, e.options);
        });
        if (groupResult.outputOptions.defaults) {
            const wrappedConfig = require('./utils/zero-config')(groupResult);
            wrappedConfig.options = this.checkDefaults(wrappedConfig.options, wrappedConfig.outputOptions);
            return wrappedConfig;
        }
        return groupResult;
    }

    async processArgs(args, yargsOptions) {
        this.setMappedGroups(args, yargsOptions);
        this.resolveGroups();
        const groupResult = await this.runOptionGroups();
        return groupResult;
    }

    async getCompiler(args, yargsOptions) {
        const groupResult = await this.processArgs(args, yargsOptions);
        const { options } = groupResult;
        return await Compiler.getCompiler(options);
    }

    async run(args, yargsOptions) {
        const groupResult = await this.processArgs(args, yargsOptions);
        const webpack = await Compiler.webpackInstance(groupResult);
        return webpack;
    }

    async runCommand(command, ...args) {
        // TODO: rename and depreciate init
        return await require('./commands/external').run(defaultCommands[command.name], ...args);
    }

    runHelp(args) {
        const HelpGroup = require('./groups/help');
        const { names } = require('./utils/commands');
        const command = names.filter(name => {
            return args.includes(name);
        })[0];
        return new HelpGroup().outputHelp(command);
    }

    runVersion() {
        const HelpGroup = require('./groups/help');
        return new HelpGroup().outputVersion();
    }
}

module.exports = WebpackCLI;
<commit_msg>fix: refactor redundant code<commit_after>/* eslint-disable @typescript-eslint/explicit-function-return-type */
const { resolve, parse, join } = require('path');
const { existsSync } = require('fs');
const GroupHelper = require('./utils/group-helper');
const Compiler = require('./utils/compiler');

const webpackMerge = require('webpack-merge');

const defaultCommands = {
    create: 'init',
    loader: 'generate-loader',
    plugin: 'generate-plugin',
    info: 'info',
    migrate: 'migrate',
};

class WebpackCLI extends GroupHelper {
    constructor() {
        super();
        this.groupMap = new Map();
        this.groups = [];
        this.processingMessageBuffer = [];
    }
    setMappedGroups(args, yargsOptions) {
        const { _all } = args;
        Object.keys(_all).forEach(key => {
            this.setGroupMap(key, _all[key], yargsOptions);
        });
    }
    setGroupMap(key, val, yargsOptions) {
        const opt = yargsOptions.find(opt => opt.name === key);
        const groupName = opt.group;
        const namePrefix = groupName.slice(0, groupName.length - 9).toLowerCase();
        if (this.groupMap.has(namePrefix)) {
            const pushToMap = this.groupMap.get(namePrefix);
            pushToMap.push({ [opt.name]: val });
        } else {
            this.groupMap.set(namePrefix, [{ [opt.name]: val }]);
        }
    }

    checkDefaults(options, outputOptions) {
        if (Array.isArray(options)) {
            return options.map(opt => this.checkDefaults(opt, outputOptions));
        }
        const defaultEntry = 'index';
        const possibleFileNames = [`./${defaultEntry}`, `./${defaultEntry}.js`, `${defaultEntry}.js`, defaultEntry, `./src/${defaultEntry}`, `./src/${defaultEntry}.js`, `src/${defaultEntry}.js`];
        if (options.entry && possibleFileNames.includes(options.entry)) {
            const absFilename = parse(options.entry);
            let tmpFileName = options.entry;
            if (absFilename.ext !== '.js') {
                tmpFileName += '.js';
            }
            const normalizedEntry = resolve(tmpFileName);
            if (!existsSync(normalizedEntry)) {
                const parsedPath = parse(normalizedEntry);
                const possibleEntries = possibleFileNames
                    .map(f => {
                        return resolve(parsedPath.dir, f);
                    })
                    .filter(e => existsSync(e));

                if (possibleEntries.length) {
                    options.entry = possibleEntries[0];
                }
            }
        }
        if (outputOptions.devtool) {
            options.devtool = outputOptions.devtool;
        }
        return options;
    }

    resolveGroups() {
        let mode;
        for (const [key, value] of this.groupMap.entries()) {
            const fileName = join(__dirname, 'groups', key);
            const GroupClass = require(fileName);
            if (key === 'config') {
                value.push({ mode });
            }
            const GroupInstance = new GroupClass(value);
            if (key === 'basic') {
                mode = GroupInstance.opts.outputOptions.dev ? 'dev' : 'prod';
            }
            this.groups.push(GroupInstance);
        }
    }

    async runOptionGroups() {
        const groupResult = {
            options: {},
            outputOptions: {},
            processingMessageBuffer: [],
        };

        const tmpGroupResult = this.groups.map(Group => Group.run()).filter(e => e);
        const resolvedResults = await Promise.all(tmpGroupResult);
        resolvedResults.forEach((e, idx) => {
            let groupObject = resolvedResults[idx + 1];
            if (e.processingMessageBuffer) {
                groupResult.processingMessageBuffer = groupResult.processingMessageBuffer.concat(...e.processingMessageBuffer);
            }
            if (!groupObject) {
                groupObject = {
                    outputOptions: {},
                    options: {},
                };
            }
            if (!groupObject.outputOptions) {
                groupObject.outputOptions = {};
            }

            groupResult.outputOptions = Object.assign(groupObject.outputOptions, e.outputOptions);
            if (Array.isArray(e.options)) {
                const defaultArrayOptions = e.options.map(arrayConfigObject => {
                    return webpackMerge(groupResult.options, arrayConfigObject);
                });
                groupResult.options = defaultArrayOptions;
                return;
            }
            if (Array.isArray(groupResult.options)) {
                const defaultArrayOptions = groupResult.options.map(arrayConfigObject => {
                    return webpackMerge(e.options, arrayConfigObject);
                });
                groupResult.options = defaultArrayOptions;
                return;
            }
            groupResult.options = webpackMerge(groupResult.options, e.options);
        });
        if (groupResult.outputOptions.defaults) {
            const wrappedConfig = require('./utils/zero-config')(groupResult);
            wrappedConfig.options = this.checkDefaults(wrappedConfig.options, wrappedConfig.outputOptions);
            return wrappedConfig;
        }
        return groupResult;
    }

    async processArgs(args, yargsOptions) {
        this.setMappedGroups(args, yargsOptions);
        this.resolveGroups();
        const groupResult = await this.runOptionGroups();
        return groupResult;
    }

    async getCompiler(args, yargsOptions) {
        const groupResult = await this.processArgs(args, yargsOptions);
        const { options } = groupResult;
        return await Compiler.getCompiler(options);
    }

    async run(args, yargsOptions) {
        const groupResult = await this.processArgs(args, yargsOptions);
        const webpack = await Compiler.webpackInstance(groupResult);
        return webpack;
    }

    async runCommand(command, ...args) {
        // TODO: rename and depreciate init
        return await require('./commands/external').run(defaultCommands[command.name], ...args);
    }

    runHelp(args) {
        const HelpGroup = require('./groups/help');
        const { names } = require('./utils/commands');
        const command = names.filter(name => {
            return args.includes(name);
        })[0];
        return new HelpGroup().outputHelp(command);
    }

    runVersion() {
        const HelpGroup = require('./groups/help');
        return new HelpGroup().outputVersion();
    }
}

module.exports = WebpackCLI;
<|endoftext|>


<commit_before>var dns = require('dns');
var Connection = require('./connection');
var xml = require('./xml');

var NS_SERVER = 'jabber:server';
var NS_DIALBACK = 'jabber:server:dialback';

/**
 * Dialback-specific events:
 * (1) dialbackKey(from, to, key)
 * (2) dialbackVerify(from, to, id, key)
 * (3) dialbackVerified(from, to, id, isValid)
 * (4) dialbackResult(from, to, isValid)
 */
function initServer(self) {
    self.xmlns = NS_SERVER;
    self.xmppVersion = '1.0';

    self.addListener('rawStanza', function(stanza) {
	var key = stanza.getText();

	if (stanza.is('result', NS_DIALBACK) &&
	    stanza.attrs.from && stanza.attrs.to &&
	    key.length > 0) {

	    self.emit('dialbackKey',
		      stanza.attrs.from, stanza.attrs.to,
		      key);

	} else if (stanza.is('verify', NS_DIALBACK) &&
		   stanza.attrs.from && stanza.attrs.to &&
		   stanza.attrs.id && key.length > 0) {

	    self.emit('dialbackVerify',
		      stanza.attrs.from, stanza.attrs.to,
		      stanza.attrs.id, key);

	} else if (stanza.is('verify', NS_DIALBACK) &&
		   stanza.attrs.from && stanza.attrs.to &&
		   stanza.attrs.id && stanza.attrs.type) {

	    self.emit('dialbackVerified',
		      stanza.attrs.from, stanza.attrs.to,
		      stanza.attrs.id, stanza.attrs.type == 'valid');

	} else if (stanza.is('result', NS_DIALBACK) &&
		   stanza.attrs.from && stanza.attrs.to &&
		   stanza.attrs.type) {

	    self.emit('dialbackResult',
		      stanza.attrs.from, stanza.attrs.to,
		      stanza.attrs.type == 'valid');
	} else
	    self.emit('stanza', stanza);
    });
}

exports.dialbackKey = function(from, to, key) {
    return new xml.Element('db:result', { to: to,
					  from: from }).
	t(key);
};
exports.dialbackVerify = function(from, to, id, key) {
    return new xml.Element('db:verify', { to: to,
					  from: from,
					  id: id }).
	t(key);
};
exports.dialbackVerified = function(from, to, id, isValid) {
    return new xml.Element('db:verify', { to: to,
					  from: from,
					  id: id,
					  type: isValid ? 'valid' : 'invalid' });
};
exports.dialbackResult = function(from, to, isValid) {
    return new xml.Element('db:result', { to: to,
					  from: from,
					  type: isValid ? 'valid' : 'invalid' });
};

exports.makeIncomingServer = function(self) {
    Connection.makeConnection(self);

    initServer(self);
    self.startStream();
    self.streamId = generateId();

    self.addListener('streamStart', function(streamAttrs) {
	var tag = "<stream:stream xmlns='" + self.xmlns +
	    "' xmlns:stream='" + Connection.NS_STREAM +
	    "' xmlns:db='" + NS_DIALBACK +
	    "' id='" + self.streamId + "'";
	if (self.xmppVersion)
	    tag += " version='" + self.xmppVersion + "'";
	tag += "><stream:features/>";
	self.send(tag);
    });

    return self;
};

function dnsLookup(domain, cb) {
    dns.resolveSrv('_xmpp-server._tcp.' + domain, function(error, data) {
	if (data[0])
	    cb(data[0].name, data[0].port);
	else
	    dns.resolveSrv('_jabber._tcp.' + domain, function(error, data) {
		if (data[0])
		    cb(data[0].name, data[0].port);
		else
		    cb(domain, 5269);
	    });
    });
}

exports.makeOutgoingServer = function(domain) {
    var self = new Connection.Connection();
    initServer(self);
    self.startStream = function() {
	Connection.Connection.prototype.startStream.call(self);

	var tag = "<stream:stream xmlns='" + self.xmlns +
	    "' xmlns:stream='" + Connection.NS_STREAM +
	    "' xmlns:db='" + NS_DIALBACK +
	    "' to='" + domain + "'";
	if (self.xmppVersion)
	    tag += " version='" + self.xmppVersion + "'";
	tag += ">";
	self.send(tag);
    };

    dnsLookup(domain, function(host, port) {
	self.connect(port, host);
	self.addListener('connect', self.startStream);
    });

    self.addListener('rawStanza', function(stanza) {
	if (stanza.is('features', Connection.NS_STREAM)) {
	    self.emit('online');
	}
    });

    return self;
};

function generateId() {
    var r = new Buffer(16);
    for(var i = 0; i < r.length; i++) {
	r[i] = 48 + Math.floor(Math.random() * 10);  // '0'..'9'
    }
    return r.toString();
};
<commit_msg>server: reorder dialback matching to allow empty keys<commit_after>var dns = require('dns');
var Connection = require('./connection');
var xml = require('./xml');

var NS_SERVER = 'jabber:server';
var NS_DIALBACK = 'jabber:server:dialback';

/**
 * Dialback-specific events:
 * (1) dialbackKey(from, to, key)
 * (2) dialbackVerify(from, to, id, key)
 * (3) dialbackVerified(from, to, id, isValid)
 * (4) dialbackResult(from, to, isValid)
 */
function initServer(self) {
    self.xmlns = NS_SERVER;
    self.xmppVersion = '1.0';

    self.addListener('rawStanza', function(stanza) {
	var key = stanza.getText();

	if (stanza.is('result', NS_DIALBACK) &&
		   stanza.attrs.from && stanza.attrs.to &&
		   stanza.attrs.type) {

	    self.emit('dialbackResult',
		      stanza.attrs.from, stanza.attrs.to,
		      stanza.attrs.type == 'valid');

	} else if (stanza.is('result', NS_DIALBACK) &&
	    stanza.attrs.from && stanza.attrs.to) {

	    self.emit('dialbackKey',
		      stanza.attrs.from, stanza.attrs.to,
		      key);

	} else if (stanza.is('verify', NS_DIALBACK) &&
		   stanza.attrs.from && stanza.attrs.to &&
		   stanza.attrs.id && stanza.attrs.type) {

	    self.emit('dialbackVerified',
		      stanza.attrs.from, stanza.attrs.to,
		      stanza.attrs.id, stanza.attrs.type == 'valid');

	} else if (stanza.is('verify', NS_DIALBACK) &&
		   stanza.attrs.from && stanza.attrs.to &&
		   stanza.attrs.id) {

	    self.emit('dialbackVerify',
		      stanza.attrs.from, stanza.attrs.to,
		      stanza.attrs.id, key);

	} else
	    self.emit('stanza', stanza);
    });
}

exports.dialbackKey = function(from, to, key) {
    return new xml.Element('db:result', { to: to,
					  from: from }).
	t(key);
};
exports.dialbackVerify = function(from, to, id, key) {
    return new xml.Element('db:verify', { to: to,
					  from: from,
					  id: id }).
	t(key);
};
exports.dialbackVerified = function(from, to, id, isValid) {
    return new xml.Element('db:verify', { to: to,
					  from: from,
					  id: id,
					  type: isValid ? 'valid' : 'invalid' });
};
exports.dialbackResult = function(from, to, isValid) {
    return new xml.Element('db:result', { to: to,
					  from: from,
					  type: isValid ? 'valid' : 'invalid' });
};

exports.makeIncomingServer = function(self) {
    Connection.makeConnection(self);

    initServer(self);
    self.startStream();
    self.streamId = generateId();

    self.addListener('streamStart', function(streamAttrs) {
	var tag = "<stream:stream xmlns='" + self.xmlns +
	    "' xmlns:stream='" + Connection.NS_STREAM +
	    "' xmlns:db='" + NS_DIALBACK +
	    "' id='" + self.streamId + "'";
	if (self.xmppVersion)
	    tag += " version='" + self.xmppVersion + "'";
	tag += "><stream:features/>";
	self.send(tag);
    });

    return self;
};

function dnsLookup(domain, cb) {
    dns.resolveSrv('_xmpp-server._tcp.' + domain, function(error, data) {
	if (data[0])
	    cb(data[0].name, data[0].port);
	else
	    dns.resolveSrv('_jabber._tcp.' + domain, function(error, data) {
		if (data[0])
		    cb(data[0].name, data[0].port);
		else
		    cb(domain, 5269);
	    });
    });
}

exports.makeOutgoingServer = function(domain) {
    var self = new Connection.Connection();
    initServer(self);
    self.startStream = function() {
	Connection.Connection.prototype.startStream.call(self);

	var tag = "<stream:stream xmlns='" + self.xmlns +
	    "' xmlns:stream='" + Connection.NS_STREAM +
	    "' xmlns:db='" + NS_DIALBACK +
	    "' to='" + domain + "'";
	if (self.xmppVersion)
	    tag += " version='" + self.xmppVersion + "'";
	tag += ">";
	self.send(tag);
    };

    dnsLookup(domain, function(host, port) {
	self.connect(port, host);
	self.addListener('connect', self.startStream);
    });

    self.addListener('rawStanza', function(stanza) {
	if (stanza.is('features', Connection.NS_STREAM)) {
	    self.emit('online');
	}
    });

    return self;
};

function generateId() {
    var r = new Buffer(16);
    for(var i = 0; i < r.length; i++) {
	r[i] = 48 + Math.floor(Math.random() * 10);  // '0'..'9'
    }
    return r.toString();
};
<|endoftext|>


<commit_before>/*
* This code is for the PowerTokens project.
* OAuth2 flow adapted from sample code from JeremiahLee
* Uses Fetch & Fitbit Web API
*/

//VARIOUS KEYS and AUTH IDS needed
var fbTok;
var clientID = 'YOUR_ID_HERE';
var callback = 'YOUR_WEBSITE_HERE';
var authURI = 'https://www.fitbit.com/oauth2/authorize';
var authTokenReq = 'https://api.fitbit.com/oauth2/token';

// Implementing 'Implicit Auth in OATH2.0'
if (!window.location.hash){
	window.location.replace( authURI+'?response_type=token'+'&client_id='+clientID
		+'&redirect_uri='+callback+'&scope=activity');
} else{
    var fragmentQueryParameters = {};
    window.location.hash.slice(1).replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function($0, $1, $2, $3) { fragmentQueryParameters[$1] = $3; }
    );

    fbTok = fragmentQueryParameters.access_token;
}

// HANDLE the response from FITBIT API (expect JSON)
var processResponse = function(response){
	if (!response.ok){
		throw new Error('Fitbit API request failed' + response);
	}
	var contentType = response.headers.get('content-type')
	if(contentType && contentType.indexOf("application/json") !== -1){
		document.querySelector('h2').textContent = 'JSON recieved!';
		return response.json();
	}else{
		throw new Error('JSON expected but received'+contentType);
	}
}

// HANDLE the data from an /ACTIVITY api endpoint
var processActivity = function(activity){
	document.getElementById('activityHeader').textContent = 'Fitbit - GET Activity';
	prettyAct = JSON.stringify(activity, null, 2);
	console.log(prettyAct)
	var display = document.getElementById('display');
	display.textContent = prettyAct;

}

// Now, actually go forth and FETCH
var activityURL = 'https://api.fitbit.com/1/user/-/activities.json';
fetch( activityURL,
	{
		headers: new Headers({
			'Authorization': 'Bearer ' + fbTok
		}),
		mode: 'cors',
		method: 'GET'
	}
	).then(processResponse)
	.then(processActivity)
	.catch(function(error){ console.log(error);});
<commit_msg>added another API call to js file<commit_after>/*
* This code is for the PowerTokens project.
* OAuth2 flow adapted from sample code from JeremiahLee
* Uses Fetch & Fitbit Web API
*/

//VARIOUS KEYS and AUTH IDS needed
var fbTok;
var clientID = 'YOUR_ID_HERE';
var callback = 'YOUR_WEBSITE_HERE';
var authURI = 'https://www.fitbit.com/oauth2/authorize';
var authTokenReq = 'https://api.fitbit.com/oauth2/token';

// Implementing 'Implicit Auth in OATH2.0'
if (!window.location.hash){
	window.location.replace( authURI+'?response_type=token'+'&client_id='+clientID
		+'&redirect_uri='+callback+'&scope=activity');
} else{
    var fragmentQueryParameters = {};
    window.location.hash.slice(1).replace(
        new RegExp("([^?=&]+)(=([^&]*))?", "g"),
        function($0, $1, $2, $3) { fragmentQueryParameters[$1] = $3; }
    );

    fbTok = fragmentQueryParameters.access_token;
}

// HANDLE the response from FITBIT API (expect JSON)
var processResponse = function(response){
	if (!response.ok){
		throw new Error('Fitbit API request failed' + response);
	}
	var contentType = response.headers.get('content-type')
	if(contentType && contentType.indexOf("application/json") !== -1){
		document.querySelector('h2').textContent = 'JSON recieved!';
		return response.json();
	}else{
		throw new Error('JSON expected but received'+contentType);
	}
}

// HANDLE the data from an /ACTIVITY api endpoint - summary data
var processActivity = function(activity){
	document.getElementById('activityHeader').textContent = 'Fitbit - GET Activity';
	prettyAct = JSON.stringify(activity, null, 2);
	console.log(prettyAct)

	//these are the three "elements" of data returned in the activity summary
	best = JSON.stringify(activity["best"], null, 2);
	lifetime = JSON.stringify(activity["best"], null, 2);
	tracker = JSON.stringify(activity["tracker"], null, 2);

	var display = document.getElementById('display');
	display.textContent = best;
}

//HANDLE data from /Activity/Date api endpoint - get actual step count data
var processActivityWithDate = function(activity){
        //get GOALS (default 10K)
        var goalSteps = activity["goals"]["steps"];

        //get STEPS BY ACTIVITY
        var activitySteps = {};
        var actArray = activity["activities"];
        var len = actArray.length;
        for ( var i = 0; i < len; i++){
                var id = actArray[i]["logId"];
                var steps = actArray[i]["steps"];
                console.log(id+ ': '+steps);
                activitySteps[id] = steps;
        }
        var activityStepsStr = JSON.stringify(activitySteps, null, 2);

        //get SUMMARY STEPS TODAY
        var sumSteps = activity["summary"]["steps"];

        //print out the data (buggy, need to figure out how to print new lines in javascript!)
        var newpara = document.createElement("p");
        var br = document.createElement("br");
        newpara.append( 'Goal Steps:' +goalSteps);
        newpara.append(br);
        newpara.append( 'Steps by Activity: ' + activityStepsStr);
        newpara.append(br);
        newpara.append( 'Summary (total) Steps Today: '+ sumSteps);

        var nextHeader = document.getElementById("otherHeader");
        document.body.insertBefore(newpara, nextHeader);

//      console.log(JSON.stringify(activity, null, 2));
}

// Now, actually go forth and FETCH Activity Summary data
var activityURL = 'https://api.fitbit.com/1/user/-/activities.json';
fetch( activityURL,
	{
		headers: new Headers({
			'Authorization': 'Bearer ' + fbTok
		}),
		mode: 'cors',
		method: 'GET'
	}
	).then(processResponse)
	.then(processActivity)
	.catch(function(error){ console.log(error);});

//go forth and fetch Daily Activity Data (much more detail)
var date = '2017-10-10';
var activityWithDateUrl = 'https://api.fitbit.com/1/user/-/activities/date/'+date+'.json';
fetch( activityWithDateUrl,
        {
                headers: new Headers({
                        'Authorization': 'Bearer ' + fbTok
                }),
                mode: 'cors',
                method: 'GET'
        }
        ).then(processResponse)
        .then(processActivityWithDate)
        .catch(function(error){ console.log(error);});
<|endoftext|>


<commit_before>console.log('Initial piece of the Fiunis module.');<commit_msg>use a self-calling constructor as in http://habrahabr.ru/post/135027/<commit_after>var Fiunis = function(){
   if (!(this instanceof Fiunis)) return new Fiunis();
};

module.exports = new Fiunis();<|endoftext|>


<commit_before>// Find all narwhal packages with Objective-J frameworks.
exports.objj_frameworks = [];
exports.objj_debug_frameworks = [];

/*var catalog = require("narwhal/packages").catalog;
for (var name in catalog)
{
    if (!catalog.hasOwnProperty(name))
        continue;

    var info = catalog[name];
    if (!info)
        continue;

    var frameworks = info["objj-frameworks"];
    if (frameworks) {
        if (!Array.isArray(frameworks))
            frameworks = [String(frameworks)];

        exports.objj_frameworks.push.apply(exports.objj_frameworks, frameworks.map(function(aFrameworkPath) {
            return FILE.join(info.directory, aFrameworkPath);
        }));
    }

    var debugFrameworks = info["objj-debug-frameworks"];
    if (debugFrameworks) {
        if (!Array.isArray(debugFrameworks))
            debugFrameworks = [String(debugFrameworks)];

        exports.objj_debug_frameworks.push.apply(exports.objj_debug_frameworks, debugFrameworks.map(function(aFrameworkPath) {
            return FILE.join(info.directory, aFrameworkPath);
        }));
    }
}*/

// push to the front of the array lowest priority first.
OBJJ_INCLUDE_PATHS.unshift.apply(OBJJ_INCLUDE_PATHS, exports.objj_frameworks);
OBJJ_INCLUDE_PATHS.unshift.apply(OBJJ_INCLUDE_PATHS, exports.objj_debug_frameworks);

if (((typeof system !== "undefined" && system) || process).env["OBJJ_INCLUDE_PATHS"])
    OBJJ_INCLUDE_PATHS.unshift.apply(OBJJ_INCLUDE_PATHS, ((typeof system !== "undefined" && system) || process).env["OBJJ_INCLUDE_PATHS"].split(":"));

// bring the "window" object into scope.
// TODO: somehow make window object the top scope?
with (window)
{
// runs the objj repl or file provided in args
exports.run = function(args, someCompilerOptions)
{
    if (args)
    {
        function help(status) {
          console.log("usage: " + require('path').basename(process.argv[1]) + " infile [--ecma3|--ecma5] [--strict-semicolons] [--track-comments]");
          console.log("        [--include-comments] [--include-comment-line-break]");
          console.log("        [--formatter <path>]  [--indent-tab] [--indent-width <n>] [--indent-string <string>]");
          console.log("        [--track-spaces] [--track-locations] [--no-objj] [--no-preprocess]");
          console.log("        [--no-debug-symbols] [--no-type-signatures] [--generate-objj]");
          console.log("        [--no-source-map] [-x | --xml] [-m | --multifiles] [-I<objj/include/paths>]");
          console.log("        [-Dmacro[([p1, p2, ...])][=definition]] [--help]");
          process.exit(status);
        }

        // we expect args to be in the format:
        //  1) "objj" [options] path [pgm-options]
        //  2) optional "-I" args
        //  3) real or "virtual" main.j
        //  4) optional program arguments

        var options = someCompilerOptions || {},
            acornOptions = {},
            argv = args.slice(1), // copy the args since we're going to modify them
            argv0 = argv.shift(),
            multipleFiles = false;

        // We loop as long as there is an option that starts with '-'
        while (argv0 && argv0.lastIndexOf('-', 0) === 0) {
            if (argv0 === "--version")
            {
                console.log(exports.fullVersionString());
            }
            else if (argv0 == "--ecma3") acornOptions.ecmaVersion = 3;
            else if (argv0 == "--ecma5") acornOptions.ecmaVersion = 5;
            else if (argv0 == "--strict-semicolons") acornOptions.strictSemicolons = true;
            else if (argv0 == "--track-comments") acornOptions.trackComments = true;
            else if (argv0 == "--include-comment-line-break") acornOptions.trackCommentsIncludeLineBreak = true;
            else if (argv0 == "--include-comments") options.includeComments = true, acornOptions.trackComments = true;
            else if (argv0 == "--track-spaces") acornOptions.trackSpaces = true;
            else if (argv0 == "--track-locations") acornOptions.locations = true;
            else if (argv0 == "--no-objj") acornOptions.objj = false;
            else if (argv0 == "--no-preprocess") acornOptions.preprocess = false;
            else if (argv0 == "--generate-objj") options.generateObjJ = true;
            //else if (argv0 == "--silent") silent = true;
            //else if (argv0 == "--old-safari-bug") options.transformNamedFunctionDeclarationToAssignment = true;
            else if (argv0 == "--no-source-map") options.sourceMap = false;
            else if (argv0 == "--no-debug-symbols") options.includeDebugSymbols = false;
            else if (argv0 == "--no-type-signatures") options.includeTypeSignatures = false;
            else if (argv0 == "--indent-width") options.indentationSpaces = parseInt(argv.shift());
            else if (argv0 == "--indent-string") {
              if (options.indentationType) {
                  console.log("Can't have both '--indent-string' and '--indent-tab'");
                  help(1);
              } else
                  options.indentationType = argv.shift();
            }
            else if (argv0 == "--indent-tab") {
              if (options.indentationType) {
                  console.log("Can't have both '--indent-string' and '--indent-tab'");
                  help(1);
              } else {
                  options.indentationType = "\t";
                  if (!options.indentationSpaces) options.indentationSpaces = 1;
              }
            }
            else if (argv0 == "--formatter") {
            var filePath = argv.shift(),
                relative = filePath.substring(0, 1) !== '/',
                jsonFile = JSON.parse(fs.readFileSync(relative ? path.resolve(process.cwd(), filePath) : filePath,'utf8'));

                options.formatDescription = jsonFile;
            }
            //else if (argv0 == "--output" || argv0 == "-o") output = process.argv[++i];
            else if (argv0.slice(0, 2) == "-D") (acornOptions.macros || (acornOptions.macros = [])).push(argv0.slice(2));
            else if (argv0 === "-x" || argv0 === "--xml") exports.messageOutputFormatInXML = true;
            else if (argv0 === "-m" || argv0 === "--multifiles") multipleFiles = true;
            else if (argv0 == "--help") help(0);
            else if (argv0 == "-") help(1);

            else if (argv0.lastIndexOf('-I', 0) === 0)
                OBJJ_INCLUDE_PATHS.unshift.apply(OBJJ_INCLUDE_PATHS, argv0.substr(2).split(':'));

            argv0 = argv.shift();
        }
    }

    if (argv0)
    {
        var mainFilePath = PATH.resolve(argv0);

        var callback = function() {
            if (typeof main === "function")
            {
                var arguments = [argv0];
                if (argv && argv.length > 0)
                    arguments = arguments.concat(argv);
                main(arguments);
            }
            else if (multipleFiles && (argv0 = argv.shift())) {
                mainFilePath = PATH.resolve(argv0);
                exports.make_narwhal_factory(mainFilePath, null, null, callback)(require, { }, module, typeof system !== "undefined" && system, console.log);
            }
            else
            {
                console.error("No main function is found for " + mainFilePath);
            }
        }

        // resolve and read all links
        while ((NODEFILE.existsSync(mainFilePath) && NODEFILE.lstatSync(mainFilePath).isSymbolicLink())) {
            mainFilePath = PATH.resolve(NODEFILE.readlinkSync(mainFilePath))
        }

        options.acornOptions = acornOptions;
        StaticResource.setCurrentCompilerFlags(options);
        exports.make_narwhal_factory(mainFilePath, null, null, callback)(require, { }, module, typeof system !== "undefined" && system, console.log);

        require("./timeout").serviceTimeouts();
    }
    else
    {
        exports.repl();
    }
}

exports.repl = function()
{
    var READLINE = require('readline-history');
    READLINE.createInterface({
        path: "/tmp/history",
        maxLength: 1234,
        input: process.stdin,
        output: process.stdout,
        next: function(rli) {
            rli.setPrompt("objj> ");
            rli.prompt();
            rli.on('line',function(line) {
                try {
                    var result = exports.objj_eval(line);
                    if (result !== undefined)
                        console.log(result);
                } catch (e) {
                    console.log(e);
                }
                require("./timeout").serviceTimeouts();
            });
        }
    });
};

// creates a narwhal factory function in the objj module scope
exports.make_narwhal_factory = function(path, basePath, filenameTranslateDictionary, aCallback)
{
    return function(require, exports, module, system, print)
    {
        Executable.setCommonJSParameters("require", "exports", "module", "system", "print", "window");
        Executable.setCommonJSArguments(require, exports, module, typeof system !== "undefined" && system, print, window);
        filenameTranslateDictionary && Executable.setFilenameTranslateDictionary(filenameTranslateDictionary);
        Executable.fileImporterForURL(basePath ? basePath : PATH.dirname(path))(path, YES, aCallback);
    }
};

} // end "with"

var pkg = null;
function getPackage() {
    if (!pkg)
        //pkg = JSON.parse(FILE.path(module.filename).directory().directory().join("package.json").read({ charset : "UTF-8" }));
        pkg = JSON.parse(NODEFILE.readFileSync(PATH.join("..", "..","package.json"), 'utf8'));
    return pkg;
}

exports.version = function() { return getPackage()["version"]; }
exports.revision = function() { return getPackage()["cappuccino-revision"]; }
exports.timestamp = function() { return new Date(getPackage()["cappuccino-timestamp"]); }

exports.fullVersionString = function() {
    var rev = exports.revision();
    return sprintf("objective-j %s (%04d-%02d-%02d %s)",
        exports.version(),
        exports.timestamp().getUTCFullYear(),
        exports.timestamp().getUTCMonth()+1,
        exports.timestamp().getUTCDate(),
        rev ? rev.slice(0,6) : null
    );
}

exports.utils = require("@objj/utils");

global.ObjectiveJ = {};

for (var key in exports)
    if (Object.prototype.hasOwnProperty.call(exports, key))
        global.ObjectiveJ[key] = exports[key];

if (require.main == module.id)
    exports.run((typeof system !== "undefined" && system.args) || process.argv);
});<commit_msg>Resolve relative symlinks in objj infile path.<commit_after>// Find all narwhal packages with Objective-J frameworks.
exports.objj_frameworks = [];
exports.objj_debug_frameworks = [];

/*var catalog = require("narwhal/packages").catalog;
for (var name in catalog)
{
    if (!catalog.hasOwnProperty(name))
        continue;

    var info = catalog[name];
    if (!info)
        continue;

    var frameworks = info["objj-frameworks"];
    if (frameworks) {
        if (!Array.isArray(frameworks))
            frameworks = [String(frameworks)];

        exports.objj_frameworks.push.apply(exports.objj_frameworks, frameworks.map(function(aFrameworkPath) {
            return FILE.join(info.directory, aFrameworkPath);
        }));
    }

    var debugFrameworks = info["objj-debug-frameworks"];
    if (debugFrameworks) {
        if (!Array.isArray(debugFrameworks))
            debugFrameworks = [String(debugFrameworks)];

        exports.objj_debug_frameworks.push.apply(exports.objj_debug_frameworks, debugFrameworks.map(function(aFrameworkPath) {
            return FILE.join(info.directory, aFrameworkPath);
        }));
    }
}*/

// push to the front of the array lowest priority first.
OBJJ_INCLUDE_PATHS.unshift.apply(OBJJ_INCLUDE_PATHS, exports.objj_frameworks);
OBJJ_INCLUDE_PATHS.unshift.apply(OBJJ_INCLUDE_PATHS, exports.objj_debug_frameworks);

if (((typeof system !== "undefined" && system) || process).env["OBJJ_INCLUDE_PATHS"])
    OBJJ_INCLUDE_PATHS.unshift.apply(OBJJ_INCLUDE_PATHS, ((typeof system !== "undefined" && system) || process).env["OBJJ_INCLUDE_PATHS"].split(":"));

// bring the "window" object into scope.
// TODO: somehow make window object the top scope?
with (window)
{
// runs the objj repl or file provided in args
exports.run = function(args, someCompilerOptions)
{
    if (args)
    {
        function help(status) {
          console.log("usage: " + require('path').basename(process.argv[1]) + " infile [--ecma3|--ecma5] [--strict-semicolons] [--track-comments]");
          console.log("        [--include-comments] [--include-comment-line-break]");
          console.log("        [--formatter <path>]  [--indent-tab] [--indent-width <n>] [--indent-string <string>]");
          console.log("        [--track-spaces] [--track-locations] [--no-objj] [--no-preprocess]");
          console.log("        [--no-debug-symbols] [--no-type-signatures] [--generate-objj]");
          console.log("        [--no-source-map] [-x | --xml] [-m | --multifiles] [-I<objj/include/paths>]");
          console.log("        [-Dmacro[([p1, p2, ...])][=definition]] [--help]");
          process.exit(status);
        }

        // we expect args to be in the format:
        //  1) "objj" [options] path [pgm-options]
        //  2) optional "-I" args
        //  3) real or "virtual" main.j
        //  4) optional program arguments

        var options = someCompilerOptions || {},
            acornOptions = {},
            argv = args.slice(1), // copy the args since we're going to modify them
            argv0 = argv.shift(),
            multipleFiles = false;

        // We loop as long as there is an option that starts with '-'
        while (argv0 && argv0.lastIndexOf('-', 0) === 0) {
            if (argv0 === "--version")
            {
                console.log(exports.fullVersionString());
            }
            else if (argv0 == "--ecma3") acornOptions.ecmaVersion = 3;
            else if (argv0 == "--ecma5") acornOptions.ecmaVersion = 5;
            else if (argv0 == "--strict-semicolons") acornOptions.strictSemicolons = true;
            else if (argv0 == "--track-comments") acornOptions.trackComments = true;
            else if (argv0 == "--include-comment-line-break") acornOptions.trackCommentsIncludeLineBreak = true;
            else if (argv0 == "--include-comments") options.includeComments = true, acornOptions.trackComments = true;
            else if (argv0 == "--track-spaces") acornOptions.trackSpaces = true;
            else if (argv0 == "--track-locations") acornOptions.locations = true;
            else if (argv0 == "--no-objj") acornOptions.objj = false;
            else if (argv0 == "--no-preprocess") acornOptions.preprocess = false;
            else if (argv0 == "--generate-objj") options.generateObjJ = true;
            //else if (argv0 == "--silent") silent = true;
            //else if (argv0 == "--old-safari-bug") options.transformNamedFunctionDeclarationToAssignment = true;
            else if (argv0 == "--no-source-map") options.sourceMap = false;
            else if (argv0 == "--no-debug-symbols") options.includeDebugSymbols = false;
            else if (argv0 == "--no-type-signatures") options.includeTypeSignatures = false;
            else if (argv0 == "--indent-width") options.indentationSpaces = parseInt(argv.shift());
            else if (argv0 == "--indent-string") {
              if (options.indentationType) {
                  console.log("Can't have both '--indent-string' and '--indent-tab'");
                  help(1);
              } else
                  options.indentationType = argv.shift();
            }
            else if (argv0 == "--indent-tab") {
              if (options.indentationType) {
                  console.log("Can't have both '--indent-string' and '--indent-tab'");
                  help(1);
              } else {
                  options.indentationType = "\t";
                  if (!options.indentationSpaces) options.indentationSpaces = 1;
              }
            }
            else if (argv0 == "--formatter") {
            var filePath = argv.shift(),
                relative = filePath.substring(0, 1) !== '/',
                jsonFile = JSON.parse(fs.readFileSync(relative ? path.resolve(process.cwd(), filePath) : filePath,'utf8'));

                options.formatDescription = jsonFile;
            }
            //else if (argv0 == "--output" || argv0 == "-o") output = process.argv[++i];
            else if (argv0.slice(0, 2) == "-D") (acornOptions.macros || (acornOptions.macros = [])).push(argv0.slice(2));
            else if (argv0 === "-x" || argv0 === "--xml") exports.messageOutputFormatInXML = true;
            else if (argv0 === "-m" || argv0 === "--multifiles") multipleFiles = true;
            else if (argv0 == "--help") help(0);
            else if (argv0 == "-") help(1);

            else if (argv0.lastIndexOf('-I', 0) === 0)
                OBJJ_INCLUDE_PATHS.unshift.apply(OBJJ_INCLUDE_PATHS, argv0.substr(2).split(':'));

            argv0 = argv.shift();
        }
    }

    if (argv0)
    {
        var mainFilePath = PATH.resolve(argv0);

        var callback = function() {
            if (typeof main === "function")
            {
                var arguments = [argv0];
                if (argv && argv.length > 0)
                    arguments = arguments.concat(argv);
                main(arguments);
            }
            else if (multipleFiles && (argv0 = argv.shift())) {
                mainFilePath = PATH.resolve(argv0);
                exports.make_narwhal_factory(mainFilePath, null, null, callback)(require, { }, module, typeof system !== "undefined" && system, console.log);
            }
            else
            {
                console.error("No main function is found for " + mainFilePath);
            }
        }

        // resolve and read all links
        while ((NODEFILE.existsSync(mainFilePath) && NODEFILE.lstatSync(mainFilePath).isSymbolicLink())) {
            var linkPath = NODEFILE.readlinkSync(mainFilePath);
            if (!PATH.isAbsolute(linkPath)) {
               mainFilePath = PATH.join(PATH.dirname(mainFilePath), linkPath);
            }
            mainFilePath = PATH.resolve(mainFilePath);
        }

        options.acornOptions = acornOptions;
        StaticResource.setCurrentCompilerFlags(options);
        exports.make_narwhal_factory(mainFilePath, null, null, callback)(require, { }, module, typeof system !== "undefined" && system, console.log);

        require("./timeout").serviceTimeouts();
    }
    else
    {
        exports.repl();
    }
}

exports.repl = function()
{
    var READLINE = require('readline-history');
    READLINE.createInterface({
        path: "/tmp/history",
        maxLength: 1234,
        input: process.stdin,
        output: process.stdout,
        next: function(rli) {
            rli.setPrompt("objj> ");
            rli.prompt();
            rli.on('line',function(line) {
                try {
                    var result = exports.objj_eval(line);
                    if (result !== undefined)
                        console.log(result);
                } catch (e) {
                    console.log(e);
                }
                require("./timeout").serviceTimeouts();
            });
        }
    });
};

// creates a narwhal factory function in the objj module scope
exports.make_narwhal_factory = function(path, basePath, filenameTranslateDictionary, aCallback)
{
    return function(require, exports, module, system, print)
    {
        Executable.setCommonJSParameters("require", "exports", "module", "system", "print", "window");
        Executable.setCommonJSArguments(require, exports, module, typeof system !== "undefined" && system, print, window);
        filenameTranslateDictionary && Executable.setFilenameTranslateDictionary(filenameTranslateDictionary);
        Executable.fileImporterForURL(basePath ? basePath : PATH.dirname(path))(path, YES, aCallback);
    }
};

} // end "with"

var pkg = null;
function getPackage() {
    if (!pkg)
        //pkg = JSON.parse(FILE.path(module.filename).directory().directory().join("package.json").read({ charset : "UTF-8" }));
        pkg = JSON.parse(NODEFILE.readFileSync(PATH.join("..", "..","package.json"), 'utf8'));
    return pkg;
}

exports.version = function() { return getPackage()["version"]; }
exports.revision = function() { return getPackage()["cappuccino-revision"]; }
exports.timestamp = function() { return new Date(getPackage()["cappuccino-timestamp"]); }

exports.fullVersionString = function() {
    var rev = exports.revision();
    return sprintf("objective-j %s (%04d-%02d-%02d %s)",
        exports.version(),
        exports.timestamp().getUTCFullYear(),
        exports.timestamp().getUTCMonth()+1,
        exports.timestamp().getUTCDate(),
        rev ? rev.slice(0,6) : null
    );
}

exports.utils = require("@objj/utils");

global.ObjectiveJ = {};

for (var key in exports)
    if (Object.prototype.hasOwnProperty.call(exports, key))
        global.ObjectiveJ[key] = exports[key];

if (require.main == module.id)
    exports.run((typeof system !== "undefined" && system.args) || process.argv);
});<|endoftext|>


<commit_before>'use strict';
var commenti;
var ss;

function put(s) {
	ss.push(s)
}

function endsWith(s, t) {
	return s[s.length - 1] == t
}

function hasBlank() {
	if (!ss.length)
		return false
	if (ss.length == 1)
		return ss[ss.length - 1] == '\n'
	return endsWith(ss[ss.length - 2], '\n') && ss[ss.length - 1] == '\n'
}

function blank() {
	if (!hasBlank())
		put('\n')
}

function indent(level) {
	while (level--)
		put(options.indent)
}

function comment(a, level) {
	while (commenti < comments.length && comments[commenti].start < a.start) {
		var c = comments[commenti++];
		indent(level)
		if (c.type == 'Line')
			put('//' + c.value)
		else
			put('/*' + c.value + '*/')
		put('\n')
	}
}

function block(a, level) {
	put('{\n')
	if (a.type == 'BlockStatement')
		for (var b of a.body) {
			comment(b)
			stmt(b, level + 1)
		} else
			stmt(a, level + 1)
	indent(level)
	put('}')
}

function expr(a, level) {
	switch (a.type) {
	case 'ArrayExpression':
		if (!a.elements.length) {
			put('[]')
			break
		}
		put('[\n')
		for (var b of a.elements) {
			indent(level + 1)
			expr(b, level + 1)
			put(',\n')
		}
		indent(level)
		put(']')
		break
	case 'ArrowFunctionExpression':
		if (a.params.length == 1)
			expr(a.params[0], level)
		else {
			put('(')
			for (var i = 0; i < a.params.length; i++) {
				if (i)
					put(', ')
				expr(a.params[i], level)
			}
			put(')')
		}
		put(' => ')
		if (a.body.type == 'BlockStatement')
			block(a.body, level)
		else
			expr(a.body, level)
		break
	case 'AssignmentExpression':
	case 'BinaryExpression':
	case 'LogicalExpression':
		expr(a.left, level)
		if (options.eq)
			switch (a.operator) {
			case '==':
				a.operator = '==='
				break
			case '!=':
				a.operator = '!=='
				break
			}
		put(' ' + a.operator + ' ')
		expr(a.right, level)
		break
	case 'CallExpression':
		expr(a.callee, level)
		put('(')
		for (var i = 0; i < a.arguments.length; i++) {
			if (i)
				put(', ')
			expr(a.arguments[i], level)
		}
		put(')')
		break
	case 'ConditionalExpression':
		expr(a.test, level)
		put(' ? ')
		expr(a.consequent, level)
		put(' : ')
		expr(a.alternate, level)
		break
	case 'FunctionExpression':
		put('function ')
		if (a.id)
			put(a.id.name)
		put('(')
		for (var i = 0; i < a.params.length; i++) {
			if (i)
				put(', ')
			expr(a.params[i], level)
		}
		put(') ')
		block(a.body, level)
		break
	case 'Identifier':
		put(a.name)
		break
	case 'Literal':
		put(a.raw)
		break
	case 'MemberExpression':
		expr(a.object, level)
		if (a.computed) {
			put('[')
			expr(a.property, level)
			put(']')
		} else {
			put('.')
			expr(a.property, level)
		}
		break
	case 'ObjectExpression':
		if (!a.properties.length) {
			put('{}')
			break
		}
		put('{\n')
		for (var b of a.properties) {
			indent(level + 1)
			expr(b, level + 1)
			put(',\n')
		}
		indent(level)
		put('}')
		break
	case 'ParenthesizedExpression':
		put('(')
		expr(a.expression, level)
		put(')')
		break
	case 'Property':
		expr(a.key, level)
		put(': ')
		expr(a.value, level)
		break
	case 'SequenceExpression':
		for (var i = 0; i < a.expressions.length; i++) {
			if (i)
				put(', ')
			expr(a.expressions[i], level)
		}
		break
	case 'UnaryExpression':
		put(a.operator)
		expr(a.argument, level)
		break
	case 'UpdateExpression':
		if (a.prefix) {
			put(a.operator)
			expr(a.argument, level)
		} else {
			expr(a.argument, level)
			put(a.operator)
		}
		break
	case 'VariableDeclaration':
		put('var ')
		for (var i = 0; i < a.declarations.length; i++) {
			if (i)
				put(', ')
			expr(a.declarations[i], level)
		}
		break
	case 'VariableDeclarator':
		put(a.id.name)
		if (a.init) {
			put(' = ')
			expr(a.init, level)
		}
		break
	default:
		console.assert(0, a)
	}
}

function stmt(a, level) {
	switch (a.type) {
	case 'BlockStatement':
		for (var b of a.body)
			stmt(b, level + 1)
		break
	case 'BreakStatement':
		indent(level)
		put('break')
		if (a.label) {
			put(' ')
			put(a.label.name)
		}
		put(';\n')
		break
	case 'ContinueStatement':
		indent(level)
		put('continue')
		if (a.label) {
			put(' ')
			put(a.label.name)
		}
		put(';\n')
		break
	case 'DoWhileStatement':
		indent(level)
		put('do ')
		block(a.body, level)
		indent(level)
		put(' while (')
		expr(a.test, level)
		put(');\n')
		break
	case 'EmptyStatement':
		break
	case 'ExpressionStatement':
		indent(level)
		expr(a.expression, level)
		put(';\n')
		break
	case 'ForInStatement':
		indent(level)
		put('for (')
		expr(a.left, level)
		put(' in ')
		expr(a.right, level)
		put(') ')
		block(a.body, level)
		put('\n')
		break
	case 'ForOfStatement':
		indent(level)
		put('for (')
		expr(a.left, level)
		put(' of ')
		expr(a.right, level)
		put(') ')
		block(a.body, level)
		put('\n')
		break
	case 'ForStatement':
		indent(level)
		put('for (')
		expr(a.init, level)
		put('; ')
		expr(a.test, level)
		put('; ')
		expr(a.update, level)
		put(') ')
		block(a.body, level)
		put('\n')
		break
	case 'FunctionDeclaration':
		blank()
		indent(level)
		put('function ' + a.id.name + '(')
		for (var i = 0; i < a.params.length; i++) {
			if (i)
				put(', ')
			expr(a.params[i], level)
		}
		put(') ')
		block(a.body, level)
		put('\n')
		blank()
		break
	case 'IfStatement':
		indent(level)
		put('if (')
		expr(a.test, level)
		put(') ')
		block(a.consequent, level)
		if (a.alternate) {
			put(' else ')
			block(a.alternate, level)
		}
		put('\n')
		break
	case 'LabeledStatement':
		stmt(a.body, loop, a.label.name)
		break
	case 'Program':
		for (var b of a.body) {
			comment(b)
			stmt(b, level)
		}
		break
	case 'ReturnStatement':
		indent(level)
		put('return')
		if (a.argument) {
			put(' ')
			expr(a.argument, level)
		}
		put(';\n')
		break
	case 'SwitchStatement':
		indent(level)
		put('switch (')
		expr(a.discriminant, level)
		put(') {\n')
		for (var c of a.cases) {
			indent(level)
			if (c.test) {
				put('case ')
				expr(c.test, level)
			} else
				put('default')
			put(':\n')
			for (var b of c.consequent)
				stmt(b, level + 1)
		}
		indent(level)
		put('}\n')
		break
	case 'TryStatement':
		indent(level)
		put('try ')
		block(a.block, level)
		if (a.handler) {
			put(' catch (')
			expr(a.handler.param, level)
			put(') ')
			block(a.handler.body, level)
		}
		if (a.finalizer) {
			put(' finally ')
			block(a.finalizer, level)
		}
		break
	case 'VariableDeclaration':
		indent(level)
		put('var ')
		for (var i = 0; i < a.declarations.length; i++) {
			if (i)
				put(', ')
			expr(a.declarations[i], level)
		}
		put(';\n')
		break
	case 'WhileStatement':
		indent(level)
		put('while (')
		expr(a.test, level)
		put(') ')
		block(a.body, level)
		put('\n')
		break
	default:
		console.assert(0, a)
	}
}

function format(a, comments, options) {
	global.comments = comments || []
	global.options = options || {
		indent: '\t'
	}
	commenti = 0
	ss = []
	stmt(a, 0)
	if (hasBlank())
		ss.pop()
	return ss.join('')
}
exports.format = format
<commit_msg>throw<commit_after>'use strict';
var commenti;
var ss;

function put(s) {
	ss.push(s)
}

function endsWith(s, t) {
	return s[s.length - 1] == t
}

function hasBlank() {
	if (!ss.length)
		return false
	if (ss.length == 1)
		return ss[ss.length - 1] == '\n'
	return endsWith(ss[ss.length - 2], '\n') && ss[ss.length - 1] == '\n'
}

function blank() {
	if (!hasBlank())
		put('\n')
}

function indent(level) {
	while (level--)
		put(options.indent)
}

function comment(a, level) {
	while (commenti < comments.length && comments[commenti].start < a.start) {
		var c = comments[commenti++];
		indent(level)
		if (c.type == 'Line')
			put('//' + c.value)
		else
			put('/*' + c.value + '*/')
		put('\n')
	}
}

function block(a, level) {
	put('{\n')
	if (a.type == 'BlockStatement')
		for (var b of a.body) {
			comment(b)
			stmt(b, level + 1)
		} else
			stmt(a, level + 1)
	indent(level)
	put('}')
}

function expr(a, level) {
	switch (a.type) {
	case 'ArrayExpression':
		if (!a.elements.length) {
			put('[]')
			break
		}
		put('[\n')
		for (var b of a.elements) {
			indent(level + 1)
			expr(b, level + 1)
			put(',\n')
		}
		indent(level)
		put(']')
		break
	case 'ArrowFunctionExpression':
		if (a.params.length == 1)
			expr(a.params[0], level)
		else {
			put('(')
			for (var i = 0; i < a.params.length; i++) {
				if (i)
					put(', ')
				expr(a.params[i], level)
			}
			put(')')
		}
		put(' => ')
		if (a.body.type == 'BlockStatement')
			block(a.body, level)
		else
			expr(a.body, level)
		break
	case 'AssignmentExpression':
	case 'BinaryExpression':
	case 'LogicalExpression':
		expr(a.left, level)
		if (options.eq)
			switch (a.operator) {
			case '==':
				a.operator = '==='
				break
			case '!=':
				a.operator = '!=='
				break
			}
		put(' ' + a.operator + ' ')
		expr(a.right, level)
		break
	case 'CallExpression':
		expr(a.callee, level)
		put('(')
		for (var i = 0; i < a.arguments.length; i++) {
			if (i)
				put(', ')
			expr(a.arguments[i], level)
		}
		put(')')
		break
	case 'ConditionalExpression':
		expr(a.test, level)
		put(' ? ')
		expr(a.consequent, level)
		put(' : ')
		expr(a.alternate, level)
		break
	case 'FunctionExpression':
		put('function ')
		if (a.id)
			put(a.id.name)
		put('(')
		for (var i = 0; i < a.params.length; i++) {
			if (i)
				put(', ')
			expr(a.params[i], level)
		}
		put(') ')
		block(a.body, level)
		break
	case 'Identifier':
		put(a.name)
		break
	case 'Literal':
		put(a.raw)
		break
	case 'MemberExpression':
		expr(a.object, level)
		if (a.computed) {
			put('[')
			expr(a.property, level)
			put(']')
		} else {
			put('.')
			expr(a.property, level)
		}
		break
	case 'ObjectExpression':
		if (!a.properties.length) {
			put('{}')
			break
		}
		put('{\n')
		for (var b of a.properties) {
			indent(level + 1)
			expr(b, level + 1)
			put(',\n')
		}
		indent(level)
		put('}')
		break
	case 'ParenthesizedExpression':
		put('(')
		expr(a.expression, level)
		put(')')
		break
	case 'Property':
		expr(a.key, level)
		put(': ')
		expr(a.value, level)
		break
	case 'SequenceExpression':
		for (var i = 0; i < a.expressions.length; i++) {
			if (i)
				put(', ')
			expr(a.expressions[i], level)
		}
		break
	case 'UnaryExpression':
		put(a.operator)
		expr(a.argument, level)
		break
	case 'UpdateExpression':
		if (a.prefix) {
			put(a.operator)
			expr(a.argument, level)
		} else {
			expr(a.argument, level)
			put(a.operator)
		}
		break
	case 'VariableDeclaration':
		put('var ')
		for (var i = 0; i < a.declarations.length; i++) {
			if (i)
				put(', ')
			expr(a.declarations[i], level)
		}
		break
	case 'VariableDeclarator':
		put(a.id.name)
		if (a.init) {
			put(' = ')
			expr(a.init, level)
		}
		break
	default:
		console.assert(0, a)
	}
}

function stmt(a, level) {
	switch (a.type) {
	case 'BlockStatement':
		for (var b of a.body)
			stmt(b, level + 1)
		break
	case 'BreakStatement':
		indent(level)
		put('break')
		if (a.label) {
			put(' ')
			put(a.label.name)
		}
		put(';\n')
		break
	case 'ContinueStatement':
		indent(level)
		put('continue')
		if (a.label) {
			put(' ')
			put(a.label.name)
		}
		put(';\n')
		break
	case 'DoWhileStatement':
		indent(level)
		put('do ')
		block(a.body, level)
		indent(level)
		put(' while (')
		expr(a.test, level)
		put(');\n')
		break
	case 'EmptyStatement':
		break
	case 'ExpressionStatement':
		indent(level)
		expr(a.expression, level)
		put(';\n')
		break
	case 'ForInStatement':
		indent(level)
		put('for (')
		expr(a.left, level)
		put(' in ')
		expr(a.right, level)
		put(') ')
		block(a.body, level)
		put('\n')
		break
	case 'ForOfStatement':
		indent(level)
		put('for (')
		expr(a.left, level)
		put(' of ')
		expr(a.right, level)
		put(') ')
		block(a.body, level)
		put('\n')
		break
	case 'ForStatement':
		indent(level)
		put('for (')
		expr(a.init, level)
		put('; ')
		expr(a.test, level)
		put('; ')
		expr(a.update, level)
		put(') ')
		block(a.body, level)
		put('\n')
		break
	case 'FunctionDeclaration':
		blank()
		indent(level)
		put('function ' + a.id.name + '(')
		for (var i = 0; i < a.params.length; i++) {
			if (i)
				put(', ')
			expr(a.params[i], level)
		}
		put(') ')
		block(a.body, level)
		put('\n')
		blank()
		break
	case 'IfStatement':
		indent(level)
		put('if (')
		expr(a.test, level)
		put(') ')
		block(a.consequent, level)
		if (a.alternate) {
			put(' else ')
			block(a.alternate, level)
		}
		put('\n')
		break
	case 'LabeledStatement':
		stmt(a.body, loop, a.label.name)
		break
	case 'Program':
		for (var b of a.body) {
			comment(b)
			stmt(b, level)
		}
		break
	case 'ReturnStatement':
		indent(level)
		put('return')
		if (a.argument) {
			put(' ')
			expr(a.argument, level)
		}
		put(';\n')
		break
	case 'SwitchStatement':
		indent(level)
		put('switch (')
		expr(a.discriminant, level)
		put(') {\n')
		for (var c of a.cases) {
			indent(level)
			if (c.test) {
				put('case ')
				expr(c.test, level)
			} else
				put('default')
			put(':\n')
			for (var b of c.consequent)
				stmt(b, level + 1)
		}
		indent(level)
		put('}\n')
		break
	case 'ThrowStatement':
		indent(level)
		put('throw ')
		expr(a.argument, level)
		put(';\n')
		break
	case 'TryStatement':
		indent(level)
		put('try ')
		block(a.block, level)
		if (a.handler) {
			put(' catch (')
			expr(a.handler.param, level)
			put(') ')
			block(a.handler.body, level)
		}
		if (a.finalizer) {
			put(' finally ')
			block(a.finalizer, level)
		}
		break
	case 'VariableDeclaration':
		indent(level)
		put('var ')
		for (var i = 0; i < a.declarations.length; i++) {
			if (i)
				put(', ')
			expr(a.declarations[i], level)
		}
		put(';\n')
		break
	case 'WhileStatement':
		indent(level)
		put('while (')
		expr(a.test, level)
		put(') ')
		block(a.body, level)
		put('\n')
		break
	default:
		console.assert(0, a)
	}
}

function format(a, comments, options) {
	global.comments = comments || []
	global.options = options || {
		indent: '\t'
	}
	commenti = 0
	ss = []
	stmt(a, 0)
	if (hasBlank())
		ss.pop()
	return ss.join('')
}
exports.format = format
<|endoftext|>


<commit_before>/* Final Score MC Ban Manager
 *
 */

(function($){

    /* ----------------------------- *
     *   DATA STRUCTURE OBJECT       *
     * ----------------------------- */

    // Convenience constructor
    var info = function(options) {
        return new DataStructure(options);
    };

    // Constructor
    var DataStructure = function(options) {
        var datum, i;

        datum = $.extend({
            // Default Options
            type:"text",
            format:"none",
            name:null,
            after:"
",
            options:[],
            showEmpty:true
        }, options);

        for ( i in datum ) {
            this[i] = datum[i];
        }

        return this;
    };

    info.fn = DataStructure.prototype = {

        // Data Structure Functions

        /**
         * Takes a data structre and turns into into a set of HTML tags.
         * @parm {String} value The value of the data structure.
         * @parm {String} name The name of the data structure.
         * @parm {int} idNum An ID number to attach to the html tags.
         * @return A jQuery object containing the HTML nodes for the data structure.
         */
        toHTML : function(value, name, idNum) {
            /* Types:
             * - text
             * - label
             * - date
             * - textarea
             * - select
             * - int
             * - checkbox
             */
            var showEmpty, html, id = name + "_" + idNum;

            // See if this field should be shown when empty
            if(typeof(this.showEmpty) === 'function') {
                showEmpty = this.showEmpty(idNum);
            } else {
                showEmpty = this.showEmpty;
            }

            if( ! showEmpty ){
                if(value == null){
                    // Don't show empty fields
                    return "";
                }
            }

            value = this.formatValue(value);

            if(this.type == "label"){
                // Non editable label
                return "" + this.name + "" + value + "" + this.after;

            }

            html = $("").text(this.name).attr("for", id);

            if(this.type == "textarea"){
                // Text area
                html = html.add($("<textarea>").attr({
                    "name": name,
                    "id"  : id
                }).text(value));

            } else if(this.type == "select"){
                // Drop Down
                var sel = $("<select>").attr({
                    "name": name,
                    "id"  : id
                });

                var i;
                for(i in this.options){
                    i = this.options[i];
                    if(i.label == null){
                        sel.append($("<option>").text(i));
                    } else {
                        sel.append($("<option>").attr("value", i.value).text(i.label));
                    }
                }
                sel.val(value);

                html = html.add(sel);

            } else if(this.type == "text" || this.type == "int"){
                // Text and int types
                var input = $("<input>").val(value).attr({
                    'type' : "text",
                    'name' : name,
                    'id'  : id
                });

                if(this.type == "int"){
                    input.addClass("int");
                }
                html = html.add(input);

            } else if(this.type == "date"){
                // Date field
                html = html.add($("<input>").attr({
                    'type' : "text",
                    'name' : name,
                    'id'  : id
                }).val(value).datepicker({
                   showOn: "both",
                   // TODO get my own calendar icon
                   buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
                   buttonImageOnly : true,
                   dateFormat : "yy-mm-dd"
                }));

            } else if(this.type == "checkbox"){
                // Checkbox
                html = html.add($("<input>").attr({
                    'type' : 'checkbox',
                    'name' : name,
                    'id'  : id
                }));

            } else {
                // Unknown
                console.log("Unkown Type: " + this.type);
                return "";
            }

            return html.add($(this.after));
        },

        formatValue : function(value) {
            // Null should be empty strings
            if(value == null)
                return "";

            if(this.format == "date"){
                // Do date formating (change from yy-mm-dd hh:mm:ss to yy-mm-dd)
                value = value.substring(0, value.indexOf(" "));
                return value;
            }

            // No formating needed, return the value
            return value;
        }
    };

    /* ----------------------------- *
     *      DATA STRUCTURES          *
     * ----------------------------- */

    // Incident Data Structure
    var incident = {
        moderator : info({
            name:"Moderator",
            type:"label"
        }),
        created_date : info({
            type:"label",
            format:"date",
            name:"Created Date",
            after:""
        }),
        incident_date : info({
            type:"date",
            format:"date",
            name:"Incident Date"
        }),
        incident_type : info({
            name: "Incident Type"
        }),
        notes : info({
            name: "Notes",
            type: "textarea"
        }),
        action_taken : info({
            type:"textarea",
            name:"Action Taken",
            after:"
Key Location
"
        }),
        world : info({
            name: "World",
            type: "select",
            options:[{
                        value:"",
                        label:""
                    },
                    {
                        value:"world",
                        label:"Alpha"
                    },
                    {
                        value:"world3",
                        label:"Delta"
                    },
                    {
                        value:"world4",
                        label:"Gamma"
                    }],
            after: ""
        }),
        coord_x : info({
            type: "int",
            name: "X",
            after:""
        }),
        coord_y : info({
            type: "int",
            name: "Y",
            after:""
        }),
        coord_z : info({
            type: "int",
            name: "Z"
        }),
        appeal_date : info({
            type:  "label",
            format:"date",
            name:  "Appeal Date",
            showEmpty:false
        }),
        appeal : info({
            name: "Appeal",
            type: "label",
            showEmpty:false
        }),
        appeal_response : info({
            type: "textarea",
            name: "Appeal Response",
            showEmpty:false // TODO: This should only be false when there is no appeal.
        })
    };

    /* ----------------------------- *
     *          FUNCTIONS            *
     * ----------------------------- */

    /**
     * Displays a message to a user in a jQuery UI highlight box.
     * @param {String} message The message to display.
     */
    function displayMessage(message) {
        // Display the message
        $("#highlight-msg").text(message);
        $("#highlight").slideDown();

        // Display for four seconds
        setTimeout(function(){$("#highlight").slideUp();}, 4000);
    }

    /**
     * Sets up an field to be an jQuery UI AutoComplete enabled field.
     * @param {String} input The jQuery selector to apply the autocomplete to.
     * @param {String} value The jQuery selector for the element to set the
     * autocompletes value to.
     * @param {Function} callback A function to call after the a value has been
     * selected from the autocomplete options. Can be null.
     * @param {String} emptyLabel The option text to display when no results are
     * found.
     * @param {Function} emptyCallback A function to call if the no result option
     * is selected. Can be null.
     */
    function lookup(input, value, callback, emptyLabel, emptyCallback) {
        $(input).autocomplete({
            source : function (request, response) {
                $.get("fsmcbm.php",{
                        term: request.term
                    }, function (data) {
                        if (data.length == 0) {
                            data.push({
                                'value': 0,
                                'label': emptyLabel
                            });
                        }
                        response(data);
                    }, 'json');
            },
            minLength : 2,
            select : function( event, ui ){
                if(ui.item.value == 0){
                    if(emptyCallback != null){
                        emptyCallback();
                    }
                } else {
                    $(this).val(ui.item.label);
                    $(value).val(ui.item.value);

                    if(callback != null){
                        callback();
                    }
                }
                return false;
            }
        });
    }

    /**
     *  Retrieves the user information, and then displays it into the manage
     *  users tab.
     */
    function getInformation() {
        $.get(
            "fsmcbm.php",
            { 'lookup': $("#lookup-user_id").val() },
            function(data){
                if(data.error == null){

                    // Empty out any previous incidents
                    var incidents = $("#incident-info").empty();

                    // Fill in the fields
                    $.each(data.user, function(index, value){
                        var field = $("#user-info-" + index);
                        if(field.attr("type") == "checkbox"){
                            field.prop("checked", value == "1");
                        } else {
                            field.val(value);
                        }
                    });

                    if(data.incident != null){
                        // Attach all the incidents
                        for(var i=0; i<data.incident.length; i++){
                            var datum = data.incident[i];

                            var div = $("
").addClass("form").attr("id", "i-" + datum.id);

                            $.each(incident, function(index, value){
                                div.append(value.toHTML(datum[index], index, datum.id));
                            });

                            // Add the save and cancel buttons
                            div.append($("<button>").text("Save").attr("id","i-s-" + datum.id).button().click(function(){
                                // TODO save incident button code here
                            }));
                            div.append($("<button>").text("Cancel").attr("id","i-c-" + datum.id).button().click(function(){
                                // TODO cancel incident save button code here
                            }));

                            div.appendTo(incidents);
                        }
                    }

                    // Switch to the manage tab
                    $("#tabs").tabs("option", "active", 0);

                } else {
                    // Error
                    handleError(data.error);
                }
            },
            'json'
        );
    }

    /**
     * Handles errors.
     * @param {String} error The error message. Optional.
     */
    function handleError(error) {
        // Log the error message
        console.error(error);

        // Display the error message
        $("#error-msg").text(error);
        $("#error").slideDown();

        // Display for six seconds
        setTimeout(function(){$("#error").slideUp();}, 6000);
    }

    /**
     * Opens the add user jQuery UI dialog.
     */
    function openAddUser() {
        $("#dialog-add-user").dialog("open");
    }

    /**
     * Opens the add user dialog, and after the new user is saved, adds them to the incident.
     */
    function addUserToIncident() {
        openAddUser();
        // TODO have the user added to the DB, and updated into the add incident dialog
    }

    /* ----------------------------- *
     *           INITALIZE           *
     * ----------------------------- */

    // Runs on document ready.
    $( function($) {

        // Set up the tabs
        $("#tabs").tabs({
            beforeLoad: function(event, ui){
                // Set up error handling
                ui.jqXHR.error(function(){
                   ui.panel.html("Couldn't load this tab.");
                });
            },
            load: function(event, ui){
                $(ui.panel).find("tr").click(function(){
                    $("#lookup-user_id").val($(this).attr("id").substring(3));
                    getInformation();
                });
            }
        });

        // Make buttons jQuery UI buttons
        $("button").button();

        // Set up the dialogs
        $("#dialog-add-user").dialog({
            autoOpen: false,
            modal: true,
            height: 400,
            width: 510,
            buttons: {
                Save : function(){
                    // TODO add verification
                    // Save the user
                    $.post(
                        "fsmcbm.php?add_user=true",
                        $("#add-user-form").serialize(),
                        function(data){
                            if(data.error == null){
                                // Success
                                displayMessage("User added succesfully.");
                            } else {
                                // Error occured
                                handleError(data.error);
                            }
                        }, 'json'
                    );

                    $(this).dialog("close");
                },

                Cancel : function(){
                    $(this).dialog("close");
                }
            }
        });
        $("#dialog-add-incident").dialog({
            autoOpen: false,
            modal: true,
            buttons: {
                Save : function(){
                    // TODO add verification
                    // Save the incident.
                    $.post(
                        "fsmcbm.php?add_incident=true",
                        $("#add-incident-form").serialize(),
                        function(data){
                            if(data.error == null){
                                // Success
                                displayMessage("Incident added.");
                            } else {
                                // Error occured
                                handleError(data.error);
                            }
                        }, 'json'
                    );

                    $(this).dialog("close");
                },
                Cancel : function(){
                    $(this).dialog("close");
                }
            }
        });

        // Set up the autocomplete lookup fields
        lookup("#lookup", "#lookup-user_id", getInformation, "No users found");
        lookup("#user_name", "#user_id", null, "Not Found - Add New", addUserToIncident);

        // Attach events
        $("#add-user").click(openAddUser);
        $("#add-incident").click(function(){
            $("#dialog-add-incident").dialog("open");

        });
    });

})(jQuery);<commit_msg>Label DataStructure types are now disabled text inputs.<commit_after>/* Final Score MC Ban Manager
 *
 */

(function($){

    /* ----------------------------- *
     *   DATA STRUCTURE OBJECT       *
     * ----------------------------- */

    // Convenience constructor
    var info = function(options) {
        return new DataStructure(options);
    };

    // Constructor
    var DataStructure = function(options) {
        var datum, i;

        datum = $.extend({
            // Default Options
            type:"text",
            format:"none",
            name:null,
            after:"
",
            options:[],
            showEmpty:true
        }, options);

        for ( i in datum ) {
            this[i] = datum[i];
        }

        return this;
    };

    info.fn = DataStructure.prototype = {

        // Data Structure Functions

        /**
         * Takes a data structre and turns into into a set of HTML tags.
         * @parm {String} value The value of the data structure.
         * @parm {String} name The name of the data structure.
         * @parm {int} idNum An ID number to attach to the html tags.
         * @return A jQuery object containing the HTML nodes for the data structure.
         */
        toHTML : function(value, name, idNum) {
            /* Types:
             * - text
             * - label
             * - date
             * - textarea
             * - select
             * - int
             * - checkbox
             */
            var showEmpty, html, id = name + "_" + idNum;

            // See if this field should be shown when empty
            if(typeof(this.showEmpty) === 'function') {
                showEmpty = this.showEmpty(idNum);
            } else {
                showEmpty = this.showEmpty;
            }

            if( ! showEmpty ){
                if(value == null){
                    // Don't show empty fields
                    return "";
                }
            }

            value = this.formatValue(value);

            html = $("").text(this.name).attr("for", id);

            if(this.type == "label"){
                // Non editable label
                html = html.add($("<input>").val(value).attr({
                    'type' : "text",
                    'name' : name,
                    'id'  : id
                }).prop('disabled', true));

            } else if(this.type == "textarea"){
                // Text area
                html = html.add($("<textarea>").attr({
                    "name": name,
                    "id"  : id
                }).text(value));

            } else if(this.type == "select"){
                // Drop Down
                var sel = $("<select>").attr({
                    "name": name,
                    "id"  : id
                });

                var i;
                for(i in this.options){
                    i = this.options[i];
                    if(i.label == null){
                        sel.append($("<option>").text(i));
                    } else {
                        sel.append($("<option>").attr("value", i.value).text(i.label));
                    }
                }
                sel.val(value);

                html = html.add(sel);

            } else if(this.type == "text" || this.type == "int"){
                // Text and int types
                var input = $("<input>").val(value).attr({
                    'type' : "text",
                    'name' : name,
                    'id'  : id
                });

                if(this.type == "int"){
                    input.addClass("int");
                }
                html = html.add(input);

            } else if(this.type == "date"){
                // Date field
                html = html.add($("<input>").attr({
                    'type' : "text",
                    'name' : name,
                    'id'  : id
                }).val(value).datepicker({
                   showOn: "both",
                   // TODO get my own calendar icon
                   buttonImage: "http://jqueryui.com/resources/demos/datepicker/images/calendar.gif",
                   buttonImageOnly : true,
                   dateFormat : "yy-mm-dd"
                }));

            } else if(this.type == "checkbox"){
                // Checkbox
                html = html.add($("<input>").attr({
                    'type' : 'checkbox',
                    'name' : name,
                    'id'  : id
                }));

            } else {
                // Unknown
                console.log("Unkown Type: " + this.type);
                return "";
            }

            return html.add($(this.after));
        },

        formatValue : function(value) {
            // Null should be empty strings
            if(value == null)
                return "";

            if(this.format == "date"){
                // Do date formating (change from yy-mm-dd hh:mm:ss to yy-mm-dd)
                value = value.substring(0, value.indexOf(" "));
                return value;
            }

            // No formating needed, return the value
            return value;
        }
    };

    /* ----------------------------- *
     *      DATA STRUCTURES          *
     * ----------------------------- */

    // Incident Data Structure
    var incident = {
        moderator : info({
            name:"Moderator",
            type:"label"
        }),
        created_date : info({
            type:"label",
            format:"date",
            name:"Created Date",
            after:""
        }),
        incident_date : info({
            type:"date",
            format:"date",
            name:"Incident Date"
        }),
        incident_type : info({
            name: "Incident Type"
        }),
        notes : info({
            name: "Notes",
            type: "textarea"
        }),
        action_taken : info({
            type:"textarea",
            name:"Action Taken",
            after:"
Key Location
"
        }),
        world : info({
            name: "World",
            type: "select",
            options:[{
                        value:"",
                        label:""
                    },
                    {
                        value:"world",
                        label:"Alpha"
                    },
                    {
                        value:"world3",
                        label:"Delta"
                    },
                    {
                        value:"world4",
                        label:"Gamma"
                    }],
            after: ""
        }),
        coord_x : info({
            type: "int",
            name: "X",
            after:""
        }),
        coord_y : info({
            type: "int",
            name: "Y",
            after:""
        }),
        coord_z : info({
            type: "int",
            name: "Z"
        }),
        appeal_date : info({
            type:  "label",
            format:"date",
            name:  "Appeal Date",
            showEmpty:false
        }),
        appeal : info({
            name: "Appeal",
            type: "label",
            showEmpty:false
        }),
        appeal_response : info({
            type: "textarea",
            name: "Appeal Response",
            showEmpty:false // TODO: This should only be false when there is no appeal.
        })
    };

    /* ----------------------------- *
     *          FUNCTIONS            *
     * ----------------------------- */

    /**
     * Displays a message to a user in a jQuery UI highlight box.
     * @param {String} message The message to display.
     */
    function displayMessage(message) {
        // Display the message
        $("#highlight-msg").text(message);
        $("#highlight").slideDown();

        // Display for four seconds
        setTimeout(function(){$("#highlight").slideUp();}, 4000);
    }

    /**
     * Sets up an field to be an jQuery UI AutoComplete enabled field.
     * @param {String} input The jQuery selector to apply the autocomplete to.
     * @param {String} value The jQuery selector for the element to set the
     * autocompletes value to.
     * @param {Function} callback A function to call after the a value has been
     * selected from the autocomplete options. Can be null.
     * @param {String} emptyLabel The option text to display when no results are
     * found.
     * @param {Function} emptyCallback A function to call if the no result option
     * is selected. Can be null.
     */
    function lookup(input, value, callback, emptyLabel, emptyCallback) {
        $(input).autocomplete({
            source : function (request, response) {
                $.get("fsmcbm.php",{
                        term: request.term
                    }, function (data) {
                        if (data.length == 0) {
                            data.push({
                                'value': 0,
                                'label': emptyLabel
                            });
                        }
                        response(data);
                    }, 'json');
            },
            minLength : 2,
            select : function( event, ui ){
                if(ui.item.value == 0){
                    if(emptyCallback != null){
                        emptyCallback();
                    }
                } else {
                    $(this).val(ui.item.label);
                    $(value).val(ui.item.value);

                    if(callback != null){
                        callback();
                    }
                }
                return false;
            }
        });
    }

    /**
     *  Retrieves the user information, and then displays it into the manage
     *  users tab.
     */
    function getInformation() {
        $.get(
            "fsmcbm.php",
            { 'lookup': $("#lookup-user_id").val() },
            function(data){
                if(data.error == null){

                    // Empty out any previous incidents
                    var incidents = $("#incident-info").empty();

                    // Fill in the fields
                    $.each(data.user, function(index, value){
                        var field = $("#user-info-" + index);
                        if(field.attr("type") == "checkbox"){
                            field.prop("checked", value == "1");
                        } else {
                            field.val(value);
                        }
                    });

                    if(data.incident != null){
                        // Attach all the incidents
                        for(var i=0; i<data.incident.length; i++){
                            var datum = data.incident[i];

                            var div = $("
").addClass("form").attr("id", "i-" + datum.id);

                            $.each(incident, function(index, value){
                                div.append(value.toHTML(datum[index], index, datum.id));
                            });

                            // Add the save and cancel buttons
                            div.append($("<button>").text("Save").attr("id","i-s-" + datum.id).button().click(function(){
                                // TODO save incident button code here
                            }));
                            div.append($("<button>").text("Cancel").attr("id","i-c-" + datum.id).button().click(function(){
                                // TODO cancel incident save button code here
                            }));

                            div.appendTo(incidents);
                        }
                    }

                    // Switch to the manage tab
                    $("#tabs").tabs("option", "active", 0);

                } else {
                    // Error
                    handleError(data.error);
                }
            },
            'json'
        );
    }

    /**
     * Handles errors.
     * @param {String} error The error message. Optional.
     */
    function handleError(error) {
        // Log the error message
        console.error(error);

        // Display the error message
        $("#error-msg").text(error);
        $("#error").slideDown();

        // Display for six seconds
        setTimeout(function(){$("#error").slideUp();}, 6000);
    }

    /**
     * Opens the add user jQuery UI dialog.
     */
    function openAddUser() {
        $("#dialog-add-user").dialog("open");
    }

    /**
     * Opens the add user dialog, and after the new user is saved, adds them to the incident.
     */
    function addUserToIncident() {
        openAddUser();
        // TODO have the user added to the DB, and updated into the add incident dialog
    }

    /* ----------------------------- *
     *           INITALIZE           *
     * ----------------------------- */

    // Runs on document ready.
    $( function($) {

        // Set up the tabs
        $("#tabs").tabs({
            beforeLoad: function(event, ui){
                // Set up error handling
                ui.jqXHR.error(function(){
                   ui.panel.html("Couldn't load this tab.");
                });
            },
            load: function(event, ui){
                $(ui.panel).find("tr").click(function(){
                    $("#lookup-user_id").val($(this).attr("id").substring(3));
                    getInformation();
                });
            }
        });

        // Make buttons jQuery UI buttons
        $("button").button();

        // Set up the dialogs
        $("#dialog-add-user").dialog({
            autoOpen: false,
            modal: true,
            height: 400,
            width: 510,
            buttons: {
                Save : function(){
                    // TODO add verification
                    // Save the user
                    $.post(
                        "fsmcbm.php?add_user=true",
                        $("#add-user-form").serialize(),
                        function(data){
                            if(data.error == null){
                                // Success
                                displayMessage("User added succesfully.");
                            } else {
                                // Error occured
                                handleError(data.error);
                            }
                        }, 'json'
                    );

                    $(this).dialog("close");
                },

                Cancel : function(){
                    $(this).dialog("close");
                }
            }
        });
        $("#dialog-add-incident").dialog({
            autoOpen: false,
            modal: true,
            buttons: {
                Save : function(){
                    // TODO add verification
                    // Save the incident.
                    $.post(
                        "fsmcbm.php?add_incident=true",
                        $("#add-incident-form").serialize(),
                        function(data){
                            if(data.error == null){
                                // Success
                                displayMessage("Incident added.");
                            } else {
                                // Error occured
                                handleError(data.error);
                            }
                        }, 'json'
                    );

                    $(this).dialog("close");
                },
                Cancel : function(){
                    $(this).dialog("close");
                }
            }
        });

        // Set up the autocomplete lookup fields
        lookup("#lookup", "#lookup-user_id", getInformation, "No users found");
        lookup("#user_name", "#user_id", null, "Not Found - Add New", addUserToIncident);

        // Attach events
        $("#add-user").click(openAddUser);
        $("#add-incident").click(function(){
            $("#dialog-add-incident").dialog("open");

        });
    });

})(jQuery);<|endoftext|>


<commit_before>/* Python built-ins for JavaScript

   Useful links:

    * https://developer.mozilla.org/En/SpiderMonkey/Introduction_to_the_JavaScript_shell

*/

var py_builtins = {};

py_builtins.__python3__ = false;

/* A reference to the global object */

var _global_this = this;

/* JavaScript helper functions */

function defined(obj) {
    return typeof(obj) != 'undefined';
}

function assert(cond, msg) {
    if (!cond) {
        throw new py_builtins.AssertionError(msg);
    }
}

function iterate(seq, func) {
    while (true) {
        try {
            func(seq.next());
        } catch (exc) {
            if (isinstance.__call__(exc, py_builtins.StopIteration)) {
                break;
            } else {
                throw exc;
            }
        }
    }
}

function copy(iterator) {
    var items = [];

    iterate(iterator, function(item) {
        items.push(item);
    });

    return items;
}

function js(obj) {
    /*
       Converts (recursively) a Python object to a javascript builtin object.

       In particular:

       tuple -> Array
       list -> Array
       dict -> Object

       It uses the obj._js_() if it is defined, otherwise it just returns the
       same object. It is the responsibility of _js_() to convert recursively
       the object itself.
    */
    if ((obj != null) && defined(obj._js_))
        return obj._js_();
    else
        return obj;
}

var Function = function(func) {
    func.__call__ = func;
    return func;
};
<commit_msg> * Converted js() function to Function type<commit_after>/* Python built-ins for JavaScript

   Useful links:

    * https://developer.mozilla.org/En/SpiderMonkey/Introduction_to_the_JavaScript_shell

*/

var py_builtins = {};

py_builtins.__python3__ = false;

/* A reference to the global object */

var _global_this = this;

/* JavaScript helper functions */

function defined(obj) {
    return typeof(obj) != 'undefined';
}

function assert(cond, msg) {
    if (!cond) {
        throw new py_builtins.AssertionError(msg);
    }
}

function iterate(seq, func) {
    while (true) {
        try {
            func(seq.next());
        } catch (exc) {
            if (isinstance.__call__(exc, py_builtins.StopIteration)) {
                break;
            } else {
                throw exc;
            }
        }
    }
}

function copy(iterator) {
    var items = [];

    iterate(iterator, function(item) {
        items.push(item);
    });

    return items;
}

js = Function(function(obj) {
    /*
       Converts (recursively) a Python object to a javascript builtin object.

       In particular:

       tuple -> Array
       list -> Array
       dict -> Object

       It uses the obj._js_() if it is defined, otherwise it just returns the
       same object. It is the responsibility of _js_() to convert recursively
       the object itself.
    */
    if ((obj != null) && defined(obj._js_))
        return obj._js_();
    else
        return obj;
});

var Function = function(func) {
    func.__call__ = func;
    return func;
};
<|endoftext|>