text:
(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.xstream = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
"use strict";
var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
    function __() { this.constructor = d; }
    d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
};
var empty = {};
function noop() { }
function copy(a) {
    var l = a.length;
    var b = Array(l);
    for (var i = 0; i < l; ++i) {
        b[i] = a[i];
    }
    return b;
}
exports.emptyIL = {
    _n: noop,
    _e: noop,
    _c: noop,
};

function internalizeProducer(producer) {
    producer._start =
        function _start(il) {
            il.next = il._n;
            il.error = il._e;
            il.complete = il._c;
            this.start(il);
        };
    producer._stop = producer.stop;
}
function compose2(f1, f2) {
    return function composedFn(arg) {
        return f1(f2(arg));
    };
}
function and(f1, f2) {
    return function andFn(t) {
        return f1(t) && f2(t);
    };
}
var MergeProducer = (function () {
    function MergeProducer(insArr) {
        this.insArr = insArr;
        this.type = 'merge';
        this.out = null;
        this.ac = insArr.length;
    }
    MergeProducer.prototype._start = function (out) {
        this.out = out;
        var s = this.insArr;
        var L = s.length;
        for (var i = 0; i < L; i++) {
            s[i]._add(this);
        }
    };
    MergeProducer.prototype._stop = function () {
        var s = this.insArr;
        var L = s.length;
        for (var i = 0; i < L; i++) {
            s[i]._remove(this);
        }
        this.out = null;
        this.ac = L;
    };
    MergeProducer.prototype._n = function (t) {
        var u = this.out;
        if (!u)
            return;
        u._n(t);
    };
    MergeProducer.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    MergeProducer.prototype._c = function () {
        if (--this.ac === 0) {
            var u = this.out;
            if (!u)
                return;
            u._c();
        }
    };
    return MergeProducer;
}());
exports.MergeProducer = MergeProducer;
var CombineListener = (function () {
    function CombineListener(i, out, p) {
        this.i = i;
        this.out = out;
        this.p = p;
        p.ils.push(this);
    }
    CombineListener.prototype._n = function (t) {
        var p = this.p, out = this.out;
        if (!out)
            return;
        if (p.up(t, this.i)) {
            out._n(p.vals);
        }
    };
    CombineListener.prototype._e = function (err) {
        var out = this.out;
        if (!out)
            return;
        out._e(err);
    };
    CombineListener.prototype._c = function () {
        var p = this.p;
        if (!p.out)
            return;
        if (--p.Nc === 0) {
            p.out._c();
        }
    };
    return CombineListener;
}());
exports.CombineListener = CombineListener;
var CombineProducer = (function () {
    function CombineProducer(insArr) {
        this.insArr = insArr;
        this.type = 'combine';
        this.out = null;
        this.ils = [];
        var n = this.Nc = this.Nn = insArr.length;
        var vals = this.vals = new Array(n);
        for (var i = 0; i < n; i++) {
            vals[i] = empty;
        }
    }
    CombineProducer.prototype.up = function (t, i) {
        var v = this.vals[i];
        var Nn = !this.Nn ? 0 : v === empty ? --this.Nn : this.Nn;
        this.vals[i] = t;
        return Nn === 0;
    };
    CombineProducer.prototype._start = function (out) {
        this.out = out;
        var s = this.insArr;
        var n = s.length;
        if (n === 0) {
            out._n([]);
            out._c();
        }
        else {
            for (var i = 0; i < n; i++) {
                s[i]._add(new CombineListener(i, out, this));
            }
        }
    };
    CombineProducer.prototype._stop = function () {
        var s = this.insArr;
        var n = this.Nc = this.Nn = s.length;
        var vals = this.vals = new Array(n);
        for (var i = 0; i < n; i++) {
            s[i]._remove(this.ils[i]);
            vals[i] = empty;
        }
        this.out = null;
        this.ils = [];
    };
    return CombineProducer;
}());
exports.CombineProducer = CombineProducer;
var FromArrayProducer = (function () {
    function FromArrayProducer(a) {
        this.a = a;
        this.type = 'fromArray';
    }
    FromArrayProducer.prototype._start = function (out) {
        var a = this.a;
        for (var i = 0, l = a.length; i < l; i++) {
            out._n(a[i]);
        }
        out._c();
    };
    FromArrayProducer.prototype._stop = function () {
    };
    return FromArrayProducer;
}());
exports.FromArrayProducer = FromArrayProducer;
var FromPromiseProducer = (function () {
    function FromPromiseProducer(p) {
        this.p = p;
        this.type = 'fromPromise';
        this.on = false;
    }
    FromPromiseProducer.prototype._start = function (out) {
        var prod = this;
        this.on = true;
        this.p.then(function (v) {
            if (prod.on) {
                out._n(v);
                out._c();
            }
        }, function (e) {
            out._e(e);
        }).then(null, function (err) {
            setTimeout(function () { throw err; });
        });
    };
    FromPromiseProducer.prototype._stop = function () {
        this.on = false;
    };
    return FromPromiseProducer;
}());
exports.FromPromiseProducer = FromPromiseProducer;
var PeriodicProducer = (function () {
    function PeriodicProducer(period) {
        this.period = period;
        this.type = 'periodic';
        this.intervalID = -1;
        this.i = 0;
    }
    PeriodicProducer.prototype._start = function (stream) {
        var self = this;
        function intervalHandler() { stream._n(self.i++); }
        this.intervalID = setInterval(intervalHandler, this.period);
    };
    PeriodicProducer.prototype._stop = function () {
        if (this.intervalID !== -1)
            clearInterval(this.intervalID);
        this.intervalID = -1;
        this.i = 0;
    };
    return PeriodicProducer;
}());
exports.PeriodicProducer = PeriodicProducer;
var DebugOperator = (function () {
    function DebugOperator(arg, ins) {
        this.ins = ins;
        this.type = 'debug';
        this.out = null;
        this.s = null;
        this.l = null;
        if (typeof arg === 'string') {
            this.l = arg;
        }
        else {
            this.s = arg;
        }
    }
    DebugOperator.prototype._start = function (out) {
        this.out = out;
        this.ins._add(this);
    };
    DebugOperator.prototype._stop = function () {
        this.ins._remove(this);
        this.out = null;
    };
    DebugOperator.prototype._n = function (t) {
        var u = this.out;
        if (!u)
            return;
        var s = this.s, l = this.l;
        if (s) {
            try {
                s(t);
            }
            catch (e) {
                u._e(e);
            }
        }
        else if (l) {
            console.log(l + ':', t);
        }
        else {
            console.log(t);
        }
        u._n(t);
    };
    DebugOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    DebugOperator.prototype._c = function () {
        var u = this.out;
        if (!u)
            return;
        u._c();
    };
    return DebugOperator;
}());
exports.DebugOperator = DebugOperator;
var DropOperator = (function () {
    function DropOperator(max, ins) {
        this.max = max;
        this.ins = ins;
        this.type = 'drop';
        this.out = null;
        this.dropped = 0;
    }
    DropOperator.prototype._start = function (out) {
        this.out = out;
        this.ins._add(this);
    };
    DropOperator.prototype._stop = function () {
        this.ins._remove(this);
        this.out = null;
        this.dropped = 0;
    };
    DropOperator.prototype._n = function (t) {
        var u = this.out;
        if (!u)
            return;
        if (this.dropped++ >= this.max)
            u._n(t);
    };
    DropOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    DropOperator.prototype._c = function () {
        var u = this.out;
        if (!u)
            return;
        u._c();
    };
    return DropOperator;
}());
exports.DropOperator = DropOperator;
var OtherIL = (function () {
    function OtherIL(out, op) {
        this.out = out;
        this.op = op;
    }
    OtherIL.prototype._n = function (t) {
        this.op.end();
    };
    OtherIL.prototype._e = function (err) {
        this.out._e(err);
    };
    OtherIL.prototype._c = function () {
        this.op.end();
    };
    return OtherIL;
}());
var EndWhenOperator = (function () {
    function EndWhenOperator(o,
        ins) {
        this.o = o;
        this.ins = ins;
        this.type = 'endWhen';
        this.out = null;
        this.oil = exports.emptyIL;
    }
    EndWhenOperator.prototype._start = function (out) {
        this.out = out;
        this.o._add(this.oil = new OtherIL(out, this));
        this.ins._add(this);
    };
    EndWhenOperator.prototype._stop = function () {
        this.ins._remove(this);
        this.o._remove(this.oil);
        this.out = null;
        this.oil = null;
    };
    EndWhenOperator.prototype.end = function () {
        var u = this.out;
        if (!u)
            return;
        u._c();
    };
    EndWhenOperator.prototype._n = function (t) {
        var u = this.out;
        if (!u)
            return;
        u._n(t);
    };
    EndWhenOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    EndWhenOperator.prototype._c = function () {
        this.end();
    };
    return EndWhenOperator;
}());
exports.EndWhenOperator = EndWhenOperator;
var FilterOperator = (function () {
    function FilterOperator(passes, ins) {
        this.passes = passes;
        this.ins = ins;
        this.type = 'filter';
        this.out = null;
    }
    FilterOperator.prototype._start = function (out) {
        this.out = out;
        this.ins._add(this);
    };
    FilterOperator.prototype._stop = function () {
        this.ins._remove(this);
        this.out = null;
    };
    FilterOperator.prototype._n = function (t) {
        var u = this.out;
        if (!u)
            return;
        try {
            if (this.passes(t))
                u._n(t);
        }
        catch (e) {
            u._e(e);
        }
    };
    FilterOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    FilterOperator.prototype._c = function () {
        var u = this.out;
        if (!u)
            return;
        u._c();
    };
    return FilterOperator;
}());
exports.FilterOperator = FilterOperator;
var FlattenListener = (function () {
    function FlattenListener(out, op) {
        this.out = out;
        this.op = op;
    }
    FlattenListener.prototype._n = function (t) {
        this.out._n(t);
    };
    FlattenListener.prototype._e = function (err) {
        this.out._e(err);
    };
    FlattenListener.prototype._c = function () {
        this.op.inner = null;
        this.op.less();
    };
    return FlattenListener;
}());
var FlattenOperator = (function () {
    function FlattenOperator(ins) {
        this.ins = ins;
        this.type = 'flatten';
        this.inner = null;
        this.il = null;
        this.open = true;
        this.out = null;
    }
    FlattenOperator.prototype._start = function (out) {
        this.out = out;
        this.ins._add(this);
    };
    FlattenOperator.prototype._stop = function () {
        this.ins._remove(this);
        this.inner = null;
        this.il = null;
        this.open = true;
        this.out = null;
    };
    FlattenOperator.prototype.less = function () {
        var u = this.out;
        if (!u)
            return;
        if (!this.open && !this.inner)
            u._c();
    };
    FlattenOperator.prototype._n = function (s) {
        var u = this.out;
        if (!u)
            return;
        var _a = this, inner = _a.inner, il = _a.il;
        if (inner && il)
            inner._remove(il);
        (this.inner = s)._add(this.il = new FlattenListener(u, this));
    };
    FlattenOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    FlattenOperator.prototype._c = function () {
        this.open = false;
        this.less();
    };
    return FlattenOperator;
}());
exports.FlattenOperator = FlattenOperator;
var FoldOperator = (function () {
    function FoldOperator(f, seed, ins) {
        this.f = f;
        this.seed = seed;
        this.ins = ins;
        this.type = 'fold';
        this.out = null;
        this.acc = seed;
    }
    FoldOperator.prototype._start = function (out) {
        this.out = out;
        out._n(this.acc);
        this.ins._add(this);
    };
    FoldOperator.prototype._stop = function () {
        this.ins._remove(this);
        this.out = null;
        this.acc = this.seed;
    };
    FoldOperator.prototype._n = function (t) {
        var u = this.out;
        if (!u)
            return;
        try {
            u._n(this.acc = this.f(this.acc, t));
        }
        catch (e) {
            u._e(e);
        }
    };
    FoldOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    FoldOperator.prototype._c = function () {
        var u = this.out;
        if (!u)
            return;
        u._c();
    };
    return FoldOperator;
}());
exports.FoldOperator = FoldOperator;
var LastOperator = (function () {
    function LastOperator(ins) {
        this.ins = ins;
        this.type = 'last';
        this.out = null;
        this.has = false;
        this.val = empty;
    }
    LastOperator.prototype._start = function (out) {
        this.out = out;
        this.ins._add(this);
    };
    LastOperator.prototype._stop = function () {
        this.ins._remove(this);
        this.out = null;
        this.has = false;
        this.val = empty;
    };
    LastOperator.prototype._n = function (t) {
        this.has = true;
        this.val = t;
    };
    LastOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    LastOperator.prototype._c = function () {
        var u = this.out;
        if (!u)
            return;
        if (this.has) {
            u._n(this.val);
            u._c();
        }
        else {
            u._e('TODO show proper error');
        }
    };
    return LastOperator;
}());
exports.LastOperator = LastOperator;
var MapFlattenInner = (function () {
    function MapFlattenInner(out, op) {
        this.out = out;
        this.op = op;
    }
    MapFlattenInner.prototype._n = function (r) {
        this.out._n(r);
    };
    MapFlattenInner.prototype._e = function (err) {
        this.out._e(err);
    };
    MapFlattenInner.prototype._c = function () {
        this.op.inner = null;
        this.op.less();
    };
    return MapFlattenInner;
}());
var MapFlattenOperator = (function () {
    function MapFlattenOperator(mapOp) {
        this.mapOp = mapOp;
        this.inner = null;
        this.il = null;
        this.open = true;
        this.out = null;
        this.type = mapOp.type + "+flatten";
        this.ins = mapOp.ins;
    }
    MapFlattenOperator.prototype._start = function (out) {
        this.out = out;
        this.mapOp.ins._add(this);
    };
    MapFlattenOperator.prototype._stop = function () {
        this.mapOp.ins._remove(this);
        this.inner = null;
        this.il = null;
        this.open = true;
        this.out = null;
    };
    MapFlattenOperator.prototype.less = function () {
        if (!this.open && !this.inner) {
            var u = this.out;
            if (!u)
                return;
            u._c();
        }
    };
    MapFlattenOperator.prototype._n = function (v) {
        var u = this.out;
        if (!u)
            return;
        var _a = this, inner = _a.inner, il = _a.il;
        if (inner && il)
            inner._remove(il);
        try {
            (this.inner = this.mapOp.project(v))._add(this.il = new MapFlattenInner(u, this));
        }
        catch (e) {
            u._e(e);
        }
    };
    MapFlattenOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    MapFlattenOperator.prototype._c = function () {
        this.open = false;
        this.less();
    };
    return MapFlattenOperator;
}());
exports.MapFlattenOperator = MapFlattenOperator;
var MapOperator = (function () {
    function MapOperator(project, ins) {
        this.project = project;
        this.ins = ins;
        this.type = 'map';
        this.out = null;
    }
    MapOperator.prototype._start = function (out) {
        this.out = out;
        this.ins._add(this);
    };
    MapOperator.prototype._stop = function () {
        this.ins._remove(this);
        this.out = null;
    };
    MapOperator.prototype._n = function (t) {
        var u = this.out;
        if (!u)
            return;
        try {
            u._n(this.project(t));
        }
        catch (e) {
            u._e(e);
        }
    };
    MapOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    MapOperator.prototype._c = function () {
        var u = this.out;
        if (!u)
            return;
        u._c();
    };
    return MapOperator;
}());
exports.MapOperator = MapOperator;
var FilterMapOperator = (function (_super) {
    __extends(FilterMapOperator, _super);
    function FilterMapOperator(passes, project, ins) {
        _super.call(this, project, ins);
        this.passes = passes;
        this.type = 'filter+map';
    }
    FilterMapOperator.prototype._n = function (v) {
        if (this.passes(v)) {
            _super.prototype._n.call(this, v);
        }
        ;
    };
    return FilterMapOperator;
}(MapOperator));
exports.FilterMapOperator = FilterMapOperator;
var ReplaceErrorOperator = (function () {
    function ReplaceErrorOperator(fn, ins) {
        this.fn = fn;
        this.ins = ins;
        this.type = 'replaceError';
        this.out = empty;
    }
    ReplaceErrorOperator.prototype._start = function (out) {
        this.out = out;
        this.ins._add(this);
    };
    ReplaceErrorOperator.prototype._stop = function () {
        this.ins._remove(this);
        this.out = null;
    };
    ReplaceErrorOperator.prototype._n = function (t) {
        var u = this.out;
        if (!u)
            return;
        u._n(t);
    };
    ReplaceErrorOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        try {
            this.ins._remove(this);
            (this.ins = this.fn(err))._add(this);
        }
        catch (e) {
            u._e(e);
        }
    };
    ReplaceErrorOperator.prototype._c = function () {
        var u = this.out;
        if (!u)
            return;
        u._c();
    };
    return ReplaceErrorOperator;
}());
exports.ReplaceErrorOperator = ReplaceErrorOperator;
var StartWithOperator = (function () {
    function StartWithOperator(ins, value) {
        this.ins = ins;
        this.value = value;
        this.type = 'startWith';
        this.out = exports.emptyIL;
    }
    StartWithOperator.prototype._start = function (out) {
        this.out = out;
        this.out._n(this.value);
        this.ins._add(out);
    };
    StartWithOperator.prototype._stop = function () {
        this.ins._remove(this.out);
        this.out = null;
    };
    return StartWithOperator;
}());
exports.StartWithOperator = StartWithOperator;
var TakeOperator = (function () {
    function TakeOperator(max, ins) {
        this.max = max;
        this.ins = ins;
        this.type = 'take';
        this.out = null;
        this.taken = 0;
    }
    TakeOperator.prototype._start = function (out) {
        this.out = out;
        this.ins._add(this);
    };
    TakeOperator.prototype._stop = function () {
        this.ins._remove(this);
        this.out = null;
        this.taken = 0;
    };
    TakeOperator.prototype._n = function (t) {
        var u = this.out;
        if (!u)
            return;
        if (this.taken++ < this.max - 1) {
            u._n(t);
        }
        else {
            u._n(t);
            u._c();
        }
    };
    TakeOperator.prototype._e = function (err) {
        var u = this.out;
        if (!u)
            return;
        u._e(err);
    };
    TakeOperator.prototype._c = function () {
        var u = this.out;
        if (!u)
            return;
        u._c();
    };
    return TakeOperator;
}());
exports.TakeOperator = TakeOperator;
var Stream = (function () {
    function Stream(producer) {
        this._stopID = empty;
        this._prod = producer;
        this._ils = [];
        this._target = null;
        this._err = null;
    }
    Stream.prototype._n = function (t) {
        var a = this._ils;
        var L = a.length;
        if (L == 1)
            a[0]._n(t);
        else {
            var b = copy(a);
            for (var i = 0; i < L; i++)
                b[i]._n(t);
        }
    };
    Stream.prototype._e = function (err) {
        if (this._err)
            return;
        this._err = err;
        var a = this._ils;
        var L = a.length;
        if (L == 1)
            a[0]._e(err);
        else {
            var b = copy(a);
            for (var i = 0; i < L; i++)
                b[i]._e(err);
        }
        this._x();
    };
    Stream.prototype._c = function () {
        var a = this._ils;
        var L = a.length;
        if (L == 1)
            a[0]._c();
        else {
            var b = copy(a);
            for (var i = 0; i < L; i++)
                b[i]._c();
        }
        this._x();
    };
    Stream.prototype._x = function () {
        if (this._ils.length === 0)
            return;
        if (this._prod)
            this._prod._stop();
        this._err = null;
        this._ils = [];
    };

    Stream.prototype.addListener = function (listener) {
        if (typeof listener.next !== 'function'
            || typeof listener.error !== 'function'
            || typeof listener.complete !== 'function') {
            throw new Error('stream.addListener() requires all three next, error, ' +
                'and complete functions.');
        }
        listener._n = listener.next;
        listener._e = listener.error;
        listener._c = listener.complete;
        this._add(listener);
    };

    Stream.prototype.removeListener = function (listener) {
        this._remove(listener);
    };
    Stream.prototype._add = function (il) {
        var ta = this._target;
        if (ta)
            return ta._add(il);
        var a = this._ils;
        a.push(il);
        if (a.length === 1) {
            if (this._stopID !== empty) {
                clearTimeout(this._stopID);
                this._stopID = empty;
            }
            var p = this._prod;
            if (p)
                p._start(this);
        }
    };
    Stream.prototype._remove = function (il) {
        var ta = this._target;
        if (ta)
            return ta._remove(il);
        var a = this._ils;
        var i = a.indexOf(il);
        if (i > -1) {
            a.splice(i, 1);
            var p_1 = this._prod;
            if (p_1 && a.length <= 0) {
                this._err = null;
                this._stopID = setTimeout(function () { return p_1._stop(); });
            }
            else if (a.length === 1) {
                this._pruneCycles();
            }
        }
    };

    Stream.prototype._pruneCycles = function () {
        if (this._onlyReachesThis(this)) {
            this._remove(this._ils[0]);
        }
    };

    Stream.prototype._onlyReachesThis = function (x) {
        if (x.out === this) {
            return true;
        }
        else if (x.out) {
            return this._onlyReachesThis(x.out);
        }
        else if (x._ils) {
            for (var i = 0, N = x._ils.length; i < N; i++) {
                if (!this._onlyReachesThis(x._ils[i]))
                    return false;
            }
            return true;
        }
        else {
            return false;
        }
    };
    Stream.prototype.ctor = function () {
        return this instanceof MemoryStream ? MemoryStream : Stream;
    };

    Stream.create = function (producer) {
        if (producer) {
            if (typeof producer.start !== 'function'
                || typeof producer.stop !== 'function') {
                throw new Error('producer requires both start and stop functions');
            }
            internalizeProducer(producer);
        }
        return new Stream(producer);
    };

    Stream.createWithMemory = function (producer) {
        if (producer) {
            internalizeProducer(producer);
        }
        return new MemoryStream(producer);
    };

    Stream.never = function () {
        return new Stream({ _start: noop, _stop: noop });
    };

    Stream.empty = function () {
        return new Stream({
            _start: function (il) { il._c(); },
            _stop: noop,
        });
    };

    Stream.throw = function (error) {
        return new Stream({
            _start: function (il) { il._e(error); },
            _stop: noop,
        });
    };

    Stream.of = function () {
        var items = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            items[_i - 0] = arguments[_i];
        }
        return Stream.fromArray(items);
    };

    Stream.fromArray = function (array) {
        return new Stream(new FromArrayProducer(array));
    };

    Stream.fromPromise = function (promise) {
        return new Stream(new FromPromiseProducer(promise));
    };

    Stream.periodic = function (period) {
        return new Stream(new PeriodicProducer(period));
    };

    Stream.merge = function () {
        var streams = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            streams[_i - 0] = arguments[_i];
        }
        return new Stream(new MergeProducer(streams));
    };
    Stream.prototype._map = function (project) {
        var p = this._prod;
        var ctor = this.ctor();
        if (p instanceof FilterOperator) {
            return new ctor(new FilterMapOperator(p.passes, project, p.ins));
        }
        if (p instanceof FilterMapOperator) {
            return new ctor(new FilterMapOperator(p.passes, compose2(project, p.project), p.ins));
        }
        if (p instanceof MapOperator) {
            return new ctor(new MapOperator(compose2(project, p.project), p.ins));
        }
        return new ctor(new MapOperator(project, this));
    };

    Stream.prototype.map = function (project) {
        return this._map(project);
    };

    Stream.prototype.mapTo = function (projectedValue) {
        var s = this.map(function () { return projectedValue; });
        var op = s._prod;
        op.type = op.type.replace('map', 'mapTo');
        return s;
    };

    Stream.prototype.filter = function (passes) {
        var p = this._prod;
        if (p instanceof FilterOperator) {
            return new Stream(new FilterOperator(and(passes, p.passes), p.ins));
        }
        return new Stream(new FilterOperator(passes, this));
    };

    Stream.prototype.take = function (amount) {
        return new (this.ctor())(new TakeOperator(amount, this));
    };

    Stream.prototype.drop = function (amount) {
        return new Stream(new DropOperator(amount, this));
    };

    Stream.prototype.last = function () {
        return new Stream(new LastOperator(this));
    };

    Stream.prototype.startWith = function (initial) {
        return new MemoryStream(new StartWithOperator(this, initial));
    };

    Stream.prototype.endWhen = function (other) {
        return new (this.ctor())(new EndWhenOperator(other, this));
    };

    Stream.prototype.fold = function (accumulate, seed) {
        return new MemoryStream(new FoldOperator(accumulate, seed, this));
    };

    Stream.prototype.replaceError = function (replace) {
        return new (this.ctor())(new ReplaceErrorOperator(replace, this));
    };

    Stream.prototype.flatten = function () {
        var p = this._prod;
        return new Stream(p instanceof MapOperator && !(p instanceof FilterMapOperator) ?
            new MapFlattenOperator(p) :
            new FlattenOperator(this));
    };

    Stream.prototype.compose = function (operator) {
        return operator(this);
    };

    Stream.prototype.remember = function () {
        var _this = this;
        return new MemoryStream({
            _start: function (il) {
                var p = _this._prod;
                if (p)
                    p._start(il);
            },
            _stop: function () {
                var p = _this._prod;
                if (p)
                    p._stop();
            },
        });
    };

    Stream.prototype.debug = function (labelOrSpy) {
        return new (this.ctor())(new DebugOperator(labelOrSpy, this));
    };

    Stream.prototype.imitate = function (target) {
        if (target instanceof MemoryStream) {
            throw new Error('A MemoryStream was given to imitate(), but it only ' +
                'supports a Stream. Read more about this restriction here: ' +
                'https://github.com/staltz/xstream#faq');
        }
        this._target = target;
    };

    Stream.prototype.shamefullySendNext = function (value) {
        this._n(value);
    };

    Stream.prototype.shamefullySendError = function (error) {
        this._e(error);
    };

    Stream.prototype.shamefullySendComplete = function () {
        this._c();
    };

    Stream.combine = function combine() {
        var streams = [];
        for (var _i = 0; _i < arguments.length; _i++) {
            streams[_i - 0] = arguments[_i];
        }
        return new Stream(new CombineProducer(streams));
    };
    return Stream;
}());
exports.Stream = Stream;
var MemoryStream = (function (_super) {
    __extends(MemoryStream, _super);
    function MemoryStream(producer) {
        _super.call(this, producer);
        this._has = false;
    }
    MemoryStream.prototype._n = function (x) {
        this._v = x;
        this._has = true;
        _super.prototype._n.call(this, x);
    };
    MemoryStream.prototype._add = function (il) {
        if (this._has) {
            il._n(this._v);
        }
        _super.prototype._add.call(this, il);
    };
    MemoryStream.prototype._x = function () {
        this._has = false;
        _super.prototype._x.call(this);
    };
    MemoryStream.prototype.map = function (project) {
        return this._map(project);
    };
    MemoryStream.prototype.mapTo = function (projectedValue) {
        return _super.prototype.mapTo.call(this, projectedValue);
    };
    MemoryStream.prototype.take = function (amount) {
        return _super.prototype.take.call(this, amount);
    };
    MemoryStream.prototype.endWhen = function (other) {
        return _super.prototype.endWhen.call(this, other);
    };
    MemoryStream.prototype.replaceError = function (replace) {
        return _super.prototype.replaceError.call(this, replace);
    };
    MemoryStream.prototype.debug = function (labelOrSpy) {
        return _super.prototype.debug.call(this, labelOrSpy);
    };
    return MemoryStream;
}(Stream));
exports.MemoryStream = MemoryStream;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = Stream;

},{}],2:[function(require,module,exports){
"use strict";
var core_1 = require('./core');
exports.Stream = core_1.Stream;
exports.MemoryStream = core_1.MemoryStream;
Object.defineProperty(exports, "__esModule", { value: true });
exports.default = core_1.Stream;

},{"./core":1}]},{},[2])(2)
});


text:
You have portions of your views layer that use the same or similar HTML in many places.

### Solution
Write a custom Handlebars helper that can be called from any template and gets updated when the model changes.

### Discussion

```html
<script type="text/x-handlebars">
   $ {{dollar model}}
</script>
```

```js
App = Ember.Application.create();

App.ApplicationRoute = Ember.Route.extend({
  model: function() {
    return 980; // cents
  }
});

Ember.Handlebars.registerBoundHelper('dollar', function(cents) {
  var dollar = Math.floor(cents / 100);

  return dollar;
});
```

JS Bin

redpajama_set_name: RedPajamaGithub


text:
define([
  'backbone',
], function(Backbone) {

      return Backbone.Collection.extend({
        url: '/api/movies'
      });

});


text:
(function() {
  var LINE_PREFIX, childProcess, flatten, gaze, minimatch;

  minimatch = require('minimatch');

  gaze = require('gaze');

  childProcess = require('child_process');

  flatten = require('lodash').flatten;

  LINE_PREFIX = "---";

  module.exports = function(path, command, opts) {
    var END_COLOR, START_COLOR, color, daemon, exclude, excluded, include, interval, log, process, restartProcess, startProcess;
    if (opts == null) {
      opts = {};
    }
    color = opts.color, daemon = opts.daemon, interval = opts.interval, exclude = opts.exclude, include = opts.include;
    if (interval == null) {
      interval = 1000;
    }
    START_COLOR = color ? "\x1b[30;1m" : "";
    END_COLOR = color ? "\x1b[0m" : "";
    log = function(message) {
      return console.log("" + START_COLOR + LINE_PREFIX + " " + message + END_COLOR);
    };
    excluded = function(file) {
      if (!exclude || exclude.length === 0) {
        return false;
      }
      return flatten([false, exclude]).reduce(function(memo, x) {
        var trimLen;
        trimLen = x.indexOf('/') && path.length + 1;
        return minimatch(file.substr(trimLen), x);
      });
    };
    process = null;
    log("Observing files in `" + path + "` and running `" + command + "` on changes");
    include.forEach(function(i) {
      return log("Include files matching: " + i);
    });
    exclude.forEach(function(x) {
      return log("Exclude files matching: " + x);
    });
    if (daemon) {
      process = startProcess();
      startProcess = processRestarter(startProcess);
    }
    gaze(include, function(err, watcher) {
      return watcher.on('all', function(evt, file) {
        if (excluded(file) || process) {
          return;
        }
        log("Change detected for " + file);
        return process = startProcess();
      });
    });
    startProcess = function() {
      var child, processRestarter;
      if (daemon) {
        log("Starting `" + command + "`");
      } else {
        log("Running `" + command + "`");
      }
      child = childProcess.spawn("sh", ['-c', command], {
        stdio: 'inherit'
      });
      child.on('exit', function(code) {
        if (code == null) {
          code = 0;
        }
        log("PID " + child.pid + " exited with " + code);
        return process = null;
      });
      child;

      processRestarter = function(startFn) {};
      return function() {
        if (process == null) {
          return process = startFn();
        }
        log("Killing process with PID " + process.pid);
        process.removeListener('exit', earlyProcessExit);
        process.on('exit', restartProcess(process, startFn));
        return process.kill();
      };
    };
    return restartProcess = function(oldProcess, startFn) {
      return function(code) {
        if (code == null) {
          code = 0;
        }
        log("PID " + oldProcess.pid + " exited with " + code);
        return process = startFn();
      };
    };
  };

}).call(this);


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
Sydowia 1: 277 (1947)

#### Original name
Zernya Petr.

### Remarks
null


text:
import { MailingList } from '../models/mailing-list.model';
import { CONTACTS, RESPONSE_CONTACTS } from '../test-data/test-contacts';

export const MAILING_LISTS: MailingList[] = [
    new MailingList(1, 'New customers', 'Description 1', CONTACTS,
        new Date().toDateString(), new Date().toDateString()),
    new MailingList(2, 'Women', 'Description 2', CONTACTS,
        new Date().toDateString(), new Date().toDateString()),
    new MailingList(3, 'Men', 'Description 3', CONTACTS,
        new Date().toDateString(), new Date().toDateString())
];

export const RESPONSE_MAILING_LISTS = [
    {
        id: 1,
        name: 'test list',
        description: 'test description',
        members: RESPONSE_CONTACTS,
        createdAt: new Date().toDateString(),
        updatedAt: new Date().toDateString()
    },
    {
        id: 2,
        name: 'test list2',
        description: 'test description2',
        members: RESPONSE_CONTACTS,
        createdAt: new Date().toDateString(),
        updatedAt: new Date().toDateString()
    },
    {
        id: 3,
        name: 'test list3',
        description: 'test description3',
        members: RESPONSE_CONTACTS,
        createdAt: new Date().toDateString(),
        updatedAt: new Date().toDateString()
    }
];


text:
static inline NSDictionary* build_error(enum ErrorCode code, NSString* message, enum ErrorCategory category) {
    if (message == nil) {
        message = @"";
    }
    return @{ @"error" : [NSNumber numberWithInt:code],
            @"message" : message,
           @"errorcat" : [NSNumber numberWithInt:category] };
}

static inline NSDictionary* build_error_with_data(enum ErrorCode code, NSString* message, enum ErrorCategory category, NSString * key, id object) {
    if (message == nil) {
        message = @"";
    }
    if ((!key.length) || (object == nil)) {
        return build_error(code, message, category);
    }
    return @{ @"error" : [NSNumber numberWithInt:code],
            @"message" : message,
           @"errorcat" : [NSNumber numberWithInt:category],
                   key : object };
}

@implementation MFErrorMessage

//------------------------------------------------------------------------------
+ (BOOL)isErrorMessage:(NSDictionary*)object {
  if ( object == nil ) return NO;
  return [self code:object] != ERRCODE_UNKNOWN &&
         [self category:object] != ERRCAT_UNKNOWN &&
         [self message:object] != nil;
}

//------------------------------------------------------------------------------
+ (BOOL)isAuthenticationError:(NSDictionary *)object {
    // The authentication error code may appear in three places. To be safe,
    // we check all codes in all known places.

    if ([self isErrorMessage:object]) {
        NSInteger code = [self code:object];

        if ([self isAuthenticationErrorCode:code]) {
            return true;
        }
    }

    if (object[@"error"] != nil) {
        id error = object[@"error"];
        if ([error respondsToSelector:@selector(integerValue)]) {
            NSInteger code = [object[@"error"] integerValue];

            if ([self isAuthenticationErrorCode:code]) {
                return true;
            }
        }
    }

    if (object[@"response"] != nil && [object[@"response"] isKindOfClass:[NSDictionary class]]) {
        NSDictionary* response = object[@"response"];

        id error = response[@"error"];
        if ([error respondsToSelector:@selector(integerValue)]) {
            NSInteger code = [response[@"error"] integerValue];

            if ([self isAuthenticationErrorCode:code]) {
                return true;
            }
        }
    }

    return false;
}

//------------------------------------------------------------------------------
+ (BOOL)isAuthenticationErrorCode:(NSInteger)code {
    BOOL authErr = false;

    switch (code) {
        case 102: // missing key
        case 103: // invalid key
        case 107: // invalid creds
        case 108: // invalid user
        case 109: // invalid app id
        case 128: // missing params
        case 129: // invalid params
        case 220: // failed to authenticate to Facebook
        case 232: // failed to authenticate with Facebook because MF email isn't verified
            authErr = true;
            break;

        default:
            break;
    }

    return authErr;
}

//------------------------------------------------------------------------------
+ (NSInteger)code:(NSDictionary*)errorObject {
    NSNumber* number = errorObject[@"error"];
    if ( number == nil ) return (NSInteger)ERRCODE_UNKNOWN;
    else return [number integerValue];
}

//------------------------------------------------------------------------------
+ (NSInteger)category:(NSDictionary*)errorObject {
    NSNumber* number = errorObject[@"errorcat"];
    if ( number == nil ) return (NSInteger)ERRCAT_UNKNOWN;
    else return [number integerValue];
}

//------------------------------------------------------------------------------
+ (NSString*)message:(NSDictionary*)errorObject {
    return errorObject[@"message"];
}

//------------------------------------------------------------------------------
+ (NSDictionary*)NullDictionary {
    return build_error(ERRCODE_NULL_DICTIONARY, @"An illegal nil dict was found.", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)NullCallback {
    return build_error(ERRCODE_NULL_CALLBACK, @"An illegal nil callback was found.", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)nullField {
    return build_error(ERRCODE_NULL_FIELD, @"An illegal nil string or number was found.", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)nullField:(NSString*)fieldName {
    return build_error_with_data(ERRCODE_NULL_FIELD, [NSString stringWithFormat:@"An illegal nil value was found: %@.", fieldName], ERRCAT_APP, @"name", fieldName);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)invalidField:(NSString*)fieldName {
    return build_error_with_data(ERRCODE_INVALID_FIELD, @"An invalid string or number was found.", ERRCAT_APP, @"name", fieldName);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)nullURL {
  return build_error(ERRCODE_NULL_URL, @"An illegal nil URL was found.", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)badResponse:(NSDictionary*)response {
    NSDictionary* error;
    NSInteger apiError = 0;
    // first check for upload response errors
    id doUpload = response[@"doupload"];
    if (doUpload != nil && [doUpload isKindOfClass:[NSDictionary class]]) {
        id doUploadResult = doUpload[@"result"];
        if ([doUploadResult integerValue] == -99) {
            return build_error(ERRCODE_INVALID_SESSION_TOKEN,
                        @"Invalid session token",
                        ERRCAT_API);
        }

        return build_error_with_data((NSInteger)ERRCODE_API_ERROR,
                              @"REST API error",
                              ERRCAT_API,
                              @"response",
                              response);

    }
    // check for normal api errors
    id errorCode = response[@"error"];
    if ( errorCode == nil ) return build_error_with_data(ERRCODE_UNRECOGNIZED_API_RESPONSE,
                                                         @"API error does not contain error code",
                                                         ERRCAT_API,
                                                         @"response",
                                                         response);
    apiError = [errorCode integerValue];
    switch ( apiError ) {
        case 100:
            error = build_error(ERRCODE_INTERNAL_SERVER_ERROR,
                                @"REST Internal server error",
                                ERRCAT_API);
            break;
        case 105:
            error = build_error(ERRCODE_INVALID_SESSION_TOKEN,
                                @"Invalid session token",
                                ERRCAT_API);
            break;
        case 107:
        case 108:
            error = build_error_with_data(ERRCODE_INVALID_CREDENTIALS,
                                          @"Invalid user credentials",
                                          ERRCAT_API,
                                          @"response",
                                          response);
            break;
        case 109:
            error = build_error_with_data(ERRCODE_INVALID_PARAMETERS,
                                          @"Invalid application ID",
                                          ERRCAT_API,
                                          @"response",
                                          response);
            break;
        case 127:
            error = build_error(ERRCODE_INVALID_SIGNATURE,
                                @"Invalid signature",
                                ERRCAT_API);
            break;
        case 128:
            error = build_error_with_data(ERRCODE_MISSING_PARAMETERS,
                                          @"Missing parameters",
                                          ERRCAT_API,
                                          @"response",
                                          response);
            break;
        case 129:
            error = build_error_with_data(ERRCODE_INVALID_PARAMETERS,
                                          @"Invalid parameters",
                                          ERRCAT_API,
                                          @"response",
                                          response);
            break;
        default:
            error = build_error_with_data((enum ErrorCode)(ERRCODE_API_ERROR + apiError),
                                          @"REST API error",
                                          ERRCAT_API,
                                          @"response",
                                          response);
    }

    return error;
}

//------------------------------------------------------------------------------
+ (NSDictionary*)badHTTP:(NSInteger)status message:(id)response {
    // Response is not guaranteed to be valid JSON. Try to deserialize JSON to
    // find API error 'message'. If failure, keep original response.
    if ([response isKindOfClass:[NSDictionary class]]) {
        return build_error_with_data((enum ErrorCode)(ERRCODE_HTTP_BASE+status), @"Bad HTTP", ERRCAT_API, @"response", response);
    }
    NSDictionary* deserializeJSON = [response deserializeJSON];
    if (deserializeJSON != nil) {
        NSDictionary* responseJSON = deserializeJSON[@"response"];
        if (responseJSON != nil && responseJSON[@"message"]) {
            response = responseJSON[@"message"];
        }
    }
    if ( status < 100 ) {
        return build_error((enum ErrorCode)(ERRCODE_NETWORK_BASE + status), response, ERRCAT_NET);
    } else {
        return build_error((enum ErrorCode)(ERRCODE_HTTP_BASE + status), response, ERRCAT_CLOUD);
    }
}

//------------------------------------------------------------------------------
+ (NSDictionary*)storageLimitExceeded {
    return build_error(ERRCODE_STORAGE_LIMIT_EXCEEDED, @"Upload cannot be completed due to lack of sufficient storage space.", ERRCAT_CLOUD);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)unexpectedResponse:(id)response message:(NSString*)msg {
    return build_error_with_data(ERRCODE_UNRECOGNIZED_API_RESPONSE,
                                 msg,
                                 ERRCAT_CLOUD,
                                 @"response",
                                 response);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)noResponseTo:(NSURL*)url {
    return build_error(ERRCODE_UNRECOGNIZED_API_RESPONSE,
                       [NSString stringWithFormat:@"No response to %@", url],
                       ERRCAT_CLOUD);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)noCurrentSession {
    return build_error(ERRCODE_NO_CURRENT_SESSION, @"No current session", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)noCredentials {
    return build_error(ERRCODE_NO_CREDENTIALS, @"No credentials were provided", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)sessionClosed {
    return build_error(ERRCODE_SESSION_CLOSED, @"Session closed", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)badRequestFormat {
    return build_error(ERRCODE_BAD_FORMAT, @"Request formatting error", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)cancelled {
    return build_error(ERRCODE_CANCELLED, @"An operation was cancelled", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)maxPolls {
    return build_error(ERRCODE_MAX_POLLS, @"Maximum number of polls exceeded", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)bitmapError {
    return build_error(ERRCODE_BITMAP, @"An error occurred during a bitmap operation", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)badTokenState {
    return build_error(ERRCODE_BAD_TOKEN_STATE, @"A token packet was found to be unlocked when it should be locked, or vice versa.", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)obtainTokenFailure:(NSDictionary*)response {
    return build_error_with_data(ERRCODE_OBTAIN_TOKEN_FAIL, [NSString stringWithFormat:@"Failed to obtain a new token: %@", response], ERRCAT_APP, @"response", response);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)fileCopyFailed {
    return build_error(ERRCODE_FILECOPY, @"Failed to copy temp file to local path.", ERRCAT_APP);
}

//------------------------------------------------------------------------------
+ (NSDictionary*)log:(NSDictionary*)errorMessage in:(const char*)srcfile at:(NSUInteger)line {
    if ([MFErrorMessage isErrorMessage:errorMessage]) {
        [MFErrorLog in:srcfile at:line message:@"Error : cat [%i] code [%i] message [%@]", [self category:errorMessage], [self code:errorMessage], [self message:errorMessage]];
    } else {
        mflog(@"Error logging ErrorMessage generated in %s at %i. Not a valid ErrorMessage format - %@", srcfile, line, errorMessage);
    }

    return errorMessage;
}

@end


text:
extern char generic_print_buffer[384];

extern const char * enctypes[6];// = { "open", "wep", "wpa", "wpa2", "wpa_wpa2", 0 };

#define printf( ... ) { ets_sprintf( generic_print_buffer, __VA_ARGS__ );  uart0_sendStr( generic_print_buffer ); }

char tohex1( uint8_t i );
int8_t fromhex1( char c ); //returns -1 if not hex char.

int32 ICACHE_FLASH_ATTR my_atoi( const char * in );
void ICACHE_FLASH_ATTR Uint32To10Str( char * out, uint32 dat );

void ICACHE_FLASH_ATTR NixNewline( char * str ); //If there's a newline at the end of this string, make it null.

//For holding TX packet buffers
extern char generic_buffer[1500];
extern char * generic_ptr;
int8_t ICACHE_FLASH_ATTR  TCPCanSend( struct espconn * conn, int size );
int8_t ICACHE_FLASH_ATTR  TCPDoneSend( struct espconn * conn );
void  ICACHE_FLASH_ATTR  EndTCPWrite( struct espconn * conn );
void ICACHE_FLASH_ATTR et_espconn_disconnect( struct espconn * pespconn );

#define PushByte( c ) { *(generic_ptr++) = c; }

void PushString( const char * buffer );
void PushBlob( const uint8 * buffer, int len );
#define START_PACK {generic_ptr=generic_buffer;}
#define PACK_LENGTH (generic_ptr-&generic_buffer[0]}

int ICACHE_FLASH_ATTR  ColonsToInts( const char * str, int32_t * vals, int max_quantity );

//As much as it pains me, we shouldn't be using the esp8266's base64_encode() function
//as it does stuff with dynamic memory.
void ICACHE_FLASH_ATTR my_base64_encode(const unsigned char *data, size_t input_length, uint8_t * encoded_data );

void ICACHE_FLASH_ATTR SafeMD5Update( MD5_CTX * md5ctx, uint8_t*from, uint32_t size1 );

char * ICACHE_FLASH_ATTR strdup( const char * src );
char * ICACHE_FLASH_ATTR strdupcaselower( const char * src );

uint32_t ICACHE_FLASH_ATTR GetCurrentIP( );

#define _BV(x) (1<<(x))

#endif


text:
using System.Collections;
using IO = System.IO;

namespace BitTorrent
{

	public delegate void PieceSectionFinishedCallback(int pieceId, int begin, int length);

	// Like the download manager, except manages uploading piece-sections to other peers
	public class UploadManager
	{
		private MetainfoFile infofile;
		private DownloadFile downloadFile;

		private ArrayList incomingRequests = new ArrayList();

		private System.Threading.Timer chokeTimer;

		private ArrayList unchokedPeers = new ArrayList();
		private ArrayList interestedPeers = new ArrayList();

		public event PieceSectionFinishedCallback PieceSectionFinished;

		public UploadManager(MetainfoFile infofile, DownloadFile downloadFile)
		{
			this.infofile = infofile;
			this.downloadFile = downloadFile;

			this.chokeTimer = new System.Threading.Timer(new System.Threading.TimerCallback(OnChokeTimer), null, Config.ChokeInterval, Config.ChokeInterval);
		}

		public void AddPeer(Peer peer)
		{
			peer.Disconnected += new PeerDisconnectedCallback(peer_Disconnected);
			peer.HeIsInterestedChange += new PeerStatusChangeCallback(peer_HeIsInterestedChange);
			peer.PieceCancel += new PeerPieceCallback(peer_PieceCancel);
			peer.PieceRequest += new PeerPieceCallback(peer_PieceRequest);
		}

		private void peer_Disconnected(Peer peer)
		{
			lock ( this.interestedPeers.SyncRoot )
			{
				if (this.interestedPeers.Contains(peer))
					this.interestedPeers.Remove(peer);
			}
		}

		private void peer_HeIsInterestedChange(Peer peer, bool newStatus)
		{
			lock ( this.interestedPeers.SyncRoot )
			{
				if (newStatus)
				{
					if (!this.interestedPeers.Contains(peer))
						this.interestedPeers.Add(peer);
				}
				else
				{
					if (this.interestedPeers.Contains(peer))
						this.interestedPeers.Remove(peer);
				}
			}
		}

		private void peer_PieceCancel(Peer peer, int pieceId, int begin, int length, byte[] data)
		{
			for (int i=0; i<this.incomingRequests.Count; ++i)
			{
				PieceRequest request = (PieceRequest)this.incomingRequests[i];
				if (request.Peer.Equals(peer) && request.PieceId == pieceId && request.Begin == begin && request.Length == length)
				{
					this.incomingRequests.RemoveAt(i);
					break;
				}
			}
		}

		private void peer_PieceRequest(Peer peer, int pieceId, int begin, int length, byte[] data)
		{
			// if i am choking, ignore
			if (!peer.AmIChoking)
			{
				this.incomingRequests.Add( new PieceRequest(peer, pieceId, begin, length) );

				// TODO: check if we can serve the request
				// TODO: make more efficient than loading the whole piece each time
				IO.MemoryStream stream = new IO.MemoryStream(this.infofile.GetPieceLength(pieceId));
				this.downloadFile.LoadFromFile(pieceId, stream);
				stream.Seek(begin, IO.SeekOrigin.Begin);
				peer.SendPiece(pieceId, begin, length, stream, new PeerPieceCallback(PieceSendFinished));
			}
		}

		private void PieceSendFinished(Peer peer, int pieceId, int begin, int length, byte[] data)
		{
			foreach (PieceRequest pieceRequest in this.incomingRequests)
			{
				if (pieceRequest.Peer.Equals(peer) && pieceRequest.PieceId == pieceId && pieceRequest.Begin == begin && pieceRequest.Length == length)
				{
					this.incomingRequests.Remove(pieceRequest);
					break;
				}
			}

			if (this.PieceSectionFinished != null)
				this.PieceSectionFinished(pieceId, begin, length);
		}

		private void OnChokeTimer(object state)
		{
			if (this.unchokedPeers.Count < Config.ActiveConfig.SimultaneousUploadsLimit)
			{
//				float worstDownload = -1;

				// find some interested peers to unchoke
				foreach ( Peer peer in this.interestedPeers )
				{
					//					if (worstDownload < 0 || worstDownload > peer.BytesDownloaded)
					//					{
					peer.AmIChoking = false;
					this.unchokedPeers.Add( peer );
					//					}
					if ( this.unchokedPeers.Count >= Config.ActiveConfig.SimultaneousUploadsLimit )
						break;
				}
			}
		}
	}
}


text:
package one.nio.net;

import one.nio.mem.DirectMemory;
import one.nio.os.Mem;

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;

public class PerfServerTest {

    private static ByteBuffer wrap(byte[] buf) {
        return ByteBuffer.wrap(buf).order(ByteOrder.nativeOrder());
    }

    public static void main(String[] args) throws Exception {
        String sockPath = args.length > 0 ? args[0] : "/tmp/one-nio.sock";
        String mapPath = args.length > 1 ? args[1] : "/tmp/one-nio-map.tmp";
        long mapSize = args.length > 2 ? Long.parseLong(args[2]) : 16 * 1024 * 1024;

        RandomAccessFile raf = new RandomAccessFile(mapPath, "rw");
        raf.setLength(mapSize);
        int fd = Mem.getFD(raf.getFD());

        MappedByteBuffer map = raf.getChannel().map(FileChannel.MapMode.READ_WRITE, 0, mapSize);
        long mapAddr = DirectMemory.getAddress(map);

        Socket srv = Socket.bindUnix(new File(sockPath), 1);
        byte[] request = new byte[4];
        byte[] response = new byte[20];

        while (true) {
            Socket s = srv.accept();
            byte[] cred = s.getOption(Socket.SOL_SOCKET, Socket.SO_PEERCRED);
            if (cred == null) {
                throw new IOException("Cannot get peer pid");
            }
            int clientPid = wrap(cred).getInt(0);

            int bytesRead = s.read(request, 0, request.length);
            if (bytesRead != 4 || wrap(request).getInt(0) != 2) {
                throw new IOException("Invalid request");
            }

            ByteBuffer buf = wrap(response);
            buf.putInt(2).putInt(0).putLong(mapSize).putInt(0);

            s.sendMsg(new Msg(response).withFd(fd), 0);
            s.close();
        }
    }
}


text:
package org.sakaiproject.cmprovider;

import java.util.Arrays;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.sakaiproject.cmprovider.data.AcademicSessionData;
import org.sakaiproject.cmprovider.data.DateUtils;
import org.sakaiproject.coursemanagement.api.AcademicSession;
import org.sakaiproject.entitybroker.EntityReference;
import org.sakaiproject.entitybroker.EntityView;
import org.sakaiproject.entitybroker.entityprovider.annotations.EntityCustomAction;
import org.sakaiproject.entitybroker.entityprovider.extension.ActionReturn;
import org.sakaiproject.entitybroker.entityprovider.search.Search;

/**
 * Provides a REST API for working with academic sessions.
 * @see AcademicSession
 *
 * @author Christopher Schauer
 */
public class AcademicSessionEntityProvider extends AbstractCmEntityProvider {

  public String getEntityPrefix() {
    return "cm-academic-session";
  }

  public Object getSampleEntity() {
    return new AcademicSessionData();
  }

  @Override
  public boolean entityExists(String id) {
    return cmService.isAcademicSessionDefined(id);
  }

  /**
   * Get all academic sessions. Wraps CourseManagementService.getAcademicSessions.
   * @see CourseManagementService#getAcademicSessions
   *
   * GET requests to /direct/cm-academic-session.json will be routed here.
   *
   * Possible responses:
   * 200 = success, list of academic sessions in response body
   * 403 = current user does not have permission to access academic sessions
   */
  public List getEntities(EntityReference ref, Search search) {
    validateUser();
    List<AcademicSessionData> sessions = new ArrayList<AcademicSessionData>();
    for (AcademicSession session : cmService.getAcademicSessions()) {
      sessions.add(new AcademicSessionData(session));
    }
    return sessions;
  }

  /**
   * Create a new academic session. Wraps CourseAdministration.createAcademicSession.
   * @see CourseAdministration#createAcademicSession
   * @see AcademicSessionData
   */
  public void create(Object entity) {
    AcademicSessionData data = (AcademicSessionData) entity;
    validateDates(data);

    cmAdmin.createAcademicSession(
      data.eid,
      data.title,
      data.description,
      DateUtils.stringToDate(data.startDate),
      DateUtils.stringToDate(data.endDate)
    );
  }

  /**
   * Update an academic session. Wraps CourseManagementAdministration.updateAcademicSession.
   * @see CourseManagementAdministration#updateAcademicSession
   * @see AcademicSessionData
   */
  public void update(Object entity) {
    AcademicSessionData data = (AcademicSessionData) entity;
    validateDates(data);

    AcademicSession updated = cmService.getAcademicSession(data.eid);
    updated.setTitle(data.title);
    updated.setDescription(data.description);
    updated.setStartDate(DateUtils.stringToDate(data.startDate));
    updated.setEndDate(DateUtils.stringToDate(data.endDate));

    // TODO: return 404 instead of 500 if there's no session with given eid
    cmAdmin.updateAcademicSession(updated);
  }

  /**
   * Get an academic session by eid. Wraps CourseManagementService.getAcademicSession.
   * @see CourseManagementService#getAcademicSession
   */
  public Object get(String eid) {
    AcademicSession session = cmService.getAcademicSession(eid);
    return new AcademicSessionData(session);
  }

  /**
   * Delete an academic session by eid. Wraps CourseManagementAdministration.removeAcademicSession.
   * @see CourseManagementAdministration#removeAcademicSession
   */
  public void delete(String eid) {
    cmAdmin.removeAcademicSession(eid);
  }

  /**
   * A custom action is required to set current sessions since AcademicSession interface doesn't contain
   * any methods for setting the session as current.
   *
   * PUT requests to /direct/cm-academic-session/setCurrentAcademicSessions?list=eid1,eid2,...
   * will be routed here.
   *
   * Possible responses:
   * 200 = current acadmic sessions set successfully
   * 400 = missing or invalid parameter: list
   */
  @EntityCustomAction(action="setCurrentAcademicSessions", viewKey=EntityView.VIEW_EDIT)
  public ActionReturn setCurrentAcademicSessions(EntityView view, Map<String, Object> params) {
    validateRequest(params, null);
    String eidListString = (String) params.get("list");
    if (eidListString == null) throw new IllegalArgumentException("Missing required parameter: list");
    List<String> eidList = Arrays.asList(eidListString.split("\\s*,\\s*"));
    cmAdmin.setCurrentAcademicSessions(eidList);
    return null;
  }

  private void validateDates(AcademicSessionData data) {
    Date startDate = DateUtils.stringToDate(data.startDate);
    Date endDate = DateUtils.stringToDate(data.endDate);

    if (startDate == null && endDate == null) return;

    if (startDate == null || endDate == null) {
      throw new IllegalArgumentException("Invalid AcademicSessionData: startDate and endDate must both be null or both be non-null");
    }

    if (startDate.compareTo(endDate) >= 0) {
      throw new IllegalArgumentException("Invalid CourseOfferingData: startDate must occur before endDate");
    }
  }
}


text:
module Sonos
  # The Sonos system. The root object to manage the collection of groups and devices. This is
  # intended to be a singleton accessed from `Sonos.system`.
  class System
    attr_reader :topology
    attr_reader :groups
    attr_reader :devices

    # Initialize the system
    # @param [Array] the system topology. If this is nil, it will autodiscover.
    def initialize(topology = Discovery.new.topology)
      rescan topology
    end

    # Returns all speakers
    def speakers
      @devices.select(&:speaker?)
    end

    # Pause all speakers
    def pause_all
      speakers.each do |speaker|
        speaker.pause if speaker.has_music?
      end
    end

    # Play all speakers
    def play_all
      speakers.each do |speaker|
        speaker.play if speaker.has_music?
      end
    end

    # Party Mode!  Join all speakers into a single group.
    def party_mode new_master = nil
      return nil unless speakers.length > 1

      new_master = find_party_master if new_master.nil?

      party_over
      speakers.each do |slave|
        next if slave.uid == new_master.uid
        slave.join new_master
      end
      rescan @topology
    end

    def find_party_master
      # 1: If there are any pre-existing groups playing something, use
      # the lowest-numbered group's master
      groups.each do |group|
        return group.master_speaker if group.master_speaker.has_music?
      end

      # 2: Lowest-number speaker that's playing something
      speakers.each do |speaker|
        return speaker if speaker.has_music?
      end

      # 3: lowest-numbered speaker
      speakers[0]
    end

    # Party's over :(
    def party_over
      groups.each { |g| g.disband }
      rescan @topology
    end

    def rescan(topology = Discovery.new.topology)
      @topology = topology
      @groups = []
      @devices = @topology.collect(&:device)

      construct_groups

      speakers.each do |speaker|
        speaker.group_master = speaker
        @groups.each do |group|
          speaker.group_master = group.master_speaker if group.master_speaker.uid == speaker.uid
          group.slave_speakers.each do |slave|
            speaker.group_master = group.master_speaker if slave.uid == speaker.uid
          end
        end
      end
    end

  private

    def construct_groups
      # Loop through all of the unique groups
      @topology.collect(&:group).uniq.each do |group_uid|

        # set group's master nade using topology's coordinator parameter
        master = nil
        @topology.each do |node|
          # Select only the nodes with this group uid
          next unless node.group == group_uid
          master = node if node.coordinator == "true"
        end

        # register other nodes in groups as slave nodes
        nodes = []
        @topology.each do |node|
          # Select only the nodes with this group uid
          next unless node.group == group_uid
          nodes << node unless node.uuid == master.uuid
        end

        # Skip this group if there are no nodes or master
        next if nodes.empty? or master.nil?

        # Add the group
        @groups << Group.new(master.device, nodes.collect(&:device))
      end
    end
  end
end


text:
using MvvmCross.Plugin.Messenger;

namespace XamarinMvvmCross_MeetupSample.Core
{
	public class LongRunningAsyncOperationMvxMessage : MvxMessage
	{
		public LongRunningAsyncOperationMvxMessage(object sender) : base(sender)
		{
		}

		public bool HasStarted { get; private set; }

		public bool HasFinished { get; private set; }

		public static LongRunningAsyncOperationMvxMessage BuildOperationStartedMessage(object sender)
		{
			return new LongRunningAsyncOperationMvxMessage(sender)
			{
				HasStarted = true
			};
		}

		public static LongRunningAsyncOperationMvxMessage BuildOperationFinishedMessage(object sender)
		{
			return new LongRunningAsyncOperationMvxMessage(sender)
			{
				HasFinished = true
			};
		}
	}

}