<commit_before>var stack = [], push = [].push, token = {}

function Cadence (parent, finalizers, self, steps, vargs, callback) {
    this.parent = parent
    this.finalizers = finalizers
    this.self = self
    this.steps = steps
    this.callback = callback
    this.loop = false
    this.cadence = this
    this.cadences = []
    this.results = []
    this.errors = []
    this.called = 0
    this.index = 0
    this.sync = true
    this.waiting = false
    this.vargs = vargs
}

Cadence.prototype.resolveCallback = function (result, vargs) {
    var error = vargs.shift()
    if (error == null) {
        result.vargs = vargs
    } else {
        this.errors.push(error)
    }
    if (++this.called === this.results.length) {
        if (this.waiting) {
            invoke(this)
        } else {
            this.sync = true
        }
    }
}

Cadence.prototype.createCallback = function () {
    var self = this
    var result = { vargs: [] }

    self.results.push(result)
    self.sync = false

    return callback

    function callback () {
        var I = arguments.length
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        self.resolveCallback(result, vargs)

        return

        // This try/catch will prevent V8 from marking this function of
        // optimization because it will only ever run once.
        /* istanbul ignore next */
        try {} catch(e) {}
    }
}

Cadence.prototype.createCadence = function (vargs) {
    var callback = this.createCallback()

    var cadence = new Cadence(this, this.finalizers, this.self, vargs, [], callback)

    this.cadences.push(cadence)

    return looper

    function looper () {
        var I = arguments.length
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        return cadence.startLoop(vargs)
    }
}

Cadence.prototype.startLoop = function (vargs) {
    this.loop = true
    this.vargs = vargs

    return {
        continue: { loopy: token, repeat: true, loop: false, cadence: this },
        break: { loopy: token, repeat: false, loop: false, cadence: this }
    }
}

function async () {
    var cadence = stack[stack.length - 1]
    var I = arguments.length
    if (I) {
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        return cadence.createCadence(vargs)
    } else {
        return cadence.createCallback()
    }
}

async.continue = { loopy: token, repeat: true, loop: false }
async.break = { loopy: token, repeat: false, loop: false }

function call (fn, self, vargs) {
    try {
        var ret = fn.apply(self, vargs)
    } catch (e) {
        return [ ret, e ]
    }
    return [ ret ]
}

Cadence.prototype.rescue = function () {
    var errors = this.errors, catcher = this.catcher
    this.errors = new Array
    this.results = new Array
    this.catcher = null
    this.called = 0
    this.waiting = true
    var callback = this.createCallback()
    var steps = [ function () { return catcher(errors[0], errors) } ]
    var rescue = new Cadence(this, [], cadence.self, steps, this.vargs, callback)
    rescue.waiting = true
    rescue.cadence = this
    invoke(rescue)
}

Cadence.prototype.finalize = function () {
    var vargs, cadence = this
    if (this.finalizers.length == 0) {
        if (this.errors.length === 0) {
            (this.callback).apply(null, this.vargs)
        } else {
            (this.callback).apply(null, [ this.errors[0] ])
        }
    } else {
        var finalizer = this.finalizers.pop()
        execute(cadence.self, finalizer.steps, finalizer.vargs.concat(done))
    }
    function done (error) {
        if (error) {
            cadence.errors.push(error)
        }
        cadence.finalize()
    }
}

function invoke (cadence) {
    for (;;) {
        var vargs, steps = cadence.steps

        async.self = cadence.self

        if (cadence.errors.length) {
            if (cadence.catcher) {
                cadence.rescue()
            } else {
                cadence.finalize()
            }
            break
        }

        if (cadence.results.length == 0) {
            vargs = cadence.vargs
            if (vargs[0] && vargs[0].loopy === token) {
                var label = vargs.shift()
                var destination = label.cadence || cadence.cadence
                var iterator = cadence
                while (destination !== iterator) {
                    iterator.loop = false
                    iterator.index = iterator.steps.length
                    iterator = iterator.parent
                }
                iterator.index = label.repeat ? 0 : iterator.steps.length
                iterator.loop = label.loop
            }
        } else {
            cadence.vargs = vargs = []
            for (var i = 0, I = cadence.results.length; i < I; i++) {
                var vargs_ = cadence.results[i].vargs
                for (var j = 0, J = vargs_.length; j < J; j++) {
                    vargs.push(vargs_[j])
                }
            }
        }

        cadence.called = 0
        cadence.cadences = []
        cadence.results = []
        cadence.errors = []
        cadence.sync = true

        if (cadence.index == steps.length) {
            if (cadence.loop) {
                cadence.index = 0
            } else {
                if (vargs.length !== 0) {
                    vargs.unshift(null)
                }
                cadence.finalize()
                break
            }
        }

        var fn = steps[cadence.index++]

        if (Array.isArray(fn)) {
            if (fn.length === 1) {
                cadence.finalizers.push({ steps: fn, vargs: vargs })
                continue
            } else if (fn.length === 2) {
                cadence.catcher = fn[1]
                fn = fn[0]
            } else if (fn.length === 3) {
                var filter = fn
                cadence.catcher = function (error) {
                    if (filter[1].test(error.code || error.message)) {
                        return filter[2](error)
                    } else {
                        throw error
                    }
                }
                fn = fn[0]
            } else {
                cadence.vargs = [ vargs ]
                continue
            }
        }

        stack.push(cadence)

        var ret = call(fn, cadence.self, vargs)
               // ^^^^

        stack.pop()

        if (ret.length === 2) {
            cadence.errors.push(ret[1])
            cadence.vargs = vargs
            cadence.sync = true
        } else {
            for (var i = 0, I = cadence.cadences.length; i < I; i++) {
                invoke(cadence.cadences[i])
            }
            if (ret[0] !== void(0)) {
                cadence.vargs = Array.isArray(ret[0]) ? ret[0] : [ ret[0] ]
            }
        }

        if (!cadence.sync) {
            cadence.waiting = true
            break
        }
    }
}

function execute (self, steps, vargs) {
    var callback = vargs.pop()
    var cadence = new Cadence(null, [], self, steps, vargs, callback)
    invoke(cadence)
}

function cadence () {
    var I = arguments.length
    var steps = new Array
    for (var i = 0; i < I; i++) {
        steps.push(arguments[i])
    }
    var f
    // Preserving arity costs next to nothing; the call to `execute` in
    // these functions will be inlined. The airty function itself will never
    // be inlined because it is in a different context than that of our
    // dear user, but it will be compiled.
    switch (steps[0].length) {
    case 0:
        f = function () {
            var I = arguments.length
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs)
        }
        break
    case 1:
        f = function (one) {
            var I = arguments.length
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs)
        }
        break
    case 2:
        f = function (one, two) {
            var I = arguments.length
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs)
        }
        break
    case 3:
        f = function (one, two, three) {
            var I = arguments.length
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs)
        }
        break
    case 4:
        f = function (one, two, three, four) {
            var I = arguments.length
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs)
        }
        break
    default:
        // Avert your eyes if you're squeamish.
        var args = []
        for (var i = 0, I = steps[0].length; i < I; i++) {
            args[i] = '_' + i
        }
        f = (new Function('execute', 'steps', 'async', '                    \n\
            return function (' + args.join(',') + ') {                      \n\
                var I = arguments.length                                    \n\
                var vargs = new Array(I + 1)                                \n\
                vargs[0] = async                                            \n\
                for (var i = 0; i < I; i++) {                               \n\
                    vargs[i + 1] = arguments[i]                             \n\
                }                                                           \n\
                execute(this, steps, vargs)                                 \n\
            }                                                               \n\
       '))(execute, steps, async)
    }

    f.toString = function () { return steps[0].toString() }

    f.isCadence = true

    return f
}

function Sink (async, self, ee) {
    this._async = async
    this._self = self
    this._ee = ee
    this._listeners = []
    this._callback = async()
}

Sink.prototype._register = function (event, fn) {
    this._ee.on(event, fn)
    this._listeners.push({ event: event, fn: fn })
}

Sink.prototype.error = function (filter) {
    this._register('error', function (error) {
        if (filter) {
            error = call(filter, this._self, [ error ])[1]
        }
        if (error) {
            this._terminate([ error ])
        }
    }.bind(this))
    return this
}

Sink.prototype.end = function (event) {
    this._register(event, variadic(function (vargs) {
        vargs.unshift(null)
        this._terminate(vargs)
    }, this))
    return this
}

Sink.prototype._terminate = function (vargs) {
    for (var i = 0, I = this._listeners.length; i < I; i++) {
        var listener = this._listeners[i]
        this._ee.removeListener(listener.event, listener.fn)
    }
    this._callback.apply(null, vargs)
}

Sink.prototype.on = function (event, listener) {
    this._register(event, variadic(function (vargs) {
        var ret = call(listener, this._self, vargs)
        if (ret.length === 2) {
            this._terminate([ ret[1] ])
        }
    }, this))
    return this
}

function variadic (f, self) {
    return function () {
        var I = arguments.length
        var vargs = new Array
        for (var i = 0; i < I; i++) {
            vargs.push(arguments[i])
        }
        return f.call(self, vargs)
    }
}

async.ee = function (ee) {
    var async = this
    return new Sink(this, async.self, ee)
}

async.forEach = variadic(function (steps) {
    return variadic(function (vargs) {
        var loop, array = vargs.shift(), index = -1
        steps.unshift(variadic(function (vargs) {
            index++
            if (index === array.length) return [ loop.break ].concat(vargs)
            return [ array[index], index ].concat(vargs)
        }))
        return loop = this.apply(null, steps).apply(null, vargs)
    }, this)
}, async)

async.map = variadic(function (steps) {
    return variadic(function (vargs) {
        var loop, array = vargs.shift(), index = -1, gather = []
        steps.unshift(variadic(function (vargs) {
            index++
            if (index === array.length) return [ loop.break, gather ]
            return [ array[index], index ].concat(vargs)
        }))
        steps.push(variadic(function (vargs) {
            gather.push.apply(gather, vargs)
        }))
        return loop = this.apply(null, steps).apply(null, vargs)
    }, this)
}, async)

module.exports = cadence
<commit_msg>Fix labeled continue.<commit_after>var stack = [], push = [].push, token = {}

function Cadence (parent, finalizers, self, steps, vargs, callback) {
    this.parent = parent
    this.finalizers = finalizers
    this.self = self
    this.steps = steps
    this.callback = callback
    this.loop = false
    this.cadence = this
    this.cadences = []
    this.results = []
    this.errors = []
    this.called = 0
    this.index = 0
    this.sync = true
    this.waiting = false
    this.vargs = vargs
}

Cadence.prototype.resolveCallback = function (result, vargs) {
    var error = vargs.shift()
    if (error == null) {
        result.vargs = vargs
    } else {
        this.errors.push(error)
    }
    if (++this.called === this.results.length) {
        if (this.waiting) {
            invoke(this)
        } else {
            this.sync = true
        }
    }
}

Cadence.prototype.createCallback = function () {
    var self = this
    var result = { vargs: [] }

    self.results.push(result)
    self.sync = false

    return callback

    function callback () {
        var I = arguments.length
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        self.resolveCallback(result, vargs)

        return

        // This try/catch will prevent V8 from marking this function of
        // optimization because it will only ever run once.
        /* istanbul ignore next */
        try {} catch(e) {}
    }
}

Cadence.prototype.createCadence = function (vargs) {
    var callback = this.createCallback()

    var cadence = new Cadence(this, this.finalizers, this.self, vargs, [], callback)

    this.cadences.push(cadence)

    return looper

    function looper () {
        var I = arguments.length
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        return cadence.startLoop(vargs)
    }
}

Cadence.prototype.startLoop = function (vargs) {
    this.loop = true
    this.vargs = vargs

    return {
        continue: { loopy: token, repeat: true, loop: true, cadence: this },
        break: { loopy: token, repeat: false, loop: false, cadence: this }
    }
}

function async () {
    var cadence = stack[stack.length - 1]
    var I = arguments.length
    if (I) {
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        return cadence.createCadence(vargs)
    } else {
        return cadence.createCallback()
    }
}

async.continue = { loopy: token, repeat: true, loop: false }
async.break = { loopy: token, repeat: false, loop: false }

function call (fn, self, vargs) {
    try {
        var ret = fn.apply(self, vargs)
    } catch (e) {
        return [ ret, e ]
    }
    return [ ret ]
}

Cadence.prototype.rescue = function () {
    var errors = this.errors, catcher = this.catcher
    this.errors = new Array
    this.results = new Array
    this.catcher = null
    this.called = 0
    this.waiting = true
    var callback = this.createCallback()
    var steps = [ function () { return catcher(errors[0], errors) } ]
    var rescue = new Cadence(this, [], cadence.self, steps, this.vargs, callback)
    rescue.waiting = true
    rescue.cadence = this
    invoke(rescue)
}

Cadence.prototype.finalize = function () {
    var vargs, cadence = this
    if (this.finalizers.length == 0) {
        if (this.errors.length === 0) {
            (this.callback).apply(null, this.vargs)
        } else {
            (this.callback).apply(null, [ this.errors[0] ])
        }
    } else {
        var finalizer = this.finalizers.pop()
        execute(cadence.self, finalizer.steps, finalizer.vargs.concat(done))
    }
    function done (error) {
        if (error) {
            cadence.errors.push(error)
        }
        cadence.finalize()
    }
}

function invoke (cadence) {
    for (;;) {
        var vargs, steps = cadence.steps

        async.self = cadence.self

        if (cadence.errors.length) {
            if (cadence.catcher) {
                cadence.rescue()
            } else {
                cadence.finalize()
            }
            break
        }

        if (cadence.results.length == 0) {
            vargs = cadence.vargs
            if (vargs[0] && vargs[0].loopy === token) {
                var label = vargs.shift()
                var destination = label.cadence || cadence.cadence
                var iterator = cadence
                while (destination !== iterator) {
                    iterator.loop = false
                    iterator.index = iterator.steps.length
                    iterator = iterator.parent
                }
                iterator.index = label.repeat ? 0 : iterator.steps.length
                iterator.loop = label.loop
            }
        } else {
            cadence.vargs = vargs = []
            for (var i = 0, I = cadence.results.length; i < I; i++) {
                var vargs_ = cadence.results[i].vargs
                for (var j = 0, J = vargs_.length; j < J; j++) {
                    vargs.push(vargs_[j])
                }
            }
        }

        cadence.called = 0
        cadence.cadences = []
        cadence.results = []
        cadence.errors = []
        cadence.sync = true

        if (cadence.index == steps.length) {
            if (cadence.loop) {
                cadence.index = 0
            } else {
                if (vargs.length !== 0) {
                    vargs.unshift(null)
                }
                cadence.finalize()
                break
            }
        }

        var fn = steps[cadence.index++]

        if (Array.isArray(fn)) {
            if (fn.length === 1) {
                cadence.finalizers.push({ steps: fn, vargs: vargs })
                continue
            } else if (fn.length === 2) {
                cadence.catcher = fn[1]
                fn = fn[0]
            } else if (fn.length === 3) {
                var filter = fn
                cadence.catcher = function (error) {
                    if (filter[1].test(error.code || error.message)) {
                        return filter[2](error)
                    } else {
                        throw error
                    }
                }
                fn = fn[0]
            } else {
                cadence.vargs = [ vargs ]
                continue
            }
        }

        stack.push(cadence)

        var ret = call(fn, cadence.self, vargs)
               // ^^^^

        stack.pop()

        if (ret.length === 2) {
            cadence.errors.push(ret[1])
            cadence.vargs = vargs
            cadence.sync = true
        } else {
            for (var i = 0, I = cadence.cadences.length; i < I; i++) {
                invoke(cadence.cadences[i])
            }
            if (ret[0] !== void(0)) {
                cadence.vargs = Array.isArray(ret[0]) ? ret[0] : [ ret[0] ]
            }
        }

        if (!cadence.sync) {
            cadence.waiting = true
            break
        }
    }
}

function execute (self, steps, vargs) {
    var callback = vargs.pop()
    var cadence = new Cadence(null, [], self, steps, vargs, callback)
    invoke(cadence)
}

function cadence () {
    var I = arguments.length
    var steps = new Array
    for (var i = 0; i < I; i++) {
        steps.push(arguments[i])
    }
    var f
    // Preserving arity costs next to nothing; the call to `execute` in
    // these functions will be inlined. The airty function itself will never
    // be inlined because it is in a different context than that of our
    // dear user, but it will be compiled.
    switch (steps[0].length) {
    case 0:
        f = function () {
            var I = arguments.length
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs)
        }
        break
    case 1:
        f = function (one) {
            var I = arguments.length
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs)
        }
        break
    case 2:
        f = function (one, two) {
            var I = arguments.length
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs)
        }
        break
    case 3:
        f = function (one, two, three) {
            var I = arguments.length
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs)
        }
        break
    case 4:
        f = function (one, two, three, four) {
            var I = arguments.length
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs)
        }
        break
    default:
        // Avert your eyes if you're squeamish.
        var args = []
        for (var i = 0, I = steps[0].length; i < I; i++) {
            args[i] = '_' + i
        }
        f = (new Function('execute', 'steps', 'async', '                    \n\
            return function (' + args.join(',') + ') {                      \n\
                var I = arguments.length                                    \n\
                var vargs = new Array(I + 1)                                \n\
                vargs[0] = async                                            \n\
                for (var i = 0; i < I; i++) {                               \n\
                    vargs[i + 1] = arguments[i]                             \n\
                }                                                           \n\
                execute(this, steps, vargs)                                 \n\
            }                                                               \n\
       '))(execute, steps, async)
    }

    f.toString = function () { return steps[0].toString() }

    f.isCadence = true

    return f
}

function Sink (async, self, ee) {
    this._async = async
    this._self = self
    this._ee = ee
    this._listeners = []
    this._callback = async()
}

Sink.prototype._register = function (event, fn) {
    this._ee.on(event, fn)
    this._listeners.push({ event: event, fn: fn })
}

Sink.prototype.error = function (filter) {
    this._register('error', function (error) {
        if (filter) {
            error = call(filter, this._self, [ error ])[1]
        }
        if (error) {
            this._terminate([ error ])
        }
    }.bind(this))
    return this
}

Sink.prototype.end = function (event) {
    this._register(event, variadic(function (vargs) {
        vargs.unshift(null)
        this._terminate(vargs)
    }, this))
    return this
}

Sink.prototype._terminate = function (vargs) {
    for (var i = 0, I = this._listeners.length; i < I; i++) {
        var listener = this._listeners[i]
        this._ee.removeListener(listener.event, listener.fn)
    }
    this._callback.apply(null, vargs)
}

Sink.prototype.on = function (event, listener) {
    this._register(event, variadic(function (vargs) {
        var ret = call(listener, this._self, vargs)
        if (ret.length === 2) {
            this._terminate([ ret[1] ])
        }
    }, this))
    return this
}

function variadic (f, self) {
    return function () {
        var I = arguments.length
        var vargs = new Array
        for (var i = 0; i < I; i++) {
            vargs.push(arguments[i])
        }
        return f.call(self, vargs)
    }
}

async.ee = function (ee) {
    var async = this
    return new Sink(this, async.self, ee)
}

async.forEach = variadic(function (steps) {
    return variadic(function (vargs) {
        var loop, array = vargs.shift(), index = -1
        steps.unshift(variadic(function (vargs) {
            index++
            if (index === array.length) return [ loop.break ].concat(vargs)
            return [ array[index], index ].concat(vargs)
        }))
        return loop = this.apply(null, steps).apply(null, vargs)
    }, this)
}, async)

async.map = variadic(function (steps) {
    return variadic(function (vargs) {
        var loop, array = vargs.shift(), index = -1, gather = []
        steps.unshift(variadic(function (vargs) {
            index++
            if (index === array.length) return [ loop.break, gather ]
            return [ array[index], index ].concat(vargs)
        }))
        steps.push(variadic(function (vargs) {
            gather.push.apply(gather, vargs)
        }))
        return loop = this.apply(null, steps).apply(null, vargs)
    }, this)
}, async)

module.exports = cadence
<|endoftext|>


<commit_before>describe('Integration: outerHTML', function() {
  beforeEach(function() {
    this.fixture = document.createElement('div');
    this.fixture.innerHTML = '

';
  });

  afterEach(function() {
    diff.release(this.fixture);
    diff.removeTransitionState();
  });

  it('can recalculate the tree if contents are unexpectedly changed', function() {
    diff.outerHTML(this.fixture, '

');
    this.fixture.innerHTML = '';
    diff.outerHTML(this.fixture, '

this

');

    assert.equal(this.fixture.firstChild.tagName, 'P');
    assert.equal(this.fixture.firstChild.textContent, 'this');
  });

  it('can replace the documentElement', function() {
    var iframe = document.createElement('iframe');
    document.body.appendChild(iframe);

    var documentElement = iframe.contentDocument.documentElement;
    var originalSource = documentElement.outerHTML;

    diff.outerHTML(documentElement, '');
    assert.equal(documentElement.childNodes.length, 1);

    diff.outerHTML(documentElement, originalSource);
    assert.equal(documentElement.childNodes.length, 2);

    diff.release(documentElement);

    iframe.parentNode.removeChild(iframe);
  });

  it('cannot replace an element without a parent', function() {
    assert.throws(function() {
      diff.outerHTML(this.fixture, '

');
    });
  });

  it('can replace an element with a parent', function() {
    diff.outerHTML(this.fixture.firstChild, '

');

    assert.equal(this.fixture.firstChild.tagName, 'P');
  });

  describe('Comments', function() {
    it('ignores comments', function() {
      diff.outerHTML(this.fixture, '

');

      assert.equal(this.fixture.innerHTML, '

');
    });
  });

  describe('Text', function() {
    it('can be updated by directly setting', function() {
      diff.outerHTML(this.fixture, '
test
');

      assert.equal(this.fixture.textContent, 'test');

      diff.outerHTML(this.fixture, '
this
');

      assert.equal(this.fixture.textContent, 'this');
    });

    it('can replace over markup', function() {
      diff.outerHTML(this.fixture, '

test div

');
      diff.outerHTML(this.fixture, '
this
');

      assert.equal(this.fixture.innerHTML, 'this');
    });

    it('will not replace a previous span', function() {
      diff.outerHTML(this.fixture, '

');
      var span = this.fixture.querySelector('.test');
      diff.outerHTML(this.fixture, '
whatever
');

      assert.equal(this.fixture.innerHTML, 'whatever');
      assert.equal(this.fixture.firstChild, span, 'are the same element');
    });

    it('supports html5 entities', function() {
      diff.outerHTML(this.fixture, '
⪥
');

      assert.equal(this.fixture.innerHTML, '⪥');
    });
  });

  describe('Attributes', function() {
    it('can change attributes', function() {
      diff.outerHTML(this.fixture, '

');

      assert.equal(this.fixture.className, 'hello');
    });

    it('can change attributes more than once', function() {
      diff.outerHTML(this.fixture, '

');
      diff.outerHTML(this.fixture, '

');

      assert.equal(this.fixture.className, 'hello to you');
    });

    it('supports inline styles', function() {
      diff.outerHTML(this.fixture,
        '

');

      assert.equal(this.fixture.innerHTML, '

');
    });

    describe('Data', function() {
      it('has basic support', function() {
        diff.outerHTML(this.fixture, '

');

        assert.equal(this.fixture.innerHTML, '

');
      });

      it('can handle dash separated properties', function() {
        diff.outerHTML(this.fixture,
          '

');

        assert.equal(this.fixture.innerHTML, '

');
      });
    });
  });
});
<commit_msg>Test showing issue with empty attributes<commit_after>describe('Integration: outerHTML', function() {
  beforeEach(function() {
    this.fixture = document.createElement('div');
    this.fixture.innerHTML = '

';
  });

  afterEach(function() {
    diff.release(this.fixture);
    diff.removeTransitionState();
  });

  it('can recalculate the tree if contents are unexpectedly changed', function() {
    diff.outerHTML(this.fixture, '

');
    this.fixture.innerHTML = '';
    diff.outerHTML(this.fixture, '

this

');

    assert.equal(this.fixture.firstChild.tagName, 'P');
    assert.equal(this.fixture.firstChild.textContent, 'this');
  });

  it('can replace the documentElement', function() {
    var iframe = document.createElement('iframe');
    document.body.appendChild(iframe);

    var documentElement = iframe.contentDocument.documentElement;
    var originalSource = documentElement.outerHTML;

    diff.outerHTML(documentElement, '');
    assert.equal(documentElement.childNodes.length, 1);

    diff.outerHTML(documentElement, originalSource);
    assert.equal(documentElement.childNodes.length, 2);

    diff.release(documentElement);

    iframe.parentNode.removeChild(iframe);
  });

  it('cannot replace an element without a parent', function() {
    assert.throws(function() {
      diff.outerHTML(this.fixture, '

');
    });
  });

  it('can replace an element with a parent', function() {
    diff.outerHTML(this.fixture.firstChild, '

');

    assert.equal(this.fixture.firstChild.tagName, 'P');
  });

  describe('Comments', function() {
    it('ignores comments', function() {
      diff.outerHTML(this.fixture, '

');

      assert.equal(this.fixture.innerHTML, '

');
    });
  });

  describe('Text', function() {
    it('can be updated by directly setting', function() {
      diff.outerHTML(this.fixture, '
test
');

      assert.equal(this.fixture.textContent, 'test');

      diff.outerHTML(this.fixture, '
this
');

      assert.equal(this.fixture.textContent, 'this');
    });

    it('can replace over markup', function() {
      diff.outerHTML(this.fixture, '

test div

');
      diff.outerHTML(this.fixture, '
this
');

      assert.equal(this.fixture.innerHTML, 'this');
    });

    it('will not replace a previous span', function() {
      diff.outerHTML(this.fixture, '

');
      var span = this.fixture.querySelector('.test');
      diff.outerHTML(this.fixture, '
whatever
');

      assert.equal(this.fixture.innerHTML, 'whatever');
      assert.equal(this.fixture.firstChild, span, 'are the same element');
    });

    it('supports html5 entities', function() {
      diff.outerHTML(this.fixture, '
⪥
');

      assert.equal(this.fixture.innerHTML, '⪥');
    });
  });

  describe('Attributes', function() {
    it('can set attributes to empty', function() {
      diff.outerHTML(this.fixture, '

');
      diff.outerHTML(this.fixture, '

');

      assert.equal(this.fixture.outerHTML, '

');
    });

    it('can change attributes', function() {
      diff.outerHTML(this.fixture, '

');

      assert.equal(this.fixture.className, 'hello');
    });

    it('can change attributes more than once', function() {
      diff.outerHTML(this.fixture, '

');
      diff.outerHTML(this.fixture, '

');

      assert.equal(this.fixture.className, 'hello to you');
    });

    it('supports inline styles', function() {
      diff.outerHTML(this.fixture,
        '

');

      assert.equal(this.fixture.innerHTML, '

');
    });

    describe('Data', function() {
      it('has basic support', function() {
        diff.outerHTML(this.fixture, '

');

        assert.equal(this.fixture.innerHTML, '

');
      });

      it('can handle dash separated properties', function() {
        diff.outerHTML(this.fixture,
          '

');

        assert.equal(this.fixture.innerHTML, '

');
      });
    });
  });
});
<|endoftext|>


<commit_before>const path      = require('path');
const fs        = require('fs-extra');
const webpack   = require('webpack');
const nodeWatch = require('node-watch');

const content   = require('./content');

// Settings
const webpackConfigBuilder = require('../../config/webpack.config');

// -----------------------------------------------------------------------------
// run webpack to build entries
// -----------------------------------------------------------------------------
function buildWebpackEntries(buildOptions) {
  return new Promise((resolve, reject) => {
    const webpackConfig = webpackConfigBuilder(buildOptions);
    if (buildOptions.stage !== 'hot') {
      const bundler = webpack(webpackConfig);
      const bundle = (err, stats) => {
        if (err) {
          console.log('webpack error', err);
          reject(err);
        }
        // console.log('webpack', stats.toString({ colors: true }));
        resolve({
          webpackConfig,
          webpackStats: stats.toJson()
        });
      };
      bundler.run(bundle);
    } else {
      resolve({
        webpackConfig,
        webpackStats: null
      });
    }
  });
}

// -----------------------------------------------------------------------------
// copy over static files to build directory
// -----------------------------------------------------------------------------
function buildStatic(staticInputPath, outputPath) {
  try {
    console.log(`Copying static files in ${staticInputPath}`);
    fs.copy(staticInputPath, outputPath);
  } catch (err) {
    // No static dir. Do nothing
  }
}

// -----------------------------------------------------------------------------
// watchStatic
// Used to copy over static files if they change
// -----------------------------------------------------------------------------
function watchStatic(staticInputPath, buildOptions) {
  console.log(`Watching static files in ${staticInputPath}`);
  nodeWatch(staticInputPath, { recursive: true }, (evt, filePath) => {
    console.log(`Change in static file ${filePath}`);
    fs.copySync(filePath, buildOptions.outputPath);
  });
}

// -----------------------------------------------------------------------------
// watchHtml
// Used to rebuild html or templates if files change.
// -----------------------------------------------------------------------------
function watchHtml(htmlInputPath, webpackAssets, buildOptions) {
  console.log(`Watching html files in ${htmlInputPath}`);
  nodeWatch(htmlInputPath, { recursive: true }, (evt, fullInputPath) => {
    console.log(`Change in html file ${fullInputPath}`);
    content.writeContent(
      htmlInputPath,
      fullInputPath,
      webpackAssets,
      buildOptions);
  });
}

// -----------------------------------------------------------------------------
// main build
// -----------------------------------------------------------------------------
function build(buildOptions) {

  return new Promise((resolve) => {

    // Copy static files to build directory
    const staticInputPath = path.join(buildOptions.app.path, buildOptions.app.staticPath);
    buildStatic(staticInputPath, buildOptions.outputPath);

    // Webpack build
    console.log(`Webpacking ${buildOptions.appName}`);

    buildWebpackEntries(buildOptions).then((packResults) => {
      let webpackAssets = null;
      const webpackAssetsFilePath = `${packResults.webpackConfig.output.path}/${buildOptions.appName}-webpack-assets.json`;
      if (fs.existsSync(webpackAssetsFilePath)) {
        webpackAssets = fs.readJsonSync(webpackAssetsFilePath);
      }

      // Build html
      console.log(`Building html for ${buildOptions.appName}`);
      const htmlInputPath = path.join(buildOptions.app.path, buildOptions.app.htmlPath);

      const pages = content.buildContents(
        htmlInputPath,
        htmlInputPath,
        buildOptions,
        webpackAssets
      );

      if (buildOptions.stage === 'hot') {
        watchStatic(staticInputPath, buildOptions);
        watchHtml(htmlInputPath, webpackAssets, buildOptions);
        // TODO figure out how to watch template files - requires rebuild of all html
      }

      resolve({
        webpackConfig : packResults.webpackConfig,
        webpackAssets,
        pages,
      });
    });

  });
}

module.exports = {
  build,
  buildWebpackEntries
};
<commit_msg>Extract html build function<commit_after>const path      = require('path');
const fs        = require('fs-extra');
const webpack   = require('webpack');
const nodeWatch = require('node-watch');

const content   = require('./content');

// Settings
const webpackConfigBuilder = require('../../config/webpack.config');

// -----------------------------------------------------------------------------
// run webpack to build entries
// -----------------------------------------------------------------------------
function buildWebpackEntries(buildOptions) {
  return new Promise((resolve, reject) => {
    const webpackConfig = webpackConfigBuilder(buildOptions);
    if (buildOptions.stage !== 'hot') {
      const bundler = webpack(webpackConfig);
      const bundle = (err, stats) => {
        if (err) {
          console.log('webpack error', err);
          reject(err);
        }
        // console.log('webpack', stats.toString({ colors: true }));
        resolve({
          webpackConfig,
          webpackStats: stats.toJson()
        });
      };
      bundler.run(bundle);
    } else {
      resolve({
        webpackConfig,
        webpackStats: null
      });
    }
  });
}

// -----------------------------------------------------------------------------
// copy over static files to build directory
// -----------------------------------------------------------------------------
function buildStatic(staticInputPath, outputPath) {
  try {
    console.log(`Copying static files in ${staticInputPath}`);
    fs.copy(staticInputPath, outputPath);
  } catch (err) {
    // No static dir. Do nothing
  }
}

// -----------------------------------------------------------------------------
// watchStatic
// Used to copy over static files if they change
// -----------------------------------------------------------------------------
function watchStatic(staticInputPath, buildOptions) {
  console.log(`Watching static files in ${staticInputPath}`);
  nodeWatch(staticInputPath, { recursive: true }, (evt, filePath) => {
    console.log(`Change in static file ${filePath}`);
    fs.copySync(filePath, buildOptions.outputPath);
  });
}

// -----------------------------------------------------------------------------
// watchHtml
// Used to rebuild html or templates if files change.
// -----------------------------------------------------------------------------
function watchHtml(htmlInputPath, webpackAssets, buildOptions) {
  console.log(`Watching html files in ${htmlInputPath}`);
  nodeWatch(htmlInputPath, { recursive: true }, (evt, fullInputPath) => {
    console.log(`Change in html file ${fullInputPath}`);
    content.writeContent(
      htmlInputPath,
      fullInputPath,
      webpackAssets,
      buildOptions);
  });
}

function buildHtml(htmlInputPath, buildOptions, webpackAssets) {

  const pages = content.buildContents(
    htmlInputPath,
    htmlInputPath,
    buildOptions,
    webpackAssets
  );

  if (buildOptions.stage === 'hot') {
    watchHtml(htmlInputPath, webpackAssets, buildOptions);
  }

  return pages;
}

// -----------------------------------------------------------------------------
// main build
// -----------------------------------------------------------------------------
function build(buildOptions) {

  return new Promise((resolve) => {

    // Copy static files to build directory
    const staticInputPath = path.join(buildOptions.app.path, buildOptions.app.staticPath);
    buildStatic(staticInputPath, buildOptions.outputPath);
    if (buildOptions.stage === 'hot') {
      watchStatic(staticInputPath, buildOptions);
    }

    // Webpack build
    console.log(`Webpacking ${buildOptions.appName}`);

    buildWebpackEntries(buildOptions).then((packResults) => {
      let webpackAssets = null;
      const webpackAssetsFilePath = `${packResults.webpackConfig.output.path}/${buildOptions.appName}-webpack-assets.json`;
      if (fs.existsSync(webpackAssetsFilePath)) {
        webpackAssets = fs.readJsonSync(webpackAssetsFilePath);
      }

      // Build html
      console.log(`Building html for ${buildOptions.appName}`);
      const htmlInputPath = path.join(buildOptions.app.path, buildOptions.app.htmlPath);

      const pages = buildHtml(htmlInputPath, buildOptions, webpackAssets);

      resolve({
        webpackConfig : packResults.webpackConfig,
        webpackAssets,
        pages,
      });
    });

  });
}

module.exports = {
  build,
  buildHtml,
  buildWebpackEntries
};
<|endoftext|>


<commit_before>'use strict';

const template = require('../../views/pages/CurrentWeather.hbs');
const Search = require('./Search.js');
const Button = require('../components/Button.js');
const ForecastWeather = require('../pages/ForecastWeather');

class CurrentWeatherPage {

	constructor(search) {
		this.container = document.createElement('div');
		this.container.classList.add('current-weather-container');

		this.render();
		this.search = search;

	}

	render() {
		this.container.innerHTML = template();
		this.button();
	}

	button() {
		const button = new Button('Go to Forecast Weather');
		this.container.appendChild(button.container);

		button.container.addEventListener('click', () => {
			this.hidden();
			this.container.nextElementSibling.classList.add('show');
		});
	}

	show(data) {
		this.container.classList.add('show');

		let show = this.container.querySelector('.content');

		show.innerHTML = this.printWeather(data);
	}

	hidden() {
		this.container.classList.remove('show');
	}

	//ToDo: Move this data to appropriate files.
	printWeather(data) {
		const html = `
			${data.location.name}
			${data.current.temp_c + " °C"}

			${data.current.condition.text}
		`;

		return html;
	}

}

module.exports = CurrentWeatherPage;
<commit_msg>Update require search path<commit_after>'use strict';

const template = require('../../views/pages/CurrentWeather.hbs');
const Search = require('../components/Search.js');
const Button = require('../components/Button.js');
const ForecastWeather = require('../pages/ForecastWeather');

class CurrentWeatherPage {

	constructor() {
		this.container = document.createElement('div');
		this.container.classList.add('current-weather-container');

		this.render();

	}

	render() {
		this.container.innerHTML = template();
		this.button();
	}

	button() {
		const button = new Button('Go to Forecast Weather');
		this.container.appendChild(button.container);

		button.container.addEventListener('click', () => {
			this.hidden();
			this.container.nextElementSibling.classList.add('show');
		});
	}

	show(data) {
		this.container.classList.add('show');

		let show = this.container.querySelector('.content');

		show.innerHTML = this.printWeather(data);
	}

	hidden() {
		this.container.classList.remove('show');
	}

	//ToDo: Move this data to appropriate files.
	printWeather(data) {
		const html = `
			${data.location.name}
			${data.current.temp_c + " °C"}

			${data.current.condition.text}
		`;

		return html;
	}

}

module.exports = CurrentWeatherPage;
<|endoftext|>


<commit_before>var stack = [], push = [].push, JUMP = {}

function Cadence (parent, finalizers, self, steps, vargs, callback, outer) {
    this.parent = parent
    this.finalizers = []
    this.self = self
    this.steps = steps
    this.callback = callback
    this.loop = false
    this.cadence = outer || this
    this.outer = outer
    this.cadences = []
    this.results = []
    this.errors = []
    this.called = 0
    this.index = 0
    this.sync = true
    this.waiting = false
    this.vargs = vargs
}

// TODO Expand on this. You keep coming back here and saying, oh, no, I need to
// give up on a step if there is an error. I'm not returning from this because
// there is an error and all the callbacks are not returning. I need to return
// immediately if there is an error, and then have a lot more code to deal with
// the stragglers that return.
//
// Go back to your code. Try to explain to me why one error first callback
// function returning an error is preventing another, completely different
// callback function from returning an error. Pretend the are calls to open two
// separate files and tell me why the orderly error reporting of the inability
// to open one file should prevent the completion of the opening of another.
// You're probably doing something complicated, a callback is deferred, and
// neglecting to notify the deferred callback of an error.
//
// In short, this code is fine. If you were not using Cadence either you would
// not have noticed the problem, or else you've have some sort of straggler
// issue causing your code to continue after you've responded to an error.
//
// TODO Update. Yes, good point. This is rare in production code, but I do
// encounter it a lot in testing where I'm testing race conditions in concurrent
// code, the kind of code that Cadence has made it easy for me to write.
//
// Because this is rare in production, it's not all that difficult to accept
// that Cadence should return on the first error, then silently swallow all
// subsequent errors. That seems ugly, but not advancing is also ugly, and in
// both cases the ugliness is avoided by writing code that runs serially.
// (Parallel code using the Node.js event loop is a boondoggle.)
//
// The logic isn't that much more difficult.
//
// It does present challenges when you consider what it means to run finalizers
// early.

Cadence.prototype.resolveCallback = function (result, error, vargs) {
    if (error == null) {
        result.vargs = vargs
    } else {
        this.errors.push(error)
    }
    if (++this.called === this.results.length) {
        if (this.waiting) {
            this.invoke()
        } else {
            this.sync = true
        }
    }
}

Cadence.prototype.createCallback = function () {
    var self = this
    var result = { vargs: [] }

    self.results.push(result)
    self.sync = false

    return callback

    function callback (error) {
        var I = arguments.length
        var vargs = new Array
        for (var i = 1; i < I; i++) {
            vargs[i - 1] = arguments[i]
        }
        self.resolveCallback(result, error, vargs)
    }
}

function async () {
    var cadence = stack[stack.length - 1]
    var I = arguments.length
    if (I) {
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        cadence.cadences.push(new Cadence(cadence, cadence.finalizers, cadence.self, vargs, [], cadence.createCallback(), cadence.outer))
    } else {
        return cadence.createCallback()
    }
}

async.continue = { jump: JUMP, index: 0, break: false }
async.break = { jump: JUMP, index: Infinity, break: true }

function call (fn, self, vargs) {
    try {
        var ret = fn.apply(self, vargs)
    } catch (e) {
        return [ ret, e ]
    }
    return [ ret ]
}

Cadence.prototype.invoke = function () {
    var vargs, fn
    for (;;) {
        if (this.errors.length) {
            // Break on error cadence is frustrated further by catch blocks that
            // would restore forward motion. I suppose you'd only short-circuit
            // cadences subordinate to this cadence.
            if (this.catcher) {
                var catcher = this.catcher, errors = this.errors
                fn = function () {
                    return catcher.call(this, errors[0], errors)
                }
            } else {
                fn = null
                this.loop = false
            }
        } else {
            if (this.results.length == 0) {
                // We had no async callbacks, so use the return value.
                vargs = this.vargs
                // Check for a loop controller in the return values.
                if (vargs[0] && vargs[0].jump === JUMP) {
                    var jump = vargs.shift()
                    // Walk up to the jumping cadence setting all the
                    // sub-cadences along the way to their last step. We
                    // continue with the current cadence, not the destination.
                    // We don't skip finalizers. When we continue, if the
                    // current cadence is not the jumping cadence, we're going
                    // to run the exit procedures for each sub-cadence.
                    var destination = jump.cadence || this.cadence
                    var iterator = this
                    while (destination !== iterator) {
                        iterator.loop = false
                        iterator.index = iterator.steps.length
                        iterator = iterator.parent
                    }
                    // Set the index and stop looping if this is a `break`.
                    iterator.index = Math.min(jump.index, iterator.steps.length)
                    iterator.loop = iterator.loop && ! jump.break
                }
            } else {
                // Combine the results of all the callbacks into an single array
                // of arguments that will be used to invoke the next step.
                this.vargs = vargs = this.results[0].vargs
                for (var i = 1, I = this.results.length; i < I; i++) {
                    var vargs_ = this.results[i].vargs
                    for (var j = 0, J = vargs_.length; j < J; j++) {
                        vargs.push(vargs_[j])
                    }
                }
            }
            // On to the next step.
            fn = this.steps[this.index++]
        }

        if (fn == null) {
            if (this.finalizers.length) {
                // We're going to continue to loop until all the finalizers have
                // executed. The step index is going to go beyond length of the
                // step array, but that's okay.
                var finalizer = this.finalizers.pop(), errors = this.errors
                fn = function () {
                    async(function () {
                        return finalizer.vargs
                    }, [finalizer.steps[0], function (error) {
                        if (errors.length) throw errors[0]
                        throw error
                    }], function () {
                        if (errors.length) throw errors[0]
                        return vargs
                    })
                }
            } else if (this.loop) {
                // Go back to the first step.
                fn = this.steps[0]
                this.index = 1
            } else if (this.errors.length) {
                // Return the first error we received.
                (this.callback).apply(null, [ this.errors[0] ])
                break
            } else {
                if (vargs.length !== 0) {
                    vargs.unshift(null)
                }
                (this.callback).apply(null, vargs)
                break
            }
        }

        this.called = 0
        this.cadences = []
        this.results = []
        this.errors = []
        this.sync = true
        this.waiting = false
        this.catcher = null

        if (Array.isArray(fn)) {
            if (fn.length === 1) {
                this.finalizers.push({ steps: fn, vargs: vargs })
                continue
            } else if (fn.length === 2) {
                this.catcher = fn[1]
                fn = fn[0]
            } else if (fn.length === 3) {
                var filter = fn
                this.catcher = function (error) {
                    if (filter[1].test(error.code || error.message)) {
                        return filter[2].call(this, error)
                    } else {
                        throw error
                    }
                }
                fn = fn[0]
            } else {
                this.vargs = [ vargs ]
                continue
            }
        }

        stack.push(this)

        var ret = call(fn, this.self, vargs)
               // ^^^^

        stack.pop()

        if (ret.length === 2) {
            this.errors.push(ret[1])
            this.vargs = vargs
            this.sync = true
        } else {
            for (var i = 0, I = this.cadences.length; i < I; i++) {
                this.cadences[i].invoke()
            }
            if (ret[0] !== void(0)) {
                this.vargs = Array.isArray(ret[0]) ? ret[0] : [ ret[0] ]
            }
        }

        if (!this.sync) {
            this.waiting = true
            break
        }
    }
}

function execute (self, steps, vargs, callback) {
    new Cadence(null, [], self, steps, vargs, callback).invoke()
}

function cadence () {
    var I = arguments.length
    var steps = new Array
    for (var i = 0; i < I; i++) {
        steps.push(arguments[i])
    }
    var f
    // Preserving arity costs next to nothing; the call to `execute` in
    // these functions will be inlined. The airty function itself will never
    // be inlined because it is in a different context than that of our
    // dear user, but it will be compiled.
    switch (steps[0].length) {
    case 0:
        f = function () {
            var I = arguments.length - 1
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs, arguments[i])
        }
        break
    case 1:
        f = function (one) {
            var I = arguments.length - 1
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs, arguments[i])
        }
        break
    case 2:
        f = function (one, two) {
            var I = arguments.length - 1
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs, arguments[i])
        }
        break
    case 3:
        f = function (one, two, three) {
            var I = arguments.length - 1
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs, arguments[i])
        }
        break
    case 4:
        f = function (one, two, three, four) {
            var I = arguments.length - 1
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs, arguments[i])
        }
        break
    default:
        // Avert your eyes if you're squeamish.
        var args = []
        for (var i = 0, I = steps[0].length; i < I; i++) {
            args[i] = '_' + i
        }
        f = (new Function('execute', 'steps', 'async', '                    \n\
            return function (' + args.join(',') + ') {                      \n\
                var I = arguments.length - 1                                \n\
                var vargs = new Array(I + 1)                                \n\
                vargs[0] = async                                            \n\
                for (var i = 0; i < I; i++) {                               \n\
                    vargs[i + 1] = arguments[i]                             \n\
                }                                                           \n\
                execute(this, steps, vargs, arguments[i])                   \n\
            }                                                               \n\
       '))(execute, steps, async)
    }

    f.toString = function () { return steps[0].toString() }

    return f
}

function variadic (f, self) {
    return function () {
        var I = arguments.length
        var vargs = new Array
        for (var i = 0; i < I; i++) {
            vargs.push(arguments[i])
        }
        return f.call(self, vargs)
    }
}

async.loop = variadic(function (steps) {
    var cadence = stack[stack.length - 1]
    var vargs = Array.isArray(steps[0]) ? steps.shift() : []
    var callback = cadence.createCallback()
    var looper = new Cadence(cadence, cadence.finalizers, cadence.self, steps, [], callback, cadence.outer)
    looper.loop = true
    looper.vargs = vargs
    looper.outer = looper
    cadence.cadences.push(looper)
    return {
        continue: { jump: JUMP, index: 0, break: false, cadence: looper },
        break: { jump: JUMP, index: Infinity, break: true, cadence: looper }
    }
})

async.forEach = variadic(function (steps) {
    var loop, vargs = steps.shift(), array = vargs.shift(), index = -1
    steps.unshift(vargs, variadic(function (vargs) {
        index++
        if (index === array.length) return [ loop.break ].concat(vargs)
        return [ array[index], index ].concat(vargs)
    }))
    return loop = this.loop.apply(this, steps)
}, async)

async.map = variadic(function (steps) {
    var loop, vargs = steps.shift(), array = vargs.shift(), index = -1, gather = []
    steps.unshift(vargs, variadic(function (vargs) {
        index++
        if (index === array.length) return [ loop.break, gather ]
        return [ array[index], index ].concat(vargs)
    }))
    steps.push(variadic(function (vargs) {
        gather.push.apply(gather, vargs)
    }))
    return loop = this.loop.apply(this, steps)
}, async)

module.exports = cadence
<commit_msg>Argument added for consistency.<commit_after>var stack = [], push = [].push, JUMP = {}

function Cadence (parent, finalizers, self, steps, vargs, callback, outer) {
    this.parent = parent
    this.finalizers = []
    this.self = self
    this.steps = steps
    this.callback = callback
    this.loop = false
    this.cadence = outer || this
    this.outer = outer
    this.cadences = []
    this.results = []
    this.errors = []
    this.called = 0
    this.index = 0
    this.sync = true
    this.waiting = false
    this.vargs = vargs
}

// TODO Expand on this. You keep coming back here and saying, oh, no, I need to
// give up on a step if there is an error. I'm not returning from this because
// there is an error and all the callbacks are not returning. I need to return
// immediately if there is an error, and then have a lot more code to deal with
// the stragglers that return.
//
// Go back to your code. Try to explain to me why one error first callback
// function returning an error is preventing another, completely different
// callback function from returning an error. Pretend the are calls to open two
// separate files and tell me why the orderly error reporting of the inability
// to open one file should prevent the completion of the opening of another.
// You're probably doing something complicated, a callback is deferred, and
// neglecting to notify the deferred callback of an error.
//
// In short, this code is fine. If you were not using Cadence either you would
// not have noticed the problem, or else you've have some sort of straggler
// issue causing your code to continue after you've responded to an error.
//
// TODO Update. Yes, good point. This is rare in production code, but I do
// encounter it a lot in testing where I'm testing race conditions in concurrent
// code, the kind of code that Cadence has made it easy for me to write.
//
// Because this is rare in production, it's not all that difficult to accept
// that Cadence should return on the first error, then silently swallow all
// subsequent errors. That seems ugly, but not advancing is also ugly, and in
// both cases the ugliness is avoided by writing code that runs serially.
// (Parallel code using the Node.js event loop is a boondoggle.)
//
// The logic isn't that much more difficult.
//
// It does present challenges when you consider what it means to run finalizers
// early.

Cadence.prototype.resolveCallback = function (result, error, vargs) {
    if (error == null) {
        result.vargs = vargs
    } else {
        this.errors.push(error)
    }
    if (++this.called === this.results.length) {
        if (this.waiting) {
            this.invoke()
        } else {
            this.sync = true
        }
    }
}

Cadence.prototype.createCallback = function () {
    var self = this
    var result = { vargs: [] }

    self.results.push(result)
    self.sync = false

    return callback

    function callback (error) {
        var I = arguments.length
        var vargs = new Array
        for (var i = 1; i < I; i++) {
            vargs[i - 1] = arguments[i]
        }
        self.resolveCallback(result, error, vargs)
    }
}

function async () {
    var cadence = stack[stack.length - 1]
    var I = arguments.length
    if (I) {
        var vargs = new Array(I)
        for (var i = 0; i < I; i++) {
            vargs[i] = arguments[i]
        }
        cadence.cadences.push(new Cadence(cadence, cadence.finalizers, cadence.self, vargs, [], cadence.createCallback(), cadence.outer))
    } else {
        return cadence.createCallback()
    }
}

async.continue = { jump: JUMP, index: 0, break: false }
async.break = { jump: JUMP, index: Infinity, break: true }

function call (fn, self, vargs) {
    try {
        var ret = fn.apply(self, vargs)
    } catch (e) {
        return [ ret, e ]
    }
    return [ ret ]
}

Cadence.prototype.invoke = function () {
    var vargs, fn
    for (;;) {
        if (this.errors.length) {
            // Break on error cadence is frustrated further by catch blocks that
            // would restore forward motion. I suppose you'd only short-circuit
            // cadences subordinate to this cadence.
            if (this.catcher) {
                var catcher = this.catcher, errors = this.errors
                fn = function () {
                    return catcher.call(this, errors[0], errors)
                }
            } else {
                fn = null
                this.loop = false
            }
        } else {
            if (this.results.length == 0) {
                // We had no async callbacks, so use the return value.
                vargs = this.vargs
                // Check for a loop controller in the return values.
                if (vargs[0] && vargs[0].jump === JUMP) {
                    var jump = vargs.shift()
                    // Walk up to the jumping cadence setting all the
                    // sub-cadences along the way to their last step. We
                    // continue with the current cadence, not the destination.
                    // We don't skip finalizers. When we continue, if the
                    // current cadence is not the jumping cadence, we're going
                    // to run the exit procedures for each sub-cadence.
                    var destination = jump.cadence || this.cadence
                    var iterator = this
                    while (destination !== iterator) {
                        iterator.loop = false
                        iterator.index = iterator.steps.length
                        iterator = iterator.parent
                    }
                    // Set the index and stop looping if this is a `break`.
                    iterator.index = Math.min(jump.index, iterator.steps.length)
                    iterator.loop = iterator.loop && ! jump.break
                }
            } else {
                // Combine the results of all the callbacks into an single array
                // of arguments that will be used to invoke the next step.
                this.vargs = vargs = this.results[0].vargs
                for (var i = 1, I = this.results.length; i < I; i++) {
                    var vargs_ = this.results[i].vargs
                    for (var j = 0, J = vargs_.length; j < J; j++) {
                        vargs.push(vargs_[j])
                    }
                }
            }
            // On to the next step.
            fn = this.steps[this.index++]
        }

        if (fn == null) {
            if (this.finalizers.length) {
                // We're going to continue to loop until all the finalizers have
                // executed. The step index is going to go beyond length of the
                // step array, but that's okay.
                var finalizer = this.finalizers.pop(), errors = this.errors
                fn = function () {
                    async(function () {
                        return finalizer.vargs
                    }, [finalizer.steps[0], function (error) {
                        if (errors.length) throw errors[0]
                        throw error
                    }], function () {
                        if (errors.length) throw errors[0]
                        return vargs
                    })
                }
            } else if (this.loop) {
                // Go back to the first step.
                fn = this.steps[0]
                this.index = 1
            } else if (this.errors.length) {
                // Return the first error we received.
                (this.callback).apply(null, [ this.errors[0] ])
                break
            } else {
                if (vargs.length !== 0) {
                    vargs.unshift(null)
                }
                (this.callback).apply(null, vargs)
                break
            }
        }

        this.called = 0
        this.cadences = []
        this.results = []
        this.errors = []
        this.sync = true
        this.waiting = false
        this.catcher = null

        if (Array.isArray(fn)) {
            if (fn.length === 1) {
                this.finalizers.push({ steps: fn, vargs: vargs })
                continue
            } else if (fn.length === 2) {
                this.catcher = fn[1]
                fn = fn[0]
            } else if (fn.length === 3) {
                var filter = fn
                this.catcher = function (error) {
                    if (filter[1].test(error.code || error.message)) {
                        return filter[2].call(this, error)
                    } else {
                        throw error
                    }
                }
                fn = fn[0]
            } else {
                this.vargs = [ vargs ]
                continue
            }
        }

        stack.push(this)

        var ret = call(fn, this.self, vargs)
               // ^^^^

        stack.pop()

        if (ret.length === 2) {
            this.errors.push(ret[1])
            this.vargs = vargs
            this.sync = true
        } else {
            for (var i = 0, I = this.cadences.length; i < I; i++) {
                this.cadences[i].invoke()
            }
            if (ret[0] !== void(0)) {
                this.vargs = Array.isArray(ret[0]) ? ret[0] : [ ret[0] ]
            }
        }

        if (!this.sync) {
            this.waiting = true
            break
        }
    }
}

function execute (self, steps, vargs, callback) {
    new Cadence(null, [], self, steps, vargs, callback).invoke()
}

function cadence () {
    var I = arguments.length
    var steps = new Array
    for (var i = 0; i < I; i++) {
        steps.push(arguments[i])
    }
    var f
    // Preserving arity costs next to nothing; the call to `execute` in
    // these functions will be inlined. The airty function itself will never
    // be inlined because it is in a different context than that of our
    // dear user, but it will be compiled.
    switch (steps[0].length) {
    case 0:
        f = function () {
            var I = arguments.length - 1
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs, arguments[i])
        }
        break
    case 1:
        f = function (one) {
            var I = arguments.length - 1
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs, arguments[i])
        }
        break
    case 2:
        f = function (one, two) {
            var I = arguments.length - 1
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs, arguments[i])
        }
        break
    case 3:
        f = function (one, two, three) {
            var I = arguments.length - 1
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs, arguments[i])
        }
        break
    case 4:
        f = function (one, two, three, four) {
            var I = arguments.length - 1
            var vargs = new Array(I + 1)
            vargs[0] = async
            for (var i = 0; i < I; i++) {
                vargs[i + 1] = arguments[i]
            }
            execute(this, steps, vargs, arguments[i])
        }
        break
    default:
        // Avert your eyes if you're squeamish.
        var args = []
        for (var i = 0, I = steps[0].length; i < I; i++) {
            args[i] = '_' + i
        }
        f = (new Function('execute', 'steps', 'async', '                    \n\
            return function (' + args.join(',') + ') {                      \n\
                var I = arguments.length - 1                                \n\
                var vargs = new Array(I + 1)                                \n\
                vargs[0] = async                                            \n\
                for (var i = 0; i < I; i++) {                               \n\
                    vargs[i + 1] = arguments[i]                             \n\
                }                                                           \n\
                execute(this, steps, vargs, arguments[i])                   \n\
            }                                                               \n\
       '))(execute, steps, async)
    }

    f.toString = function () { return steps[0].toString() }

    return f
}

function variadic (f, self) {
    return function () {
        var I = arguments.length
        var vargs = new Array
        for (var i = 0; i < I; i++) {
            vargs.push(arguments[i])
        }
        return f.call(self, vargs)
    }
}

async.loop = variadic(function (steps) {
    var cadence = stack[stack.length - 1]
    var vargs = Array.isArray(steps[0]) ? steps.shift() : []
    var callback = cadence.createCallback()
    var looper = new Cadence(cadence, cadence.finalizers, cadence.self, steps, [], callback, cadence.outer)
    looper.loop = true
    looper.vargs = vargs
    looper.outer = looper
    cadence.cadences.push(looper)
    return {
        continue: { jump: JUMP, index: 0, break: false, cadence: looper },
        break: { jump: JUMP, index: Infinity, break: true, cadence: looper }
    }
}, async)

async.forEach = variadic(function (steps) {
    var loop, vargs = steps.shift(), array = vargs.shift(), index = -1
    steps.unshift(vargs, variadic(function (vargs) {
        index++
        if (index === array.length) return [ loop.break ].concat(vargs)
        return [ array[index], index ].concat(vargs)
    }))
    return loop = this.loop.apply(this, steps)
}, async)

async.map = variadic(function (steps) {
    var loop, vargs = steps.shift(), array = vargs.shift(), index = -1, gather = []
    steps.unshift(vargs, variadic(function (vargs) {
        index++
        if (index === array.length) return [ loop.break, gather ]
        return [ array[index], index ].concat(vargs)
    }))
    steps.push(variadic(function (vargs) {
        gather.push.apply(gather, vargs)
    }))
    return loop = this.loop.apply(this, steps)
}, async)

module.exports = cadence
<|endoftext|>


<commit_before>var dgram = require("dgram");
var fs = require('fs');
var child = require('child_process');

var pulsar;
var server = dgram.createSocket("udp4");

server.on("listening", function () {
  var address = server.address();
  //console.log("server listening " +
  //  address.address + ":" + address.port);
});

server.on("error", function (err) {
  //console.log("server error:\n" + err.stack);
  server.close();
  console.log("dgram socket failure: " + err.stack);
});

server.on("message", function (msg, rinfo) {
  server.recievedPulse = JSON.parse(msg);

  if (server.recievedPulse.supernova) {
    if (server.recievedPulse.action &&
        server.recievedPulse.action === "die") {

      console.log("DIE RECIEVED");
      if (pulsar) {
        pulsar.kill('SIGTERM');
        pulsar = undefined;
      }
      process.exit();
    }

    if (!pulsar) {
      copyFile('/Volumes/Transit/PULSAR/Pulsar.json', './Pulsar.json', function() {
        console.log("Pulsar.json downloaded");
        copyFile('/Volumes/Transit/PULSAR/PULSAR.jar', './Pulsar.jar', function() {
          console.log("Pulsar.jar downloaded");
          pulsar = child.spawn('java', ['-jar', 'PULSAR.jar']);
        });
      });
    } else {
      pulsar.kill('SIGTERM');
      pulsar = undefined;
    }
  }
});

// stolen from http://stackoverflow.com/questions/11293857/fastest-way-to-copy-file-in-node-js
function copyFile(source, target, cb) {
  var cbCalled = false;

  var rd = fs.createReadStream(source);
  rd.on("error", function(err) {
    done(err);
  });
  var wr = fs.createWriteStream(target);
  wr.on("error", function(err) {
    done(err);
  });
  wr.on("close", function(ex) {
    done();
  });
  rd.pipe(wr);

  function done(err) {
    if (!cbCalled) {
      cb(err);
      cbCalled = true;
    }
  }
}

server.bind(6661);
<commit_msg>Enable stdout and stderr from pulsar to print to console<commit_after>var dgram = require("dgram");
var fs = require('fs');
var child = require('child_process');

var pulsar;
var server = dgram.createSocket("udp4");

server.on("listening", function () {
  var address = server.address();
  //console.log("server listening " +
  //  address.address + ":" + address.port);
});

server.on("error", function (err) {
  //console.log("server error:\n" + err.stack);
  server.close();
  console.log("dgram socket failure: " + err.stack);
});

server.on("message", function (msg, rinfo) {
  server.recievedPulse = JSON.parse(msg);

  if (server.recievedPulse.supernova) {
    if (server.recievedPulse.action &&
        server.recievedPulse.action === "die") {

      console.log("DIE RECIEVED");
      if (pulsar) {
        pulsar.kill('SIGTERM');
        pulsar = undefined;
      }
      process.exit();
    }

    if (!pulsar) {
      copyFile('/Volumes/Transit/PULSAR/Pulsar.json', './Pulsar.json', function() {
        console.log("Pulsar.json downloaded");
        copyFile('/Volumes/Transit/PULSAR/PULSAR.jar', './Pulsar.jar', function() {
          console.log("Pulsar.jar downloaded");
          pulsar = child.spawn('java', ['-jar', 'PULSAR.jar']);

          pulsar.stdout.on('data', function (data) {
            console.log('stdout: ' + data);
          });

          pulsar.stderr.on('data', function (data) {
            console.log('stderr: ' + data);
          });

          pulsar.on('close', function (code) {
            console.log('pulsar process exited with code ' + code);
          });
        });
      });
    } else {
      pulsar.kill('SIGTERM');
      pulsar = undefined;
    }
  }
});

// stolen from http://stackoverflow.com/questions/11293857/fastest-way-to-copy-file-in-node-js
function copyFile(source, target, cb) {
  var cbCalled = false;

  var rd = fs.createReadStream(source);
  rd.on("error", function(err) {
    done(err);
  });
  var wr = fs.createWriteStream(target);
  wr.on("error", function(err) {
    done(err);
  });
  wr.on("close", function(ex) {
    done();
  });
  rd.pipe(wr);

  function done(err) {
    if (!cbCalled) {
      cb(err);
      cbCalled = true;
    }
  }
}

server.bind(6661);
<|endoftext|>


<commit_before>			var TRANSPARENT = 0.3;
				var OPAQUE = 1.0;
				var DISTRACTION = 0.075;
				d3.json("book_1_gist_subsampled.json",function(error, data){
					if (error) {
						console.log(error);
					}
					else {
						var weights = [];
						for (var day in data) {
							var datapoint = [];
							datapoint.push(parseInt(day,10));
							datapoint.push(data[day]["weight"]);
							datapoint.push(data[day]["date"]);
							datapoint.push(data[day]["summary"]);
							weights.push(datapoint);
						}
						generateBridgetsLife(weights);

					}
				});
				var jitter = function (epsilon) {
					return Math.random()*(2*epsilon) - epsilon;
				};
				var eliminateDISTRACTIONs = function (circles, currCircle) {
					circles.filter(function(d){
						return d[0] != currCircle[0][0].__data__[0];
					})
					.transition()
					.duration(200)
					.attr("fill-opacity",DISTRACTION);
					currCircle
					.transition()
					.duration(200)
					.attr("fill-opacity",OPAQUE);
				};
				var restoreAll = function (circles) {
					circles
					.transition()
					.duration(200)
					.attr("fill-opacity",TRANSPARENT);
				};
				var generateBridgetsLife = function (dataset) {

					var mean = d3.mean(dataset, function (dp) {
						return dp[1];
					});
					var w = 500;
					var h = 200;
					var r = 5;
					var yPadding = 30;
					var xPadding = 30;
					var xScale = d3.scale.linear()
											.domain([-xPadding, d3.max(dataset, function(d) {return d[0];} )])
											 .range([xPadding, w - xPadding]).nice();
					var yScale = d3.scale.linear()
											.domain([0, 2*d3.max(dataset, function(d) {return d[1];} )])
											.range([h - yPadding, yPadding]).nice();
					var xAxis = d3.svg.axis()
											.scale(xScale)
											.orient("bottom")
											.ticks(5);
					var yAxis = d3.svg.axis()
											.scale(yScale)
											.orient("left")
											.ticks(5);
					var svg = d3.select("#bridgetchart")
								.append("svg")
								.attr("width", w)
								.attr("height", h);
					svg.append("g")
						.attr("class","axis")
						.attr("transform", "translate(0," + (h - xPadding) + ")")
						.call(xAxis);
					svg.append("g")
						.attr("class","axis")
						.attr("transform", "translate(" + 1.25*yPadding + ",0)")
						.call(yAxis);
					svg.append("text")
						.attr("class", "title")
						.attr("text-anchor", "middle")
						.attr("x", w/2)
						.attr("y", 15)
						.text("Bridget Jones: A year of emotions, pounds");
					svg.append("text")
						.attr("class","label")
	    				.attr("text-anchor", "middle")
	   				    .attr("x", w/2)
	    				.attr("y", h - 5)
	  				    .text("days");
	  				svg.append("text")
	    				.attr("class", "label")
	   				    .attr("text-anchor", "middle")
	   				    .attr("x", -h/2)
	    				.attr("y", -2)
	   				    .attr("dy", ".75em")
	    				.attr("transform", "rotate(-90)")
	    				.text("pounds");
					var circles = svg.selectAll("circle")
									.data(dataset)
									.enter()
									.append("circle").attr("class","circle");
					circles
						 .attr("cx", function(d) { return xScale(d[0]); })
						 .attr("cy", function (d) { return yScale(d[1]) + jitter(r); })
						 .attr("r", r)
						 .attr("fill",function (d) {
							if (d[1] >= mean) {
								return "red";
							}
							else {
								return "green";
							}
							} )
						 .attr("fill-opacity",TRANSPARENT)
						 .on("mouseover",function(d) {
						 	eliminateDISTRACTIONs(d3.selectAll("circle"),d3.select(this));
							var xPosition = parseFloat(d3.select(this).attr("cx")) + w/4;
							var yPosition = parseFloat(d3.select(this).attr("cy")) + yPadding;
							d3.select("#caption")
							  .style("left", xPosition + "px")
	  						  .style("top", yPosition + "px")
	  						  .select("#value")
	  						  .text("On " + d[2] + ", Bridget wrote \"" + d[3] + "\"");
							//Show the caption
							d3.select("#caption")
							  .classed("hidden", false);
						 })
						 .on("mouseout",function() {
						 	restoreAll(d3.selectAll("circle"),d3.select(this));
						 	d3.select("#caption")
						 	   .classed("hidden", true);
						 });
				};<commit_msg>Added minor visualization changes to bridget jones<commit_after>			var TRANSPARENT = 0.3;
				var OPAQUE = 1.0;
				var DISTRACTION = 0.075;
				d3.json("book_1_gist_subsampled.json",function(error, data){
					if (error) {
						console.log(error);
					}
					else {
						var weights = [];
						for (var day in data) {
							var datapoint = [];
							datapoint.push(parseInt(day,10));
							datapoint.push(data[day]["weight"]);
							datapoint.push(data[day]["date"]);
							datapoint.push(data[day]["summary"]);
							weights.push(datapoint);
						}
						generateBridgetsLife(weights);

					}
				});
				var jitter = function (epsilon) {
					return Math.random()*(2*epsilon) - epsilon;
				};
				var eliminateDISTRACTIONs = function (circles, currCircle) {
					circles.filter(function(d){
						return d[0] != currCircle[0][0].__data__[0];
					})
					.transition()
					.duration(200)
					.attr("fill-opacity",DISTRACTION);
					currCircle
					.transition()
					.duration(200)
					.attr("fill-opacity",OPAQUE);
				};
				var restoreAll = function (circles) {
					circles
					.transition()
					.duration(200)
					.attr("fill-opacity",TRANSPARENT);
				};
				var generateBridgetsLife = function (dataset) {

					var mean = d3.mean(dataset, function (dp) {
						return dp[1];
					});
					var w = 500;
					var h = 200;
					var r = 5;
					var yPadding = 30;
					var xPadding = 30;
					var xScale = d3.scale.linear()
											.domain([-xPadding, d3.max(dataset, function(d) {return d[0];} )])
											 .range([xPadding, w - xPadding]).nice();
					var yScale = d3.scale.linear()
											.domain([0.9*d3.min(dataset, function(d) {return d[1];}), 1.1*d3.max(dataset, function(d) {return d[1];}])
											.range([h - yPadding, yPadding]).nice();
					var xAxis = d3.svg.axis()
											.scale(xScale)
											.orient("bottom")
											.ticks(5);
					var yAxis = d3.svg.axis()
											.scale(yScale)
											.orient("left")
											.ticks(5);
					var svg = d3.select("#bridgetchart")
								.append("svg")
								.attr("width", w)
								.attr("height", h);
					svg.append("g")
						.attr("class","axis")
						.attr("transform", "translate(0," + (h - xPadding) + ")")
						.call(xAxis);
					svg.append("g")
						.attr("class","axis")
						.attr("transform", "translate(" + 1.25*yPadding + ",0)")
						.call(yAxis);
					svg.append("text")
						.attr("class", "title")
						.attr("text-anchor", "middle")
						.attr("x", w/2)
						.attr("y", 15)
						.text("Bridget Jones: A year of emotions, pounds");
					svg.append("text")
						.attr("class","label")
	    				.attr("text-anchor", "middle")
	   				    .attr("x", w/2)
	    				.attr("y", h - 5)
	  				    .text("days");
	  				svg.append("text")
	    				.attr("class", "label")
	   				    .attr("text-anchor", "middle")
	   				    .attr("x", -h/2)
	    				.attr("y", -2)
	   				    .attr("dy", ".75em")
	    				.attr("transform", "rotate(-90)")
	    				.text("pounds");
					var circles = svg.selectAll("circle")
									.data(dataset)
									.enter()
									.append("circle").attr("class","circle");
					circles
						 .attr("cx", function(d) { return xScale(d[0]); })
						 .attr("cy", function (d) { return yScale(d[1]) + jitter(r); })
						 .attr("r", r)
						 .attr("fill",function (d) {
							if (d[1] >= mean) {
								return "red";
							}
							else {
								return "green";
							}
							} )
						 .attr("fill-opacity",TRANSPARENT)
						 .on("mouseover",function(d) {
						 	eliminateDISTRACTIONs(d3.selectAll("circle"),d3.select(this));
	 						var xPosition = parseFloat(d3.event.pageX) + w/16;
						 	var yPosition = parseFloat(d3.event.pageY) - h/4;
							d3.select("#caption")
							  .style("left", xPosition + "px")
	  						  .style("top", yPosition + "px")
	  						  .select("#value")
	  						  .text("On " + d[2] + ", Bridget wrote \"" + d[3] + "\"");
							//Show the caption
							d3.select("#caption")
							  .classed("hidden", false);
						 })
						 .on("mouseout",function() {
						 	restoreAll(d3.selectAll("circle"),d3.select(this));
						 	d3.select("#caption")
						 	   .classed("hidden", true);
						 });
				};<|endoftext|>


<commit_before>'use strict';

/**
 * Backend API
 * Interaction with Ripple Trade Backend REST API
 */

var module = angular.module('api', []);

module.factory('rpAPI', ['$http', '$q', function($http, $q) {
  var rpAPI = {};
  var httpOptions = {};

  rpAPI.setHttpOptions = function() {
    httpOptions = {
      headers: {'Authorization': 'Bearer ' + store.get('backend_token')},
      timeout: 8000
    };
  };

  rpAPI.setHttpOptions();

  rpAPI.getSubscription = function() {
    return $http.get(Options.backend_url + '/api/subscription', httpOptions);
  };

  rpAPI.updateSubscription = function(subscription) {
    return $http.put(Options.backend_url + '/api/subscription', subscription, httpOptions);
  };

  rpAPI.addTransaction = function(transaction, result, hash, local_time) {
    var request_body = {
      transaction: transaction,
      result: result,
      hash: hash,
      local_time: local_time
    };

    return $http.post(Options.backend_url + '/api/transactions', request_body, httpOptions);
  };

  rpAPI.getUserProfile = function() {
    return $http.get(Options.backend_url + '/api/user', httpOptions);
  };

  rpAPI.getUserAccess = function() {
    return $http.get(Options.backend_url + '/api/user/access', httpOptions).then(function(res) {
      if (res.data.access === 'allowed') {
        return 'allowed';
      }

      return $q.reject('denied');
    });
  };

  rpAPI.getBlob = function() {
    return $http.get(Options.backend_url + '/api/blob', httpOptions);
  };

  rpAPI.updateBlob = function(blobData) {
    return $http.post(Options.backend_url + '/api/blob', blobData, httpOptions);
  };

  return rpAPI;
}]);
<commit_msg>[TASK] Update transaction log api call fields<commit_after>'use strict';

/**
 * Backend API
 * Interaction with Ripple Trade Backend REST API
 */

var module = angular.module('api', []);

module.factory('rpAPI', ['$http', '$q', function($http, $q) {
  var rpAPI = {};
  var httpOptions = {};

  rpAPI.setHttpOptions = function() {
    httpOptions = {
      headers: {'Authorization': 'Bearer ' + store.get('backend_token')},
      timeout: 8000
    };
  };

  rpAPI.setHttpOptions();

  rpAPI.getSubscription = function() {
    return $http.get(Options.backend_url + '/api/subscription', httpOptions);
  };

  rpAPI.updateSubscription = function(subscription) {
    return $http.put(Options.backend_url + '/api/subscription', subscription, httpOptions);
  };

  rpAPI.addTransaction = function(transaction, result, hash, submit_response_time) {
    var request_body = {
      transaction: transaction,
      result: result,
      hash: hash,
      submit_response_time: submit_response_time
    };

    return $http.post(Options.backend_url + '/api/transactions', request_body, httpOptions);
  };

  rpAPI.getUserProfile = function() {
    return $http.get(Options.backend_url + '/api/user', httpOptions);
  };

  rpAPI.getUserAccess = function() {
    return $http.get(Options.backend_url + '/api/user/access', httpOptions).then(function(res) {
      if (res.data.access === 'allowed') {
        return 'allowed';
      }

      return $q.reject('denied');
    });
  };

  rpAPI.getBlob = function() {
    return $http.get(Options.backend_url + '/api/blob', httpOptions);
  };

  rpAPI.updateBlob = function(blobData) {
    return $http.post(Options.backend_url + '/api/blob', blobData, httpOptions);
  };

  return rpAPI;
}]);
<|endoftext|>


<commit_before>import React from 'react'
import styled from 'styled-components'
import ContentHeader from './ContentHeader'

const ContentBody = styled.div`
  line-height: 1.6;

  & > h2 {
    padding-top: 3rem;
    margin-top: 3rem;
    border-top: 1px solid #ececec;
  }

  & > h3 {
    padding-top: 3rem;
  }

  & > p {
    margin: 1em 0 0 0;
  }

  & a {
    border-bottom: 1px dotted rgba(162, 162, 162, 0.8);

    &:hover {
      border-bottom-style: solid;
    }

    &.anchor,
    &.gatsby-resp-image-link {
      border: none;
    }
  }

  & > blockquote {
    box-sizing: border-box;
    margin: 1.75em 0 1.75em -2.2em;
    padding: 0 0 0 1.75em;
    border-left: 0.4em solid rgba(32, 35, 42, 0.85);
  }

  & > blockquote p {
    margin: 0.8em 0;
    font-style: italic;
  }

  & .gatsby-highlight {
    border-radius: 5px;
    font-size: 15px;
    line-height: 1.7;
    background: #2d2d2d;
    color: #ffffff;
    border-radius: 10px;
    overflow: auto;
    tab-size: 1.5em;
    margin: 1.5em 0em 1.5em 0;
    padding: 1em;
  }

  & .gatsby-highlight > pre {
    border: 0;
    margin: 0;
    padding: 0;
  }

  & p > code.language-text,
  & li > code.language-text {
    background: rgba(255, 229, 100, 0.2);
    color: #222222cc;
    padding: 0 3px;
    font-size: 0.94em;
    border-radius: 0.3rem;
  }
`

class Content extends React.Component {
  render() {
    const { content, date, tags } = this.props

    return (

        {(tags || date) && <ContentHeader date={date} tags={tags} />}
        <ContentBody dangerouslySetInnerHTML={{ __html: content }} />

    )
  }
}

export default Content
<commit_msg>Following https://github.com/maxpou/gatsby-starter-morning-dew/pull/33 (#23)<commit_after>import React from 'react'
import styled from 'styled-components'
import ContentHeader from './ContentHeader'

const ContentBody = styled.div`
  line-height: 1.6;

  & > h2 {
    padding-top: 3rem;
    margin-top: 3rem;
    border-top: 1px solid #ececec;
  }

  & > h3 {
    padding-top: 3rem;
  }

  & > p {
    margin: 1em 0 0 0;
  }

  & a {
    border-bottom: 1px dotted rgba(162, 162, 162, 0.8);

    &:hover {
      border-bottom-style: solid;
    }

    &.anchor,
    &.gatsby-resp-image-link {
      border: none;
    }
  }

  & > blockquote {
    box-sizing: border-box;
    margin: 1.75em 0 1.75em -2.2em;
    padding: 0 0 0 1.75em;
    border-left: 0.4em solid rgba(32, 35, 42, 0.85);
  }

  & > blockquote p {
    margin: 0.8em 0;
    font-style: italic;
  }

  & .gatsby-highlight {
    border-radius: 5px;
    font-size: 15px;
    line-height: 1.7;
    background: #2d2d2d;
    color: #ffffff;
    border-radius: 10px;
    overflow: auto;
    tab-size: 1.5em;
    margin: 1.5em 0em 1.5em 0;
    /* padding: 1em; */
  }

  & .gatsby-highlight > pre {
    border: 0;
    margin: 0;
    padding: 1;
  }

  & .gatsby-highlight-code-line {
    background-color: #022a4b;
    display: block;
    margin-right: -1em;
    margin-left: -1em;
    padding-right: 1em;
    padding-left: .75em;
    border-left: .25em solid #ffa7c4;
  }

  & p > code.language-text,
  & li > code.language-text {
    background: rgba(255, 229, 100, 0.2);
    color: #222222cc;
    padding: 0 3px;
    font-size: 0.94em;
    border-radius: 0.3rem;
  }
`

class Content extends React.Component {
  render() {
    const { content, date, tags } = this.props

    return (

        {(tags || date) && <ContentHeader date={date} tags={tags} />}
        <ContentBody dangerouslySetInnerHTML={{ __html: content }} />

    )
  }
}

export default Content
<|endoftext|>


<commit_before>;((rc) => {
  'use strict';
  var tagContent = 'router3';
  var tagConfig = 'router3-config';
  var hiddenAttr = 'hidden';
  var specialHideAttr = 'private-hidden';

  var div = document.createElement('div');
  div.innerHTML = `
    <${tagConfig} class-show="class-show0"
                  class-hide="class-hide0">
      <!--
                  // removed because I want to dream in small steps :))
      By default, this config, if not given, will have the following
      values:
  class-show=""             // add to the element's class when showing
  class-hide=""             // remove from the element's class when hidding
  hidden-attribute="hidden" // put/remove this attribute when showing/hidding
                            // if (class-show === "" && class-hide === "")
  // removed because I want to dream in small steps :))
      -->
    </${tagConfig}>
    <${tagContent} hash="case9-1" class-show="class-show1" class-hide="class-hide1">
      Case 9-1
    </${tagContent}>

    <${tagContent} hash="case9-2" class-show="class-show1">
      Case 9-2
    </${tagContent}>

    <${tagContent} hash="case9-3" class-hide="class-hide1">
      Case 9-2
    </${tagContent}>

    <${tagContent} hash="case9-4">
      Case 9-2
    </${tagContent}>

    <${tagContent} hash="case9-5" class-show="" class-hide="">
      Case 9-2
    </${tagContent}>
  `;

  var async1 = async_test('Case 9: hash changed to content[hash="case9-1"]');

  async1.next = async1.step_func(_ => {
    var hash = 'case9-1';
    var content1 = document.querySelector(`${tagContent}[hash="case9-1"]`);
    var content2 = document.querySelector(`${tagContent}[hash="case9-2"]`);
    var content3 = document.querySelector(`${tagContent}[hash="case9-3"]`);
    var content4 = document.querySelector(`${tagContent}[hash="case9-4"]`);
    var content5 = document.querySelector(`${tagContent}[hash="case9-5"]`);

    var check_hash = async1.step_func(_ => {
      assert_equals(content1.getAttribute(specialHideAttr), null);
      assert_equals(content2.getAttribute(specialHideAttr), '');
      assert_equals(content3.getAttribute(specialHideAttr), '');
      assert_equals(content4.getAttribute(specialHideAttr), '');
      assert_equals(content5.getAttribute(specialHideAttr), '');

      assert_false(content1.hasAttribute(hiddenAttr));
      assert_false(content2.hasAttribute(hiddenAttr));
      assert_false(content3.hasAttribute(hiddenAttr));

      assert_true(content4.hasAttribute(hiddenAttr));
      assert_true(content5.hasAttribute(hiddenAttr));

      rc.next();
      document.body.removeChild(div);
      async1.done();
    });

    content1.addEventListener('show', check_hash);
    window.location.hash = hash;
  });

  rc.push(_ => {
    async1.step(_ => {
      document.body.appendChild(div);
      async1.next();
    });
  });

})(window.routeCases);
<commit_msg>Add an extra assert to the first test<commit_after>;((rc) => {
  'use strict';
  var tagContent = 'router3';
  var tagConfig = 'router3-config';
  var hiddenAttr = 'hidden';
  var specialHideAttr = 'private-hidden';

  var div = document.createElement('div');
  div.innerHTML = `
    <${tagConfig} class-show="class-show0"
                  class-hide="class-hide0">
      <!--
                  // removed because I want to dream in small steps :))
      By default, this config, if not given, will have the following
      values:
  class-show=""             // add to the element's class when showing
  class-hide=""             // remove from the element's class when hidding
  hidden-attribute="hidden" // put/remove this attribute when showing/hidding
                            // if (class-show === "" && class-hide === "")
  // removed because I want to dream in small steps :))
      -->
    </${tagConfig}>
    <${tagContent} hash="case9-1" class-show="class-show1" class-hide="class-hide1">
      Case 9-1
    </${tagContent}>

    <${tagContent} hash="case9-2" class-show="class-show1">
      Case 9-2
    </${tagContent}>

    <${tagContent} hash="case9-3" class-hide="class-hide1">
      Case 9-2
    </${tagContent}>

    <${tagContent} hash="case9-4">
      Case 9-2
    </${tagContent}>

    <${tagContent} hash="case9-5" class-show="" class-hide="">
      Case 9-2
    </${tagContent}>
  `;

  var async1 = async_test('Case 9: hash changed to content[hash="case9-1"]');

  async1.next = async1.step_func(_ => {
    var hash = 'case9-1';
    var content1 = document.querySelector(`${tagContent}[hash="case9-1"]`);
    var content2 = document.querySelector(`${tagContent}[hash="case9-2"]`);
    var content3 = document.querySelector(`${tagContent}[hash="case9-3"]`);
    var content4 = document.querySelector(`${tagContent}[hash="case9-4"]`);
    var content5 = document.querySelector(`${tagContent}[hash="case9-5"]`);

    var check_hash = async1.step_func(_ => {
      assert_equals(content1.getAttribute(specialHideAttr), null);
      assert_equals(content2.getAttribute(specialHideAttr), '');
      assert_equals(content3.getAttribute(specialHideAttr), '');
      assert_equals(content4.getAttribute(specialHideAttr), '');
      assert_equals(content5.getAttribute(specialHideAttr), '');

      assert_false(content1.hasAttribute(hiddenAttr));
      assert_false(content2.hasAttribute(hiddenAttr));
      assert_false(content3.hasAttribute(hiddenAttr));

      assert_true(content4.hasAttribute(hiddenAttr));
      assert_true(content5.hasAttribute(hiddenAttr));

      assert_true(content1.classList.contains('class-show1'));

      rc.next();
      document.body.removeChild(div);
      async1.done();
    });

    content1.addEventListener('show', check_hash);
    window.location.hash = hash;
  });

  rc.push(_ => {
    async1.step(_ => {
      document.body.appendChild(div);
      async1.next();
    });
  });

})(window.routeCases);
<|endoftext|>