<commit_before>const set = '7191-1';
// const set = 'MOC-7540';
const app = document.getElementById('root');

let legoSetID = localStorage.getItem('legoSetID') ? localStorage.getItem('legoSetID') : '';
let rebrickApiKey = localStorage.getItem('rebrickApiKey') ? localStorage.getItem('rebrickApiKey') : '';
let rebrickType = localStorage.getItem('rebrickType') ? localStorage.getItem('rebrickType') : '';

var logo = document.createElement('img');
var container = document.createElement('div');
var options = document.createElement('div');
var clearStorage = document.createElement('button');
var apiKey = document.createElement('input');
var setID = document.createElement('input');
var loadSet = document.createElement('button');

// var baseUrl = `https://rebrickable.com/api/v3/lego/${rebrickType}/${legoSetID}`;
var baseUrl = 'https://rebrickable.com/api/v3/lego/';
var partsUrl = '/parts/?page_size=100000';

container.setAttribute('class', 'container');
logo.setAttribute('id', 'setImage');
logo.setAttribute('class', 'headerImage');
options.setAttribute('class', 'buttons');
apiKey.setAttribute('class', 'field-light text');
apiKey.setAttribute('type', 'text');
apiKey.setAttribute('id', 'rebrickApiKey');
apiKey.setAttribute('placeholder', 'User API Key');
apiKey.value = rebrickApiKey;
setID.setAttribute('class', 'field-light text');
setID.setAttribute('type', 'text');
setID.setAttribute('id', 'legoSetID');
setID.setAttribute('placeholder', 'LEGO Set ID');
setID.setAttribute('placeholder', 'LEGO Set ID');
setID.value = legoSetID;

app.appendChild(logo);
app.appendChild(options);
options.appendChild(clearStorage);
options.appendChild(apiKey);
options.appendChild(setID);
options.appendChild(loadSet);
app.appendChild(container);

clearStorage.innerHTML = "Reset";
clearStorage.onclick = function () {
    setID.value = '';
    apiKey.value = '';
    localStorage.clear();
    // window.location.reload();
};

loadSet.innerHTML = "Load";
loadSet.onclick = function () {
    legoSetID = document.getElementById('legoSetID').value;
    localStorage.setItem('legoSetID', legoSetID.toLowerCase());

    rebrickApiKey = document.getElementById('rebrickApiKey').value;
    localStorage.setItem('rebrickApiKey', rebrickApiKey);

    rebrickType = checkSetIDType(legoSetID);

    setSetLogo();

    url = baseUrl + rebrickType + 's/' + legoSetID + partsUrl;

    partList(url);
};

function request(url) {
    var request = new Request(url, {
        method: 'GET',
        headers: new Headers({
            'Authorization': `key ${rebrickApiKey}`,
            'Accept': 'application/json'
        })
    });
    return request;
};

function checkSetIDType() {
    if (legoSetID.includes('moc')) {
        // localStorage.setItem('rebrickType', 'mocs');
        type = 'moc';
        return type;
    } else {
        // localStorage.setItem('rebrickType', 'sets');
        type = 'set';
        return type;
    }
}

function setSetLogo() {
    console.log(legoSetID)
    console.log(rebrickApiKey)
    console.log(rebrickType)

    url = baseUrl + rebrickType + 's/' + legoSetID + '/';
    console.log(url)

    fetch(request(url))
        .then(response => response.json())
        .then(set => {
            console.log(set);
            document.getElementById('setImage').style.background = 'none';
            logo.src = set[rebrickType + '_img_url'];
        })
        .catch(console.error);
}

function partList(url) {

    fetch(request(url))
        .then(response => response.json())
        .then(parts => {
            var object = parts.results;
            console.log(object)

            object.forEach(function (object) {
                var setPartID = set + '-' + object.id
                console.log(setPartID)

                const card = document.createElement('div');
                card.setAttribute('class', 'card');

                const title = document.createElement('div');
                title.setAttribute('class', 'title');
                const name = document.createElement('h1');
                name.setAttribute('class', 'box');
                name.textContent = object.part.name;

                const body = document.createElement('div');
                body.setAttribute('class', 'body');

                const partImg = document.createElement('img');
                partImg.setAttribute('class', 'partImg');
                partImg.src = object.part.part_img_url;

                const info = document.createElement('span');
                info.innerText = `Colour: ${object.color.name}\r\nQuantity: `;

                let qtyState = localStorage.getItem(setPartID) ? localStorage.getItem(setPartID) : 0;
                var qty = document.createElement('span');
                qty.setAttribute('id', setPartID);
                qty.innerHTML = qtyState;
                var qtyTotal = document.createElement('span');
                qtyTotal.innerText = ` of ${object.quantity}`;

                var buttons = document.createElement('div');
                buttons.setAttribute('class', 'buttons')

                var buttonPlus = document.createElement('button');
                buttonPlus.innerHTML = "+";

                var buttonMinus = document.createElement('button');
                buttonMinus.innerHTML = "-";

                var buttonReset = document.createElement('button');
                buttonReset.innerHTML = "RESET";

                console.log('Creating the Card now')
                container.appendChild(card);
                card.appendChild(title);
                title.appendChild(name);
                card.appendChild(body);
                body.appendChild(partImg);
                body.appendChild(info);
                info.appendChild(qty);
                info.appendChild(qtyTotal);
                card.appendChild(buttons)
                buttons.appendChild(buttonPlus);
                buttons.appendChild(buttonMinus);
                buttons.appendChild(buttonReset);

                buttonPlus.onclick = function () {
                    qtyState++;
                    localStorage.setItem(setPartID, qtyState);
                    return qty.innerHTML = qtyState;
                };

                buttonMinus.onclick = function () {
                    qtyState--;
                    localStorage.setItem(setPartID, qtyState);
                    return qty.innerHTML = qtyState;
                };

                buttonReset.onclick = function () {
                    qtyState = 0;
                    localStorage.setItem(setPartID, qtyState);
                    return qty.innerHTML = qtyState;
                };

            });
        })
        .catch(function (err) {
            console.log(err);
            return err;
        });

}

textFit(document.getElementsByClassName('box'), {
    multiLine: true
});<commit_msg>Minor fixes to console logging<commit_after>const set = '7191-1';
// const set = 'MOC-7540';
const app = document.getElementById('root');

let legoSetID = localStorage.getItem('legoSetID') ? localStorage.getItem('legoSetID') : '';
let rebrickApiKey = localStorage.getItem('rebrickApiKey') ? localStorage.getItem('rebrickApiKey') : '';
let rebrickType = localStorage.getItem('rebrickType') ? localStorage.getItem('rebrickType') : '';

var logo = document.createElement('img');
var container = document.createElement('div');
var options = document.createElement('div');
var clearStorage = document.createElement('button');
var apiKey = document.createElement('input');
var setID = document.createElement('input');
var loadSet = document.createElement('button');

// var baseUrl = `https://rebrickable.com/api/v3/lego/${rebrickType}/${legoSetID}`;
var baseUrl = 'https://rebrickable.com/api/v3/lego/';
var partsUrl = '/parts/?page_size=100000';

container.setAttribute('class', 'container');
logo.setAttribute('id', 'setImage');
logo.setAttribute('class', 'headerImage');
options.setAttribute('class', 'buttons');
apiKey.setAttribute('class', 'field-light text');
apiKey.setAttribute('type', 'text');
apiKey.setAttribute('id', 'rebrickApiKey');
apiKey.setAttribute('placeholder', 'User API Key');
apiKey.value = rebrickApiKey;
setID.setAttribute('class', 'field-light text');
setID.setAttribute('type', 'text');
setID.setAttribute('id', 'legoSetID');
setID.setAttribute('placeholder', 'LEGO Set ID');
setID.setAttribute('placeholder', 'LEGO Set ID');
setID.value = legoSetID;

app.appendChild(logo);
app.appendChild(options);
options.appendChild(clearStorage);
options.appendChild(apiKey);
options.appendChild(setID);
options.appendChild(loadSet);
app.appendChild(container);

clearStorage.innerHTML = "Reset";
clearStorage.onclick = function () {
    setID.value = '';
    apiKey.value = '';
    localStorage.clear();
    // window.location.reload();
};

loadSet.innerHTML = "Load";
loadSet.onclick = function () {
    legoSetID = document.getElementById('legoSetID').value.toLowerCase();
    localStorage.setItem('legoSetID', legoSetID);

    rebrickApiKey = document.getElementById('rebrickApiKey').value;
    localStorage.setItem('rebrickApiKey', rebrickApiKey);

    rebrickType = checkSetIDType(legoSetID);

    setSetLogo();

    url = baseUrl + rebrickType + 's/' + legoSetID + partsUrl;

    partList(url);
};

function request(url) {
    var request = new Request(url, {
        method: 'GET',
        headers: new Headers({
            'Authorization': `key ${rebrickApiKey}`,
            'Accept': 'application/json'
        })
    });
    return request;
};

function checkSetIDType() {
    if (legoSetID.includes('moc')) {
        // localStorage.setItem('rebrickType', 'mocs');
        type = 'moc';
        return type;
    } else {
        // localStorage.setItem('rebrickType', 'sets');
        type = 'set';
        return type;
    }
}

function setSetLogo() {
    console.log('LEGO Set ID: ' + legoSetID)
    console.log('Rebrickable API Key: ' + rebrickApiKey)
    console.log('LEGO Set Type: ' + rebrickType)

    url = baseUrl + rebrickType + 's/' + legoSetID + '/';
    console.log('Rebrickable Set URL: ' + url)

    fetch(request(url))
        .then(response => response.json())
        .then(set => {
            console.log(set);
            document.getElementById('setImage').style.background = 'none';
            logo.src = set[rebrickType + '_img_url'];
        })
        .catch(console.error);
}

function partList(url) {
    console.log('Rebrickable Parts URL: ' + url)

    fetch(request(url))
        .then(response => response.json())
        .then(parts => {
            var object = parts.results;
            console.log(object)

            console.log('Creating cards now')
            object.forEach(function (object) {
                var setPartID = set + '-' + object.id

                const card = document.createElement('div');
                card.setAttribute('class', 'card');

                const title = document.createElement('div');
                title.setAttribute('class', 'title');
                const name = document.createElement('h1');
                name.setAttribute('class', 'box');
                name.textContent = object.part.name;

                const body = document.createElement('div');
                body.setAttribute('class', 'body');

                const partImg = document.createElement('img');
                partImg.setAttribute('class', 'partImg');
                partImg.src = object.part.part_img_url;

                const info = document.createElement('span');
                info.innerText = `Colour: ${object.color.name}\r\nQuantity: `;

                let qtyState = localStorage.getItem(setPartID) ? localStorage.getItem(setPartID) : 0;
                var qty = document.createElement('span');
                qty.setAttribute('id', setPartID);
                qty.innerHTML = qtyState;
                var qtyTotal = document.createElement('span');
                qtyTotal.innerText = ` of ${object.quantity}`;

                var buttons = document.createElement('div');
                buttons.setAttribute('class', 'buttons')

                var buttonPlus = document.createElement('button');
                buttonPlus.innerHTML = "+";

                var buttonMinus = document.createElement('button');
                buttonMinus.innerHTML = "-";

                var buttonReset = document.createElement('button');
                buttonReset.innerHTML = "RESET";

                container.appendChild(card);
                card.appendChild(title);
                title.appendChild(name);
                card.appendChild(body);
                body.appendChild(partImg);
                body.appendChild(info);
                info.appendChild(qty);
                info.appendChild(qtyTotal);
                card.appendChild(buttons)
                buttons.appendChild(buttonPlus);
                buttons.appendChild(buttonMinus);
                buttons.appendChild(buttonReset);

                buttonPlus.onclick = function () {
                    qtyState++;
                    localStorage.setItem(setPartID, qtyState);
                    return qty.innerHTML = qtyState;
                };

                buttonMinus.onclick = function () {
                    qtyState--;
                    localStorage.setItem(setPartID, qtyState);
                    return qty.innerHTML = qtyState;
                };

                buttonReset.onclick = function () {
                    qtyState = 0;
                    localStorage.setItem(setPartID, qtyState);
                    return qty.innerHTML = qtyState;
                };

            });
        })
        .catch(function (err) {
            console.log(err);
            return err;
        });

}

textFit(document.getElementsByClassName('box'), {
    multiLine: true
});<|endoftext|>


<commit_before>"use strict";

// Usage: (secure-<func>.js)
// const shim = require('openwhisk-shim');
// main = shim.makeShim(true);

const {NodeVM} = require("vm2");
const fs = require("fs");
const {PartialOrder} = require("po-utils");
const {TotalOrder} = require("to-utils");
const {auth} = require("auth");
const {SecureKV_PO} = require("secure-kv-po");
const {SecureKV_TO} = require("secure-kv-to");
const nodemailer = require("nodemailer");
const got = require('got');

const rmFilesInDir = function (dirPath) {
    try {
        const files = fs.readdirSync(dirPath);

        if (files.length > 0)
            for (let i = 0; i < files.length; i++) {
                const filePath = dirPath + '/' + files[i];
                if (fs.statSync(filePath).isFile())
                    fs.unlinkSync(filePath);
                else
                    rmFilesInDir(filePath);
            }
    }
    catch(e) { }
};

const notEmptyDir = function (dirPath) {
    try {
        const files = fs.readdirSync(dirPath);
        return files.length > 0;
    }
    catch(e) { return true; }
};

const conf = JSON.parse(fs.readFileSync(__dirname.split('node_modules')[0] + 'conf.json', 'utf8'));
const unsecuredLambda = fs.readFileSync(__dirname.split('node_modules')[0] + conf.unsecLambda, 'utf8');

const labelOrdering = conf.usingPO ? new PartialOrder(conf.labels) : new TotalOrder(conf.min, conf.max);

module.exports.makeShim = function (allowExtReq) {
    return function (params) {

        let label;

        let reqUser;
        let reqPass;

        if (conf.runFromGET) { // Run http GET request on behalf of invoking user.
            reqUser = params.queryStringParameters.user;
            reqPass = params.queryStringParameters.pass;
            if (conf.userPassForIFCOnly) {
                delete params.queryStringParameters.user;
                delete params.queryStringParameters.pass;
            }
        } else { // Run http POST request on behalf of invoking user.
            let reqBody;
            if ((typeof params.body) === "string") {
                reqBody = JSON.parse(params.body);
            } else {
                reqBody = params.body;
            }
            reqUser = reqBody.user;
            reqPass = reqBody.pass;

        }

        const p = auth(reqUser, reqPass);

        const processEnv = {};

        for (let envVar of conf.processEnv) {
            processEnv[envVar] = process.env[envVar];
        }

        let executionEnv = {
            console: 'inherit',
            sandbox: {
                process: {
                    env: processEnv,
                },
                externalParams: params,
                bumpLabelTo:
                    function (newLabel) {
                        if (labelOrdering.lte(label, newLabel)) {
                            label = newLabel;
                            return true;
                        } else {
                            return false;
                        }
                    },
                bumpLabelToTop:
                    function () {
                        label = labelOrdering.getTop();
                    }
            },
            require: {
                external: allowExtReq,
                builtin: ['fs', 'url'],
                root: "./",
                mock: {
                    'kv-store': {
                        KV_Store: function (h, u, pwd, tableName) {
                            const skv = conf.usingPO ?
                                new SecureKV_PO(conf.host, conf.user, conf.pass, labelOrdering, tableName) :
                                new SecureKV_TO(conf.host, conf.user, conf.pass, tableName);

                            return {
                                init: () => skv.init(),
                                close: () => skv.close(),
                                put: (k, v) => skv.put(k, v, label),
                                get: (k) => {
                                    return skv.get(k, label)
                                        .then((res) => {
                                            if (res.length > 0) {
                                                return res[0].rowvalues;
                                            } else {
                                                return res;
                                            }
                                        }); // Arbitrary choice (?)
                                },
                                del: (k) => skv.del(k, label),
                                keys: () => skv.keys(label),
                                entries: () => skv.entries(label),
                            }
                        }
                    },
                    'nodemailer': {
                        createTestAccount: () => {
                            if (labelOrdering.lte(label, conf.securityBound)) {
                                return nodemailer.createTestAccount();
                            } else {
                                throw "Attempting to create test account in violation with security policy"
                            }
                        },
                        createTransport: (params) => {
                            const mailer = nodemailer.createTransport(params);

                            return {
                                sendMail: (mailOptions) => {
                                    if (labelOrdering.lte(label, conf.securityBound)) {
                                        return mailer.sendMail(mailOptions);
                                    } else {
                                        throw "Attempting to send in violation with security policy"
                                    }

                                }
                            }
                        },
                        getTestMessageUrl: (info) => nodemailer.getTestMessageUrl(info),
                    },
                    'got': {
                        get: (uri, params) => {
                            if (labelOrdering.lte(label, conf.securityBound)) {
                                return got.get(uri, params);
                            } else {
                                return Promise.reject("Attempting to access a url in violation with security policy");
                            }
                        }
                    }
                }
            }
        };

        // Need to understand exactly how the filesystem retains information between executions and
        // make sure that it is handled.
        // if (notEmptyDir('/tmp/')) {
        //     console.log("WARNING : /tmp/ dir not empty on fresh invocation of lambda. Might lead to data leak.")
        // }

        return p.then((l) => {
            if (l === undefined) {
                // In case getting the label failed, run on behalf of 'bottom' (completely unprivileged).
                label = labelOrdering.getBottom();
            } else {
                label = l;
            }

            const vm = new NodeVM(executionEnv);

            console.log(`
//  ***********************************
//  ** Original Lambda Code:
${unsecuredLambda}
//  ** End of Original Lambda Code:
//  ***********************************

module.exports = module.exports.main(externalParams);

        `);

            return vm.run(`
//  ***********************************
//  ** Original Lambda Code:
${unsecuredLambda}
//  ** End of Original Lambda Code:
//  ***********************************

module.exports = module.exports.main(externalParams);
        `, conf.secLambdaFullPath);
        })
            .then((executionResult) => {
                if (conf.declassifier &&
                    labelOrdering.lte(label, conf.declassifier.maxLabel) &&
                    labelOrdering.lte(conf.declassifier.minLabel, conf.securityBound)) {
                    const declf = require("../../decl");
                    declf.declassifier(err, value, callback);
                } else {
                    if (labelOrdering.lte(label, conf.securityBound)) {
                        return executionResult;
                    } else {
                        return Promise.reject("Attempting to return a dict/promise in violation with security policy");
                    }
                }
            })
    };
};<commit_msg>Fixed a bug where the wrong script file was passed to the vm (might have caused issues with relative path requires in the sandboxed code).<commit_after>"use strict";

// Usage: (secure-<func>.js)
// const shim = require('openwhisk-shim');
// main = shim.makeShim(true);

const {NodeVM} = require("vm2");
const fs = require("fs");
const {PartialOrder} = require("po-utils");
const {TotalOrder} = require("to-utils");
const {auth} = require("auth");
const {SecureKV_PO} = require("secure-kv-po");
const {SecureKV_TO} = require("secure-kv-to");
const nodemailer = require("nodemailer");
const got = require('got');

const rmFilesInDir = function (dirPath) {
    try {
        const files = fs.readdirSync(dirPath);

        if (files.length > 0)
            for (let i = 0; i < files.length; i++) {
                const filePath = dirPath + '/' + files[i];
                if (fs.statSync(filePath).isFile())
                    fs.unlinkSync(filePath);
                else
                    rmFilesInDir(filePath);
            }
    }
    catch(e) { }
};

const notEmptyDir = function (dirPath) {
    try {
        const files = fs.readdirSync(dirPath);
        return files.length > 0;
    }
    catch(e) { return true; }
};

const conf = JSON.parse(fs.readFileSync(__dirname.split('node_modules')[0] + 'conf.json', 'utf8'));
const unsecuredLambda = fs.readFileSync(__dirname.split('node_modules')[0] + conf.unsecLambda, 'utf8');

const labelOrdering = conf.usingPO ? new PartialOrder(conf.labels) : new TotalOrder(conf.min, conf.max);

module.exports.makeShim = function (allowExtReq) {
    return function (params) {

        let label;

        let reqUser;
        let reqPass;

        if (conf.runFromGET) { // Run http GET request on behalf of invoking user.
            reqUser = params.queryStringParameters.user;
            reqPass = params.queryStringParameters.pass;
            if (conf.userPassForIFCOnly) {
                delete params.queryStringParameters.user;
                delete params.queryStringParameters.pass;
            }
        } else { // Run http POST request on behalf of invoking user.
            let reqBody;
            if ((typeof params.body) === "string") {
                reqBody = JSON.parse(params.body);
            } else {
                reqBody = params.body;
            }
            reqUser = reqBody.user;
            reqPass = reqBody.pass;

        }

        const p = auth(reqUser, reqPass);

        const processEnv = {};

        for (let envVar of conf.processEnv) {
            processEnv[envVar] = process.env[envVar];
        }

        let executionEnv = {
            console: 'inherit',
            sandbox: {
                process: {
                    env: processEnv,
                },
                externalParams: params,
                bumpLabelTo:
                    function (newLabel) {
                        if (labelOrdering.lte(label, newLabel)) {
                            label = newLabel;
                            return true;
                        } else {
                            return false;
                        }
                    },
                bumpLabelToTop:
                    function () {
                        label = labelOrdering.getTop();
                    }
            },
            require: {
                external: allowExtReq,
                builtin: ['fs', 'url'],
                root: "./",
                mock: {
                    'kv-store': {
                        KV_Store: function (h, u, pwd, tableName) {
                            const skv = conf.usingPO ?
                                new SecureKV_PO(conf.host, conf.user, conf.pass, labelOrdering, tableName) :
                                new SecureKV_TO(conf.host, conf.user, conf.pass, tableName);

                            return {
                                init: () => skv.init(),
                                close: () => skv.close(),
                                put: (k, v) => skv.put(k, v, label),
                                get: (k) => {
                                    return skv.get(k, label)
                                        .then((res) => {
                                            if (res.length > 0) {
                                                return res[0].rowvalues;
                                            } else {
                                                return res;
                                            }
                                        }); // Arbitrary choice (?)
                                },
                                del: (k) => skv.del(k, label),
                                keys: () => skv.keys(label),
                                entries: () => skv.entries(label),
                            }
                        }
                    },
                    'nodemailer': {
                        createTestAccount: () => {
                            if (labelOrdering.lte(label, conf.securityBound)) {
                                return nodemailer.createTestAccount();
                            } else {
                                throw "Attempting to create test account in violation with security policy"
                            }
                        },
                        createTransport: (params) => {
                            const mailer = nodemailer.createTransport(params);

                            return {
                                sendMail: (mailOptions) => {
                                    if (labelOrdering.lte(label, conf.securityBound)) {
                                        return mailer.sendMail(mailOptions);
                                    } else {
                                        throw "Attempting to send in violation with security policy"
                                    }

                                }
                            }
                        },
                        getTestMessageUrl: (info) => nodemailer.getTestMessageUrl(info),
                    },
                    'got': {
                        get: (uri, params) => {
                            if (labelOrdering.lte(label, conf.securityBound)) {
                                return got.get(uri, params);
                            } else {
                                return Promise.reject("Attempting to access a url in violation with security policy");
                            }
                        }
                    }
                }
            }
        };

        // Need to understand exactly how the filesystem retains information between executions and
        // make sure that it is handled.
        // if (notEmptyDir('/tmp/')) {
        //     console.log("WARNING : /tmp/ dir not empty on fresh invocation of lambda. Might lead to data leak.")
        // }

        return p.then((l) => {
            if (l === undefined) {
                // In case getting the label failed, run on behalf of 'bottom' (completely unprivileged).
                label = labelOrdering.getBottom();
            } else {
                label = l;
            }

            const vm = new NodeVM(executionEnv);

            console.log(`
//  ***********************************
//  ** Original Lambda Code:
${unsecuredLambda}
//  ** End of Original Lambda Code:
//  ***********************************

module.exports = module.exports.main(externalParams);

        `);

            return vm.run(`
//  ***********************************
//  ** Original Lambda Code:
${unsecuredLambda}
//  ** End of Original Lambda Code:
//  ***********************************

module.exports = module.exports.main(externalParams);
        `, __dirname + "/" + conf.secLambda);
        })
            .then((executionResult) => {
                if (conf.declassifier &&
                    labelOrdering.lte(label, conf.declassifier.maxLabel) &&
                    labelOrdering.lte(conf.declassifier.minLabel, conf.securityBound)) {
                    const declf = require("../../decl");
                    declf.declassifier(err, value, callback);
                } else {
                    if (labelOrdering.lte(label, conf.securityBound)) {
                        return executionResult;
                    } else {
                        return Promise.reject("Attempting to return a dict/promise in violation with security policy");
                    }
                }
            })
    };
};<|endoftext|>


<commit_before>module.exports = {
  pattern: /help/,
  reply: function(message, match, reply) {
    reply("Here's what I know: \n- search add-ons ...\n- search author ...\n- search in forums ...\n- search wiki for ...\n- search source for ...\n- joke\n- current version\n- help");
  }
};
<commit_msg>Display help message on empty input<commit_after>module.exports = {
  pattern: /help|^$/,
  reply: function(message, match, reply) {
    reply("Here's what I know: \n- search add-ons ...\n- search author ...\n- search in forums ...\n- search wiki for ...\n- search source for ...\n- joke\n- current version\n- help");
  }
};
<|endoftext|>


<commit_before>const BASEMINERALS = [RESOURCE_HYDROGEN, RESOURCE_OXYGEN, RESOURCE_UTRIUM, RESOURCE_LEMERGIUM, RESOURCE_KEANIUM, RESOURCE_ZYNTHIUM, RESOURCE_CATALYST];

module.exports = {
    init : function(room){
        if(room.memory.labManager == undefined){
            room.memory.labManager = {};
        }
        var labs = room.find(FIND_MY_STRUCTURES,{filter: (s) => s.structureType == STRUCTURE_LAB});
        room.memory.labManager.labs = [];
        for(lab of labs){
            room.memory.labManager.labs.push({id:lab.id});
        }
        if(room.terminal && labs.length >= 3){
            var terminal = room.terminal;
            for(dx of [-1,0,1]){
                for(dy of [-1,0,1]){
                    var mypos = {x: terminal.pos.x + dx, y: terminal.pos.y + dy, roomName: room.name};
                    if(labs[0].pos.getRangeTo(mypos) == 1 && labs[1].pos.getRangeTo(mypos) == 1 && labs[2].pos.getRangeTo(mypos) == 1){
                        room.memory.labManager.pos = mypos;
                        return OK;
                    }
                }
            }
        }
    },

    addOrder : function(input1,input2,output,amount,roomName){
        var room = Game.rooms[roomName];
        if(room.memory.labManager == undefined){
            this.init(room);
        }
        if(room.memory.labManager.orders == undefined){
            room.memory.labManager.orders = [];
        }
        room.memory.labManager.orders.push({'input1': input1, 'input2':input2, 'output':output, 'amount': amount, 'roomName':roomName});
    },

    addChain : function(output,amount,roomName){
        if(_.findIndex(BASEMINERALS,output) != -1){
            return;
        }
        var input1;
        var input2;
        for(var i in REACTIONS){
            input2 = _.findKey(REACTIONS[i], (x) => x == output);
            if(input2 != undefined){
                input1 = i;
                break;
            }
        }
        this.addChain(input1,amount,roomName);
        this.addChain(input2,amount,roomName);
        // this.addOrder(input1,input2,output,amount,roomName);
        console.log(JSON.stringify({'input1': input1, 'input2':input2, 'output':output, 'amount': amount, 'roomName':roomName}));
    }

    //,

    // run : function(room){
    //     if(room.memory.labManager == undefined){
    //         this.init(room);
    //     }
    //     var orders = room.memory.labManager.orders;
    //     if(orders){
    //         var order = orders[0];
    //         if(order){
    //             room.memory.labManager.labs[0].type = order.input1;
    //             room.memory.labManager.labs[1].type = order.input2;
    //             room.memory.labManager.labs[2].type = order.output;
    //             var labs = [];
    //             for(lab of room.memory.labManager.labs){
    //                 labs.push(Game.getObjectById(lab.id));
    //             }
    //             if(labs[0].mineralType == room.memory.labManager.labs[0].type && labs[1].mineralType == room.memory.labManager.labs[1].type && (labs[2].mineralType == room.memory.labManager.labs[2].type || labs[2].mineralType == undefined)){
    //                 if(labs[2].runReaction(labs[0],labs[1]) == OK){
    //                     order.amount -= 5;
    //                     if(order.amount <= 0){
    //                         orders.shift();
    //                     }
    //                 }
    //             }
    //         }
    //     }
    // }
}
<commit_msg>amend last commit<commit_after>const BASEMINERALS = [RESOURCE_HYDROGEN, RESOURCE_OXYGEN, RESOURCE_UTRIUM, RESOURCE_LEMERGIUM, RESOURCE_KEANIUM, RESOURCE_ZYNTHIUM, RESOURCE_CATALYST];

module.exports = {
    init : function(room){
        if(room.memory.labManager == undefined){
            room.memory.labManager = {};
        }
        var labs = room.find(FIND_MY_STRUCTURES,{filter: (s) => s.structureType == STRUCTURE_LAB});
        room.memory.labManager.labs = [];
        for(lab of labs){
            room.memory.labManager.labs.push({id:lab.id});
        }
        if(room.terminal && labs.length >= 3){
            var terminal = room.terminal;
            for(dx of [-1,0,1]){
                for(dy of [-1,0,1]){
                    var mypos = {x: terminal.pos.x + dx, y: terminal.pos.y + dy, roomName: room.name};
                    if(labs[0].pos.getRangeTo(mypos) == 1 && labs[1].pos.getRangeTo(mypos) == 1 && labs[2].pos.getRangeTo(mypos) == 1){
                        room.memory.labManager.pos = mypos;
                        return OK;
                    }
                }
            }
        }
    },

    addOrder : function(input1,input2,output,amount,roomName){
        var room = Game.rooms[roomName];
        if(room.memory.labManager == undefined){
            this.init(room);
        }
        if(room.memory.labManager.orders == undefined){
            room.memory.labManager.orders = [];
        }
        room.memory.labManager.orders.push({'input1': input1, 'input2':input2, 'output':output, 'amount': amount, 'roomName':roomName});
    },

    addChain : function(output,amount,roomName){
        if(_.findIndex(BASEMINERALS,output) != -1){
            console.log(output + " is a base mineral");
            return;
        }
        var input1;
        var input2;
        for(var i in REACTIONS){
            input2 = _.findKey(REACTIONS[i], (x) => x == output);
            if(input2 != undefined){
                input1 = i;
                break;
            }
        }
        this.addChain(input1,amount,roomName);
        this.addChain(input2,amount,roomName);
        // this.addOrder(input1,input2,output,amount,roomName);
        console.log(JSON.stringify({'input1': input1, 'input2':input2, 'output':output, 'amount': amount, 'roomName':roomName}));
    }

    //,

    // run : function(room){
    //     if(room.memory.labManager == undefined){
    //         this.init(room);
    //     }
    //     var orders = room.memory.labManager.orders;
    //     if(orders){
    //         var order = orders[0];
    //         if(order){
    //             room.memory.labManager.labs[0].type = order.input1;
    //             room.memory.labManager.labs[1].type = order.input2;
    //             room.memory.labManager.labs[2].type = order.output;
    //             var labs = [];
    //             for(lab of room.memory.labManager.labs){
    //                 labs.push(Game.getObjectById(lab.id));
    //             }
    //             if(labs[0].mineralType == room.memory.labManager.labs[0].type && labs[1].mineralType == room.memory.labManager.labs[1].type && (labs[2].mineralType == room.memory.labManager.labs[2].type || labs[2].mineralType == undefined)){
    //                 if(labs[2].runReaction(labs[0],labs[1]) == OK){
    //                     order.amount -= 5;
    //                     if(order.amount <= 0){
    //                         orders.shift();
    //                     }
    //                 }
    //             }
    //         }
    //     }
    // }
}
<|endoftext|>


<commit_before>'use strict'
var u = require('./util')
var isMessage = u.isMessage
var isNote = u.isNote

//Math.max(null, -1) => 0, but I would rather it be -1
function max (a, b) {
  return a == null ? b : b == null ? a : a < b ? b : a
}

//okay just pretending to be purely functional
//(but if you have good functional disipline, you can mutate)
function clone (state) { return state }

function isInitRx (state) {
  return state.remote.req == null || state.local.req == null
}

function canSend(state) {
  return !isInitRx(state) &&
    state.local.seq > max(state.remote.seq, state.remote.req)  && state.local.tx
}

function toSeq (n) {
  //return Math.abs(n)
  return n < -1 ? ~n : n
}

//actually, want to be able to initialize this in receive mode or not.
exports.init = function (local) {
//  if(!Number.isInteger(local))
//    throw new Error('local must be integer')
  //idea for better structure
  return {
    //state of local,
      //highest sequence we have
      //the sequence we asked for (set on initial)
      //whether we are transmitting
    local: {seq: local, req: null, tx: true},
      //the highest sequence we have sent to them
      //the sequence they gave us (which they thus definitely have)
      //whether they are transmitting
    remote: {seq: null, req: null, tx: true},
    //the next item to send. (orderly queue)
    ready: local,
    //the next thing to do to database (disorderly queue)
    effect: null
  }
}

//this is not a reduce, and it has side effects.
exports.read = function (state) {
  if(state.ready == null) return state
  var _ready = state.ready
  state.ready = null
  if(isMessage(_ready)) {
    if(state.remote.seq != null && max(state.remote.seq, state.remote.req) +1 !== _ready.sequence) {
      throw new Error('out of order!')
    }
    state.remote.seq = _ready.sequence
    state.local.req = max(state.local.req, _ready.sequence)
  } else {
    state.local.req = toSeq(_ready)
    state.remote.tx = _ready >= 0
  }
  if(canSend(state)) {
    state.effect = max(state.remote.seq, state.remote.req) + 1
  }

  return state
}

function isOldMessage(state, msg) {
  return (state.local.seq >= msg.sequence)
}

function isNextRxMessage(state, msg) {
  return state.local.seq + 1 == msg.sequence
}

function isNextTxMessage (state, msg) {
  return (
    !isInitRx(state) &&
    state.remote.req < msg.sequence &&
    msg.sequence === max(state.remote.seq, state.remote.req) + 1
  )
}

exports.receiveMessage = function (state, msg) {
  if(!isMessage(msg)) throw new Error('expected a Message!')
  var _state = clone(state)

  _state.remote.req = max(state.remote.req || 0, msg.sequence)
  //not the same^
  _state.remote.seq = max(state.remote.seq || 0, msg.sequence)

  if(state.remote.tx == null)
    throw new Error('we received a message, when we where waiting for remote to send initial request')

  var seq = state.local.seq
  if(isMessage(state.ready)) {
    if(state.ready.sequence <= msg.sequence)
      state.ready = null
  }
  if(isOldMessage(state, msg)) {
    //we already know this, please shut up!
    //let read move us out of tx mode,
    if(state.remote.tx)
      _state.ready = -(seq + 1)
    //XXX: there might be a race here if we are cancelling this feed
  }
  else if(isNextRxMessage(state, msg)) {
    //since we now know they are ahead, stop transmitting to them
    if(state.ready != null)
      _state.ready = null
    _state.effect = msg
    if(state.remote.tx == false)
      state.ready = state.local.seq
  }
  else {
    //this means something went really wrong
    _state.error = true
  }
  return _state
}

exports.receiveNote = function (state, note) {
  if(!isNote(note)) throw new Error('expected note!')
  var _state = clone(state)
  var seq = state.local.seq
  var requested = note >= 0
  var _seq = note == -1 ? -1 : max(toSeq(note), state.remote.seq)

  _state.local.tx = requested
  _state.remote.req = max(_seq, _state.remote.req)

  //if we havn't decided, or have decided we don't want this feed:
  if(state.local.req == null) return _state
  if(state.local.req == -1) return _state

  if(isMessage(state.ready) && _seq >= state.ready.sequence)
      state.ready = null

  //if they sent a note which is ahead of us, and we did not previously send something.

  if(seq < _seq && state.remote.tx == false) {
    state.ready = state.local.seq
  }
  else
  if((seq > _seq) && requested)
    _state.effect = _seq + 1

  return _state
}

//we have either written a new message ourselves,
//or received a message (and validated it) from another peer.
exports.appendMessage = function (state, msg) {
  if(!isMessage(msg)) throw new Error('appendMessage expects a message!')
  //if this is the msg they need next, make
  var _state = clone(state)
  _state.local.seq = msg.sequence

  if(state.local.tx) {
    if(isNextTxMessage(state, msg)) {
      _state.ready = msg
    }
    else if(isNote(state.ready)) { //this should only happen when it is the initial request
      //if we are transmitting, why would we be sending a note?
      //if it's back to even, we don't need to send a message, but if we are not
      //then the message has meaning.
      //if(state.remote.tx)

      if(state.local.req != null) {
        _state.ready = null
        if(_state.local.seq > max(state.remote.seq, state.remote.req))
          _state.effect = max(state.remote.seq, state.remote.req) + 1
      }
    }
    else if(!isMessage(_state.ready)) {
      _state.ready = null

      if(state.local.seq > max(state.remote.req,state.remote.seq))
        state.effect = max(state.remote.req,state.remote.seq) + 1
    }
  }
  else if(!state.local.tx) {
    //if we don't know they are up to this, and they havn't
    //asked us to not send anything (-1) then send a note.
    if(state.remote.req == -1)
      ; //they do not want to hear about this one
    else if(msg.sequence > state.remote.req && state.remote.req != 0) {
      _state.ready = state.remote.tx ? msg.sequence : -(msg.sequence+1) //SEND NOTE
    }
    else if(isNote(state.ready) && state.ready > 0)
      state.ready = msg.sequence //UPDATE NOTE
    else
      state.ready = null
  }
  return state
}

//have retrived an requested message
exports.gotMessage = function (state, msg) {
  if(!isMessage(msg)) throw new Error('expected message')
  var _state = clone(state)
  if (isNextTxMessage(state, msg)) {
    _state.ready = msg
  }
  //if it's not the next message
  //we must have changed state while retriving this message
  //anyway, just get on with things
  return _state
}

<commit_msg>handle if appendMessage is called with an old message<commit_after>'use strict'
var u = require('./util')
var isMessage = u.isMessage
var isNote = u.isNote

//Math.max(null, -1) => 0, but I would rather it be -1
function max (a, b) {
  return a == null ? b : b == null ? a : a < b ? b : a
}

//okay just pretending to be purely functional
//(but if you have good functional disipline, you can mutate)
function clone (state) { return state }

function isInitRx (state) {
  return state.remote.req == null || state.local.req == null
}

function canSend(state) {
  return !isInitRx(state) &&
    state.local.seq > max(state.remote.seq, state.remote.req)  && state.local.tx
}

function toSeq (n) {
  //return Math.abs(n)
  return n < -1 ? ~n : n
}

//actually, want to be able to initialize this in receive mode or not.
exports.init = function (local) {
//  if(!Number.isInteger(local))
//    throw new Error('local must be integer')
  //idea for better structure
  return {
    //state of local,
      //highest sequence we have
      //the sequence we asked for (set on initial)
      //whether we are transmitting
    local: {seq: local, req: null, tx: true},
      //the highest sequence we have sent to them
      //the sequence they gave us (which they thus definitely have)
      //whether they are transmitting
    remote: {seq: null, req: null, tx: true},
    //the next item to send. (orderly queue)
    ready: local,
    //the next thing to do to database (disorderly queue)
    effect: null
  }
}

//this is not a reduce, and it has side effects.
exports.read = function (state) {
  if(state.ready == null) return state
  var _ready = state.ready
  state.ready = null
  if(isMessage(_ready)) {
    if(state.remote.seq != null && max(state.remote.seq, state.remote.req) +1 !== _ready.sequence) {
      throw new Error('out of order!')
    }
    state.remote.seq = _ready.sequence
    state.local.req = max(state.local.req, _ready.sequence)
  } else {
    state.local.req = toSeq(_ready)
    state.remote.tx = _ready >= 0
  }
  if(canSend(state)) {
    state.effect = max(state.remote.seq, state.remote.req) + 1
  }

  return state
}

function isOldMessage(state, msg) {
  return (state.local.seq >= msg.sequence)
}

function isNextRxMessage(state, msg) {
  return state.local.seq + 1 == msg.sequence
}

function isNextTxMessage (state, msg) {
  return (
    !isInitRx(state) &&
    state.remote.req < msg.sequence &&
    msg.sequence === max(state.remote.seq, state.remote.req) + 1
  )
}

exports.receiveMessage = function (state, msg) {
  if(!isMessage(msg)) throw new Error('expected a Message!')
  var _state = clone(state)

  _state.remote.req = max(state.remote.req || 0, msg.sequence)
  //not the same^
  _state.remote.seq = max(state.remote.seq || 0, msg.sequence)

  if(state.remote.tx == null)
    throw new Error('we received a message, when we where waiting for remote to send initial request')

  var seq = state.local.seq
  if(isMessage(state.ready)) {
    if(state.ready.sequence <= msg.sequence) {
      state.ready = null
    }
  }
  if(isOldMessage(state, msg)) {
    //we already know this, please shut up!
    //let read move us out of tx mode,
    if(state.remote.tx) {
      _state.ready = -(seq + 1)
    }
    //XXX: there might be a race here if we are cancelling this feed
  }
  else if(isNextRxMessage(state, msg)) {
    //since we now know they are ahead, stop transmitting to them
    if(state.ready != null)
      _state.ready = null
    _state.effect = msg
    if(state.remote.tx == false) {
      state.ready = state.local.seq
    }
  }
  else {
    //this means something went really wrong
    console.log('WRONG MESSAGE', msg, state)
    _state.error = true
  }
  return _state
}

exports.receiveNote = function (state, note) {
  if(!isNote(note)) throw new Error('expected note!')
  var _state = clone(state)
  var seq = state.local.seq
  var requested = note >= 0
  var _seq = note == -1 ? -1 : max(toSeq(note), state.remote.seq)

  _state.local.tx = requested
  _state.remote.req = max(_seq, _state.remote.req)

  //if we havn't decided, or have decided we don't want this feed:
  if(state.local.req == null) return _state
  if(state.local.req == -1) return _state

  if(isMessage(state.ready) && _seq >= state.ready.sequence)
      state.ready = null

  //if they sent a note which is ahead of us, and we did not previously send something.

  if(seq < _seq && state.remote.tx == false) {
    state.ready = state.local.seq
  }
  else
  if((seq > _seq) && requested)
    _state.effect = _seq + 1

  return _state
}

//we have either written a new message ourselves,
//or received a message (and validated it) from another peer.
exports.appendMessage = function (state, msg) {
  if(!isMessage(msg)) throw new Error('appendMessage expects a message!')
  //if this is the msg they need next, make
  var _state = clone(state)
  //this shouldn't really happen, but this is a hack
  //to support recent changes to secure-scuttlebutt.
  if(msg.sequence <= _state.local.seq)
    return _state

  _state.local.seq = msg.sequence
  if(state.local.tx) {
    if(isNextTxMessage(state, msg)) {
      _state.ready = msg
    }
    else if(isNote(state.ready)) { //this should only happen when it is the initial request
      //if we are transmitting, why would we be sending a note?
      //if it's back to even, we don't need to send a message, but if we are not
      //then the message has meaning.
      //if(state.remote.tx)

      if(state.local.req != null) {
        _state.ready = null
        if(_state.local.seq > max(state.remote.seq, state.remote.req))
          _state.effect = max(state.remote.seq, state.remote.req) + 1
      }
    }
    else if(!isMessage(_state.ready)) {
      _state.ready = null

      if(state.local.seq > max(state.remote.req,state.remote.seq))
        state.effect = max(state.remote.req,state.remote.seq) + 1
    }
  }
  else if(!state.local.tx) {
    //if we don't know they are up to this, and they havn't
    //asked us to not send anything (-1) then send a note.
    if(state.remote.req == -1)
      ; //they do not want to hear about this one
    else if(msg.sequence > state.remote.req && state.remote.req != 0) {
      _state.ready = state.remote.tx ? msg.sequence : -(msg.sequence+1) //SEND NOTE
    }
    else if(isNote(state.ready) && state.ready > 0)
      state.ready = msg.sequence //UPDATE NOTE
    else
      state.ready = null
  }
  return state
}

//have retrived an requested message
exports.gotMessage = function (state, msg) {
  if(!isMessage(msg)) throw new Error('expected message')
  var _state = clone(state)
  if (isNextTxMessage(state, msg)) {
    _state.ready = msg
  }
  //if it's not the next message
  //we must have changed state while retriving this message
  //anyway, just get on with things
  return _state
}

<|endoftext|>


<commit_before>
var express = require('express');
var s = require('express')
var app = module.exports = express();
var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

var ApiQuick = function () {};

ApiQuick.prototype = {

	init: function(port) {
		this.packages = {};
		this.checkAuth = function(user,code) {return true;}
		app.get('/:package/:func', this.get(this));
		app.get('/:package/:func/:arg', this.get(this));
		app.post('/:package/:func', this.post(this));
		app.post('/:package/:func/:arg', this.post(this));
		app.listen(port);
	},

	addPackage: function (name, p, extra) {
		this.packages[name] = {'package':p};
		if(extra) {
			if(extra.auth) {
				this.packages[name].auth = extra.auth;
			}
		}
	},

	get: function(self) {
		return function(req, res) {
			console.log(req.headers.authorization);
			auth64 = (req.headers.authorization || ":").split(':');
			console.log(auth64)
			user = undefined;
			pass = undefined;
			if(auth64.length>=2) {
				user = new Buffer(auth64[0], 'base64').toString("ascii");
				pass = new Buffer(auth64[1], 'base64').toString("ascii");
			}

			responseData = {"error":"Unknown error AQ100"}
			if(!self.packages[req.params.package]) {
				responseData = {"Error": "No package called "+req.params.package};
			} else if(!self.packages[req.params.package]['package']) {
				responseData = {"Error": "Package object does not exist Q101"};
			} else if(!self.packages[req.params.package]['package'][req.params.func]) {
				responseData = {"Error": "No function "+req.params.func+" in package"};
			} else {
				auth = true;
				if(self.packages[req.params.package].auth) {
					auth = self.packages[req.params.package].auth(user, pass, req.params.package, req.params.func, req.params.arg);
				} else {
					auth = self.checkAuth(user, pass, req.params.package, req.params.func, req.params.arg);
				}

				if(!auth) {
					res.writeHead( 401, 'Auth failed', {'content-type' : 'text/plain'})
					responseData = {"error":"Auth failed"}
				} else {
					responseData = self.packages[req.params.package]['package'][req.params.func]("GET", req.params.arg, req.query)
				}
			}

			return res.end(JSON.stringify(responseData));
		};
	},

	post: function(self) {
		return function(req, res) {
			responseData = "Unknown error AQ100"
			if(!self.packages[req.params.package]) {
				responseData = {"Error": "No package called "+req.params.package};
			} else if(!self.packages[req.params.package]['package']) {
				responseData = {"Error": "Package object does not exist Q101"};
			} else if(!self.packages[req.params.package]['package'][req.params.func]) {
				responseData = {"Error": "No function "+req.params.func+" in package"};
			} else {
				responseData = self.packages[req.params.package]['package'][req.params.func]("POST", req.params.arg, req.body)
			}

			return res.end(JSON.stringify(responseData));

		};
	},

	auth: function(f) {
		this.checkAuth = f;
	}
};

module.exports = new ApiQuick();
<commit_msg>undefined auth function means allow<commit_after>
var express = require('express');
var s = require('express')
var app = module.exports = express();
var bodyParser = require('body-parser')
app.use( bodyParser.json() );       // to support JSON-encoded bodies
app.use(bodyParser.urlencoded({     // to support URL-encoded bodies
  extended: true
}));

var ApiQuick = function () {};

ApiQuick.prototype = {

	init: function(port) {
		this.packages = {};
		this.checkAuth = false;
		app.get('/:package/:func', this.get(this));
		app.get('/:package/:func/:arg', this.get(this));
		app.post('/:package/:func', this.post(this));
		app.post('/:package/:func/:arg', this.post(this));
		app.listen(port);
	},

	addPackage: function (name, p, extra) {
		this.packages[name] = {'package':p};
		if(extra) {
			if(extra.auth) {
				this.packages[name].auth = extra.auth;
			}
		}
	},

	get: function(self) {
		return function(req, res) {
			console.log(req.headers.authorization);
			auth64 = (req.headers.authorization || ":").split(':');
			console.log(auth64)
			user = undefined;
			pass = undefined;
			if(auth64.length>=2) {
				user = new Buffer(auth64[0], 'base64').toString("ascii");
				pass = new Buffer(auth64[1], 'base64').toString("ascii");
			}

			responseData = {"error":"Unknown error AQ100"}
			if(!self.packages[req.params.package]) {
				responseData = {"Error": "No package called "+req.params.package};
			} else if(!self.packages[req.params.package]['package']) {
				responseData = {"Error": "Package object does not exist Q101"};
			} else if(!self.packages[req.params.package]['package'][req.params.func]) {
				responseData = {"Error": "No function "+req.params.func+" in package"};
			} else {
				auth = true;
				if(self.packages[req.params.package].auth) {
					auth = self.packages[req.params.package].auth(user, pass, req.params.package, req.params.func, req.params.arg);
				} else if(self.checkAuth) {
					auth = self.checkAuth(user, pass, req.params.package, req.params.func, req.params.arg);
				}

				if(!auth) {
					res.writeHead( 401, 'Auth failed', {'content-type' : 'text/plain'})
					responseData = {"error":"Auth failed"}
				} else {
					responseData = self.packages[req.params.package]['package'][req.params.func]("GET", req.params.arg, req.query)
				}
			}

			return res.end(JSON.stringify(responseData));
		};
	},

	post: function(self) {
		return function(req, res) {
			responseData = "Unknown error AQ100"
			if(!self.packages[req.params.package]) {
				responseData = {"Error": "No package called "+req.params.package};
			} else if(!self.packages[req.params.package]['package']) {
				responseData = {"Error": "Package object does not exist Q101"};
			} else if(!self.packages[req.params.package]['package'][req.params.func]) {
				responseData = {"Error": "No function "+req.params.func+" in package"};
			} else {
				responseData = self.packages[req.params.package]['package'][req.params.func]("POST", req.params.arg, req.body)
			}

			return res.end(JSON.stringify(responseData));

		};
	},

	auth: function(f) {
		this.checkAuth = f;
	}
};

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


<commit_before>function forwardAuthentication(){

	function castBallot(req){
	    var manifest = JSON.parse(sessionStorage.getItem("manifest"));
            // Make an (ajax) cast request:
            $.post(manifest.collectingServer.URI+"/cast", req)
		.fail(function otpRequestFailed() {  // request failed
		    showError('Cannot connect with the server');
		})
		.done(function castRequestDone(result) {  // the signed acknowledgment
		    parent.postMessage({result: result}, "*");
		});
	}

	window.addEventListener('message',function(event) {
	    //console.log("frame recieved: "+event.data);
	    if(event.data.hasOwnProperty("manifest")){
		sessionStorage.setItem("manifest", JSON.stringify(event.data.manifest));
	    }
	    else if(event.data === "loaded"){
		var manifest = JSON.parse(sessionStorage.getItem("manifest"));
		parent.postMessage({manifest: manifest}, "*");
	    }
	    else if(event.data.hasOwnProperty("credentials")){
		sessionStorage.setItem("toBeSubmitted", JSON.stringify(event.data.submitCS));
	    }
	    else if(event.data.hasOwnProperty("ballot")){
		var submit = JSON.parse(sessionStorage.getItem("toBeSubmitted"));
		submit.ballot = event.data.ballot;
		castBallot(submit);
	    }
	},false);

}
<commit_msg>take electionID from manifest, only credentials from authenticator<commit_after>function forwardAuthentication(){

	function castBallot(req){
	    var manifest = JSON.parse(sessionStorage.getItem("manifest"));
            // Make an (ajax) cast request:
            $.post(manifest.collectingServer.URI+"/cast", req)
		.fail(function otpRequestFailed() {  // request failed
		    showError('Cannot connect with the server');
		})
		.done(function castRequestDone(result) {  // the signed acknowledgment
		    parent.postMessage({result: result}, "*");
		});
	}

	window.addEventListener('message',function(event) {
	    //console.log("frame recieved: "+event.data);
	    if(event.data.hasOwnProperty("manifest")){
		sessionStorage.setItem("manifest", JSON.stringify(event.data.manifest));
	    }
	    else if(event.data === "loaded"){
		var manifest = JSON.parse(sessionStorage.getItem("manifest"));
		parent.postMessage({manifest: manifest}, "*");
	    }
	    else if(event.data.hasOwnProperty("credentials")){
		sessionStorage.setItem("toBeSubmitted", JSON.stringify(event.data.credentials));
	    }
	    else if(event.data.hasOwnProperty("ballot")){
		var submit = JSON.parse(sessionStorage.getItem("toBeSubmitted"));
		var manifest = JSON.parse(sessionStorage.getItem("manifest"));
		submit.electionID = manifest.hash;
		submit.ballot = event.data.ballot;
		castBallot(submit);
	    }
	},false);

}
<|endoftext|>


<commit_before>var dgram  = require('dgram')
  , sys    = require('sys')
  , net    = require('net')
  , config = require('./config')

var counters = {};
var timers = {};
var debugInt, flushInt, server;

function measureForKey (key, fields){
  var sampleRate = 1;
  if (fields[1] === undefined) {
    sys.log('Bad line: ' + fields);
  } else {
    if (fields[1].trim() == "ms") {
      if (! timers[key]) {
        timers[key] = [];
      }
      timers[key].push(Number(fields[0] || 0));
    } else {
      if (fields[2] && fields[2].match(/^@([\d\.]+)/)) {
        sampleRate = Number(fields[2].match(/^@([\d\.]+)/)[1]);
      }
      if (! counters[key]) {
        counters[key] = 0;
      }
      counters[key] += Number(fields[0] || 1) * (1 / sampleRate);
    }
  }
}

config.configFile(process.argv[2], function (config, oldConfig) {
  if (! config.debug && debugInt) {
    clearInterval(debugInt);
    debugInt = false;
  }

  if (config.debug) {
    if (debugInt !== undefined) { clearInterval(debugInt); }
    debugInt = setInterval(function () {
      sys.log("Counters:\n" + sys.inspect(counters) + "\nTimers:\n" + sys.inspect(timers));
    }, config.debugInterval || 10000);
  }

  if (server === undefined) {
    server = dgram.createSocket('udp4', function (msg, rinfo) {
      if (config.dumpMessages) { sys.log(msg.toString()); }
      var bits = msg.toString().split(':');
      var key = bits.shift()
                    .replace(/\s+/g, '_')
                    .replace(/\//g, '-')
                    .replace(/[^a-zA-Z_\-0-9\.]/g, '');

      if (bits.length == 0) {
        bits.push("1");
      }

      for (var i = 0; i < bits.length; i++) {
        var fields = bits[i].split("|");
        if (config.measureByIP) {
          measureForKey(key + ".all", fields);
          var keyWithIp = key + '.' + rinfo.address.replace(/\./g,'-') ;
          measureForKey(keyWithIp , fields);
        } else {
          measureForKey(key, fields);
        }
      }
    });

    server.bind(config.port || 8125);

    var flushInterval = Number(config.flushInterval || 10000);

    flushInt = setInterval(function () {
      var statString = '';
      var ts = Math.round(new Date().getTime() / 1000);
      var numTimers = 0;
      var numCounters = 0;
      var numTimersWithValues = 0;
      var key;

      for (key in counters) {
        var value = counters[key] / (flushInterval / 1000);
        var message = 'stats.' + key + ' ' + value + ' ' + ts + "\n";
        message += 'stats_counts.' + key + ' ' + counters[key] + ' ' + ts + "\n";
        statString += message;
        counters[key] = 0;
	numCounters += 1;
      }

      for (key in timers) {
        numTimers += 1;
        if (timers[key].length > 0) {
          var pctThreshold = config.percentThreshold || 90;
          var values = timers[key].sort(function (a,b) { return a-b; });
          var count = values.length;
          var min = values[0];
          var max = values[count - 1];

          var mean = min;
          var maxAtThreshold = max;

          if (count > 1) {
            var thresholdIndex = Math.round(((100 - pctThreshold) / 100) * count);
            var numInThreshold = count - thresholdIndex;
            values = values.slice(0, numInThreshold);
            maxAtThreshold = values[numInThreshold - 1];

            // average the remaining timings
            var sum = 0;
            for (var i = 0; i < numInThreshold; i++) {
              sum += values[i];
            }

            mean = sum / numInThreshold;
          }

          timers[key] = [];

          var message = "";
          message += 'stats.timers.' + key + '.mean ' + mean + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.upper ' + max + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.upper_' + pctThreshold + ' ' + maxAtThreshold + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.lower ' + min + ' ' + ts + "\n";
          message += 'stats.timers.' + key + '.count ' + count + ' ' + ts + "\n";
          statString += message;
          numTimersWithValues +=1;
        }
      }

      statString += 'statsd.numCounters ' + numCounters + ' ' + ts + "\n";
      statString += 'statsd.numTimers ' + numTimers + ' ' + ts + "\n";
      statString += 'statsd.numTimersWithValues ' + numTimersWithValues + ' ' + ts + "\n";

      try {
        var graphite = net.createConnection(config.graphitePort, config.graphiteHost);
        graphite.addListener('error', function(connectionException){
          if (config.debug) {
            sys.log(connectionException);
          }
        });
        graphite.on('connect', function() {
          this.write(statString);
          this.end();
        });
      } catch(e){
        if (config.debug) {
          sys.log(e);
        }
      }

    }, flushInterval);
  }

});

<commit_msg>Handle additional Parameter that should contain appname.hostname for better grouping of values by app and server<commit_after>var dgram  = require('dgram')
  , sys    = require('sys')
  , net    = require('net')
  , config = require('./config')

var counters = {};
var timers = {};
var debugInt, flushInt, server;

function measureForKey (key, fields){
  var sampleRate = 1;
  var finalKey = key;
  if (fields[1] === undefined) {
    sys.log('Bad line: ' + fields);
  } else {
    if (fields[1].trim() == "ms") {
      if (!(fields[3] === undefined)) {
        finalKey = fields[3] + '.timers.' + key ;
      } else {
        finalKey = 'other.unknownHosts.timers.' + key ;
      }
      if (! timers[finalKey]) {
        timers[finalKey] = [];
      }
      timers[finalKey].push(Number(fields[0] || 0));
    } else {
      if (!(fields[3] === undefined)) {
        finalKey = fields[3] + "." + key ;
      } else {
        finalKey = 'other.unknownHosts' + key ;
      }
      if (fields[2] && fields[2].match(/^@([\d\.]+)/)) {
        sampleRate = Number(fields[2].match(/^@([\d\.]+)/)[1]);
      }
      if (! counters[finalKey]) {
        counters[finalKey] = 0;
      }
      counters[finalKey] += Number(fields[0] || 1) * (1 / sampleRate);
    }
  }
}

config.configFile(process.argv[2], function (config, oldConfig) {
  if (! config.debug && debugInt) {
    clearInterval(debugInt);
    debugInt = false;
  }

  if (config.debug) {
    if (debugInt !== undefined) { clearInterval(debugInt); }
    debugInt = setInterval(function () {
      sys.log("Counters:\n" + sys.inspect(counters) + "\nTimers:\n" + sys.inspect(timers));
    }, config.debugInterval || 10000);
  }

  if (server === undefined) {
    server = dgram.createSocket('udp4', function (msg, rinfo) {
      if (config.dumpMessages) { sys.log(msg.toString()); }
      var bits = msg.toString().split(':');
      var key = bits.shift()
                    .replace(/\s+/g, '_')
                    .replace(/\//g, '-')
                    .replace(/[^a-zA-Z_\-0-9\.]/g, '');

      if (bits.length == 0) {
        bits.push("1");
      }

      for (var i = 0; i < bits.length; i++) {
        var fields = bits[i].split("|");
        measureForKey(key, fields);
      }
    });

    server.bind(config.port || 8125);

    var flushInterval = Number(config.flushInterval || 10000);

    flushInt = setInterval(function () {
      var statString = '';
      var ts = Math.round(new Date().getTime() / 1000);
      var numTimers = 0;
      var numCounters = 0;
      var numTimersWithValues = 0;
      var key;

      for (key in counters) {
        var value = counters[key] / (flushInterval / 1000);
        var message = key + ' ' + value + ' ' + ts + "\n";
        statString += message;
        counters[key] = 0;
	numCounters += 1;
      }

      for (key in timers) {
        numTimers += 1;
        if (timers[key].length > 0) {
          var pctThreshold = config.percentThreshold || 90;
          var values = timers[key].sort(function (a,b) { return a-b; });
          var count = values.length;
          var min = values[0];
          var max = values[count - 1];

          var mean = min;
          var maxAtThreshold = max;

          if (count > 1) {
            var thresholdIndex = Math.round(((100 - pctThreshold) / 100) * count);
            var numInThreshold = count - thresholdIndex;
            values = values.slice(0, numInThreshold);
            maxAtThreshold = values[numInThreshold - 1];

            // average the remaining timings
            var sum = 0;
            for (var i = 0; i < numInThreshold; i++) {
              sum += values[i];
            }

            mean = sum / numInThreshold;
          }

          timers[key] = [];

          var message = "";
          message += key + '.mean ' + mean + ' ' + ts + "\n";
          message += key + '.upper ' + max + ' ' + ts + "\n";
          message += key + '.upper_' + pctThreshold + ' ' + maxAtThreshold + ' ' + ts + "\n";
          message += key + '.lower ' + min + ' ' + ts + "\n";
          message += key + '.count ' + count + ' ' + ts + "\n";
          statString += message;
          numTimersWithValues +=1;
        }
      }

      statString += 'statsd.numCounters ' + numCounters + ' ' + ts + "\n";
      statString += 'statsd.numTimers ' + numTimers + ' ' + ts + "\n";
      statString += 'statsd.numTimersWithValues ' + numTimersWithValues + ' ' + ts + "\n";

      try {
        var graphite = net.createConnection(config.graphitePort, config.graphiteHost);
        graphite.addListener('error', function(connectionException){
          if (config.debug) {
            sys.log(connectionException);
          }
        });
        graphite.on('connect', function() {
          this.write(statString);
          this.end();
        });
      } catch(e){
        if (config.debug) {
          sys.log(e);
        }
      }

    }, flushInterval);
  }

});

<|endoftext|>


<commit_before>var Botkit = require(__dirname + '/CoreBot.js');
var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');
var JSONbig = require('json-bigint');

function Facebookbot(configuration) {

    // Create a core botkit bot
    var facebook_botkit = Botkit(configuration || {});

    // customize the bot definition, which will be used when new connections
    // spawn!
    facebook_botkit.defineBot(function(botkit, config) {

        var bot = {
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances,
        };

        bot.startConversation = function(message, cb) {
            botkit.startConversation(this, message, cb);
        };

        bot.send = function(message, cb) {

            var facebook_message = {
                recipient: {},
                message: {}
            };

            if (typeof(message.channel) == 'string' && message.channel.match(/\+\d+\(\d\d\d\)\d\d\d\-\d\d\d\d/)) {
                facebook_message.recipient.phone_number = message.channel;
            } else {
                facebook_message.recipient.id = message.channel;
            }

            if (message.text) {
                facebook_message.message.text = message.text;
            }

            if (message.attachment) {
                facebook_message.message.attachment = message.attachment;
            }

            request.post('https://graph.facebook.com/me/messages?access_token=' + configuration.access_token,
                function(err, res, body) {
                    if (err) {
                        botkit.debug('WEBHOOK ERROR', err);
                        return cb && cb(err);
                    }

                    try {

                        var json = JSON.parse(body);

                    } catch (err) {

                        botkit.debug('JSON Parse error: ', err);
                        return cb && cb(err);

                    }

                    if (json.error) {
                        botkit.debug('API ERROR', json.error);
                        return cb && cb(json.error.message);
                    }

                    botkit.debug('WEBHOOK SUCCESS', body);
                    cb && cb(null, body);
                }).form(facebook_message);
        };

        bot.reply = function(src, resp, cb) {
            var msg = {};

            if (typeof(resp) == 'string') {
                msg.text = resp;
            } else {
                msg = resp;
            }

            msg.channel = src.channel;

            bot.say(msg, cb);
        };

        bot.findConversation = function(message, cb) {
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
                    if (
                        botkit.tasks[t].convos[c].isActive() &&
                        botkit.tasks[t].convos[c].source_message.user == message.user
                    ) {
                        botkit.debug('FOUND EXISTING CONVO!');
                        cb(botkit.tasks[t].convos[c]);
                        return;
                    }
                }
            }

            cb();
        };

        return bot;

    });

    // set up a web route for receiving outgoing webhooks and/or slash commands
    facebook_botkit.createWebhookEndpoints = function(webserver, bot) {

        facebook_botkit.log(
            '** Serving webhook endpoints for Slash commands and outgoing ' +
            'webhooks at: http://MY_HOST:' + facebook_botkit.config.port + '/facebook/receive');
        webserver.post('/facebook/receive', function(req, res) {
            facebook_botkit.debug('GOT A MESSAGE HOOK');
            var obj = JSONbig.parse(req.body);
            console.log(obj)
            if (obj.entry) {
                for (var e = 0; e < obj.entry.length; e++) {
                    for (var m = 0; m < obj.entry[e].messaging.length; m++) {
                        var facebook_message = obj.entry[e].messaging[m];
                        var fbSenderId = facebook_message.sender.id.toString();
                        if (facebook_message.message) {

                            var message = {
                                text: facebook_message.message.text,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                                seq: facebook_message.message.seq,
                                mid: facebook_message.message.mid,
                            };

                            facebook_botkit.receiveMessage(bot, message);
                        } else if (facebook_message.postback) {

                            var message = {
                                payload: facebook_message.postback.payload,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_postback', [bot, message]);
                        } else if (facebook_message.optin) {

                            var message = {
                                optin: facebook_message.optin,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_optin', [bot, message]);
                        } else if (facebook_message.delivery) {

                            var message = {
                                optin: facebook_message.delivery,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('message_delivered', [bot, message]);

                        } else {
                            botkit.log('Got an unexpected message from Facebook: ', facebook_message);
                        }
                    }
                }
            }
            res.send('ok');
        });

        webserver.get('/facebook/receive', function(req, res) {
            console.log(req.query);
            if (req.query['hub.mode'] == 'subscribe') {
                if (req.query['hub.verify_token'] == configuration.verify_token) {
                    res.send(req.query['hub.challenge']);
                } else {
                    res.send('OK');
                }
            }
        });

        return facebook_botkit;
    };

    facebook_botkit.setupWebserver = function(port, cb) {

        if (!port) {
            throw new Error('Cannot start webserver without a port');
        }
        if (isNaN(port)) {
            throw new Error('Specified port is not a valid number');
        }

        facebook_botkit.config.port = port;

        facebook_botkit.webserver = express();
        facebook_botkit.webserver.use(bodyParser.text({ type: 'application/json' }));
        facebook_botkit.webserver.use(bodyParser.urlencoded({ extended: true }));
        facebook_botkit.webserver.use(express.static(__dirname + '/public'));

        var server = facebook_botkit.webserver.listen(
            facebook_botkit.config.port,
            function() {
                facebook_botkit.log('** Starting webserver on port ' +
                    facebook_botkit.config.port);
                if (cb) { cb(null, facebook_botkit.webserver); }
            });

        request.post('https://graph.facebook.com/me/subscribed_apps?access_token=' + configuration.access_token,
            function(err, res, body) {
                if (err) {
                    facebook_botkit.log('Could not subscribe to page messages');
                } else {
                    facebook_botkit.debug('Successfully subscribed to Facebook events:', body);
                    facebook_botkit.startTicking();
                }
            });

        return facebook_botkit;

    };

    return facebook_botkit;
};

module.exports = Facebookbot;
<commit_msg>to string<commit_after>var Botkit = require(__dirname + '/CoreBot.js');
var request = require('request');
var express = require('express');
var bodyParser = require('body-parser');
var JSONbig = require('json-bigint');

function Facebookbot(configuration) {

    // Create a core botkit bot
    var facebook_botkit = Botkit(configuration || {});

    // customize the bot definition, which will be used when new connections
    // spawn!
    facebook_botkit.defineBot(function(botkit, config) {

        var bot = {
            botkit: botkit,
            config: config || {},
            utterances: botkit.utterances,
        };

        bot.startConversation = function(message, cb) {
            botkit.startConversation(this, message, cb);
        };

        bot.send = function(message, cb) {

            var facebook_message = {
                recipient: {},
                message: {}
            };

            if (typeof(message.channel) == 'string' && message.channel.match(/\+\d+\(\d\d\d\)\d\d\d\-\d\d\d\d/)) {
                facebook_message.recipient.phone_number = message.channel;
            } else {
                facebook_message.recipient.id = message.channel;
            }

            if (message.text) {
                facebook_message.message.text = message.text;
            }

            if (message.attachment) {
                facebook_message.message.attachment = message.attachment;
            }

            request.post('https://graph.facebook.com/me/messages?access_token=' + configuration.access_token,
                function(err, res, body) {
                    if (err) {
                        botkit.debug('WEBHOOK ERROR', err);
                        return cb && cb(err);
                    }

                    try {

                        var json = JSON.parse(body);

                    } catch (err) {

                        botkit.debug('JSON Parse error: ', err);
                        return cb && cb(err);

                    }

                    if (json.error) {
                        botkit.debug('API ERROR', json.error);
                        return cb && cb(json.error.message);
                    }

                    botkit.debug('WEBHOOK SUCCESS', body);
                    cb && cb(null, body);
                }).form(facebook_message);
        };

        bot.reply = function(src, resp, cb) {
            var msg = {};

            if (typeof(resp) == 'string') {
                msg.text = resp;
            } else {
                msg = resp;
            }

            msg.channel = src.channel;

            bot.say(msg, cb);
        };

        bot.findConversation = function(message, cb) {
            botkit.debug('CUSTOM FIND CONVO', message.user, message.channel);
            for (var t = 0; t < botkit.tasks.length; t++) {
                for (var c = 0; c < botkit.tasks[t].convos.length; c++) {
                    if (
                        botkit.tasks[t].convos[c].isActive() &&
                        botkit.tasks[t].convos[c].source_message.user == message.user
                    ) {
                        botkit.debug('FOUND EXISTING CONVO!');
                        cb(botkit.tasks[t].convos[c]);
                        return;
                    }
                }
            }

            cb();
        };

        return bot;

    });

    // set up a web route for receiving outgoing webhooks and/or slash commands
    facebook_botkit.createWebhookEndpoints = function(webserver, bot) {

        facebook_botkit.log(
            '** Serving webhook endpoints for Slash commands and outgoing ' +
            'webhooks at: http://MY_HOST:' + facebook_botkit.config.port + '/facebook/receive');
        webserver.post('/facebook/receive', function(req, res) {
            facebook_botkit.debug('GOT A MESSAGE HOOK');
            var obj = JSONbig.parse(req.body);
            console.log(obj)
            if (obj.entry) {
                for (var e = 0; e < obj.entry.length; e++) {
                    for (var m = 0; m < obj.entry[e].messaging.length; m++) {
                        var facebook_message = obj.entry[e].messaging[m];
                        var fbSenderId = facebook_message.sender.id.toString();
                        if (facebook_message.message) {

                            var message = {
                                text: facebook_message.message.text,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                                seq: facebook_message.message.seq,
                                mid: facebook_message.message.mid,
                            };

                            facebook_botkit.receiveMessage(bot, message);
                        } else if (facebook_message.postback) {

                            var message = {
                                payload: facebook_message.postback.payload,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_postback', [bot, message]);
                        } else if (facebook_message.optin) {

                            var message = {
                                optin: facebook_message.optin,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('facebook_optin', [bot, message]);
                        } else if (facebook_message.delivery) {

                            var message = {
                                optin: facebook_message.delivery,
                                user: fbSenderId,
                                channel: fbSenderId,
                                timestamp: facebook_message.timestamp,
                            };

                            facebook_botkit.trigger('message_delivered', [bot, message]);

                        } else {
                            botkit.log('Got an unexpected message from Facebook: ', facebook_message);
                        }
                    }
                }
            }
            res.send('ok');
        });

        webserver.get('/facebook/receive', function(req, res) {
            console.log(req.query);
            if (req.query['hub.mode'] == 'subscribe') {
                if (req.query['hub.verify_token'] == configuration.verify_token) {
                    res.send(req.query['hub.challenge']);
                } else {
                    res.send('OK');
                }
            }
        });

        return facebook_botkit;
    };

    facebook_botkit.setupWebserver = function(port, cb) {

        if (!port) {
            throw new Error('Cannot start webserver without a port');
        }
        if (isNaN(port)) {
            throw new Error('Specified port is not a valid number');
        }

        facebook_botkit.config.port = port;

        facebook_botkit.webserver = express();
        facebook_botkit.webserver.use(bodyParser.text({ type: 'application/json' }));
        facebook_botkit.webserver.use(bodyParser.urlencoded({ extended: true }));
        facebook_botkit.webserver.use(express.static(__dirname + '/public'));

        var server = facebook_botkit.webserver.listen(
            facebook_botkit.config.port,
            function() {
                facebook_botkit.log('** Starting webserver on port ' +
                    facebook_botkit.config.port);
                if (cb) { cb(null, facebook_botkit.webserver); }
            });

        request.post('https://graph.facebook.com/me/subscribed_apps?access_token=' + configuration.access_token,
            function(err, res, body) {
                if (err) {
                    facebook_botkit.log('Could not subscribe to page messages');
                } else {
                    facebook_botkit.debug('Successfully subscribed to Facebook events:', body);
                    // facebook_botkit.startTicking();
                }
            });

        return facebook_botkit;

    };

    return facebook_botkit;
};

module.exports = Facebookbot;
<|endoftext|>


<commit_before>'use strict';

var moment = require('moment');
var _ = require('underscore');

var Forecast = function () { };

Forecast.init = function (data) {
    var forecast = _.extend(data, new Forecast);
    forecast.forEach(function (entry, i) {
        forecast[i] = _.extend(entry, new ForecastEntry);
    });
    return forecast;
};

Forecast.prototype.dataPoints = function () {
    return this.length;
};

Forecast.prototype.toString = function () {
    var output = '';
    this.forEach(function (entry) {
        output += entry.toString() + '\n';
    });
    return output;
};

var ForecastEntry = function () { };

ForecastEntry.prototype.toString = function () {
    var output = moment.unix(this.localTimestamp).format('MMM D HH:mm ');
    for (var i = 0; i < this.solidRating; i++) output += "★ ";
    return output;
};

module.exports = Forecast;
<commit_msg>Adding swell height<commit_after>'use strict';

var moment = require('moment');
var _ = require('underscore');

var Forecast = function () { };

Forecast.init = function (data) {
    var forecast = _.extend(data, new Forecast);
    forecast.forEach(function (entry, i) {
        forecast[i] = ForecastEntry.init(entry);
    });
    return forecast;
};

Forecast.prototype.dataPoints = function () {
    return this.length;
};

Forecast.prototype.toString = function () {
    var output = '';
    this.forEach(function (entry) {
        output += entry.toString() + '\n';
    });
    return output;
};

var ForecastEntry = function () { };

ForecastEntry.init = function (data) {
    var entry = _.extend(data, new ForecastEntry);
    entry.swell = _.extend(data.swell, new ForecastSwellEntry);
    entry.wind = _.extend(data.wind, new ForecastWindEntry);
    entry.condition = _.extend(data.condition, new ForecastConditionEntry);
    //entry.charts = ...
    return entry;
};

ForecastEntry.prototype.toString = function () {
    var output = moment.unix(this.localTimestamp).format('MMM D HH:mm  ');
    for (var i = 0; i < this.solidRating; i++) output += "★ ";
    for (var i = 0; i < this.fadedRating; i++) output += "☆ ";
    for (var i = this.solidRating + this.fadedRating; i > 0; i--) output += ' ';
    output += '\t' + this.swell.toString() + ' ' + this.wind.toString() + ' ' + this.condition.toString();
    return output;
};

var ForecastSwellEntry = function () { };
ForecastSwellEntry.prototype.toString = function () {
    if (this.maxBreakingHeight < 1) return 'Flat';
    else if (this.minBreakingHeight === this.maxBreakingHeight) return this.minBreakingHeight + this.unit;
    else return this.minBreakingHeight + '-' + this.maxBreakingHeight + this.unit;
};

var ForecastWindEntry = function () { };
ForecastWindEntry.prototype.toString = function () {
    var output = '';
    return output;
};

var ForecastConditionEntry = function () { };
ForecastConditionEntry.prototype.toString = function () {
    var output = '';
    return output;
};

module.exports = Forecast;
<|endoftext|>


<commit_before>#!/usr/bin/env node
/*
 * Furnance
 * https://github.com/jfk/Furnance
 *
 * Copyright (c) 2013 pjazdzewski1990
 * Licensed under the MIT license.
 */

'use strict';

var exec = require('child_process').exec;

var log = function(str) {
  console.log("Furnance: " + str);
};

//clean the workspace
var clean = function(input, nextStep){
  log("Cleaning...");
  var child = exec('ant clean', function(err, stdout, stderr) {
    if(err) {
      throw err;
    }else{
      if(nextStep) nextStep(stdout);
    }
  });
};

//build the app
var build = function(input, nextStep){
  log("Building...");
  var child = exec('ant debug -f build.xml', function(err, stdout, stderr) {
    if(err) {
      throw err;
    }else{
      if(nextStep) nextStep(stdout);
    }
  });
};

//push the app to devices
//TODO: remove hard-coded values
var start = function(input, nextStep){
  var runOnDevice = function(device){
    log("Starting app on " + device);
    var child = exec('adb -s ' + device + ' install -r bin/AshDemo-debug.apk', function(err, stdout, stderr) {
      if(err) {
        throw err;
      }else{
        log("Installed app on " + device);
        var child = exec('adb -s ' + device + ' shell am start -a android.intent.action.MAIN -n pl.ug.ash/pl.ug.ash.AshDemo',
        function(err, stdout, stderr) {
          if(err) {
            throw err;
          }else{
            log("Started app on " + device);
            if(nextStep) nextStep(null);
          }
        });
      }
    });
  };//runOnDevice
  for(var i=0; i<input.length; i++){
    runOnDevice(input[i].id);
  }//for
};

//launch tests on connected devices
var test = function(input, nextStep){
  detect(null, start);
};

//detect connected devices
var detect = function(input, nextStep){
  log("Detecting connected devices...");
  var child = exec('adb devices', function(err, stdout, stderr) {
    if(err) {
      throw err;
    }else{
      var devices = [];
      var lines = stdout.split('\n');
      for(var i=1; i<lines.length-2; i++){
        var data = lines[i].match(/\S+/g);
        devices.push({id: data[0], type: data[1]});
      }
      if(nextStep) nextStep(devices);
    }
  });
};

var userArgs = process.argv.slice(2);
log("User Args - " + userArgs);

switch (userArgs[0]) {
  case "clean":
    clean();
    break;
  case "build":
    clean(null, build);
    break;
  case "test":
    build(null, test);
    break;
  default:
}

<commit_msg>run clean with test<commit_after>#!/usr/bin/env node
/*
 * Furnance
 * https://github.com/jfk/Furnance
 *
 * Copyright (c) 2013 pjazdzewski1990
 * Licensed under the MIT license.
 */

'use strict';

var exec = require('child_process').exec;

var log = function(str) {
  console.log("Furnance: " + str);
};

//clean the workspace
var clean = function(input, nextStep){
  log("Cleaning...");
  var child = exec('ant clean', function(err, stdout, stderr) {
    if(err) {
      throw err;
    }else{
      if(nextStep) nextStep(stdout);
    }
  });
};

//build the app
var build = function(input, nextStep){
  log("Building...");
  var child = exec('ant debug -f build.xml', function(err, stdout, stderr) {
    if(err) {
      throw err;
    }else{
      if(nextStep) nextStep(stdout);
    }
  });
};

//push the app to devices
//TODO: remove hard-coded values
var start = function(input, nextStep){
  var runOnDevice = function(device){
    log("Starting app on " + device);
    var child = exec('adb -s ' + device + ' install -r bin/AshDemo-debug.apk', function(err, stdout, stderr) {
      if(err) {
        throw err;
      }else{
        log("Installed app on " + device);
        var child = exec('adb -s ' + device + ' shell am start -a android.intent.action.MAIN -n pl.ug.ash/pl.ug.ash.AshDemo',
        function(err, stdout, stderr) {
          if(err) {
            throw err;
          }else{
            log("Started app on " + device);
            if(nextStep) nextStep(null);
          }
        });
      }
    });
  };//runOnDevice
  for(var i=0; i<input.length; i++){
    runOnDevice(input[i].id);
  }//for
};

//launch tests on connected devices
var test = function(input, nextStep){
  detect(null, start);
};

//detect connected devices
var detect = function(input, nextStep){
  log("Detecting connected devices...");
  var child = exec('adb devices', function(err, stdout, stderr) {
    if(err) {
      throw err;
    }else{
      var devices = [];
      var lines = stdout.split('\n');
      for(var i=1; i<lines.length-2; i++){
        var data = lines[i].match(/\S+/g);
        devices.push({id: data[0], type: data[1]});
      }
      if(nextStep) nextStep(devices);
    }
  });
};

var userArgs = process.argv.slice(2);
log("User Args - " + userArgs);

switch (userArgs[0]) {
  case "clean":
    clean();
    break;
  case "build":
    clean(null, build);
    break;
  case "test":
    clean(null, function(){build(null, test);});
    break;
  default:
}

<|endoftext|>


<commit_before>const EE = require('events');

module.exports = (instance_name, args, scope) => {

    // get/load instance
    //console.log('Instance.factory:', instance_name);
    const obs = new EE();
    const cache_key = 'i:' + instance_name;
    const onModule = (_obs) => {
        _obs.on('ready', (module) => {

            var instance = Object.create(module);
            instance.flow = (inst_name, event, args) => {
                scope.flow(inst_name || instance_name, event, args);
            };
            instance._name = instance_name;
            instance._reset = scope.reset;

            obs.instance = instance;
            check(obs);
        });
    };

    const check = (obs) => {

        if (!obs.instance || !obs.args) {
            return;
        }

        let args = obs.args;
        let instance = obs.instance;
        let ready = function (err, data) {

            if (err) {
                return obs.emit('error', err);
            }

            // update cache
            scope.cache.set(cache_key, instance);

            // ?mark instance as ready
            //obs.ready = true;

            obs.emit('ready', instance);
        };

        // append args to instance, for modules with no init method
        instance._args = args;

        // init loader instance
        instance.init ? instance.init(args, ready) : ready();
    };

    const onArgs = (_obs) => {
        _obs.on('ready', (args) => {
            obs.args = args[instance_name] || {};
            check(obs);
        });
    };

    obs.module = onModule;
    obs.args = onArgs;

    // get cached instance
    let cached_inst = scope.cache.get(cache_key);
    if (cached_inst) {
        process.nextTick(() => {
            obs.emit('ready', cached_inst);
        });
        return obs;
    }

    if (cached_inst === null) {
        return obs;
    }
    scope.cache.set(cache_key, null);

    // TODO load module instance configuration
    scope.read(instance_name, null, args);

    return obs;
};
<commit_msg>instances are loaded within event<commit_after>const EE = require('events');

module.exports = (instance_name, args, scope) => {

    // get/load instance
    //console.log('Instance.factory:', instance_name);
    const obs = new EE();
    const cache_key = 'i:' + instance_name;
    const onModule = (_obs) => {
        _obs.on('ready', (module) => {

            var instance = Object.create(module);
            instance.flow = (inst_name, event, args) => {
                scope.flow(inst_name || instance_name, event, args);
            };
            instance._name = instance_name;
            instance._reset = scope.reset;

            obs.instance = instance;
            check(obs);
        });
        return obs;
    };

    const check = (obs) => {

        if (!obs.instance || !obs.args) {
            return;
        }

        let args = obs.args;
        let instance = obs.instance;
        let ready = function (err, data) {

            if (err) {
                return obs.emit('error', err);
            }

            // update cache
            scope.cache.set(cache_key, instance);

            // ?mark instance as ready
            //obs.ready = true;

            obs.emit('ready', instance);
        };

        // append args to instance, for modules with no init method
        instance._args = args;

        // init loader instance
        instance.init ? instance.init(args, ready) : ready();
    };

    const onArgs = (_obs) => {
        _obs.on('ready', (args) => {
            obs.args = args[instance_name] || {};
            check(obs);
        });
        return obs;
    };

    obs.module = onModule;
    obs.args = onArgs;

    // get cached instance
    let cached_inst = scope.cache.get(cache_key);
    if (cached_inst) {
        process.nextTick(() => {
            obs.emit('ready', cached_inst);
        });
        return obs;
    }

    if (cached_inst === null) {
        return obs;
    }
    scope.cache.set(cache_key, null);

    return obs;
};
<|endoftext|>