<commit_before>"use strict";

var execa = require("execa");
var fs = require("mz/fs");
var path = require("path");
var tempfile = require("tempfile");

const merge = path.join(__dirname, "cidr-merge.py");
const exclude = path.join(__dirname, "cidr-exclude.py");

module.exports.merge = function(nets) {
  return new Promise(function(resolve, reject) {
    if (!Array.isArray(nets)) return reject(new Error("Expected an array"));
    const netfile = tempfile(".net");
    fs.writeFile(netfile, nets.join("\n")).then(function() {
      execa.stdout(merge, [netfile]).then(function(stdout) {
        resolve(stdout.split("\n").filter(net => Boolean(net)));
      }).catch(reject);
    }).catch(reject);
  });
};

module.exports.exclude = function(basenets, excludenets) {
  return new Promise(function(resolve, reject) {
    if (!Array.isArray(basenets) || !Array.isArray(excludenets))
      return reject(new Error("Expected an array"));
    const basefile = tempfile(".net");
    const excludefile = tempfile(".net");
    fs.writeFile(basefile, basenets.join("\n")).then(function() {
      fs.writeFile(excludefile, excludenets.join("\n")).then(function() {
        execa.stdout(exclude, [basefile, excludefile]).then(function(stdout) {
          resolve(stdout.split("\n").filter(net => Boolean(net)));
        }).catch(reject);
      }).catch(reject);
    }).catch(reject);
  });
};
<commit_msg>cleanup temp files<commit_after>"use strict";

var execa = require("execa");
var fs = require("mz/fs");
var path = require("path");
var tempfile = require("tempfile");

const merge = path.join(__dirname, "cidr-merge.py");
const exclude = path.join(__dirname, "cidr-exclude.py");

module.exports.merge = function(nets) {
  return new Promise(function(resolve, reject) {
    if (!Array.isArray(nets)) return reject(new Error("Expected an array"));
    const netfile = tempfile(".net");
    fs.writeFile(netfile, nets.join("\n")).then(function() {
      execa.stdout(merge, [netfile]).then(function(stdout) {
        resolve(stdout.split("\n").filter(net => Boolean(net)));
        fs.unlink(netfile);
      }).catch(reject);
    }).catch(reject);
  });
};

module.exports.exclude = function(basenets, excludenets) {
  return new Promise(function(resolve, reject) {
    if (!Array.isArray(basenets) || !Array.isArray(excludenets))
      return reject(new Error("Expected an array"));
    const basefile = tempfile(".net");
    const excludefile = tempfile(".net");
    fs.writeFile(basefile, basenets.join("\n")).then(function() {
      fs.writeFile(excludefile, excludenets.join("\n")).then(function() {

        execa.stdout(exclude, [basefile, excludefile]).then(function(stdout) {
          resolve(stdout.split("\n").filter(net => Boolean(net)));
          fs.unlink(basefile);
          fs.unlink(excludefile);
        }).catch(reject);
      }).catch(reject);
    }).catch(reject);
  });
};
<|endoftext|>


<commit_before>! function (definition) {
    if (typeof window != "undefined") window.cadence = definition()
    else if (typeof define == "function") define(definition)
    else module.exports = definition()
} (function () {
    var __slice = [].slice, __push = [].push

    function consume (to, from) {
        to.push.apply(to, from.splice(0, from.length))
    }

    function cadence () {
        var steps = __slice.call(arguments)

        function enframe (self, consumer, steps, index, caller, callbacks, catcher) {
            return {
                self: self,
                consumer: consumer,
                steps: steps,
                index: index,
                nextIndex: index + 1,
                caller: caller,
                catcher: catcher,
                callbacks: callbacks,
                errors: [],
                finalizers: []
            }
        }

        function execute () {
            var vargs = __slice.call(arguments, 0),
                callback = function (error) { if (error) throw error }

            if (vargs.length) {
                callback = vargs.pop()
            }

            invoke(enframe(this, consumer, steps, -1, { root: true }, argue([ step ].concat(vargs))))

            function consumer (errors, finalizers, results) {
                var vargs = results.length ? [null].concat(results) : []
                finalize.call(this, finalizers, finalizers.length - 1, errors, function (errors) {
                    if (errors.length) {
                        callback(errors.uncaught || errors.shift())
                    } else {
                        callback.apply(null, vargs)
                    }
                })
            }
        }

        // To use the same `step` function throughout while supporting reentrancy,
        // we keep a stack of frame objects. The stack is reversed; top is 0. The
        // `step` function is synchronous and will return immediately.
        //
        // It is possible for the user to invoke `step` outside of a step in a
        // cadence, we can't prevent it, nor really even detect it. Imagine the user
        // invoking `setTimeout` with a callback that calls `step` five minutes
        // later, long after the cadence has ended. Mayhem, but what can you do?

        //
        var frames = []

        function step () {
            return _step(frames[0], { errors: [], results: [] }, false, __slice.call(arguments))
        }

        function _step (frame, callback, event, vargs) {
            if (vargs.length) {
                if (vargs[0] === step) {
                    callback.fixup = !! vargs.shift()
                    if (!vargs.length) return function () {
                        return _step(frame, callback, false, __slice.call(arguments))
                    }
                    throw new Error('relocating')
                }

                if (vargs[0] === Error) {
                    return _step(frame, callback, true, [ 0, [] ].concat(vargs.slice(1)))
                }

                if (vargs[0] === null) {
                  var callback = _step(frame, callback, true, vargs.slice(1))
                  return function () {
                        return callback.apply(null, [ null ].concat(__slice.call(arguments)))
                  }
                }

                if (vargs[0] && vargs[0].invoke === invoke) {
                    frame.callbacks[0].results[0].push(vargs.shift())
                }

                if (typeof vargs[0] == 'string') {
                    callback.property = vargs.shift()
                }

                if (!isNaN(parseInt(vargs[0], 10))) {
                    callback.arity = +(vargs.shift())
                }

                if (Array.isArray(vargs[0]) && vargs[0].length == 0) {
                    callback.arrayed = !! vargs.shift()
                }

                if (vargs[0] && typeof vargs[0].then == 'function') {
                    var promise = vargs.shift(), handler = step.apply(frame.self, vargs)
                    return promise.then(function () {
                        handler.apply(null, [null].concat(__slice.call(arguments)))
                    }, handler)
                }
            }

            frame.callbacks.push(callback)

            callback.steps = vargs

            if (callback.steps.length) {
                if (!callback.fixup) return createCadence(frames[0], callback)
            }

            if (callback.arrayed) {
                if (event) return createCallback(frames[0], callback, -1)
                else return createArray(frames[0], callback)
            }

            return createCallback(frame, callback, 0)
        }

        function createCadence (frame, callback) {
            var index = 0

            if (!callback.arrayed) callback.starter = starter

            function starter () {
                var vargs = __slice.call(arguments)
                var count = 0
                var prefix, gather, counter
                var whilst, each, first

                if (callback.arrayed) {
                    return createCallback(frame, callback, index++).apply(null, [null].concat(vargs))
                } else if (vargs[0] === invoke) {
                    // A reminder; zero index because the result is not arrayed.
                    createCallback(frame, callback, 0).call(null)
                } else {
                    delete callback.starter

                    whilst = function () { return true }
                    if (vargs[0] == null) {
                        vargs.shift()
                    } else {
                        if (Array.isArray(vargs[0]) && vargs.length > 1) {
                            gather = []
                            callback.arrayed = true
                            vargs.shift()
                        }
                        counter = vargs.shift()
                        if (typeof counter == 'number') {
                            whilst = function () { return count != counter }
                        } else if (each = Array.isArray(counter)) {
                            whilst = function () { return count != counter.length }
                        } else {
                            throw new Error('invalid arguments')
                        }
                    }

                    callback.steps.unshift(function () {
                        var vargs = __slice.call(arguments)
                        if (whilst()) {
                            if (counter) {
                                step().apply(frame.self, [ null ].concat(each ? [ counter[count] ] : [], count, vargs))
                            } else {
                                step().apply(frame.self, [ null ].concat(vargs).concat(count))
                            }
                        } else if (gather) {
                            //var release = _step(frame, false, [0])
                            //return [ step ].concat(vargs)
                            //callback.results = gather
                            //release()
                            callback.results = [ null ].concat(gather)
                            return [ step ]
                        } else {
                            return [ step ].concat(vargs)
                        }
                    })

                    callback.steps.push(function () {
                        var vargs = __slice.call(arguments)
                        if (gather) gather.push(vargs)
                        frames[0].nextIndex = 0
                        step().apply(frame.self, [null].concat(vargs))
                        count++
                    })

                    callback.starter = function () {
                        createCallback(frame, callback, 0).apply(null, [null].concat(vargs))
                    }

                    var label = function () {
                        label.offset = 0
                        return label
                    }

                    label.invoke = invoke
                    label.step = callback.steps[0]
                    label.offset = callback.steps.length

                    return label
                }
            }

            starter.invoke = invoke
            starter.step = callback.steps[0]
            starter.offset = callback.steps.length

            return starter
        }

        function createArray (frame, callback) {
            var index = 0
            return function () {
                return createCallback(frame, callback, index++)
            }
        }

        function createCallback (frame, callback, index) {
            if (-1 < index) frame.count++
            return function () {
                var vargs = __slice.call(arguments, 0), error
                error = vargs.shift()
                if (error) {
                    frame.errors.push(error)
                } else {
                    if (index < 0) callback.results.push(vargs)
                    else callback.results[index] = vargs
                    if (callback.steps.length) {
                        frame.count++
                        invoke(enframe(frame.self, consumer, callback.steps, -1, frame, argue(callback.results[index])))
                        function consumer (errors, finalizers, results) {
                            callback.results[index] = results
                            __push.apply(frame.errors, errors)

                            if (callback.fixup) {
                                __push.apply(frame.finalizers, finalizers)
                                consumer()
                            } else {
                                finalize.call(frame.self, finalizers, finalizers.length - 1, frame.errors, consumer)
                            }

                            function consumer () {
                                if (-1 < index && ++frame.called == frame.count) {
                                    invoke(frame)
                            //        frame.join()
                                }
                            }
                        }
                    }
                }
                if (index < 0 ? frame.errors.length : ++frame.called == frame.count) {
                    frame.join()
                }
            }
        }

        function subClass (base, override) {
            var object = {}
            for (var key in base) {
                object[key] = base[key]
            }
            for (var key in override) {
                object[key] = override[key]
            }
            return object
        }

        function finalize (finalizers, index, errors, consumer) {
            if (index == -1) {
                consumer.call(this, errors)
            } else {
                var finalizer = finalizers[index]
                invoke(enframe(this, function (e) {
                    __push.apply(errors, e)
                    finalize.call(this, finalizers, index - 1, errors, consumer)
                }, [ finalizer.f ], -1, finalizer.caller, argue(finalizer.vargs)))
            }
        }

        // When we explicitly set we always set the vargs as an array.
        function argue (vargs) { return [{ results: [[vargs]] }] }

        function invoke (frame) {
            var f = _invoke(frame)
            while (f) f = f()
        }

        function _invoke (frame) {
            var callbacks = frame.callbacks, vargs = [], arg = 0
            var catcher, finalizers, callback, arity, i, j, k, result, hold, jump
            var steps = frame.steps

            if (frame.errors.length) {
                catcher = frame._catcher
                if (catcher) {
                    invoke(enframe(frame.self, _consumer, [ catcher ], -1, frame, argue([ frame.errors, frame.errors[0] ]), true))
                    function _consumer (errors, finalizers, results) {
                        frame.errors = []
                        __push.apply(frame.finalizers, finalizers)
                        if (errors.length) {
                            frame.consumer.call(frame.self, errors, frame.finalizers, results)
                        } else {
                            frame.callbacks = argue(results)
                            invoke(frame)
                        }
                    }
                } else {
                    frame.consumer.call(frame.self, frame.errors, frame.finalizers.splice(0, frame.finalizers.length), [])
                }
                return
            }

            var results = callbacks[0].results[0]
            if (results.length == 1 && Array.isArray(results[0])) {
                callbacks[0].results[0] = results = results[0]
            }

            if (results[0] === step && !frame.caller.root) {
                var iterator = frame.catcher ? frame.caller : frame
                results[0] = {
                    invoke: invoke,
                    step: iterator.steps[0],
                    offset: iterator.steps.length
                }
            }

            if (results[0] && results[0].invoke === invoke) {
                var iterator = frame
                var label = results.shift()
                var finalizers = []
                // fixme: what about finalizers? are they run? probably not.
                while (!iterator.root) {
                    if (iterator.steps[0] === label.step) {
                        iterator.nextIndex = label.offset
                        iterator.callbacks = callbacks
                        callbacks[0].results[0] = [ results ]
                        iterator.errors.length = 0
                        consume(iterator.finalizers, finalizers)
                        return function () { invoke(iterator) }
                    }
                    consume(finalizers, iterator.finalizers)
                    iterator = iterator.caller
                }
            }

            // One in callbacks means that there were no callbacks created, we're
            // going to use the return value.
            if (callbacks.length == 1) {
                i = 0, j = 0
            } else {
                i = 1, j = 0
            }

            for (; i < callbacks.length; i++) {
                callback = callbacks[i]
                if (callback.arrayed) {
                    callback.results = callback.results.filter(function (vargs) { return vargs.length })
                }
                if ('arity' in callback) {
                    arity = callback.arity
                } else {
                    arity = callback.arrayed ? 1 : 0
                    callback.results.forEach(function (result) {
                        arity = Math.max(arity, result.length - j)
                    })
                }
                for (k = 0; k < arity; k++) {
                    vargs.push({ values: [], arrayed: callback.arrayed })
                }
                callback.results.forEach(function (result) {
                    for (k = 0; k < arity; k++) {
                        vargs[arg + k].values.push(result[k + j])
                    }
                })
                if (callback.property) {
                    frame.self[callback.property] = vargs[0].arrayed ? vargs[0].values : vargs[0].values[0]
                }
                arg += arity
                j = 0
            }

            vargs = vargs.map(function (vargs) {
                return vargs.arrayed ? vargs.values : vargs.values.shift()
            })

            frame = subClass(frame, {
                callbacks: [],
                errors: [],
                count: 0,
                called: 0,
                index: frame.nextIndex,
                nextIndex: frame.nextIndex + 1,
                sync: false,
                join: function () { frame.sync = true }
            })

            if (steps.length == frame.index) {
                return function () {
                    frame.consumer.call(frame.self, [], frame.finalizers.splice(0, frame.finalizers.length), vargs)
                }
            }

            var s = frame.steps[frame.index], fn
            if (Array.isArray(s)) {
                if (s.length == 1) {
                    frame.finalizers.push({ f: s[0], vargs: vargs, caller: frame.caller })
                    fn = function () {}
                } else {
                    s = s.slice()
                    fn = s[0]
                    frame._catcher = function (errors, error) {
                        var uncaught = []
                        errors.forEach(function (error) {
                            var caught = true
                            if (s.length == 4) {
                                caught = s[2].test(error[s[1]])
                            } else if (s.length == 3) {
                                var value = error.code || error.message
                                caught = s[1].test(value)
                            }
                            if (!caught && !errors.uncaught) errors.uncaught = error
                            return caught
                        })
                        if (!errors.uncaught) {
                            return s[s.length - 1].call(this, errors, errors[0])
                        } else {
                            throw errors
                        }
                    }
                }
            } else if (typeof s == 'function') {
                fn = s
            } else {
                throw new Error('invalid arguments')
            }

            frames.unshift(frame)

            hold = step()
            var results = frames[0].callbacks[0].results[0] = [ null ]
            try {
                result = fn.apply(frame.self, vargs)
            } catch (errors) {
                if (errors === frame.caller.errors) {
                    frames[0].errors.uncaught = errors.uncaught
                } else {
                    errors = [ errors ]
                }
                __push.apply(frames[0].errors, errors)
                frames[0].called = frames[0].count - 1
            }
            frame = frames.shift()
            frame.callbacks.forEach(function (callback) {
                if (callback.starter) callback.starter(invoke)
            })
            hold.apply(frame.self, results.concat([ result === void(0) ? vargs : result ]))

            if (frame.sync) {
                return function () { invoke(frame) }
            } else {
                frame.join = function () { invoke(frame) }
            }
        }

        return execute
    }

    return cadence
})
<commit_msg>Prepare for clean ups by reserving mnemonic.<commit_after>! function (definition) {
    if (typeof window != "undefined") window.cadence = definition()
    else if (typeof define == "function") define(definition)
    else module.exports = definition()
} (function () {
    var __slice = [].slice, __push = [].push

    function consume (to, from) {
        to.push.apply(to, from.splice(0, from.length))
    }

    function cadence () {
        var steps = __slice.call(arguments)

        function enframe (self, consumer, steps, index, caller, callbacks, catcher) {
            return {
                self: self,
                consumer: consumer,
                steps: steps,
                index: index,
                nextIndex: index + 1,
                caller: caller,
                catcher: catcher,
                callbacks: callbacks,
                cleanup: [],
                errors: [],
                finalizers: []
            }
        }

        function execute () {
            var vargs = __slice.call(arguments, 0),
                callback = function (error) { if (error) throw error }

            if (vargs.length) {
                callback = vargs.pop()
            }

            invoke(enframe(this, consumer, steps, -1, { root: true }, argue([ step ].concat(vargs))))

            function consumer (errors, finalizers, results) {
                var vargs = results.length ? [null].concat(results) : []
                finalize.call(this, finalizers, finalizers.length - 1, errors, function (errors) {
                    if (errors.length) {
                        callback(errors.uncaught || errors.shift())
                    } else {
                        callback.apply(null, vargs)
                    }
                })
            }
        }

        // To use the same `step` function throughout while supporting reentrancy,
        // we keep a stack of frame objects. The stack is reversed; top is 0. The
        // `step` function is synchronous and will return immediately.
        //
        // It is possible for the user to invoke `step` outside of a step in a
        // cadence, we can't prevent it, nor really even detect it. Imagine the user
        // invoking `setTimeout` with a callback that calls `step` five minutes
        // later, long after the cadence has ended. Mayhem, but what can you do?

        //
        var frames = []

        function step () {
            return _step(frames[0], { errors: [], results: [] }, false, __slice.call(arguments))
        }

        function _step (frame, callback, event, vargs) {
            if (vargs.length) {
                if (vargs[0] === step) {
                    callback.fixup = !! vargs.shift()
                    if (!vargs.length) return function () {
                        return _step(frame, callback, false, __slice.call(arguments))
                    }
                    throw new Error('relocating')
                }

                if (vargs[0] === Error) {
                    return _step(frame, callback, true, [ 0, [] ].concat(vargs.slice(1)))
                }

                if (vargs[0] === null) {
                  var callback = _step(frame, callback, true, vargs.slice(1))
                  return function () {
                        return callback.apply(null, [ null ].concat(__slice.call(arguments)))
                  }
                }

                if (vargs[0] && vargs[0].invoke === invoke) {
                    frame.callbacks[0].results[0].push(vargs.shift())
                }

                if (typeof vargs[0] == 'string') {
                    callback.property = vargs.shift()
                }

                if (!isNaN(parseInt(vargs[0], 10))) {
                    callback.arity = +(vargs.shift())
                }

                if (vargs[0] && typeof vargs[0].then == 'function') {
                    var promise = vargs.shift(), handler = step.apply(frame.self, vargs)
                    return promise.then(function () {
                        handler.apply(null, [null].concat(__slice.call(arguments)))
                    }, handler)
                }

                if (Array.isArray(vargs[0])) {
                    if (vargs[0].length == 0) {
                        callback.arrayed = !! vargs.shift()
                    } else if (!callback.fixup
                            && vargs.length == 1
                            && vargs[0].length == 1
                            && typeof vargs[0][0] == 'function') {
                        throw new Error('reserved')
                        frame.cleanup.push(vargs.shift().shift())
                        return
                    }
                }
            }

            frame.callbacks.push(callback)

            callback.steps = vargs

            if (callback.steps.length) {
                if (!callback.fixup) return createCadence(frames[0], callback)
            }

            if (callback.arrayed) {
                if (event) return createCallback(frames[0], callback, -1)
                else return createArray(frames[0], callback)
            }

            return createCallback(frame, callback, 0)
        }

        function createCadence (frame, callback) {
            var index = 0

            if (!callback.arrayed) callback.starter = starter

            function starter () {
                var vargs = __slice.call(arguments)
                var count = 0
                var prefix, gather, counter
                var whilst, each, first

                if (callback.arrayed) {
                    return createCallback(frame, callback, index++).apply(null, [null].concat(vargs))
                } else if (vargs[0] === invoke) {
                    // A reminder; zero index because the result is not arrayed.
                    createCallback(frame, callback, 0).call(null)
                } else {
                    delete callback.starter

                    whilst = function () { return true }
                    if (vargs[0] == null) {
                        vargs.shift()
                    } else {
                        if (Array.isArray(vargs[0]) && vargs.length > 1) {
                            gather = []
                            callback.arrayed = true
                            vargs.shift()
                        }
                        counter = vargs.shift()
                        if (typeof counter == 'number') {
                            whilst = function () { return count != counter }
                        } else if (each = Array.isArray(counter)) {
                            whilst = function () { return count != counter.length }
                        } else {
                            throw new Error('invalid arguments')
                        }
                    }

                    callback.steps.unshift(function () {
                        var vargs = __slice.call(arguments)
                        if (whilst()) {
                            if (counter) {
                                step().apply(frame.self, [ null ].concat(each ? [ counter[count] ] : [], count, vargs))
                            } else {
                                step().apply(frame.self, [ null ].concat(vargs).concat(count))
                            }
                        } else if (gather) {
                            //var release = _step(frame, false, [0])
                            //return [ step ].concat(vargs)
                            //callback.results = gather
                            //release()
                            callback.results = [ null ].concat(gather)
                            return [ step ]
                        } else {
                            return [ step ].concat(vargs)
                        }
                    })

                    callback.steps.push(function () {
                        var vargs = __slice.call(arguments)
                        if (gather) gather.push(vargs)
                        frames[0].nextIndex = 0
                        step().apply(frame.self, [null].concat(vargs))
                        count++
                    })

                    callback.starter = function () {
                        createCallback(frame, callback, 0).apply(null, [null].concat(vargs))
                    }

                    var label = function () {
                        label.offset = 0
                        return label
                    }

                    label.invoke = invoke
                    label.step = callback.steps[0]
                    label.offset = callback.steps.length

                    return label
                }
            }

            starter.invoke = invoke
            starter.step = callback.steps[0]
            starter.offset = callback.steps.length

            return starter
        }

        function createArray (frame, callback) {
            var index = 0
            return function () {
                return createCallback(frame, callback, index++)
            }
        }

        function createCallback (frame, callback, index) {
            if (-1 < index) frame.count++
            return function () {
                var vargs = __slice.call(arguments, 0), error
                error = vargs.shift()
                if (error) {
                    frame.errors.push(error)
                } else {
                    if (index < 0) callback.results.push(vargs)
                    else callback.results[index] = vargs
                    if (callback.steps.length) {
                        frame.count++
                        invoke(enframe(frame.self, consumer, callback.steps, -1, frame, argue(callback.results[index])))
                        function consumer (errors, finalizers, results) {
                            callback.results[index] = results
                            __push.apply(frame.errors, errors)

                            if (callback.fixup) {
                                __push.apply(frame.finalizers, finalizers)
                                consumer()
                            } else {
                                finalize.call(frame.self, finalizers, finalizers.length - 1, frame.errors, consumer)
                            }

                            function consumer () {
                                if (-1 < index && ++frame.called == frame.count) {
                                    invoke(frame)
                            //        frame.join()
                                }
                            }
                        }
                    }
                }
                if (index < 0 ? frame.errors.length : ++frame.called == frame.count) {
                    frame.join()
                }
            }
        }

        function subClass (base, override) {
            var object = {}
            for (var key in base) {
                object[key] = base[key]
            }
            for (var key in override) {
                object[key] = override[key]
            }
            return object
        }

        function finalize (finalizers, index, errors, consumer) {
            if (index == -1) {
                consumer.call(this, errors)
            } else {
                var finalizer = finalizers[index]
                invoke(enframe(this, function (e) {
                    __push.apply(errors, e)
                    finalize.call(this, finalizers, index - 1, errors, consumer)
                }, [ finalizer.f ], -1, finalizer.caller, argue(finalizer.vargs)))
            }
        }

        // When we explicitly set we always set the vargs as an array.
        function argue (vargs) { return [{ results: [[vargs]] }] }

        function invoke (frame) {
            var f = _invoke(frame)
            while (f) f = f()
        }

        function _invoke (frame) {
            var callbacks = frame.callbacks, vargs = [], arg = 0
            var catcher, finalizers, callback, arity, i, j, k, result, hold, jump
            var steps = frame.steps

            if (frame.errors.length) {
                catcher = frame._catcher
                if (catcher) {
                    invoke(enframe(frame.self, _consumer, [ catcher ], -1, frame, argue([ frame.errors, frame.errors[0] ]), true))
                    function _consumer (errors, finalizers, results) {
                        frame.errors = []
                        __push.apply(frame.finalizers, finalizers)
                        if (errors.length) {
                            frame.consumer.call(frame.self, errors, frame.finalizers, results)
                        } else {
                            frame.callbacks = argue(results)
                            invoke(frame)
                        }
                    }
                } else {
                    frame.consumer.call(frame.self, frame.errors, frame.finalizers.splice(0, frame.finalizers.length), [])
                }
                return
            }

            if (frame.cleanup.length) {
                return function () {
                    invoke(enframe(frame.self, function (errors, finalizers, results) {
                        consume(frame.errors, errors)
                        consume(frame.finalizers, finalizers)
                        invoke(frame)
                    }, [ frame.cleanup.pop() ], -1, frame, argue([])))
                }
            }

            var results = callbacks[0].results[0]
            if (results.length == 1 && Array.isArray(results[0])) {
                callbacks[0].results[0] = results = results[0]
            }

            if (results[0] === step && !frame.caller.root) {
                var iterator = frame.catcher ? frame.caller : frame
                results[0] = {
                    invoke: invoke,
                    step: iterator.steps[0],
                    offset: iterator.steps.length
                }
            }

            if (results[0] && results[0].invoke === invoke) {
                var iterator = frame
                var label = results.shift()
                var finalizers = []
                // fixme: what about finalizers? are they run? probably not.
                while (!iterator.root) {
                    if (iterator.steps[0] === label.step) {
                        iterator.nextIndex = label.offset
                        iterator.callbacks = callbacks
                        callbacks[0].results[0] = [ results ]
                        iterator.errors.length = 0
                        consume(iterator.finalizers, finalizers)
                        return function () { invoke(iterator) }
                    }
                    consume(finalizers, iterator.finalizers)
                    iterator = iterator.caller
                }
            }

            // One in callbacks means that there were no callbacks created, we're
            // going to use the return value.
            if (callbacks.length == 1) {
                i = 0, j = 0
            } else {
                i = 1, j = 0
            }

            for (; i < callbacks.length; i++) {
                callback = callbacks[i]
                if (callback.arrayed) {
                    callback.results = callback.results.filter(function (vargs) { return vargs.length })
                }
                if ('arity' in callback) {
                    arity = callback.arity
                } else {
                    arity = callback.arrayed ? 1 : 0
                    callback.results.forEach(function (result) {
                        arity = Math.max(arity, result.length - j)
                    })
                }
                for (k = 0; k < arity; k++) {
                    vargs.push({ values: [], arrayed: callback.arrayed })
                }
                callback.results.forEach(function (result) {
                    for (k = 0; k < arity; k++) {
                        vargs[arg + k].values.push(result[k + j])
                    }
                })
                if (callback.property) {
                    frame.self[callback.property] = vargs[0].arrayed ? vargs[0].values : vargs[0].values[0]
                }
                arg += arity
                j = 0
            }

            vargs = vargs.map(function (vargs) {
                return vargs.arrayed ? vargs.values : vargs.values.shift()
            })

            frame = subClass(frame, {
                cleanup: [],
                callbacks: [],
                errors: [],
                count: 0,
                called: 0,
                index: frame.nextIndex,
                nextIndex: frame.nextIndex + 1,
                sync: false,
                join: function () { frame.sync = true }
            })

            if (steps.length == frame.index) {
                return function () {
                    frame.consumer.call(frame.self, [], frame.finalizers.splice(0, frame.finalizers.length), vargs)
                }
            }

            var s = frame.steps[frame.index], fn
            if (Array.isArray(s)) {
                if (s.length == 1) {
                    frame.finalizers.push({ f: s[0], vargs: vargs, caller: frame.caller })
                    fn = function () {}
                } else {
                    s = s.slice()
                    fn = s[0]
                    frame._catcher = function (errors, error) {
                        var uncaught = []
                        errors.forEach(function (error) {
                            var caught = true
                            if (s.length == 4) {
                                caught = s[2].test(error[s[1]])
                            } else if (s.length == 3) {
                                var value = error.code || error.message
                                caught = s[1].test(value)
                            }
                            if (!caught && !errors.uncaught) errors.uncaught = error
                            return caught
                        })
                        if (!errors.uncaught) {
                            return s[s.length - 1].call(this, errors, errors[0])
                        } else {
                            throw errors
                        }
                    }
                }
            } else if (typeof s == 'function') {
                fn = s
            } else {
                throw new Error('invalid arguments')
            }

            frames.unshift(frame)

            hold = step()
            var results = frames[0].callbacks[0].results[0] = [ null ]
            try {
                result = fn.apply(frame.self, vargs)
            } catch (errors) {
                if (errors === frame.caller.errors) {
                    frames[0].errors.uncaught = errors.uncaught
                } else {
                    errors = [ errors ]
                }
                __push.apply(frames[0].errors, errors)
                frames[0].called = frames[0].count - 1
            }
            frame = frames.shift()
            frame.callbacks.forEach(function (callback) {
                if (callback.starter) callback.starter(invoke)
            })
            hold.apply(frame.self, results.concat([ result === void(0) ? vargs : result ]))

            if (frame.sync) {
                return function () { invoke(frame) }
            } else {
                frame.join = function () { invoke(frame) }
            }
        }

        return execute
    }

    return cadence
})
<|endoftext|>


<commit_before>
load("steal/rhino/rhino.js");
steal('steal/build/pluginify', 'jquery/build/stealify.js', 'jquery/build/amdify.js', 'jquery/build/extract.js',
function() {

	var out = "jquery/dist/",
		excludes = [ 'steal/dev',
			"can/util/jquery/jquery.1.7.1.js",
			"jquery/build/lib.js" ];

	steal.File(out).mkdirs();

	// Create full library
	steal.build.pluginify('jquery/build/lib.js', {
		out: out + "jquerypp.js",
		skipCallbacks: true,
		exclude : excludes.concat([
			'jquery/dom/dom.js', 'jquery/event/event.js', 'jquery/jquery.js'
		])
	});

	// Create separate files
	steal.build.extract({
		"jquery/dom/animate/animate.js" : "jquery.animate.js",
		"jquery/dom/compare/compare.js" : "jquery.compare.js",
		"jquery/dom/cookie/cookie.js" : "jquery.cookie.js",
		"jquery/dom/dimensions/dimensions.js" : "jquery.dimensions.js",
		"jquery/dom/form_params/form_params.js" : "jquery.form_params.js",
		"jquery/dom/range/range.js" : "jquery.range.js",
		"jquery/dom/selection/selection.js" : "jquery.selection.js",
		"jquery/dom/styles/styles.js" : "jquery.styles.js",
		"jquery/dom/within/within.js" : "jquery.within.js",
		"jquery/event/default/default.js" : "jquery.event.default.js",
		"jquery/event/destroyed/destroyed.js" : "jquery.event.destroyed.js",
		"jquery/event/drag/drag.js" : "jquery.event.drag.js",
		"jquery/event/drop/drop.js" : "jquery.event.drop.js",
		"jquery/event/fastfix/fastfix.js" : "jquery.event.fastfix.js",
		"jquery/event/hover/hover.js" : "jquery.event.hover.js",
		"jquery/event/key/key.js" : "jquery.event.key.js",
		"jquery/event/pause/pause.js" : "jquery.event.pause.js",
		"jquery/event/resize/resize.js" : "jquery.event.resize.js",
		"jquery/event/swipe/swipe.js" : "jquery.event.swipe.js",
		"jquery/event/livehack/livehack.js" : "jquery.event.livehack.js",
		"jquery/lang/json/json.js" : "jquery.lang.json.js",
		"jquery/lang/vector/vector.js" : "jquery.lang.vector.js"
	}, {
		skipCallbacks: true,
		exclude : excludes.concat([
			'jquery/dom/dom.js', 'jquery/event/event.js', 'jquery/jquery.js'
		]),
		out : out + 'lib/'
	});

	// Make Steal distributable
	steal.build.stealify('jquery/build/lib.js', {
		out : out + 'steal/',
		exclude : excludes
	});

	// Make AMD modules
	steal.build.amdify('jquery/build/lib.js', {
		out : out + 'amd/',
		exclude : excludes.concat([
			'jquery/dom/dom.js', 'jquery/event/event.js'
		]),
		map : { // steal file to CommonJS module name mappings
			"jquery/jquery.js" : "jquery",
			"jquery/build/lib.js" : "jquerypp/index",
			"jquery/lang/json/json.js" : "jquerypp/util/json",
			"jquery/lang/vector/vector.js" : "jquerypp/util/vector",
			"jquery/dom/animate/animate.js" : "jquerypp/animate",
			"jquery/dom/compare/compare.js" : "jquerypp/compare",
			"jquery/dom/cookie/cookie.js" : "jquerypp/cookie",
			"jquery/dom/dimensions/dimensions.js" : "jquerypp/dimensions",
			"jquery/dom/form_params/form_params.js" : "jquerypp/form_params",
			"jquery/dom/range/range.js" : "jquerypp/range",
			"jquery/dom/selection/selection.js" : "jquerypp/selection",
			"jquery/dom/styles/styles.js" : "jquerypp/styles",
			"jquery/dom/within/within.js" : "jquerypp/within",
			"jquery/event/default/default.js" : "jquerypp/event/default",
			"jquery/event/destroyed/destroyed.js" : "jquerypp/event/destroyed",
			"jquery/event/drag/drag.js" : "jquerypp/event/drag",
			"jquery/event/drag/limit/limit.js" : "jquerypp/event/drag.limit",
			"jquery/event/drag/scroll/scroll.js" : "jquerypp/event/drag.scroll",
			"jquery/event/drag/step/step.js" : "jquerypp/event/drag.step",
			"jquery/event/drop/drop.js" : "jquerypp/event/drop",
			"jquery/event/fastfix/fastfix.js" : "jquerypp/event/fastfix",
			"jquery/event/hover/hover.js" : "jquerypp/event/hover",
			"jquery/event/key/key.js" : "jquerypp/event/key",
			"jquery/event/reverse/reverse.js" : "jquerypp/event/reverse",
			"jquery/event/livehack/livehack.js" : "jquerypp/event/livehack",
			"jquery/event/pause/pause.js" : "jquerypp/event/pause",
			"jquery/event/resize/resize.js" : "jquerypp/event/resize",
			"jquery/event/swipe/swipe.js" : "jquerypp/event/swipe"
		},
		names : { // Module name to variable name mappings
			'jquery' : 'jQuery'
		},
		global : 'jQuery'
	});
});
<commit_msg>Fixing makefile for jQuery++<commit_after>
load("steal/rhino/rhino.js");
steal('steal/build/pluginify', // 'jquery/build/stealify.js', 'jquery/build/amdify.js', 'jquery/build/extract.js',
function() {

	var out = "jquery/dist/",
		excludes = [ 'steal/dev/',
			'jquery',
			'jquery/build/lib.js' ];

	steal.File(out).mkdirs();

	// Create full library
	steal.build.pluginify('jquery/build/lib.js', {
		out: out + "jquerypp.js",
		skipCallbacks: true,
		shim : { 'jquery' : 'jQuery' },
		exclude : excludes.concat([
			'jquery/dom/dom.js', 'jquery/event/event.js', 'jquery/jquery.js'
		])
	});

	// Create separate files
//	steal.build.extract({
//		"jquery/dom/animate/animate.js" : "jquery.animate.js",
//		"jquery/dom/compare/compare.js" : "jquery.compare.js",
//		"jquery/dom/cookie/cookie.js" : "jquery.cookie.js",
//		"jquery/dom/dimensions/dimensions.js" : "jquery.dimensions.js",
//		"jquery/dom/form_params/form_params.js" : "jquery.form_params.js",
//		"jquery/dom/range/range.js" : "jquery.range.js",
//		"jquery/dom/selection/selection.js" : "jquery.selection.js",
//		"jquery/dom/styles/styles.js" : "jquery.styles.js",
//		"jquery/dom/within/within.js" : "jquery.within.js",
//		"jquery/event/default/default.js" : "jquery.event.default.js",
//		"jquery/event/destroyed/destroyed.js" : "jquery.event.destroyed.js",
//		"jquery/event/drag/drag.js" : "jquery.event.drag.js",
//		"jquery/event/drop/drop.js" : "jquery.event.drop.js",
//		"jquery/event/fastfix/fastfix.js" : "jquery.event.fastfix.js",
//		"jquery/event/hover/hover.js" : "jquery.event.hover.js",
//		"jquery/event/key/key.js" : "jquery.event.key.js",
//		"jquery/event/pause/pause.js" : "jquery.event.pause.js",
//		"jquery/event/resize/resize.js" : "jquery.event.resize.js",
//		"jquery/event/swipe/swipe.js" : "jquery.event.swipe.js",
//		"jquery/event/livehack/livehack.js" : "jquery.event.livehack.js",
//		"jquery/lang/json/json.js" : "jquery.lang.json.js",
//		"jquery/lang/vector/vector.js" : "jquery.lang.vector.js"
//	}, {
//		skipCallbacks: true,
//		exclude : excludes.concat([
//			'jquery/dom/dom.js', 'jquery/event/event.js', 'jquery/jquery.js'
//		]),
//		out : out + 'lib/'
//	});

	// Make Steal distributable
//	steal.build.stealify('jquery/build/lib.js', {
//		out : out + 'steal/',
//		exclude : excludes
//	});

	// Make AMD modules
//	steal.build.amdify('jquery/build/lib.js', {
//		out : out + 'amd/',
//		exclude : excludes.concat([
//			'jquery/dom/dom.js', 'jquery/event/event.js'
//		]),
//		map : { // steal file to CommonJS module name mappings
//			"jquery/jquery.js" : "jquery",
//			"jquery/build/lib.js" : "jquerypp/index",
//			"jquery/lang/json/json.js" : "jquerypp/util/json",
//			"jquery/lang/vector/vector.js" : "jquerypp/util/vector",
//			"jquery/dom/animate/animate.js" : "jquerypp/animate",
//			"jquery/dom/compare/compare.js" : "jquerypp/compare",
//			"jquery/dom/cookie/cookie.js" : "jquerypp/cookie",
//			"jquery/dom/dimensions/dimensions.js" : "jquerypp/dimensions",
//			"jquery/dom/form_params/form_params.js" : "jquerypp/form_params",
//			"jquery/dom/range/range.js" : "jquerypp/range",
//			"jquery/dom/selection/selection.js" : "jquerypp/selection",
//			"jquery/dom/styles/styles.js" : "jquerypp/styles",
//			"jquery/dom/within/within.js" : "jquerypp/within",
//			"jquery/event/default/default.js" : "jquerypp/event/default",
//			"jquery/event/destroyed/destroyed.js" : "jquerypp/event/destroyed",
//			"jquery/event/drag/drag.js" : "jquerypp/event/drag",
//			"jquery/event/drag/limit/limit.js" : "jquerypp/event/drag.limit",
//			"jquery/event/drag/scroll/scroll.js" : "jquerypp/event/drag.scroll",
//			"jquery/event/drag/step/step.js" : "jquerypp/event/drag.step",
//			"jquery/event/drop/drop.js" : "jquerypp/event/drop",
//			"jquery/event/fastfix/fastfix.js" : "jquerypp/event/fastfix",
//			"jquery/event/hover/hover.js" : "jquerypp/event/hover",
//			"jquery/event/key/key.js" : "jquerypp/event/key",
//			"jquery/event/reverse/reverse.js" : "jquerypp/event/reverse",
//			"jquery/event/livehack/livehack.js" : "jquerypp/event/livehack",
//			"jquery/event/pause/pause.js" : "jquerypp/event/pause",
//			"jquery/event/resize/resize.js" : "jquerypp/event/resize",
//			"jquery/event/swipe/swipe.js" : "jquerypp/event/swipe"
//		},
//		names : { // Module name to variable name mappings
//			'jquery' : 'jQuery'
//		},
//		global : 'jQuery'
//	});
});
<|endoftext|>


<commit_before>const firebase = require('firebase')
const config = require('./config')

firebase.initializeApp(config);

var ref = firebase.database().ref().child("room1")
var Gpio = require('onoff').Gpio;
var led = new Gpio(17, 'out');

ref.on('value', function (data) {
    if (data.val().Light == "1") {
        console.log('led on')
        led.writeSync(1);
        // var iv = setInterval(function(){
        //     led.writeSync(led.readSync() === 0 ? 1 : 0)
        // }, 800);
        // var iv = setInterval(function(){
        //     led.writeSync(led.readSync() === 0 ? 1 : 0)
        // }, 100);
    } else {
        console.log('led off')
        led.writeSync(0);
    }
})
<commit_msg>update project<commit_after>const firebase = require('firebase')
const config = require('./config')

firebase.initializeApp(config);

var ref = firebase.database().ref().child("room1")
var Gpio = require('onoff').Gpio;
var led = new Gpio(17, 'out');

ref.on('value', function (data) {
    if (data.val().Light == "1") {
        console.log('led on')
        // led.writeSync(1);
        // var iv = setInterval(function(){
        //     led.writeSync(led.readSync() === 0 ? 1 : 0)
        // }, 800);
        var iv = setInterval(function(){
            led.writeSync(led.readSync() === 0 ? 1 : 0)
        }, 100);
    } else {
        console.log('led off')
        led.writeSync(0);
    }
})
<|endoftext|>


<commit_before>const Sequencer = require('./sequencer');

/**
 * Generates `{time, intensity, duration}` values to control the groove of a {@link Part}.
 * @extends Sequencer
 */
class Rhythm extends Sequencer {

  /**
   * @param {Object} options
   * @param {String|Iterable} options.pattern When a String, it can contain the following characters:
   *   - `"X"` → accented note
   *   - `"x"` → normal note
   *   - `"="` → tie
   *   - `"."` → rest
   *
   * Each characters' duration is determined by the `pulse` option.
   * NOTE: Other characters are ignored and can be used to improve readability, for example `"X.x.|x==.|..x=|x=X="`
   *
   * When an {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable|Iterable}
   * of delta-start times, it represents the time between each note (with the first note always starting immediately).
   * NOTE: Negative numbers can be used as rests, and the absolute value is the time until the next note.
   * @param {Number} [options.pulse=1] The duration in beats of each character in a String `pattern`.
   * Only relevant if the `pattern` option is a String.
   * @param {Iterable} [options.intensities=[0.7]]
   * Determines the note intensities in an Iterable `pattern`. Ignored if the `pattern` option is a String.
   * @param {Iterable} [options.durations=time between notes]
   * Determines the note durations in an Iterable `pattern`. Ignored if the `pattern` option is a String.
   * @param {Iterable} [options.length=pattern length]
   * Overrides the length of this rhythm to be different than the `pattern` length.
   * Useful when this rhythm is `looped` or when using {@link Random.duration}s.
   * @param {Iterable} [options.looped=false] If true, this rhythm will repeat infinitely. Note that delta-start times,
   * intensities, and durations loop independently for Iterable `pattern`s, which creates less repetitive rhythms.
   */
  constructor({ pattern=[], pulse=1, intensities, durations, length, looped=false } = {}) {
    const times = [];
    if (typeof pattern === 'string') {
      length = length || pattern.length * pulse;
      intensities = [];
      durations = [];
      let duration = null;
      let count = 0;
      for (const char of pattern) {
        switch (char) {
          case 'X':
            times.push(pulse * count);
            intensities.push(1);
            if (duration) durations.push(duration); // previous duration
            duration = pulse;
            count++;
            break;
          case 'x':
            times.push(pulse * count);
            intensities.push(0.7);
            if (duration) durations.push(duration); // previous duration
            duration = pulse;
            count++;
            break;
          case '=':
            if (duration) duration += pulse;
            count++;
            break;
          case '.':
            if (duration) durations.push(duration);
            duration = null;
            count++;
            break;
          default:
        }
      }
      if (duration) durations.push(duration);
    }
    else {
      length = length || pattern.map(Math.abs).reduce((a,b) => a + b, 0);
      const legatoDurations = [];
      let time = 0;
      let nextTime;
      for (const value of pattern) {
        nextTime = time + Math.abs(value);
        const duration = (nextTime - time) * Math.sign(value);
        if (duration > 0) {
          times.push(time);
          legatoDurations.push(duration);
        } // else this is a rest
        time = nextTime;
      }
      if (!durations) durations = legatoDurations;
    }
    intensities = intensities || [0.7];
    super({ time: times, intensity: intensities, duration: durations }, { length, looped });
    this.times = times;
    this.intensities = intensities;
    this.durations = durations;
  }

  /**
   * Generates a Rhythm pattern String by evenly distributes the given number of pulses into the given total number of
   * time units. Very similar to a "Euclidean pattern". Use the return value for the constructor's pattern option.
   * @param pulses {number}
   * @param total {number}
   * @param {Object} options
   * @param {Number} [options.rotation=0] shifts the pattern with wrap-around
   * @see https://en.wikipedia.org/wiki/Euclidean_pattern
   */
  static distribute(pulses, total, options={}) {
    const pattern = [];
    let count = 0;
    let nextPulse = Math.floor(++count/pulses * total);
    for (let i=1; i<=total; i++) {
      if (i < nextPulse) {
        pattern.push('.'); // rest
      } else {
        pattern.push('x'); // pulse
        nextPulse = Math.floor(++count/pulses * total);
      }
    }
    let patternString = pattern.reverse().join('');
    // TODO: I think rotation is better handled by manipulating the Array, not the String
    if (options.rotation) {
      const rotation = options.rotation;
      for (let i =  1; i <= rotation; i++) {
        const nextX = patternString.indexOf('x', 1);
        if (nextX > 0) patternString = patternString.slice(nextX) + patternString.slice(0, nextX);
        else break;
      }
      for (let i = -1; i >= rotation; i--) {
        const prevX = patternString.lastIndexOf('x');
        if (prevX > 0) patternString = patternString.slice(prevX) + patternString.slice(0, prevX);
        else break;
      }
    }
    return patternString;
  }
}

module.exports = Rhythm;
<commit_msg>changed Rhythm.distribute to use Array manipulation instead of String manipulation for the rotation behavior<commit_after>const Sequencer = require('./sequencer');

/**
 * Generates `{time, intensity, duration}` values to control the groove of a {@link Part}.
 * @extends Sequencer
 */
class Rhythm extends Sequencer {

  /**
   * @param {Object} options
   * @param {String|Iterable} options.pattern When a String, it can contain the following characters:
   *   - `"X"` → accented note
   *   - `"x"` → normal note
   *   - `"="` → tie
   *   - `"."` → rest
   *
   * Each characters' duration is determined by the `pulse` option.
   * NOTE: Other characters are ignored and can be used to improve readability, for example `"X.x.|x==.|..x=|x=X="`
   *
   * When an {@link https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#iterable|Iterable}
   * of delta-start times, it represents the time between each note (with the first note always starting immediately).
   * NOTE: Negative numbers can be used as rests, and the absolute value is the time until the next note.
   * @param {Number} [options.pulse=1] The duration in beats of each character in a String `pattern`.
   * Only relevant if the `pattern` option is a String.
   * @param {Iterable} [options.intensities=[0.7]]
   * Determines the note intensities in an Iterable `pattern`. Ignored if the `pattern` option is a String.
   * @param {Iterable} [options.durations=time between notes]
   * Determines the note durations in an Iterable `pattern`. Ignored if the `pattern` option is a String.
   * @param {Iterable} [options.length=pattern length]
   * Overrides the length of this rhythm to be different than the `pattern` length.
   * Useful when this rhythm is `looped` or when using {@link Random.duration}s.
   * @param {Iterable} [options.looped=false] If true, this rhythm will repeat infinitely. Note that delta-start times,
   * intensities, and durations loop independently for Iterable `pattern`s, which creates less repetitive rhythms.
   */
  constructor({ pattern=[], pulse=1, intensities, durations, length, looped=false } = {}) {
    const times = [];
    if (typeof pattern === 'string') {
      length = length || pattern.length * pulse;
      intensities = [];
      durations = [];
      let duration = null;
      let count = 0;
      for (const char of pattern) {
        switch (char) {
          case 'X':
            times.push(pulse * count);
            intensities.push(1);
            if (duration) durations.push(duration); // previous duration
            duration = pulse;
            count++;
            break;
          case 'x':
            times.push(pulse * count);
            intensities.push(0.7);
            if (duration) durations.push(duration); // previous duration
            duration = pulse;
            count++;
            break;
          case '=':
            if (duration) duration += pulse;
            count++;
            break;
          case '.':
            if (duration) durations.push(duration);
            duration = null;
            count++;
            break;
          default:
        }
      }
      if (duration) durations.push(duration);
    }
    else {
      length = length || pattern.map(Math.abs).reduce((a,b) => a + b, 0);
      const legatoDurations = [];
      let time = 0;
      let nextTime;
      for (const value of pattern) {
        nextTime = time + Math.abs(value);
        const duration = (nextTime - time) * Math.sign(value);
        if (duration > 0) {
          times.push(time);
          legatoDurations.push(duration);
        } // else this is a rest
        time = nextTime;
      }
      if (!durations) durations = legatoDurations;
    }
    intensities = intensities || [0.7];
    super({ time: times, intensity: intensities, duration: durations }, { length, looped });
    this.times = times;
    this.intensities = intensities;
    this.durations = durations;
  }

  /**
   * Generates a Rhythm pattern String by evenly distributes the given number of pulses into the given total number of
   * time units. Very similar to a "Euclidean pattern". Use the return value for the constructor's pattern option.
   * @param pulses {number}
   * @param total {number}
   * @param {Object} options
   * @param {Number} [options.rotation=0] shifts the pattern with wrap-around
   * @see https://en.wikipedia.org/wiki/Euclidean_pattern
   */
  static distribute(pulses, total, options={}) {
    let pattern = [];
    let count = 0;
    let nextPulse = Math.floor(++count/pulses * total);
    for (let i=1; i<=total; i++) {
      if (i < nextPulse) {
        pattern.push('.'); // rest
      } else {
        pattern.push('x'); // pulse
        nextPulse = Math.floor(++count/pulses * total);
      }
    }
    pattern = pattern.reverse();
    if (options.rotation) {
      const rotation = options.rotation;
      for (let i =  1; i <= rotation; i++) {
        const nextX = pattern.indexOf('x', 1);
        if (nextX > 0) pattern = pattern.slice(nextX).concat(pattern.slice(0, nextX));
        else break;
      }
      for (let i = -1; i >= rotation; i--) {
        const prevX = pattern.lastIndexOf('x');
        if (prevX > 0) pattern = pattern.slice(prevX).concat(pattern.slice(0, prevX));
        else break;
      }
    }
    return pattern.join('');
  }
}

module.exports = Rhythm;
<|endoftext|>


<commit_before>// =============================================================================
// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var chalk      = require('chalk');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;

var mongoose   = require('mongoose');
mongoose.connect('mongodb://localhost/calendar_test');
var Activity   = require('./app/models/activity');

var ade = require('./app/ade/index.js')(Activity);
var roomfinder = require('./app/roomfinder/index.js')(Activity);

// =============================================================================
// MAKE ROOM CACHE
// =============================================================================

ade.refreshRoomsCache();
// Refresh every hours
setInterval(ade.refreshRoomsCache, 3600000);

// =============================================================================
// ROUTES FOR OUR API
// =============================================================================

var requestsLogPrefix = chalk.bold.underline("[Request]") + " ";

// get an instance of the express Router
var router = express.Router();

// middleware to use for all requests
router.use(function(req, res, next) {
	// do logging
	console.log(requestsLogPrefix + "URI /api" + req.path + ' Requested.');

	// make sure we go to the next routes and don't stop here
	next();
});

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
	res.json({message: 'Hooray! welcome to our api!'});
});

router.route('/activities')
	.get(function(req, res) {
		Activity.find(function(err, activities) {
			if (err)
				res.send(err);

			res.json(activities);
		});
	});

router.route('/activities/:activity_id')
	.get(function(req, res) {
		Activity.findById(req.params.activity_id, function(err, activity) {
			if(err)
				res.send(err);

			res.json(activity);
		});
	});

router.route('/refresh')
	.get(function(req, res) {
		ade.refreshRoomsCache();
		console.log(requestsLogPrefix + 'Database refresh requested.');
		res.json({message: 'Rooms refreshed!'});
	});

router.route('/rooms')
	.get(function(req, res) {
		roomfinder.findRoomNow(res);
	});

router.route('/rooms/:date')
	.get(function(req, res) {
		roomfinder.findRoom(new Date(Date.parse(req.params.date)), res);
	});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// =============================================================================
// START THE SERVER
// =============================================================================

app.listen(port);
console.log('Magic happens on port ' + port);
<commit_msg>Refresh only on request + decreasing refresh interval to 10mins<commit_after>// =============================================================================
// BASE SETUP
// =============================================================================

// call the packages we need
var express    = require('express');
var app        = express();
var bodyParser = require('body-parser');
var chalk      = require('chalk');

// configure app to use bodyParser()
// this will let us get the data from a POST
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());

var port = process.env.PORT || 8080;

var mongoose   = require('mongoose');
mongoose.connect('mongodb://localhost/calendar_test');
var Activity   = require('./app/models/activity');

var ade = require('./app/ade/index.js')(Activity);
var roomfinder = require('./app/roomfinder/index.js')(Activity);

// =============================================================================
// MAKE ROOM CACHE
// =============================================================================

ade.refreshRoomsCache();
var lastRefresh = new Date();

// =============================================================================
// ROUTES FOR OUR API
// =============================================================================

var requestsLogPrefix = chalk.bold.underline("[Request]") + " ";

// get an instance of the express Router
var router = express.Router();

// middleware to use for all requests
router.use(function(req, res, next) {
	// do logging
	console.log(requestsLogPrefix + "URI /api" + req.path + ' Requested.');

	// If it's been 10 minutes
	if(new Date() - lastRefresh >= 600000) {
		ade.refreshRoomsCache();
		lastRefresh = new Date();
	}

	// make sure we go to the next routes and don't stop here
	next();
});

// test route to make sure everything is working (accessed at GET http://localhost:8080/api)
router.get('/', function(req, res) {
	res.json({message: 'Hooray! welcome to our api!'});
});

router.route('/activities')
	.get(function(req, res) {
		Activity.find(function(err, activities) {
			if (err)
				res.send(err);

			res.json(activities);
		});
	});

router.route('/activities/:activity_id')
	.get(function(req, res) {
		Activity.findById(req.params.activity_id, function(err, activity) {
			if(err)
				res.send(err);

			res.json(activity);
		});
	});

router.route('/refresh')
	.get(function(req, res) {
		ade.refreshRoomsCache();
		console.log(requestsLogPrefix + 'Database refresh requested.');
		res.json({message: 'Rooms refreshed!'});
	});

router.route('/rooms')
	.get(function(req, res) {
		roomfinder.findRoomNow(res);
	});

router.route('/rooms/:date')
	.get(function(req, res) {
		roomfinder.findRoom(new Date(Date.parse(req.params.date)), res);
	});

// REGISTER OUR ROUTES -------------------------------
// all of our routes will be prefixed with /api
app.use('/api', router);

// =============================================================================
// START THE SERVER
// =============================================================================

app.listen(port);
console.log('Magic happens on port ' + port);
<|endoftext|>


<commit_before>const duration = require('iso8601-duration');

class Video {
    constructor(youtube, data) {
        this.youtube = youtube;
        this.title = data.snippet.title;
        this.id = data.id.videoId ? data.id.videoId : data.id;
        this.description = data.snippet.description;
        this.url = `https://www.youtube.com/watch?v=${this.id}`;
        this.publishedAt = data.snippet.publishedAt;
        this.channel = {
            title: data.snippet.channelTitle,
            id: data.snippet.channelId
        };

        if(data.contentDetails) {
            this.id = data.contentDetails.videoId || this.id;
            this.duration = data.contentDetails.duration ? duration.parse(data.contentDetails.duration) : null;
            this.duration_seconds = this.duration ? duration.toSeconds(this.duration) : -1;
        }
    }
}

module.exports = Video;
<commit_msg>Fix video URL from PlaylistItem<commit_after>const duration = require('iso8601-duration');

class Video {
    constructor(youtube, data) {
        this.youtube = youtube;
        this.title = data.snippet.title;
        this.id = data.id.videoId ? data.id.videoId : data.id;
        this.description = data.snippet.description;
        this.publishedAt = data.snippet.publishedAt;
        this.channel = {
            title: data.snippet.channelTitle,
            id: data.snippet.channelId
        };

        if(data.contentDetails) {
            this.id = data.contentDetails.videoId || this.id;
            this.duration = data.contentDetails.duration ? duration.parse(data.contentDetails.duration) : null;
            this.duration_seconds = this.duration ? duration.toSeconds(this.duration) : -1;
        }

        this.url = `https://www.youtube.com/watch?v=${this.id}`;
    }
}

module.exports = Video;
<|endoftext|>


<commit_before>var fs = require('fs');
var _ = require('lodash');
var exec = require('child_process').exec;

var Promise = require('es6-promise').Promise;
var csv = require('csvjson');
var converter = require('json-2-csv');

var Overpass = require('./lib/overpass');

var defaultData = {
  masters:{
    format:'json',
    ext:'.json',
    dir:'./cache/'
  },
  nodes:{
    format:'json',
    ext:'.json',
    dir:'./cache/'
  },
  routes:{
    format:'json',
    ext:'.json',
    dir:'./cache/'
  },
  stops:{
    format:'json',
    ext:'.json',
    dir:'./cache/'
  },
  ways:{
    format:'json',
    ext:'.json',
    dir:'./cache/'
  },
  agency:{
    format:'csv',
    ext:'.txt',
    dir:'./gtfs/'
  },
  trips:{
    format:'csv',
    ext:'.txt',
    dir:'./gtfs/'
  }
};

var parser = {
  csv: function( filepath ){
    return csv.toObject( filepath ).output;
  },
  json: function( filepath ){
    return JSON.parse(fs.readFileSync( filepath ).toString());
  }
};

var GtfsMaker = function(config){
  config = config || {};
  this._settings = config.settings;
  this._data = _.extend(defaultData, config.data);
  this.builders = {
    routes: require('./builders/routes').bind(this),
    shapes: require('./builders/shapes').bind(this),
    stops: require('./builders/stops').bind(this),
    stopTimes: require('./builders/stop_times').bind(this)
  };
};

_.extend( GtfsMaker.prototype, {
  cache:function cache(){
    var OSM3S_API = 'http://api.openstreetmap.fr/oapi/interpreter';

    var masterIds = _.map( this._settings.lines, function(line){
      return line.osmId;
    });

    var overpass = new Overpass( masterIds );

    var types = ['masters', 'stops', 'routes', 'ways', 'nodes'];

    /*
     * array of arrays with [routes, ways, nodes]
     */
    function saveData(data){
      var types = ['masters', 'stops', 'routes', 'ways', 'nodes'];
      _.each(data, function(arr, index){
        fs.writeFileSync('./cache/' + types[index] + '.json', JSON.stringify(arr));
      });
      console.log('data saved to ./cache');
    }

    /*
     * get all data and save to disk
     */
     return Promise.all(types.map(overpass.fetch, overpass))
       .then(saveData);

  },
  /**
   * load static assets from files
   *
   * list, list of file kind as specified in config file
   *
   * a file kind could be a simple file (csv or json)
   * or a directory of similar files
   *
   */
  loadData: function loadData(list){
    var data = this._data;
    return list.map(function(type){

      var file = data[type];
      var rootdir;
      var filepath;

      if (!file){
        throw new Error('No file config for type ' + type + '.');
      }
      // if it is a directory load all files in a bundle
      if ( file.isDirectory ){
        return fs.readdirSync( file.dir )
          .map(function(filename){
            filepath = file.dir + filename;
            return {
              name:filename,
              content:parser[ file.format ].call(undefined, filepath )
            };
         }).map( file.transform );
      } else {
        filepath = file.dir + type + file.ext;
        if ( !fs.existsSync(filepath)){
          throw new Error('File not found ' + filepath + '.');
        }
        return parser[ file.format ].call(undefined, filepath );
      }
    });
  },
  saveDataAsCsv:function saveDataAsCsv(data, filepath){
    return new Promise(function(resolve, reject){
      converter.json2csv(data, function(err, csv){
        if (err){
          reject(err);
        } else {
          fs.writeFileSync( filepath, csv );
          resolve();
        }
      });
    });
  },
  validateGtfs:function(directory){
    var command = 'python '+ __dirname + '/utils/transitfeed/feedvalidator.py ' + directory;
    return new Promise(function(resolve, reject){
      exec(command, function (error, stdout, stderr) {
        if (error){
          reject(error);
        } else {
          resolve();
        }
      });
    });

  }
});

module.exports = GtfsMaker;
<commit_msg>added transform function for the result of loadData<commit_after>var fs = require('fs');
var _ = require('lodash');
var exec = require('child_process').exec;

var Promise = require('es6-promise').Promise;
var csv = require('csvjson');
var converter = require('json-2-csv');

var Overpass = require('./lib/overpass');

var defaultData = {
  masters:{
    format:'json',
    ext:'.json',
    dir:'./cache/'
  },
  nodes:{
    format:'json',
    ext:'.json',
    dir:'./cache/'
  },
  routes:{
    format:'json',
    ext:'.json',
    dir:'./cache/'
  },
  stops:{
    format:'json',
    ext:'.json',
    dir:'./cache/'
  },
  ways:{
    format:'json',
    ext:'.json',
    dir:'./cache/'
  },
  agency:{
    format:'csv',
    ext:'.txt',
    dir:'./gtfs/'
  },
  trips:{
    format:'csv',
    ext:'.txt',
    dir:'./gtfs/'
  }
};

var parser = {
  csv: function( filepath ){
    return csv.toObject( filepath ).output;
  },
  json: function( filepath ){
    return JSON.parse(fs.readFileSync( filepath ).toString());
  }
};

var GtfsMaker = function(config){
  config = config || {};
  this._settings = config.settings;
  this._data = _.extend(defaultData, config.data);
  this.builders = {
    routes: require('./builders/routes').bind(this),
    shapes: require('./builders/shapes').bind(this),
    stops: require('./builders/stops').bind(this),
    stopTimes: require('./builders/stop_times').bind(this)
  };
};

_.extend( GtfsMaker.prototype, {
  cache:function cache(){
    var OSM3S_API = 'http://api.openstreetmap.fr/oapi/interpreter';

    var masterIds = _.map( this._settings.lines, function(line){
      return line.osmId;
    });

    var overpass = new Overpass( masterIds );

    var types = ['masters', 'stops', 'routes', 'ways', 'nodes'];

    /*
     * array of arrays with [routes, ways, nodes]
     */
    function saveData(data){
      var types = ['masters', 'stops', 'routes', 'ways', 'nodes'];
      _.each(data, function(arr, index){
        fs.writeFileSync('./cache/' + types[index] + '.json', JSON.stringify(arr));
      });
      console.log('data saved to ./cache');
    }

    /*
     * get all data and save to disk
     */
     return Promise.all(types.map(overpass.fetch, overpass))
       .then(saveData);

  },
  /**
   * load static assets from files
   *
   * list, list of file kind as specified in config file
   *
   * a file kind could be a simple file (csv or json)
   * or a directory of similar files
   *
   */
  loadData: function loadData(list){
    var data = this._data;
    return list.map(function(type){

      var file = data[type];
      var rootdir;
      var filepath;

      if (!file){
        throw new Error('No file config for type ' + type + '.');
      }
      // if it is a directory load all files in a bundle
      if ( file.isDirectory ){
        return fs.readdirSync( file.dir )
          .map(function(filename){
            filepath = file.dir + filename;
            return {
              name:filename,
              content:parser[ file.format ].call(undefined, filepath )
            };
         }).map( file.transform );
      } else {
        filepath = file.dir + type + file.ext;
        if ( !fs.existsSync(filepath)){
          throw new Error('File not found ' + filepath + '.');
        }
        return parser[ file.format ].call(undefined, filepath ).map(file.transform || _.identity);
      }
    });
  },
  saveDataAsCsv:function saveDataAsCsv(data, filepath){
    return new Promise(function(resolve, reject){
      converter.json2csv(data, function(err, csv){
        if (err){
          reject(err);
        } else {
          fs.writeFileSync( filepath, csv );
          resolve();
        }
      });
    });
  },
  validateGtfs:function(directory){
    var command = 'python '+ __dirname + '/utils/transitfeed/feedvalidator.py ' + directory;
    return new Promise(function(resolve, reject){
      exec(command, function (error, stdout, stderr) {
        if (error){
          reject(error);
        } else {
          resolve();
        }
      });
    });

  }
});

module.exports = GtfsMaker;
<|endoftext|>


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

var fs   = require('fs'),
    path = require('path'),
    url  = require('url'),
    templates = require('./templates'),
    Server = require('./server').Server;

Server.new(function (req, res) {
    console.log(req.url);
    var parsedUrl = url.parse(req.url, true);
    var pathname = path.normalize(parsedUrl.pathname);

    fs.stat('.' + pathname, function (err, stats) {
        if(err && err.code === "ENOENT") {
            Server.notFound(res);
        } else if (err) {
            Server.serverError(res, err);
        } else if(stats.isDirectory()) {
            res.writeHead(200, Server.contentTypes['text/html']);

            fs.readdir('.' + pathname, function(err, files) {
                if (err) {
                    Server.serverError(res, err);
                }
                var baseUrl = pathname.match(/^\/$/)? '/' : pathname + '/';
                res.end(templates.main({baseUrl: baseUrl, files: files}));
            });
        } else {
            var contentType = Server.mimetype(pathname);
            res.writeHead(200, Server.contentTypes[contentType]);
            fs.readFile('.' + pathname, function(err, data){
                if(err) { throw err; }
                res.end(data);
            });
        }
    });
});
<commit_msg>Use error response instead of throwing error<commit_after>#!/usr/bin/env node

var fs   = require('fs'),
    path = require('path'),
    url  = require('url'),
    templates = require('./templates'),
    Server = require('./server').Server;

Server.new(function (req, res) {
    console.log(req.url);
    var parsedUrl = url.parse(req.url, true);
    var pathname = path.normalize(parsedUrl.pathname);

    fs.stat('.' + pathname, function (err, stats) {
        if(err && err.code === "ENOENT") {
            Server.notFound(res);
        } else if (err) {
            Server.serverError(res, err);
        } else if(stats.isDirectory()) {
            res.writeHead(200, Server.contentTypes['text/html']);

            fs.readdir('.' + pathname, function(err, files) {
                if (err) {
                    Server.serverError(res, err);
                }
                var baseUrl = pathname.match(/^\/$/)? '/' : pathname + '/';
                res.end(templates.main({baseUrl: baseUrl, files: files}));
            });
        } else {
            var contentType = Server.mimetype(pathname);
            res.writeHead(200, Server.contentTypes[contentType]);
            fs.readFile('.' + pathname, function(err, data){
                if(err) { return Server.serverError(res, err); }
                return res.end(data);
            });
        }
    });
});
<|endoftext|>


<commit_before>module.exports.startServer = function startServer(options) {
  String.prototype.contains = function StringContainsProto(substring){
    // It would be better to get this from a generic library
    return this.indexOf(substring) > -1;
  };

  if (!options) options = {};

  var root = process.cwd() + (options.root ? '/'+options.root : '');
  console.log("ROOT", root);

  /**
   * Module dependencies.
   */

  var express = require('express')
    , http = require('http')
    , path = require('path')
    , fs = require('fs');

  var app = express();

  app.configure(function appConfig(){
    app.set('port', process.env.PORT || 3000);
    app.set('views', root);
    app.set('view engine', 'ejs'); // Probably don't need this
    app.use(express.favicon());
    app.use(express.logger('dev'));
    app.use(express.bodyParser());
    app.use(express.methodOverride());

    // From --sessions
    app.use(express.cookieParser(options.cookieSecret || 'psn trollin'));
    app.use(express.session({ secret: options.sessionSecret || 'PSN TROOOLLLS' }));

    app.use(app.router);

    // For use .styl files in public and have it 'just work'
    app.use(require('stylus').middleware(root));
    app.use(express.static(root));
  });

  app.configure('development', function(){
    app.use(express.errorHandler());
  });

  var StringifyForCircularRefs = require('JSONUtil').JSONUtil().stringify;

  /**
   * Routing:
   *
   * '*' route filters all GET's. We do this so we can filter and handle .ejs files.
   */
  app.get('*', function(req, res, expressNext) {

    /**
     * handleEjsRequest handles all the .ejs GET requests
     */
    var handleEjsRequest = function handleEjsRequest(req, res, file){
      file = file.toLowerCase();

      // Make request object non-circular

      res.render(file, {
        req: req,
        JSON: {
          stringify: StringifyForCircularRefs
        }
      });
    };

    // File is the requested file. (aka url)
    file = req.params[0].substr(1, req.params[0].length);
    if (file.contains('.ejs')) {
      handleEjsRequest(req, res, file);
    } else {
      if (file.contains('.')) {
        if (file.contains('?')) {
          throw 'woah, looks like you have a querystring for a non .ejs file. Please use a url to a .ejs file.';
        }

        // Forward request to /public folder.
        expressNext();
      } else {

        // If last character is a '/'
        if (file.charAt(file.length - 1) === '/') {

          // Point to index.ejs of that folder
          file = file + 'index.ejs';
        } else {

          // Very very root of whole site
          if (file === '') {

            // Point to 'index.ejs'
            file = 'index.ejs';
          } else {

            // Append '/index.ejs'
            file = file + '/index.ejs';
          }
        }
        handleEjsRequest(req, res, file);
      }
    }
  });

  http.createServer(app).listen(app.get('port'), function(){
    console.log('psn server running at: http://localhost:' + app.get('port').toString());
  });
};<commit_msg>mostly re-written DOCS OUT OF DATE :p<commit_after>String.prototype.contains = function StringContainsProto(substring){
  // It would be better to get this from a generic library
  return this.indexOf(substring) > -1;
};

/**
 * Module dependencies.
 */

var express = require('express')
  , http = require('http')
  , path = require('path')
  , fs = require('fs');

var app = express();

var wait = 350; //for simulated lag on localhost, because I'm crazy about performance.
process.env.NODE_ENV = 'production';
process.env.ROOT = 'app';
if (process.env.PORT && process.env.PORT !== 80) {
  wait = 0;
  process.env.NODE_ENV = 'production';
  process.env.ROOT = 'dist';
}
var root = process.cwd() + (process.env.ROOT ? '/'+process.env.ROOT : '');
console.log("ROOT", root);

app.configure(function appConfig(){
  app.set('port', process.env.PORT || 80);
  app.set('views', root);
  app.set('view engine', 'ejs'); // Probably don't need this
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());

  // From --sessions. `options` is no longer defined if you want to use this.
  //app.use(express.cookieParser(options.cookieSecret || 'psn trollin'));
  //app.use(express.session({ secret: options.sessionSecret || 'PSN TROOOLLLS' }));

  app.use(app.router);

  // For use .styl files in public and have it 'just work'
  app.use(require('stylus').middleware(root));
  app.use(express.static(root));
});

app.configure('development', function(){
  app.use(express.errorHandler());
});

var StringifyForCircularRefs = require('JSONUtil').JSONUtil().stringify;

/**
 * Routing:
 *
 * '*' route filters all GET's. We do this so we can filter and handle .ejs files.
 */
app.get('*', function(req, res, expressNext) {

  /**
   * handleEjsRequest handles all the .ejs GET requests
   */
  var handleEjsRequest = function handleEjsRequest(req, res, file){
    file = file.toLowerCase();

    // Make request object non-circular

    res.render(file, {
      req: req
    });
  };

  // File is the requested file. (aka url)
  file = req.params[0].substr(1, req.params[0].length);
  setTimeout(function(){
    if (file.contains('.ejs')) {
      handleEjsRequest(req, res, file);
    } else {
      if (file.contains('.')) {
        if (file.contains('?')) {
          throw 'woah, looks like you have a querystring for a non .ejs file. Please use a url to a .ejs file.';
        }

        // Forward request to /public folder.
        expressNext();
      } else {

        // If last character is a '/'
        if (file.charAt(file.length - 1) === '/') {

          // Point to index.ejs of that folder
          file = file + 'index.ejs';
        } else {

          // Very very root of whole site
          if (file === '') {

            // Point to 'index.ejs'
            file = 'index.ejs';
          } else {

            // Append '/index.ejs'
            file = file + '/index.ejs';
          }
        }
        handleEjsRequest(req, res, file);
      }
    }
  }, wait);
});

http.createServer(app).listen(app.get('port'), function(){
  console.log('psn server running at: http://localhost:' + app.get('port').toString());
});<|endoftext|>