<commit_before>#!/usr/bin/env node

'use strict';

var fluent = require('./lib/main.js');

// Some example data:
var val1 = 'val1';

var obj = {};

obj.array = [
    {prop1: val1, pos: 'first'},
    {prop1: null},
    {prop1: val1, pos: 'third'},
    {prop1: val1, pos: 'fourth'}
];

var testCount = 1;

/* if (obj && obj.array)
{
    for (var item in obj.array)
    {
        if (item.prop1 === val1)
        {
            result = item.value;
        }
    }
} */

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.check(obj).and(obj.array).and(undefined).notnull()
.then(function()
{
    console.log('Everything\'s OK');
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.check(null).and(undefined).null()
.then(function()
{
    console.log('Everything\'s OK');
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.notnull(obj, obj.array)
.otherwise(function(err)
{
    console.log('%s', err);
})
.then(function()
{
    console.log('Everything\'s OK');
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.notnull(obj, null)
.otherwise(function(err)
{
    console.log('%s', err);
})
.then(function()
{
    console.log('Everything\'s OK');
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.then(function(item, stop)
{
    console.log('item: %s', JSON.stringify(item));

    stop(); // eventually decide to
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from([])
.where({prop1: val1})
.then(function()
{
    throw new Error('Should have been empty');
})
.otherwise(function(err)
{
    throw new Error('Should have been recognized as empty. Raised an error instead. ' + err);
})
.empty(function()
{
    console.log('Everything\'s OK');
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from([])
.where({prop1: val1})
.then(function()
{
    throw new Error('Should have been empty');
})
.empty(function()
{
    console.log('Everything\'s OK');
})
.otherwise(function(err)
{
    throw new Error('Should have been recognized as empty. Raised an error instead. ' + err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.otherwise(function(err)
{
    console.log(err);
})
.then(function(item, stop)
{
    console.log('item: %s', JSON.stringify(item));

    stop(); // eventually decide to
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.then(function(item /*, stop */)
{
    console.log('item: %s', JSON.stringify(item));

    // stop(); // eventually decide not to
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.all(function(all)
{
    console.log('items: %s', JSON.stringify(all));
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.first(function(item)
{
    console.log('first: %s', JSON.stringify(item));
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.last(function(item)
{
    console.log('last: %s', JSON.stringify(item));
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.check(obj).and(obj.array).notnull()
.then(fluent.from(obj.array)
      .where(function(item, ok, not_ok)
      {
          if (item.prop1 === val1)
          {
              return ok();
          }
          else
          {
              return not_ok();
          }
      })
      .then(function(item, stop)
      {
          console.log('item: %s', JSON.stringify(item));

          stop();
      })
      .otherwise(function(err)
      {
          console.log('%s', err);
      }))
.otherwise(function(err)
{
    console.log('%s', err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.bundle(obj, 'hola', [], [1])
.then(function(result)
{
    console.log('result: %s', JSON.stringify(result));
})
.otherwise(function(err)
{
    console.log('%s', err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

function callMeMaybe(arg1, arg2, arg3)
{
    fluent.constrain(arg1, arg2, arg3).notnull()
    .valid(function()
    {
        console.log('Everything\'s OK');
    })
    .otherwise(function(err)
    {
        console.log('%s', err);
    });
}

callMeMaybe('boooh', '', {});

console.log('-------');
console.log('TEST #%s', testCount++);

function callMeMaybe2(arg1, arg2, arg3)
{
    fluent.constrain(arg1, arg2, arg3).notnull()
    .throws()
    .valid(function()
    {
        console.log('Everything\'s OK');
    });
}

// callMeMaybe2('boooh');  // This one throws
callMeMaybe2(0, 1, 2);  // This one doesn't throw

console.log('-------');
console.log('TEST #%s', testCount++);

function callMeMaybe3(arg1, arg2)
{
    fluent.constrain(arg1, arg2).objects()
    .throws()
    .valid(function()
    {
        console.log('Everything\'s OK');
    });
}

callMeMaybe3(obj, {});

console.log('-------');
console.log('TEST #%s', testCount++);

function callMeMaybe4(arg1, arg2, arg3)
{
    fluent.constrain(arg1, arg2).objects()
    .constrain(arg3).notnull()
    .throws()
    .valid(function()
    {
        console.log('Everything\'s OK');
    });
}

callMeMaybe4(obj, {}, '');

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.call(function()
{
    throw new Error('error1');
})
.then(function()
{
    throw new Error('Test failed');
})
.otherwise(function(err)
{
    if (err)
    {
        console.log('Is everything OK? ' + err);
    }
    else
    {
        throw new Error('Test failed');
    }
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.call(function()
{
    return 'OK';
})
.then(function(result)
{
    if (result === 'OK')
    {
        console.log('Everything\'s %s', result);
    }
    else
    {
        throw new Error('Test failed. Result: ' + result);
    }
})
.otherwise(function(err)
{
    throw new Error('Test failed. ' + err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.call(function()
{
    return new Error('error1');
})
.then(function()
{
    throw new Error('Test failed');
})
.otherwise(function(err)
{
    if (err)
    {
        console.log('Is everything OK? ' + err);
    }
    else
    {
        throw new Error('Test failed');
    }
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.call(function()
{
    return 'result1';

}, function(res)
{
    return res + '-result2';
})
.then(function(result)
{
    if (result === 'result1-result2')
    {
        console.log('Everything\'s OK');
    }
    else
    {
        throw new Error('Test failed. Result: ' + result);
    }
})
.otherwise(function(err)
{
    throw new Error('Test failed. ' + err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

var result = fluent.protect(function(param1, param2)
{
    if (   param1 === 'param1'
        && param2 === 'param2')
    {
        console.log('Got parameters right');

        return param1 + param2;
    }
    else
    {
        throw new Error('Test failed. Parameters mismatch: ' + param1 + ', ' + param2);
    }
})
.pass('param1', 'param2')
.catch(function(err)
{
    throw new Error('Test failed. ' + err);
})
.return();

if (result === 'param1param2')
{
    console.log('Everything\'s OK');
}
else
{
    throw new Error('Test failed. Result mismatch: ' + result);
}
<commit_msg>Added tests for the last commits<commit_after>#!/usr/bin/env node

'use strict';

var fluent = require('./lib/main.js');

// Some example data:
var val1 = 'val1';

var obj = {};

obj.array = [
    {prop1: val1, pos: 'first'},
    {prop1: null},
    {prop1: val1, pos: 'third'},
    {prop1: val1, pos: 'fourth'}
];

var testCount = 1;

/* if (obj && obj.array)
{
    for (var item in obj.array)
    {
        if (item.prop1 === val1)
        {
            result = item.value;
        }
    }
} */

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.check(obj).and(obj.array).and(undefined).notnull()
.then(function()
{
    console.log('Everything\'s OK');
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.check(null).and(undefined).null()
.then(function()
{
    console.log('Everything\'s OK');
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.notnull(obj, obj.array)
.otherwise(function(err)
{
    console.log('%s', err);
})
.then(function()
{
    console.log('Everything\'s OK');
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.notnull(obj, null)
.otherwise(function(err)
{
    console.log('%s', err);
})
.then(function()
{
    console.log('Everything\'s OK');
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.then(function(item, stop)
{
    console.log('item: %s', JSON.stringify(item));

    stop(); // eventually decide to
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from([])
.where({prop1: val1})
.then(function()
{
    throw new Error('Should have been empty');
})
.otherwise(function(err)
{
    throw new Error('Should have been recognized as empty. Raised an error instead. ' + err);
})
.empty(function()
{
    console.log('Everything\'s OK');
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from([])
.where({prop1: val1})
.then(function()
{
    throw new Error('Should have been empty');
})
.empty(function()
{
    console.log('Everything\'s OK');
})
.otherwise(function(err)
{
    throw new Error('Should have been recognized as empty. Raised an error instead. ' + err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.otherwise(function(err)
{
    console.log(err);
})
.then(function(item, stop)
{
    console.log('item: %s', JSON.stringify(item));

    stop(); // eventually decide to
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.then(function(item /*, stop */)
{
    console.log('item: %s', JSON.stringify(item));

    // stop(); // eventually decide not to
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.all(function(all)
{
    console.log('items: %s', JSON.stringify(all));
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.first(function(item)
{
    console.log('first: %s', JSON.stringify(item));
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.from(obj.array)
.where({prop1: val1})
.last(function(item)
{
    console.log('last: %s', JSON.stringify(item));
})
.otherwise(function(err)
{
    console.log(err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.check(obj).and(obj.array).notnull()
.then(fluent.from(obj.array)
      .where(function(item, ok, not_ok)
      {
          if (item.prop1 === val1)
          {
              return ok();
          }
          else
          {
              return not_ok();
          }
      })
      .then(function(item, stop)
      {
          console.log('item: %s', JSON.stringify(item));

          stop();
      })
      .otherwise(function(err)
      {
          console.log('%s', err);
      }))
.otherwise(function(err)
{
    console.log('%s', err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.bundle(obj, 'hola', [], [1])
.then(function(result)
{
    console.log('result: %s', JSON.stringify(result));
})
.otherwise(function(err)
{
    console.log('%s', err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

function callMeMaybe(arg1, arg2, arg3)
{
    fluent.constrain(arg1, arg2, arg3).notnull()
    .valid(function()
    {
        console.log('Everything\'s OK');
    })
    .otherwise(function(err)
    {
        console.log('%s', err);
    });
}

callMeMaybe('boooh', '', {});

console.log('-------');
console.log('TEST #%s', testCount++);

function callMeMaybe1bis(arg1, arg2, arg3)
{
    fluent.constrain([arg1, arg2, arg3]).notnull()
    .valid(function()
    {
        console.log('Everything\'s OK');
    })
    .otherwise(function(err)
    {
        console.log('%s', err);
    });
}

callMeMaybe1bis('boooh', '', {});

console.log('-------');
console.log('TEST #%s', testCount++);

function callMeMaybe2(arg1, arg2, arg3)
{
    fluent.constrain(arg1, arg2, arg3).notnull()
    .throws()
    .valid(function()
    {
        console.log('Everything\'s OK');
    });
}

// callMeMaybe2('boooh');  // This one throws
callMeMaybe2(0, 1, 2);  // This one doesn't throw

console.log('-------');
console.log('TEST #%s', testCount++);

function callMeMaybe3(arg1, arg2)
{
    fluent.constrain(arg1, arg2).objects()
    .throws()
    .valid(function()
    {
        console.log('Everything\'s OK');
    });
}

callMeMaybe3(obj, {});

console.log('-------');
console.log('TEST #%s', testCount++);

function callMeMaybe4(arg1, arg2, arg3)
{
    fluent.constrain(arg1, arg2).objects()
    .constrain(arg3).notnull()
    .throws()
    .valid(function()
    {
        console.log('Everything\'s OK');
    });
}

callMeMaybe4(obj, {}, '');

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.call(function()
{
    throw new Error('error1');
})
.then(function()
{
    throw new Error('Test failed');
})
.otherwise(function(err)
{
    if (err)
    {
        console.log('Is everything OK? ' + err);
    }
    else
    {
        throw new Error('Test failed');
    }
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.call(function()
{
    return 'OK';
})
.then(function(result)
{
    if (result === 'OK')
    {
        console.log('Everything\'s %s', result);
    }
    else
    {
        throw new Error('Test failed. Result: ' + result);
    }
})
.otherwise(function(err)
{
    throw new Error('Test failed. ' + err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.call(function()
{
    return new Error('error1');
})
.then(function()
{
    throw new Error('Test failed');
})
.otherwise(function(err)
{
    if (err)
    {
        console.log('Is everything OK? ' + err);
    }
    else
    {
        throw new Error('Test failed');
    }
});

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.call(function()
{
    return 'result1';

}, function(res)
{
    return res + '-result2';
})
.then(function(result)
{
    if (result === 'result1-result2')
    {
        console.log('Everything\'s OK');
    }
    else
    {
        throw new Error('Test failed. Result: ' + result);
    }
})
.otherwise(function(err)
{
    throw new Error('Test failed. ' + err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

var called = false;

fluent.protect(function()
{
    console.log('Everything\'s OK.');

    called = true;
})
.catch(function(err)
{
    throw new Error('Test failed. ' + err);
});

if (!called)
{
    throw new Error('Test failed. Function wasn\'t called.');
}

console.log('-------');
console.log('TEST #%s', testCount++);

var result = fluent.protect(function(param1, param2)
{
    if (   param1 === 'param1'
        && param2 === 'param2')
    {
        console.log('Got parameters right');

        return param1 + param2;
    }
    else
    {
        throw new Error('Test failed. Parameters mismatch: ' + param1 + ', ' + param2);
    }
})
.pass('param1', 'param2')
.catch(function(err)
{
    throw new Error('Test failed. ' + err);
})
.return();

if (result === 'param1param2')
{
    console.log('Everything\'s OK');
}
else
{
    throw new Error('Test failed. Result mismatch: ' + result);
}

console.log('-------');
console.log('TEST #%s', testCount++);

fluent.protect(function(param1, param2)
{
    throw new Error('Test failed. Shouldn\'t have entered here. Parameters were: ' + param1 + ', ' + param2);
})
.pass('param1', undefined)
.catch(function(err)
{
    console.log('Everything\'s OK. ' + err);
});

console.log('-------');
console.log('TEST #%s', testCount++);

var result = fluent.protect(function(param1, param2)
{
    throw new Error('Test failed. Shouldn\'t have entered here. Parameters were: ' + param1 + ', ' + param2);
})
.pass('param1', undefined)
.catch(function(err)
{
    console.log('Everything\'s OK (1). ' + err);
})
.return();

if (result === undefined || result === null)
{
    console.log('Everything\'s OK (2)');
}
else
{
    throw new Error('Test failed. Result mismatch: ' + result);
}
<|endoftext|>


<commit_before>export default function() {
    const app = this;
    app.addFilter('GlitchFilter', {
        enabled: true,
        global: false,
        opened: false,
        args: [{
            bandCount: 8,
            offset: app.initWidth / 4 >> 0,
            average: true,
            red: [2, 2],
            green: [-10, 4],
            blue: [10, -4],
            seed: 0.5,
        }, 0],
        oncreate(folder) {
            const filter = this;

            window.glitchFilter = filter;

            filter.animating = true;

            app.events.on('animate', function() {
                if (filter.animating) {
                    filter.seed = Math.random();
                }
            });

            folder.add(this, 'animating').name('(animating)');
            folder.add(this, 'seed', 0, 1);
            folder.add(this, 'offset', 0, app.initWidth / 2 >> 0);
            folder.add(this.red, '0', -20, 20).name('red.x');
            folder.add(this.red, '1', -20, 20).name('red.y');
            folder.add(this.blue, '0', -20, 20).name('blue.x');
            folder.add(this.blue, '1', -20, 20).name('blue.y');
            folder.add(this.green, '0', -20, 20).name('green.x');
            folder.add(this.green, '1', -20, 20).name('green.y');
        }
    });
}
<commit_msg>update<commit_after>export default function() {
    const app = this;
    app.addFilter('GlitchFilter', {
        enabled: true,
        global: false,
        opened: false,
        args: [{
            bandCount: 8,
            offset: app.initWidth / 4 >> 0,
            average: false,
            red: [2, 2],
            green: [-10, 4],
            blue: [10, -4],
            seed: 0.5,
        }, 0],
        oncreate(folder) {
            const filter = this;

            window.glitchFilter = filter;

            filter.animating = true;

            app.events.on('animate', function() {
                if (filter.animating) {
                    filter.seed = Math.random();
                }
            });

            folder.add(this, 'animating').name('(animating)');
            folder.add(this, 'seed', 0, 1);
            folder.add(this, 'offset', 0, app.initWidth / 2 >> 0);
            folder.add(this.red, '0', -20, 20).name('red.x');
            folder.add(this.red, '1', -20, 20).name('red.y');
            folder.add(this.blue, '0', -20, 20).name('blue.x');
            folder.add(this.blue, '1', -20, 20).name('blue.y');
            folder.add(this.green, '0', -20, 20).name('green.x');
            folder.add(this.green, '1', -20, 20).name('green.y');
        }
    });
}
<|endoftext|>


<commit_before>/*
 * This module defines a replacement navigator.geolocation.* which
 * invokes emscripten to do a lookup.
 */

self.port.on("offline_fix_found", function(message) {
    console.log("DEBUG: geo-script.js received a message: " + JSON.stringify(message));

    // This listener receives messages from index.js to get the
    // lat/lon JSON blob.  We then forward this message on to the page
    // script

    // Tag this JSON object so that we can just test the string in
    // the page javascript before we try the callback
    message['__fx_elm_location'] = 1;
    var json_msg = JSON.stringify(message);
    window.postMessage(json_msg, "*");
});

self.port.on("offline_fix_unavailable", function(message) {
    console.log("DEBUG: geo-script.js received an unavailable location message: " + JSON.stringify(message));

    // This listener receives messages from index.js to get the
    // lat/lon JSON blob.  We then forward this message on to the page
    // script

    // Tag this JSON object so that we can just test the string in
    // the page javascript before we try the callback
    message['__fx_elm_unavailable_location'] = 1;
    var json_msg = JSON.stringify(message);
    console.log("Sending page unavailable JSON: " + json_msg);
    window.postMessage(json_msg, "*");
});

if (self.options.showOptions) {
    function injectedCode() {

        /* None of this code will work within the regular javascript
         * debugger if you put a breakpoint inside of it.  ALl the
         * code here is clobbered into each HTML page and injected at
         * the top so the only way to set a break point is to go into
         * the individual page HTML and set a breakpoint there.
         *
         * You also can't even view the code within the HTML page as
         * injected code in a content script doesn't exist within
         * the regular Javascript runtime.
         *
         * So debugging this relies on console.log messages as you can
         * never actually see the code running within the page.
         *
         * Generally - debugging content scripts is awful.
         *
         * https://bugzilla.mozilla.org/show_bug.cgi?id=1016046
         *
         * I've managed to make things even *worse* by injecting code
         * dynamically into the actual content of the page with the
         * content script.
         *
         */

        navigator.geolocation.getCurrentPosition = function(callBack,
                                                            errBack,
                                                            options) {

            function MockGeoPositionObject(lat, lng, acc) {
              this.coords = new MockGeoCoordsObject(lat, lng, acc, 0, 0);
              this.address = null;
              this.timestamp = Date.now();
            }

            function MockGeoCoordsObject(lat, lon, acc, alt, altacc) {
              this.latitude = lat;
              this.longitude = lon;
              this.accuracy = acc;
              this.altitude = alt;
              this.altitudeAccuracy = altacc;
            }

            window.startOfflineScan();

            navigator.geolocation.captured_callBack = callBack;
            navigator.geolocation.captured_errBack = errBack;

            console.log("Callback function: " + navigator.geolocation.captured_callBack);
            console.log("^^ Bound callback to navigator.geolocation.captured_callBack");

            // TODO: this callback needs to be invoked after a lookup
            // in the marisa trie
            //callBack(new MockGeoPositionObject(44.033639,-79.490813, 50));
        };

        navigator.geolocation.watchPosition = function(cb1, cb2, options) {
            alert("watchPosition was called");
        };

        navigator.geolocation.clearWatch = function () {
            alert("clearWatch was called");
        };

        // Remove script
        // Ok - this is a bit wacky and probably unnecessary.
        // Once we're finished clobbering the navigator.geolocation
        // namespace - we actually *delete* the clobbering code from
        // the page content.  Just to be sneaky.

        /*
        var s = document.getElementById('__offline_clobber');
        if (s) {
            s.remove();	// DEMO: in demo injectCode is run directly so there's no script
        }
        */
    }

    if (document.documentElement.tagName.toLowerCase() == 'html') { // only for html
        // Step 1- Clobber the navigator.geolocation namespace
        var inject = "(function(){"
            + injectedCode +
            " injectedCode();" +
            "})()";

        var script = document.createElement('script');
        script.setAttribute('id', '__offline_clobber');
        script.appendChild(document.createTextNode(inject));

        // FF: there is already another variable in the scope named
        // 'parent', this causes a very hard to catch bug so we'll
        // just call this '_parent'
        var _parent = document.head || document.body || document.documentElement;
        var firstChild = (_parent.childNodes && (_parent.childNodes.length > 0)) ? _parent.childNodes[0] : null;
        if (firstChild) {
            _parent.insertBefore(script, firstChild);
        } else {
            _parent.appendChild(script);
        }

        // Step 2 - add a listener for offline fixes
        // Now inject a listener for when the content script passes
        // a message with the offline fix.
        var script = document.createElement('script');
        var inject = "window.addEventListener('message', function(event) {  \
            console.log('Page got a message: ' + event.data);  \
            if (event.data.indexOf('__fx_elm_location')  > -1) {  \
                console.log('Available position received in page'); \
                var json_obj = JSON.parse(event.data);  \
                function MockGeoPositionObject(lat, lng, acc) {  \
                  this.coords = new MockGeoCoordsObject(lat, lng, acc, 0, 0);  \
                  this.address = null;  \
                  this.timestamp = Date.now();  \
                }  \
                function MockGeoCoordsObject(lat, lon, acc, alt, altacc) {  \
                  this.latitude = lat;  \
                  this.longitude = lon;  \
                  this.accuracy = acc;  \
                  this.altitude = alt;  \
                  this.altitudeAccuracy = altacc;  \
                }  \
                var mockLocation = new MockGeoPositionObject(json_obj['lat'], json_obj['lon'], 100); \
                navigator.geolocation.captured_callBack(mockLocation);  \
            }  \
            if (event.data.indexOf('__fx_elm_unavailable_location') > -1) {  \
                console.log('Unavailable position received in page'); \
                function MockPositionError() {  \
                  this.code = 2;  \
                  this.message = 'Offline position is unavailable'; \
                }  \
                var posError = new MockPositionError(); \
                console.log('ErrBack: ' + navigator.geolocation.captured_errBack);\
                console.log('PositionError: ' + posError); \
                var mockLocation = new MockGeoPositionObject(0, 0, 100); \
                navigator.geolocation.captured_errBack(posError); \
            }  \
         }, false);";

        script.setAttribute('id', '__offline_receiver');
        script.appendChild(document.createTextNode(inject));
        var _parent = document.head || document.body || document.documentElement;
        var firstChild = (_parent.childNodes && (_parent.childNodes.length > 0)) ? _parent.childNodes[0] : null;
        if (firstChild) {
            _parent.insertBefore(script, firstChild);
        } else {
            _parent.appendChild(script);
        }
    }
}
<commit_msg>Remove dead commented out code<commit_after>/*
 * This module defines a replacement navigator.geolocation.* which
 * invokes emscripten to do a lookup.
 */

self.port.on("offline_fix_found", function(message) {
    console.log("DEBUG: geo-script.js received a message: " + JSON.stringify(message));

    // This listener receives messages from index.js to get the
    // lat/lon JSON blob.  We then forward this message on to the page
    // script

    // Tag this JSON object so that we can just test the string in
    // the page javascript before we try the callback
    message['__fx_elm_location'] = 1;
    var json_msg = JSON.stringify(message);
    window.postMessage(json_msg, "*");
});

self.port.on("offline_fix_unavailable", function(message) {
    console.log("DEBUG: geo-script.js received an unavailable location message: " + JSON.stringify(message));

    // This listener receives messages from index.js to get the
    // lat/lon JSON blob.  We then forward this message on to the page
    // script

    // Tag this JSON object so that we can just test the string in
    // the page javascript before we try the callback
    message['__fx_elm_unavailable_location'] = 1;
    var json_msg = JSON.stringify(message);
    console.log("Sending page unavailable JSON: " + json_msg);
    window.postMessage(json_msg, "*");
});

if (self.options.showOptions) {
    function injectedCode() {

        /* None of this code will work within the regular javascript
         * debugger if you put a breakpoint inside of it.  ALl the
         * code here is clobbered into each HTML page and injected at
         * the top so the only way to set a break point is to go into
         * the individual page HTML and set a breakpoint there.
         *
         * You also can't even view the code within the HTML page as
         * injected code in a content script doesn't exist within
         * the regular Javascript runtime.
         *
         * So debugging this relies on console.log messages as you can
         * never actually see the code running within the page.
         *
         * Generally - debugging content scripts is awful.
         *
         * https://bugzilla.mozilla.org/show_bug.cgi?id=1016046
         *
         * I've managed to make things even *worse* by injecting code
         * dynamically into the actual content of the page with the
         * content script.
         *
         */

        navigator.geolocation.getCurrentPosition = function(callBack,
                                                            errBack,
                                                            options) {

            function MockGeoPositionObject(lat, lng, acc) {
              this.coords = new MockGeoCoordsObject(lat, lng, acc, 0, 0);
              this.address = null;
              this.timestamp = Date.now();
            }

            function MockGeoCoordsObject(lat, lon, acc, alt, altacc) {
              this.latitude = lat;
              this.longitude = lon;
              this.accuracy = acc;
              this.altitude = alt;
              this.altitudeAccuracy = altacc;
            }

            window.startOfflineScan();

            navigator.geolocation.captured_callBack = callBack;
            navigator.geolocation.captured_errBack = errBack;

            console.log("Callback function: " + navigator.geolocation.captured_callBack);
            console.log("^^ Bound callback to navigator.geolocation.captured_callBack");
        };

        navigator.geolocation.watchPosition = function(cb1, cb2, options) {
            alert("watchPosition was called");
        };

        navigator.geolocation.clearWatch = function () {
            alert("clearWatch was called");
        };

        // Remove script
        // Ok - this is a bit wacky and probably unnecessary.
        // Once we're finished clobbering the navigator.geolocation
        // namespace - we actually *delete* the clobbering code from
        // the page content.  Just to be sneaky.

        /*
        var s = document.getElementById('__offline_clobber');
        if (s) {
            s.remove();	// DEMO: in demo injectCode is run directly so there's no script
        }
        */
    }

    if (document.documentElement.tagName.toLowerCase() == 'html') { // only for html
        // Step 1- Clobber the navigator.geolocation namespace
        var inject = "(function(){"
            + injectedCode +
            " injectedCode();" +
            "})()";

        var script = document.createElement('script');
        script.setAttribute('id', '__offline_clobber');
        script.appendChild(document.createTextNode(inject));

        // FF: there is already another variable in the scope named
        // 'parent', this causes a very hard to catch bug so we'll
        // just call this '_parent'
        var _parent = document.head || document.body || document.documentElement;
        var firstChild = (_parent.childNodes && (_parent.childNodes.length > 0)) ? _parent.childNodes[0] : null;
        if (firstChild) {
            _parent.insertBefore(script, firstChild);
        } else {
            _parent.appendChild(script);
        }

        // Step 2 - add a listener for offline fixes
        // Now inject a listener for when the content script passes
        // a message with the offline fix.
        var script = document.createElement('script');
        var inject = "window.addEventListener('message', function(event) {  \
            console.log('Page got a message: ' + event.data);  \
            if (event.data.indexOf('__fx_elm_location')  > -1) {  \
                console.log('Available position received in page'); \
                var json_obj = JSON.parse(event.data);  \
                function MockGeoPositionObject(lat, lng, acc) {  \
                  this.coords = new MockGeoCoordsObject(lat, lng, acc, 0, 0);  \
                  this.address = null;  \
                  this.timestamp = Date.now();  \
                }  \
                function MockGeoCoordsObject(lat, lon, acc, alt, altacc) {  \
                  this.latitude = lat;  \
                  this.longitude = lon;  \
                  this.accuracy = acc;  \
                  this.altitude = alt;  \
                  this.altitudeAccuracy = altacc;  \
                }  \
                var mockLocation = new MockGeoPositionObject(json_obj['lat'], json_obj['lon'], 100); \
                navigator.geolocation.captured_callBack(mockLocation);  \
            }  \
            if (event.data.indexOf('__fx_elm_unavailable_location') > -1) {  \
                console.log('Unavailable position received in page'); \
                function MockPositionError() {  \
                  this.code = 2;  \
                  this.message = 'Offline position is unavailable'; \
                }  \
                var posError = new MockPositionError(); \
                console.log('ErrBack: ' + navigator.geolocation.captured_errBack);\
                console.log('PositionError: ' + posError); \
                var mockLocation = new MockGeoPositionObject(0, 0, 100); \
                navigator.geolocation.captured_errBack(posError); \
            }  \
         }, false);";

        script.setAttribute('id', '__offline_receiver');
        script.appendChild(document.createTextNode(inject));
        var _parent = document.head || document.body || document.documentElement;
        var firstChild = (_parent.childNodes && (_parent.childNodes.length > 0)) ? _parent.childNodes[0] : null;
        if (firstChild) {
            _parent.insertBefore(script, firstChild);
        } else {
            _parent.appendChild(script);
        }
    }
}
<|endoftext|>


<commit_before>'use strict';
var assert = require('assert');
var firstChunkStream = require('./');
var streamtest = require('streamtest');

describe('firstChunk()', function () {
	var content = 'unicorn rainbows \ncake';

	streamtest.versions.forEach(function (version) {

		describe('for ' + version + ' streams', function () {

			it('should should work for a single oversized chunk', function (cb) {
				streamtest[version].fromChunks([content])
					.pipe(firstChunkStream(function (chunk, enc, cb) {
						this.push(chunk);
						cb();
					}))
					.pipe(streamtest[version].toText(function (err, text) {
						if(err) {
							return done(err);
						}
						assert.deepEqual(text, content);
						cb();
					}));
			});

			it('should should work for required size chunk', function (cb) {
				streamtest[version].fromChunks([content.substr(0, 7), content.substr(7)])
					.pipe(firstChunkStream({minSize: 7}, function (chunk, enc, cb) {
						this.push(chunk);
						cb();
					}))
					.pipe(streamtest[version].toText(function (err, text) {
						if(err) {
							return done(err);
						}
						assert.deepEqual(text, content);
						cb();
					}));
			});

			it('should should work for several small chunks', function (cb) {
				streamtest[version].fromChunks(content.split(''))
					.pipe(firstChunkStream(function (chunk, enc, cb) {
						this.push(chunk);
						cb();
					}))
					.pipe(streamtest[version].toText(function (err, text) {
						if(err) {
							return done(err);
						}
						assert.deepEqual(text, content);
						cb();
					}));
			});

		});

	});

});
<commit_msg>Changing tests for the new API<commit_after>'use strict';
var assert = require('assert');
var firstChunkStream = require('./');
var streamtest = require('streamtest');

describe('firstChunk()', function () {
	var content = 'unicorn rainbows \ncake';

	streamtest.versions.forEach(function (version) {

		describe('for ' + version + ' streams', function () {

			describe('and leaving content as is', function () {

				it('should work for a single oversized chunk', function (cb) {
					streamtest[version].fromChunks([content])
						.pipe(firstChunkStream({firstChunkSize: 7}, function (chunk, enc, cb) {
							assert.equal(chunk.toString('utf-8'), content.substr(0, 7));
							cb(null, chunk);
						}))
						.pipe(streamtest[version].toText(function (err, text) {
							if(err) {
								return done(err);
							}
							assert.deepEqual(text, content);
							cb();
						}));
				});

				it('should work for required size chunk', function (cb) {
					streamtest[version].fromChunks([content.substr(0, 7), content.substr(7)])
						.pipe(firstChunkStream({firstChunkSize: 7}, function (chunk, enc, cb) {
							assert.equal(chunk.toString('utf-8'), content.substr(0, 7));
							cb(null, chunk);
						}))
						.pipe(streamtest[version].toText(function (err, text) {
							if(err) {
								return done(err);
							}
							assert.deepEqual(text, content);
							cb();
						}));
				});

				it('should work for several small chunks', function (cb) {
					streamtest[version].fromChunks(content.split(''))
						.pipe(firstChunkStream({firstChunkSize: 7}, function (chunk, enc, cb) {
							assert.equal(chunk.toString('utf-8'), content.substr(0, 7));
							cb(null, chunk);
						}))
						.pipe(streamtest[version].toText(function (err, text) {
							if(err) {
								return done(err);
							}
							assert.deepEqual(text, content);
							cb();
						}));
				});

			});

			describe('and changing content', function () {

				it('should work when removing the first chunk', function (cb) {
					streamtest[version].fromChunks([content])
						.pipe(firstChunkStream({firstChunkSize: 7}, function (chunk, enc, cb) {
							assert.equal(chunk.toString('utf-8'), content.substr(0, 7));
							cb(null, new Buffer(''));
						}))
						.pipe(streamtest[version].toText(function (err, text) {
							if(err) {
								return done(err);
							}
							assert.deepEqual(text, content.substr(8));
							cb();
						}));
				});

				it('should work when replacing per a larger chunk', function (cb) {
					streamtest[version].fromChunks([content.substr(0, 7), content.substr(7)])
						.pipe(firstChunkStream({firstChunkSize: 7}, function (chunk, enc, cb) {
							assert.equal(chunk.toString('utf-8'), content.substr(0, 7));
							cb(null, Buffer.concat([chunk, new Buffer('plop')], 2));
						}))
						.pipe(streamtest[version].toText(function (err, text) {
							if(err) {
								return done(err);
							}
							assert.deepEqual(text, content.substr(0, 7) + 'plop' + content.substr(8));
							cb();
						}));
				});

				it('should work when replacing per a smaller chunk', function (cb) {
					streamtest[version].fromChunks(content.split(''))
						.pipe(firstChunkStream({firstChunkSize: 7}, function (chunk, enc, cb) {
							assert.equal(chunk.toString('utf-8'), content.substr(0, 7));
							cb(null, new Buffer('plop'));
						}))
						.pipe(streamtest[version].toText(function (err, text) {
							if(err) {
								return done(err);
							}
							assert.deepEqual(text, 'plop' + content.substr(8));
							cb();
						}));
				});

			});

		});

	});

});
<|endoftext|>


<commit_before>// NOTE: to run this you will probably need to be authorized with GitHub.
// Run `./changelog-maker.js` by itself to set this up.

'use strict'

const path = require('path')
const { execSync } = require('child_process')
const { test } = require('tap')

function exec (args) {
  const stdout = execSync(`"${process.execPath}" ${path.join(__dirname, 'changelog-maker.js')} ${args}`).toString()

  return stdout
}

test('test basic commit block', (t) => {
  t.equal(exec('--start-ref=v1.3.9 --end-ref=v1.3.10'),
    `* [[\`e28b3f2813\`](https://github.com/nodejs/changelog-maker/commit/e28b3f2813)] - 1.3.10 (Rod Vagg)
* [[\`ace3af943e\`](https://github.com/nodejs/changelog-maker/commit/ace3af943e)] - Merge pull request #13 from jamsyoung/private-repo-support (Rod Vagg)
* [[\`25ec5428bc\`](https://github.com/nodejs/changelog-maker/commit/25ec5428bc)] - default to repo scope always - revert previous changes (James Young)
* [[\`424d6c22c1\`](https://github.com/nodejs/changelog-maker/commit/424d6c22c1)] - add --private arg to set repo scope, update readme (James Young)
* [[\`7c8c5e6215\`](https://github.com/nodejs/changelog-maker/commit/7c8c5e6215)] - 1.3.9 (Rod Vagg)
`)
  t.end()
})

test('test filter-release', (t) => {
  t.equal(exec('--start-ref=v1.3.9 --end-ref=v1.3.10 --filter-release'),
    `* [[\`ace3af943e\`](https://github.com/nodejs/changelog-maker/commit/ace3af943e)] - Merge pull request #13 from jamsyoung/private-repo-support (Rod Vagg)
* [[\`25ec5428bc\`](https://github.com/nodejs/changelog-maker/commit/25ec5428bc)] - default to repo scope always - revert previous changes (James Young)
* [[\`424d6c22c1\`](https://github.com/nodejs/changelog-maker/commit/424d6c22c1)] - add --private arg to set repo scope, update readme (James Young)
`)
  t.end()
})

test('test simple', (t) => {
  t.equal(exec('--start-ref=v1.3.9 --end-ref=v1.3.10 --simple'),
    `* [e28b3f2813] - 1.3.10 (Rod Vagg)
* [ace3af943e] - Merge pull request #13 from jamsyoung/private-repo-support (Rod Vagg)
* [25ec5428bc] - default to repo scope always - revert previous changes (James Young)
* [424d6c22c1] - add --private arg to set repo scope, update readme (James Young)
* [7c8c5e6215] - 1.3.9 (Rod Vagg)
`)
  t.end()
})

test('test plaintext', (t) => {
  t.equal(exec('--start-ref=9c700d2 --end-ref=dd937e9 --group --filter-release --plaintext'),
    `feature:
  * refactor and improve --commit-url (Rod Vagg)
test:
  * update refs for testing (Rod Vagg)
`)
  t.end()
})

test('test group, semver labels, PR-URL', (t) => {
  t.equal(exec('--start-ref=v2.2.7 --end-ref=9c700d29 --group --filter-release --simple'),
    `* [cc442b6534] - (SEMVER-MINOR) minor nit (Rod Vagg) https://github.com/nodejs/node/pull/23715
* [4f2b7f8136] - deps: use strip-ansi instead of chalk.stripColor (Rod Vagg)
* [6898501e18] - deps: update deps, introduce test & lint deps (Rod Vagg)
* [9c700d2910] - feature: refactor and improve --commit-url (Rod Vagg)
* [5094524655] - feature: make the commit url configurable via an additional argument (Jim Nielsen) https://github.com/nodejs/changelog-maker/pull/55
* [42f248cf89] - src: use \`standard\` for linting (Rod Vagg)
* [64a8fdef3c] - test: basic test infrastructure (Rod Vagg)
`)
  t.end()
})

test('test simple group, semver labels, PR-URL', (t) => {
  t.equal(exec('--start-ref=v2.2.7 --end-ref=9c700d29 --group --filter-release'),
    `* [[\`cc442b6534\`](https://github.com/nodejs/changelog-maker/commit/cc442b6534)] - **(SEMVER-MINOR)** minor nit (Rod Vagg) [nodejs/node#23715](https://github.com/nodejs/node/pull/23715)
* [[\`4f2b7f8136\`](https://github.com/nodejs/changelog-maker/commit/4f2b7f8136)] - **deps**: use strip-ansi instead of chalk.stripColor (Rod Vagg)
* [[\`6898501e18\`](https://github.com/nodejs/changelog-maker/commit/6898501e18)] - **deps**: update deps, introduce test & lint deps (Rod Vagg)
* [[\`9c700d2910\`](https://github.com/nodejs/changelog-maker/commit/9c700d2910)] - **feature**: refactor and improve --commit-url (Rod Vagg)
* [[\`5094524655\`](https://github.com/nodejs/changelog-maker/commit/5094524655)] - **feature**: make the commit url configurable via an additional argument (Jim Nielsen) [#55](https://github.com/nodejs/changelog-maker/pull/55)
* [[\`42f248cf89\`](https://github.com/nodejs/changelog-maker/commit/42f248cf89)] - **src**: use \`standard\` for linting (Rod Vagg)
* [[\`64a8fdef3c\`](https://github.com/nodejs/changelog-maker/commit/64a8fdef3c)] - **test**: basic test infrastructure (Rod Vagg)
`)
  t.end()
})

test('test blank commit-url', (t) => {
  let actual = exec('--start-ref=v2.2.7 --end-ref=9c700d29 --filter-release --commit-url=http://foo.bar/').split('\n')
  actual.splice(0, actual.length - 3)
  actual = actual.join('\n')
  t.equal(actual,
    `* [[\`cc442b6534\`](http://foo.bar/)] - **(SEMVER-MINOR)** minor nit (Rod Vagg) [nodejs/node#23715](https://github.com/nodejs/node/pull/23715)
* [[\`5094524655\`](http://foo.bar/)] - **feature**: make the commit url configurable via an additional argument (Jim Nielsen) [#55](https://github.com/nodejs/changelog-maker/pull/55)
`)
  t.end()
})

test('test blank commit-url', (t) => {
  let actual = exec('--start-ref=v2.2.7 --end-ref=9c700d29 --filter-release --commit-url=https://yeehaw.com/{ref}/{ref}/{ghUser}/{ghRepo}/').split('\n')
  actual.splice(0, actual.length - 3)
  actual = actual.join('\n')
  t.equal(actual,
    `* [[\`cc442b6534\`](https://yeehaw.com/cc442b6534/cc442b6534/nodejs/changelog-maker/)] - **(SEMVER-MINOR)** minor nit (Rod Vagg) [nodejs/node#23715](https://github.com/nodejs/node/pull/23715)
* [[\`5094524655\`](https://yeehaw.com/5094524655/5094524655/nodejs/changelog-maker/)] - **feature**: make the commit url configurable via an additional argument (Jim Nielsen) [#55](https://github.com/nodejs/changelog-maker/pull/55)
`)
  t.end()
})
<commit_msg>test: add tests for backticks<commit_after>// NOTE: to run this you will probably need to be authorized with GitHub.
// Run `./changelog-maker.js` by itself to set this up.

'use strict'

const path = require('path')
const { execSync } = require('child_process')
const { test } = require('tap')

function exec (args) {
  const stdout = execSync(`"${process.execPath}" ${path.join(__dirname, 'changelog-maker.js')} ${args}`).toString()

  return stdout
}

test('test basic commit block', (t) => {
  t.equal(exec('--start-ref=v1.3.9 --end-ref=v1.3.10'),
    `* [[\`e28b3f2813\`](https://github.com/nodejs/changelog-maker/commit/e28b3f2813)] - 1.3.10 (Rod Vagg)
* [[\`ace3af943e\`](https://github.com/nodejs/changelog-maker/commit/ace3af943e)] - Merge pull request #13 from jamsyoung/private-repo-support (Rod Vagg)
* [[\`25ec5428bc\`](https://github.com/nodejs/changelog-maker/commit/25ec5428bc)] - default to repo scope always - revert previous changes (James Young)
* [[\`424d6c22c1\`](https://github.com/nodejs/changelog-maker/commit/424d6c22c1)] - add --private arg to set repo scope, update readme (James Young)
* [[\`7c8c5e6215\`](https://github.com/nodejs/changelog-maker/commit/7c8c5e6215)] - 1.3.9 (Rod Vagg)
`)
  t.end()
})

test('test filter-release', (t) => {
  t.equal(exec('--start-ref=v1.3.9 --end-ref=v1.3.10 --filter-release'),
    `* [[\`ace3af943e\`](https://github.com/nodejs/changelog-maker/commit/ace3af943e)] - Merge pull request #13 from jamsyoung/private-repo-support (Rod Vagg)
* [[\`25ec5428bc\`](https://github.com/nodejs/changelog-maker/commit/25ec5428bc)] - default to repo scope always - revert previous changes (James Young)
* [[\`424d6c22c1\`](https://github.com/nodejs/changelog-maker/commit/424d6c22c1)] - add --private arg to set repo scope, update readme (James Young)
`)
  t.end()
})

test('test simple', (t) => {
  t.equal(exec('--start-ref=v1.3.9 --end-ref=v1.3.10 --simple'),
    `* [e28b3f2813] - 1.3.10 (Rod Vagg)
* [ace3af943e] - Merge pull request #13 from jamsyoung/private-repo-support (Rod Vagg)
* [25ec5428bc] - default to repo scope always - revert previous changes (James Young)
* [424d6c22c1] - add --private arg to set repo scope, update readme (James Young)
* [7c8c5e6215] - 1.3.9 (Rod Vagg)
`)
  t.end()
})

test('test plaintext', (t) => {
  t.equal(exec('--start-ref=9c700d2 --end-ref=dd937e9 --group --filter-release --plaintext'),
    `feature:
  * refactor and improve --commit-url (Rod Vagg)
test:
  * update refs for testing (Rod Vagg)
`)
  t.end()
})

test('test group, semver labels, PR-URL', (t) => {
  t.equal(exec('--start-ref=v2.2.7 --end-ref=9c700d29 --group --filter-release --simple'),
    `* [cc442b6534] - (SEMVER-MINOR) minor nit (Rod Vagg) https://github.com/nodejs/node/pull/23715
* [4f2b7f8136] - deps: use strip-ansi instead of chalk.stripColor (Rod Vagg)
* [6898501e18] - deps: update deps, introduce test & lint deps (Rod Vagg)
* [9c700d2910] - feature: refactor and improve --commit-url (Rod Vagg)
* [5094524655] - feature: make the commit url configurable via an additional argument (Jim Nielsen) https://github.com/nodejs/changelog-maker/pull/55
* [42f248cf89] - src: use \`standard\` for linting (Rod Vagg)
* [64a8fdef3c] - test: basic test infrastructure (Rod Vagg)
`)
  t.end()
})

test('test simple group, semver labels, PR-URL', (t) => {
  t.equal(exec('--start-ref=v2.2.7 --end-ref=9c700d29 --group --filter-release'),
    `* [[\`cc442b6534\`](https://github.com/nodejs/changelog-maker/commit/cc442b6534)] - **(SEMVER-MINOR)** minor nit (Rod Vagg) [nodejs/node#23715](https://github.com/nodejs/node/pull/23715)
* [[\`4f2b7f8136\`](https://github.com/nodejs/changelog-maker/commit/4f2b7f8136)] - **deps**: use strip-ansi instead of chalk.stripColor (Rod Vagg)
* [[\`6898501e18\`](https://github.com/nodejs/changelog-maker/commit/6898501e18)] - **deps**: update deps, introduce test & lint deps (Rod Vagg)
* [[\`9c700d2910\`](https://github.com/nodejs/changelog-maker/commit/9c700d2910)] - **feature**: refactor and improve --commit-url (Rod Vagg)
* [[\`5094524655\`](https://github.com/nodejs/changelog-maker/commit/5094524655)] - **feature**: make the commit url configurable via an additional argument (Jim Nielsen) [#55](https://github.com/nodejs/changelog-maker/pull/55)
* [[\`42f248cf89\`](https://github.com/nodejs/changelog-maker/commit/42f248cf89)] - **src**: use \`standard\` for linting (Rod Vagg)
* [[\`64a8fdef3c\`](https://github.com/nodejs/changelog-maker/commit/64a8fdef3c)] - **test**: basic test infrastructure (Rod Vagg)
`)
  t.end()
})

test('test blank commit-url', (t) => {
  let actual = exec('--start-ref=v2.2.7 --end-ref=9c700d29 --filter-release --commit-url=http://foo.bar/').split('\n')
  actual.splice(0, actual.length - 3)
  actual = actual.join('\n')
  t.equal(actual,
    `* [[\`cc442b6534\`](http://foo.bar/)] - **(SEMVER-MINOR)** minor nit (Rod Vagg) [nodejs/node#23715](https://github.com/nodejs/node/pull/23715)
* [[\`5094524655\`](http://foo.bar/)] - **feature**: make the commit url configurable via an additional argument (Jim Nielsen) [#55](https://github.com/nodejs/changelog-maker/pull/55)
`)
  t.end()
})

test('test blank commit-url', (t) => {
  let actual = exec('--start-ref=v2.2.7 --end-ref=9c700d29 --filter-release --commit-url=https://yeehaw.com/{ref}/{ref}/{ghUser}/{ghRepo}/').split('\n')
  actual.splice(0, actual.length - 3)
  actual = actual.join('\n')
  t.equal(actual,
    `* [[\`cc442b6534\`](https://yeehaw.com/cc442b6534/cc442b6534/nodejs/changelog-maker/)] - **(SEMVER-MINOR)** minor nit (Rod Vagg) [nodejs/node#23715](https://github.com/nodejs/node/pull/23715)
* [[\`5094524655\`](https://yeehaw.com/5094524655/5094524655/nodejs/changelog-maker/)] - **feature**: make the commit url configurable via an additional argument (Jim Nielsen) [#55](https://github.com/nodejs/changelog-maker/pull/55)
`)
  t.end()
})

test('test backtick strings in commit messages', (t) => {
  t.equal(
    exec('--start-ref=ce886b5130 --end-ref=0717fdc946 --filter-release --commit-url=https://yeehaw.com/{ref}/{ref}/{ghUser}/{ghRepo}/'),
    `* [[\`0717fdc946\`](https://yeehaw.com/0717fdc946/0717fdc946/nodejs/changelog-maker/)] - **test**: \\\`commit\\_msg\\\` with an unescaped \\\` backtick char (Antoine du Hamel)
* [[\`9f1d897c88\`](https://yeehaw.com/9f1d897c88/9f1d897c88/nodejs/changelog-maker/)] - **test**: \\\`commit\\_msg\\\` with an escaped \\\\\\\` backtick char (Antoine du Hamel)
* [[\`4a3154bde0\`](https://yeehaw.com/4a3154bde0/4a3154bde0/nodejs/changelog-maker/)] - **test**: \`commit_msg\` starting with a backtick string (Antoine du Hamel)
* [[\`46384bb241\`](https://yeehaw.com/46384bb241/46384bb241/nodejs/changelog-maker/)] - **test**: commit\\_msg with \\\`backtick\\\\\\\` string (Antoine du Hamel)
* [[\`3b13c6804d\`](https://yeehaw.com/3b13c6804d/3b13c6804d/nodejs/changelog-maker/)] - **test**: commit\\_msg with \\\`\\\`backtick \\\` string\\\`\\\` (Antoine du Hamel)
* [[\`699ce8c377\`](https://yeehaw.com/699ce8c377/699ce8c377/nodejs/changelog-maker/)] - **test**: commit\\_msg with \`back_tick\` string (Antoine du Hamel)
* [[\`ce886b5130\`](https://yeehaw.com/ce886b5130/ce886b5130/nodejs/changelog-maker/)] - **test**: commit\\_msg with \`backtick\` string (Antoine du Hamel)
`)
  t.end()
})
<|endoftext|>


<commit_before>$(document).ready(function(){
	$('#removeUserFromGroup').on('click', removeUserFromList);
	$('#addUserToGroup').on('click', addUserToList);
	$('#changeGroupName').on('click', changeListName);
	$('#deleteGroupButton').on('click', deleteList);
	fillUsers();
});

function fillUsers() {
	$.ajax({
		url:'/manageList',
		type:'GET',
		dataType:'json',
		data:{'fillUsers':'true'},
		success:function(data, status, xhr) {
			var users = [];
			for (i = 0; i < data.length; ++i)
				users.push(data[i]);
			$( "#userToAdd" ).autocomplete({
				source: users,
				minLength: 2,
				autoFocus: true,
				_renderMenu: function( ul, items ) {
					var self = this;
					$.each( items, function( index, item ) {
					self._renderItem( ul, item );
					});
				}
			})
			.data('ui-autocomplete')._renderItem = function( ul, item ) {
				return $( "

" )
				.data( "ui-autocomplete-item", item )
				.append( '
' + item.label + '
' )
				.appendTo( ul );
			};
		},
		error:function(xhr, status, error) {
				alert(status);
				console.error(xhr, status, error);
		}
	});
}

function removeUserFromList() {
	var userName = $('#userSelect').val();
	if (userName==null || userName=="") {
		alert('Select a user to remove');
		return;
	}
	$.ajax({
		url:'/manageList',
		type:'GET',
		dataType:'json',
		data:{deleteUser:userName},
		success:function(data, status, xhr) {
			alert('User removed successfully');
		},
		error:function(xhr, status, error) {
				alert(status);
				console.error(xhr, status, error);
		}
	});
}

function addUserToList() {
	var userName = $('#userToAdd').val();
	if (userName==null || userName=="")
	{
		alert('Enter username to add');
		return;
	}
	$.ajax({
		url:'/manageList',
		type:'GET',
		dataType:'json',
		data:{addUser:userName},
		success:function(data, status, xhr) {
			if (data == 'userNotExist')
				alert('User doesn\'t exist');
			else if (data == 'userExist')
				alert('User already in group');
			else
				alert('User added successfully');
		},
		error:function(xhr, status, error) {
				alert(status);
				console.error(xhr, status, error);
		}
	});
}

function changeListName() {
	var newGroupName = $('#newNameForGroup').val();
	if (newGroupName==null || newGroupName=="")
	{
		alert('Enter a name');
		return;
	}
	$.ajax({
		url:'/manageList',
		type:'GET',
		dataType:'json',
		data:{newGroupName:newGroupName},
		success:function(data, status, xhr) {
			alert('Name changed successfully');
		},
		error:function(xhr, status, error) {
				alert(status);
				console.error(xhr, status, error);
		}
	});
}

function deleteList() {
		if (confirm('Are you sure you want to delete this list?')) {
			confirmDeletion="yes";
		}
		else {
			return;
		}
		$.ajax({
		url:'/manageList',
		type:'GET',
		dataType:'json',
		data:{confirmDeletion:confirmDeletion},
		success:function(data, status, xhr) {
			if (data == "statusDeleted")
				alert('dsds');
				window.location = "/index";
		},
		error:function(xhr, status, error) {
				alert(status);
				console.error(xhr, status, error);
		}
	});
}

<commit_msg>fixing some bug in autocomplete<commit_after>$(document).ready(function(){
	$('#removeUserFromGroup').on('click', removeUserFromList);
	$('#addUserToGroup').on('click', addUserToList);
	$('#changeGroupName').on('click', changeListName);
	$('#deleteGroupButton').on('click', deleteList);
	fillUsers();
});

function fillUsers() {
	$.ajax({
		url:'/manageList',
		type:'GET',
		dataType:'json',
		data:{'fillUsers':'true'},
		success:function(data, status, xhr) {
			var users = [];
			for (i = 0; i < data.length; ++i)
				users.push(data[i]);
			$( "#userToAdd" ).autocomplete({
				source: users,
				minLength: 2,
				autoFocus: true
			})
			.data('ui-autocomplete')._renderItem = function( ul, item ) {
				return $( "

" )
				.data( "ui-autocomplete-item", item )
				.append( '
' + item.label + '
' )
				.appendTo( ul );
			};
		},
		error:function(xhr, status, error) {
				alert(status);
				console.error(xhr, status, error);
		}
	});
}

function removeUserFromList() {
	var userName = $('#userSelect').val();
	if (userName==null || userName=="") {
		alert('Select a user to remove');
		return;
	}
	$.ajax({
		url:'/manageList',
		type:'GET',
		dataType:'json',
		data:{deleteUser:userName},
		success:function(data, status, xhr) {
			alert('User removed successfully');
		},
		error:function(xhr, status, error) {
				alert(status);
				console.error(xhr, status, error);
		}
	});
}

function addUserToList() {
	var userName = $('#userToAdd').val();
	if (userName==null || userName=="")
	{
		alert('Enter username to add');
		return;
	}
	$.ajax({
		url:'/manageList',
		type:'GET',
		dataType:'json',
		data:{addUser:userName},
		success:function(data, status, xhr) {
			if (data == 'userNotExist')
				alert('User doesn\'t exist');
			else if (data == 'userExist')
				alert('User already in group');
			else
				alert('User added successfully');
		},
		error:function(xhr, status, error) {
				alert(status);
				console.error(xhr, status, error);
		}
	});
}

function changeListName() {
	var newGroupName = $('#newNameForGroup').val();
	if (newGroupName==null || newGroupName=="")
	{
		alert('Enter a name');
		return;
	}
	$.ajax({
		url:'/manageList',
		type:'GET',
		dataType:'json',
		data:{newGroupName:newGroupName},
		success:function(data, status, xhr) {
			alert('Name changed successfully');
		},
		error:function(xhr, status, error) {
				alert(status);
				console.error(xhr, status, error);
		}
	});
}

function deleteList() {
		if (confirm('Are you sure you want to delete this list?')) {
			confirmDeletion="yes";
		}
		else {
			return;
		}
		$.ajax({
		url:'/manageList',
		type:'GET',
		dataType:'json',
		data:{confirmDeletion:confirmDeletion},
		success:function(data, status, xhr) {
			if (data == "statusDeleted")
				alert('dsds');
				window.location = "/index";
		},
		error:function(xhr, status, error) {
				alert(status);
				console.error(xhr, status, error);
		}
	});
}

<|endoftext|>


<commit_before>/* globals describe, it */

'use strict'

var expect = require('chai').expect
var op = require('./index.js')

describe('set', function () {
  it('should set a deep key without modifying the original object', function () {
    var obj = {
      a: {
        b: 1
      },
      c: {
        d: 2
      }
    }

    var newObj = op.set(obj, 'a.b', 3)

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({b: 1})
    // this should be the same
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a.b).to.be.equal(3)
  })

  it('should set a deep array', function () {
    var obj = {
      a: {
        b: [1, 2, 3]
      },
      c: {
        d: 2
      }
    }

    var newObj = op.set(obj, 'a.b.1', 4)

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.a.b).not.to.be.equal(obj.a.b)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a.b).to.be.eql([1, 4, 3])
  })

  it('should create intermediate objects and array', function () {
    var obj = {
      a: {},
      c: {
        d: 2
      }
    }

    var newObj = op.set(obj, 'a.b.1.f', 'a')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({})
    expect(newObj.a).to.be.eql({b: [, {f: 'a'}]}) // eslint-disable-line no-sparse-arrays
  })

  it('should return the original object if passed an empty path', function () {
    var obj = {}

    expect(op.set(obj, '', 'yo')).to.be.equal(obj)
  })

  it('should set at a numeric path', function () {
    expect(op.set([], 0, 'yo')).to.deep.equal(['yo'])
  })

  it('should update a deep key', function () {
    var obj = {
      a: {
        b: 1
      },
      c: {
        d: 2
      }
    }

    var newObj = op.update(obj, 'a.b', function (value) {
      return value + 1
    })

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({b: 1})
    // this should be the same
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a.b).to.be.equal(2)
  })
})

describe('insert', function () {
  it('should insert value into existing array without modifying the object', function () {
    var obj = {
      a: ['a'],
      c: {}
    }

    var newObj = op.insert(obj, 'a', 'b', 0)

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql(['b', 'a'])
  })

  it('should create intermediary array', function () {
    var obj = {
      a: [],
      c: {}
    }

    var newObj = op.insert(obj, 'a.0.1', 'b')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql([[, ['b']]]) // eslint-disable-line no-sparse-arrays
  })

  it('should insert in another index', function () {
    var obj = {
      a: 'b',
      b: {
        c: [],
        d: ['a', 'b'],
        e: [{}, {f: 'g'}],
        f: 'i'
      }
    }

    var newObj = op.insert(obj, 'b.d', 'asdf', 1)

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.b.d).to.be.eql(['a', 'asdf', 'b'])
  })

  it('should handle sparse array', function () {
    var obj = {
      a: 'b',
      b: {
        c: [],
        d: ['a', 'b'],
        e: [{}, {f: 'g'}],
        f: 'i'
      }
    }
    obj.b.d = new Array(4)
    obj.b.d[0] = 'a'
    obj.b.d[1] = 'b'

    var newObj = op.insert(obj, 'b.d', 'asdf', 3)
    expect(newObj).not.to.be.equal(obj)
    expect(newObj.b.d).to.be.eql(['a', 'b', , 'asdf']) // eslint-disable-line no-sparse-arrays
  })

  it('should throw if asked to insert into something other than an array',
    function () {
      expect(function () {
        op.insert({ foo: 'bar' }, 'foo', 'baz')
      }).to.throw()
    })

  it('should return the original object if passed an empty path', function () {
    var obj = {}

    expect(op.insert(obj, '')).to.be.equal(obj)
  })

  it('should insert at a numeric path', function () {
    expect(op.insert([[23, 42]], 0, 'yo', 1)).to.deep.equal([[23, 'yo', 42]])
  })
})

describe('push', function () {
  it('should push values without modifying the object', function () {
    var obj = {
      a: ['a'],
      c: {}
    }

    var newObj = op.push(obj, 'a', 'b')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql(['a', 'b'])
  })

  it('should create intermediate objects/arrays', function () {
    var obj = {
      a: [],
      c: {}
    }

    var newObj = op.push(obj, 'a.0.1', 'b')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql([[, ['b']]]) // eslint-disable-line no-sparse-arrays
  })

  it('should return the original object if passed an empty path', function () {
    var obj = {}

    expect(op.push(obj, '', 'yo')).to.be.equal(obj)
  })

  it('should push at a numeric path', function () {
    expect(op.insert([[]], 0, 'yo')).to.deep.equal([['yo']])
  })
})

describe('del', function () {
  it('should delete deep values without modifying the object', function () {
    var obj = {
      a: {
        d: 1,
        f: 2
      },
      c: {}
    }

    var newObj = op.del(obj, 'a.d')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql({f: 2})
  })

  it('should delete deep values in array without modifying the object', function () {
    var obj = {
      a: ['a'],
      c: {}
    }

    var newObj = op.del(obj, 'a.0')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql([])
  })

  it('should return the original object if passed an empty path', function () {
    var obj = {}

    expect(op.del(obj, '')).to.be.equal(obj)
  })

  it('should del at a numeric path', function () {
    expect(op.del([23, 'yo', 42], 1)).to.deep.equal([23, 42])
  })

  it('should delete falsy value', function () {
    expect(op.del(['', false], 1)).to.deep.equal([''])
  })
})

describe('assign', function () {
  it('should assign an object without modifying the original object', function () {
    var obj = {
      a: {
        b: 1
      },
      c: {
        d: 2
      }
    }

    var newObj = op.assign(obj, 'a', { b: 3 })

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({b: 1})
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a.b).to.be.equal(3)
  })

  it('should keep existing fields that are not overwritten', function () {
    var obj = {
      a: {
        b: 1
      }
    }

    var newObj = op.assign(obj, 'a', { c: 2 })

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({b: 1})
    expect(newObj.a).to.be.eql({ b: 1, c: 2 })
  })

  it('should create intermediate objects', function () {
    var obj = {
      a: {},
      c: {
        d: 2
      }
    }

    var newObj = op.assign(obj, 'a.b', { f: 'a' })

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({})
    expect(newObj.a).to.be.eql({b: {f: 'a'}})
  })

  it('should return the original object if passed an empty path', function () {
    var obj = {}

    expect(op.assign(obj, '', {})).to.be.equal(obj)
  })

  it('should assign at a numeric path', function () {
    expect(op.assign([{
      foo: 'bar'
    }], 0, {
      foo: 'baz',
      fiz: 'biz'
    })).to.deep.equal([{
      foo: 'baz',
      fiz: 'biz'
    }])
  })

  it('does not assign inherited properties', function () {
    var base = {
      fiz: 'biz'
    }

    var source = Object.create(base)
    source.frob = 'nard'

    var obj = {
      foo: {}
    }

    expect(op.assign(obj, 'foo', source)).to.deep.equal({
      foo: {
        frob: 'nard'
      }
    })
  })
})

describe('bind', function () {
  it('should execute all methods on the bound object', function () {
    var obj = {
      a: {
        d: 1,
        f: 2
      },
      c: {}
    }

    var newObj = op(obj).set('a.q', 'q').del('a.d').update('a.f', function (v) {
      return v + 1
    }).value()

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql({f: 3, q: 'q'})
  })

  it('should return the bound object if no operations made', function () {
    var obj = {}

    expect(op(obj).value()).to.be.equal(obj)
  })

  it('should throw if an operation is attempted after `value` called', function () {
    var transaction = op({
      foo: 'bar',
      fiz: [],
      frob: {}
    })

    transaction.value()

    expect(function () {
      transaction.set('foo', 'baz')
    }).to.throw()

    expect(function () {
      transaction.push('fiz', 'biz')
    }).to.throw()

    expect(function () {
      transaction.insert('fiz', 'biz', 23)
    }).to.throw()

    expect(function () {
      transaction.del('foo')
    }).to.throw()

    expect(function () {
      transaction.update('foo', function (v) {
        return v + 'bar'
      })
    }).to.throw()

    expect(function () {
      transaction.assign('frob', {
        nard: 23
      })
    }).to.throw()
  })
})
<commit_msg>Add istanbul ignore<commit_after>/* globals describe, it */

'use strict'

var expect = require('chai').expect
var op = require('./index.js')

describe('set', function () {
  it('should set a deep key without modifying the original object', function () {
    var obj = {
      a: {
        b: 1
      },
      c: {
        d: 2
      }
    }

    var newObj = op.set(obj, 'a.b', 3)

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({b: 1})
    // this should be the same
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a.b).to.be.equal(3)
  })

  it('should set a deep array', function () {
    var obj = {
      a: {
        b: [1, 2, 3]
      },
      c: {
        d: 2
      }
    }

    var newObj = op.set(obj, 'a.b.1', 4)

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.a.b).not.to.be.equal(obj.a.b)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a.b).to.be.eql([1, 4, 3])
  })

  it('should create intermediate objects and array', function () {
    var obj = {
      a: {},
      c: {
        d: 2
      }
    }

    var newObj = op.set(obj, 'a.b.1.f', 'a')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({})
    expect(newObj.a).to.be.eql({b: [, {f: 'a'}]}) // eslint-disable-line no-sparse-arrays
  })

  it('should return the original object if passed an empty path', function () {
    var obj = {}

    expect(op.set(obj, '', 'yo')).to.be.equal(obj)
  })

  it('should set at a numeric path', function () {
    expect(op.set([], 0, 'yo')).to.deep.equal(['yo'])
  })

  it('should update a deep key', function () {
    var obj = {
      a: {
        b: 1
      },
      c: {
        d: 2
      }
    }

    var newObj = op.update(obj, 'a.b', function (value) {
      return value + 1
    })

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({b: 1})
    // this should be the same
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a.b).to.be.equal(2)
  })
})

describe('insert', function () {
  it('should insert value into existing array without modifying the object', function () {
    var obj = {
      a: ['a'],
      c: {}
    }

    var newObj = op.insert(obj, 'a', 'b', 0)

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql(['b', 'a'])
  })

  it('should create intermediary array', function () {
    var obj = {
      a: [],
      c: {}
    }

    var newObj = op.insert(obj, 'a.0.1', 'b')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql([[, ['b']]]) // eslint-disable-line no-sparse-arrays
  })

  it('should insert in another index', function () {
    var obj = {
      a: 'b',
      b: {
        c: [],
        d: ['a', 'b'],
        e: [{}, {f: 'g'}],
        f: 'i'
      }
    }

    var newObj = op.insert(obj, 'b.d', 'asdf', 1)

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.b.d).to.be.eql(['a', 'asdf', 'b'])
  })

  it('should handle sparse array', function () {
    var obj = {
      a: 'b',
      b: {
        c: [],
        d: ['a', 'b'],
        e: [{}, {f: 'g'}],
        f: 'i'
      }
    }
    obj.b.d = new Array(4)
    obj.b.d[0] = 'a'
    obj.b.d[1] = 'b'

    var newObj = op.insert(obj, 'b.d', 'asdf', 3)
    expect(newObj).not.to.be.equal(obj)
    expect(newObj.b.d).to.be.eql(['a', 'b', , 'asdf']) // eslint-disable-line no-sparse-arrays
  })

  it('should throw if asked to insert into something other than an array',
    function () {
      expect(function () {
        op.insert({ foo: 'bar' }, 'foo', 'baz')
      }).to.throw()
    })

  it('should return the original object if passed an empty path', function () {
    var obj = {}

    expect(op.insert(obj, '')).to.be.equal(obj)
  })

  it('should insert at a numeric path', function () {
    expect(op.insert([[23, 42]], 0, 'yo', 1)).to.deep.equal([[23, 'yo', 42]])
  })
})

describe('push', function () {
  it('should push values without modifying the object', function () {
    var obj = {
      a: ['a'],
      c: {}
    }

    var newObj = op.push(obj, 'a', 'b')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql(['a', 'b'])
  })

  it('should create intermediate objects/arrays', function () {
    var obj = {
      a: [],
      c: {}
    }

    var newObj = op.push(obj, 'a.0.1', 'b')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql([[, ['b']]]) // eslint-disable-line no-sparse-arrays
  })

  it('should return the original object if passed an empty path', function () {
    var obj = {}

    expect(op.push(obj, '', 'yo')).to.be.equal(obj)
  })

  it('should push at a numeric path', function () {
    expect(op.insert([[]], 0, 'yo')).to.deep.equal([['yo']])
  })
})

describe('del', function () {
  it('should delete deep values without modifying the object', function () {
    var obj = {
      a: {
        d: 1,
        f: 2
      },
      c: {}
    }

    var newObj = op.del(obj, 'a.d')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql({f: 2})
  })

  it('should delete deep values in array without modifying the object', function () {
    var obj = {
      a: ['a'],
      c: {}
    }

    var newObj = op.del(obj, 'a.0')

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql([])
  })

  it('should return the original object if passed an empty path', function () {
    var obj = {}

    expect(op.del(obj, '')).to.be.equal(obj)
  })

  it('should del at a numeric path', function () {
    expect(op.del([23, 'yo', 42], 1)).to.deep.equal([23, 42])
  })

  it('should delete falsy value', function () {
    expect(op.del(['', false], 1)).to.deep.equal([''])
  })
})

describe('assign', function () {
  it('should assign an object without modifying the original object', function () {
    var obj = {
      a: {
        b: 1
      },
      c: {
        d: 2
      }
    }

    var newObj = op.assign(obj, 'a', { b: 3 })

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({b: 1})
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a.b).to.be.equal(3)
  })

  it('should keep existing fields that are not overwritten', function () {
    var obj = {
      a: {
        b: 1
      }
    }

    var newObj = op.assign(obj, 'a', { c: 2 })

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({b: 1})
    expect(newObj.a).to.be.eql({ b: 1, c: 2 })
  })

  it('should create intermediate objects', function () {
    var obj = {
      a: {},
      c: {
        d: 2
      }
    }

    var newObj = op.assign(obj, 'a.b', { f: 'a' })

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(obj.a).to.be.eql({})
    expect(newObj.a).to.be.eql({b: {f: 'a'}})
  })

  it('should return the original object if passed an empty path', function () {
    var obj = {}

    expect(op.assign(obj, '', {})).to.be.equal(obj)
  })

  it('should assign at a numeric path', function () {
    expect(op.assign([{
      foo: 'bar'
    }], 0, {
      foo: 'baz',
      fiz: 'biz'
    })).to.deep.equal([{
      foo: 'baz',
      fiz: 'biz'
    }])
  })

  it('does not assign inherited properties', function () {
    var base = {
      fiz: 'biz'
    }

    var source = Object.create(base)
    source.frob = 'nard'

    var obj = {
      foo: {}
    }

    expect(op.assign(obj, 'foo', source)).to.deep.equal({
      foo: {
        frob: 'nard'
      }
    })
  })
})

describe('bind', function () {
  it('should execute all methods on the bound object', function () {
    var obj = {
      a: {
        d: 1,
        f: 2
      },
      c: {}
    }

    var newObj = op(obj).set('a.q', 'q').del('a.d').update('a.f', function (v) {
      return v + 1
    }).value()

    expect(newObj).not.to.be.equal(obj)
    expect(newObj.a).not.to.be.equal(obj.a)
    expect(newObj.c).to.be.equal(obj.c)

    expect(newObj.a).to.be.eql({f: 3, q: 'q'})
  })

  it('should return the bound object if no operations made', function () {
    var obj = {}

    expect(op(obj).value()).to.be.equal(obj)
  })

  it('should throw if an operation is attempted after `value` called', function () {
    var transaction = op({
      foo: 'bar',
      fiz: [],
      frob: {}
    })

    transaction.value()

    expect(function () {
      transaction.set('foo', 'baz')
    }).to.throw()

    expect(function () {
      transaction.push('fiz', 'biz')
    }).to.throw()

    expect(function () {
      transaction.insert('fiz', 'biz', 23)
    }).to.throw()

    expect(function () {
      transaction.del('foo')
    }).to.throw()

    expect(function () {
      /* istanbul ignore next */
      transaction.update('foo', function (v) {
        return v + 'bar'
      })
    }).to.throw()

    expect(function () {
      transaction.assign('frob', {
        nard: 23
      })
    }).to.throw()
  })
})
<|endoftext|>


<commit_before>'use strict';

Connector.playerSelector = '#player';

Connector.artistTrackSelector = '.player-current-title';

Connector.getArtistTrack = () => {
	const text = $(Connector.artistTrackSelector).text();
	const m = text.match(/ - /g);
	if (m && m.length === 2) {
		const arr = text.split(' - ');
		return { artist: arr[1], track: arr[2] };
	}
	return Util.splitArtistTrack(text);
};

Connector.pauseButtonSelector = '.player-pause';

Connector.onReady = Connector.onStateChanged;
<commit_msg>Fix byte.fm connector following update (#2621)<commit_after>'use strict';

Connector.playerSelector = '.player';

Connector.artistTrackSelector = '.player-current-title';

Connector.isPlaying = () => Util.getTextFromSelectors('.player-play-button') !== 'play';

Connector.onReady = Connector.onStateChanged;
<|endoftext|>


<commit_before>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length < 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<commit_msg>🤖(fix): 2017-12-3 21:29:57<commit_after>const test = require('ava');
const random = require('./helpers/random');
const all = require('./products');

test('all()', t => {
  t.true(all.length > 0);
});

test('random()', t => {
  t.truthy(random(all));
  t.not(random(all), random(all));
});
<|endoftext|>


<commit_before>var neoip	= require('./neoip');
var sys		= require('sys');

neoip.discover_app("oload", function(version, strerror){
	sys.puts("version:"+version);
	sys.puts("strerror:"+strerror);
});
<commit_msg>test.js: beautifullation 	modified:   test.js<commit_after>var neoip	= require('./neoip');
var sys		= require('sys');

neoip.discover_app("casti", function(version, strerror){
	// TODO what about the port ?
	sys.puts("version:"+version);
	sys.puts("strerror:"+strerror);
});
<|endoftext|>


<commit_before>var should = require('should')
var cheerio = require('cheerio')
var proxyquire = require('proxyquire')
var J$X = proxyquire('./jDollarX', { 'jquery': cheerio })

describe('Build with tag name', function () {
  it('should works', function () {
    var $el =

    $el.is('div').should.ok
  })

  it('should works with nested elements', function () {
    var $el =

    $el.children('span').length.should.be.equal(1)
  })
})

describe('Build with content', function () {
  it('should works with text', function () {
    var $el =
foo

    $el.text().should.be.equal('foo')
  })

  it('should works with encoded text', function () {
    var $el =
{""}

    $el.text().should.be.equal('')
  })

  it('should works with number', function () {
    var $el =
{2}

    $el.text().should.be.equal('2')
  })

  it('should works with boolean', function () {
    var $true =
{true}

    var $false =
{false}

    $true.text().should.be.equal('true')
    $false.text().should.be.equal('false')
  })

  it('should works with null', function () {
    var $el =
{null}

    $el.text().should.be.empty
  })

  it('should works with undefined', function () {
    var $el =
{void 0}

    $el.text().should.be.empty
  })

  it('should works with custom attributes', function () {
    var $el =

    $el.attr('data-foo').should.be.equal('bar')
  })

  it('should works with class', function () {
    var classList = 'foo bar'
    var $el =

    $el.hasClass('bar').should.be.equal(true)
  })

  it('should works with style', function () {
    var inlineStyle = {color: '#fff'}
    var $el =

    $el.css('color').should.be.equal('#fff')
  })

  it('should works with attributes & expression', function () {
    var $true =

    var $false =

    $true.attr('data-foo').should.be.equal('true')
    $false.attr('data-foo').should.be.equal('false')
  })
})
<commit_msg>split attribute test<commit_after>var should = require('should')
var cheerio = require('cheerio')
var proxyquire = require('proxyquire')
var J$X = proxyquire('./jDollarX', { 'jquery': cheerio })

describe('Build with tag name', function () {
  it('should works', function () {
    var $el =

    $el.is('div').should.ok
  })

  it('should works with nested elements', function () {
    var $el =

    $el.children('span').length.should.be.equal(1)
  })
})

describe('Build with content', function () {
  it('should works with text', function () {
    var $el =
foo

    $el.text().should.be.equal('foo')
  })

  it('should works with encoded text', function () {
    var $el =
{""}

    $el.text().should.be.equal('')
  })

  it('should works with number', function () {
    var $el =
{2}

    $el.text().should.be.equal('2')
  })

  it('should works with boolean', function () {
    var $true =
{true}

    var $false =
{false}

    $true.text().should.be.equal('true')
    $false.text().should.be.equal('false')
  })

  it('should works with null', function () {
    var $el =
{null}

    $el.text().should.be.empty
  })

  it('should works with undefined', function () {
    var $el =
{void 0}

    $el.text().should.be.empty
  })
})

describe('Build with attributes', function () {
  it('should works with custom attributes', function () {
    var $el =

    $el.attr('data-foo').should.be.equal('bar')
  })

  it('should works with class', function () {
    var classList = 'foo bar'
    var $el =

    $el.hasClass('bar').should.be.equal(true)
  })

  it('should works with style', function () {
    var inlineStyle = {color: '#fff'}
    var $el =

    $el.css('color').should.be.equal('#fff')
  })

  it('should works with attributes & expression', function () {
    var $true =

    var $false =

    $true.attr('data-foo').should.be.equal('true')
    $false.attr('data-foo').should.be.equal('false')
  })
})
<|endoftext|>


<commit_before>// Load in dependencies
var path = require('path');
var async = require('async');
var Presentation = require('./presentation');
function noop() {}

function CliPresentation(optionsStr) {
  // Fallback optionsStr
  optionsStr = optionsStr || CliPresentation.pathDefault;

  // Upcast options
  var options = optionsStr;
  if (typeof optionsStr === 'string') {
    var optionsPath = path.resolve(process.cwd(), optionsStr);
    options = require(optionsPath);
  }

  // Create a presentation and save options for later
  this.presentation = new Presentation(options);
  this.options = options;
}
CliPresentation.pathDefault = 'cli-presentation';
CliPresentation.prototype = {
  // Tolerant slide navigator
  goToSlide: function (_slide, cb) {
    var slides, slide;
    var that = this;
    async.series([
      function fallbackSlide (cb) {
        // Fallback slide to active one
        if (_slide === undefined) {
          that.presentation.getCurrentIndex(function (err, val) {
            // Save the info and callback
            _slide = val || 0;
            cb(err);
          });
        } else {
          cb();
        }
      },
      function coerceSlide (cb) {
        // Parse the slide and guarantee it is within our bounds
        slide = parseInt(_slide, 10);
        if (isNaN(slide)) {
          return cb(new Error('Slide "' + _slide + '" parsed to NaN'));
        }
        slide = Math.max(0, slide);
        slide = Math.min(slide, that.presentation.length - 1);
        cb();
      },
      function loadSlide (cb) {
        // Load and run the slide
        var slideObj = that.presentation.getSlide(slide);
        try {
          var output = slideObj.fn();
          if (typeof output === 'string') {
            console.log(output);
          }
        } catch (e) {
          return cb(e);
        }
        cb();
      },
      function saveState (cb) {
        // Save the slide state
        that.presentation.setCurrentIndex(slide, cb);
      }
    ], function handleErrors (err) {
      // If there is a callback, send back the error
      if (cb) {
        cb(err);
      // Otherwise, if there was an error, throw it
      } else if (err) {
        throw err;
      }
    });
  },

  // Define common actions
  // TODO: Extend this into `byName`
  goToCurrent: function () {
    this.goToIndex();
  },
  goToIndex: function (index) {
    this.goToSlide(index);
  },
  goToFirst: function () {
    this.goToSlide(0);
  },
  goToLast: function () {
    this.goToSlide(this.presentation.length - 1);
  },
  goToNext: function () {
    var that = this;
    this.presentation.getCurrentIndex(function (err, val) {
      if (err) { throw err; }
      var next = val === undefined ? 0 : val + 1;
      that.goToSlide(next);
    });
  },
  goToPrevious: function () {
    var that = this;
    this.presentation.getCurrentIndex(function (err, val) {
      if (err) { throw err; }
      var prev = val === undefined ? 0 : val - 1;
      that.goToSlide(prev);
    });
  },
  status: function () {
    var that = this;
    this.presentation.getCurrentIndex(function (err, val) {
      if (err) { throw err; }

      // TODO: Use presentation.slides
      val = val || 0;
      that.options.slides.forEach(function (name, i) {
        var active = val === i ? '*' : ' ';
        console.log(active + ' ' + i + ' ' + name);
      });
    });
  }
};

CliPresentation.cli = function () {
  // Create a program
  var program = require('commander')
                  .option('-c, --config <config>', 'Path to configuration file (accepts .js, .json, .yml)');

  program.runPresentationMethod = function (method) {
    return function runPresentationMethodFn (/* param1, ..., argv */) {
      // Attempt to look at the top level argv
      var rawArgv = arguments[arguments.length - 1];
      var argv = rawArgv.parent || rawArgv;

      // Create a presentation and run the method
      var presentation = new CliPresentation(argv.config);
      presentation[method].apply(presentation, arguments);
    };
  };

  // Define CLI commands
  var that = this;
  program
    .command('slide <slide>')
    .description('Jump to a specific slide')
    .action(program.runPresentationMethod('goToIndex'));

  program
    .command('first')
    .description('Go back to the beginning')
    .action(program.runPresentationMethod('goToFirst'));

  program
    .command('last')
    .description('Jump to the final slide')
    .action(program.runPresentationMethod('goToLast'));

  program
    .command('next')
    .description('Move following by one slide')
    .action(program.runPresentationMethod('goToNext'));

  program
    .command('previous')
    .description('Move back by one slide')
    .action(program.runPresentationMethod('goToPrevious'));

  program
    .command('back')
    .description('Alias for previous')
    .action(program.runPresentationMethod('goToPrevious'));

  program
    .command('status')
    .description('Get overview of slides')
    .action(program.runPresentationMethod('status'));

  // Overwrite parse such that it will use the same slide
  program._parse = program.parse;
  program.parse = function (argv) {
    // If there was no command, re-run the current slide
    if (argv.length === 2) {
      return program.runPresentationMethod('goToCurrent')(argv);
    }

    // Otherwise, run the normal parse
    return program._parse.apply(this, arguments);
  };

  // Return our program
  return program;
};

module.exports = CliPresentation;<commit_msg>Repaired regression for cwd<commit_after>// Load in dependencies
var path = require('path');
var async = require('async');
var Presentation = require('./presentation');
function noop() {}

function CliPresentation(optionsStr) {
  // Fallback optionsStr
  optionsStr = optionsStr || CliPresentation.pathDefault;

  // Upcast options
  var options = optionsStr;
  if (typeof optionsStr === 'string') {
    var optionsPath = path.resolve(process.cwd(), optionsStr);
    options = require(optionsPath);
    options.cwd = options.cwd || path.dirname(optionsPath);
  }

  // Create a presentation and save options for later
  this.presentation = new Presentation(options);
  this.options = options;
}
CliPresentation.pathDefault = 'cli-presentation';
CliPresentation.prototype = {
  // Tolerant slide navigator
  goToSlide: function (_slide, cb) {
    var slides, slide;
    var that = this;
    async.series([
      function fallbackSlide (cb) {
        // Fallback slide to active one
        if (_slide === undefined) {
          that.presentation.getCurrentIndex(function (err, val) {
            // Save the info and callback
            _slide = val || 0;
            cb(err);
          });
        } else {
          cb();
        }
      },
      function coerceSlide (cb) {
        // Parse the slide and guarantee it is within our bounds
        slide = parseInt(_slide, 10);
        if (isNaN(slide)) {
          return cb(new Error('Slide "' + _slide + '" parsed to NaN'));
        }
        slide = Math.max(0, slide);
        slide = Math.min(slide, that.presentation.length - 1);
        cb();
      },
      function loadSlide (cb) {
        // Load and run the slide
        var slideObj = that.presentation.getSlide(slide);
        try {
          var output = slideObj.fn();
          if (typeof output === 'string') {
            console.log(output);
          }
        } catch (e) {
          return cb(e);
        }
        cb();
      },
      function saveState (cb) {
        // Save the slide state
        that.presentation.setCurrentIndex(slide, cb);
      }
    ], function handleErrors (err) {
      // If there is a callback, send back the error
      if (cb) {
        cb(err);
      // Otherwise, if there was an error, throw it
      } else if (err) {
        throw err;
      }
    });
  },

  // Define common actions
  // TODO: Extend this into `byName`
  goToCurrent: function () {
    this.goToIndex();
  },
  goToIndex: function (index) {
    this.goToSlide(index);
  },
  goToFirst: function () {
    this.goToSlide(0);
  },
  goToLast: function () {
    this.goToSlide(this.presentation.length - 1);
  },
  goToNext: function () {
    var that = this;
    this.presentation.getCurrentIndex(function (err, val) {
      if (err) { throw err; }
      var next = val === undefined ? 0 : val + 1;
      that.goToSlide(next);
    });
  },
  goToPrevious: function () {
    var that = this;
    this.presentation.getCurrentIndex(function (err, val) {
      if (err) { throw err; }
      var prev = val === undefined ? 0 : val - 1;
      that.goToSlide(prev);
    });
  },
  status: function () {
    var that = this;
    this.presentation.getCurrentIndex(function (err, val) {
      if (err) { throw err; }

      // TODO: Use presentation.slides
      val = val || 0;
      that.options.slides.forEach(function (name, i) {
        var active = val === i ? '*' : ' ';
        console.log(active + ' ' + i + ' ' + name);
      });
    });
  }
};

CliPresentation.cli = function () {
  // Create a program
  var program = require('commander')
                  .option('-c, --config <config>', 'Path to configuration file (accepts .js, .json, .yml)');

  program.runPresentationMethod = function (method) {
    return function runPresentationMethodFn (/* param1, ..., argv */) {
      // Attempt to look at the top level argv
      var rawArgv = arguments[arguments.length - 1];
      var argv = rawArgv.parent || rawArgv;

      // Create a presentation and run the method
      var presentation = new CliPresentation(argv.config);
      presentation[method].apply(presentation, arguments);
    };
  };

  // Define CLI commands
  var that = this;
  program
    .command('slide <slide>')
    .description('Jump to a specific slide')
    .action(program.runPresentationMethod('goToIndex'));

  program
    .command('first')
    .description('Go back to the beginning')
    .action(program.runPresentationMethod('goToFirst'));

  program
    .command('last')
    .description('Jump to the final slide')
    .action(program.runPresentationMethod('goToLast'));

  program
    .command('next')
    .description('Move following by one slide')
    .action(program.runPresentationMethod('goToNext'));

  program
    .command('previous')
    .description('Move back by one slide')
    .action(program.runPresentationMethod('goToPrevious'));

  program
    .command('back')
    .description('Alias for previous')
    .action(program.runPresentationMethod('goToPrevious'));

  program
    .command('status')
    .description('Get overview of slides')
    .action(program.runPresentationMethod('status'));

  // Overwrite parse such that it will use the same slide
  program._parse = program.parse;
  program.parse = function (argv) {
    // If there was no command, re-run the current slide
    if (argv.length === 2) {
      return program.runPresentationMethod('goToCurrent')(argv);
    }

    // Otherwise, run the normal parse
    return program._parse.apply(this, arguments);
  };

  // Return our program
  return program;
};

module.exports = CliPresentation;<|endoftext|>