<commit_before>(function () {
    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var BlockCipher = C_lib.BlockCipher;
    var C_algo = C.algo;

    // Lookup tables
    var SBOX = [];
    var INV_SBOX = [];
    var SUB_MIX_0 = [];
    var SUB_MIX_1 = [];
    var SUB_MIX_2 = [];
    var SUB_MIX_3 = [];
    var INV_SUB_MIX_0 = [];
    var INV_SUB_MIX_1 = [];
    var INV_SUB_MIX_2 = [];
    var INV_SUB_MIX_3 = [];

    // Compute lookup tables
    (function () {
        // Compute double table
        var d = [];
        for (var i = 0; i < 256; i++) {
            if (i < 128) {
                d[i] = i << 1;
            } else {
                d[i] = (i << 1) ^ 0x11b;
            }
        }

        // Walk GF(2^8)
        var x = 0;
        var xi = 0;
        for (var i = 0; i < 256; i++) {
            // Compute sbox
            var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
            sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
            SBOX[x] = sx;
            INV_SBOX[sx] = x;

            // Compute multiplication
            var x2 = d[x];
            var x4 = d[x2];
            var x8 = d[x4];

            // Compute sub bytes, mix columns tables
            var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
            SUB_MIX_0[x] = (t << 24) | (t >>> 8);
            SUB_MIX_1[x] = (t << 16) | (t >>> 16);
            SUB_MIX_2[x] = (t << 8)  | (t >>> 24);
            SUB_MIX_3[x] = t;

            // Compute inv sub bytes, inv mix columns tables
            var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
            INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
            INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
            INV_SUB_MIX_2[sx] = (t << 8)  | (t >>> 24);
            INV_SUB_MIX_3[sx] = t;

            // Compute next counter
            if (!x) {
                x = xi = 1;
            } else {
                x = x2 ^ d[d[d[x8 ^ x2]]];
                xi ^= d[d[xi]];
            }
        }
    }());

    // Precomputed Rcon lookup
    var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];

    /**
     * AES block cipher algorithm.
     */
    var AES = C_algo.AES = BlockCipher.extend({
        _doReset: function () {
            // Shortcuts
            var key = this._key;
            var keyWords = key.words;
            var keySize = key.sigBytes / 4;

            // Compute number of rounds
            var nRounds = this._nRounds = keySize + 6

            // Compute number of key schedule rows
            var ksRows = (nRounds + 1) * 4;

            // Compute key schedule
            var keySchedule = this._keySchedule = [];
            for (var ksRow = 0; ksRow < ksRows; ksRow++) {
                if (ksRow < keySize) {
                    keySchedule[ksRow] = keyWords[ksRow];
                } else {
                    var t = keySchedule[ksRow - 1];

                    if (!(ksRow % keySize)) {
                        // Rot word
                        t = (t << 8) | (t >>> 24);

                        // Sub word
                        t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];

                        // Mix Rcon
                        t ^= RCON[(ksRow / keySize) | 0] << 24;
                    } else if (keySize > 6 && ksRow % keySize == 4) {
                        // Sub word
                        t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
                    }

                    keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
                }
            }

            // Compute inv key schedule
            var invKeySchedule = this._invKeySchedule = [];
            for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
                var ksRow = ksRows - invKsRow;

                if (invKsRow % 4) {
                    var t = keySchedule[ksRow];
                } else {
                    var t = keySchedule[ksRow - 4];
                }

                if (invKsRow < 4 || ksRow <= 4) {
                    invKeySchedule[invKsRow] = t;
                } else {
                    invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
                                               INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
                }
            }
        },

        encryptBlock: function (M, offset) {
            this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
        },

        decryptBlock: function (M, offset) {
            // Swap 2nd and 4th rows
            var t = M[offset + 1];
            M[offset + 1] = M[offset + 3];
            M[offset + 3] = t;

            this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);

            // Inv swap 2nd and 4th rows
            var t = M[offset + 1];
            M[offset + 1] = M[offset + 3];
            M[offset + 3] = t;
        },

        _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
            // Shortcut
            var nRounds = this._nRounds;

            // Get input, add round key
            var s0 = M[offset]     ^ keySchedule[0];
            var s1 = M[offset + 1] ^ keySchedule[1];
            var s2 = M[offset + 2] ^ keySchedule[2];
            var s3 = M[offset + 3] ^ keySchedule[3];

            // Key schedule row counter
            var ksRow = 4;

            // Rounds
            for (var round = 1; round < nRounds; round++) {
                // Shift rows, sub bytes, mix columns, add round key
                var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
                var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
                var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
                var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];

                // Update state
                s0 = t0;
                s1 = t1;
                s2 = t2;
                s3 = t3;
            }

            // Shift rows, sub bytes, add round key
            var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
            var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
            var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
            var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];

            // Set output
            M[offset]     = t0;
            M[offset + 1] = t1;
            M[offset + 2] = t2;
            M[offset + 3] = t3;
        },

        keySize: 256/32
    });

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.AES.decrypt(ciphertext, key, cfg);
     */
    C.AES = BlockCipher._createHelper(AES);
}());
<commit_msg>JSHint-related and other cosmetic changes.<commit_after>(function () {
    /*global CryptoJS:true */

    'use strict';

    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var BlockCipher = C_lib.BlockCipher;
    var C_algo = C.algo;

    // Lookup tables
    var SBOX = [];
    var INV_SBOX = [];
    var SUB_MIX_0 = [];
    var SUB_MIX_1 = [];
    var SUB_MIX_2 = [];
    var SUB_MIX_3 = [];
    var INV_SUB_MIX_0 = [];
    var INV_SUB_MIX_1 = [];
    var INV_SUB_MIX_2 = [];
    var INV_SUB_MIX_3 = [];

    // Compute lookup tables
    (function () {
        // Reusable iterator
        var i;

        // Compute double table
        var d = [];
        for (i = 0; i < 256; i++) {
            if (i < 128) {
                d[i] = i << 1;
            } else {
                d[i] = (i << 1) ^ 0x11b;
            }
        }

        // Walk GF(2^8)
        var x = 0;
        var xi = 0;
        for (i = 0; i < 256; i++) {
            // Compute sbox
            var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
            sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
            SBOX[x] = sx;
            INV_SBOX[sx] = x;

            // Compute multiplication
            var x2 = d[x];
            var x4 = d[x2];
            var x8 = d[x4];

            // Reusable temp value
            var t;

            // Compute sub bytes, mix columns tables
            t = (d[sx] * 0x101) ^ (sx * 0x1010100);
            SUB_MIX_0[x] = (t << 24) | (t >>> 8);
            SUB_MIX_1[x] = (t << 16) | (t >>> 16);
            SUB_MIX_2[x] = (t << 8)  | (t >>> 24);
            SUB_MIX_3[x] = t;

            // Compute inv sub bytes, inv mix columns tables
            t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
            INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
            INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
            INV_SUB_MIX_2[sx] = (t << 8)  | (t >>> 24);
            INV_SUB_MIX_3[sx] = t;

            // Compute next counter
            if (!x) {
                x = xi = 1;
            } else {
                x = x2 ^ d[d[d[x8 ^ x2]]];
                xi ^= d[d[xi]];
            }
        }
    }());

    // Precomputed Rcon lookup
    var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];

    /**
     * AES block cipher algorithm.
     */
    var AES = C_algo.AES = BlockCipher.extend({
        _doReset: function () {
            // Shortcuts
            var key = this._key;
            var keyWords = key.words;
            var keySize = key.sigBytes / 4;

            // Compute number of rounds
            var nRounds = this._nRounds = keySize + 6;

            // Compute number of key schedule rows
            var ksRows = (nRounds + 1) * 4;

            // Key schedule row
            var ksRow;

            // Reusable temp value
            var t;

            // Compute key schedule
            var keySchedule = this._keySchedule = [];
            for (ksRow = 0; ksRow < ksRows; ksRow++) {
                if (ksRow < keySize) {
                    keySchedule[ksRow] = keyWords[ksRow];
                } else {
                    t = keySchedule[ksRow - 1];

                    if (ksRow % keySize === 0) {
                        // Rot word
                        t = (t << 8) | (t >>> 24);

                        // Sub word
                        t = (
                            (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) |
                            (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]
                        );

                        // Mix Rcon
                        t ^= RCON[(ksRow / keySize) | 0] << 24;
                    } else if (keySize > 6 && ksRow % keySize == 4) {
                        // Sub word
                        t = (
                            (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) |
                            (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]
                        );
                    }

                    keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
                }
            }

            // Compute inv key schedule
            var invKeySchedule = this._invKeySchedule = [];
            for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
                ksRow = ksRows - invKsRow;

                if (invKsRow % 4) {
                    t = keySchedule[ksRow];
                } else {
                    t = keySchedule[ksRow - 4];
                }

                if (invKsRow < 4 || ksRow <= 4) {
                    invKeySchedule[invKsRow] = t;
                } else {
                    invKeySchedule[invKsRow] = (
                        INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
                        INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]
                    );
                }
            }
        },

        encryptBlock: function (M, offset) {
            this._doCryptBlock(
                M, offset,
                this._keySchedule,
                SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3,
                SBOX
            );
        },

        decryptBlock: function (M, offset) {
            // Reusable temp value
            var t;

            // Swap 2nd and 4th rows
            t = M[offset + 1];
            M[offset + 1] = M[offset + 3];
            M[offset + 3] = t;

            this._doCryptBlock(
                M, offset,
                this._invKeySchedule,
                INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3,
                INV_SBOX
            );

            // Inv swap 2nd and 4th rows
            t = M[offset + 1];
            M[offset + 1] = M[offset + 3];
            M[offset + 3] = t;
        },

        _doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
            // Shortcut
            var nRounds = this._nRounds;

            // Get input, add round key
            var s0 = M[offset]     ^ keySchedule[0];
            var s1 = M[offset + 1] ^ keySchedule[1];
            var s2 = M[offset + 2] ^ keySchedule[2];
            var s3 = M[offset + 3] ^ keySchedule[3];

            // Temp state values
            var t0, t1, t2, t3;

            // Key schedule row counter
            var ksRow = 4;

            // Rounds
            for (var round = 1; round < nRounds; round++) {
                // Shift rows, sub bytes, mix columns, add round key
                t0 = (
                    SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^
                    SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]
                );
                t1 = (
                    SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^
                    SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]
                );
                t2 = (
                    SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^
                    SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]
                );
                t3 = (
                    SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^
                    SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]
                );

                // Update state
                s0 = t0;
                s1 = t1;
                s2 = t2;
                s3 = t3;
            }

            // Shift rows, sub bytes, add round key
            t0 = (
                    (SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) |
                    (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]
                ) ^ keySchedule[ksRow++];
            t1 = (
                    (SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) |
                    (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]
                ) ^ keySchedule[ksRow++];
            t2 = (
                    (SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) |
                    (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]
                ) ^ keySchedule[ksRow++];
            t3 = (
                    (SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) |
                    (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]
                ) ^ keySchedule[ksRow++];

            // Set output
            M[offset]     = t0;
            M[offset + 1] = t1;
            M[offset + 2] = t2;
            M[offset + 3] = t3;
        },

        keySize: 256/32
    });

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.AES.decrypt(ciphertext, key, cfg);
     */
    C.AES = BlockCipher._createHelper(AES);
}());
<|endoftext|>


<commit_before>(function () {
    /*global CryptoJS:true */

    'use strict';

    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var BlockCipher = C_lib.BlockCipher;
    var C_algo = C.algo;

    // Lookup tables
    var SBOX = [];
    var INV_SBOX = [];
    var SUB_MIX_0 = [];
    var SUB_MIX_1 = [];
    var SUB_MIX_2 = [];
    var SUB_MIX_3 = [];
    var INV_SUB_MIX_0 = [];
    var INV_SUB_MIX_1 = [];
    var INV_SUB_MIX_2 = [];
    var INV_SUB_MIX_3 = [];

    // Compute lookup tables
    (function () {
        // Reusable iterator
        var i;

        // Compute double table
        var d = [];
        for (i = 0; i < 256; i++) {
            if (i < 128) {
                d[i] = i << 1;
            } else {
                d[i] = (i << 1) ^ 0x11b;
            }
        }

        // Walk GF(2^8)
        var x = 0;
        var xi = 0;
        for (i = 0; i < 256; i++) {
            // Compute sbox
            var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
            sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
            SBOX[x] = sx;
            INV_SBOX[sx] = x;

            // Compute multiplication
            var x2 = d[x];
            var x4 = d[x2];
            var x8 = d[x4];

            // Reusable temp value
            var t;

            // Compute sub bytes, mix columns tables
            t = (d[sx] * 0x101) ^ (sx * 0x1010100);
            SUB_MIX_0[x] = (t << 24) | (t >>> 8);
            SUB_MIX_1[x] = (t << 16) | (t >>> 16);
            SUB_MIX_2[x] = (t << 8)  | (t >>> 24);
            SUB_MIX_3[x] = t;

            // Compute inv sub bytes, inv mix columns tables
            t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
            INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
            INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
            INV_SUB_MIX_2[sx] = (t << 8)  | (t >>> 24);
            INV_SUB_MIX_3[sx] = t;

            // Compute next counter
            if (!x) {
                x = xi = 1;
            } else {
                x = x2 ^ d[d[d[x8 ^ x2]]];
                xi ^= d[d[xi]];
            }
        }
    }());

    // Precomputed Rcon lookup
    var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];

    /**
     * AES block cipher algorithm.
     */
    var AES = C_algo.AES = BlockCipher.extend({
        _doReset: function () {
            // Shortcuts
            var key = this._key;
            var keyWords = key.words;
            var keySize = key.sigBytes / 4;

            // Compute number of rounds
            var nRounds = this._nRounds = keySize + 6;

            // Compute number of key schedule rows
            var ksRows = (nRounds + 1) * 4;

            // Key schedule row
            var ksRow;

            // Reusable temp value
            var t;

            // Compute key schedule
            var keySchedule = this._keySchedule = [];
            for (ksRow = 0; ksRow < ksRows; ksRow++) {
                if (ksRow < keySize) {
                    keySchedule[ksRow] = keyWords[ksRow];
                } else {
                    t = keySchedule[ksRow - 1];

                    if (ksRow % keySize === 0) {
                        // Rot word
                        t = (t << 8) | (t >>> 24);

                        // Sub word
                        t = (
                            (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) |
                            (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]
                        );

                        // Mix Rcon
                        t ^= RCON[(ksRow / keySize) | 0] << 24;
                    } else if (keySize > 6 && ksRow % keySize == 4) {
                        // Sub word
                        t = (
                            (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) |
                            (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]
                        );
                    }

                    keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
                }
            }

            // Compute inv key schedule
            var invKeySchedule = this._invKeySchedule = [];
            for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
                ksRow = ksRows - invKsRow;

                if (invKsRow % 4) {
                    t = keySchedule[ksRow];
                } else {
                    t = keySchedule[ksRow - 4];
                }

                if (invKsRow < 4 || ksRow <= 4) {
                    invKeySchedule[invKsRow] = t;
                } else {
                    invKeySchedule[invKsRow] = (
                        INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
                        INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]
                    );
                }
            }
        },

        encryptBlock: function (M, offset) {
            doCryptBlock.call(
                this,
                M, offset,
                this._keySchedule,
                SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3,
                SBOX
            );
        },

        decryptBlock: function (M, offset) {
            // Reusable temp value
            var t;

            // Swap 2nd and 4th rows
            t = M[offset + 1];
            M[offset + 1] = M[offset + 3];
            M[offset + 3] = t;

            doCryptBlock.call(
                this,
                M, offset,
                this._invKeySchedule,
                INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3,
                INV_SBOX
            );

            // Inv swap 2nd and 4th rows
            t = M[offset + 1];
            M[offset + 1] = M[offset + 3];
            M[offset + 3] = t;
        },

        keySize: 256/32
    });

    function doCryptBlock(M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
        /*jshint validthis:true */

        // Shortcut
        var nRounds = this._nRounds;

        // Get input, add round key
        var s0 = M[offset]     ^ keySchedule[0];
        var s1 = M[offset + 1] ^ keySchedule[1];
        var s2 = M[offset + 2] ^ keySchedule[2];
        var s3 = M[offset + 3] ^ keySchedule[3];

        // Temp state values
        var t0, t1, t2, t3;

        // Key schedule row counter
        var ksRow = 4;

        // Rounds
        for (var round = 1; round < nRounds; round++) {
            // Shift rows, sub bytes, mix columns, add round key
            t0 = (
                SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^
                SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]
            );
            t1 = (
                SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^
                SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]
            );
            t2 = (
                SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^
                SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]
            );
            t3 = (
                SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^
                SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]
            );

            // Update state
            s0 = t0;
            s1 = t1;
            s2 = t2;
            s3 = t3;
        }

        // Shift rows, sub bytes, add round key
        t0 = (
                (SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) |
                (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]
            ) ^ keySchedule[ksRow++];
        t1 = (
                (SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) |
                (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]
            ) ^ keySchedule[ksRow++];
        t2 = (
                (SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) |
                (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]
            ) ^ keySchedule[ksRow++];
        t3 = (
                (SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) |
                (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]
            ) ^ keySchedule[ksRow++];

        // Set output
        M[offset]     = t0;
        M[offset + 1] = t1;
        M[offset + 2] = t2;
        M[offset + 3] = t3;
    }

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.AES.decrypt(ciphertext, key, cfg);
     */
    C.AES = BlockCipher._createHelper(AES);
}());
<commit_msg>Removed unnecessary operation and other cosmetic changes.<commit_after>(function () {
    /*global CryptoJS:true */

    'use strict';

    // Shortcuts
    var C = CryptoJS;
    var C_lib = C.lib;
    var BlockCipher = C_lib.BlockCipher;
    var C_algo = C.algo;

    // Lookup tables
    var SBOX = [];
    var INV_SBOX = [];
    var SUB_MIX_0 = [];
    var SUB_MIX_1 = [];
    var SUB_MIX_2 = [];
    var SUB_MIX_3 = [];
    var INV_SUB_MIX_0 = [];
    var INV_SUB_MIX_1 = [];
    var INV_SUB_MIX_2 = [];
    var INV_SUB_MIX_3 = [];

    // Compute lookup tables
    (function () {
        // Reusable iterator
        var i;

        // Compute double table
        var d = [];
        for (i = 0; i < 256; i++) {
            if (i < 128) {
                d[i] = i << 1;
            } else {
                d[i] = (i << 1) ^ 0x11b;
            }
        }

        // Walk GF(2^8)
        var x = 0;
        var xi = 0;
        for (i = 0; i < 256; i++) {
            // Compute sbox
            var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
            sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
            SBOX[x] = sx;
            INV_SBOX[sx] = x;

            // Compute multiplication
            var x2 = d[x];
            var x4 = d[x2];
            var x8 = d[x4];

            // Reusable temp value
            var t;

            // Compute sub bytes, mix columns tables
            t = (d[sx] * 0x101) ^ (sx * 0x1010100);
            SUB_MIX_0[x] = (t << 24) | (t >>> 8);
            SUB_MIX_1[x] = (t << 16) | (t >>> 16);
            SUB_MIX_2[x] = (t << 8)  | (t >>> 24);
            SUB_MIX_3[x] = t;

            // Compute inv sub bytes, inv mix columns tables
            t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
            INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
            INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
            INV_SUB_MIX_2[sx] = (t << 8)  | (t >>> 24);
            INV_SUB_MIX_3[sx] = t;

            // Compute next counter
            if (!x) {
                x = xi = 1;
            } else {
                x = x2 ^ d[d[d[x8 ^ x2]]];
                xi ^= d[d[xi]];
            }
        }
    }());

    // Precomputed Rcon lookup
    var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];

    /**
     * AES block cipher algorithm.
     */
    var AES = C_algo.AES = BlockCipher.extend({
        _doReset: function () {
            // Shortcuts
            var key = this._key;
            var keyWords = key.words;
            var keySize = key.sigBytes / 4;

            // Compute number of rounds
            var nRounds = this._nRounds = keySize + 6;

            // Compute number of key schedule rows
            var ksRows = (nRounds + 1) * 4;

            // Key schedule row
            var ksRow;

            // Reusable temp value
            var t;

            // Compute key schedule
            var keySchedule = this._keySchedule = [];
            for (ksRow = 0; ksRow < ksRows; ksRow++) {
                if (ksRow < keySize) {
                    keySchedule[ksRow] = keyWords[ksRow];
                } else {
                    t = keySchedule[ksRow - 1];

                    if (ksRow % keySize === 0) {
                        // Rot word
                        t = (t << 8) | (t >>> 24);

                        // Sub word
                        t = (
                            (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) |
                            (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]
                        );

                        // Mix Rcon
                        t ^= RCON[ksRow / keySize] << 24;
                    } else if (keySize > 6 && ksRow % keySize == 4) {
                        // Sub word
                        t = (
                            (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) |
                            (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff]
                        );
                    }

                    keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
                }
            }

            // Compute inv key schedule
            var invKeySchedule = this._invKeySchedule = [];
            for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
                ksRow = ksRows - invKsRow;

                if (invKsRow % 4) {
                    t = keySchedule[ksRow];
                } else {
                    t = keySchedule[ksRow - 4];
                }

                if (invKsRow < 4 || ksRow <= 4) {
                    invKeySchedule[invKsRow] = t;
                } else {
                    invKeySchedule[invKsRow] = (
                        INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
                        INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]]
                    );
                }
            }
        },

        encryptBlock: function (M, offset) {
            doCryptBlock.call(
                this,
                M, offset,
                this._keySchedule,
                SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3,
                SBOX
            );
        },

        decryptBlock: function (M, offset) {
            // Reusable temp value
            var t;

            // Swap 2nd and 4th rows
            t = M[offset + 1];
            M[offset + 1] = M[offset + 3];
            M[offset + 3] = t;

            doCryptBlock.call(
                this,
                M, offset,
                this._invKeySchedule,
                INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3,
                INV_SBOX
            );

            // Inv swap 2nd and 4th rows
            t = M[offset + 1];
            M[offset + 1] = M[offset + 3];
            M[offset + 3] = t;
        },

        keySize: 256/32
    });

    function doCryptBlock(M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
        /*jshint validthis:true */

        // Get input, add round key
        var s0 = M[offset]     ^ keySchedule[0];
        var s1 = M[offset + 1] ^ keySchedule[1];
        var s2 = M[offset + 2] ^ keySchedule[2];
        var s3 = M[offset + 3] ^ keySchedule[3];

        // Key schedule row counter
        var ksRow = 4;

        // Shortcut
        var nRounds = this._nRounds;

        // Temp state values
        var t0, t1, t2, t3;

        // Rounds
        for (var round = 1; round < nRounds; round++) {
            // Shift rows, sub bytes, mix columns, add round key
            t0 = (
                SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^
                SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++]
            );
            t1 = (
                SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^
                SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++]
            );
            t2 = (
                SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^
                SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++]
            );
            t3 = (
                SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^
                SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++]
            );

            // Update state
            s0 = t0;
            s1 = t1;
            s2 = t2;
            s3 = t3;
        }

        // Shift rows, sub bytes, add round key
        t0 = (
                (SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) |
                (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]
            ) ^ keySchedule[ksRow++];
        t1 = (
                (SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) |
                (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]
            ) ^ keySchedule[ksRow++];
        t2 = (
                (SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) |
                (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]
            ) ^ keySchedule[ksRow++];
        t3 = (
                (SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) |
                (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]
            ) ^ keySchedule[ksRow++];

        // Set output
        M[offset]     = t0;
        M[offset + 1] = t1;
        M[offset + 2] = t2;
        M[offset + 3] = t3;
    }

    /**
     * Shortcut functions to the cipher's object interface.
     *
     * @example
     *
     *     var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
     *     var plaintext  = CryptoJS.AES.decrypt(ciphertext, key, cfg);
     */
    C.AES = BlockCipher._createHelper(AES);
}());
<|endoftext|>


<commit_before>import axions from 'axios'
import * as Cookies from 'es-cookie'

export const HTTP = axions.create({
  baseURL: window.location.origin + '/api',
  headers: {
    'X-CSRF-Token': Cookies.get('csrftoken')
  },
  params: {
    _: new Date().getTime()
  }
})
<commit_msg>Fixes<commit_after>import axios from 'axios'
import * as Cookies from 'es-cookie'

export const HTTP = axios.create({
  baseURL: window.location.origin + '/api',
  headers: {
    'X-CSRF-Token': Cookies.get('csrftoken')
  },
  params: {
    _: new Date().getTime()
  }
})
<|endoftext|>


<commit_before>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

describe('charm token drag and drop', function() {
  var Y, container, outerContainer, CharmToken, token;

  before(function(done) {
    Y = YUI(GlobalConfig).use([
      'browser-charm-token',
      'juju-tests-utils'
    ],
    function(Y) {
      CharmToken = Y.juju.widgets.browser.CharmToken;
      done();
    });

  });

  beforeEach(function() {
    outerContainer = Y.namespace('juju-tests.utils').makeContainer()
      .addClass('yui3-charmtoken');
    container = Y.namespace('juju-tests.utils').makeContainer();
    outerContainer.append(container);
  });

  afterEach(function() {
    outerContainer.remove().destroy(true);
    if (token) {
      token.destroy();
    }
  });

  it('makes each charm token draggable', function() {
    var cfg = {
      id: 'test',
      name: 'some-charm',
      description: 'some description',
      recent_commit_count: 1,
      recent_download_count: 3,
      tested_providers: ['ec2'],
      boundingBox: container,
      contentBox: container
    };
    // We need to simulate a complex token with several nested elements.
    token = new CharmToken(cfg);
    var draggable = [];
    token._makeDraggable = function(element, charmData) {
      draggable.push(Y.JSON.parse(charmData).id);
    };
    token.renderUI(container);
    // Many elements are made draggable for a single token token.
    assert.isTrue(draggable.length > 1);
    // There is only a single token represented by all the draggable elements.
    draggable = Y.Array.dedupe(draggable);
    assert.equal(draggable.length, 1);
    // All of the charm tokens are made draggable.
    assert.deepEqual(draggable, ['test']);
  });

  it('can make an element draggable', function() {
    token = new CharmToken();
    var setAttributeCalled, onCalled;
    var element = {
      setAttribute: function(name, value) {
        assert.equal(name, 'draggable');
        assert.equal(value, 'true');
        setAttributeCalled = true;
      },
      on: function(when, callable) {
        assert.equal(when, 'dragstart');
        onCalled = true;
        return {detach: function() {}};
      }
    };
    var dragImage = {};
    token._makeDragStartHandler = function(dragImage, charmData) {
      assert.equal(element, element);
      assert.equal(dragImage, dragImage);
      assert.equal(charmData, charmData);
    };
    token._makeDraggable(element, dragImage, 'charm-id');
    assert.isTrue(setAttributeCalled);
    assert.isTrue(onCalled);
  });

  it('can set up drag and drop configuration', function(done) {
    var cfg = {
      boundingBox: container,
      contentBox: container
    };
    token = new CharmToken(cfg);
    token.render();
    var setDataCalled, setDragImageCalled;
    var charmData = 'data';
    var handler = token._makeDragStartHandler(charmData);
    var dragDataSet = [];
    var evt = {
      _event: {
        dataTransfer: {
          setData: function(name, value) {
            dragDataSet.push([name, value]);
            setDataCalled = true;
          },
          setDragImage: function(provideDragImage, x, y) {
            assert.equal(
                provideDragImage.outerHTML.indexOf('<div class="charm-icon"'),
                0);
            assert.equal(x, 0);
            assert.equal(y, 0);
            setDragImageCalled = true;
          }
        },
        stopPropagation: function() {
          // The last thing the event handler does is to stop event propegation.
          done();
        }
      }
    };
    handler(evt);
    assert.equal(evt._event.dataTransfer.effectAllowed, 'copy');
    assert.equal(Y.JSON.stringify(dragDataSet),
        '[["charmData","data"],["dataType","charm-token-drag-and-drop"]]');
    assert.isTrue(setDataCalled);
    assert.isTrue(setDragImageCalled);
  });

  it('respects the isDraggable switch', function() {
    token = new CharmToken({contentBox: container});
    token.set('isDraggable', false);
    var dragEnabled = false;
    token._addDraggability = function() {
      dragEnabled = true;
    };
    token.renderUI(container);
    // Since we set isDraggable to false, _addDraggability was not called.
    assert.isFalse(dragEnabled);
    // If we set isDraggable to true, _addDraggability will be called.
    token.set('isDraggable', true);
    token.renderUI(container);
    assert.isTrue(dragEnabled);
  });

});
<commit_msg>Fixes DD test failure in FF<commit_after>/*
This file is part of the Juju GUI, which lets users view and manage Juju
environments within a graphical interface (https://launchpad.net/juju-gui).
Copyright (C) 2012-2013 Canonical Ltd.

This program is free software: you can redistribute it and/or modify it under
the terms of the GNU Affero General Public License version 3, as published by
the Free Software Foundation.

This program is distributed in the hope that it will be useful, but WITHOUT
ANY WARRANTY; without even the implied warranties of MERCHANTABILITY,
SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Affero
General Public License for more details.

You should have received a copy of the GNU Affero General Public License along
with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

'use strict';

describe('charm token drag and drop', function() {
  var Y, container, outerContainer, CharmToken, token;

  before(function(done) {
    Y = YUI(GlobalConfig).use([
      'browser-charm-token',
      'juju-tests-utils'
    ],
    function(Y) {
      CharmToken = Y.juju.widgets.browser.CharmToken;
      done();
    });

  });

  beforeEach(function() {
    outerContainer = Y.namespace('juju-tests.utils').makeContainer()
      .addClass('yui3-charmtoken');
    container = Y.namespace('juju-tests.utils').makeContainer();
    outerContainer.append(container);
  });

  afterEach(function() {
    outerContainer.remove().destroy(true);
    if (token) {
      token.destroy();
    }
  });

  it('makes each charm token draggable', function() {
    var cfg = {
      id: 'test',
      name: 'some-charm',
      description: 'some description',
      recent_commit_count: 1,
      recent_download_count: 3,
      tested_providers: ['ec2'],
      boundingBox: container,
      contentBox: container
    };
    // We need to simulate a complex token with several nested elements.
    token = new CharmToken(cfg);
    var draggable = [];
    token._makeDraggable = function(element, charmData) {
      draggable.push(Y.JSON.parse(charmData).id);
    };
    token.renderUI(container);
    // Many elements are made draggable for a single token token.
    assert.isTrue(draggable.length > 1);
    // There is only a single token represented by all the draggable elements.
    draggable = Y.Array.dedupe(draggable);
    assert.equal(draggable.length, 1);
    // All of the charm tokens are made draggable.
    assert.deepEqual(draggable, ['test']);
  });

  it('can make an element draggable', function() {
    token = new CharmToken();
    var setAttributeCalled, onCalled;
    var element = {
      setAttribute: function(name, value) {
        assert.equal(name, 'draggable');
        assert.equal(value, 'true');
        setAttributeCalled = true;
      },
      on: function(when, callable) {
        assert.equal(when, 'dragstart');
        onCalled = true;
        return {detach: function() {}};
      }
    };
    var dragImage = {};
    token._makeDragStartHandler = function(dragImage, charmData) {
      assert.equal(element, element);
      assert.equal(dragImage, dragImage);
      assert.equal(charmData, charmData);
    };
    token._makeDraggable(element, dragImage, 'charm-id');
    assert.isTrue(setAttributeCalled);
    assert.isTrue(onCalled);
  });

  it('can set up drag and drop configuration', function(done) {
    var cfg = {
      boundingBox: container,
      contentBox: container
    };
    token = new CharmToken(cfg);
    token.render();
    var setDataCalled, setDragImageCalled;
    var charmData = 'data';
    var handler = token._makeDragStartHandler(charmData);
    var dragDataSet = [];
    var evt = {
      _event: {
        dataTransfer: {
          setData: function(name, value) {
            dragDataSet.push([name, value]);
            setDataCalled = true;
          },
          setDragImage: function(provideDragImage, x, y) {
            assert.equal(provideDragImage.className.indexOf('charm-icon'), 0);
            assert.equal(x, 0);
            assert.equal(y, 0);
            setDragImageCalled = true;
          }
        },
        stopPropagation: function() {
          // The last thing the event handler does is to stop event propegation.
          done();
        }
      }
    };
    handler(evt);
    assert.equal(evt._event.dataTransfer.effectAllowed, 'copy');
    assert.equal(Y.JSON.stringify(dragDataSet),
        '[["charmData","data"],["dataType","charm-token-drag-and-drop"]]');
    assert.isTrue(setDataCalled);
    assert.isTrue(setDragImageCalled);
  });

  it('respects the isDraggable switch', function() {
    token = new CharmToken({contentBox: container});
    token.set('isDraggable', false);
    var dragEnabled = false;
    token._addDraggability = function() {
      dragEnabled = true;
    };
    token.renderUI(container);
    // Since we set isDraggable to false, _addDraggability was not called.
    assert.isFalse(dragEnabled);
    // If we set isDraggable to true, _addDraggability will be called.
    token.set('isDraggable', true);
    token.renderUI(container);
    assert.isTrue(dragEnabled);
  });

});
<|endoftext|>


<commit_before>'use strict';

const Support   = require(__dirname + '/../support');
const current   = Support.sequelize;
const expectsql = Support.expectsql;
const sql = current.dialect.QueryGenerator;

describe(Support.getTestDialectTeaser('SQL'), () => {
  describe('showConstraint', () => {
    it('naming', () => {
      expectsql(sql.showConstraintsQuery('myTable'), {
        mssql: "EXEC sp_helpconstraint @objname = N'[myTable]';",
        postgres: 'SELECT tc.constraint_catalog AS "constraintCatalog", tc.constraint_schema AS "constraintSchema", tc.constraint_name AS "constraintName", tc.table_catalog AS "tableCatalog", tc.table_schema AS "tableSchema", tc.table_name AS "tableName", tc.constraint_type AS "constraintType", tc.is_deferrable AS "isDeferrable", tc.initially_deferred AS "initiallyDeferred", kcu.column_name AS "columnName" from INFORMATION_SCHEMA.table_constraints as "tc" join INFORMATION_SCHEMA.key_column_usage as "kcu" on (tc.constraint_name = kcu.constraint_name and tc.table_name = kcu.table_name) WHERE tc.table_name=\'myTable\';',
        mysql: "SELECT tc.CONSTRAINT_CATALOG AS constraintCatalog, tc.CONSTRAINT_NAME AS constraintName, tc.CONSTRAINT_SCHEMA AS constraintSchema, tc.CONSTRAINT_TYPE AS constraintType, tc.TABLE_NAME AS tableName, tc.TABLE_SCHEMA AS tableSchema, kcu.column_name AS columnName from INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc join INFORMATION_SCHEMA.key_column_usage as kcu on (tc.constraint_name = kcu.constraint_name and tc.table_name = kcu.table_name) WHERE tc.table_name='myTable';",
        oracle: 'SELECT constraint_name "constraintName", constraint_type "constraintType" , column_name "columnName" from user_constraints natural join user_cons_columns where table_name = \'MYTABLE\'',
        default: "SELECT sql FROM sqlite_master WHERE tbl_name='myTable';"
      });
    });

    it('should add constraint_name to where clause if passed in case of mysql', () => {
      expectsql(sql.showConstraintsQuery('myTable', 'myConstraintName'), {
        mssql: "EXEC sp_helpconstraint @objname = N'[myTable]';",
        postgres: 'SELECT tc.constraint_catalog AS "constraintCatalog", tc.constraint_schema AS "constraintSchema", tc.constraint_name AS "constraintName", tc.table_catalog AS "tableCatalog", tc.table_schema AS "tableSchema", tc.table_name AS "tableName", tc.constraint_type AS "constraintType", tc.is_deferrable AS "isDeferrable", tc.initially_deferred AS "initiallyDeferred", kcu.column_name AS "columnName" from INFORMATION_SCHEMA.table_constraints as "tc" join INFORMATION_SCHEMA.key_column_usage as "kcu" on (tc.constraint_name = kcu.constraint_name and tc.table_name = kcu.table_name) WHERE tc.table_name=\'myTable\';',
        mysql: "SELECT tc.CONSTRAINT_CATALOG AS constraintCatalog, tc.CONSTRAINT_NAME AS constraintName, tc.CONSTRAINT_SCHEMA AS constraintSchema, tc.CONSTRAINT_TYPE AS constraintType, tc.TABLE_NAME AS tableName, tc.TABLE_SCHEMA AS tableSchema, kcu.column_name AS columnName from INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc join INFORMATION_SCHEMA.key_column_usage as kcu on (tc.constraint_name = kcu.constraint_name and tc.table_name = kcu.table_name) WHERE tc.table_name='myTable' AND tc.constraint_name = 'myConstraintName';",
        oracle: 'SELECT constraint_name "constraintName", constraint_type "constraintType" , column_name "columnName" from user_constraints natural join user_cons_columns where table_name = \'MYTABLE\'',
        default: "SELECT sql FROM sqlite_master WHERE tbl_name='myTable' AND sql LIKE '%myConstraintName%';"
      });
    });
  });
});
<commit_msg>test(show-constraints) : showConstraintsQuery<commit_after>'use strict';

const Support   = require(__dirname + '/../support');
const current   = Support.sequelize;
const expectsql = Support.expectsql;
const sql = current.dialect.QueryGenerator;

describe(Support.getTestDialectTeaser('SQL'), () => {
  describe('showConstraint', () => {
    it('naming', () => {
      expectsql(sql.showConstraintsQuery('myTable'), {
        mssql: "EXEC sp_helpconstraint @objname = N'[myTable]';",
        postgres: 'SELECT tc.constraint_catalog AS "constraintCatalog", tc.constraint_schema AS "constraintSchema", tc.constraint_name AS "constraintName", tc.table_catalog AS "tableCatalog", tc.table_schema AS "tableSchema", tc.table_name AS "tableName", tc.constraint_type AS "constraintType", tc.is_deferrable AS "isDeferrable", tc.initially_deferred AS "initiallyDeferred", kcu.column_name AS "columnName" from INFORMATION_SCHEMA.table_constraints as "tc" left outer join INFORMATION_SCHEMA.key_column_usage as "kcu" on (tc.constraint_name = kcu.constraint_name and tc.table_name = kcu.table_name) WHERE tc.table_name=\'myTable\';',
        mysql: "SELECT tc.CONSTRAINT_CATALOG AS constraintCatalog, tc.CONSTRAINT_NAME AS constraintName, tc.CONSTRAINT_SCHEMA AS constraintSchema, tc.CONSTRAINT_TYPE AS constraintType, tc.TABLE_NAME AS tableName, tc.TABLE_SCHEMA AS tableSchema, kcu.column_name AS columnName from INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc join INFORMATION_SCHEMA.key_column_usage as kcu on (tc.constraint_name = kcu.constraint_name and tc.table_name = kcu.table_name) WHERE tc.table_name='myTable';",
        oracle: 'SELECT constraint_name "constraintName", constraint_type "constraintType" , column_name "columnName" from user_constraints natural join user_cons_columns where table_name = \'MYTABLE\'',
        default: "SELECT sql FROM sqlite_master WHERE tbl_name='myTable';"
      });
    });

    it('should add constraint_name to where clause if passed in case of mysql', () => {
      expectsql(sql.showConstraintsQuery('myTable', 'myConstraintName'), {
        mssql: "EXEC sp_helpconstraint @objname = N'[myTable]';",
        postgres: 'SELECT tc.constraint_catalog AS "constraintCatalog", tc.constraint_schema AS "constraintSchema", tc.constraint_name AS "constraintName", tc.table_catalog AS "tableCatalog", tc.table_schema AS "tableSchema", tc.table_name AS "tableName", tc.constraint_type AS "constraintType", tc.is_deferrable AS "isDeferrable", tc.initially_deferred AS "initiallyDeferred", kcu.column_name AS "columnName" from INFORMATION_SCHEMA.table_constraints as "tc" left outer join INFORMATION_SCHEMA.key_column_usage as "kcu" on (tc.constraint_name = kcu.constraint_name and tc.table_name = kcu.table_name) WHERE tc.table_name=\'myTable\';',
        mysql: "SELECT tc.CONSTRAINT_CATALOG AS constraintCatalog, tc.CONSTRAINT_NAME AS constraintName, tc.CONSTRAINT_SCHEMA AS constraintSchema, tc.CONSTRAINT_TYPE AS constraintType, tc.TABLE_NAME AS tableName, tc.TABLE_SCHEMA AS tableSchema, kcu.column_name AS columnName from INFORMATION_SCHEMA.TABLE_CONSTRAINTS as tc join INFORMATION_SCHEMA.key_column_usage as kcu on (tc.constraint_name = kcu.constraint_name and tc.table_name = kcu.table_name) WHERE tc.table_name='myTable' AND tc.constraint_name = 'myConstraintName';",
        oracle: 'SELECT constraint_name "constraintName", constraint_type "constraintType" , column_name "columnName" from user_constraints natural join user_cons_columns where table_name = \'MYTABLE\'',
        default: "SELECT sql FROM sqlite_master WHERE tbl_name='myTable' AND sql LIKE '%myConstraintName%';"
      });
    });
  });
});
<|endoftext|>


<commit_before>var CONFIG         = require("./config"),
    fs             = require("fs"),
    Client         = require("ftp"),
    Git            = require("nodegit"),
    del            = require("del"),
    unzip          = require("unzip"),
    logging        = require("./logger")(true)

listPrimaryDirectory (function (latestFolder) {
  listSecondaryDirectory (latestFolder, function (c, pathToZip) {
    downloadZip (c, pathToZip, function () {
      updateGitFiles (0, function () {
        deleteRepoContents (function () {
          extractZipIntoRepo (function () {
            // TODO: git add . -A && git commit -m "update" && git push
          })
        })
      })
    })
  })
})

function updateGitFiles (fail_counter, callback) {
  logging.print ("cloning " + (fail_counter >= 1 ? " (again) " : "") + "repo ... ")
  Git.Clone(CONFIG.GIT_PATH, "/tmp/ftp2git_repo").then(function(repository) {
    logging.println ("done")

    callback ()
  }, function () {  // Error: folder exists (already cloned?)
    if (fail_counter++ == 0) {
      logging.println ("failed")
      logging.print   ("deleting old repo ... ")

      deleteFromFileSystem ("/tmp/ftp2git_repo/", function () {
        updateGitFiles (fail_counter, callback)
      })
    } else {
      logging.println ("failed!")
    }
  })
}

function deleteRepoContents (callback) {
  logging.print ("Deleting old repo files and folders ... ")

  deleteFromFileSystem ("/tmp/ftp2git_repo/*", callback)
}

function deleteFromFileSystem (path, callback) {
  var delete_options = {
    force: true // allow access from outside directory running script (ie /tmp/)
  }

  del([path], delete_options, function (err, paths) {
    logging.println ("done")

    callback ()
  })
}

function extractZipIntoRepo (callback) {
  logging.print ("Extracting zip into repo ... ")

  fs.createReadStream("/tmp/ftp2git.zip")
    .pipe(unzip.Extract({ path: "/tmp/ftp2git_repo" }))
    .on("close", function () {
      logging.println ("done")

      callback ()
    })
}

function listPrimaryDirectory (callback) {
  var c = new Client()

  logging.print ("Listing primary dir ... ")
  c.on("ready", function() {
    c.list(function(err, list) {
      if (err) throw err

      c.end()

      var latestFolder = getLatestFolder (list)

      logging.println ("done")
      callback (latestFolder)
    })
  })

  c.connect(CONFIG.CLIENT_OPTIONS)
}

function listSecondaryDirectory (latestFolder, callback) {
  var c = new Client()

  logging.print ("Listing secondary dir ... ")
  c.on ("ready", function () {
    c.list(latestFolder, function(err, list) {
      if (err) throw err

      var pathToZip = latestFolder + "/" + getPathToZip (list)

      logging.println ("done")
      callback (c, pathToZip)
    })
  })

  c.connect (CONFIG.CLIENT_OPTIONS)
}

function downloadZip (c, pathToZip, callback) {
  logging.print ("downloading zip file ... ")

  c.get(pathToZip, function(err, stream) {
    if (err) throw err

    stream.once("close", function() {
      c.end()

      logging.println ("done")
      callback()
    })

    stream.pipe(fs.createWriteStream("/tmp/ftp2git.zip"))
  })
}

function getLatestFolder (list) {
  var latestFolder

  for (i in list) {
    var current_folder_name = list[i].name

    if (current_folder_name.indexOf(CONFIG.KEY_WORD) >= 0) {
      latestFolder = current_folder_name
    }
  }

  return latestFolder
}

function getPathToZip (list) {
  var pathToZip

  for (i in list) {
    var filename = list[i].name

    pathToZip = filename
  }

  return pathToZip
}<commit_msg>uses keychain for git ssh auth<commit_after>var CONFIG         = require("./config"),
    fs             = require("fs"),
    Client         = require("ftp"),
    Git            = require("nodegit"),
    del            = require("del"),
    unzip          = require("unzip"),
    logging        = require("./logger")(true)

listPrimaryDirectory (function (latestFolder) {
  listSecondaryDirectory (latestFolder, function (c, pathToZip) {
    downloadZip (c, pathToZip, function () {
      updateGitFiles (0, function () {
        deleteRepoContents (function () {
          extractZipIntoRepo (function () {
            // TODO: git add . -A && git commit -m "update" && git push
          })
        })
      })
    })
  })
})

function updateGitFiles (fail_counter, callback) {
  var options = {
    remoteCallbacks: {
      credentials: function (url, userName) {
        return Git.Cred.sshKeyFromAgent(userName)
//        return Git.Cred.sshKeyNew (userName, 'public.key', 'private.key', '')
      }
    }
  }

  logging.print ("cloning " + (fail_counter >= 1 ? "(again) " : "") + "repo ... ")
  Git.Clone(CONFIG.GIT_PATH, "/tmp/ftp2git_repo", options).then(function(repository) {
    logging.println ("done")

    callback ()
  }, function () {  // Error: folder exists (already cloned?)
    if (fail_counter++ == 0) {
      logging.println ("failed")
      logging.print   ("deleting old repo ... ")

      deleteFromFileSystem ("/tmp/ftp2git_repo/", function () {
        updateGitFiles (fail_counter, callback)
      })
    } else {
      logging.println ("failed!")
    }
  })
}

function deleteRepoContents (callback) {
  logging.print ("Deleting old repo files and folders ... ")

  deleteFromFileSystem ("/tmp/ftp2git_repo/*", callback)
}

function deleteFromFileSystem (path, callback) {
  var delete_options = {
    force: true // allow access from outside directory running script (ie /tmp/)
  }

  del([path], delete_options, function (err, paths) {
    logging.println ("done")

    callback ()
  })
}

function extractZipIntoRepo (callback) {
  logging.print ("Extracting zip into repo ... ")

  fs.createReadStream("/tmp/ftp2git.zip")
    .pipe(unzip.Extract({ path: "/tmp/ftp2git_repo" }))
    .on("close", function () {
      logging.println ("done")

      callback ()
    })
}

function listPrimaryDirectory (callback) {
  var c = new Client()

  logging.print ("Listing primary dir ... ")
  c.on("ready", function() {
    c.list(function(err, list) {
      if (err) throw err

      c.end()

      var latestFolder = getLatestFolder (list)

      logging.println ("done")
      callback (latestFolder)
    })
  })

  c.connect(CONFIG.CLIENT_OPTIONS)
}

function listSecondaryDirectory (latestFolder, callback) {
  var c = new Client()

  logging.print ("Listing secondary dir ... ")
  c.on ("ready", function () {
    c.list(latestFolder, function(err, list) {
      if (err) throw err

      var pathToZip = latestFolder + "/" + getPathToZip (list)

      logging.println ("done")
      callback (c, pathToZip)
    })
  })

  c.connect (CONFIG.CLIENT_OPTIONS)
}

function downloadZip (c, pathToZip, callback) {
  logging.print ("downloading zip file ... ")

  c.get(pathToZip, function(err, stream) {
    if (err) throw err

    stream.once("close", function() {
      c.end()

      logging.println ("done")
      callback()
    })

    stream.pipe(fs.createWriteStream("/tmp/ftp2git.zip"))
  })
}

function getLatestFolder (list) {
  var latestFolder

  for (i in list) {
    var current_folder_name = list[i].name

    if (current_folder_name.indexOf(CONFIG.KEY_WORD) >= 0) {
      latestFolder = current_folder_name
    }
  }

  return latestFolder
}

function getPathToZip (list) {
  var pathToZip

  for (i in list) {
    var filename = list[i].name

    pathToZip = filename
  }

  return pathToZip
}<|endoftext|>


<commit_before>// Copyright (c) 2015 Uber Technologies, Inc.
//
// 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.

'use strict';

var inherits = require('util').inherits;

var TChannelPeersBase = require('./peers_base.js');
var PeerHeap = require('./peer_heap.js');

function TChannelSubPeers(channel, options) {
    if (!(this instanceof TChannelSubPeers)) {
        return new TChannelSubPeers(channel, options);
    }
    var self = this;
    TChannelPeersBase.call(self, channel, options);

    self.peerScoreThreshold = self.options.peerScoreThreshold || 0;
    self._heap = new PeerHeap(channel.random);
    self.choosePeerWithHeap = channel.choosePeerWithHeap;
}

inherits(TChannelSubPeers, TChannelPeersBase);

TChannelSubPeers.prototype.close = function close(callback) {
    var self = this;

    var peers = self.values();
    TChannelPeersBase.prototype.close.call(self, peers, callback);
};

TChannelSubPeers.prototype.add = function add(hostPort, options) {
    /* eslint max-statements: [2, 25]*/
    var self = this;

    var peer = self._map[hostPort];
    if (peer) {
        return peer;
    }

    var topChannel = self.channel.topChannel;

    if (hostPort === topChannel.hostPort) {
        return topChannel.peers.getSelfPeer();
    }

    peer = topChannel.peers.add(hostPort, options);
    peer.setPreferConnectionDirection(self.preferConnectionDirection);

    self._map[hostPort] = peer;
    self._keys.push(hostPort);

    var el = self._heap.add(peer);
    peer.heapElements.push(el);

    return peer;
};

TChannelSubPeers.prototype.clear = function clear() {
    var self = this;

    self._map = Object.create(null);
    self._keys = [];
    self._heap.clear();
};

TChannelSubPeers.prototype._delete = function _del(peer) {
    var self = this;

    var index = self._keys.indexOf(peer.hostPort);
    if (index === -1) {
        return;
    }

    delete self._map[peer.hostPort];
    popout(self._keys, index);

    for (var i = 0; i < peer.heapElements.length; i++) {
        var el = peer.heapElements[i];
        if (el.heap === self._heap) {
            el.heap.remove(el.index);
            popout(peer.heapElements, i);
            break;
        }
    }
};

TChannelSubPeers.prototype.choosePeer = function choosePeer(req) {
    var self = this;

    if (self.choosePeerWithHeap) {
        return self.chooseHeapPeer(req);
    }

    return self.chooseLinearPeer(req);
};

TChannelSubPeers.prototype.chooseLinearPeer = function chooseLinearPeer(req) {
    /* eslint complexity: [2, 15]*/
    var self = this;

    var hosts = self._keys;
    if (!hosts || !hosts.length) {
        return null;
    }

    var threshold = self.peerScoreThreshold;

    var selectedPeer = null;
    var selectedScore = 0;
    for (var i = 0; i < hosts.length; i++) {
        var hostPort = hosts[i];
        var peer = self._map[hostPort];
        if (!req || !req.triedRemoteAddrs || !req.triedRemoteAddrs[hostPort]) {
            var score = peer.getScore(req);

            if (self.channel.topChannel.peerScoredEvent) {
                self.channel.topChannel.peerScoredEvent.emit(peer, {
                    peer: peer,
                    reason: 'chooseLinearPeer',
                    score: score,
                });
            }

            var want = score > threshold &&
                       (selectedPeer === null || score > selectedScore);
            if (want) {
                selectedPeer = peer;
                selectedScore = score;
            }
        }
    }

    if (self.channel.topChannel.peerChosenEvent) {
        self.channel.topChannel.peerChosenEvent.emit(self, {
            mode: 'linear',
            peer: selectedPeer
        });
    }

    return selectedPeer;
};

TChannelSubPeers.prototype.chooseHeapPeer = function chooseHeapPeer(req) {
    var self = this;

    var peer;
    if (req && req.triedRemoteAddrs) {
        peer = self._choosePeerSkipTried(req);
    } else {
        peer = self._heap.choose(self.peerScoreThreshold);
    }

    if (self.channel.topChannel.peerChosenEvent) {
        self.channel.topChannel.peerChosenEvent.emit(self, {
            mode: 'heap',
            peer: peer
        });
    }

    return peer;
};

TChannelSubPeers.prototype._choosePeerSkipTried =
function _choosePeerSkipTried(req) {
    var self = this;

    return self._heap.choose(self.peerScoreThreshold, filterTriedPeers);

    function filterTriedPeers(peer) {
        return !req.triedRemoteAddrs[peer.hostPort];
    }
};

function popout(array, i) {
    if (!array.length) {
        return;
    }

    var j = array.length - 1;
    if (i !== j) {
        var tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
    array.pop();
}

module.exports = TChannelSubPeers;
<commit_msg>linting: [sub_peers] comply with no-comma-dangle rule<commit_after>// Copyright (c) 2015 Uber Technologies, Inc.
//
// 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.

'use strict';

var inherits = require('util').inherits;

var TChannelPeersBase = require('./peers_base.js');
var PeerHeap = require('./peer_heap.js');

function TChannelSubPeers(channel, options) {
    if (!(this instanceof TChannelSubPeers)) {
        return new TChannelSubPeers(channel, options);
    }
    var self = this;
    TChannelPeersBase.call(self, channel, options);

    self.peerScoreThreshold = self.options.peerScoreThreshold || 0;
    self._heap = new PeerHeap(channel.random);
    self.choosePeerWithHeap = channel.choosePeerWithHeap;
}

inherits(TChannelSubPeers, TChannelPeersBase);

TChannelSubPeers.prototype.close = function close(callback) {
    var self = this;

    var peers = self.values();
    TChannelPeersBase.prototype.close.call(self, peers, callback);
};

TChannelSubPeers.prototype.add = function add(hostPort, options) {
    /* eslint max-statements: [2, 25]*/
    var self = this;

    var peer = self._map[hostPort];
    if (peer) {
        return peer;
    }

    var topChannel = self.channel.topChannel;

    if (hostPort === topChannel.hostPort) {
        return topChannel.peers.getSelfPeer();
    }

    peer = topChannel.peers.add(hostPort, options);
    peer.setPreferConnectionDirection(self.preferConnectionDirection);

    self._map[hostPort] = peer;
    self._keys.push(hostPort);

    var el = self._heap.add(peer);
    peer.heapElements.push(el);

    return peer;
};

TChannelSubPeers.prototype.clear = function clear() {
    var self = this;

    self._map = Object.create(null);
    self._keys = [];
    self._heap.clear();
};

TChannelSubPeers.prototype._delete = function _del(peer) {
    var self = this;

    var index = self._keys.indexOf(peer.hostPort);
    if (index === -1) {
        return;
    }

    delete self._map[peer.hostPort];
    popout(self._keys, index);

    for (var i = 0; i < peer.heapElements.length; i++) {
        var el = peer.heapElements[i];
        if (el.heap === self._heap) {
            el.heap.remove(el.index);
            popout(peer.heapElements, i);
            break;
        }
    }
};

TChannelSubPeers.prototype.choosePeer = function choosePeer(req) {
    var self = this;

    if (self.choosePeerWithHeap) {
        return self.chooseHeapPeer(req);
    }

    return self.chooseLinearPeer(req);
};

TChannelSubPeers.prototype.chooseLinearPeer = function chooseLinearPeer(req) {
    /* eslint complexity: [2, 15]*/
    var self = this;

    var hosts = self._keys;
    if (!hosts || !hosts.length) {
        return null;
    }

    var threshold = self.peerScoreThreshold;

    var selectedPeer = null;
    var selectedScore = 0;
    for (var i = 0; i < hosts.length; i++) {
        var hostPort = hosts[i];
        var peer = self._map[hostPort];
        if (!req || !req.triedRemoteAddrs || !req.triedRemoteAddrs[hostPort]) {
            var score = peer.getScore(req);

            if (self.channel.topChannel.peerScoredEvent) {
                self.channel.topChannel.peerScoredEvent.emit(peer, {
                    peer: peer,
                    reason: 'chooseLinearPeer',
                    score: score
                });
            }

            var want = score > threshold &&
                       (selectedPeer === null || score > selectedScore);
            if (want) {
                selectedPeer = peer;
                selectedScore = score;
            }
        }
    }

    if (self.channel.topChannel.peerChosenEvent) {
        self.channel.topChannel.peerChosenEvent.emit(self, {
            mode: 'linear',
            peer: selectedPeer
        });
    }

    return selectedPeer;
};

TChannelSubPeers.prototype.chooseHeapPeer = function chooseHeapPeer(req) {
    var self = this;

    var peer;
    if (req && req.triedRemoteAddrs) {
        peer = self._choosePeerSkipTried(req);
    } else {
        peer = self._heap.choose(self.peerScoreThreshold);
    }

    if (self.channel.topChannel.peerChosenEvent) {
        self.channel.topChannel.peerChosenEvent.emit(self, {
            mode: 'heap',
            peer: peer
        });
    }

    return peer;
};

TChannelSubPeers.prototype._choosePeerSkipTried =
function _choosePeerSkipTried(req) {
    var self = this;

    return self._heap.choose(self.peerScoreThreshold, filterTriedPeers);

    function filterTriedPeers(peer) {
        return !req.triedRemoteAddrs[peer.hostPort];
    }
};

function popout(array, i) {
    if (!array.length) {
        return;
    }

    var j = array.length - 1;
    if (i !== j) {
        var tmp = array[i];
        array[i] = array[j];
        array[j] = tmp;
    }
    array.pop();
}

module.exports = TChannelSubPeers;
<|endoftext|>


<commit_before>var CONFIG         = require("./config"),
    fs             = require("fs"),
    Client         = require("ftp"),
    Git            = require("nodegit"),
    del            = require("del"),
    unzip          = require("unzip"),
    latestFolder   = "",
    pathToZip      = "",
    delete_options = {
      force: true // allow access from outside directory running script (ie /tmp/)
    }

function print (message) {
  process.stdout.write (message)
}

function println (message) {
  print (message + "\n")
}

listPrimaryDirectory (function () {
  listSecondaryDirectory (function (c, pathToZip) {
    downloadZip (c, pathToZip, function () {
      updateGitFiles ()  // TODO: cant have a callback in a promise?
    })
  })
})

function updateGitFiles () {
  print ("cloning repo ... ")
  Git.Clone(CONFIG.GIT_PATH, "/tmp/ftp2git_repo").then(function(repository) {
    println ("done")

    deleteRepoContents (function () {
    })
  }, function () {  // Error: folder exists (already cloned?)
    println ("failed")
    print   ("deleting old repo ... ")

    del(["/tmp/ftp2git_repo/"], delete_options, function (err, paths) {
      println ("done")

      updateGitFiles ()
    })
  })
}

function deleteRepoContents () {
  print ("Deleting old repo files and folders ... ")

  del(["/tmp/ftp2git_repo/*"], delete_options, function (err, paths) {
    println ("done")

    extractZipIntoRepo ()
  })
}

function extractZipIntoRepo () {
  print ("Extracting zip into repo ... ")

  fs.createReadStream("/tmp/ftp2git.zip")
    .pipe(unzip.Extract({ path: "/tmp/ftp2git_repo" }))
    .on("close", function () {
      println ("done")
    })
}

function listPrimaryDirectory (callback) {
  var c = new Client()

  print ("Listing primary dir ... ")
  c.on("ready", function() {
    c.list(function(err, list) {
      if (err) throw err
      println ("done")

      c.end()

      latestFolder = getLatestFolder (list)

      callback ()
    })
  })

  c.connect(CONFIG.CLIENT_OPTIONS)
}

function listSecondaryDirectory (callback) {
  var c = new Client()

  print ("Listing secondary dir ... ")
  c.on ("ready", function () {
    c.list(latestFolder, function(err, list) {
      if (err) throw err
      println ("done")

      var pathToZip = latestFolder + "/" + getPathToZip (list)

      callback (c, pathToZip)
    })
  })

  c.connect (CONFIG.CLIENT_OPTIONS)
}

function downloadZip (c, pathToZip, callback) {
  print ("downloading zip file ... ")
  c.get(pathToZip, function(err, stream) {
    if (err) throw err

    stream.once("close", function() {
      c.end()

      println ("done")

      callback()
    })

    stream.pipe(fs.createWriteStream("/tmp/ftp2git.zip"))
  })
}

function getLatestFolder (list) {
  var latestFolder

  for (i in list) {
    var current_folder_name = list[i].name

    if (current_folder_name.indexOf(CONFIG.KEY_WORD) >= 0) {
      latestFolder = current_folder_name
    }
  }

  return latestFolder
}

function getPathToZip (list) {
  var pathToZip

  for (i in list) {
    var filename = list[i].name

    pathToZip = filename
  }

  return pathToZip
}<commit_msg>logging refactor (should be made its own module)<commit_after>var CONFIG         = require("./config"),
    fs             = require("fs"),
    Client         = require("ftp"),
    Git            = require("nodegit"),
    del            = require("del"),
    unzip          = require("unzip"),
    latestFolder   = "",
    pathToZip      = "",
    delete_options = {
      force: true // allow access from outside directory running script (ie /tmp/)
    }, Logging     = function () {
      this.constructor.prototype.print = function (message) {
        process.stdout.write (message)
      }

      this.constructor.prototype.println = function (message) {
        this.print (message + "\n")
      }
    }, logging = new Logging()

listPrimaryDirectory (function () {
  listSecondaryDirectory (function (c, pathToZip) {
//    downloadZip (c, pathToZip, function () {
      updateGitFiles ()  // TODO: cant have a callback in a promise?
//    })
  })
})

function updateGitFiles () {
  logging.print ("cloning repo ... ")
  Git.Clone(CONFIG.GIT_PATH, "/tmp/ftp2git_repo").then(function(repository) {
    logging.println ("done")

    deleteRepoContents (function () {
    })
  }, function () {  // Error: folder exists (already cloned?)
    logging.println ("failed")
    logging.print   ("deleting old repo ... ")

    del(["/tmp/ftp2git_repo/"], delete_options, function (err, paths) {
      logging.println ("done")

      updateGitFiles ()
    })
  })
}

function deleteRepoContents () {
  logging.print ("Deleting old repo files and folders ... ")

  del(["/tmp/ftp2git_repo/*"], delete_options, function (err, paths) {
    logging.println ("done")

    extractZipIntoRepo ()
  })
}

function extractZipIntoRepo () {
  logging.print ("Extracting zip into repo ... ")

  fs.createReadStream("/tmp/ftp2git.zip")
    .pipe(unzip.Extract({ path: "/tmp/ftp2git_repo" }))
    .on("close", function () {
      logging.println ("done")
    })
}

function listPrimaryDirectory (callback) {
  var c = new Client()

  logging.print ("Listing primary dir ... ")
  c.on("ready", function() {
    c.list(function(err, list) {
      if (err) throw err

      c.end()

      latestFolder = getLatestFolder (list)

      logging.println ("done")
      callback ()
    })
  })

  c.connect(CONFIG.CLIENT_OPTIONS)
}

function listSecondaryDirectory (callback) {
  var c = new Client()

  logging.print ("Listing secondary dir ... ")
  c.on ("ready", function () {
    c.list(latestFolder, function(err, list) {
      if (err) throw err

      var pathToZip = latestFolder + "/" + getPathToZip (list)

      logging.println ("done")
      callback (c, pathToZip)
    })
  })

  c.connect (CONFIG.CLIENT_OPTIONS)
}

function downloadZip (c, pathToZip, callback) {
  logging.print ("downloading zip file ... ")

  c.get(pathToZip, function(err, stream) {
    if (err) throw err

    stream.once("close", function() {
      c.end()

      logging.println ("done")
      callback()
    })

    stream.pipe(fs.createWriteStream("/tmp/ftp2git.zip"))
  })
}

function getLatestFolder (list) {
  var latestFolder

  for (i in list) {
    var current_folder_name = list[i].name

    if (current_folder_name.indexOf(CONFIG.KEY_WORD) >= 0) {
      latestFolder = current_folder_name
    }
  }

  return latestFolder
}

function getPathToZip (list) {
  var pathToZip

  for (i in list) {
    var filename = list[i].name

    pathToZip = filename
  }

  return pathToZip
}<|endoftext|>


<commit_before>var PubNub = require('pubnub')
var async = require('async')
var os = require("os");
var config = require('./config.json');

var hostname = os.hostname();

var subscribe = function(callback) {

  pubnub = new PubNub({
     publishKey : config.publishKey,
     subscribeKey : config.subscribeKey,
     ssl: true
  })

  pubnub.addListener({
    message : function(message) {
      // Calculate Latency
      var now = new Date();
      var sent = new Date(message.message.Date);
      var diff = now - sent;
      // Reduce size of hostname to save on log line size

      // Print full hostname if there is no "."
      if((hostname.indexOf(".")) == -1) {
          shortHostname = hostname;
      } else {
          var shortHostname = hostname.substr(0,  hostname.indexOf("."));
      }

      console.log(message.message.Date + ' ' + shortHostname +
        ' ' + message.message['E-Tag'] + ' ' + message.message.Status +
        ' ' + diff);
    }

  })

  pubnub.subscribe({
    channels : [ 'test' ]
  });

  callback(null,"connected and subscribed");

};

if (require.main === module) {
  // Number of connections to run on server.
  var connections = config.connections;
  // Number of seconds to ramp up over.
  var ramp = config.ramp;
  // Concurrent connections attempted per second.
  var rate = Math.ceil((connections / ramp) * 100)/100;;

  var count = 0

  intervalPerConnection = (1/rate)*1000;

  console.log("Ramping up " + connections +
    " connections at a rate of " + rate +
    " per second over a period of " + ramp + " seconds");

  var subscribers = [];

  setTimeout(function request() {
    subscribers.length = 0
    subscribers.push(subscribe);
    async.parallel(subscribers, function(err, result){
      console.log("Connection: " + count + ' ' + result )
    });

    if(count == connections){
    }
    else {
      interval = setTimeout(request,intervalPerConnection);
      count++;
    }
  }, intervalPerConnection);

} else {
  console.log('please start via node subscribe.js');
}
<commit_msg>Improved logging format<commit_after>var PubNub = require('pubnub')
var async = require('async')
var os = require("os");
var config = require('./config.json');

var workerID = process.argv[2];

var subscribe = function(subID) {

  return function (callback) {

    var subscriber = workerID + '_' + subID;
    pubnub = new PubNub({
       publishKey : config.publishKey,
       subscribeKey : config.subscribeKey,
       ssl: true
    })

    pubnub.addListener({
      message : function(message) {
        // Calculate Latency
        var now = new Date();
        var sent = new Date(message.message.Date);
        var diff = now - sent;
        // Reduce size of hostname to save on log line size

        console.log(message.message.Date + ' ' + subscriber +
          ' ' + message.message['E-Tag'] + ' ' + message.message.Status +
          ' ' + diff);
      }

    })

    pubnub.subscribe({
      channels : [ 'test' ]
    });

    callback(null, 'subscriber ' + subscriber + ' initialised');
  }
};

if (require.main === module) {
  // Number of connections to run on server.
  var connections = config.connections;
  // Number of seconds to ramp up over.
  var ramp = config.ramp;
  // Concurrent connections attempted per second.
  var rate = Math.ceil((connections / ramp) * 100)/100;;

  var count = 0

  intervalPerConnection = (1/rate)*1000;

  console.log("Ramping up " + connections +
    " connections at a rate of " + rate +
    " per second over a period of " + ramp + " seconds");

  var subscribers = [];

  setTimeout(function request() {
    subscribers.length = 0
    subscribers.push(subscribe(count));
    async.parallel(subscribers, function(err, result){
      console.log((new Date()).toISOString() + " connection: " + count + ' ' + result )
    });

    if(count == connections){
    }
    else {
      interval = setTimeout(request,intervalPerConnection);
      count++;
    }
  }, intervalPerConnection);

} else {
  console.log('please start via node subscribe.js');
}
<|endoftext|>


<commit_before>var domain    = require('domain');
var through   = require('through2');
var graft     = require('graft');

var debug     = require('debug');
var log       = debug('ab:subscribe');
var logStream = require('debug-stream')(log);

module.exports = function subscribe() {
  var merge = graft();

  var active = 0;

  return through.obj(function(msg, enc, done) {

    var client = active++;
    log('receive subscribe message: '+client);

    var d = domain.create();

    d.on('error', function(err) { log('ending of client '+client+' with error: '+err); });

    d.run(function() {

      msg._session.on('close' , function() {
        merge.unpipe(msg.strokeSync);
        msg.strokeInput.unpipe();
      });

      merge.pipe(msg.strokeSync);

      msg.strokeInput
        .pipe(logStream('incoming stroke %s from: '+client))
        .pipe(through.obj(function(chunk, enc, done) {
          var msg = {
            topic: chunk.topic,
            size: chunk.size,
            color: chunk.color,
            segments: through.obj()
          };
          chunk.segments.pipe(msg.segments);
          merge.write(msg);
          done();
        }));
      done();
    });
  });
};
<commit_msg>can pass in channel to subscribe on<commit_after>var domain    = require('domain');
var through   = require('through2');
var graft     = require('graft');

var debug     = require('debug');
var log       = debug('ab:subscribe');
var logStream = require('debug-stream')(log);

module.exports = function subscribe(merge) {
  var merge = merge || graft();

  var active = 0;

  return through.obj(function(msg, enc, done) {

    var client = active++;
    log('receive subscribe message: '+client);

    var d = domain.create();

    d.on('error', function(err) { log('ending of client '+client+' with error: '+err); });

    d.run(function() {

      msg._session.on('close' , function() {
        merge.unpipe(msg.strokeSync);
        msg.strokeInput.unpipe();
      });

      merge.pipe(msg.strokeSync);

      msg.strokeInput
        .pipe(logStream('incoming stroke %s from: '+client))
        .pipe(through.obj(function(chunk, enc, done) {
          var msg = {
            topic: chunk.topic,
            size: chunk.size,
            color: chunk.color,
            segments: through.obj()
          };
          chunk.segments.pipe(msg.segments);
          merge.write(msg);
          done();
        }));
      done();
    });
  });
};
<|endoftext|>


<commit_before>/**

  cli

**/

//
//  Dependencies
//

var program    = require("commander"),
    chalk      = require("chalk"),
    data       = require("./data-editor"),
    middleware = require("./middleware-editor"),
    pipelines  = require("./pipelines-editor"),
    routes     = require("./routes-editor"),
    utils      = require("./cli-utils"),
    vars       = require("./vars-editor");

//
//  Exports
//

module.exports = function() {

  var command = process.argv[2];

  // Set start as default argument
  if ("undefined" == typeof process.argv[2]) process.argv[2] = "help";

  program
    .version("0.7.0");

  program
    .command("start")
    .action(start);

  program
    .command("help")
    .action(showHelp);

  program
    .command("config")
    .action(function() {
      data.list();
      vars.listEnvs();
      vars.listLocals();
      middleware.list();
      pipelines.list();
      routes.list();
    });

  program
    .command("data")
    .action(data.list);

  program
    .command("data:add <folder> [route]")
    .action(data.add);

  program
    .command("data:remove <folder>")
    .action(data.remove);

  program
    .command("defaults")
    .action(listDefaults);

  program
    .command("defaults:restore")
    .action(restoreDefaults);

  program
    .command("env")
    .action(vars.listEnvs);

  program
    .command("env:add <key> <value>")
    .action(vars.addEnv);

  program
    .command("env:remove <key>")
    .action(vars.removeEnv);

  program
    .command("locals")
    .action(vars.listLocals);

  program
    .command("locals:add <key> <value>")
    .action(vars.addLocal);

  program
    .command("locals:remove <key>")
    .action(vars.removeLocal);

  program
    .command("middleware")
    .action(middleware.list);

  program
    .command("middleware:add <position> <package>")
    .action(middleware.add);

  program
    .command("middleware:remove <position> <package>")
    .action(middleware.remove);

  program
    .command("pipelines")
    .action(pipelines.list);

  program
    .command("pipelines:add <extension> <pipeline>")
    .action(pipelines.add);

  program
    .command("pipelines:remove <extension>")
    .action(pipelines.remove);

  program
    .command("routes")
    .action(routes.list);

  program
    .command("routes:scripts <route> <folder> <bundleFolders>")
    .action(routes.scripts);

  program
    .command("routes:statics <route> <folder>")
    .action(routes.statics);

  program
    .command("routes:styles <route> <folder>")
    .action(routes.styles);

  program
    .command("routes:views <route> <folder>")
    .action(routes.views);

  program
    .command("routes:remove <route>")
    .action(routes.remove);

  program.parse(process.argv);

};

/**

  Starts the server

**/

function start(env) {

  var server = require("../server/");

  // Start the server
  console.log(chalk.green.bold("\nStarting server...\n"));

  if (/^prod/i.test(env)) {
    process.env.NODE_ENV = "production";
    server();
  } else {
    // Start browser sync and proxy
    server({ liveRefresh: true });
    global.server.init({ proxy : "localhost:" + global.ports.server });
  }

}

/**

  Shows help on commands

**/

function showHelp() {

  var columns = [];

  console.log("");
  console.log("To start the server, run", chalk.magenta("shipp start"));
  console.log("");
  console.log(chalk.cyan(" Usage:"));
  console.log("");
  console.log("    " + chalk.magenta("shipp") + chalk.yellow(" <command> [<args>]"));
  console.log("");
  console.log(chalk.cyan(" Commands:"));
  console.log("");

  readHelpFile("main.json").forEach(listCommand);

}

/**

  Helper to read in a file from the help directory

**/

function readHelpFile(filename) {
  return JSON.parse(utils.readFile(require("path").join(__dirname, "help", filename), "utf8"));
}

/**

  Helper to list a command, properly spaced

**/

function listCommand(command, description) {

  var key = command.command;

  // Allow for blank line
  if ("" === key) return console.log("");

  // Pad key
  key = utils.pad(key, 39);

  // Replace <commands> with yellow
  key = key.replace(/\"?<[^>]+>\"?/g, function(x) { return chalk.yellow(x); });
  console.log("    " + key + "  " + command.description);

}

/**

  Lists defaults

**/

function listDefaults() {

  require("./config-editor").loadDefaults();

  console.log("");
  console.log(chalk.magenta(" Note:"), "The following settings are the defaults and may or may not reflect your");
  console.log("       app's configuration. To see your config, use the", chalk.yellow("config"), "command. To");
  console.log("       restore defaults, use the", chalk.yellow("defaults:restore"), "command.");

  data.list();
  vars.listEnvs();
  vars.listLocals();
  middleware.list();
  pipelines.list();
  routes.list();

}

/**

  Deletes the shipp.json file and restores defaults.

**/

function restoreDefaults() {

  var str;

  console.log("");
  str  = chalk.red("   Warning!") + " This command will delete your ";
  str += chalk.yellow("shipp.json") + " file (using default options instead)";
  console.log(str);
  console.log("   To continue type DELETE and press enter.");

  process.stdout.write("   > ");

  process.stdout.on("data", function(res) {
    console.log("");
    res = res.toString().trim();

    if (/^delete$/i.test(res)) {
      console.log("   We've restored defaults by deleting your", chalk.yellow("shipp.json"), "file");
      require("./config-editor").remove();
    } else
      console.log("   Nothing done. Come back if you need us.");

    console.log("");
    process.exit();
  });

}
<commit_msg>cli: BrowserSync uses open port<commit_after>/**

  cli

**/

//
//  Dependencies
//

var program    = require("commander"),
    chalk      = require("chalk"),
    data       = require("./data-editor"),
    middleware = require("./middleware-editor"),
    pipelines  = require("./pipelines-editor"),
    routes     = require("./routes-editor"),
    utils      = require("./cli-utils"),
    vars       = require("./vars-editor");

//
//  Exports
//

module.exports = function() {

  var command = process.argv[2];

  // Set start as default argument
  if ("undefined" == typeof process.argv[2]) process.argv[2] = "help";

  program
    .version("0.7.0");

  program
    .command("start")
    .action(start);

  program
    .command("help")
    .action(showHelp);

  program
    .command("config")
    .action(function() {
      data.list();
      vars.listEnvs();
      vars.listLocals();
      middleware.list();
      pipelines.list();
      routes.list();
    });

  program
    .command("data")
    .action(data.list);

  program
    .command("data:add <folder> [route]")
    .action(data.add);

  program
    .command("data:remove <folder>")
    .action(data.remove);

  program
    .command("defaults")
    .action(listDefaults);

  program
    .command("defaults:restore")
    .action(restoreDefaults);

  program
    .command("env")
    .action(vars.listEnvs);

  program
    .command("env:add <key> <value>")
    .action(vars.addEnv);

  program
    .command("env:remove <key>")
    .action(vars.removeEnv);

  program
    .command("locals")
    .action(vars.listLocals);

  program
    .command("locals:add <key> <value>")
    .action(vars.addLocal);

  program
    .command("locals:remove <key>")
    .action(vars.removeLocal);

  program
    .command("middleware")
    .action(middleware.list);

  program
    .command("middleware:add <position> <package>")
    .action(middleware.add);

  program
    .command("middleware:remove <position> <package>")
    .action(middleware.remove);

  program
    .command("pipelines")
    .action(pipelines.list);

  program
    .command("pipelines:add <extension> <pipeline>")
    .action(pipelines.add);

  program
    .command("pipelines:remove <extension>")
    .action(pipelines.remove);

  program
    .command("routes")
    .action(routes.list);

  program
    .command("routes:scripts <route> <folder> <bundleFolders>")
    .action(routes.scripts);

  program
    .command("routes:statics <route> <folder>")
    .action(routes.statics);

  program
    .command("routes:styles <route> <folder>")
    .action(routes.styles);

  program
    .command("routes:views <route> <folder>")
    .action(routes.views);

  program
    .command("routes:remove <route>")
    .action(routes.remove);

  program.parse(process.argv);

};

/**

  Starts the server

**/

function start(env) {

  var server = require("../server/");

  // Start the server
  console.log(chalk.green.bold("\nStarting server...\n"));

  if (/^prod/i.test(env)) {
    process.env.NODE_ENV = "production";
    server();
  } else {
    // Start browser sync and proxy
    server({ liveRefresh: true }, function() {
      global.server.init({ proxy : "localhost:" + global.ports.server });
    });
  }

}

/**

  Shows help on commands

**/

function showHelp() {

  var columns = [];

  console.log("");
  console.log("To start the server, run", chalk.magenta("shipp start"));
  console.log("");
  console.log(chalk.cyan(" Usage:"));
  console.log("");
  console.log("    " + chalk.magenta("shipp") + chalk.yellow(" <command> [<args>]"));
  console.log("");
  console.log(chalk.cyan(" Commands:"));
  console.log("");

  readHelpFile("main.json").forEach(listCommand);

}

/**

  Helper to read in a file from the help directory

**/

function readHelpFile(filename) {
  return JSON.parse(utils.readFile(require("path").join(__dirname, "help", filename), "utf8"));
}

/**

  Helper to list a command, properly spaced

**/

function listCommand(command, description) {

  var key = command.command;

  // Allow for blank line
  if ("" === key) return console.log("");

  // Pad key
  key = utils.pad(key, 39);

  // Replace <commands> with yellow
  key = key.replace(/\"?<[^>]+>\"?/g, function(x) { return chalk.yellow(x); });
  console.log("    " + key + "  " + command.description);

}

/**

  Lists defaults

**/

function listDefaults() {

  require("./config-editor").loadDefaults();

  console.log("");
  console.log(chalk.magenta(" Note:"), "The following settings are the defaults and may or may not reflect your");
  console.log("       app's configuration. To see your config, use the", chalk.yellow("config"), "command. To");
  console.log("       restore defaults, use the", chalk.yellow("defaults:restore"), "command.");

  data.list();
  vars.listEnvs();
  vars.listLocals();
  middleware.list();
  pipelines.list();
  routes.list();

}

/**

  Deletes the shipp.json file and restores defaults.

**/

function restoreDefaults() {

  var str;

  console.log("");
  str  = chalk.red("   Warning!") + " This command will delete your ";
  str += chalk.yellow("shipp.json") + " file (using default options instead)";
  console.log(str);
  console.log("   To continue type DELETE and press enter.");

  process.stdout.write("   > ");

  process.stdout.on("data", function(res) {
    console.log("");
    res = res.toString().trim();

    if (/^delete$/i.test(res)) {
      console.log("   We've restored defaults by deleting your", chalk.yellow("shipp.json"), "file");
      require("./config-editor").remove();
    } else
      console.log("   Nothing done. Come back if you need us.");

    console.log("");
    process.exit();
  });

}
<|endoftext|>