<commit_before>#!/usr/bin/env node
"use strict";

var db,
    path   = require("path"),
    fs     = require("fs"),
    spin   = require("char-spinner"),
    isCLI  = require.main === module,
    dbPath = path.join(__dirname + "/db.json"),
    source = "http://standards.ieee.org/develop/regauth/oui/oui.txt",
    strictFormats = [
        /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/,
        /^([0-9A-F]{2}[:-]){2}([0-9A-F]{2})$/,
        /^([0-9A-F]{4}[.]){2}([0-9A-F]{4})$/,
        /^[0-9A-F]{6}$/,
        /^[0-9A-F]{12}$/
    ];

function oui(input, opts, cb) {
    if (typeof opts === "function" && typeof cb === "undefined") {
        cb = opts;
        opts = null;
    }

    if (opts && opts.strict) {
        var matched;
        input = input.toUpperCase();
        matched = strictFormats.some(function (regex) {
            if (regex.test(input)) return true;
        });
        if (!matched)
            return cb(new Error("Input '" + input + "' " + "violates strict mode."));
        input = input.replace(/[.:-]/g, "").substring(0, 6);
    } else {
        input = input.replace(/[^0-9a-fA-F]/g, "").substring(0, 6).toUpperCase();
    }

    if (input.length < 6) {
        cb(new Error("Please provide at least 6 hexadecimal digits."));
    } else {
        if (db) {
            lookup(input, cb);
        } else {
            fs.readFile(dbPath, function (err, data) {
                if (err) return cb(err);
                try {
                    db = JSON.parse(data);
                } catch (err) {
                    return cb(err);
                }
                lookup(input, cb);
            });
        }
    }
}

oui.update = function (cb) {
    var interval;

    if (isCLI) {
        process.stdout.write("Fetching " + source + " ...\n");
        interval = spin();
    }

    require("got")(source, function (err, body) {
        if (isCLI) {
            if (err) return process.stdout.write(err);
            if (interval) clearInterval(interval);
            spin.clear();
        }
        if (err) return cb(err);
        parse(body.split("\n"), function (result) {
            fs.writeFile(dbPath, JSON.stringify(result, null, 4), function () {
                if (cb) cb();
            });
        });
    });
};

function lookup(input, cb) {
    if (typeof db[input] !== "undefined")  {
        cb(null, db[input]);
    } else {
        cb(new Error("Prefix '" + input + "' not found in database."));
    }
}

function isStart(firstLine, secondLine) {
    if (firstLine === undefined || secondLine === undefined) return false;
    return firstLine.trim().length === 0 && /([0-9A-F]{2}[-]){2}([0-9A-F]{2})/.test(secondLine);
}

function parse(lines, cb) {
    var result = {}, i = 6;
    while (i !== lines.length) {
        if (isStart(lines[i], lines[i + 1])) {
            var oui   = lines[i + 2].substring(2, 10).trim(),
                owner = lines[i + 1].replace(/\((hex|base 16)\)/, "").substring(10).trim();

            i += 3;
            while (!isStart(lines[i], lines[i + 1]) && i < lines.length) {
                if (lines[i] && lines[i].trim()) owner += "\n" + lines[i].trim();
                i++;
            }
            result[oui] = owner;
        }
    }
    if (cb) cb(result);
}

if (isCLI && process.argv.length >= 2) {
    var arg = process.argv[2];
    if (arg === "--update") {
        oui.update(function (err) {
            if (err) {
                process.stdout.write(err + "\n");
            } else {
                process.stdout.write("Database updated successfully!\n");
            }
            process.exit(err ? 1 : 0);
        });
    } else if (!arg) {
        fs.readFile(path.join(__dirname + "/package.json"), function (err, data) {
            var pkg = JSON.parse(data);
            process.stdout.write([
                pkg.name + "@" + pkg.version + " - " + pkg.homepage,
                "",
                "Usage: ",
                "  oui MAC                 Look up an MAC-address or OUI prefix.",
                "  oui --update            Update the database.\n"
            ].join("\n"));
            process.exit(1);
        });
    } else {
        oui(arg, function (err, result) {
            if (err) {
                process.stdout.write(err.message + "\n");
                process.exit(1);
            } else {
                process.stdout.write(result + "\n");
                process.exit(0);
            }
        });
    }
}

exports = module.exports = oui;
<commit_msg>Reformat CLI help<commit_after>#!/usr/bin/env node
"use strict";

var db,
    path   = require("path"),
    fs     = require("fs"),
    spin   = require("char-spinner"),
    isCLI  = require.main === module,
    dbPath = path.join(__dirname + "/db.json"),
    source = "http://standards.ieee.org/develop/regauth/oui/oui.txt",
    strictFormats = [
        /^([0-9A-F]{2}[:-]){5}([0-9A-F]{2})$/,
        /^([0-9A-F]{2}[:-]){2}([0-9A-F]{2})$/,
        /^([0-9A-F]{4}[.]){2}([0-9A-F]{4})$/,
        /^[0-9A-F]{6}$/,
        /^[0-9A-F]{12}$/
    ];

function oui(input, opts, cb) {
    if (typeof opts === "function" && typeof cb === "undefined") {
        cb = opts;
        opts = null;
    }

    if (opts && opts.strict) {
        var matched;
        input = input.toUpperCase();
        matched = strictFormats.some(function (regex) {
            if (regex.test(input)) return true;
        });
        if (!matched)
            return cb(new Error("Input '" + input + "' " + "violates strict mode."));
        input = input.replace(/[.:-]/g, "").substring(0, 6);
    } else {
        input = input.replace(/[^0-9a-fA-F]/g, "").substring(0, 6).toUpperCase();
    }

    if (input.length < 6) {
        cb(new Error("Please provide at least 6 hexadecimal digits."));
    } else {
        if (db) {
            lookup(input, cb);
        } else {
            fs.readFile(dbPath, function (err, data) {
                if (err) return cb(err);
                try {
                    db = JSON.parse(data);
                } catch (err) {
                    return cb(err);
                }
                lookup(input, cb);
            });
        }
    }
}

oui.update = function (cb) {
    var interval;

    if (isCLI) {
        process.stdout.write("Fetching " + source + " ...\n");
        interval = spin();
    }

    require("got")(source, function (err, body) {
        if (isCLI) {
            if (err) return process.stdout.write(err);
            if (interval) clearInterval(interval);
            spin.clear();
        }
        if (err) return cb(err);
        parse(body.split("\n"), function (result) {
            fs.writeFile(dbPath, JSON.stringify(result, null, 4), function () {
                if (cb) cb();
            });
        });
    });
};

function lookup(input, cb) {
    if (typeof db[input] !== "undefined")  {
        cb(null, db[input]);
    } else {
        cb(new Error("Prefix '" + input + "' not found in database."));
    }
}

function isStart(firstLine, secondLine) {
    if (firstLine === undefined || secondLine === undefined) return false;
    return firstLine.trim().length === 0 && /([0-9A-F]{2}[-]){2}([0-9A-F]{2})/.test(secondLine);
}

function parse(lines, cb) {
    var result = {}, i = 6;
    while (i !== lines.length) {
        if (isStart(lines[i], lines[i + 1])) {
            var oui   = lines[i + 2].substring(2, 10).trim(),
                owner = lines[i + 1].replace(/\((hex|base 16)\)/, "").substring(10).trim();

            i += 3;
            while (!isStart(lines[i], lines[i + 1]) && i < lines.length) {
                if (lines[i] && lines[i].trim()) owner += "\n" + lines[i].trim();
                i++;
            }
            result[oui] = owner;
        }
    }
    if (cb) cb(result);
}

if (isCLI && process.argv.length >= 2) {
    var arg = process.argv[2];
    if (arg === "--update") {
        oui.update(function (err) {
            if (err) {
                process.stdout.write(err + "\n");
            } else {
                process.stdout.write("Database updated successfully!\n");
            }
            process.exit(err ? 1 : 0);
        });
    } else if (!arg) {
        fs.readFile(path.join(__dirname + "/package.json"), function (err, data) {
            var pkg = JSON.parse(data);
            process.stdout.write([
                "",
                "  Usage: oui mac [options]",
                "",
                "  Options:",
                "",
                "    --update    update the database",
                "",
                ""
            ].join("\n"));
            process.exit(1);
        });
    } else {
        oui(arg, function (err, result) {
            if (err) {
                process.stdout.write(err.message + "\n");
                process.exit(1);
            } else {
                process.stdout.write(result + "\n");
                process.exit(0);
            }
        });
    }
}

exports = module.exports = oui;
<|endoftext|>


<commit_before>var pduParser = {};

pduParser.parse = function(pdu) {
    //Cursor points to the last octet we've read.
    var cursor = 0;

    var smscSize = parseInt(pdu.slice(0, 2), 16);
    cursor += 2;

    var smscType = pdu.slice(cursor, cursor+2);
    cursor += 2;

    var smscNum  = pduParser.deSwapNibbles(pdu.slice(cursor, smscSize*2+2));
    cursor = smscSize*2+2;

    var smsDeliver = parseInt(pdu.slice(cursor, cursor+2), 16);
    cursor += 2;

    var smsDeliverBits = ("00000000"+parseInt(smsDeliver).toString(2)).slice(-8);
    var udhi = smsDeliverBits.slice(1,2) === "1";

    var senderSize = parseInt(pdu.slice(cursor, cursor+2), 16);
    if(senderSize % 2 === 1)
        senderSize++;
    cursor += 2;

    var senderType = pdu.slice(cursor, cursor+2);
    cursor += 2;

    var senderNum = pduParser.deSwapNibbles(pdu.slice(cursor, cursor+senderSize));
    cursor += senderSize;

    var protocolIdentifier = pdu.slice(cursor, cursor+2);
    cursor += 2;

    var dataCodingScheme = pdu.slice(cursor, cursor+2);
    cursor = cursor+2;

    var encoding = pduParser.detectEncoding(dataCodingScheme);

    var timestamp = pduParser.deSwapNibbles(pdu.slice(cursor, cursor+14));
    var time = new Date('20'+timestamp.slice(0,2), timestamp.slice(2,4)-1, timestamp.slice(4,6), timestamp.slice(6,8), timestamp.slice(8,10), timestamp.slice(10,12));
    var time = time.getTime();
    time += ((timestamp.slice(12,14)*15)*1000) * 60; //Apply timezone offset.
    cursor += 14;

    var dataLength = parseInt(pdu.slice(cursor, cursor+2), 16).toString(10);
    cursor += 2;

    if(udhi) { //User-Data-Header-Indicator: means there's some User-Data-Header.
        var udhLength = pdu.slice(cursor, cursor+2);
        var iei = pdu.slice(cursor+2, cursor+4);
        if(iei == "00") { //Concatenaded sms.
            var headerLength = pdu.slice(cursor+4, cursor+6);
            var referenceNumber = pdu.slice(cursor+6, cursor+8);
            var parts = pdu.slice(cursor+8, cursor+10);
            var currentPart = pdu.slice(cursor+10, cursor+12);
        }

        if(iei == "08") { //Concatenaded sms with a two-bytes reference number
            var headerLength = pdu.slice(cursor+4, cursor+6);
            var referenceNumber = pdu.slice(cursor+6, cursor+10);
            var parts = pdu.slice(cursor+10, cursor+12);
            var currentPart = pdu.slice(cursor+12, cursor+14);
        }

        if(encoding === '16bit')
            if(iei == '00')
                cursor += (udhLength-2)*4;
            else if(iei == '08')
                cursor += ((udhLength-2)*4)+2;
        else
            cursor += (udhLength-2)*2;
    }

    if(encoding === '16bit')
        var text = pduParser.decode16Bit(pdu.slice(cursor), dataLength);
    else if(encoding === '7bit')
        var text = pduParser.decode7Bit(pdu.slice(cursor), dataLength);
    else if(encoding === '8bit')
        var text = ''; //TODO

    var data = {
        'smsc' : smscNum,
        'smsc_type' : smscType,
        'sender' : senderNum,
        'sender_type' : senderType,
        'encoding' : encoding,
        'time' : time,
        'text' : text
    };

    if(udhi) {
        data['udh'] = {
            'length' : udhLength,
            'iei' : iei,
        };

        if(iei == '00' || iei == '08') {
            data['udh']['reference_number'] = referenceNumber;
            data['udh']['parts'] = parseInt(parts);
            data['udh']['current_part'] = parseInt(currentPart);
        }
    }

    return data;
}

pduParser.detectEncoding = function(dataCodingScheme) {
    var binary = ('00000000'+(parseInt(dataCodingScheme, 16).toString(2))).slice(-8);

    if(binary == '00000000')
        return '7bit';

    if(binary.slice(0, 2) === '00') {
        var compressed = binary.slice(2, 1) === '1';
        var bitsHaveMeaning = binary.slice(3, 1) === '1';

        if(binary.slice(4,6) === '00')
            return '7bit';

        if(binary.slice(4,6) === '01')
            return '8bit';

        if(binary.slice(4,6) === '10')
            return '16bit';
    }
}

pduParser.decode16Bit = function(data, length) {
    //We are getting ucs2 characters.
    var ucs2 = '';
    for(var i = 0;i<=data.length;i=i+4) {
        ucs2 += String.fromCharCode("0x"+data[i]+data[i+1]+data[i+2]+data[i+3]);
    }

    return ucs2;
}

pduParser.deSwapNibbles = function(nibbles) {
    var out = '';
    for(var i = 0; i< nibbles.length; i=i+2) {
        if(nibbles[i] === 'F') //Dont consider trailing F.
            out += parseInt(nibbles[i+1], 16).toString(10);
        else
            out += parseInt(nibbles[i+1], 16).toString(10)+parseInt(nibbles[i], 16).toString(10);
    }
    return out;
}

pduParser.decode7Bit = function(code, count) {
    //We are getting 'septeps'. We should decode them.
    var binary = '';
    for(var i = 0; i<code.length;i++)
        binary += ('0000'+parseInt(code.slice(i,i+1), 16).toString(2)).slice(-4);

    var bin = Array();
    var cursor = 0;
    var fromPrevious = '';
    var i = 0;
    while(binary[i]) {
        var remaining = 7 - fromPrevious.length;
        var toNext = 8 - remaining;
        bin[i] = binary.slice(cursor+toNext, cursor+toNext+remaining) + fromPrevious;
        var fromPrevious = binary.slice(cursor, cursor+toNext);
        if(toNext === 8)
            fromPrevious = '';
        else
            cursor += 8;
        i++;
    }

    var ascii = '';
    for(i in bin)
        ascii += String.fromCharCode(parseInt(bin[i], 2));

    return ascii;
}

pduParser.encode7Bit = function(ascii) {
    //We should create septeps now.
    var octets = new Array();
    for(var i = 0; i<ascii.length; i++)
        octets.push(('0000000'+(ascii.charCodeAt(i).toString(2))).slice(-7));

    for(var i in octets) {
        var i = parseInt(i);
        var freeSpace = 8 - octets[i].length;

        if(octets[i+1] && freeSpace !== 8) {
            octets[i] = octets[i+1].slice(7-freeSpace) + octets[i];
            octets[i+1] = octets[i+1].slice(0, 7-freeSpace);
        }
    }

    var hex = '';
    for(i in octets)
        if(octets[i].length > 0)
            hex += ('00'+(parseInt(octets[i], 2).toString(16))).slice(-2);
    return hex;
}

//TODO: TP-Validity-Period (Delivery)
pduParser.generate = function(message) {
    var pdu = '00';

    var parts = 1;
    if(message.encoding === '16bit' && message.text.length > 70)
        parts = message.text.length / 66;

    else if(message.encoding === '7bit' && message.text.length > 160)
        parts = message.text.length / 153;

    parts = Math.ceil(parts);

    TPMTI  = 1;
    TPRD   = 4;
    TPVPF  = 8;
    TPSRR  = 32;
    TPUDHI = 64;
    TPRP   = 128;

    var submit = TPMTI;

    if(parts > 1) //UDHI
        submit = submit | TPUDHI;

    submit = submit | TPSRR;

    pdu += submit.toString(16);

    pdu += '00'; //TODO: Reference Number;

    var receiverSize = ('00'+(parseInt(message.receiver.length, 10).toString(16))).slice(-2);
    var receiver = pduParser.swapNibbles(message.receiver);
    var receiverType = 81; //TODO: NOT-Hardcoded PDU generation. Please note that Hamrah1 doesnt work if we set it to 91 (International).

    pdu += receiverSize.toString(16) + receiverType + receiver;

    pdu += '00'; //TODO TP-PID

    pdu += '08'; //TODO: TP-CS

    var pdus = new Array();

    for(var i=0; i< parts; i++) {
        pdus[i] = pdu;

        if(message.encoding === '16bit') {
            /* If there are more than one messages to be sent, we are going to have to put some UDH. Then, we would have space only
             * for 66 UCS2 characters instead of 77 */
            if(parts === 1)
                var length = 70;
            else
                var length = 66;
        } else if(message.encoding === '7bit') {
            /* If there are more than one messages to be sent, we are going to have to put some UDH. Then, we would have space only
             * for 153 UCS2 characters instead of 160 */
            if(parts === 1)
                var length = 160;
            else
                var length = 153;
        }

        var user_data = message.text.slice(i*length, (i*length)+length);
        pdus[i] += ('00'+parseInt(user_data.length*2).toString(16)).slice(-2);

        user_data = pduParser.encode16Bit(user_data); //TODO: 7Bit  PDU generation

        if(parts > 1) {
            pdus[i] += '05';
            pdus[i] += '00';
            pdus[i] += '03';
            pdus[i] += '00';
            pdus[i] += ('00'+parts.toString(16)).slice(-2);
            pdus[i] += ('00'+(i+1).toString(16)).slice(-2);
        }
        pdus[i] += user_data;
    }

    return pdus;
}

pduParser.encode16Bit = function(text) {
    var out = '';
    for(var i = 0; i<text.length;i++) {
        out += ('0000'+(parseInt(text.charCodeAt(i), 10).toString(16))).slice(-4);
    }
    return out;
}

pduParser.swapNibbles = function(nibbles) {
    var out = '';
    for(var i = 0; i< nibbles.length; i=i+2) {
        if(typeof(nibbles[i+1]) === 'undefined') // Add a trailing F.
            out += 'F'+parseInt(nibbles[i], 16).toString(10);
        else
            out += parseInt(nibbles[i+1], 16).toString(10)+parseInt(nibbles[i], 16).toString(10);
    }
    return out;
}

pduParser.parseStatusReport = function(pdu) {
    //Cursor points to the last octet we've read.
    var cursor = 0;

    var smscSize = parseInt(pdu.slice(0, 2), 16);
    cursor += 2;

    var smscType = parseInt(pdu.slice(cursor, cursor+2), 16);
    cursor += 2;

    var smscNum  = pduParser.deSwapNibbles(pdu.slice(cursor, (smscSize*2)+2));
    cursor = (smscSize*2+2);

    var header = parseInt(pdu.slice(cursor,cursor+2));
    cursor += 2;

    var reference = parseInt(pdu.slice(cursor,cursor+2), 16);
    cursor += 2;

    var senderSize = parseInt(pdu.slice(cursor,cursor+2), 16);
    if(senderSize % 2 === 1)
        senderSize++;
    cursor += 2;

    var senderType = parseInt(pdu.slice(cursor,cursor+2));
    cursor += 2;

    var sender = pduParser.deSwapNibbles(pdu.slice(cursor, cursor+senderSize));

    var status = pdu.slice(-2);

    return {
        smsc:smscNum,
        reference:reference,
        sender:sender,
        status:status
    }
}

if(module && module.exports)
    module.exports = pduParser;<commit_msg>Lots of fixes.<commit_after>var pduParser = {};

pduParser.parse = function(pdu) {
    //Cursor points to the last octet we've read.
    var cursor = 0;

    var buffer = new Buffer(pdu.slice(0,4), 'hex');
    var smscSize = buffer[0];
    var smscType = buffer[1].toString(16);
    cursor = (smscSize*2+2);
    var smscNum  = pduParser.deSwapNibbles(pdu.slice(4, cursor));

    var buffer = new Buffer(pdu.slice(cursor,cursor+6), 'hex');
    cursor += 6;
    var smsDeliver = buffer[0];

    var smsDeliverBits = ("00000000"+parseInt(smsDeliver).toString(2)).slice(-8);
    var udhi = smsDeliverBits.slice(1,2) === "1";

    var senderSize = buffer[1];
    if(senderSize % 2 === 1)
        senderSize++;

    var senderType = parseInt(buffer[2]).toString(16)

    var senderNum = pduParser.deSwapNibbles(pdu.slice(cursor, cursor+senderSize));
    cursor += senderSize;

    var protocolIdentifier = pdu.slice(cursor, cursor+2);
    cursor += 2;

    var dataCodingScheme = pdu.slice(cursor, cursor+2);
    cursor = cursor+2;

    var encoding = pduParser.detectEncoding(dataCodingScheme);

    var timestamp = pduParser.deSwapNibbles(pdu.slice(cursor, cursor+14));

    var time = new Date;
    time.setUTCFullYear('20'+timestamp.slice(0,2));
    time.setUTCMonth(timestamp.slice(2,4)-1);
    time.setUTCDate(timestamp.slice(4,6));
    time.setUTCHours(timestamp.slice(6,8));
    time.setUTCMinutes(timestamp.slice(8,10));
    time.setUTCSeconds(timestamp.slice(10,12));

    var firstTimezoneOctet = parseInt(timestamp.slice(12,13));
    var binary = ("0000"+firstTimezoneOctet.toString(2)).slice(-4);
    var factor = binary.slice(0,1) === '1' ? 1 : -1;
    var binary = '0'+binary.slice(1, 4);
    var firstTimezoneOctet = parseInt(binary, 2).toString(10);
    var timezoneDiff = parseInt(firstTimezoneOctet + timestamp.slice(13, 14));
    var time = new Date(time.getTime() + (timezoneDiff * 15 * 1000 * 60 * factor));

    cursor += 14;

    var dataLength = parseInt(pdu.slice(cursor, cursor+2), 16).toString(10);
    cursor += 2;

    if(udhi) { //User-Data-Header-Indicator: means there's some User-Data-Header.
        var udhLength = pdu.slice(cursor, cursor+2);
        var iei = pdu.slice(cursor+2, cursor+4);
        if(iei == "00") { //Concatenated sms.
            var headerLength = pdu.slice(cursor+4, cursor+6);
            var referenceNumber = pdu.slice(cursor+6, cursor+8);
            var parts = pdu.slice(cursor+8, cursor+10);
            var currentPart = pdu.slice(cursor+10, cursor+12);
        }

        if(iei == "08") { //Concatenaded sms with a two-bytes reference number
            var headerLength = pdu.slice(cursor+4, cursor+6);
            var referenceNumber = pdu.slice(cursor+6, cursor+10);
            var parts = pdu.slice(cursor+10, cursor+12);
            var currentPart = pdu.slice(cursor+12, cursor+14);
        }

        if(encoding === '16bit')
            if(iei == '00')
                cursor += (udhLength-2)*4;
            else if(iei == '08')
                cursor += ((udhLength-2)*4)+2;
        else
            cursor += (udhLength-2)*2;
    }

    if(encoding === '16bit')
        var text = pduParser.decode16Bit(pdu.slice(cursor), dataLength);
    else if(encoding === '7bit')
        var text = pduParser.decode7Bit(pdu.slice(cursor), dataLength);
    else if(encoding === '8bit')
        var text = ''; //TODO

    var data = {
        'smsc' : smscNum,
        'smsc_type' : smscType,
        'sender' : senderNum,
        'sender_type' : senderType,
        'encoding' : encoding,
        'time' : time,
        'text' : text
    };

    if(udhi) {
        data['udh'] = {
            'length' : udhLength,
            'iei' : iei,
        };

        if(iei == '00' || iei == '08') {
            data['udh']['reference_number'] = referenceNumber;
            data['udh']['parts'] = parseInt(parts);
            data['udh']['current_part'] = parseInt(currentPart);
        }
    }

    return data;
}

pduParser.detectEncoding = function(dataCodingScheme) {
    var binary = ('00000000'+(parseInt(dataCodingScheme, 16).toString(2))).slice(-8);

    if(binary == '00000000')
        return '7bit';

    if(binary.slice(0, 2) === '00') {
        var compressed = binary.slice(2, 1) === '1';
        var bitsHaveMeaning = binary.slice(3, 1) === '1';

        if(binary.slice(4,6) === '00')
            return '7bit';

        if(binary.slice(4,6) === '01')
            return '8bit';

        if(binary.slice(4,6) === '10')
            return '16bit';
    }
}

pduParser.decode16Bit = function(data, length) {
    //We are getting ucs2 characters.
    var ucs2 = '';
    for(var i = 0;i<=data.length;i=i+4) {
        ucs2 += String.fromCharCode("0x"+data[i]+data[i+1]+data[i+2]+data[i+3]);
    }

    return ucs2;
}

pduParser.deSwapNibbles = function(nibbles) {
    var out = '';
    for(var i = 0; i< nibbles.length; i=i+2) {
        if(nibbles[i] === 'F') //Dont consider trailing F.
            out += parseInt(nibbles[i+1], 16).toString(10);
        else
            out += parseInt(nibbles[i+1], 16).toString(10)+parseInt(nibbles[i], 16).toString(10);
    }
    return out;
}

pduParser.decode7Bit = function(code, count) {
    //We are getting 'septeps'. We should decode them.
    var binary = '';
    for(var i = 0; i<code.length;i++)
        binary += ('0000'+parseInt(code.slice(i,i+1), 16).toString(2)).slice(-4);

    var bin = Array();
    var cursor = 0;
    var fromPrevious = '';
    var i = 0;
    while(binary[i]) {
        var remaining = 7 - fromPrevious.length;
        var toNext = 8 - remaining;
        bin[i] = binary.slice(cursor+toNext, cursor+toNext+remaining) + fromPrevious;
        var fromPrevious = binary.slice(cursor, cursor+toNext);
        if(toNext === 8)
            fromPrevious = '';
        else
            cursor += 8;
        i++;
    }

    var ascii = '';
    for(i in bin)
        ascii += String.fromCharCode(parseInt(bin[i], 2));

    return ascii;
}

pduParser.encode7Bit = function(ascii) {
    //We should create septeps now.
    var octets = new Array();
    for(var i = 0; i<ascii.length; i++)
        octets.push(('0000000'+(ascii.charCodeAt(i).toString(2))).slice(-7));

    for(var i in octets) {
        var i = parseInt(i);
        var freeSpace = 8 - octets[i].length;

        if(octets[i+1] && freeSpace !== 8) {
            octets[i] = octets[i+1].slice(7-freeSpace) + octets[i];
            octets[i+1] = octets[i+1].slice(0, 7-freeSpace);
        }
    }

    var hex = '';
    for(i in octets)
        if(octets[i].length > 0)
            hex += ('00'+(parseInt(octets[i], 2).toString(16))).slice(-2);
    return hex;
}

//TODO: TP-Validity-Period (Delivery)
pduParser.generate = function(message) {
    var pdu = '00';

    var parts = 1;
    if(message.encoding === '16bit' && message.text.length > 70)
        parts = message.text.length / 66;

    else if(message.encoding === '7bit' && message.text.length > 160)
        parts = message.text.length / 153;

    parts = Math.ceil(parts);

    TPMTI  = 1;
    TPRD   = 4;
    TPVPF  = 8;
    TPSRR  = 32;
    TPUDHI = 64;
    TPRP   = 128;

    var submit = TPMTI;

    if(parts > 1) //UDHI
        submit = submit | TPUDHI;

    submit = submit | TPSRR;

    pdu += submit.toString(16);

    pdu += '00'; //TODO: Reference Number;

    var receiverSize = ('00'+(parseInt(message.receiver.length, 10).toString(16))).slice(-2);
    var receiver = pduParser.swapNibbles(message.receiver);
    var receiverType = 81; //TODO: NOT-Hardcoded PDU generation. Please note that Hamrah1 doesnt work if we set it to 91 (International).

    pdu += receiverSize.toString(16) + receiverType + receiver;

    pdu += '00'; //TODO TP-PID

    if(message.encoding === '16bit')
        pdu += '08';
    else if(message.encoding === '7bit')
        pdu += '00';

    var pdus = new Array();

    for(var i=0; i< parts; i++) {
        pdus[i] = pdu;

        if(message.encoding === '16bit') {
            /* If there are more than one messages to be sent, we are going to have to put some UDH. Then, we would have space only
             * for 66 UCS2 characters instead of 70 */
            if(parts === 1)
                var length = 70;
            else
                var length = 66;

        } else if(message.encoding === '7bit') {
            /* If there are more than one messages to be sent, we are going to have to put some UDH. Then, we would have space only
             * for 153 ASCII characters instead of 160 */
            if(parts === 1)
                var length = 160;
            else
                var length = 153;
        }
        var text = message.text.slice(i*length, (i*length)+length);

        if(message.encoding === '16bit') {
            user_data = pduParser.encode16Bit(text);
            var size = (user_data.length / 2);

            if(parts > 1)
                size += 6; //6 is the number of data headers we append.

        } else if(message.encoding === '7bit') {
            user_data = pduParser.encode7Bit(text);
            var size = user_data.length / 2;
        }

        pdus[i] += ('00'+parseInt(size).toString(16)).slice(-2);

        if(parts > 1) {
            pdus[i] += '05';
            pdus[i] += '00';
            pdus[i] += '03';
            pdus[i] += '00';
            pdus[i] += ('00'+parts.toString(16)).slice(-2);
            pdus[i] += ('00'+(i+1).toString(16)).slice(-2);
        }
        pdus[i] += user_data;
    }

    return pdus;
}

pduParser.encode16Bit = function(text) {
    var out = '';
    for(var i = 0; i<text.length;i++) {
        out += ('0000'+(parseInt(text.charCodeAt(i), 10).toString(16))).slice(-4);
    }
    return out;
}

pduParser.swapNibbles = function(nibbles) {
    var out = '';
    for(var i = 0; i< nibbles.length; i=i+2) {
        if(typeof(nibbles[i+1]) === 'undefined') // Add a trailing F.
            out += 'F'+parseInt(nibbles[i], 16).toString(10);
        else
            out += parseInt(nibbles[i+1], 16).toString(10)+parseInt(nibbles[i], 16).toString(10);
    }
    return out;
}

pduParser.parseStatusReport = function(pdu) {
    //Cursor points to the last octet we've read.
    var cursor = 0;

    var smscSize = parseInt(pdu.slice(0, 2), 16);
    cursor += 2;

    var smscType = parseInt(pdu.slice(cursor, cursor+2), 16);
    cursor += 2;

    var smscNum  = pduParser.deSwapNibbles(pdu.slice(cursor, (smscSize*2)+2));
    cursor = (smscSize*2+2);

    var header = parseInt(pdu.slice(cursor,cursor+2));
    cursor += 2;

    var reference = parseInt(pdu.slice(cursor,cursor+2), 16);
    cursor += 2;

    var senderSize = parseInt(pdu.slice(cursor,cursor+2), 16);
    if(senderSize % 2 === 1)
        senderSize++;
    cursor += 2;

    var senderType = parseInt(pdu.slice(cursor,cursor+2));
    cursor += 2;

    var sender = pduParser.deSwapNibbles(pdu.slice(cursor, cursor+senderSize));

    var status = pdu.slice(-2);

    return {
        smsc:smscNum,
        reference:reference,
        sender:sender,
        status:status
    }
}

module.exports = pduParser;

<|endoftext|>


<commit_before>var http=require("http");
var fs=require("fs");

var readAndDo=function(path,f){
  fs.readFile(path,'utf8',function(err,data){
    if(err)console.log(err);
    else f(data);
  });
};

var route=function(req,res){
  readAndDo('index.phpjs',function(erm){
    var C=0;
    var O={};
    res.end(erm.replace(/<\?js(.|\s)*?\?>/mg,function(x){
      var R="";
      var echo=function(x){
        R+=(x+'\n');
        console.log(x);
        return x;
      };
      eval(x.slice(4,-3));
      return R;
    }));
  });
};

var server=http.createServer(route);
server.listen(8080);
<commit_msg>exportable as a lib<commit_after>var http=require("http");
var fs=require("fs");
var php={};

var readAndDo=php.readAndDo=function(path,f){
  fs.readFile(path,'utf8',function(err,data){
    if(err)console.log(err);
    else f(data);
  });
  return '';
};

var main=php.main=function(opt){
  opt=opt||{};
  var path=opt.path||"";
  var def=opt.def||'index.phpjs';

  return function(req,res){
    console.log(readAndDo(path+(req.url.slice(1)||def),function(erm){
      var C=0;
      var O={};
      res.end(erm.replace(/<\?js(.|\s)*?\?>/mg,function(x){
        var R="";
        var echo=function(x){
          R+=(x+'\n');
          console.log(x);
          return x;
        };
        eval(x.slice(4,-3));
        return R;
      }));
    }));
  };
};

if(!module.parent){
  var server=http.createServer(main({path:'views/'}));
  server.listen(8080);
}else{
  module.exports=php;
}
<|endoftext|>


<commit_before>export class Pos {
  constructor(path, offset) {
    this.path = path
    this.offset = offset
  }

  toString() {
    return this.path.join("/") + ":" + this.offset
  }

  get depth() {
    return this.path.length
  }

  static cmp(pathA, offsetA, pathB, offsetB) {
    let lenA = pathA.length, lenB = pathB.length
    for (var i = 0, end = Math.min(lenA, lenB); i < end; i++) {
      var diff = pathA[i] - pathB[i]
      if (diff != 0) return diff
    }
    if (lenA > lenB)
      return offsetB <= pathA[i] ? 1 : -1
    else if (lenB > lenA)
      return offsetA <= pathB[i] ? -1 : 1
    else
      return offsetA - offsetB
  }

  static samePath(pathA, pathB) {
    if (pathA.length != pathB.length) return false
    for (let i = 0; i < pathA.length; i++) if (pathA[i] !== pathB[i]) return false
    return true
  }

  cmp(other) {
    if (other == this) return 0
    return Pos.cmp(this.path, this.offset, other.path, other.offset)
  }

  static shorten(path, to = null, offset = 0) {
    if (to == null) to = path.length - 1
    return new Pos(path.slice(0, to), path[to] + offset)
  }

  shorten(to = null, offset = 0) {
    if (to >= this.depth) return this
    return Pos.shorten(this.path, to, offset)
  }

  move(by) {
    return new Pos(this.path, this.offset + by)
  }

  extend(pos) {
    let path = this.path.slice(), add = this.offset
    for (let i = 0; i < pos.path.length; i++) {
      path.push(pos.path[i] + add)
      add = 0
    }
    return new Pos(path, pos.offset + add)
  }

  toJSON() { return this }

  static fromJSON(json) { return new Pos(json.path, json.offset) }

  static after(node, pos) { return findAfter(node, pos, []) }
  static start(node) { return findLeft(node, []) }

  static before(node, pos) { return findBefore(node, pos, []) }
  static end(node) { return findRight(node, []) }

  static near(node, pos) { return Pos.after(node, pos) || Pos.before(node, pos) }
}

function findLeft(node, path) {
  if (node.isTextblock)
    return new Pos(path, 0)
  for (let i = 0; i < node.length; i++) {
    path.push(i)
    let found = findLeft(node.child(i), path)
    if (found) return found
    path.pop()
  }
}

function findAfter(node, pos, path) {
  if (node.isTextblock)
    return pos
  let atEnd = path.length == pos.path.length
  let start = atEnd ? pos.offset : pos.path[path.length]
  for (let i = start; i < node.length; i++) {
    path.push(i)
    let child = node.child(i)
    let found = i == start && !atEnd ? findAfter(child, pos, path) : findLeft(child, path)
    if (found) return found
    path.pop()
  }
}

function findRight(node, path) {
  if (node.isTextblock)
    return new Pos(path, node.maxOffset)
  for (let i = node.length - 1; i >= 0; i--) {
    path.push(i)
    let found = findRight(node.child(i), path)
    if (found) return found
    path.pop()
  }
}

function findBefore(node, pos, path) {
  if (node.isTextblock) return pos
  let atEnd = pos.path.length == path.length
  let end = atEnd ? pos.offset - 1 : pos.path[path.length]
  for (let i = end; i >= 0; i--) {
    path.push(i)
    let child = node.child(i)
    let found = i == end && !atEnd ? findBefore(child, pos, path) : findRight(child, path)
    if (found) return found
    path.pop()
  }
}
<commit_msg>Fix node selection with arrow keys<commit_after>export class Pos {
  constructor(path, offset) {
    this.path = path
    this.offset = offset
  }

  toString() {
    return this.path.join("/") + ":" + this.offset
  }

  get depth() {
    return this.path.length
  }

  static cmp(pathA, offsetA, pathB, offsetB) {
    let lenA = pathA.length, lenB = pathB.length
    for (var i = 0, end = Math.min(lenA, lenB); i < end; i++) {
      var diff = pathA[i] - pathB[i]
      if (diff != 0) return diff
    }
    if (lenA > lenB)
      return offsetB <= pathA[i] ? 1 : -1
    else if (lenB > lenA)
      return offsetA <= pathB[i] ? -1 : 1
    else
      return offsetA - offsetB
  }

  static samePath(pathA, pathB) {
    if (pathA.length != pathB.length) return false
    for (let i = 0; i < pathA.length; i++) if (pathA[i] !== pathB[i]) return false
    return true
  }

  cmp(other) {
    if (other == this) return 0
    return Pos.cmp(this.path, this.offset, other.path, other.offset)
  }

  static shorten(path, to = null, offset = 0) {
    if (to == null) to = path.length - 1
    return new Pos(path.slice(0, to), path[to] + offset)
  }

  shorten(to = null, offset = 0) {
    if (to >= this.depth) return this
    return Pos.shorten(this.path, to, offset)
  }

  move(by) {
    return new Pos(this.path, this.offset + by)
  }

  extend(pos) {
    let path = this.path.slice(), add = this.offset
    for (let i = 0; i < pos.path.length; i++) {
      path.push(pos.path[i] + add)
      add = 0
    }
    return new Pos(path, pos.offset + add)
  }

  toJSON() { return this }

  static fromJSON(json) { return new Pos(json.path, json.offset) }

  static after(node, pos) { return findAfter(node, pos, []) }
  static start(node) { return findLeft(node, []) }

  static before(node, pos) { return findBefore(node, pos, []) }
  static end(node) { return findRight(node, []) }

  static near(node, pos, bias) {
    return (bias > 0 && Pos.after(node, pos)) || Pos.before(node, pos) || Pos.after(node, pos)
  }
}

function findLeft(node, path) {
  if (node.isTextblock)
    return new Pos(path, 0)
  for (let i = 0; i < node.length; i++) {
    path.push(i)
    let found = findLeft(node.child(i), path)
    if (found) return found
    path.pop()
  }
}

function findAfter(node, pos, path) {
  if (node.isTextblock)
    return pos
  let atEnd = path.length == pos.path.length
  let start = atEnd ? pos.offset : pos.path[path.length]
  for (let i = start; i < node.length; i++) {
    path.push(i)
    let child = node.child(i)
    let found = i == start && !atEnd ? findAfter(child, pos, path) : findLeft(child, path)
    if (found) return found
    path.pop()
  }
}

function findRight(node, path) {
  if (node.isTextblock)
    return new Pos(path, node.maxOffset)
  for (let i = node.length - 1; i >= 0; i--) {
    path.push(i)
    let found = findRight(node.child(i), path)
    if (found) return found
    path.pop()
  }
}

function findBefore(node, pos, path) {
  if (node.isTextblock) return pos
  let atEnd = pos.path.length == path.length
  let end = atEnd ? pos.offset - 1 : pos.path[path.length]
  for (let i = end; i >= 0; i--) {
    path.push(i)
    let child = node.child(i)
    let found = i == end && !atEnd ? findBefore(child, pos, path) : findRight(child, path)
    if (found) return found
    path.pop()
  }
}
<|endoftext|>


<commit_before>(function () {

  var clues, solution, p = [0, 0];
  var startTime = new Date(), endTime, elapsedTime;

  var chars = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];

  function init()
  {
    jQuery.noConflict();

    // hexagonal puzzle
    if(jQuery("form.puzzle-hexagonal").length > 0)
    {
      clues = [
        // lol later
      ];
    }

    // rectangular puzzle
    else
    {
      clues = [
        jQuery("div.grid table tbody tr th:even span"),
        jQuery("div.grid table thead tr th:gt(0) span")
      ];
    }

    // change dom objects to regexs and setup clues array
    var dims = [];
    for(var i = 0; i < clues.length; i++)
    {
      dims.push(clues[i].length);
      for(var j = 0; j < clues[i].length; j++)
      {
        clues[i][j] = new RegExp(clues[i][j].getAttribute('title'));
      }
    }

    // setup solution array
    solution = createArray.apply(this, dims);
    setInitialArrayState(solution);

    //solve();

  }

  function solve()
  {
    var solved = false;

    // check for win condition

    if(solved)
    {
      endTime = new Date();
      elapsedTime = (endTime - startTime) / 1000;
      alert("Solved in " + elapsedTime + " seconds!");
      return;
    }

    // the fun part

    for(var i = 0; i < solution[p[0], p[1]].length; i++)
    {

    }

    solve();
  }

  // http://stackoverflow.com/a/966938
  function createArray(length)
  {
    var arr = new Array(length || 0), i = length;
    if(arguments.length > 1)
    {
      var args = Array.prototype.slice.call(arguments, 1);
      while(i--) arr[length-1 - i] = createArray.apply(this, args);
    }
    return arr;
  }

  // http://stackoverflow.com/a/15854485/3365483
  function zeroArray(arr)
  {
    for(var i = 0; i < arr.length; i++)
    {
      if(Array.isArray(arr[i])) zeroArray(arr[i]);
      else arr[i] = 0;
    }
  }

  var s = document.createElement("script");
  s.type = "text/javascript";
  s.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
  s.onload = init;
  document.getElementsByTagName("head")[0].appendChild(s);

})();
<commit_msg>Brute force approach<commit_after>(function () {

  var clues, solution, guesses = 1;
  var chars = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
  var startTime = new Date(), endTime, elapsedTime;

  function init()
  {
    jQuery.noConflict();

    // hexagonal puzzle
    if(jQuery("form.puzzle-hexagonal").length > 0)
    {
      clues = [
        // lol later
      ];
    }

    // rectangular puzzle
    else
    {
      clues = [
        jQuery("div.grid table tbody tr th:even span"),
        jQuery("div.grid table thead tr th:gt(0) span")
      ];
    }

    // change dom objects to regexs and setup clues array
    var dims = [];
    for(var i = 0; i < clues.length; i++)
    {
      dims.push(clues[i].length);
      for(var j = 0; j < clues[i].length; j++)
      {
        clues[i][j] = new RegExp(clues[i][j].getAttribute('title'));
      }
    }

    // setup solution array
    solution = createMultiDimArray.apply(this, dims);
    zeroArray(solution);

    // solve
    solve();

  }

  function solve()
  {
    // check for win condition
    var solved = true;

    if(solved)
    {
      // solution found
      endTime = new Date();
      elapsedTime = (endTime - startTime) / 1000;
      alert("Solved in " + elapsedTime + " seconds with " + guesses + " guesses!");
      return;
    }

    else
    {
      // increment solution and continue
      guesses++;
      var incremented = {flag: false};
      incrementArray(solution, chars.length, incremented);
      solve();
    }

  }

  // http://stackoverflow.com/a/966938
  function createMultiDimArray(length)
  {
    var arr = new Array(length || 0), i = length;
    if(arguments.length > 1)
    {
      var args = Array.prototype.slice.call(arguments, 1);
      while(i--) arr[length-1 - i] = createMultiDimArray.apply(this, args);
    }
    return arr;
  }

  // http://stackoverflow.com/a/15854485/3365483
  function zeroArray(arr)
  {
    for(var i = 0; i < arr.length; i++)
    {
      if(Array.isArray(arr[i])) zeroArray(arr[i]);
      else arr[i] = 0;
    }
  }

  function incrementArray(arr, mod, incremented)
  {
    for(var i = 0; i < arr.length; i++)
    {
      if(Array.isArray(arr[i])) incrementArray(arr[i], mod, incremented);
      else if(!incremented.flag)
      {
        arr[i]++;
        if(arr[i] < mod)
        {
          incremented.flag = true;
          return;
        }
        else arr[i] = 0;
      }
    }
  }

  var s = document.createElement("script");
  s.type = "text/javascript";
  s.src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js";
  s.onload = init;
  document.getElementsByTagName("head")[0].appendChild(s);

})();
<|endoftext|>


<commit_before>/*
   res.js v1.25.2

   Author: Steve Belovarich

   The MIT License (MIT)
   Copyright (c) 2014 Steve Belovarich

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.

   Usage: var r = new res([{
                     "state": "portrait",
                     "breakpoint": 420,
                     "cols": 4,
                     "margin": 10,
                     "gutter": 10
                 },
                 {
                     "state": "landscape",
                     "breakpoint": 640,
                     "cols": 4,
                     "margin": 10,
                     "gutter": 10
                 },
                 {
                     "state": "tablet",
                     "breakpoint": 768,
                     "cols": 12,
                     "margin": 40,
                     "gutter": 10
                 }]);

                 window.addEventListener('stateChange',function(ev,i){

                    console.log(r.state); // get the state from the object you created

                 });

*/

//Polyfill for CustomEvent in IE9+
(function () {
  function CustomEvent ( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
   };
  CustomEvent.prototype = window.Event.prototype;
})();

var res = function(json){

    var that = this;
    this.uagent = navigator.userAgent.toLowerCase();
    this.state = undefined;
    this.input = undefined;
    this.orient = undefined;
	  this.device = undefined;
	  this.os = undefined;
	  this.browser = undefined;
	  this.version = undefined;
	  this.width = 0;
	  this.grid = {};
    this.viewports = {};
    this.gridsettings = {};

	  var lastBreakpoint = 0;

	  for(var i = 0; i < json.length; i++) {
      that.viewports[json[i].state] = [lastBreakpoint+1, json[i].breakpoint];
      if(json[i].cols !== undefined && json[i].margin !== undefined && json[i].gutter !== undefined){
        that.gridsettings[json[i].state] = [json[i].cols, json[i].margin, json[i].gutter ];
      }
      lastBreakpoint = json[i].breakpoint;
    };

    this.init();
};
res.prototype = {

  setState: function() {
  	var that = this;

  	if(that.device === 'desktop'){
	  	that.width = window.innerWidth;
  	}
  	else if(that.device !== 'desktop'){
  		if(that.orient === 'portrait'){
	  	  that.width = screen.width;
	  	}
	  	else if(that.orient === 'landscape'){
		    that.width = screen.height;
	  	}
  	}

    for (var key in that.viewports) {
	    if (that.viewports.hasOwnProperty(key)) {
		  if (that.width >= that.viewports[key][0] && that.width <= that.viewports[key][1]) {
		    if (that.state != key) {
		        that.state = key;
            return that.state;
		    }
		  }
	    }
	  }
  },

  inputCheck: function() {
  	 var that = this;
     if (that.os === 'ios' || that.os === 'android' || that.os === 'winphone') {
       that.input = 'touch';
     }
     else{
	   that.input = 'mouse';
     }
  },

  browserCheck: function(){
    var that = this;
	  var tem,
    M = that.uagent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem =  /\brv[ :]+(\d+)/g.exec(that.uagent) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1] === 'Chrome'){
        tem = that.uagent.match(/\bOPR\/(\d+)/);
        if(tem != null) {
          return 'Opera '+tem[1];
        }
    }

    M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];

    if((tem = that.uagent.match(/version\/(\d+)/i)) != null) {
	    M.splice(1, 1, tem[1]);
    }
    that.browser = M[0];
    that.version = M[1];
    return M.join(' ');
  },

  osCheck: function() {
  	 var that = this;
     if (navigator.appVersion.indexOf("Win")!=-1) {
       that.os = 'windows';
       that.device = 'desktop';
     }
     else if (navigator.appVersion.indexOf("Mac")!=-1 && navigator.userAgent.match(/(iPhone|iPod|iPad)/) == null) {
       that.os = 'osx';
       that.device = 'desktop';
     }
     else if (navigator.userAgent.indexOf("Android") > -1) {
       that.os = 'android';
       if (navigator.userAgent.indexOf("Mobile") > -1) {
	       that.device = 'mobile';
       }
       else{
	       that.device = 'tablet';
       }

     }
     else if (navigator.userAgent.indexOf("windows phone") > 0) {
       that.os = 'windows';
       that.device = 'mobile';
     }
     else if (navigator.appVersion.indexOf("X11")!=-1) {
       that.os = 'unix';
       that.device = 'desktop';
     }
     else if (navigator.appVersion.indexOf("Linux")!=-1) {
       that.os = 'linux';
       that.device = 'desktop';
     }
     else if (navigator.userAgent.match(/(iPhone|iPod|iPad)/).length > 0) {
       that.os = 'ios';
       if( that.uagent.indexOf("iphone") > 0 ){
	       that.device = "iphone";
       }
	   if( that.uagent.indexOf("ipod") > 0 ){
	       that.device = "ipod";
	   }
	   if( that.uagent.indexOf("ipad") > 0 ){
	       that.device = "ipad";
	   }
     }
  },

  gridHelper: function(key){

    var that = this;

    var col,
        colArr = [],
        colSpan,
        colSpanArr = [],
        margin,
        gutter,
        cols;

    cols = that.gridsettings[key][0];
    margin = that.gridsettings[key][1];
    gutter = that.gridsettings[key][2];

    col = [];
    colSpan = [];
    width = window.innerWidth - (margin*2) + gutter;
    columnWidth = (width/cols)-gutter;

    for(var i = 0; i<cols; i++){
      if(i===0){
        colSpan = 0;
      }
      else{
        colSpan = (columnWidth*i)+(gutter*(i-1));
      }
      col = ((width/cols)*i)+margin;
      colArr.push(col);
      colSpanArr.push(colSpan);

      if(i===cols-1){
        colSpan = (columnWidth*(i+1))+(gutter*(i))
        colSpanArr.push(colSpan);
      }
    }
    return {
            "cols"   : cols,
            "col"    : colArr,
            "colSpan": colSpanArr,
            "width"  : width,
            "margin" : margin,
            "gutter" : gutter
           };

  },

  resize: function() {
     var that = this;

     if (window.innerHeight > window.innerWidth) {
       that.orient = 'portrait';
     }
     else {
       that.orient = 'landscape';
     }

     that.setState();

     if (that.gridsettings.hasOwnProperty(that.state)) {
       that.grid = that.gridHelper(that.state);
     }

     that.stateChange = new CustomEvent("stateChange",{
	  	bubbles: false,
	  	cancelable: true
	   });

     window.dispatchEvent(that.stateChange);

     return that;
  },

  init: function() {
     var that = this;

     that.osCheck();
     that.inputCheck();
     that.browserCheck();

     window.onorientationchange = function() {
       that.resize();
     };

     window.onresize = function() {
       that.resize();
     };

     that.resize();
  }

};<commit_msg>Updated the polyfill.<commit_after>/*
   res.js v1.25.2

   Author: Steve Belovarich

   The MIT License (MIT)
   Copyright (c) 2014 Steve Belovarich

   Permission is hereby granted, free of charge, to any person obtaining a copy
   of this software and associated documentation files (the "Software"), to deal
   in the Software without restriction, including without limitation the rights
   to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
   copies of the Software, and to permit persons to whom the Software is
   furnished to do so, subject to the following conditions:

   The above copyright notice and this permission notice shall be included in
   all copies or substantial portions of the Software.

   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
   IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
   FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
   AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
   LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
   OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
   THE SOFTWARE.

   Usage: var r = new res([{
                     "state": "portrait",
                     "breakpoint": 420,
                     "cols": 4,
                     "margin": 10,
                     "gutter": 10
                 },
                 {
                     "state": "landscape",
                     "breakpoint": 640,
                     "cols": 4,
                     "margin": 10,
                     "gutter": 10
                 },
                 {
                     "state": "tablet",
                     "breakpoint": 768,
                     "cols": 12,
                     "margin": 40,
                     "gutter": 10
                 }]);

                 window.addEventListener('stateChange',function(ev,i){

                    console.log(r.state); // get the state from the object you created

                 });

*/

//Polyfill for CustomEvent in IE9+
(function () {
  function CustomEvent ( event, params ) {
    params = params || { bubbles: false, cancelable: false, detail: undefined };
    var evt = document.createEvent( 'CustomEvent' );
    evt.initCustomEvent( event, params.bubbles, params.cancelable, params.detail );
    return evt;
   };
  CustomEvent.prototype = window.Event.prototype;
  window.CustomEvent = CustomEvent;
})();

var res = function(json){

    var that = this;
    this.uagent = navigator.userAgent.toLowerCase();
    this.state = undefined;
    this.input = undefined;
    this.orient = undefined;
	  this.device = undefined;
	  this.os = undefined;
	  this.browser = undefined;
	  this.version = undefined;
	  this.width = 0;
	  this.grid = {};
    this.viewports = {};
    this.gridsettings = {};

	  var lastBreakpoint = 0;

	  for(var i = 0; i < json.length; i++) {
      that.viewports[json[i].state] = [lastBreakpoint+1, json[i].breakpoint];
      if(json[i].cols !== undefined && json[i].margin !== undefined && json[i].gutter !== undefined){
        that.gridsettings[json[i].state] = [json[i].cols, json[i].margin, json[i].gutter ];
      }
      lastBreakpoint = json[i].breakpoint;
    };

    this.init();
};
res.prototype = {

  setState: function() {
  	var that = this;

  	if(that.device === 'desktop'){
	  	that.width = window.innerWidth;
  	}
  	else if(that.device !== 'desktop'){
  		if(that.orient === 'portrait'){
	  	  that.width = screen.width;
	  	}
	  	else if(that.orient === 'landscape'){
		    that.width = screen.height;
	  	}
  	}

    for (var key in that.viewports) {
	    if (that.viewports.hasOwnProperty(key)) {
		  if (that.width >= that.viewports[key][0] && that.width <= that.viewports[key][1]) {
		    if (that.state != key) {
		        that.state = key;
            return that.state;
		    }
		  }
	    }
	  }
  },

  inputCheck: function() {
  	 var that = this;
     if (that.os === 'ios' || that.os === 'android' || that.os === 'winphone') {
       that.input = 'touch';
     }
     else{
	   that.input = 'mouse';
     }
  },

  browserCheck: function(){
    var that = this;
	  var tem,
    M = that.uagent.match(/(opera|chrome|safari|firefox|msie|trident(?=\/))\/?\s*(\d+)/i) || [];
    if(/trident/i.test(M[1])){
        tem =  /\brv[ :]+(\d+)/g.exec(that.uagent) || [];
        return 'IE '+(tem[1] || '');
    }
    if(M[1] === 'Chrome'){
        tem = that.uagent.match(/\bOPR\/(\d+)/);
        if(tem != null) {
          return 'Opera '+tem[1];
        }
    }

    M = M[2]? [M[1], M[2]]: [navigator.appName, navigator.appVersion, '-?'];

    if((tem = that.uagent.match(/version\/(\d+)/i)) != null) {
	    M.splice(1, 1, tem[1]);
    }
    that.browser = M[0];
    that.version = M[1];
    return M.join(' ');
  },

  osCheck: function() {
  	 var that = this;
     if (navigator.appVersion.indexOf("Win")!=-1) {
       that.os = 'windows';
       that.device = 'desktop';
     }
     else if (navigator.appVersion.indexOf("Mac")!=-1 && navigator.userAgent.match(/(iPhone|iPod|iPad)/) == null) {
       that.os = 'osx';
       that.device = 'desktop';
     }
     else if (navigator.userAgent.indexOf("Android") > -1) {
       that.os = 'android';
       if (navigator.userAgent.indexOf("Mobile") > -1) {
	       that.device = 'mobile';
       }
       else{
	       that.device = 'tablet';
       }

     }
     else if (navigator.userAgent.indexOf("windows phone") > 0) {
       that.os = 'windows';
       that.device = 'mobile';
     }
     else if (navigator.appVersion.indexOf("X11")!=-1) {
       that.os = 'unix';
       that.device = 'desktop';
     }
     else if (navigator.appVersion.indexOf("Linux")!=-1) {
       that.os = 'linux';
       that.device = 'desktop';
     }
     else if (navigator.userAgent.match(/(iPhone|iPod|iPad)/).length > 0) {
       that.os = 'ios';
       if( that.uagent.indexOf("iphone") > 0 ){
	       that.device = "iphone";
       }
	   if( that.uagent.indexOf("ipod") > 0 ){
	       that.device = "ipod";
	   }
	   if( that.uagent.indexOf("ipad") > 0 ){
	       that.device = "ipad";
	   }
     }
  },

  gridHelper: function(key){

    var that = this;

    var col,
        colArr = [],
        colSpan,
        colSpanArr = [],
        margin,
        gutter,
        cols;

    cols = that.gridsettings[key][0];
    margin = that.gridsettings[key][1];
    gutter = that.gridsettings[key][2];

    col = [];
    colSpan = [];
    width = window.innerWidth - (margin*2) + gutter;
    columnWidth = (width/cols)-gutter;

    for(var i = 0; i<cols; i++){
      if(i===0){
        colSpan = 0;
      }
      else{
        colSpan = (columnWidth*i)+(gutter*(i-1));
      }
      col = ((width/cols)*i)+margin;
      colArr.push(col);
      colSpanArr.push(colSpan);

      if(i===cols-1){
        colSpan = (columnWidth*(i+1))+(gutter*(i))
        colSpanArr.push(colSpan);
      }
    }
    return {
            "cols"   : cols,
            "col"    : colArr,
            "colSpan": colSpanArr,
            "width"  : width,
            "margin" : margin,
            "gutter" : gutter
           };

  },

  resize: function() {
     var that = this;

     if (window.innerHeight > window.innerWidth) {
       that.orient = 'portrait';
     }
     else {
       that.orient = 'landscape';
     }

     that.setState();

     if (that.gridsettings.hasOwnProperty(that.state)) {
       that.grid = that.gridHelper(that.state);
     }

     that.stateChange = new CustomEvent("stateChange",{
	  	bubbles: false,
	  	cancelable: true
	   });

     window.dispatchEvent(that.stateChange);

     return that;
  },

  init: function() {
     var that = this;

     that.osCheck();
     that.inputCheck();
     that.browserCheck();

     window.onorientationchange = function() {
       that.resize();
     };

     window.onresize = function() {
       that.resize();
     };

     that.resize();
  }

};
<|endoftext|>


<commit_before>const BaseView = require('../BaseView');
const elementCreator = require('../../../ElementCreator');
const keyhandler = require('../../../KeyHandler');

class InputArea extends BaseView {
  constructor({
    sendOnEnter,
    classes = [],
    placeholder = '',
    shouldResize = true,
    triggerCallback = () => {},
    focusCallback = () => {},
    blurCallback = () => {},
    inputCallback = () => {},
  }) {
    super({
      classes: classes.concat(['inputArea']),
      elementId: `inputArea-${Date.now()}`,
    });

    this.textArea = elementCreator.createInput({
      placeholder,
      type: 'text',
      multiLine: true,
    });

    this.textArea.addEventListener('focus', () => {
      this.textArea.classList.add('focused');

      focusCallback();
    });
    this.textArea.addEventListener('blur', () => {
      this.textArea.classList.remove('focused');

      blurCallback();
    });
    this.textArea.addEventListener('input', () => {
      if (shouldResize) {
        this.resizeInput();
      }

      inputCallback(this.getInputValue());
    });

    if (sendOnEnter) {
      keyhandler.addKey(13, triggerCallback);
    }
  }

  resizeInput() {
    this.textArea.style.height = 'auto';
    this.textArea.style.height = `${this.textArea.scrollHeight}px`;
  }

  getInputValue() {
    return `${this.textArea.value}`;
  }

  getSplitInputValue() {
    return `${this.textArea.value}`.split('\n');
  }

  clearInput() {
    this.textArea.value = '';

    this.resizeInput();
  }
}

module.exports = InputArea;
<commit_msg>Key trigged added to input.<commit_after>const BaseView = require('../BaseView');
const elementCreator = require('../../../ElementCreator');
const keyhandler = require('../../../KeyHandler');

class InputArea extends BaseView {
  constructor({
    sendOnEnter,
    classes = [],
    placeholder = '',
    shouldResize = true,
    triggerCallback = () => {},
    focusCallback = () => {},
    blurCallback = () => {},
    inputCallback = () => {},
  }) {
    super({
      classes: classes.concat(['inputArea']),
      elementId: `inputArea-${Date.now()}`,
    });

    this.textArea = elementCreator.createInput({
      placeholder,
      type: 'text',
      multiLine: true,
    });
    this.isFocused = false;

    this.textArea.addEventListener('focus', () => {
      this.isFocused = true;
      this.textArea.classList.add('focused');

      focusCallback();
    });
    this.textArea.addEventListener('blur', () => {
      this.isFocused = false;
      this.textArea.classList.remove('focused');

      blurCallback();
    });
    this.textArea.addEventListener('input', () => {
      if (shouldResize) {
        this.resizeInput();
      }

      inputCallback(this.getInputValue());
    });

    this.element.appendChild(this.textArea);

    keyhandler.addKey(13, () => {
      if (this.isFocused) {
        triggerCallback({ text: this.getSplitInputValue() });
      }
    }, sendOnEnter);
  }

  resizeInput() {
    this.textArea.style.height = 'auto';
    this.textArea.style.height = `${this.textArea.scrollHeight}px`;
  }

  getInputValue() {
    return `${this.textArea.value}`;
  }

  getSplitInputValue() {
    return `${this.textArea.value}`.split('\n');
  }

  clearInput() {
    this.textArea.value = '';

    this.resizeInput();
  }
}

module.exports = InputArea;
<|endoftext|>


<commit_before>var util = require('util'),
    debug;

var RPC_ERROR_PARSE_ERROR = -32700,
    RPC_ERROR_INVALID_REQUEST = -32600,
    RPC_ERROR_INVALID_METHOD = -32601,
    RPC_ERROR_INVALID_PARAMS = -32602;

debug = util.debuglog('rpclib');

function RPCAPI() {
    this.methods = {};
    this.preProcessor = null;
}

RPCAPI.prototype.addMethod = function(name, handler, params, flags) {
    if (typeof handler !== 'function') {
        throw new TypeError('Invalid handler method sent to addMethod for ' + name);
    }
    this.methods[name] = {
        params: params,
        handler: handler,
        flags: +flags
    };
};

RPCAPI.prototype.setPreProcessor = function(func) {
    if (func === null) {
        this.preProcessor = null;
        return;
    }
    if (typeof func !== 'function') {
        throw new TypeError('Invalid function sent to setPreProcessor');
    }
    this.preProcessor = func;
};

function respondError(errorCode, id, response) {
    var resp = {
        jsonrpc: '2.0',
        error: {
            code: errorCode
        },
        id: id
    };
    response.write(JSON.stringify(resp));
}

function respondResult(result, id, response) {
    var resp = {
        jsonrpc: '2.0',
        result: result,
        id: id
    };
    response.write(JSON.stringify(resp));
}

RPCAPI.prototype.handleRequest = function(request, response) {
    debug('handleRequest');
    var message = null,
        methodDetail = null,
        k = '',
        v = '',
        t = '',
        messageID = null,
        shouldRespond = true,
        params = null,
        respObj = null;
    try {
        message = JSON.parse(request);
    } catch (ignore) {}
    if (message == null) {
        debug('Invalid JSON received');
        if (shouldRespond) {
            respondError(RPC_ERROR_PARSE_ERROR, messageID, response);
        }
        return;
    }
    if (message.id === undefined) {
        shouldRespond = false;
    } else {
        messageID = message.id;
    }
    if (message.jsonrpc !== '2.0') {
        debug('Invalid jsonrpc value received');
        if (shouldRespond) {
            respondError(RPC_ERROR_INVALID_REQUEST, messageID, response);
        }
        return;
    }
    if (typeof message.method !== 'string') {
        debug('Invalid method value received');
        if (shouldRespond) {
            respondError(RPC_ERROR_INVALID_REQUEST, messageID, response);
        }
        return;
    }
    if (typeof message.params !== 'object') {
        debug('Invalid params value received');
        if (shouldRespond) {
            respondError(RPC_ERROR_INVALID_REQUEST, messageID, response);
        }
        return;
    }

    methodDetail = this.methods[message.method];
    if (methodDetail === undefined) {
        debug('Method', message.method, 'doesnt exist');
        if (shouldRespond) {
            respondError(RPC_ERROR_INVALID_METHOD, messageID, response);
        }
        return false;
    }
    if (methodDetail.params !== undefined) {
        for (k in methodDetail.params) {
            v = methodDetail.params[k];
            t = typeof message.params[k];
            if (v.type !== '*' && t !== v.type && (!v.optional || t !== 'undefined')) {
                debug('Method', message.method, 'requires param', k, 'to be type', v);
                if (shouldRespond) {
                    respondError(RPC_ERROR_INVALID_PARAMS, messageID, response);
                }
                return;
            }
        }
        params = message.params;
    }

    respObj = new RPCResponse(response, messageID);
    if (this.preProcessor !== null) {
        this.preProcessor(message, methodDetail, respObj);
    }

    methodDetail.handler(params, respObj);
};

function RPCResponse(response, messageID) {
    this._response = response;
    this._messageID = messageID;
    this.keyVals = null;
}
RPCResponse.prototype.set = function(name, value) {
    if (this.keyVals === null) {
        this.keyVals = {};
    }
    this.keyVals[name] = value;
};
RPCResponse.prototype.get = function(name) {
    if (this.keyVals === null) {
        return undefined;
    }
    return this.keyVals[name];
};
RPCResponse.prototype.resolve = function(result) {
    respondResult(result, this._messageID, this._response);
};
RPCResponse.prototype.reject = function(errorCode, errorMessage) {
    respondError(errorCode, this._messageID, this._response);
};

module.exports = RPCAPI;
<commit_msg>Call end instead of write<commit_after>var util = require('util'),
    debug;

var RPC_ERROR_PARSE_ERROR = -32700,
    RPC_ERROR_INVALID_REQUEST = -32600,
    RPC_ERROR_INVALID_METHOD = -32601,
    RPC_ERROR_INVALID_PARAMS = -32602;

debug = util.debuglog('rpclib');

function RPCAPI() {
    this.methods = {};
    this.preProcessor = null;
}

RPCAPI.prototype.addMethod = function(name, handler, params, flags) {
    if (typeof handler !== 'function') {
        throw new TypeError('Invalid handler method sent to addMethod for ' + name);
    }
    this.methods[name] = {
        params: params,
        handler: handler,
        flags: +flags
    };
};

RPCAPI.prototype.setPreProcessor = function(func) {
    if (func === null) {
        this.preProcessor = null;
        return;
    }
    if (typeof func !== 'function') {
        throw new TypeError('Invalid function sent to setPreProcessor');
    }
    this.preProcessor = func;
};

function respondError(errorCode, id, response) {
    var resp = {
        jsonrpc: '2.0',
        error: {
            code: errorCode
        },
        id: id
    };
    response.end(JSON.stringify(resp));
}

function respondResult(result, id, response) {
    var resp = {
        jsonrpc: '2.0',
        result: result,
        id: id
    };
    response.end(JSON.stringify(resp));
}

RPCAPI.prototype.handleRequest = function(request, response) {
    debug('handleRequest');
    var message = null,
        methodDetail = null,
        k = '',
        v = '',
        t = '',
        messageID = null,
        shouldRespond = true,
        params = null,
        respObj = null;
    try {
        message = JSON.parse(request);
    } catch (ignore) {}
    if (message == null) {
        debug('Invalid JSON received');
        if (shouldRespond) {
            respondError(RPC_ERROR_PARSE_ERROR, messageID, response);
        }
        return;
    }
    if (message.id === undefined) {
        shouldRespond = false;
    } else {
        messageID = message.id;
    }
    if (message.jsonrpc !== '2.0') {
        debug('Invalid jsonrpc value received');
        if (shouldRespond) {
            respondError(RPC_ERROR_INVALID_REQUEST, messageID, response);
        }
        return;
    }
    if (typeof message.method !== 'string') {
        debug('Invalid method value received');
        if (shouldRespond) {
            respondError(RPC_ERROR_INVALID_REQUEST, messageID, response);
        }
        return;
    }
    if (typeof message.params !== 'object') {
        debug('Invalid params value received');
        if (shouldRespond) {
            respondError(RPC_ERROR_INVALID_REQUEST, messageID, response);
        }
        return;
    }

    methodDetail = this.methods[message.method];
    if (methodDetail === undefined) {
        debug('Method', message.method, 'doesnt exist');
        if (shouldRespond) {
            respondError(RPC_ERROR_INVALID_METHOD, messageID, response);
        }
        return false;
    }
    if (methodDetail.params !== undefined) {
        for (k in methodDetail.params) {
            v = methodDetail.params[k];
            t = typeof message.params[k];
            if (v.type !== '*' && t !== v.type && (!v.optional || t !== 'undefined')) {
                debug('Method', message.method, 'requires param', k, 'to be type', v);
                if (shouldRespond) {
                    respondError(RPC_ERROR_INVALID_PARAMS, messageID, response);
                }
                return;
            }
        }
        params = message.params;
    }

    respObj = new RPCResponse(response, messageID);
    if (this.preProcessor !== null) {
        this.preProcessor(message, methodDetail, respObj);
    }

    methodDetail.handler(params, respObj);
};

function RPCResponse(response, messageID) {
    this._response = response;
    this._messageID = messageID;
    this.keyVals = null;
    this.resolved = false;
}
RPCResponse.prototype.set = function(name, value) {
    if (this.keyVals === null) {
        this.keyVals = {};
    }
    this.keyVals[name] = value;
};
RPCResponse.prototype.get = function(name) {
    if (this.keyVals === null) {
        return undefined;
    }
    return this.keyVals[name];
};
RPCResponse.prototype.resolve = function(result) {
    if (this.resolved) {
        throw new Error('Cannot call resolve twice on a RPCResponse');
    }
    this.resolved = true;
    respondResult(result, this._messageID, this._response);
};
RPCResponse.prototype.reject = function(errorCode, errorMessage) {
    if (this.resolved) {
        throw new Error('Cannot call resolve twice on a RPCResponse');
    }
    this.resolve = true;
    respondError(errorCode, this._messageID, this._response);
};

module.exports = RPCAPI;
<|endoftext|>


<commit_before>import React, { PropTypes } from 'react';

import { connect } from 'react-redux'
import { updateProps } from '../../actions'

/*
 * EditableContent passes a connected onChange handler down to its child
 * as a prop
 */

const mapStateToProps = (state, ownProps) => {
  return {}
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    updateProps: (newProps) => {
        console.warn('newProps: ', newProps);
        dispatch(updateProps({
            props: newProps,
            itempath: React.Children.only(ownProps.children).props.path
        }));
    }
  }
}

const EditableContent = ({ updateProps, children }) => {
    // pass onChange as props to the child element e.g. an <input>
    return React.cloneElement(children, {updateProps});
};

EditableContent.propTypes = {
    onChange: PropTypes.func.isRequired
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(EditableContent);
<commit_msg>:see_no_evil: tyop<commit_after>import React, { PropTypes } from 'react';

import { connect } from 'react-redux'
import { updateProps } from '../../actions'

/*
 * EditableContent passes a connected updateProps handler down to its child
 * as a prop
 */

const mapStateToProps = (state, ownProps) => {
  return {}
}

const mapDispatchToProps = (dispatch, ownProps) => {
  return {
    updateProps: (newProps) => {
        console.warn('newProps: ', newProps);
        dispatch(updateProps({
            props: newProps,
            itempath: React.Children.only(ownProps.children).props.path
        }));
    }
  }
}

const EditableContent = ({ updateProps, children }) => {
    // pass updateProps as props to the child element e.g. an <input>
    return React.cloneElement(children, {updateProps});
};

EditableContent.propTypes = {
    updateProps: PropTypes.func.isRequired
};

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(EditableContent);
<|endoftext|>


<commit_before>var Q = require('Q');
var cartesianProduct = require('cartesian-product');
var process_exec = require('child_process').exec;
var zip = require('node-7z')
var xpath = require('xpath');
var dom = require('xmldom').DOMParser;
var http = require('http');
var path = require('path');
var locks = require('locks');
var fs = require('fs');
var os = require('os');
var argv = require('yargs').argv;

var boss_models = require("./models.js").models;
var model;
var timeModel

if(!argv.model) {
    var m = boss_models.filter((m) => {
        return m.name == "nighthold";
    })[0]
    model = m.model;
    timeModel = m.timeModel;
} else {
    var m = boss_models.filter((m) => {
        return m.name == argv.model;
    })[0]
    model = m.model;
    timeModel = m.timeModel;
}

var region = process.argv[2];
var realm = process.argv[3];
var name = process.argv[4];

var config = { names: ["fighttime","fightstyle"], values: [[90, 250, 400],["low_movement","high_movement","patchwerk"]]};
var addConfig = { names: ["fighttime","fightstyle","adds"], values: [[30,35,50,55,60],["low_movement","patchwerk"],['3','4','5']]}

var cp = config.names.reduce(function(prev, cur) {
    var name= cur;
    var values =config.values[config.names.indexOf(cur)];
    var cp = cartesianProduct([[name], values]);
    return prev.concat([cp]);
},[]);

var addCp = addConfig.names.reduce(function(prev, cur) {
    var name= cur;
    var values =addConfig.values[addConfig.names.indexOf(cur)];
    var cp = cartesianProduct([[name], values]);
    return prev.concat([cp]);
},[]);

var deleteContents = function(path) {
    if(fs.existsSync(path) ) {
        fs.readdirSync(path).forEach(function(file,index){
            var curPath = path + "/" + file;
            if(fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteContents(curPath);
                fs.rmdirSync(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
    }
}

var pool = [null,null,null,null,null,null,null,null];
var pool_size = 4;
if(argv.threads && argv.threads >= 1 && argv.threads <= 8) {
    pool_size = argv.threads;
}
var threads = 0;

var mutex = locks.createMutex();
var exec = function(command, options, callback) {
    mutex.lock(function() {
        var return_promise;
        if (pool[threads%pool_size] == null) {
            console.log("Running: " + command);
            return_promise = Q.nfcall(process_exec, command, options).then(function() {
                callback();
            });
            pool[threads%pool_size] = return_promise;
            threads++;
        } else {
            var chain = (pool[threads%pool_size]).then(function() {
                console.log("Running: " + command);
                return Q.nfcall(process_exec, command, options).then(function() {
                    callback();
                })
            });
            pool[threads%pool_size] = chain;
            console.log("Queued: " + command);
            threads++;
        }
        mutex.unlock();
    });
}

var configurations = cartesianProduct(cp);
var addConfiguration = cartesianProduct(addCp);

Q.nfcall(fs.readdir,"templates").then(function(templates) {
    var addTemplates = templates.filter(template => {
        return template.includes("adds");
    });
    var simTemplates = templates.filter(template => {
        return !template.includes("adds");
    });
    return (cartesianProduct([simTemplates, configurations])).concat(cartesianProduct([addTemplates,addConfiguration]));
}).then(function(sims){
    var simsFolder = 'sims';
    if (!fs.existsSync(simsFolder)) {
        fs.mkdirSync(simsFolder);
    }  else {
        deleteContents(simsFolder);
    }
    console.log("Generating simc profiles.");
    return Q.all(sims.map(function(sim){
        return Q.nfcall(fs.readFile, "templates/"+ sim[0], "utf-8").then(function(templateData){
            var fighttime;
            var fightstyle;
            var adds = null;
            sim[1].forEach(function(variable) {
                if(variable[0] == "fighttime") {
                    fighttime = variable[1];
                } else if(variable[0] == "fightstyle") {
                    fightstyle = variable[1];
                } else if(variable[0] == "adds") {
                    adds = variable[1];
                }

                templateData = templateData.replace("%" + variable[0] + "%",variable[1]);
            })

            var replaceValue;
            var filename;
            if(adds != null) {
                replaceValue = fighttime + '_' + fightstyle.replace("_", "")  + '_' + adds;
                filename = sim[0].replace("template", replaceValue);
            } else {
                replaceValue = fightstyle.replace("_", "");
                filename = fighttime + '_' + sim[0].replace("template", replaceValue);
            }
            var modelName = sim[0].split('.')[0].replace("template", replaceValue); // IE 35_patchwerk_3_adds or patchwerk_ba_2t
            if(model[modelName] == null || model[modelName] == 0 || ((timeModel[fighttime] == null || timeModel[fighttime] == 0) && adds == null)) {
                console.log("Preventing generation of unused model: " + modelName);
                return null;
            }
            if(process.argv[2] == "sim_test") {
                templateData = templateData.replace("#","");
                templateData = templateData.replace("%version%", "905");
				templateData = templateData.replace("armory=%region%,%realm%,%name%","input=../test_profiles/characterbase.simc\r\ninput=../test_profiles/apl232017.simc");
                region = "test";
                realm = "test";
                name = "sim_test";
            }
            if(argv.ptr) {
                templateData = "ptr=1\r\n" + templateData;
            }
            if(argv.noweights) {
                templateData = templateData.replace("calculate_scale_factors=1","#noweights");
            }
            templateData = templateData.replace("%region%",region);
            templateData = templateData.replace("%realm%",realm);
            templateData = templateData.replace("%name%",name);
            filename = name + '_' + filename;
            templateData = templateData.replace("%filename%",filename);

            var prefix = fs.readFileSync(path.join('templates','prefix.simc'), 'utf-8');
            var postfix = fs.readFileSync(path.join('templates','postfix.simc'), 'utf-8');
            templateData = prefix + '\r\n' + templateData + '\r\n' + postfix;
            console.log("Generating simc profile: " + filename);
            return {data: templateData,fileName: filename};
        }).then(function(data) {
            if(data == null) {
                return;
            }
            return Q.nfcall(fs.writeFile, path.join(simsFolder,data.fileName), data.data, "utf-8")
        });
    }))
}).then(function() {
    var deferred = Q.defer();
    var rawData = "";
    console.log("Downloading SimulationCraft version list.");
    http.get("http://downloads.simulationcraft.org/?C=M;O=D", (response) => {
        response.on('data', (chunk) => rawData += chunk);
        response.on('end', () => {
            deferred.resolve(rawData);
        });
    });

    return deferred.promise;
}).then((response) => {
        var doc = new dom().parseFromString(response, "text/html")
        var select = xpath.useNamespaces({ h: 'http://www.w3.org/1999/xhtml' });
        var arch = 'win64';
        if (os.arch() != 'x64') {
            arch = 'win32';
        }
        var fname = select("//h:html/h:body/h:table/h:tr/h:td/h:a[contains(@href,'.7z') and contains(@href,'" + arch + "')][1]/@href", doc)[0].value
        var link = "http://downloads.simulationcraft.org/" + fname;
        console.log('Found: ' + link);
        if (fs.existsSync(fname)) {
            console.log("Skipping download. Already found existing file.");
            return fname;
        }
        console.log("Downloading simc.7z for " + arch + " platform.");
	    var file = fs.createWriteStream(fname);
        var deferred = Q.defer();
        http.get(link, (response) => {
            response.pipe(file);
            response.on('end', () => {
                console.log("Done downloading simc.7z");
                deferred.resolve(fname);
            });
        })
        return deferred.promise;
}).then((name) => {
    var deferred = Q.defer();
    var binFolder = path.join('.','bin');
    if (!fs.existsSync(binFolder)) {
        fs.mkdirSync(binFolder);
    } else {
        deleteContents(binFolder);
    }

    console.log("Extracting simc.7z archive.");
    new zip().extractFull(name, 'bin', {})
    .then(() => {
        console.log("Done extracting simc.7z.");
        deferred.resolve();
    });
    return deferred.promise;
}).then(function() {
    var resultsFolder = path.join('.','results');
    if (!fs.existsSync(resultsFolder)) {
        fs.mkdirSync(resultsFolder);
    } else {
        deleteContents(resultsFolder);
    }
    console.log("Starting SimulationCraft run");
    var promises = fs.readdirSync("sims").map(function(sim) {
        var cmd = path.join("..","bin",fs.readdirSync("bin")[0], "simc.exe") + " " + path.join("..","sims", sim);

        var deferred = Q.defer();
        exec(cmd, { cwd: resultsFolder }, function() {
            console.log("Done sim: " + sim);
            deferred.resolve();
        });
        return deferred.promise;
    });
    return Q.allSettled(promises).then(function() {
        var deferral = Q.defer();
        console.log('Done Simming.');
        var analyze = path.join('.','analyze.js') + " " + process.argv[2];
        if(argv.noweights) {
            analyze += " --noweights";
        }
        if(argv.model) {
            analyze += " --model " + argv.model;
        } else {
            analyze += " --model nighthold"
        }
        process_exec("node " + analyze, function(err, out, stderr) {
            console.log(out);
            console.log('Done Analysis.');
            deferral.resolve();
        });
        return deferral.promise;
    });
}).done();<commit_msg>Fixing a bug where we wouldn't capture errors.<commit_after>var Q = require('Q');
var cartesianProduct = require('cartesian-product');
var process_exec = require('child_process').exec;
var zip = require('node-7z')
var xpath = require('xpath');
var dom = require('xmldom').DOMParser;
var http = require('http');
var path = require('path');
var locks = require('locks');
var fs = require('fs');
var os = require('os');
var argv = require('yargs').argv;

var boss_models = require("./models.js").models;
var model;
var timeModel

if(!argv.model) {
    var m = boss_models.filter((m) => {
        return m.name == "nighthold";
    })[0]
    model = m.model;
    timeModel = m.timeModel;
} else {
    var m = boss_models.filter((m) => {
        return m.name == argv.model;
    })[0]
    model = m.model;
    timeModel = m.timeModel;
}

var region = process.argv[2];
var realm = process.argv[3];
var name = process.argv[4];

var config = { names: ["fighttime","fightstyle"], values: [[90, 250, 400],["low_movement","high_movement","patchwerk"]]};
var addConfig = { names: ["fighttime","fightstyle","adds"], values: [[30,35,50,55,60],["low_movement","patchwerk"],['3','4','5']]}

var cp = config.names.reduce(function(prev, cur) {
    var name= cur;
    var values =config.values[config.names.indexOf(cur)];
    var cp = cartesianProduct([[name], values]);
    return prev.concat([cp]);
},[]);

var addCp = addConfig.names.reduce(function(prev, cur) {
    var name= cur;
    var values =addConfig.values[addConfig.names.indexOf(cur)];
    var cp = cartesianProduct([[name], values]);
    return prev.concat([cp]);
},[]);

var deleteContents = function(path) {
    if(fs.existsSync(path) ) {
        fs.readdirSync(path).forEach(function(file,index){
            var curPath = path + "/" + file;
            if(fs.lstatSync(curPath).isDirectory()) { // recurse
                deleteContents(curPath);
                fs.rmdirSync(curPath);
            } else { // delete file
                fs.unlinkSync(curPath);
            }
        });
    }
}

var pool = [null,null,null,null,null,null,null,null];
var pool_size = 4;
if(argv.threads && argv.threads >= 1 && argv.threads <= 8) {
    pool_size = argv.threads;
}
var threads = 0;

var mutex = locks.createMutex();
var exec = function(command, options, callback) {
    mutex.lock(function() {
        var return_promise;
        if (pool[threads%pool_size] == null) {
            console.log("Running: " + command);
            return_promise = Q.nfcall(process_exec, command, options).then(function() {
                callback();
            }, (err) => {
                console.log("Error: Failed to execute sim profile " + command);
                throw err;
            });
            pool[threads%pool_size] = return_promise;
            threads++;
        } else {
            var chain = (pool[threads%pool_size]).then(function() {
                console.log("Running: " + command);
                return Q.nfcall(process_exec, command, options).then(function() {
                        callback();
                    }, (err) => {
                        console.log("Error: Failed to execute sim profile " + command);
                        throw err;
                    });
            });
            pool[threads%pool_size] = chain;
            console.log("Queued: " + command);
            threads++;
        }
        mutex.unlock();
    });
}

var configurations = cartesianProduct(cp);
var addConfiguration = cartesianProduct(addCp);

Q.nfcall(fs.readdir,"templates").then(function(templates) {
    var addTemplates = templates.filter(template => {
        return template.includes("adds");
    });
    var simTemplates = templates.filter(template => {
        return !template.includes("adds");
    });
    return (cartesianProduct([simTemplates, configurations])).concat(cartesianProduct([addTemplates,addConfiguration]));
}).then(function(sims){
    var simsFolder = 'sims';
    if (!fs.existsSync(simsFolder)) {
        fs.mkdirSync(simsFolder);
    }  else {
        deleteContents(simsFolder);
    }
    console.log("Generating simc profiles.");
    return Q.all(sims.map(function(sim){
        return Q.nfcall(fs.readFile, "templates/"+ sim[0], "utf-8").then(function(templateData){
            var fighttime;
            var fightstyle;
            var adds = null;
            sim[1].forEach(function(variable) {
                if(variable[0] == "fighttime") {
                    fighttime = variable[1];
                } else if(variable[0] == "fightstyle") {
                    fightstyle = variable[1];
                } else if(variable[0] == "adds") {
                    adds = variable[1];
                }

                templateData = templateData.replace("%" + variable[0] + "%",variable[1]);
            })

            var replaceValue;
            var filename;
            if(adds != null) {
                replaceValue = fighttime + '_' + fightstyle.replace("_", "")  + '_' + adds;
                filename = sim[0].replace("template", replaceValue);
            } else {
                replaceValue = fightstyle.replace("_", "");
                filename = fighttime + '_' + sim[0].replace("template", replaceValue);
            }
            var modelName = sim[0].split('.')[0].replace("template", replaceValue); // IE 35_patchwerk_3_adds or patchwerk_ba_2t
            if(model[modelName] == null || model[modelName] == 0 || ((timeModel[fighttime] == null || timeModel[fighttime] == 0) && adds == null)) {
                console.log("Preventing generation of unused model: " + modelName);
                return null;
            }
            if(process.argv[2] == "sim_test") {
                templateData = templateData.replace("#","");
                templateData = templateData.replace("%version%", "905");
				templateData = templateData.replace("armory=%region%,%realm%,%name%","input=../test_profiles/characterbase.simc\r\ninput=../test_profiles/apl232017.simc");
                region = "test";
                realm = "test";
                name = "sim_test";
            }
            if(argv.ptr) {
                templateData = "ptr=1\r\n" + templateData;
            }
            if(argv.noweights) {
                templateData = templateData.replace("calculate_scale_factors=1","#noweights");
            }
            templateData = templateData.replace("%region%",region);
            templateData = templateData.replace("%realm%",realm);
            templateData = templateData.replace("%name%",name);
            filename = name + '_' + filename;
            templateData = templateData.replace("%filename%",filename);

            var prefix = fs.readFileSync(path.join('templates','prefix.simc'), 'utf-8');
            var postfix = fs.readFileSync(path.join('templates','postfix.simc'), 'utf-8');
            templateData = prefix + '\r\n' + templateData + '\r\n' + postfix;
            console.log("Generating simc profile: " + filename);
            return {data: templateData,fileName: filename};
        }).then(function(data) {
            if(data == null) {
                return;
            }
            return Q.nfcall(fs.writeFile, path.join(simsFolder,data.fileName), data.data, "utf-8")
        });
    }))
}).then(function() {
    var deferred = Q.defer();
    var rawData = "";
    console.log("Downloading SimulationCraft version list.");
    http.get("http://downloads.simulationcraft.org/?C=M;O=D", (response) => {
        response.on('data', (chunk) => rawData += chunk);
        response.on('end', () => {
            deferred.resolve(rawData);
        });
    });

    return deferred.promise;
}).then((response) => {
        var doc = new dom().parseFromString(response, "text/html")
        var select = xpath.useNamespaces({ h: 'http://www.w3.org/1999/xhtml' });
        var arch = 'win64';
        if (os.arch() != 'x64') {
            arch = 'win32';
        }
        var fname = select("//h:html/h:body/h:table/h:tr/h:td/h:a[contains(@href,'.7z') and contains(@href,'" + arch + "')][1]/@href", doc)[0].value
        var link = "http://downloads.simulationcraft.org/" + fname;
        console.log('Found: ' + link);
        if (fs.existsSync(fname)) {
            console.log("Skipping download. Already found existing file.");
            return fname;
        }
        console.log("Downloading simc.7z for " + arch + " platform.");
	    var file = fs.createWriteStream(fname);
        var deferred = Q.defer();
        http.get(link, (response) => {
            response.pipe(file);
            response.on('end', () => {
                console.log("Done downloading simc.7z");
                deferred.resolve(fname);
            });
        })
        return deferred.promise;
}).then((name) => {
    var deferred = Q.defer();
    var binFolder = path.join('.','bin');
    if (!fs.existsSync(binFolder)) {
        fs.mkdirSync(binFolder);
    } else {
        deleteContents(binFolder);
    }

    console.log("Extracting simc.7z archive.");
    new zip().extractFull(name, 'bin', {})
    .then(() => {
        console.log("Done extracting simc.7z.");
        deferred.resolve();
    });
    return deferred.promise;
}).then(function() {
    var resultsFolder = path.join('.','results');
    if (!fs.existsSync(resultsFolder)) {
        fs.mkdirSync(resultsFolder);
    } else {
        deleteContents(resultsFolder);
    }
    console.log("Starting SimulationCraft run");
    var promises = fs.readdirSync("sims").map(function(sim) {
        var cmd = path.join("..","bin",fs.readdirSync("bin")[0], "simc.exe") + " " + path.join("..","sims", sim);

        var deferred = Q.defer();
        exec(cmd, { cwd: resultsFolder }, function() {
            console.log("Done sim: " + sim);
            deferred.resolve();
        });
        return deferred.promise;
    });
    return Q.allSettled(promises).then(function() {
        var deferral = Q.defer();
        console.log('Done Simming.');
        var analyze = path.join('.','analyze.js') + " " + process.argv[2];
        if(argv.noweights) {
            analyze += " --noweights";
        }
        if(argv.model) {
            analyze += " --model " + argv.model;
        } else {
            analyze += " --model nighthold"
        }
        process_exec("node " + analyze, function(err, out, stderr) {
            console.log(out);
            console.log('Done Analysis.');
            deferral.resolve();
        });
        return deferral.promise;
    });
}).done();<|endoftext|>


<commit_before>#!/usr/bin/env node
var sbt = require('./backuptool');
sbt.Tool.main();
<commit_msg>made sbt.js executable<commit_after>#!/usr/bin/env node
var sbt = require('./backuptool');
sbt.Tool.main();
<|endoftext|>


<commit_before>var Set = function(input){
  var set
    , value = null

  this.get = function(prop){
    return set[prop], prop || Object.keys(set)
  }

  this.add = function(item){
    set[item] = value
  }

  this.unique = function(input){
    var set = {}
      , i = 0
      , l = input.length

    for(; i < l; i++) {
      set[input[i]] = value
    }

    return set
  }

  set = this.unique(input) || {}
}

module.exports = Set;
<commit_msg>Added method stubs for set operations<commit_after>var Set = function(input){
  var set
    , value = null

  this.contains = function(prop){
    throw new Error('not implemented')
  }

  this.empty = function(){
    throw new Error('not implemented')
  }

  this.size = function(){
    throw new Error('not implemented')
  }

  this.get = function(){
    return Object.keys(set)
  }

  this.create = function(){
    throw new Error('not implemented')
  }

  this.add = function(prop){
    set[prop] = value
  }

  this.remove = function(prop){
    throw new Error('not implemented')
  }

  this.union = function(iset){
    throw new Error('not implemented')
  }

  this.intersect = function(iset){
    throw new Error('not implemented')
  }

  this.difference = function(iset){
    throw new Error('not implemented')
  }

  this.subset = function(iset){
    throw new Error('not implemented')
  }

  this.pop = function(){
    throw new Error('not implemented')
  }

  this.find = function(pred){
    throw new Error('not implemented')
  }

  this.clear = function(){
    throw new Error('not implemented')
  }

  this.unique = function(iset){
    var set = {}
      , i = 0
      , l = input.length

    for(; i < l; i++) {
      set[iset[i]] = value
    }

    return set
  }

  set = this.unique(input) || {}
}

module.exports = Set;
<|endoftext|>