<commit_before>/*global casper*/
/*jshint strict:false maxstatements:99*/
var utils = require('utils'),
    t = casper.test,
    x = require('casper').selectXPath;

t.comment('betterTypeOf()');
(function() {
    var testCases = [
        {subject: 1, expected: 'number'},
        {subject: '1', expected: 'string'},
        {subject: {}, expected: 'object'},
        {subject: [], expected: 'array'},
        {subject: undefined, expected: 'undefined'},
        {subject: null, expected: 'null'},
        {subject: function(){}, expected: 'function'},
        {subject: window, expected: 'domwindow'},
        {subject: new Date(), expected: 'date'},
        {subject: new RegExp(), expected: 'regexp'}
    ];
    testCases.forEach(function(testCase) {
        t.assertEquals(utils.betterTypeOf(testCase.subject), testCase.expected,
            require('utils').format('betterTypeOf() detects expected type "%s"', testCase.subject));
    });
})();

t.comment('cleanUrl()');
(function() {
    var testCases = {
        'http://google.com/': 'http://google.com/',
        'http://google.com': 'http://google.com/',
        'http://www.google.com/': 'http://www.google.com/',
        'http://www.google.com/?plop=2': 'http://www.google.com/?plop=2',
        'https://google.com/': 'https://google.com/',
        'https://google.com': 'https://google.com/',
        'https://www.google.com/': 'https://www.google.com/',
        'https://www.google.com/?plop=2': 'https://www.google.com/?plop=2',
        'file:///Users/toto/toto.html': 'file:///Users/toto/toto.html',
        '/100': '/100'
    };
    for (var testCase in testCases) {
        t.assertEquals(utils.cleanUrl(testCase), testCases[testCase], 'cleanUrl() cleans an URL');
    }
})();

t.comment('clone()');
(function() {
    var a = {a: 1, b: 2, c: [1, 2]};
    t.assertEquals(utils.clone(a), a);
    var b = [1, 2, 3, a];
    t.assertEquals(utils.clone(b), b);
})();

t.comment('equals()');
(function() {
    t.assert(utils.equals(null, null), 'equals() null equality');
    t.assertNot(utils.equals(null, undefined), 'equals() null vs. undefined inequality');
    t.assert(utils.equals("hi", "hi"), 'equals() string equality');
    t.assertNot(utils.equals("hi", "ih"), 'equals() string inequality');
    t.assert(utils.equals(5, 5), 'equals() number equality');
    t.assertNot(utils.equals("5", 5), 'equals() number equality without implicit cast');
    t.assert(utils.equals(5, 5.0), 'equals() number equality with cast');
    t.assertNot(utils.equals(5, 10), 'equals() number inequality');
    t.assert(utils.equals([], []), 'equals() empty array equality');
    t.assert(utils.equals([1,2], [1,2]), 'equals() array equality');
    t.assert(utils.equals([1,2,[1,2,function(){}]], [1,2,[1,2,function(){}]]), 'equals() complex array equality');
    t.assertNot(utils.equals([1,2,[1,2,function(a){}]], [1,2,[1,2,function(b){}]]), 'equals() complex array inequality');
    t.assertNot(utils.equals([1,2], [2,1]), 'equals() shuffled array inequality');
    t.assertNot(utils.equals([1,2], [1,2,3]), 'equals() array length inequality');
    t.assert(utils.equals({}, {}), 'equals() empty object equality');
    t.assert(utils.equals({a:1,b:2}, {a:1,b:2}), 'equals() object length equality');
    t.assert(utils.equals({a:1,b:2}, {b:2,a:1}), 'equals() shuffled object keys equality');
    t.assertNot(utils.equals({a:1,b:2}, {a:1,b:3}), 'equals() object inequality');
    t.assert(utils.equals({1:{name:"bob",age:28}, 2:{name:"john",age:26}}, {1:{name:"bob",age:28}, 2:{name:"john",age:26}}), 'equals() complex object equality');
    t.assertNot(utils.equals({1:{name:"bob",age:28}, 2:{name:"john",age:26}}, {1:{name:"bob",age:28}, 2:{name:"john",age:27}}), 'equals() complex object inequality');
    t.assert(utils.equals(function(x){return x;}, function(x){return x;}), 'equals() function equality');
    t.assertNot(utils.equals(function(x){return x;}, function(y){return y+2;}), 'equals() function inequality');
    t.assert(utils.equals([{a:1, b:2}, {c:3, d:4}], [{a:1, b:2}, {c:3, d:4}]), 'equals() arrays of objects');
})();

t.comment('fileExt()');
(function() {
    var testCases = {
        'foo.ext':    'ext',
        'FOO.EXT':    'ext',
        'a.ext':      'ext',
        '.ext':       'ext',
        'toto.':      '',
        ' plop.ext ': 'ext'
    };

    for (var testCase in testCases) {
        t.assertEquals(utils.fileExt(testCase), testCases[testCase], 'fileExt() extract file extension');
    }
})();

t.comment('fillBlanks()');
(function() {
    var testCases = {
        'foo':         'foo       ',
        '  foo bar ':  '  foo bar ',
        '  foo bar  ': '  foo bar  '
    };

    for (var testCase in testCases) {
        t.assertEquals(utils.fillBlanks(testCase, 10), testCases[testCase], 'fillBlanks() fills blanks');
    }
})();

t.comment('getPropertyPath()');
(function() {
    var testCases = [
        {
            input:  utils.getPropertyPath({}, 'a.b.c'),
            output: undefined
        },
        {
            input:  utils.getPropertyPath([1, 2, 3], 'a.b.c'),
            output: undefined
        },
        {
            input:  utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b.c'),
            output: 1
        },
        {
            input:  utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b.x'),
            output: undefined
        },
        {
            input:  utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b'),
            output: { c: 1 }
        },
        {
            input:  utils.getPropertyPath({ 'a-b': { 'c-d': 1} }, 'a-b.c-d'),
            output: 1
        },
        {
            input:  utils.getPropertyPath({ 'a.b': { 'c.d': 1} }, 'a.b.c.d'),
            output: undefined
        }
    ];
    testCases.forEach(function(testCase) {
        t.assertEquals(testCase.input, testCase.output, 'getPropertyPath() gets a property using a path');
    });
})();

t.comment('isArray()');
(function() {
    t.assertEquals(utils.isArray([]), true, 'isArray() checks for an Array');
    t.assertEquals(utils.isArray({}), false, 'isArray() checks for an Array');
    t.assertEquals(utils.isArray("foo"), false, 'isArray() checks for an Array');
})();

t.comment('isClipRect()');
(function() {
    var testCases = [
        [{},                                              false],
        [{top: 2},                                        false],
        [{top: 2, left: 2, width: 2, height: 2},          true],
        [{top: 2, left: 2, height: 2, width: 2},          true],
        [{top: 2, left: 2, width: 2, height: new Date()}, false]
    ];

    testCases.forEach(function(testCase) {
        t.assertEquals(utils.isClipRect(testCase[0]), testCase[1], 'isClipRect() checks for a ClipRect');
    });
})();

t.comment('isHTTPResource()');
(function() {
    var testCases = [
        [{},                              false],
        [{url: 'file:///var/www/i.html'}, false],
        [{url: 'mailto:plop@plop.com'},   false],
        [{url: 'ftp://ftp.plop.com'},     false],
        [{url: 'HTTP://plop.com/'},       true],
        [{url: 'https://plop.com/'},      true]
    ];

    testCases.forEach(function(testCase) {
        t.assertEquals(utils.isHTTPResource(testCase[0]), testCase[1], 'isHTTPResource() checks for an HTTP resource');
    });
})();

t.comment('isObject()');
(function() {
    t.assertEquals(utils.isObject({}), true, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject([]), true, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject(1), false, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject("1"), false, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject(function(){}), false, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject(new Function('return {};')()), true, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject(require('webpage').create()), true, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject(null), false, 'isObject() checks for an Object');
})();

t.comment('isValidSelector()');
(function() {
    t.assertEquals(utils.isValidSelector({}), false, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector(""), false, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector("a"), true, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector('div#plop form[name="form"] input[type="submit"]'), true, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector(x('//a')), true, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector({
        type: "css",
        path: 'div#plop form[name="form"] input[type="submit"]'
    }), true, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector({
        type: "xpath",
        path: '//a'
    }), true, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector({
        type: "css"
    }), false, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector({
        type: "xpath"
    }), false, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector({
        type: "css3",
        path: "a"
    }), false, 'isValidSelector() checks for a valid selector');
})();

t.comment('isWebPage()');
(function() {
    var pageModule = require('webpage');
    t.assertEquals(utils.isWebPage(pageModule), false, 'isWebPage() checks for a WebPage instance');
    t.assertEquals(utils.isWebPage(pageModule.create()), true, 'isWebPage() checks for a WebPage instance');
    t.assertEquals(utils.isWebPage(null), false, 'isWebPage() checks for a WebPage instance');
})();

t.comment('isJsFile()');
(function() {
    var testCases = {
        '':             false,
        'toto.png':     false,
        'plop':         false,
        'gniii.coffee': true,
        'script.js':    true
    };

    for (var testCase in testCases) {
        t.assertEquals(utils.isJsFile(testCase), testCases[testCase], 'isJsFile() checks for js file');
    }
})();

t.comment('mergeObjects()');
(function() {
    var testCases = [
        {
            obj1: {a: 1}, obj2: {b: 2}, merged: {a: 1, b: 2}
        },
        {
            obj1: {}, obj2: {a: 1}, merged: {a: 1}
        },
        {
            obj1: {a: 1}, obj2: {}, merged: {a: 1}
        },
        {
            obj1: {a: 1}, obj2: {a: 2}, merged: {a: 2}
        },
        {
            obj1:   {x: 0, double: function(){return this.x*2;}},
            obj2:   {triple: function(){return this.x*3;}},
            merged: {
                x: 0,
                double: function(){return this.x*2;},
                triple: function(){return this.x*3;}
            }
        }
    ];

    testCases.forEach(function(testCase) {
        t.assertEquals(utils.mergeObjects(testCase.obj1, testCase.obj2), testCase.merged, 'mergeObjects() can merge objects');
    });
})();

t.comment('objectValues()');
(function() {
    t.assertEquals(utils.objectValues({}), [], 'objectValues() can extract object values');
    t.assertEquals(utils.objectValues({a: 1, b: 2}), [1, 2], 'objectValues() can extract object values');
})();

t.comment('unique()');
(function() {
    var testCases = [
        {
            input:  [1,2,3],
            output: [1,2,3]
        },
        {
            input:  [1,2,3,2,1],
            output: [1,2,3]
        },
        {
            input:  ["foo", "bar", "foo"],
            output: ["foo", "bar"]
        },
        {
            input:  [],
            output: []
        }
    ];
    testCases.forEach(function(testCase) {
        t.assertEquals(utils.unique(testCase.input), testCase.output, 'unique() computes unique values of an array');
    });
})();

t.done(112);
<commit_msg>added tests for version comparison utils<commit_after>/*global casper*/
/*jshint strict:false maxstatements:99*/
var utils = require('utils'),
    t = casper.test,
    x = require('casper').selectXPath;

t.comment('betterTypeOf()');
(function() {
    var testCases = [
        {subject: 1, expected: 'number'},
        {subject: '1', expected: 'string'},
        {subject: {}, expected: 'object'},
        {subject: [], expected: 'array'},
        {subject: undefined, expected: 'undefined'},
        {subject: null, expected: 'null'},
        {subject: function(){}, expected: 'function'},
        {subject: window, expected: 'domwindow'},
        {subject: new Date(), expected: 'date'},
        {subject: new RegExp(), expected: 'regexp'}
    ];
    testCases.forEach(function(testCase) {
        t.assertEquals(utils.betterTypeOf(testCase.subject), testCase.expected,
            require('utils').format('betterTypeOf() detects expected type "%s"', testCase.subject));
    });
})();

t.comment('cleanUrl()');
(function() {
    var testCases = {
        'http://google.com/': 'http://google.com/',
        'http://google.com': 'http://google.com/',
        'http://www.google.com/': 'http://www.google.com/',
        'http://www.google.com/?plop=2': 'http://www.google.com/?plop=2',
        'https://google.com/': 'https://google.com/',
        'https://google.com': 'https://google.com/',
        'https://www.google.com/': 'https://www.google.com/',
        'https://www.google.com/?plop=2': 'https://www.google.com/?plop=2',
        'file:///Users/toto/toto.html': 'file:///Users/toto/toto.html',
        '/100': '/100'
    };
    for (var testCase in testCases) {
        t.assertEquals(utils.cleanUrl(testCase), testCases[testCase], 'cleanUrl() cleans an URL');
    }
})();

t.comment('clone()');
(function() {
    var a = {a: 1, b: 2, c: [1, 2]};
    t.assertEquals(utils.clone(a), a);
    var b = [1, 2, 3, a];
    t.assertEquals(utils.clone(b), b);
})();

t.comment('equals()');
(function() {
    t.assert(utils.equals(null, null), 'equals() null equality');
    t.assertNot(utils.equals(null, undefined), 'equals() null vs. undefined inequality');
    t.assert(utils.equals("hi", "hi"), 'equals() string equality');
    t.assertNot(utils.equals("hi", "ih"), 'equals() string inequality');
    t.assert(utils.equals(5, 5), 'equals() number equality');
    t.assertNot(utils.equals("5", 5), 'equals() number equality without implicit cast');
    t.assert(utils.equals(5, 5.0), 'equals() number equality with cast');
    t.assertNot(utils.equals(5, 10), 'equals() number inequality');
    t.assert(utils.equals([], []), 'equals() empty array equality');
    t.assert(utils.equals([1,2], [1,2]), 'equals() array equality');
    t.assert(utils.equals([1,2,[1,2,function(){}]], [1,2,[1,2,function(){}]]), 'equals() complex array equality');
    t.assertNot(utils.equals([1,2,[1,2,function(a){}]], [1,2,[1,2,function(b){}]]), 'equals() complex array inequality');
    t.assertNot(utils.equals([1,2], [2,1]), 'equals() shuffled array inequality');
    t.assertNot(utils.equals([1,2], [1,2,3]), 'equals() array length inequality');
    t.assert(utils.equals({}, {}), 'equals() empty object equality');
    t.assert(utils.equals({a:1,b:2}, {a:1,b:2}), 'equals() object length equality');
    t.assert(utils.equals({a:1,b:2}, {b:2,a:1}), 'equals() shuffled object keys equality');
    t.assertNot(utils.equals({a:1,b:2}, {a:1,b:3}), 'equals() object inequality');
    t.assert(utils.equals({1:{name:"bob",age:28}, 2:{name:"john",age:26}}, {1:{name:"bob",age:28}, 2:{name:"john",age:26}}), 'equals() complex object equality');
    t.assertNot(utils.equals({1:{name:"bob",age:28}, 2:{name:"john",age:26}}, {1:{name:"bob",age:28}, 2:{name:"john",age:27}}), 'equals() complex object inequality');
    t.assert(utils.equals(function(x){return x;}, function(x){return x;}), 'equals() function equality');
    t.assertNot(utils.equals(function(x){return x;}, function(y){return y+2;}), 'equals() function inequality');
    t.assert(utils.equals([{a:1, b:2}, {c:3, d:4}], [{a:1, b:2}, {c:3, d:4}]), 'equals() arrays of objects');
})();

t.comment('fileExt()');
(function() {
    var testCases = {
        'foo.ext':    'ext',
        'FOO.EXT':    'ext',
        'a.ext':      'ext',
        '.ext':       'ext',
        'toto.':      '',
        ' plop.ext ': 'ext'
    };

    for (var testCase in testCases) {
        t.assertEquals(utils.fileExt(testCase), testCases[testCase], 'fileExt() extract file extension');
    }
})();

t.comment('fillBlanks()');
(function() {
    var testCases = {
        'foo':         'foo       ',
        '  foo bar ':  '  foo bar ',
        '  foo bar  ': '  foo bar  '
    };

    for (var testCase in testCases) {
        t.assertEquals(utils.fillBlanks(testCase, 10), testCases[testCase], 'fillBlanks() fills blanks');
    }
})();

t.comment('getPropertyPath()');
(function() {
    var testCases = [
        {
            input:  utils.getPropertyPath({}, 'a.b.c'),
            output: undefined
        },
        {
            input:  utils.getPropertyPath([1, 2, 3], 'a.b.c'),
            output: undefined
        },
        {
            input:  utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b.c'),
            output: 1
        },
        {
            input:  utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b.x'),
            output: undefined
        },
        {
            input:  utils.getPropertyPath({ a: { b: { c: 1 } }, c: 2 }, 'a.b'),
            output: { c: 1 }
        },
        {
            input:  utils.getPropertyPath({ 'a-b': { 'c-d': 1} }, 'a-b.c-d'),
            output: 1
        },
        {
            input:  utils.getPropertyPath({ 'a.b': { 'c.d': 1} }, 'a.b.c.d'),
            output: undefined
        }
    ];
    testCases.forEach(function(testCase) {
        t.assertEquals(testCase.input, testCase.output, 'getPropertyPath() gets a property using a path');
    });
})();

t.comment('isArray()');
(function() {
    t.assertEquals(utils.isArray([]), true, 'isArray() checks for an Array');
    t.assertEquals(utils.isArray({}), false, 'isArray() checks for an Array');
    t.assertEquals(utils.isArray("foo"), false, 'isArray() checks for an Array');
})();

t.comment('isClipRect()');
(function() {
    var testCases = [
        [{},                                              false],
        [{top: 2},                                        false],
        [{top: 2, left: 2, width: 2, height: 2},          true],
        [{top: 2, left: 2, height: 2, width: 2},          true],
        [{top: 2, left: 2, width: 2, height: new Date()}, false]
    ];

    testCases.forEach(function(testCase) {
        t.assertEquals(utils.isClipRect(testCase[0]), testCase[1], 'isClipRect() checks for a ClipRect');
    });
})();

t.comment('isHTTPResource()');
(function() {
    var testCases = [
        [{},                              false],
        [{url: 'file:///var/www/i.html'}, false],
        [{url: 'mailto:plop@plop.com'},   false],
        [{url: 'ftp://ftp.plop.com'},     false],
        [{url: 'HTTP://plop.com/'},       true],
        [{url: 'https://plop.com/'},      true]
    ];

    testCases.forEach(function(testCase) {
        t.assertEquals(utils.isHTTPResource(testCase[0]), testCase[1], 'isHTTPResource() checks for an HTTP resource');
    });
})();

t.comment('isObject()');
(function() {
    t.assertEquals(utils.isObject({}), true, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject([]), true, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject(1), false, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject("1"), false, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject(function(){}), false, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject(new Function('return {};')()), true, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject(require('webpage').create()), true, 'isObject() checks for an Object');
    t.assertEquals(utils.isObject(null), false, 'isObject() checks for an Object');
})();

t.comment('isValidSelector()');
(function() {
    t.assertEquals(utils.isValidSelector({}), false, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector(""), false, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector("a"), true, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector('div#plop form[name="form"] input[type="submit"]'), true, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector(x('//a')), true, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector({
        type: "css",
        path: 'div#plop form[name="form"] input[type="submit"]'
    }), true, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector({
        type: "xpath",
        path: '//a'
    }), true, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector({
        type: "css"
    }), false, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector({
        type: "xpath"
    }), false, 'isValidSelector() checks for a valid selector');
    t.assertEquals(utils.isValidSelector({
        type: "css3",
        path: "a"
    }), false, 'isValidSelector() checks for a valid selector');
})();

t.comment('isWebPage()');
(function() {
    var pageModule = require('webpage');
    t.assertEquals(utils.isWebPage(pageModule), false, 'isWebPage() checks for a WebPage instance');
    t.assertEquals(utils.isWebPage(pageModule.create()), true, 'isWebPage() checks for a WebPage instance');
    t.assertEquals(utils.isWebPage(null), false, 'isWebPage() checks for a WebPage instance');
})();

t.comment('isJsFile()');
(function() {
    var testCases = {
        '':             false,
        'toto.png':     false,
        'plop':         false,
        'gniii.coffee': true,
        'script.js':    true
    };

    for (var testCase in testCases) {
        t.assertEquals(utils.isJsFile(testCase), testCases[testCase], 'isJsFile() checks for js file');
    }
})();

t.comment('mergeObjects()');
(function() {
    var testCases = [
        {
            obj1: {a: 1}, obj2: {b: 2}, merged: {a: 1, b: 2}
        },
        {
            obj1: {}, obj2: {a: 1}, merged: {a: 1}
        },
        {
            obj1: {a: 1}, obj2: {}, merged: {a: 1}
        },
        {
            obj1: {a: 1}, obj2: {a: 2}, merged: {a: 2}
        },
        {
            obj1:   {x: 0, double: function(){return this.x*2;}},
            obj2:   {triple: function(){return this.x*3;}},
            merged: {
                x: 0,
                double: function(){return this.x*2;},
                triple: function(){return this.x*3;}
            }
        }
    ];

    testCases.forEach(function(testCase) {
        t.assertEquals(utils.mergeObjects(testCase.obj1, testCase.obj2), testCase.merged, 'mergeObjects() can merge objects');
    });
})();

t.comment('objectValues()');
(function() {
    t.assertEquals(utils.objectValues({}), [], 'objectValues() can extract object values');
    t.assertEquals(utils.objectValues({a: 1, b: 2}), [1, 2], 'objectValues() can extract object values');
})();

t.comment('unique()');
(function() {
    var testCases = [
        {
            input:  [1,2,3],
            output: [1,2,3]
        },
        {
            input:  [1,2,3,2,1],
            output: [1,2,3]
        },
        {
            input:  ["foo", "bar", "foo"],
            output: ["foo", "bar"]
        },
        {
            input:  [],
            output: []
        }
    ];
    testCases.forEach(function(testCase) {
        t.assertEquals(utils.unique(testCase.input), testCase.output, 'unique() computes unique values of an array');
    });
})();

t.comment('cmpVersion() tests');
(function() {
    t.assertEquals(utils.cmpVersion('1.0.0', '2.0.0'), -1,
        'cmpVersion() can compare version strings');
    t.assertEquals(utils.cmpVersion('1.0.0-DEV', '2.0.0-BOOM'), -1,
        'cmpVersion() can compare version strings');
    t.assertEquals(utils.cmpVersion('1.0.0', '1.1.0'), -1,
        'cmpVersion() can compare version strings');
    t.assertEquals(utils.cmpVersion('1.1.0', '1.0.0'), 1,
        'cmpVersion() can compare version strings');
    t.assertEquals(utils.cmpVersion('0.0.3', '0.0.4'), -1,
        'cmpVersion() can compare version strings');
    t.assertEquals(utils.cmpVersion('0.0.3', '1.0.3'), -1,
        'cmpVersion() can compare version strings');
    t.assertEquals(utils.cmpVersion('0.1', '1.0.3.8'), -1,
        'cmpVersion() can compare version strings');
    t.assertEquals(utils.cmpVersion({major: 1, minor: 2, patch: 3},
                                       {major: 1, minor: 2, patch: 4}), -1,
        'cmpVersion() can compare version objects');
    t.assertEquals(utils.cmpVersion({major: 2, minor: 0, patch: 3},
                                       {major: 1, minor: 0, patch: 4}), 1,
        'cmpVersion() can compare version objects');
    t.assertEquals(utils.cmpVersion({major: 0, minor: 0, patch: 3},
                                       {major: 1, minor: 0, patch: 3}), -1,
        'cmpVersion() can compare version objects');
    t.done();
})();

t.comment('gteVersion() tests');
(function() {
    t.assert(utils.gteVersion('1.1.0', '1.0.0'),
        'gteVersion() checks for a greater or equal version');
    t.assertNot(utils.gteVersion('1.0.0', '1.1.0'),
        'gteVersion() checks for a greater or equal version');
    t.assert(utils.gteVersion({major: 1, minor: 1, patch: 0},
                                 {major: 1, minor: 0, patch: 0}),
        'gteVersion() checks for a greater or equal version');
    t.assertNot(utils.gteVersion({major: 1, minor: 0, patch: 0},
                                    {major: 1, minor: 1, patch: 0}),
        'gteVersion() checks for a greater or equal version');
    t.done();
})();

t.comment('ltVersion() tests');
(function() {
    t.assert(utils.ltVersion('1.0.0', '1.1.0'),
        'ltVersion() checks for a lesser version');
    t.assertNot(utils.ltVersion('1.1.0', '1.0.0'),
        'ltVersion() checks for a lesser version');
    t.assert(utils.ltVersion({major: 1, minor: 0, patch: 0},
                                {major: 1, minor: 1, patch: 0}),
        'ltVersion() checks for a lesser version');
    t.assertNot(utils.ltVersion({major: 1, minor: 1, patch: 0},
                                   {major: 1, minor: 0, patch: 0}),
        'ltVersion() checks for a lesser version');
    t.done();
})();

t.done(130);
<|endoftext|>


<commit_before>// This file configures the development web server
// which supports hot reloading and synchronized testing.

// Require Browsersync along with webpack and middleware for it
import browserSync from 'browser-sync';
// Required for react-router browserHistory
// see https://github.com/BrowserSync/browser-sync/issues/204#issuecomment-102623643
import historyApiFallback from 'connect-history-api-fallback';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import config from '../webpack.config.dev';
import mongoose from 'mongoose'

const bundler = webpack(config);

// Run Browsersync and use middleware for Hot Module Replacement
browserSync({
  port: 3000,
  ui: {
    port: 3001
  },
  server: {
    baseDir: 'src',

    middleware: [
      historyApiFallback(),

      webpackDevMiddleware(bundler, {
        // Dev middleware can't access config, so we provide publicPath
        publicPath: config.output.publicPath,

        // These settings suppress noisy webpack output so only errors are displayed to the console.
        noInfo: false,
        quiet: false,
        stats: {
          assets: false,
          colors: true,
          version: false,
          hash: false,
          timings: false,
          chunks: false,
          chunkModules: false
        },

        // for other settings see
        // http://webpack.github.io/docs/webpack-dev-middleware.html
      }),

      // bundler should be the same as above
      webpackHotMiddleware(bundler)
    ]
  },

  // no need to watch '*.js' here, webpack will take care of it for us,
  // including full page reloads if HMR won't work
  files: [
    'src/*.html'
  ]
});

mongoose.connect('mongodb://localhost/voter');
const connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', ()=>{
    console.log('Database connection open');
});

<commit_msg>changed port 3000 => 3001. API will run on port 3000<commit_after>// This file configures the development web server
// which supports hot reloading and synchronized testing.

// Require Browsersync along with webpack and middleware for it
import browserSync from 'browser-sync';
// Required for react-router browserHistory
// see https://github.com/BrowserSync/browser-sync/issues/204#issuecomment-102623643
import historyApiFallback from 'connect-history-api-fallback';
import webpack from 'webpack';
import webpackDevMiddleware from 'webpack-dev-middleware';
import webpackHotMiddleware from 'webpack-hot-middleware';
import config from '../webpack.config.dev';
import mongoose from 'mongoose'

const bundler = webpack(config);

// Run Browsersync and use middleware for Hot Module Replacement
browserSync({
  port: 3001,
  ui: {
    port: 3002
  },
  server: {
    baseDir: 'src',

    middleware: [
      historyApiFallback(),

      webpackDevMiddleware(bundler, {
        // Dev middleware can't access config, so we provide publicPath
        publicPath: config.output.publicPath,

        // These settings suppress noisy webpack output so only errors are displayed to the console.
        noInfo: false,
        quiet: false,
        stats: {
          assets: false,
          colors: true,
          version: false,
          hash: false,
          timings: false,
          chunks: false,
          chunkModules: false
        },

        // for other settings see
        // http://webpack.github.io/docs/webpack-dev-middleware.html
      }),

      // bundler should be the same as above
      webpackHotMiddleware(bundler)
    ]
  },

  // no need to watch '*.js' here, webpack will take care of it for us,
  // including full page reloads if HMR won't work
  files: [
    'src/*.html'
  ]
});

mongoose.connect('mongodb://localhost/voter');
const connection = mongoose.connection;
connection.on('error', console.error.bind(console, 'connection error:'));
connection.once('open', ()=>{
    console.log('Database connection open');
});

<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Box from '@material-ui/core/Box';
import CodeBlock from '@src/components/CodeBlock';
import LinuxIcon from '@src/assets/icons/linux.inline.svg';
import AppleIcon from '@src/assets/icons/apple.inline.svg';
import WindowsIcon from '@src/assets/icons/windows.inline.svg';

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box p={3}>
          {children}
        </Box>
      )}

  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired,
};

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    backgroundColor: 'transparent',
  },
}));

export default function SimpleTabs() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (

      <AppBar elevation={0} style={{ background: 'transparent', color: 'black', borderBottom: '1px solid #e8e8e8', }} position="static">
        <Tabs value={value} onChange={handleChange} aria-label="operating system tabs">
          <Tab icon={<AppleIcon />} label="macOS" {...a11yProps(0)} style={{ minWidth: "10%", textTransform: 'none' }} />
          <Tab icon={<LinuxIcon />} label="Linux" {...a11yProps(1)} style={{ minWidth: "10%", textTransform: 'none' }} />
          <Tab icon={<WindowsIcon />} label="Windows" {...a11yProps(2)} style={{ minWidth: "10%", textTransform: 'none' }} />
        </Tabs>
      </AppBar>
      <TabPanel value={value} index={0}>
        <CodeBlock>
        {
          '# Install via brew:' +
          '\n' +
          'brew install datawire/blackbird/telepresence' +
          '\n \n' +
          '# OR install manually:' +
          '\n' +
          '# 1. Download the latest binary (~60 MB):' +
          '\n' +
          'sudo curl -fL https://app.getambassador.io/download/tel2/darwin/amd64/latest/telepresence -o /usr/local/bin/telepresence' +
          '\n \n' +
          '# 2. Make the binary executable:' +
          '\n' +
          'sudo chmod a+x /usr/local/bin/telepresence'
        }
        </CodeBlock>
      </TabPanel>
      <TabPanel value={value} index={1}>
        <CodeBlock>
        {
          '# 1. Download the latest binary (~50 MB):' +
          '\n' +
          'sudo curl -fL https://app.getambassador.io/download/tel2/linux/amd64/latest/telepresence -o /usr/local/bin/telepresence' +
          '\n \n' +
          '# 2. Make the binary executable:' +
          '\n' +
          'sudo chmod a+x /usr/local/bin/telepresence'
        }
        </CodeBlock>
      </TabPanel>
      <TabPanel value={value} index={2}>
        <CodeBlock>
        {
          '# Make sure you run the following from Powershell as Administrator' +
          '# 1. Download the latest windows zip containing telepresence.exe and its dependencies (~50 MB):' +
          '\n' +
          'curl -fL https://app.getambassador.io/download/tel2/windows/amd64/latest/telepresence.zip -o telepresence.zip' +
          '\n \n' +
          '# 2. Unzip the zip file to a suitable directory + cleanup zip' +
          '\n' +
          'Expand-Archive -Path telepresence.zip' +
          '\n' +
          'Remove-Item \'telepresence.zip\'' +
          '\n' +
          'cd telepresence' +
          '\n \n' +
          '# 3. Run the install-telepresence.ps1 to install telepresence\'s dependencies. It will install telepresence to' +
          '\n' +
          '# C:\\telepresence by default, but you can specify a custom path $path with -Path $path' +
          '\n' +
          '.\\install-telepresence.ps1' +
          '\n \n' +
          '# 4. Remove the unzipped directory' +
          '\n' +
          'cd ..' +
          '\n' +
          'Remove-Item telepresence' +
          '\n' +
          '# 5. Close your current Powershell and open a new one. Telepresence should now be usable as telepresence.exe'
        }
        </CodeBlock>
      </TabPanel>

  );
}
<commit_msg>Add newline to qs-tabs<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Box from '@material-ui/core/Box';
import CodeBlock from '@src/components/CodeBlock';
import LinuxIcon from '@src/assets/icons/linux.inline.svg';
import AppleIcon from '@src/assets/icons/apple.inline.svg';
import WindowsIcon from '@src/assets/icons/windows.inline.svg';

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box p={3}>
          {children}
        </Box>
      )}

  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired,
};

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    backgroundColor: 'transparent',
  },
}));

export default function SimpleTabs() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (

      <AppBar elevation={0} style={{ background: 'transparent', color: 'black', borderBottom: '1px solid #e8e8e8', }} position="static">
        <Tabs value={value} onChange={handleChange} aria-label="operating system tabs">
          <Tab icon={<AppleIcon />} label="macOS" {...a11yProps(0)} style={{ minWidth: "10%", textTransform: 'none' }} />
          <Tab icon={<LinuxIcon />} label="Linux" {...a11yProps(1)} style={{ minWidth: "10%", textTransform: 'none' }} />
          <Tab icon={<WindowsIcon />} label="Windows" {...a11yProps(2)} style={{ minWidth: "10%", textTransform: 'none' }} />
        </Tabs>
      </AppBar>
      <TabPanel value={value} index={0}>
        <CodeBlock>
        {
          '# Install via brew:' +
          '\n' +
          'brew install datawire/blackbird/telepresence' +
          '\n \n' +
          '# OR install manually:' +
          '\n' +
          '# 1. Download the latest binary (~60 MB):' +
          '\n' +
          'sudo curl -fL https://app.getambassador.io/download/tel2/darwin/amd64/latest/telepresence -o /usr/local/bin/telepresence' +
          '\n \n' +
          '# 2. Make the binary executable:' +
          '\n' +
          'sudo chmod a+x /usr/local/bin/telepresence'
        }
        </CodeBlock>
      </TabPanel>
      <TabPanel value={value} index={1}>
        <CodeBlock>
        {
          '# 1. Download the latest binary (~50 MB):' +
          '\n' +
          'sudo curl -fL https://app.getambassador.io/download/tel2/linux/amd64/latest/telepresence -o /usr/local/bin/telepresence' +
          '\n \n' +
          '# 2. Make the binary executable:' +
          '\n' +
          'sudo chmod a+x /usr/local/bin/telepresence'
        }
        </CodeBlock>
      </TabPanel>
      <TabPanel value={value} index={2}>
        <CodeBlock>
        {
          '# Make sure you run the following from Powershell as Administrator' +
          '\n' +
          '# 1. Download the latest windows zip containing telepresence.exe and its dependencies (~50 MB):' +
          '\n' +
          'curl -fL https://app.getambassador.io/download/tel2/windows/amd64/latest/telepresence.zip -o telepresence.zip' +
          '\n \n' +
          '# 2. Unzip the zip file to a suitable directory + cleanup zip' +
          '\n' +
          'Expand-Archive -Path telepresence.zip' +
          '\n' +
          'Remove-Item \'telepresence.zip\'' +
          '\n' +
          'cd telepresence' +
          '\n \n' +
          '# 3. Run the install-telepresence.ps1 to install telepresence\'s dependencies. It will install telepresence to' +
          '\n' +
          '# C:\\telepresence by default, but you can specify a custom path $path with -Path $path' +
          '\n' +
          '.\\install-telepresence.ps1' +
          '\n \n' +
          '# 4. Remove the unzipped directory' +
          '\n' +
          'cd ..' +
          '\n' +
          'Remove-Item telepresence' +
          '\n' +
          '# 5. Close your current Powershell and open a new one. Telepresence should now be usable as telepresence.exe'
        }
        </CodeBlock>
      </TabPanel>

  );
}
<|endoftext|>


<commit_before>"use strict";
define(['app'], function (app) {
	app.register.directive('oDropdownFilter',['$rootScope','AtomicPath','Atomic',function ($rootScope,aPath,atomic) {
		const  DEFAULTS = {entryLimit:10,showPeriod:true,showSectionUI:'search'};
		return {
			restrict: 'E',
			scope:{
				Active:'=ngModel',
				showSem:'=?',
				showPeriod:'=?',
				showYearLevel:'=?',
				showSection:'=?',
				showSectionUI:'@?',
				update:'&',
				dropdownPreview:'@?'
			},
			replace:true,
			transclude:true,
			templateUrl:function(elem,attr){
				return aPath.url('/view/organism/oDropdownFilter.html');
			},
			link: function($scope,elem, attrs,ctrl,transclude) {
				transclude(function(clone){
					$scope.isOverloaded = clone.length>1;
				});
			},
			bindToController:true,
			controllerAs:'oFilterDropdownCtrl',
			controller:function($scope){
				$scope.oFilterDropdownCtrl.showSectionUI = $scope.showSectionUI || DEFAULTS.showSectionUI;
				$scope.oFilterDropdownCtrl.showPeriod = $scope.showPeriod || DEFAULTS.showPeriod;
				$scope.SectSearchObj = ['id','name','alias','department_id','program_id','year_level'];
				function bindData(){
					$scope._APP =  $rootScope._APP;
					$scope._APP.Departments =  atomic.Departments;
					$scope._APP.Sections =  atomic.Sections;

					$scope._APP.YearLevels =  atomic.YearLevels;
					var active = {
									dept:atomic.ActiveDept,
									sy:atomic.ActiveSY,
									sem:atomic.SelectedSem,
									period:atomic.SelectedPeriod
								};
					if(!$scope.oFilterDropdownCtrl.showPeriod)
						delete active.period;

					if(active.period){
						if(active.period.id>4)
							active.period.id = active.period.id/10;
						active.esp =  parseFloat(active.sy+'.'+active.period.id);
					}
					$scope.oFilterDropdownCtrl.Active = active;
				}

				if(atomic.ready(bindData).fuse())
					$rootScope.$on('$routeChangeSuccess',bindData);

				$scope.$watch("oFilterDropdownCtrl.Active",buildActive);

				function buildActive(val){
					var active =  val||{dept:null,sy:null,sem:null,period:null,esp:null};
						$scope.ActiveDept =  active.dept;
						$scope.ActiveSY =  active.sy;
						$scope.ActiveESP =  active.esp;
						if($scope.oFilterDropdownCtrl.showPeriod)
							$scope.SelectedPeriod =  active.period;
						$scope.SelectedSemester =  active.sem;
					$scope.currentPage = 1;
					renderPreview(active);
				}
				$scope.toggleText='More';

				$scope.setActiveSY = function(sy){
					$scope.ActiveSY =  sy;
				}
				$scope.setSelectedSemester = function(sem){
					$scope.SelectedSemester =  sem;

				}
				$scope.setSelectedPeriod = function(period){
					$scope.SelectedPeriod = period;
				}
				$scope.setActiveDept = function(dept){
					$scope.ActiveDept = dept;
				}

				$scope.setActiveYearLevel = function(level){
					if($scope.ActiveYearLevel == level) level = null;
					$scope.ActiveYearLevel =  level;
					$scope.currentPage = 1;
					$scope.sanaAll = false;
					var entryLimit = $scope.entryLimit = DEFAULTS.entryLimit;
					var sections = $scope._APP.Sections;
					var yearlevel = $scope.ActiveYearLevel;
					var activeSections = [];
					for(var i in sections){
						var section = sections[i];
						if(section.year_level_id==yearlevel.id){
							activeSections.push(section);
						}
					}
					$scope.ActiveSections = activeSections;
					$scope.ActiveSection = null;
					$scope.lastPage =  Math.ceil(activeSections.length/entryLimit);
				}
				$scope.toggleAll = function(){
					$scope.sanaAll = !$scope.sanaAll;
					$scope.entryLimit = $scope.sanaAll?null: DEFAULTS.entryLimit;
					$scope.currentPage=1;

				}
				$scope.setCurrentPage = function(change){
					$scope.currentPage += change;
				}
				$scope.$watch('oFilterDropdownCtrl.SearchSection',function(section){
					if(section){
						$scope.setActiveSection(section);
					}
				});
				$scope.setActiveSection = function(sect){

					if($scope.ActiveSection ==sect) sect = null;
					if(sect=='all'){

						var sections = $scope.ActiveSections;
						var ids = [];
						for(var i in sections){
							var section =  sections[i];
							ids.push(section.id);
						}
						var allSections = angular.copy(sections[0]);
						allSections.id = 'all';
						allSections.ids = ids;
						allSections.program_id = null;
						allSections.name = "All "+allSections.year_level;
						allSections.alias = allSections.name;
						allSections.description = allSections.name;

						if($scope.ActiveSection)
							if($scope.ActiveSection.id=='all')
								return $scope.ActiveSection=null;
						$scope.ActiveSection = allSections;
					}else{
						$scope.ActiveSection =  sect;
					}
				}
				$scope.toggleOtherSY = function(){
					$scope.toggleDropdown = !$scope.toggleDropdown;
					$scope.toggleText = $scope.toggleText == 'More'?'Less':'More';
				}

				$scope.closeFilter = function(){
					$scope.openDropdown = false;
				}
				$scope.confirmFilter = function(){
					var active =  {dept:$scope.ActiveDept,
									sy:$scope.ActiveSY,
									sem:$scope.SelectedSemester,
									period:$scope.SelectedPeriod

								};
					if(!$scope.oFilterDropdownCtrl.showPeriod)
						delete active.period;
					if(active.period){
						if(active.period.id>4)
							active.period.id = active.period.id/10;
						active.esp =  parseFloat(active.sy+'.'+active.period.id);
					}
					if($scope.oFilterDropdownCtrl.showSection){
						active.section =  $scope.ActiveSection;
					}
					if($scope.oFilterDropdownCtrl.showYearLevel){
						active.year_level =  $scope.ActiveYearLevel;
					}
					$scope.oFilterDropdownCtrl.Active = active;
					$scope.openDropdown = false;
					renderPreview(active);
				}
				function renderPreview(active){

					if($scope.oFilterDropdownCtrl.dropdownPreview) return;
					var preview = [];
					if(active.sy)
						preview .push("SY "+ active.sy + " - "+ (active.sy+1));
					if(active.sem)
						preview.push(active.sem.alias.full);
					if(active.period)
						if(active.period.alias.full!=preview[1])
							preview.push(active.period.alias.full);

					active.section =  active.section ||{};
					if( active.year_level)
						preview.push(active.year_level.description);
					if(active.section.id=='all')
						preview.pop();

					if(active.section.id)
							preview.push(active.section.alias);
					$scope.oFilterDropdownCtrl.preview = preview.join(" | ");

				}
				$scope.$watch('oFilterDropdownCtrl.dropdownPreview',function(value){
					$scope.oFilterDropdownCtrl.preview = value;
				});
				$scope.$watch('oFilterDropdownCtrl.preview',function(value){
					var active = $scope.oFilterDropdownCtrl.Active;
					if(value==undefined && active){
						renderPreview(active);
					}
				});

			}
		}
	}]);
	app.register.filter('startFrom', function () {
		return function (input, start) {
			if (input) {
				start = +start;
				return input.slice(start);
			}
			return [];
		};
	});
	app.register.directive('oFilterDropdown',[function () {
		return {
			restrict: 'E',
			replace:true,
			template:'
ERROR
',
		}
	}]);
});<commit_msg>Implement liveUpdate  and sem switching<commit_after>"use strict";
define(['app'], function (app) {
	app.register.directive('oDropdownFilter',['$rootScope','AtomicPath','Atomic',function ($rootScope,aPath,atomic) {
		const  DEFAULTS = {entryLimit:10,showPeriod:true,showSectionUI:'search'};
		return {
			restrict: 'E',
			scope:{
				Active:'=ngModel',
				showSem:'=?',
				showPeriod:'=?',
				showYearLevel:'=?',
				showSection:'=?',
				showSectionUI:'@?',
				dropdownPreview:'@?',
				liveUpdate:'=?',

			},
			replace:true,
			transclude:true,
			templateUrl:function(elem,attr){
				return aPath.url('/view/organism/oDropdownFilter.html');
			},
			link: function($scope,elem, attrs,ctrl,transclude) {
				transclude(function(clone){
					$scope.isOverloaded = clone.length>1;
				});
			},
			bindToController:true,
			controllerAs:'oFilterDropdownCtrl',
			controller:function($scope){
				$scope.oFilterDropdownCtrl.showSectionUI = $scope.showSectionUI || DEFAULTS.showSectionUI;
				$scope.oFilterDropdownCtrl.showPeriod = $scope.showPeriod || DEFAULTS.showPeriod;
				$scope.SectSearchObj = ['id','name','alias','department_id','program_id','year_level'];
				function bindData(){
					$scope._APP =  $rootScope._APP;
					$scope._APP.Departments =  atomic.Departments;
					$scope._APP.Sections =  atomic.Sections;

					$scope._APP.YearLevels =  atomic.YearLevels;
					var active = {
									dept:atomic.ActiveDept,
									sy:atomic.ActiveSY,
									sem:atomic.SelectedSem,
									period:atomic.SelectedPeriod
								};
					if(!$scope.oFilterDropdownCtrl.showPeriod)
						delete active.period;

					if(active.period){
						if(active.period.id>4)
							active.period.id = active.period.id/10;
						active.esp =  parseFloat(active.sy+'.'+active.period.id);
					}
					$scope.oFilterDropdownCtrl.Active = active;
				}

				if(atomic.ready(bindData).fuse())
					$rootScope.$on('$routeChangeSuccess',bindData);

				$scope.$watch("oFilterDropdownCtrl.Active",buildActive);

				function buildActive(val){
					var active =  val||{dept:null,sy:null,sem:null,period:null,esp:null};
						$scope.ActiveDept =  active.dept;
						$scope.ActiveSY =  active.sy;
						$scope.ActiveESP =  active.esp;
						if($scope.oFilterDropdownCtrl.showPeriod)
							$scope.SelectedPeriod =  active.period;
						$scope.SelectedSemester =  active.sem;
					$scope.currentPage = 1;
					renderPreview(active);
				}
				$scope.toggleText='More';

				$scope.setActiveSY = function(sy){
					$scope.ActiveSY =  sy;
				}
				$scope.setSelectedSemester = function(sem){
					$scope.SelectedSemester =  sem;
					//Fix selected period when switching between semester
					var flag =  sem.id==25?-2:2;
					var index = ($scope.SelectedPeriod.id-1)+flag;
					$scope.setSelectedPeriod(atomic.Periods[index])

				}
				$scope.setSelectedPeriod = function(period){
					$scope.SelectedPeriod = period;
				}
				$scope.setActiveDept = function(dept){
					$scope.ActiveDept = dept;
				}

				$scope.setActiveYearLevel = function(level){
					if($scope.ActiveYearLevel == level) level = null;
					$scope.ActiveYearLevel =  level;
					$scope.currentPage = 1;
					$scope.sanaAll = false;
					var entryLimit = $scope.entryLimit = DEFAULTS.entryLimit;
					var sections = $scope._APP.Sections;
					var yearlevel = $scope.ActiveYearLevel;
					var activeSections = [];
					for(var i in sections){
						var section = sections[i];
						if(section.year_level_id==yearlevel.id){
							activeSections.push(section);
						}
					}
					$scope.ActiveSections = activeSections;
					$scope.ActiveSection = null;
					$scope.lastPage =  Math.ceil(activeSections.length/entryLimit);
				}
				$scope.toggleAll = function(){
					$scope.sanaAll = !$scope.sanaAll;
					$scope.entryLimit = $scope.sanaAll?null: DEFAULTS.entryLimit;
					$scope.currentPage=1;

				}
				$scope.setCurrentPage = function(change){
					$scope.currentPage += change;
				}
				$scope.$watch('oFilterDropdownCtrl.SearchSection',function(section){
					if(section){
						$scope.setActiveSection(section);
					}
				});
				$scope.setActiveSection = function(sect){

					if($scope.ActiveSection ==sect) sect = null;
					if(sect=='all'){

						var sections = $scope.ActiveSections;
						var ids = [];
						for(var i in sections){
							var section =  sections[i];
							ids.push(section.id);
						}
						var allSections = angular.copy(sections[0]);
						allSections.id = 'all';
						allSections.ids = ids;
						allSections.program_id = null;
						allSections.name = "All "+allSections.year_level;
						allSections.alias = allSections.name;
						allSections.description = allSections.name;

						if($scope.ActiveSection)
							if($scope.ActiveSection.id=='all')
								return $scope.ActiveSection=null;
						$scope.ActiveSection = allSections;
					}else{
						$scope.ActiveSection =  sect;
					}
				}
				$scope.toggleOtherSY = function(){
					$scope.toggleDropdown = !$scope.toggleDropdown;
					$scope.toggleText = $scope.toggleText == 'More'?'Less':'More';
				}

				$scope.closeFilter = function(){
					$scope.openDropdown = false;
				}
				$scope.confirmFilter = function(){
					var active = mutateActive();
					$scope.oFilterDropdownCtrl.Active = active;
					$scope.openDropdown = false;
					renderPreview(active);
				}
				$scope.$watchGroup(['ActiveDept','ActiveSY',
									'SelectedSemester','SelectedPeriod',
									'ActiveSection','ActiveYearLevel'],function(){
							 $scope.oFilterDropdownCtrl.liveUpdate =  mutateActive();
				});
				function mutateActive(){
					var active =  {dept:$scope.ActiveDept,
									sy:$scope.ActiveSY,
									sem:$scope.SelectedSemester,
									period:$scope.SelectedPeriod

								};
					if(!$scope.oFilterDropdownCtrl.showPeriod)
						delete active.period;
					if(active.period){
						if(active.period.id>4)
							active.period.id = active.period.id/10;
						active.esp =  parseFloat(active.sy+'.'+active.period.id);
					}
					if($scope.oFilterDropdownCtrl.showSection){
						active.section =  $scope.ActiveSection;
					}
					if($scope.oFilterDropdownCtrl.showYearLevel){
						active.year_level =  $scope.ActiveYearLevel;
					}
					return active;
				}
				function renderPreview(active){

					if($scope.oFilterDropdownCtrl.dropdownPreview) return;
					var preview = [];
					if(active.sy)
						preview .push("SY "+ active.sy + " - "+ (active.sy+1));
					if(active.sem)
						preview.push(active.sem.alias.full);
					if(active.period)
						if(active.period.alias.full!=preview[1])
							preview.push(active.period.alias.full);

					active.section =  active.section ||{};
					if( active.year_level)
						preview.push(active.year_level.description);
					if(active.section.id=='all')
						preview.pop();

					if(active.section.id)
							preview.push(active.section.alias);
					$scope.oFilterDropdownCtrl.preview = preview.join(" | ");

				}
				$scope.$watch('oFilterDropdownCtrl.dropdownPreview',function(value){
					$scope.oFilterDropdownCtrl.preview = value;
				});
				$scope.$watch('oFilterDropdownCtrl.preview',function(value){
					var active = $scope.oFilterDropdownCtrl.Active;
					if(value==undefined && active){
						renderPreview(active);
					}
				});

			}
		}
	}]);
	app.register.filter('startFrom', function () {
		return function (input, start) {
			if (input) {
				start = +start;
				return input.slice(start);
			}
			return [];
		};
	});
	app.register.directive('oFilterDropdown',[function () {
		return {
			restrict: 'E',
			replace:true,
			template:'
ERROR
',
		}
	}]);
});<|endoftext|>


<commit_before>import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Box from '@material-ui/core/Box';
import CodeBlock from '@src/components/CodeBlock';
import LinuxIcon from '@src/assets/icons/linux.inline.svg';
import AppleIcon from '@src/assets/icons/apple.inline.svg';
import WindowsIcon from '@src/assets/icons/windows.inline.svg';

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box p={3}>
          {children}
        </Box>
      )}

  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired,
};

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    backgroundColor: 'transparent',
  },
}));

export default function SimpleTabs() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (

      <AppBar elevation={0} style={{ background: 'transparent', color: 'black', borderBottom: '1px solid #e8e8e8', }} position="static">
        <Tabs value={value} onChange={handleChange} aria-label="operating system tabs">
          <Tab icon={<AppleIcon />} label="macOS" {...a11yProps(0)} style={{ minWidth: "10%", textTransform: 'none' }} />
          <Tab icon={<LinuxIcon />} label="Linux" {...a11yProps(1)} style={{ minWidth: "10%", textTransform: 'none' }} />
          <Tab icon={<WindowsIcon />} label="Windows" {...a11yProps(2)} style={{ minWidth: "10%", textTransform: 'none' }} />
        </Tabs>
      </AppBar>
      <TabPanel value={value} index={0}>
        <CodeBlock>
        {
          '# Install via brew:' +
          '\n' +
          'brew install datawire/blackbird/telepresence' +
          '\n \n' +
          '# OR install manually:' +
          '\n' +
          '# 1. Download the latest binary (~60 MB):' +
          '\n' +
          'sudo curl -fL https://app.getambassador.io/download/tel2/darwin/amd64/latest/telepresence -o /usr/local/bin/telepresence' +
          '\n \n' +
          '# 2. Make the binary executable:' +
          '\n' +
          'sudo chmod a+x /usr/local/bin/telepresence'
        }
        </CodeBlock>
      </TabPanel>
      <TabPanel value={value} index={1}>
        <CodeBlock>
        {
          '# 1. Download the latest binary (~50 MB):' +
          '\n' +
          'sudo curl -fL https://app.getambassador.io/download/tel2/linux/amd64/latest/telepresence -o /usr/local/bin/telepresence' +
          '\n \n' +
          '# 2. Make the binary executable:' +
          '\n' +
          'sudo chmod a+x /usr/local/bin/telepresence'
        }
        </CodeBlock>
      </TabPanel>
      <TabPanel value={value} index={2}>
        <CodeBlock>
        {
          '# Windows is in Developer Preview, here is how you can install it:' +
          '\n' +
          '# Make sure you run the following from Powershell as Administrator' +
          '\n' +
          '# 1. Download the latest windows zip containing telepresence.exe and its dependencies (~50 MB):' +
          '\n' +
          'curl -fL https://app.getambassador.io/download/tel2/windows/amd64/latest/telepresence.zip -o telepresence.zip' +
          '\n \n' +
          '# 2. Unzip the zip file to a suitable directory + cleanup zip' +
          '\n' +
          'Expand-Archive -Path telepresence.zip' +
          '\n' +
          'Remove-Item \'telepresence.zip\'' +
          '\n' +
          'cd telepresence' +
          '\n \n' +
          '# 3. Run the install-telepresence.ps1 to install telepresence\'s dependencies. It will install telepresence to' +
          '\n' +
          '# C:\\telepresence by default, but you can specify a custom path $path with -Path $path' +
          '\n' +
          '.\\install-telepresence.ps1' +
          '\n \n' +
          '# 4. Remove the unzipped directory' +
          '\n' +
          'cd ..' +
          '\n' +
          'Remove-Item telepresence' +
          '\n' +
          '# 5. Close your current Powershell and open a new one. Telepresence should now be usable as telepresence.exe'
        }
        </CodeBlock>
      </TabPanel>

  );
}
<commit_msg>Update windows instructions with ExecutionPolicy<commit_after>import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles } from '@material-ui/core/styles';
import AppBar from '@material-ui/core/AppBar';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import Box from '@material-ui/core/Box';
import CodeBlock from '@src/components/CodeBlock';
import LinuxIcon from '@src/assets/icons/linux.inline.svg';
import AppleIcon from '@src/assets/icons/apple.inline.svg';
import WindowsIcon from '@src/assets/icons/windows.inline.svg';

function TabPanel(props) {
  const { children, value, index, ...other } = props;

  return (
    <div
      role="tabpanel"
      hidden={value !== index}
      id={`simple-tabpanel-${index}`}
      aria-labelledby={`simple-tab-${index}`}
      {...other}
    >
      {value === index && (
        <Box p={3}>
          {children}
        </Box>
      )}

  );
}

TabPanel.propTypes = {
  children: PropTypes.node,
  index: PropTypes.any.isRequired,
  value: PropTypes.any.isRequired,
};

function a11yProps(index) {
  return {
    id: `simple-tab-${index}`,
    'aria-controls': `simple-tabpanel-${index}`,
  };
}

const useStyles = makeStyles((theme) => ({
  root: {
    flexGrow: 1,
    backgroundColor: 'transparent',
  },
}));

export default function SimpleTabs() {
  const classes = useStyles();
  const [value, setValue] = React.useState(0);

  const handleChange = (event, newValue) => {
    setValue(newValue);
  };

  return (

      <AppBar elevation={0} style={{ background: 'transparent', color: 'black', borderBottom: '1px solid #e8e8e8', }} position="static">
        <Tabs value={value} onChange={handleChange} aria-label="operating system tabs">
          <Tab icon={<AppleIcon />} label="macOS" {...a11yProps(0)} style={{ minWidth: "10%", textTransform: 'none' }} />
          <Tab icon={<LinuxIcon />} label="Linux" {...a11yProps(1)} style={{ minWidth: "10%", textTransform: 'none' }} />
          <Tab icon={<WindowsIcon />} label="Windows" {...a11yProps(2)} style={{ minWidth: "10%", textTransform: 'none' }} />
        </Tabs>
      </AppBar>
      <TabPanel value={value} index={0}>
        <CodeBlock>
        {
          '# Install via brew:' +
          '\n' +
          'brew install datawire/blackbird/telepresence' +
          '\n \n' +
          '# OR install manually:' +
          '\n' +
          '# 1. Download the latest binary (~60 MB):' +
          '\n' +
          'sudo curl -fL https://app.getambassador.io/download/tel2/darwin/amd64/latest/telepresence -o /usr/local/bin/telepresence' +
          '\n \n' +
          '# 2. Make the binary executable:' +
          '\n' +
          'sudo chmod a+x /usr/local/bin/telepresence'
        }
        </CodeBlock>
      </TabPanel>
      <TabPanel value={value} index={1}>
        <CodeBlock>
        {
          '# 1. Download the latest binary (~50 MB):' +
          '\n' +
          'sudo curl -fL https://app.getambassador.io/download/tel2/linux/amd64/latest/telepresence -o /usr/local/bin/telepresence' +
          '\n \n' +
          '# 2. Make the binary executable:' +
          '\n' +
          'sudo chmod a+x /usr/local/bin/telepresence'
        }
        </CodeBlock>
      </TabPanel>
      <TabPanel value={value} index={2}>
        <CodeBlock>
        {
          '# Windows is in Developer Preview, here is how you can install it:' +
          '\n' +
          '# Make sure you run the following from Powershell as Administrator' +
          '\n' +
          '# 1. Download the latest windows zip containing telepresence.exe and its dependencies (~50 MB):' +
          '\n' +
          'curl -fL https://app.getambassador.io/download/tel2/windows/amd64/latest/telepresence.zip -o telepresence.zip' +
          '\n \n' +
          '# 2. Unzip the zip file to a suitable directory + cleanup zip' +
          '\n' +
          'Expand-Archive -Path telepresence.zip' +
          '\n' +
          'Remove-Item \'telepresence.zip\'' +
          '\n' +
          'cd telepresence' +
          '\n \n' +
          '# 3. Run the install-telepresence.ps1 to install telepresence\'s dependencies. It will install telepresence to' +
          '\n' +
          '# C:\\telepresence by default, but you can specify a custom path $path with -Path $path' +
          '\n' +
          'Set-ExecutionPolicy Bypass -Scope Process' +
          '\n' +
          '.\\install-telepresence.ps1' +
          '\n \n' +
          '# 4. Remove the unzipped directory' +
          '\n' +
          'cd ..' +
          '\n' +
          'Remove-Item telepresence' +
          '\n' +
          '# 5. Close your current Powershell and open a new one. Telepresence should now be usable as telepresence.exe'
        }
        </CodeBlock>
      </TabPanel>

  );
}
<|endoftext|>


<commit_before>var server = require('./server')
  , events = require('events')
  , stream = require('stream')
  , assert = require('assert')
  , request = require('../index')
  ;

var s = server.createServer();
var expectedBody = "waited";
var remainingTests = 5;

s.listen(s.port, function () {
  // Request that waits for 200ms
  s.on('/timeout', function (req, resp) {
    setTimeout(function(){
      resp.writeHead(200, {'content-type':'text/plain'})
      resp.write(expectedBody)
      resp.end()
    }, 200);
  });

  // Scenario that should timeout
  var shouldTimeout = {
    url: s.url + "/timeout",
    timeout:100
  }

  request(shouldTimeout, function (err, resp, body) {
    assert.equal(err.code, "ETIMEDOUT");
    checkDone();
  })

  // Scenario that shouldn't timeout
  var shouldntTimeout = {
    url: s.url + "/timeout",
    timeout:300
  }

  request(shouldntTimeout, function (err, resp, body) {
    assert.equal(err, null);
    assert.equal(expectedBody, body)
    checkDone();
  })

  // Scenario with no timeout set, so shouldn't timeout
  var noTimeout = {
    url: s.url + "/timeout"
  }

  request(noTimeout, function (err, resp, body) {
    assert.equal(err);
    assert.equal(expectedBody, body)
    checkDone();
  })

  // Scenario with a negative timeout value, should be treated a zero or the minimum delay
  var negativeTimeout = {
    url: s.url + "/timeout",
    timeout:-1000
  }

  request(negativeTimeout, function (err, resp, body) {
    assert.equal(err.code, "ETIMEDOUT");
    checkDone();
  })

  // Scenario with a float timeout value, should be rounded by setTimeout anyway
  var floatTimeout = {
    url: s.url + "/timeout",
    timeout: 100.76
  }

  request(floatTimeout, function (err, resp, body) {
    assert.equal(err.code, "ETIMEDOUT");
    checkDone();
  })

  function checkDone() {
    if(--remainingTests == 0) {
      s.close();
      console.log("All tests passed.");
    }
  }
})

<commit_msg>Test case for #304.<commit_after>var server = require('./server')
  , events = require('events')
  , stream = require('stream')
  , assert = require('assert')
  , request = require('../index')
  ;

var s = server.createServer();
var expectedBody = "waited";
var remainingTests = 6;

s.listen(s.port, function () {
  // Request that waits for 200ms
  s.on('/timeout', function (req, resp) {
    setTimeout(function(){
      resp.writeHead(200, {'content-type':'text/plain'})
      resp.write(expectedBody)
      resp.end()
    }, 200);
  });

  // Scenario that should timeout
  var shouldTimeout = {
    url: s.url + "/timeout",
    timeout:100
  }

  request(shouldTimeout, function (err, resp, body) {
    assert.equal(err.code, "ETIMEDOUT");
    checkDone();
  })

  var shouldTimeoutWithEvents = {
    url: s.url + "/timeout",
    timeout:100
  }

  request(shouldTimeoutWithEvents)
    .on('error', function (err) {
      assert.equal(err.code, "ETIMEDOUT");
      checkDone();
    })

  // Scenario that shouldn't timeout
  var shouldntTimeout = {
    url: s.url + "/timeout",
    timeout:300
  }

  request(shouldntTimeout, function (err, resp, body) {
    assert.equal(err, null);
    assert.equal(expectedBody, body)
    checkDone();
  })

  // Scenario with no timeout set, so shouldn't timeout
  var noTimeout = {
    url: s.url + "/timeout"
  }

  request(noTimeout, function (err, resp, body) {
    assert.equal(err);
    assert.equal(expectedBody, body)
    checkDone();
  })

  // Scenario with a negative timeout value, should be treated a zero or the minimum delay
  var negativeTimeout = {
    url: s.url + "/timeout",
    timeout:-1000
  }

  request(negativeTimeout, function (err, resp, body) {
    assert.equal(err.code, "ETIMEDOUT");
    checkDone();
  })

  // Scenario with a float timeout value, should be rounded by setTimeout anyway
  var floatTimeout = {
    url: s.url + "/timeout",
    timeout: 100.76
  }

  request(floatTimeout, function (err, resp, body) {
    assert.equal(err.code, "ETIMEDOUT");
    checkDone();
  })

  function checkDone() {
    if(--remainingTests == 0) {
      s.close();
      console.log("All tests passed.");
    }
  }
})

<|endoftext|>


<commit_before>'use strict';
let co     = require('co');
let Heroku = require('heroku-client');

function handleErr(err) {
  if (err.body) {
    if (err.body.message) {
      console.error("\n !  " + err.body.message);
    } else if (err.body.error) {
      console.error("\n !  " + err.body.error);
    }
  } else {
    console.error(err.stack);
  }
  process.exit(1);
}

module.exports = function command (fn) {
  return function (context) {
    co(function *() {
      let heroku;
      if (context.auth.password) {
        heroku = new Heroku({token: context.auth.password});
      }
      yield fn(context, heroku);
    }).catch(handleErr);
  };
};
<commit_msg>change into cwd during command setup<commit_after>'use strict';
let co     = require('co');
let Heroku = require('heroku-client');

function handleErr(err) {
  if (err.body) {
    if (err.body.message) {
      console.error("\n !  " + err.body.message);
    } else if (err.body.error) {
      console.error("\n !  " + err.body.error);
    }
  } else {
    console.error(err.stack);
  }
  process.exit(1);
}

module.exports = function command (fn) {
  return function (context) {
    process.chdir(context.cwd);
    co(function *() {
      let heroku;
      if (context.auth.password) {
        heroku = new Heroku({token: context.auth.password});
      }
      yield fn(context, heroku);
    }).catch(handleErr);
  };
};
<|endoftext|>


<commit_before>/*
 * Copyright 2005-2012 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Processes a response that has been returned from an Ajax call
 *
 * @param contents - the response contents (or body)
 */
function KradResponse(contents) {
    this.responseContents = contents;
}

KradResponse.prototype = {
    // full response contents
    responseContents: null,

    // maps return types to handler function names
    handlerMapping: {"update-page": "updatePageHandler", "update-component": "updateComponentHandler",
        "update-view": "updateViewHandler", "redirect": "redirectHandler",
        "display-lightbox": "displayLightBoxHandler"},

    // invoked to process the response contents by invoking necessary handlers
    processResponse: function () {
        var responseFn = this;

        // iterate over returned contents divs and invoke handler
        jQuery(this.responseContents).children().each(function () {
            var div = jQuery(this);

            // get the return type sent by the server
            var returnType = div.data("returntype");

            // find the handler function from the mapping
            var functionName = responseFn.handlerMapping[returnType];
            var handlerFunc = responseFn[functionName];

            // invoke the handler function
            if (handlerFunc) {
                handlerFunc(div, div.data());
            }
        });
    },

    // finds the page content in the returned content and updates the page, then processes breadcrumbs and hidden
    // scripts. While processing, the page contents are hidden
    updatePageHandler: function (content, dataAttr) {
        var page = jQuery("#page_update", content);

        // TODO: should this be hiding page or pageInLayout?
        page.hide();

        // give a selector that will avoid the temporary iframe used to hold ajax responses by the jquery form plugin
        var pageInLayout = "#" + kradVariables.VIEW_CONTENT_HEADER_CLASS + " > #" +
                kradVariables.PAGE_CONTENT_HEADER_CLASS;
        hideBubblePopups(pageInLayout);

        // update page contents from response
        jQuery(pageInLayout).empty().append(page.find(">*"));

        // process breadcrumbs
        setPageBreadcrumb();

        pageValidatorReady = false;
        runHiddenScripts(jQuery(pageInLayout).attr("id"), false, true);

        jQuery(pageInLayout).show();
    },

    // retrieves the component with the matching id from the server and replaces a matching
    // _refreshWrapper marker span with the same id with the result.  In addition, if the result contains a label
    // and a displayWith marker span has a matching id, that span will be replaced with the label content
    // and removed from the component.  This allows for label and component content separation on fields
    updateComponentHandler: function (content, dataAttr) {
        var id = dataAttr.updatecomponentid;
        var elementToBlock = jQuery("#" + id);

        hideBubblePopups(elementToBlock);

        var component = jQuery("#" + id + "_update", content);

        var displayWithId = id;

        // special label handling, if any
        var theLabel = jQuery("#" + displayWithId + "_label_span", component);
        if (jQuery(".displayWith-" + displayWithId).length && theLabel.length) {
            theLabel.addClass("displayWith-" + displayWithId);
            jQuery("span.displayWith-" + displayWithId).replaceWith(theLabel);
            component.remove("#" + displayWithId + "_label_span");
        }

        elementToBlock.unblock({onUnblock: function () {
            jQuery(component).find("#" + id).addClass(kradVariables.PROGRESSIVE_DISCLOSURE_HIGHLIGHT_CLASS);

            // remove old stuff
            if (jQuery("#" + id + "_errors").length) {
                jQuery("#" + id + "_errors").remove();
            }

            jQuery("input[data-for='" + id + "']").each(function () {
                jQuery(this).remove();
            });

            // replace component
            if (jQuery("#" + id).length) {
                jQuery("#" + id).replaceWith(component.html());
            }

            if (jQuery("#" + id).parent().is("td")) {
                jQuery("#" + id).parent().show();
            }

            // runs scripts on the span or div with id
            runHiddenScripts(id);

            // lightbox specific processing
            if (jQuery('#renderedInLightBox').val() == 'true') {
                jQuery("#" + id).css('display', 'none');
            }

            var newComponent = jQuery("#" + id);
            newComponent.animate({backgroundColor:"transparent"}, 6000);
            jQuery(component).find("#" + id).animate({backgroundColor:"transparent"}, 6000);
        }
        });

        var displayWithLabel = jQuery(".displayWith-" + displayWithId);
        displayWithLabel.show();
        if (displayWithLabel.parent().is("td") || displayWithLabel.parent().is("th")) {
            displayWithLabel.parent().show();
        }
    },

    // performs a redirect to the URL found in the returned contents
    redirectHandler: function (content, dataAttr) {
        // get contents between div and do window.location = parsed href
        window.location.href = jQuery(content).text();
    },

    // replaces the view with the given content and run the hidden scripts
    updateViewHandler: function (content, dataAttr) {
        jQuery('#' + kradVariables.APP_ID).replaceWith(content);

        runHiddenScriptsAgain();
    },

    // displays the response contents in a lightbox
    displayLightBoxHandler: function (content, dataAttr) {
        showLightboxContent(content);
    }
}<commit_msg>[KULRICE-8496] Fix to do component replace before unblocking<commit_after>/*
 * Copyright 2005-2012 The Kuali Foundation
 *
 * Licensed under the Educational Community License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.opensource.org/licenses/ecl2.php
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
/**
 * Processes a response that has been returned from an Ajax call
 *
 * @param contents - the response contents (or body)
 */
function KradResponse(contents) {
    this.responseContents = contents;
}

KradResponse.prototype = {
    // full response contents
    responseContents: null,

    // maps return types to handler function names
    handlerMapping: {"update-page": "updatePageHandler", "update-component": "updateComponentHandler",
        "update-view": "updateViewHandler", "redirect": "redirectHandler",
        "display-lightbox": "displayLightBoxHandler"},

    // invoked to process the response contents by invoking necessary handlers
    processResponse: function () {
        var responseFn = this;

        // iterate over returned contents divs and invoke handler
        jQuery(this.responseContents).children().each(function () {
            var div = jQuery(this);

            // get the return type sent by the server
            var returnType = div.data("returntype");

            // find the handler function from the mapping
            var functionName = responseFn.handlerMapping[returnType];
            var handlerFunc = responseFn[functionName];

            // invoke the handler function
            if (handlerFunc) {
                handlerFunc(div, div.data());
            }
        });
    },

    // finds the page content in the returned content and updates the page, then processes breadcrumbs and hidden
    // scripts. While processing, the page contents are hidden
    updatePageHandler: function (content, dataAttr) {
        var page = jQuery("#page_update", content);

        // TODO: should this be hiding page or pageInLayout?
        page.hide();

        // give a selector that will avoid the temporary iframe used to hold ajax responses by the jquery form plugin
        var pageInLayout = "#" + kradVariables.VIEW_CONTENT_HEADER_CLASS + " > #" +
                kradVariables.PAGE_CONTENT_HEADER_CLASS;
        hideBubblePopups(pageInLayout);

        // update page contents from response
        jQuery(pageInLayout).empty().append(page.find(">*"));

        // process breadcrumbs
        setPageBreadcrumb();

        pageValidatorReady = false;
        runHiddenScripts(jQuery(pageInLayout).attr("id"), false, true);

        jQuery(pageInLayout).show();
    },

    // retrieves the component with the matching id from the server and replaces a matching
    // _refreshWrapper marker span with the same id with the result.  In addition, if the result contains a label
    // and a displayWith marker span has a matching id, that span will be replaced with the label content
    // and removed from the component.  This allows for label and component content separation on fields
    updateComponentHandler: function (content, dataAttr) {
        var id = dataAttr.updatecomponentid;
        var elementToBlock = jQuery("#" + id);

        hideBubblePopups(elementToBlock);

        var component = jQuery("#" + id + "_update", content);

        var displayWithId = id;

        // special label handling, if any
        var theLabel = jQuery("#" + displayWithId + "_label_span", component);
        if (jQuery(".displayWith-" + displayWithId).length && theLabel.length) {
            theLabel.addClass("displayWith-" + displayWithId);
            jQuery("span.displayWith-" + displayWithId).replaceWith(theLabel);
            component.remove("#" + displayWithId + "_label_span");
        }

        // remove old stuff
        if (jQuery("#" + id + "_errors").length) {
            jQuery("#" + id + "_errors").remove();
        }

        jQuery("input[data-for='" + id + "']").each(function () {
            jQuery(this).remove();
        });

        // replace component
        if (jQuery("#" + id).length) {
            jQuery("#" + id).replaceWith(component.html());
        }

        if (jQuery("#" + id).parent().is("td")) {
            jQuery("#" + id).parent().show();
        }

        // lightbox specific processing
        if (jQuery('#renderedInLightBox').val() == 'true') {
            jQuery("#" + id).css('display', 'none');
        }

        var newComponent = jQuery("#" + id);

        var displayWithLabel = jQuery(".displayWith-" + displayWithId);
        displayWithLabel.show();
        if (displayWithLabel.parent().is("td") || displayWithLabel.parent().is("th")) {
            displayWithLabel.parent().show();
        }

        // runs scripts on the span or div with id
        runHiddenScripts(id);

        elementToBlock.unblock({onUnblock: function () {
            jQuery(component).find("#" + id).addClass(kradVariables.PROGRESSIVE_DISCLOSURE_HIGHLIGHT_CLASS);
            newComponent.animate({backgroundColor:"transparent"}, 6000);
            jQuery(component).find("#" + id).animate({backgroundColor:"transparent"}, 6000);
        }
        });

    },

    // performs a redirect to the URL found in the returned contents
    redirectHandler: function (content, dataAttr) {
        // get contents between div and do window.location = parsed href
        window.location.href = jQuery(content).text();
    },

    // replaces the view with the given content and run the hidden scripts
    updateViewHandler: function (content, dataAttr) {
        jQuery('#' + kradVariables.APP_ID).replaceWith(content);

        runHiddenScriptsAgain();
    },

    // displays the response contents in a lightbox
    displayLightBoxHandler: function (content, dataAttr) {
        showLightboxContent(content);
    }
}<|endoftext|>