text:
var Code = require('code');
var Cryptiles = require('cryptiles');
var Hoek = require('hoek');
var Iron = require('iron');
var Lab = require('lab');
var Statehood = require('../');

// Declare internals

var internals = {};

// Test shortcuts

var lab = exports.lab = Lab.script();
var describe = lab.describe;
var it = lab.it;
var expect = Code.expect;

describe('Definitions', function () {

    describe('add()', function () {

        it('throws on missing name', function (done) {

            var definitions = new Statehood.Definitions();
            expect(function () {

                definitions.add();
            }).to.throw('Invalid name');
            done();
        });

        it('uses defaults', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('test');
            expect(definitions.cookies.test).to.deep.equal({
                strictHeader: true,
                ignoreErrors: false,
                isSecure: false,
                isHttpOnly: false,
                path: null,
                domain: null,
                ttl: null,
                encoding: 'none'
            });
            done();
        });

        it('records name', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('test');
            expect(definitions.names).to.deep.equal(['test']);
            done();
        });

        it('adds definition with null value', function (done) {

            var definitions = new Statehood.Definitions({ path: '/' });

            definitions.add('base');
            expect(definitions.cookies.base.path).to.equal('/');

            definitions.add('test', { path: null });
            expect(definitions.cookies.test.path).to.equal(null);

            done();
        });
    });

    describe('parse()', function () {

        it('parses cookie', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a=b', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: 'b' });
                done();
            });
        });

        it('parses cookie (loose)', function (done) {

            var definitions = new Statehood.Definitions({ strictHeader: false });
            definitions.parse('a="1; b="2"; c=3; d[1]=4', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: '"1', b: '2', c: '3', 'd[1]': '4' });
                done();
            });
        });

        it('parses cookie (empty)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a=', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: '' });
                done();
            });
        });

        it('parses cookie (quoted empty)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a=""', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: '' });
                done();
            });
        });

        it('parses cookie (semicolon single)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a=;', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: '' });
                done();
            });
        });

        it('parses cookie (number)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a=23', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: '23' });
                done();
            });
        });

        it('parses cookie (array)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a=1; a=2', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: ['1', '2'] });
                done();
            });
        });

        it('parses cookie (mixed style array)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a=1; b="2"; c=3', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: '1', b: '2', c: '3' });
                done();
            });
        });

        it('parses cookie (mixed style array quoted first)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a="1"; b="2"; c=3', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: '1', b: '2', c: '3' });
                done();
            });
        });

        it('parses cookie (white space)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('A    = b;   b  =   c', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ A: 'b', b: 'c' });
                done();
            });
        });

        it('parses cookie (raw form)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a="b=123456789&c=something"', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: 'b=123456789&c=something' });
                done();
            });
        });

        it('parses cookie (raw percent)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a=%1;b=x', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: '%1', b: 'x' });
                done();
            });
        });

        it('parses cookie (raw encoded)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('z=%20%22%2c%3b%2f', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ z: '%20%22%2c%3b%2f' });
                done();
            });
        });

        it('parses cookie (form single)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('a', { encoding: 'form' });
            definitions.parse('a="b=%p123456789"', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: { b: '%p123456789' } });
                done();
            });
        });

        it('parses cookie (form multiple)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('a', { encoding: 'form' });
            definitions.parse('a="b=123456789&c=something%20else"', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: { b: '123456789', c: 'something else' } });
                done();
            });
        });

        it('parses cookie (base64 array 2)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('a', { encoding: 'base64' });
            definitions.parse('a=dGVzdA; a=dGVzdA', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: ['test', 'test'] });
                done();
            });
        });

        it('parses cookie (base64 array 3)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('a', { encoding: 'base64' });
            definitions.parse('a=dGVzdA; a=dGVzdA; a=dGVzdA', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: ['test', 'test', 'test'] });
                done();
            });
        });

        it('parses cookie (base64 padding)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('key', { encoding: 'base64' });
            definitions.parse('key=dGVzdA==', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ key: 'test' });
                done();
            });
        });

        it('parses cookie (base64)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('key', { encoding: 'base64' });
            definitions.parse('key=dGVzdA', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ key: 'test' });
                done();
            });
        });

        it('parses cookie (none encoding)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('key', { encoding: 'none' });
            definitions.parse('key=dGVzdA', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ key: 'dGVzdA' });
                done();
            });
        });

        it('parses cookie (base64json)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('key', { encoding: 'base64json' });
            definitions.parse('key=eyJ0ZXN0aW5nIjoianNvbiJ9', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ key: { testing: 'json' } });
                done();
            });
        });

        it('parses cookie (iron)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('key', { encoding: 'iron', password: 'password' });
            definitions.parse('key=Fe26.2**f3fc42242467f7a97c042be866a32c1e7645045c2cc085124eadc66d25fc8395*URXpH8k-R0d4O5bnY23fRQ*uq9rd8ZzdjZqUrq9P2Ci0yZ-EEUikGzxTLn6QTcJ0bc**3880c0ac8bab054f529afec8660ebbbbc8050e192e39e5d622e7ac312b9860d0*r_g7N9kJYqXDrFlvOnuKpfpEWwrJLOKMXEI43LAGeFg', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ key: { a: 1, b: 2, c: 3 } });
                done();
            });
        });

        it('parses cookie (iron settings)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('key', { encoding: 'iron', password: 'password', iron: Iron.defaults });
            definitions.parse('key=Fe26.2**f3fc42242467f7a97c042be866a32c1e7645045c2cc085124eadc66d25fc8395*URXpH8k-R0d4O5bnY23fRQ*uq9rd8ZzdjZqUrq9P2Ci0yZ-EEUikGzxTLn6QTcJ0bc**3880c0ac8bab054f529afec8660ebbbbc8050e192e39e5d622e7ac312b9860d0*r_g7N9kJYqXDrFlvOnuKpfpEWwrJLOKMXEI43LAGeFg', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ key: { a: 1, b: 2, c: 3 } });
                done();
            });
        });

        it('parses cookie (signed form)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'form', sign: { password: 'password' } });
            definitions.parse('sid=a=1&b=2&c=3%20x.2d75635d74c1a987f84f3ee7f3113b9a2ff71f89d6692b1089f19d5d11d140f8*xGhc6WvkE55V-TzucCl0NVFmbijeCwgs5Hf5tAVbSUo', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ sid: { a: '1', b: '2', c: '3 x' } });
                done();
            });
        });

        it('parses cookie (signed form integrity settings)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'form', sign: { password: 'password', integrity: Iron.defaults.integrity } });
            definitions.parse('sid=a=1&b=2&c=3%20x.2d75635d74c1a987f84f3ee7f3113b9a2ff71f89d6692b1089f19d5d11d140f8*xGhc6WvkE55V-TzucCl0NVFmbijeCwgs5Hf5tAVbSUo', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ sid: { a: '1', b: '2', c: '3 x' } });
                done();
            });
        });

        it('parses cookie (cookie level strict override)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('a', { strictHeader: false });
            definitions.parse('a="1', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.have.length(0);
                expect(states).to.deep.equal({ a: '"1' });
                done();
            });
        });

        it('fails parsing cookie (mismatching quotes)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a="1; b="2"; c=3', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.data).to.deep.equal([
                    {
                        name: 'a',
                        value: '"1',
                        settings: {
                            isSecure: false,
                            isHttpOnly: false,
                            path: null,
                            domain: null,
                            ttl: null,
                            encoding: 'none',
                            strictHeader: true,
                            ignoreErrors: false
                        },
                        reason: 'Invalid cookie value'
                    }
                ]);

                expect(failed).to.deep.equal(err.data);

                done();
            });
        });

        it('ignores failed parsing cookie (mismatching quotes)', function (done) {

            var definitions = new Statehood.Definitions({ ignoreErrors: true });
            definitions.parse('a="1; b="2"; c=3', function (err, states, failed) {

                expect(err).to.not.exist();
                expect(failed).to.deep.equal([
                    {
                        name: 'a',
                        value: '"1',
                        settings: {
                            isSecure: false,
                            isHttpOnly: false,
                            path: null,
                            domain: null,
                            ttl: null,
                            encoding: 'none',
                            strictHeader: true,
                            ignoreErrors: true
                        },
                        reason: 'Invalid cookie value'
                    }
                ]);
                done();
            });
        });

        it('ignores failed parsing cookie (cookie settings)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('a', { ignoreErrors: true });
            definitions.parse('a="1', function (err, states, failed) {

                expect(err).to.not.exist();
                done();
            });
        });

        it('fails parsing cookie (name)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a@="1"; b="2"; c=3', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.data).to.deep.equal([
                    {
                        name: 'a@',
                        value: '1',
                        settings: {
                            isSecure: false,
                            isHttpOnly: false,
                            path: null,
                            domain: null,
                            ttl: null,
                            encoding: 'none',
                            strictHeader: true,
                            ignoreErrors: false
                        },
                        reason: 'Invalid cookie name'
                    }
                ]);
                done();
            });
        });

        it('fails parsing cookie (multiple)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a@="1"; b@="2"; c=3', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.data).to.deep.equal([
                    {
                        name: 'a@',
                        value: '1',
                        settings: {
                            isSecure: false,
                            isHttpOnly: false,
                            path: null,
                            domain: null,
                            ttl: null,
                            encoding: 'none',
                            strictHeader: true,
                            ignoreErrors: false
                        },
                        reason: 'Invalid cookie name'
                    },
                    {
                        name: 'b@',
                        value: '2',
                        settings: {
                            isSecure: false,
                            isHttpOnly: false,
                            path: null,
                            domain: null,
                            ttl: null,
                            encoding: 'none',
                            strictHeader: true,
                            ignoreErrors: false
                        },
                        reason: 'Invalid cookie name'
                    }
                ]);
                done();
            });
        });

        it('ignores failed parsing cookie (name)', function (done) {

            var definitions = new Statehood.Definitions({ ignoreErrors: true });
            definitions.parse('a@="1"; b="2"; c=3', function (err, states, failed) {

                expect(err).to.not.exist();
                done();
            });
        });

        it('fails parsing cookie (empty pair)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.parse('a=1; b=2; c=3;;', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie header');
                done();
            });
        });

        it('fails parsing cookie (base64json)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('x', { encoding: 'base64json' });
            definitions.parse('x=XeyJ0ZXN0aW5nIjoianNvbiJ9', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value');
                expect(err.data).to.deep.equal([
                    {
                        name: 'x',
                        value: 'XeyJ0ZXN0aW5nIjoianNvbiJ9',
                        settings: {
                            strictHeader: true,
                            ignoreErrors: false,
                            isSecure: false,
                            isHttpOnly: false,
                            path: null,
                            domain: null,
                            ttl: null,
                            encoding: 'base64json'
                        },
                        reason: 'Unexpected token ]'
                    }
                ]);

                done();
            });
        });

        it('ignores failed parsing cookie (base64json)', function (done) {

            var definitions = new Statehood.Definitions({ ignoreErrors: true });
            definitions.add('x', { encoding: 'base64json' });
            definitions.parse('x=XeyJ0ZXN0aW5nIjoianNvbiJ9', function (err, states, failed) {

                expect(err).to.not.exist();
                done();
            });
        });

        it('fails parsing cookie (double base64json)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('x', { encoding: 'base64json' });
            definitions.parse('x=XeyJ0ZXN0aW5nIjoianNvbiJ9; x=XeyJ0ZXN0aW5dnIjoianNvbiJ9', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value');
                done();
            });
        });

        it('ignores failed parsing cookie (double base64json)', function (done) {

            var definitions = new Statehood.Definitions({ ignoreErrors: true });
            definitions.add('x', { encoding: 'base64json' });
            definitions.parse('x=XeyJ0ZXN0aW5nIjoianNvbiJ9; x=XeyJ0ZXN0aW5dnIjoianNvbiJ9', function (err, states, failed) {

                expect(err).to.not.exist();
                done();
            });
        });

        it('fails parsing cookie (iron)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('key', { encoding: 'iron', password: 'password' });
            definitions.parse('key=Fe26.1**f3fc42242467f7a97c042be866a32c1e7645045c2cc085124eadc66d25fc8395*URXpH8k-R0d4O5bnY23fRQ*uq9rd8ZzdjZqUrq9P2Ci0yZ-EEUikGzxTLn6QTcJ0bc**3880c0ac8bab054f529afec8660ebbbbc8050e192e39e5d622e7ac312b9860d0*r_g7N9kJYqXDrFlvOnuKpfpEWwrJLOKMXEI43LAGeFg', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value');
                done();
            });
        });

        it('fails parsing cookie (iron password)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('key', { encoding: 'iron', password: 'passwordx' });
            definitions.parse('key=Fe26.2**f3fc42242467f7a97c042be866a32c1e7645045c2cc085124eadc66d25fc8395*URXpH8k-R0d4O5bnY23fRQ*uq9rd8ZzdjZqUrq9P2Ci0yZ-EEUikGzxTLn6QTcJ0bc**3880c0ac8bab054f529afec8660ebbbbc8050e192e39e5d622e7ac312b9860d0*r_g7N9kJYqXDrFlvOnuKpfpEWwrJLOKMXEI43LAGeFg', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value');
                done();
            });
        });

        it('fails parsing cookie (signed form missing options)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'form', sign: {} });
            definitions.parse('sid=a=1&b=2&c=3%20x.2d75635d74c1a987f84f3ee7f3113b9a2ff71f89d6692b1089f19d5d11d140f8*khsb8lmkNJS-iljqDKZDMmd__2PcHBz7Ksrc-48gZ-0', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value');
                done();
            });
        });

        it('fails parsing cookie (signed form missing signature)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'form', sign: { password: 'password' } });
            definitions.parse('sid=a=1&b=2&c=3%20x', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value');
                done();
            });
        });

        it('ignores failed parsing cookie (signed form missing signature)', function (done) {

            var definitions = new Statehood.Definitions({ ignoreErrors: true });
            definitions.add('sid', { encoding: 'form', sign: { password: 'password' } });
            definitions.parse('sid=a=1&b=2&c=3%20x', function (err, states, failed) {

                expect(err).to.not.exist();
                done();
            });
        });

        it('fails parsing cookie (signed form missing signature double)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'form', sign: { password: 'password' } });
            definitions.parse('sid=a=1&b=2&c=3%20x; sid=a=1&b=2&c=3%20x', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value');
                done();
            });
        });

        it('ignores failed parsing cookie (signed form missing signature double)', function (done) {

            var definitions = new Statehood.Definitions({ ignoreErrors: true });
            definitions.add('sid', { encoding: 'form', sign: { password: 'password' } });
            definitions.parse('sid=a=1&b=2&c=3%20x; sid=a=1&b=2&c=3%20x', function (err, states, failed) {

                expect(err).to.not.exist();
                done();
            });
        });

        it('fails parsing cookie (signed form missing signature with sep)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'form', sign: { password: 'password' } });
            definitions.parse('sid=a=1&b=2&c=3%20x.', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value');
                done();
            });
        });

        it('fails parsing cookie (signed form invalid signature)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'form', sign: { password: 'password' } });
            definitions.parse('sid=a=1&b=2&c=3%20x.2d75635d74c1a987f84f3ee7f3113b9a2ff71f89d6692b1089f19d5d11d140f8', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value');
                done();
            });
        });

        it('fails parsing cookie (signed form wrong signature)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'form', sign: { password: 'password' } });
            definitions.parse('sid=a=1&b=2&c=3%20x.2d75635d74c1a987f84f3ee7f3113b9a2ff71f89d6692b1089f19d5d11d140f8*-Ghc6WvkE55V-TzucCl0NVFmbijeCwgs5Hf5tAVbSUo', function (err, states, failed) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value');
                done();
            });
        });
    });

    describe('format()', function () {

        it('skips an empty header', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format(null, function (err, header) {

                expect(err).to.not.exist();
                expect(header).to.deep.equal([]);
                done();
            });
        });

        it('skips an empty array', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format([], function (err, header) {

                expect(err).to.not.exist();
                expect(header).to.deep.equal([]);
                done();
            });
        });

        it('formats a header', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format({ name: 'sid', value: 'fihfieuhr9384hf', options: { ttl: 3600, isSecure: true, isHttpOnly: true, path: '/', domain: 'example.com' } }, function (err, header) {

                var expires = new Date(Date.now() + 3600);
                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=fihfieuhr9384hf; Max-Age=3; Expires=' + expires.toUTCString() + '; Secure; HttpOnly; Domain=example.com; Path=/');
                done();
            });
        });

        it('formats a header (with null ttl)', function (done) {

            var definitions = new Statehood.Definitions({ ttl: 3600 });
            definitions.format({ name: 'sid', value: 'fihfieuhr9384hf', options: { ttl: null, isSecure: true, isHttpOnly: true, path: '/', domain: 'example.com' } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=fihfieuhr9384hf; Secure; HttpOnly; Domain=example.com; Path=/');
                done();
            });
        });

        it('formats a header (with zero ttl)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format({ name: 'sid', value: 'fihfieuhr9384hf', options: { ttl: 0, isSecure: true, isHttpOnly: true, path: '/', domain: 'example.com' } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=fihfieuhr9384hf; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT; Secure; HttpOnly; Domain=example.com; Path=/');
                done();
            });
        });

        it('formats a header with null value', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format({ name: 'sid', options: { ttl: 3600, isSecure: true, isHttpOnly: true, path: '/', domain: 'example.com' } }, function (err, header) {

                var expires = new Date(Date.now() + 3600);
                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=; Max-Age=3; Expires=' + expires.toUTCString() + '; Secure; HttpOnly; Domain=example.com; Path=/');
                done();
            });
        });

        it('formats a header with server definition', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { ttl: 3600, isSecure: true, isHttpOnly: true, path: '/', domain: 'example.com' });
            definitions.format({ name: 'sid', value: 'fihfieuhr9384hf' }, function (err, header) {

                var expires = new Date(Date.now() + 3600);
                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=fihfieuhr9384hf; Max-Age=3; Expires=' + expires.toUTCString() + '; Secure; HttpOnly; Domain=example.com; Path=/');
                done();
            });
        });

        it('formats a header with server definition (base64)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'base64' });
            definitions.format({ name: 'sid', value: 'fihfieuhr9384hf' }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=ZmloZmlldWhyOTM4NGhm');
                done();
            });
        });

        it('formats a header with server definition (base64json)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'base64json' });
            definitions.format({ name: 'sid', value: { a: 1, b: 2, c: 3 } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=eyJhIjoxLCJiIjoyLCJjIjozfQ==');
                done();
            });
        });

        it('fails on a header with server definition and bad value (base64json)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'base64json' });
            var bad = { a: {} };
            bad.b = bad.a;
            bad.a.x = bad.b;

            definitions.format({ name: 'sid', value: bad }, function (err, header) {

                expect(err).to.exist();
                done();
            });
        });

        it('formats a header with server definition (form)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'form' });
            definitions.format({ name: 'sid', value: { a: 1, b: 2, c: '3 x' } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=a=1&b=2&c=3%20x');
                done();
            });
        });

        it('formats a header with server definition (form+sign)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', {
                encoding: 'form',
                sign: {
                    password: 'password',
                    integrity: {
                        saltBits: 256,
                        algorithm: 'sha256',
                        iterations: 1,
                        salt: '2d75635d74c1a987f84f3ee7f3113b9a2ff71f89d6692b1089f19d5d11d140f8'
                    }
                }
            });
            definitions.format({ name: 'sid', value: { a: 1, b: 2, c: '3 x' } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=a=1&b=2&c=3%20x.2d75635d74c1a987f84f3ee7f3113b9a2ff71f89d6692b1089f19d5d11d140f8*xGhc6WvkE55V-TzucCl0NVFmbijeCwgs5Hf5tAVbSUo');
                done();
            });
        });

        it('formats a header with server definition (form+sign, buffer password)', function (done) {

            var buffer = new Buffer('fa4321e8c21b44a49d382fa7709226855f40eb23a32b2f642c3fd797c958718e', 'base64');
            var definitions = new Statehood.Definitions();
            definitions.add('sid', {
                encoding: 'form',
                sign: {
                    password: buffer,
                    integrity: {
                        saltBits: 256,
                        algorithm: 'sha256',
                        iterations: 1,
                        salt: '2d75635d74c1a987f84f3ee7f3113b9a2ff71f89d6692b1089f19d5d11d140f8'
                    }
                }
            });
            definitions.format({ name: 'sid', value: { a: 1, b: 2, c: '3 x' } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=a=1&b=2&c=3%20x.*4wjD4tIxyiNW-rC3xBqL56TxUbb_aQT5PMykruWlR0Q');
                done();
            });
        });

        it('fails a header with bad server definition (form+sign)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', {
                encoding: 'form',
                sign: {}
            });
            definitions.format({ name: 'sid', value: { a: 1, b: 2, c: '3 x' } }, function (err, header) {

                expect(err).to.exist();
                expect(err.message).to.equal('Failed to sign cookie (sid) value: Empty password');
                done();
            });
        });

        it('formats a header with server definition (iron)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'iron', password: 'password' });
            definitions.format({ name: 'sid', value: { a: 1, b: 2, c: 3 } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.have.string('sid=Fe26.2*');
                done();
            });
        });

        it('formats a header with server definition (iron + options)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'iron', password: 'password', iron: Iron.defaults });
            definitions.format({ name: 'sid', value: { a: 1, b: 2, c: 3 } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.have.string('sid=Fe26.2*');
                done();
            });
        });

        it('formats a header with server definition (iron + options, buffer password)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'iron', password: Cryptiles.randomBits(256), iron: Iron.defaults });
            definitions.format({ name: 'sid', value: { a: 1, b: 2, c: 3 } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.have.string('sid=Fe26.2*');
                done();
            });
        });

        it('fails a header with bad server definition (iron)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('sid', { encoding: 'iron' });
            definitions.format({ name: 'sid', value: { a: 1, b: 2, c: 3 } }, function (err, header) {

                expect(err).to.exist();
                expect(err.message).to.equal('Failed to encode cookie (sid) value: Empty password');
                done();
            });
        });

        it('formats a header with multiple cookies', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format([
                { name: 'sid', value: 'fihfieuhr9384hf', options: { ttl: 3600, isSecure: true, isHttpOnly: true, path: '/', domain: 'example.com' } },
                { name: 'pid', value: 'xyz' }
            ], function (err, header) {

                var expires = new Date(Date.now() + 3600);
                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=fihfieuhr9384hf; Max-Age=3; Expires=' + expires.toUTCString() + '; Secure; HttpOnly; Domain=example.com; Path=/');
                expect(header[1]).to.equal('pid=xyz');
                done();
            });
        });

        it('fails on bad cookie name', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format({ name: 's;id', value: 'fihfieuhr9384hf', options: { isSecure: true, isHttpOnly: false, path: '/', domain: 'example.com' } }, function (err, header) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie name: s;id');
                done();
            });
        });

        it('allows bad cookie name in loose mode', function (done) {

            var definitions = new Statehood.Definitions({ strictHeader: false });
            definitions.format({ name: 's;id', value: 'fihfieuhr9384hf', options: { isSecure: true, isHttpOnly: false, path: '/', domain: 'example.com' } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.equal('s;id=fihfieuhr9384hf; Secure; Domain=example.com; Path=/');
                done();
            });
        });

        it('allows bad cookie name in loose mode (cookie level)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('s;id', { strictHeader: false });
            definitions.format({ name: 's;id', value: 'fihfieuhr9384hf', options: { isSecure: true, isHttpOnly: false, path: '/', domain: 'example.com' } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.equal('s;id=fihfieuhr9384hf; Secure; Domain=example.com; Path=/');
                done();
            });
        });

        it('fails on bad cookie value', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format({ name: 'sid', value: 'fi"hfieuhr9384hf', options: { isSecure: true, isHttpOnly: false, path: '/', domain: 'example.com' } }, function (err, header) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value: fi"hfieuhr9384hf');
                done();
            });
        });

        it('fails on bad cookie value (non string)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format({ name: 'sid', value: {}, options: { isSecure: true, isHttpOnly: false, path: '/', domain: 'example.com' } }, function (err, header) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie value: [object Object]');
                done();
            });
        });

        it('allows bad cookie value in loose mode', function (done) {

            var definitions = new Statehood.Definitions({ strictHeader: false });
            definitions.format({ name: 'sid', value: 'fi"hfieuhr9384hf', options: { isSecure: true, isHttpOnly: false, path: '/', domain: 'example.com' } }, function (err, header) {

                expect(err).to.not.exist();
                expect(header[0]).to.equal('sid=fi"hfieuhr9384hf; Secure; Domain=example.com; Path=/');
                done();
            });
        });

        it('fails on bad cookie domain', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format({ name: 'sid', value: 'fihfieuhr9384hf', options: { isSecure: true, isHttpOnly: false, path: '/', domain: '-example.com' } }, function (err, header) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie domain: -example.com');
                done();
            });
        });

        it('fails on too long cookie domain', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format({ name: 'sid', value: 'fihfieuhr9384hf', options: { isSecure: true, isHttpOnly: false, path: '/', domain: '1234567890123456789012345678901234567890123456789012345678901234567890.example.com' } }, function (err, header) {

                expect(err).to.exist();
                expect(err.message).to.equal('Cookie domain too long: 1234567890123456789012345678901234567890123456789012345678901234567890.example.com');
                done();
            });
        });

        it('formats a header with cookie domain with . prefix', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format({ name: 'sid', value: 'fihfieuhr9384hf', options: { isSecure: true, isHttpOnly: false, path: '/', domain: '.12345678901234567890.example.com' } }, function (err, header) {

                expect(err).to.not.exist();
                done();
            });
        });

        it('fails on bad cookie path', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.format({ name: 'sid', value: 'fihfieuhr9384hf', options: { isSecure: true, isHttpOnly: false, path: 'd', domain: 'example.com' } }, function (err, header) {

                expect(err).to.exist();
                expect(err.message).to.equal('Invalid cookie path: d');
                done();
            });
        });
    });

    describe('passThrough()', function () {

        it('returns header unchanged', function (done) {

            var definitions = new Statehood.Definitions();
            var header = 'a=4;b=5;c=6';
            var result = definitions.passThrough(header);
            expect(result).to.equal(header);
            done();
        });

        it('returns header excluding local', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('b');
            var header = 'a=4;b=5;c=6';
            var result = definitions.passThrough(header);
            expect(result).to.equal('a=4;c=6');
            done();
        });

        it('returns header including local (fallback)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('b');
            var header = 'a=4;b=5;c=6';
            var result = definitions.passThrough(header, true);
            expect(result).to.equal('a=4;b=5;c=6');
            done();
        });

        it('returns header including local (state option)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('b', { passThrough: true });
            var header = 'a=4;b=5;c=6';
            var result = definitions.passThrough(header);
            expect(result).to.equal('a=4;b=5;c=6');
            done();
        });

        it('returns header including local (state option with fallback)', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('b', { passThrough: false });
            var header = 'a=4;b=5;c=6';
            var result = definitions.passThrough(header, true);
            expect(result).to.equal('a=4;c=6');
            done();
        });

        it('errors on invalid header', function (done) {

            var definitions = new Statehood.Definitions();
            definitions.add('b');
            var header = 'a=4;b=5;c=6;;';
            var result = definitions.passThrough(header);
            expect(result.message).to.equal('Invalid cookie header');
            done();
        });
    });
});

describe('prepareValue()', function () {

    it('throws when missing options', function (done) {

        expect(function () {

            Statehood.prepareValue('name', 'value');
        }).to.throw('Missing or invalid options');
        done();
    });
});

describe('exclude()', function () {

    it('returns all keys', function (done) {

        var header = 'a=4;b=5;c=6';
        var result = Statehood.exclude(header, []);
        expect(result).to.equal(header);
        done();
    });

    it('returns keys without excluded', function (done) {

        var header = 'a=4;b=5;c=6';
        var result = Statehood.exclude(header, ['b']);
        expect(result).to.equal('a=4;c=6');
        done();
    });

    it('returns error on invalid header', function (done) {

        var header = 'a';
        var result = Statehood.exclude(header, ['b']);
        expect(result.message).to.equal('Invalid cookie header');
        done();
    });
});


text:
"""Generate Buildkite pipelines dynamically"""

import json

INSTANCES = [
    "m5d.metal",
    "m6i.metal",
    "m6a.metal",
    "m6gd.metal",
]

KERNELS = ["4.14", "5.10"]

def group(group_name, command, agent_tags=None, priority=0, timeout=30):
    """
    Generate a group step with specified parameters, for each instance+kernel
    combination

    https://buildkite.com/docs/pipelines/group-step
    """
    if agent_tags is None:
        agent_tags = []
    # Use the 1st character of the group name (should be an emoji)
    label1 = group_name[0]
    steps = []
    for instance in INSTANCES:
        for kv in KERNELS:
            agents = [
                f"type={instance}",
                f"kv={kv}",
            ]
            agents.extend(agent_tags)
            step = {
                "command": command,
                "label": f"{label1} {instance} kv={kv}",
                "priority": priority,
                "timeout": timeout,
                "agents": agents,
            }
            steps.append(step)

    return {"group": group_name, "steps": steps}

step_block_unless_maintainer = {
    "block": "Waiting for approval to run",
    "if": '(build.creator.teams includes "prod-compute-capsule") == false',
}

step_style = {
    "command": "./tools/devtool -y test -- ../tests/integration_tests/style/",
    "label": "🪶 Style",
    # we only install the required dependencies in x86_64
    "agents": ["platform=x86_64.metal"]
}

build_grp = group(
    "📦 Build",
    "./tools/devtool -y test -- ../tests/integration_tests/build/",
    priority=1,
)

functional_1_grp = group(
    "⚙ Functional [a-n]",
    "./tools/devtool -y test -- `cd tests; ls integration_tests/functional/test_[a-n]*.py`",
    priority=1,
)

functional_2_grp = group(
    "⚙ Functional [o-z]",
    "./tools/devtool -y test -- `cd tests; ls integration_tests/functional/test_[o-z]*.py`",
    priority=1,
)

security_grp = group(
    "🔒 Security",
    "./tools/devtool -y test -- ../tests/integration_tests/security/",
    priority=1,
)

performance_grp = group(
    "⏱ Performance",
    "./tools/devtool -y test -- ../tests/integration_tests/performance/",
    priority=1,
    agent_tags=["ag=1"],
)

pipeline = {
    "agents": {"queue": "default"},
    "steps": [
        step_block_unless_maintainer,
        step_style,
        build_grp,
        functional_1_grp,
        functional_2_grp,
        security_grp,
        performance_grp,
    ],
}

print(json.dumps(pipeline, indent=4, sort_keys=True, ensure_ascii=False))

redpajama_set_name: RedPajamaGithub


text:
package das.base;

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

import org.apache.ibatis.annotations.Param;

/**
 * Template Object-Relation-Mapper interface.
 * Mostly used with CRUDSingleDAO
 * @author serg
 *
 * @param <B>
 */
public interface CRUDSingleMapper<B> {

	/*
	 * You can pass multiple parameters to a mapper method. If you do, they will be named by the literal
	 * "param" followed by their position in the parameter list by default, for example: #{param1},
	 * #{param2} etc. If you wish to change the name of the parameters (multiple only), then you can use
	 * the @Param("paramName") annotation on the parameter.
	 **/

	List<B> getAll() throws IOException;
	int insert(B item) throws IOException;
	int update(B item) throws IOException;
	int delete(B item) throws IOException;
}


text:
<TITLE>Review for My Dinner with André (1981)</TITLE>
<LINK REL="STYLESHEET" TYPE="text/css" HREF="/ramr.css">

My Dinner with André (1981)

reviewed by
Kevin Walker

MY DINNER WITH ANDRE is one of the greatest movies of all time because
it works on a seemingly infinite number of levels. Yet at the same
time it is one of the biggest failures in film because it only
succeeds in connecting to the most insightful of its audience. The
resulting paradox only serves to prove the film's lesson to be true.
Brilliant!

This is either a movie you will turn off after fifteen minutes, or it
is a movie you will watch over and over again to pick up all the
things you missed in previous screenings. The former will be bored and
lost by the endless, meaningless talk. The latter will find gold in
every word, and veins left to be mined time after time.

In simple terms, the question is understood "If life is a stage, are
you going to be an actor, a director, or a playwright?" It is the
viewer's choice. Wally is a struggling playwright who has fallen back
on acting. Andre is a former actor and director who has left the
theatre entirely. Wally and Andre meet for dinner, and Andre recounts
his experiences since leaving the theatre.

But one of the many ironies is that their dinner itself is theatre,
and both Andre and Wally have roles to fill. [Notice they wrote the
script and use their real names. They are not playing characters. They
are necessarily playing themselves.] And summarily the viewer also has
a role to fill. If life is a stage, viewing the theatre is in itself
theatre. The viewer is now in a place of filling a role, and the
question is will it be done mechanically or deliberately?
Mechanically is to be put there by script, or director, or instinct.
It is done without thought or personal intention.  Mechanics is
acting.  Deliberation is with personal intention and therefore choice.
Deliberation is thought.  Deliberation is playwrighting.

This is a brilliant, brilliant film. One of the greatest movies of all
time. And its resolve is purely subjective to the individual viewer.
The goal is for viewers to deliberate and come away enlightened
(literally). Unfortunately the majority of viewers will act
mechanically and turn it off.

    -- Kevin Walker /IL
       -- fideist@NOSPAMxnet.com (-NOSPAM)
     ****************************************
     *  "Qui me amat, amat et canem meum."  *
     *  ("He who loves me, loves my dog.")  *
     *     -- St. Bernard of Clairvaux      *
     ****************************************

The review above was posted to the
rec.arts.movies.reviews newsgroup (de.rec.film.kritiken for German reviews).

The Internet Movie Database accepts no responsibility for the contents of the
review and has no editorial control. Unless stated otherwise, the copyright
belongs to the author.

Please direct comments/criticisms of the review to relevant newsgroups.

Broken URLs inthe reviews are the responsibility of the author.

The formatting of the review is likely to differ from the original due
to ASCII to HTML conversion.

Related links: index of all rec.arts.movies.reviews reviews


text:
local timeconvert = {}
local php

function timeconvert.setupInterface(options)
   -- Remove setup function.
   timeconvert.setupInterface = nil

   -- Copy the PHP callbacks to a local variable, and remove the global one.
   php = mw_interface
   mw_interface = nil

   -- Do any other setup here.
   timeconvert.timeconvert = php.timeconvert

   -- Install into the mw global.
   mw = mw or {}
   mw.ext = mw.ext or {}
   mw.ext.timeconvert = timeconvert

   -- Indicate that we're loaded.
   package.loaded["mw.ext.timeconvert"] = timeconvert
end

return timeconvert


text:
@echo off
echo Check directory strcuture
:: first cehck the directory structure
if not exist "Release" mkdir Release
if not exist "Release\js" mkdir Release\js
if not exist "Release\css" mkdir Release\css
if not exist "Release\images" mkdir Release\images
if not exist "Release\images\favicons" mkdir Release\images\favicons
if not exist "Release\cron" mkdir Release\cron
if not exist "Release\php" mkdir Release\php
if not exist "Release\php\templates" mkdir Release\php\templates
if not exist "Release\fonts" mkdir Release\fonts

echo Copying HTML
:: copy html files and icon
copy /y index.html Release\index.html
copy /y favicon.ico Release\favicon.ico
copy /y calendar.html Release\calendar.html
::copy /y blokhut_impressie.html Release\blokhut_impressie.html

echo Copying JavaScript
:: copy js files
copy /y js\scripts.js Release\js\scripts.js
copy /y js\calendar.js Release\js\calendar.js

echo Copying CSS
::copy css files
copy /y css\style.min.css Release\css\style.min.css
copy /y css\calendar.min.css Release\css\calendar.min.css

echo Copying images
:: copy the entire images directory
xcopy /y /s images Release\images

echo Copying fonts
:: copy the fonts directory
xcopy /y /s fonts Release\fonts

echo Copying PHP
:: copy php files
copy /y php\contact-form.php Release\php\contact-form.php
copy /y php\date_layer.php Release\php\date_layer.php
copy /y php\db_layer.php Release\php\db_layer.php
copy /y php\mail_layer.php Release\php\mail_layer.php
copy /y php\huurovereenkomst.php Release\php\huurovereenkomst.php
copy /y php\kostenberekening.php Release\php\kostenberekening.php
copy /y php\templates\huurovereenkomst.tpl Release\php\templates\huurovereenkomst.tpl
copy /y php\templateParser.php Release\php\templateParser.php
copy /y php\Reservering.php Release\php\Reservering.php
copy /y php\ReserveringVerification.php Release\php\ReserveringVerification.php
copy /y php\ReserveringMonth.php Release\php\ReserveringMonth.php
copy /y php\verhuur_settings.php Release\php\verhuur_settings.php
copy /y php\verhuur-confirm.php Release\php\verhuur-confirm.php
copy /y php\verhuur-form.php Release\php\verhuur-form.php

echo Copying cron jobs
:: copy cron job files
copy /y cron\poetsrooster.php Release\cron\poetsrooster.php
copy /y cron\batch.php Release\cron\batch.php

pause


text:
package com.shwootide.metabolictreat;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.shwootide.metabolictreat.widget.HackyViewPager;
import com.shwootide.metabolictreat.widget.imageview.PhotoView;
import com.shwootide.metabolictreat.widget.imageview.PhotoViewAttacher;

import java.util.ArrayList;
import java.util.List;

/**
 * 显示多张图片
 *
 * @author GMY
 * @mail 2275964276@qq.com
 * @date 2015年6月2日
 */
public class ImagesShowActivity extends BaseActivity {
    private HackyViewPager viewPager;
    private MyPageAdapter adapter;

    private List<String> res = new ArrayList<>();
    private int position = 0;
    private TextView txt;
    private Button back;
    int old = 0;

    @Override
    public void setLayout() {
        setContentView(R.layout.activity_imagesshow);
    }

    @Override
    public void setTitleBarOption() {

    }
    @Override
    public void wentTo(RadioGroup group, int checkedId) {

    }
    public void initView() {
        viewPager = (HackyViewPager) this.findViewById(R.id.viewpage);
        txt = (TextView) findViewById(R.id.show_txt);
        back = (Button) findViewById(R.id.show_back);
        res = getIntent().getStringArrayListExtra("mlist");
        String pos = getIntent().getStringExtra("pos");
        if (!pos.equals("")) {
            position = Integer.parseInt(pos);
        }

        if (res != null && res.size() != 0) {
            adapter = new MyPageAdapter(res, ImagesShowActivity.this);
        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initView();
        back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                finish();
            }
        });
        viewPager.setAdapter(adapter);
        viewPager.setCurrentItem(position);
        txt.setText(position + 1 + "/" + res.size());
        viewPager.setOnPageChangeListener(new OnPageChangeListener() {

            @Override
            public void onPageSelected(int arg0) {
                txt.setText(arg0 + 1 + "/" + res.size());
                old = arg0;
            }

            @Override
            public void onPageScrolled(int arg0, float arg1, int arg2) {

            }

            @Override
            public void onPageScrollStateChanged(int arg0) {

            }
        });
    }

    public class MyPageAdapter extends PagerAdapter {
        private List<String> res;
        private Context context;

        public MyPageAdapter(List<String> res, Context context) {
            super();
            this.res = res;
            this.context = context;
        }

        @Override
        public int getCount() {
            return res.size();
        }

        @Override
        public boolean isViewFromObject(View arg0, Object arg1) {
            return arg0 == arg1;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            View iv = LayoutInflater.from(context).inflate(
                    R.layout.item_viewpage, null);
            PhotoView img = (PhotoView) iv.findViewById(R.id.imageview);
            if (!res.get(position).equals("")) {
                img.setZoomable(true);
                img.setAllowParentInterceptOnEdge(true);
//                img.setImageResource(Integer.parseInt(res.get(position)));
//                img.setImageUri(res.get(position));
                Glide.with(ImagesShowActivity.this).load(res.get(position)).into(img);
            }
            //图片区域内单击之后退出
            img.setOnPhotoTapListener(new PhotoViewAttacher.OnPhotoTapListener() {
                @Override
                public void onPhotoTap(View view, float x, float y) {
                    finish();
                    overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
                }
            });
            container.addView(iv, 0);
            return iv;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {

        if (keyCode == KeyEvent.KEYCODE_BACK) {
            finish();
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);
        }
        return false;
    }
}


text:
NS_ASSUME_NONNULL_BEGIN

@interface CCUserFavoritesPlayersIDCoreDataModel (CoreDataProperties)

+ (NSFetchRequest<CCUserFavoritesPlayersIDCoreDataModel *> *)fetchRequest;

@property (nullable, nonatomic, retain) NSData *playersIDDataArray;

@end

NS_ASSUME_NONNULL_END


text:
// coding: utf-8
// ----------------------------------------------------------------------------

// ----------------------------------------------------------------------------

#include <avr/interrupt.h>
#include "adc_interrupt.hpp"

// ----------------------------------------------------------------------------
xpcc::atmega::AdcInterrupt::Function xpcc::atmega::AdcInterrupt::conversionComplete=xpcc::dummy;

// ----------------------------------------------------------------------------
ISR(ADC_vect)
{
	xpcc::atmega::AdcInterrupt::conversionComplete();
}


text:
Agregar un Encargado

        <form class="form-horizontal" data-ng-submit="create()" novalidate>
            <fieldset>

                        Nombre del encargado

                            <input type="text" data-ng-model="name" id="name" class="form-control align-field" placeholder="Nombre" required>

                            <input type="text" data-ng-model="primer_apellido" id="primer_apellido" class="form-control align-field" placeholder="Primer apellido" required>

                            <input type="text" data-ng-model="segundo_apellido" id="segundo_apellido" class="form-control align-field" placeholder="Segundo Apellido" required>

                    Cédula del encargado

                        <input type="text" data-ng-model="cedula" id="cedula" class="form-control align-field" placeholder="0-0000-0000" required>

                    Parentesco

                        <select class="form-control align-field" data-ng-model="parentesco" id="parentesco"
                                ng-options="opt as opt.relationship for opt in relationshipStudentList">
                        </select>

                    Ocupación

                        <input type="text" data-ng-model="ocupacion" id="ocupacion" class="form-control align-field" placeholder="Empresario, Panadero, Profesor..." required>

                    Estado Civil

                        <input type="text" data-ng-model="estado_civil" id="estado_civil" class="form-control align-field" placeholder="Soltero, Casado, Divorciado..." required>

                    Nacionalidad

                        <input type="text" data-ng-model="nacionalidad" id="nacionalidad" class="form-control align-field" placeholder="Costarricense, Nicaragüense..." required>

                    Teléfono

                        <input type="text" data-ng-model="telefono" id="telefono" class="form-control align-field" placeholder="0000-0000" required>

                    Correo electrónico

                        <input type="text" data-ng-model="correo" id="correo" class="form-control align-field" placeholder="usuario@hotmail.com" required>

                    Dirección

                        <input type="text" data-ng-model="direccion" id="direccion" class="form-control align-field" placeholder="Alajuela, San Carlos, Santa Rosa de Pocosol, 300 m norte de la entrada principal de Barrio Paraíso" required>

                    <input type="submit" value="Agregar encargado" class="btn btn-primary align-field">

            </fieldset>
        </form>


text:
package org.gradoop.flink.model.impl.functions.utils;

import org.apache.flink.api.common.functions.FilterFunction;

/**
 * Checks if a given object of type {@link IN} is instance of a specific class
 * of type {@link T}.
 *
 * @param <IN>  input type
 * @param <T>   class type to check
 */
public class IsInstance<IN, T> implements FilterFunction<IN> {
  /**
   * Class for isInstance check
   */
  private final Class<T> clazz;

  /**
   * Constructor
   *
   * @param clazz class for isInstance check
   */
  public IsInstance(Class<T> clazz) {
    this.clazz = clazz;
  }

  @Override
  public boolean filter(IN value) throws Exception {
    return clazz.isInstance(value);
  }
}


text:
void wrenLoadMetaLibrary(WrenVM* vm);

#endif

#endif


text:
'use strict';

var HTML = [
  '
',
    '<button class="btn" name="left">Left</button>',
    '<button class="btn" name="center">Center</button>',
    '<button class="btn" name="right">Right</button>',
    '
',
    '<input type="text" name="font-size" value="24"></input>',
  '
'
].join('\n');

function Toolbar(element) {
  //Append self to element
  if(element) element.append($(HTML));
}

Toolbar.prototype.getHTML = function() {
  return HTML;
};

module.exports = Toolbar;


text:
var g_registerWidget = null;
var g_modalRegister = null;
var g_sectionRegister = null;

function RegisterWidget(name, nameCheck, email, emailCheck, psw, pswCheck, pswConfirm, pswConfirmCheck, btn, onSuccess, onError, captcha) {
	// prototypes: onSuccess(data), onError(err)
	this.name = name;
	this.nameCheck = nameCheck;
	this.email = email;
	this.emailCheck = emailCheck;
	this.psw = psw;
	this.pswCheck = pswCheck;
	this.pswConfirm = pswConfirm;
	this.pswConfirmCheck = pswConfirmCheck;
	this.btn = btn;
	this.onSuccess = onSuccess;
	this.onError = onError;
	this.captcha = captcha;
	this.hide = function() {
		this.name.hide();
		this.nameCheck.hide();
		this.email.hide();
		this.emailCheck.hide();
		this.psw.hide();
		this.pswCheck.hide();
		this.pswConfirm.hide();
		this.pswConfirmCheck.hide();
		this.btn.hide();
		this.captcha.hide();
	};
	this.show = function() {
		this.name.show();
		this.nameCheck.show();
		this.email.show();
		this.emailCheck.show();
		this.psw.show();
		this.pswCheck.show();
		this.pswConfirm.show();
		this.pswConfirmCheck.show();
		this.btn.show();
		this.captcha.show();
	};
	this.empty = function() {
		this.name.val("");
		this.nameCheck.text("");
		this.email.val("");
		this.emailCheck.text("");
		this.psw.val("");
		this.pswCheck.text("");
		this.pswConfirm.val("");
		this.pswConfirmCheck.text("");
		this.captcha.input.val("");
		this.captcha.img.attr("src", "/captcha?" + g_keySid + "=" + this.captcha.sid + "&ts=" + new Date().getTime());
	};

	this.btn.click(this, function(evt) {
		var widget = evt.data;
		var username = widget.name.val();
		var email = widget.email.val();
		var password = widget.psw.val();
		var passwordConfirm = widget.pswConfirm.val();

		if(username == null || username.length == 0 || !validateName(username)
		    || email == null || email.length == 0 || !validateEmail(email)
		    || password == null || password.length == 0 || !validatePassword(password) || !validatePasswordConfirm(password, passwordConfirm)) return;

		var btnRegister = $(this);
		disableField(btnRegister);
		var params = {};
		params[g_keyName] = username;
		params[g_keyEmail] = email;
		params[g_keyPassword] = password;
		params[g_keySid] = widget.captcha.sid;
		params[g_keyCaptcha] = widget.captcha.input.val();

		$.ajax({
		    type: "POST",
		    url: "/user/register",
		    data: params,
		    success: function(data, status, xhr){
				enableField(btnRegister);
				if (isCaptchaNotMatched(data)) {
					alert(ALERTS["captcha_not_matched"]);
					if (widget.onError != null) widget.onError(data);
                    return;
				}
				widget.empty();
				if (widget.onSuccess == null) return;
				widget.onSuccess(data);
		    },
		    error: function(xhr, status, err){
				enableField(btnRegister);
				if (widget.onError == null) return;
				widget.onError(err);
		    }
		});
	});

	this.name.on("focusin focusout", this.nameCheck, function(evt){
		evt.preventDefault();
		var nameCheck = evt.data;
		nameCheck.empty();
		nameCheck.html("");
		nameCheck.removeClass("warning");
		var nameVal = $(this).val();
		if(nameVal == null || nameVal.length == 0) return;
		if(!validateName(nameVal)) {
			nameCheck.html("
" + MESSAGES["username_requirement"] + "
");
			nameCheck.addClass("warning");
			return;
		}

		var params={};
		params[g_keyName] = nameVal;
		$.ajax({
			type: "GET",
			url: "/user/name/duplicate",
			data: params,
			success: function(data, status, xhr){
				if (isStandardSuccess(data)){
					nameCheck.html("
" + MESSAGES["username_valid"] + "
");
			    }else{
					nameCheck.addClass("warning");
					nameCheck.html("
" + MESSAGES["username_invalid"] + "
");
				}
			},
			error: function(xhr, status, err){
			}
		});
	});

	this.email.on("focusin focusout", this.emailCheck, function(evt){
		evt.preventDefault();
		var emailCheck = evt.data;
		emailCheck.empty();
		emailCheck.html("");
		emailCheck.removeClass("warning");
		var emailVal = $(this).val();
		if(emailVal == null || emailVal.length == 0) return;
		if(!validateEmail(emailVal)) {
			emailCheck.addClass("warning");
			emailCheck.html("
" + MESSAGES["email_requirement"] + "
");
			return;
		}

		var params = {};
		params[g_keyEmail] = emailVal;
		$.ajax({
			type: "GET",
			url: "/user/email/duplicate",
			data: params,
			success: function(data, status, xhr){
				if (isStandardSuccess(data)){
					emailCheck.html("
" + MESSAGES["email_valid"] + "
");
				}else{
					emailCheck.addClass("warning");
					emailCheck.html("
" + MESSAGES["email_invalid"] + "
");
				}
			},
			error: function(xhr, status, err){
			}
		});
	});

	this.psw.on("input keyup paste", this.pswCheck, function(evt){
		evt.preventDefault();
		var pswCheck = evt.data;
		pswCheck.empty();
		pswCheck.html("");
		pswCheck.removeClass("warning");
		var pswVal = $(this).val();
		if(pswVal == null || pswVal.length ==0 ) return;
		if(validatePassword(pswVal))	return;
		pswCheck.addClass("warning");
		pswCheck.html("
" + MESSAGES["password_requirement"] + "
");
	});

	this.pswConfirm.on("input keyup paste", {0: this.pswConfirmCheck, 1: this.psw}, function(evt){
		evt.preventDefault();
		var pswConfirmCheck = evt.data[0];
		var pswConfirmVal = $(this).val();
		var pswVal = evt.data[1].val();
		pswConfirmCheck.empty();
		pswConfirmCheck.html("");
		pswConfirmCheck.removeClass("warning");
		if(validatePasswordConfirm(pswVal, pswConfirmVal))	return;
		pswConfirmCheck.addClass("warning");
		pswConfirmCheck.html("
" + MESSAGES["password_confirm_requirement"] + "
");
	});
}

function removeRegisterWidget() {
	if (g_sectionRegister == null) return;
	g_sectionRegister.empty();
	if (g_modalRegister == null) return;
	g_modalRegister.empty();
	g_modalRegister = null;
	g_sectionRegister.modal("hide");
}

function initRegisterWidget(par, isModal) {
	removeRegisterWidget();
	if (!isModal) {
		g_sectionRegister = $("
").appendTo(par);
		return;
	}
	g_sectionRegister = $("
").appendTo(par);
	var dialog = $("
", {
		"class": "modal-dialog modal-lg"
	}).appendTo(g_sectionRegister);
	g_modalRegister = $("
", {
		"class": "modal-content"
	}).appendTo(dialog);
}

function generateRegisterWidget(container, isModal, onSuccess, onError){
	initRegisterWidget(container, isModal);
	var par = (isModal ? g_modalRegister : g_sectionRegister);
	var registerBox = $('
', {
		id: "register-box"
	}).appendTo(par);
	var rowName = $('
', {
		"class": "register-name"
	}).appendTo(registerBox);
	var fieldName = $('<input>', {
		type: "text",
		placeHolder: HINTS["username"],
	}).appendTo(rowName);
	var spName = $('
', {
		"class": "message"
	}).appendTo(rowName);

	var rowEmail = $('
', {
		"class": "register-email"
	}).appendTo(registerBox);
	var fieldEmail = $('<input>', {
		type: "text",
		placeHolder: HINTS["email"],
	}).appendTo(rowEmail);
	var spEmail = $('
', {
		"class": "message"
	}).appendTo(rowEmail);

	var rowPsw = $('
', {
		"class": "register-password"
	}).appendTo(registerBox);
	var fieldPsw = $('<input>', {
		type: "password",
		placeHolder: HINTS["password"]
	}).appendTo(rowPsw);
	var spanPsw = $('
', {
		"class": "message"
	}).appendTo(rowPsw);

	var rowPswConfirm = $('
', {
		"class": "register-pswconfirm"
	}).appendTo(registerBox);
	var fieldPswConfirm = $('<input>', {
		type: "password",
		placeHolder: HINTS["confirm_password"]
	}).appendTo(rowPswConfirm);
	var spPswConfirm = $('
', {
		"class": "message"
	}).appendTo(rowPswConfirm);

	var sid = generateUuid();
	var captcha = new Captcha(sid);
	captcha.appendTo(registerBox);

	var rowButton = $('
', {
		"class": "register-button"
	}).appendTo(registerBox);
	var btnRegister = $('<button>', {
		text: TITLES["register"],
		"class": "positive-button"
	}).appendTo(rowButton);

	return new RegisterWidget(fieldName, spName, fieldEmail, spEmail, fieldPsw, spanPsw, fieldPswConfirm, spPswConfirm, btnRegister, onSuccess, onError, captcha);
}

function validatePasswordConfirm(psw, pswConfirm){
	if(psw == null || pswConfirm == null) return false;
	if(psw != pswConfirm) return false;
	return true;
}


text:
require 'test_helper'

class MeasurementsControllerTest < ActionController::TestCase

  # setup do
  #   @measurement = measurements(:one)
  # end

  # test "should get index" do
  #   sign_in users(:one)
  #   get :index
  #   assert_response :success
  #   assert_not_nil assigns(:measurements)
  # end

  # test "should get new" do
  #   sign_in users(:one)
  #   get :new
  #   assert_response :success
  # end

  # test "should create measurement" do
  #   sign_in users(:one)
  #   assert_difference('Measurement.count') do
  #     post :create, measurement: { datetime: @measurement.datetime, sensor_id: @measurement.sensor_id, value: @measurement.value }
  #   end

  #   assert_redirected_to measurement_path(assigns(:measurement))
  # end

  # test "should show measurement" do
  #   sign_in users(:one)
  #   get :show, id: @measurement
  #   assert_response :success
  # end

  # test "should get edit" do
  #   sign_in users(:one)
  #   get :edit, id: @measurement
  #   assert_response :success
  # end

  # test "should update measurement" do
  #   sign_in users(:one)
  #   patch :update, id: @measurement, measurement: { datetime: @measurement.datetime, sensor_id: @measurement.sensor_id, value: @measurement.value }
  #   assert_redirected_to measurement_path(assigns(:measurement))
  # end

  # test "should destroy measurement" do
  #   sign_in users(:one)
  #   assert_difference('Measurement.count', -1) do
  #     delete :destroy, id: @measurement
  #   end

  #   assert_redirected_to measurements_path
  # end

end


text:
package lua

import (
	"unsafe"
)

func CGoBytes(p, length uintptr) []byte {
	if length <= 0 || p == 0 {
		return []byte{}
	}
	buffer := make([]byte, length)
	copyMemory(uintptr(unsafe.Pointer(&buffer[0])), p, length)
	return buffer
}

func CGoStringN(p, length uintptr) string {
	if length <= 0 || p == 0 {
		return ""
	}
	return string(CGoBytes(p, length))
}

func CGoStringZ(p uintptr) string {
	return CGoStringN(p, strLen(p))
}


text:
Capybara.javascript_driver = :webkit

Capybara::Webkit.configure do |config|
  config.block_unknown_urls
end


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
  "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <title>OnLine Bottom Up Deposition — CasperJS  documentation</title>

    <link rel="stylesheet" href="../_static/basic.css" type="text/css" />
    <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
    <link rel="stylesheet" href="../_static/jsdemo.css" type="text/css" />
    <link rel="stylesheet" href="../_static/sphinxcontrib-images/LightBox2/lightbox2/css/lightbox.css" type="text/css" />

    <link rel="shortcut icon" href="../_static/casperjs-favicon.ico"/>
    <link rel="top" title="CasperJS  documentation" href="../index.html" />
    <link rel="up" title="Data Depository" href="$_02-core-10-deposition.html" />
    <link rel="next" title="Nutrition Mathematics" href="$_02-core-11-mathematics.html" />
    <link rel="prev" title="OnLine Top Down Deposition" href="$_02-core-10-deposition-2-top-down.html" />
    <link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Asap:400,700,400italic,700italic&subset=latin,latin-ext">
    <link rel="stylesheet" title="Dark theme" href="../_static/casperjs-dark.css">
    <link rel="alternate stylesheet" title="Light theme" href="../_static/casperjs-light.css">

Navigation

          index

          next |

          previous |

CasperJS  documentation »

Features - Core »

Data Depository »

OnLine Bottom Up Deposition¶

Table of Contents¶

Process

Concept

Vocal Terms

Process¶

Ontology driven process that classifies a food according to precise ontology terms.

Initiate conversation € by traversing a graph € and selecting appropriate terms.

Use a broad term when there is insufficient information to use a more narrow, precise term.

Conversation € has three stages:

identify unique terms [source; part of source; origin of source]

identify combinations of terms that are jointWith € and disjointWith

identify data associated with ontology terms.

Concept¶

Vocal Terms¶

terms to support bottom-up

Document Outline

OnLine Bottom Up Deposition

Table of Contents

Process

Concept

Vocal Terms

Previous topic

OnLine Top Down Deposition

Next topic

Nutrition Mathematics

Index

Thesaurus

This Page

Show Source

Quick search

    <form class="search" action="../search.html" method="get">
      <input type="text" name="q" />
      <input type="submit" value="Go" />
      <input type="hidden" name="check_keywords" value="yes" />
      <input type="hidden" name="area" value="default" />
    </form>

    Enter search terms or a module, class or function name.

Navigation

          index

          next |

          previous |

CasperJS  documentation »

Features - Core »

Data Depository »

        © Copyright 2011-2015 Nicolas Perriault and contributors. CasperJS logo by Jeremy Forveille.
      Created using Sphinx 1.3.1.


text:
package org.apache.accumulo.master.tableOps;

import org.apache.accumulo.core.master.state.tables.TableState;
import org.apache.accumulo.fate.Repo;
import org.apache.accumulo.master.Master;
import org.apache.accumulo.server.tables.TableManager;
import org.slf4j.LoggerFactory;

class FinishCreateTable extends MasterRepo {

  private static final long serialVersionUID = 1L;

  private TableInfo tableInfo;

  public FinishCreateTable(TableInfo ti) {
    this.tableInfo = ti;
  }

  @Override
  public long isReady(long tid, Master environment) throws Exception {
    return 0;
  }

  @Override
  public Repo<Master> call(long tid, Master env) throws Exception {
    TableManager.getInstance().transitionTableState(tableInfo.tableId, TableState.ONLINE);

    Utils.unreserveNamespace(tableInfo.namespaceId, tid, false);
    Utils.unreserveTable(tableInfo.tableId, tid, true);

    env.getEventCoordinator().event("Created table %s ", tableInfo.tableName);

    LoggerFactory.getLogger(FinishCreateTable.class).debug("Created table " + tableInfo.tableId + " " + tableInfo.tableName);

    return null;
  }

  @Override
  public String getReturn() {
    return tableInfo.tableId;
  }

  @Override
  public void undo(long tid, Master env) throws Exception {}

}


text:
#include "tensorflow/core/framework/rendezvous.h"

#include "third_party/eigen3/unsupported/Eigen/CXX11/Tensor"
#include "tensorflow/core/framework/cancellation.h"
#include "tensorflow/core/framework/tensor.h"
#include "tensorflow/core/framework/tensor_shape.h"
#include "tensorflow/core/framework/tensor_types.h"
#include "tensorflow/core/framework/types.pb.h"
#include "tensorflow/core/lib/core/errors.h"
#include "tensorflow/core/lib/core/notification.h"
#include "tensorflow/core/lib/core/status_test_util.h"
#include "tensorflow/core/lib/core/threadpool.h"
#include "tensorflow/core/lib/random/simple_philox.h"
#include "tensorflow/core/lib/strings/strcat.h"
#include "tensorflow/core/platform/env.h"
#include "tensorflow/core/platform/logging.h"
#include "tensorflow/core/platform/mutex.h"
#include "tensorflow/core/platform/notification.h"
#include "tensorflow/core/platform/test.h"
#include "tensorflow/core/platform/test_benchmark.h"
#include "tensorflow/core/platform/types.h"

namespace tensorflow {
namespace {

TEST(RendezvousTest, Key) {
  const string key = Rendezvous::CreateKey(
      "/job:mnist/replica:1/task:2/CPU:0", 7890,
      "/job:mnist/replica:1/task:2/device:GPU:0", "var0", FrameAndIter(0, 0));
  EXPECT_EQ(key,
            "/job:mnist/replica:1/task:2/CPU:0;"
            "0000000000001ed2;"  // 7890 = 0x1ed2
            "/job:mnist/replica:1/task:2/device:GPU:0;"
            "var0;"
            "0:0");
  Rendezvous::ParsedKey parsed;
  TF_EXPECT_OK(Rendezvous::ParseKey(key, &parsed));
  EXPECT_EQ(parsed.src_device, "/job:mnist/replica:1/task:2/CPU:0");
  EXPECT_EQ(parsed.src_incarnation, 7890);
  EXPECT_EQ(parsed.src.type, "CPU");
  EXPECT_EQ(parsed.dst_device, "/job:mnist/replica:1/task:2/device:GPU:0");
  EXPECT_EQ(parsed.dst.type, "GPU");

  EXPECT_FALSE(Rendezvous::ParseKey("foo;bar;baz", &parsed).ok());
  EXPECT_FALSE(Rendezvous::ParseKey("/job:mnist/replica:1/task:2/CPU:0;"
                                    "/job:mnist/replica:1/task:2/device:GPU:0;",
                                    &parsed)
                   .ok());
  EXPECT_FALSE(
      Rendezvous::ParseKey(strings::StrCat(key, ";", key), &parsed).ok());
}

class LocalRendezvousTest : public ::testing::Test {
 public:
  LocalRendezvousTest() : threads_(Env::Default(), "test", 16) {
    rendez_ = NewLocalRendezvous();
  }

  ~LocalRendezvousTest() override { rendez_->Unref(); }

  void SchedClosure(std::function<void()> fn) {
    threads_.Schedule(std::move(fn));
  }

  Rendezvous* rendez_;

 private:
  thread::ThreadPool threads_;
};

// string -> Tensor<string>
Tensor V(const string& content) {
  Tensor tensor(DT_STRING, TensorShape({}));
  tensor.scalar<tstring>()() = content;
  return tensor;
}

// Tensor<string> -> string
string V(const Tensor& tensor) {
  CHECK_EQ(tensor.dtype(), DT_STRING);
  CHECK(TensorShapeUtils::IsScalar(tensor.shape()));
  return tensor.scalar<tstring>()();
}

Rendezvous::ParsedKey MakeKey(const string& name) {
  string s = Rendezvous::CreateKey("/job:mnist/replica:1/task:2/CPU:0", 7890,
                                   "/job:mnist/replica:1/task:2/device:GPU:0",
                                   name, FrameAndIter(0, 0));
  Rendezvous::ParsedKey k;
  TF_EXPECT_OK(Rendezvous::ParseKey(s, &k));
  return k;
}

const Rendezvous::ParsedKey& KeyFoo() {
  static auto* key = new Rendezvous::ParsedKey(MakeKey("foo"));
  return *key;
}

const Rendezvous::ParsedKey& KeyBar() {
  static auto* key = new Rendezvous::ParsedKey(MakeKey("bar"));
  return *key;
}

TEST_F(LocalRendezvousTest, SendRecv) {
  Rendezvous::Args args;
  TF_ASSERT_OK(rendez_->Send(KeyFoo(), args, V("hello"), false));
  Tensor val(DT_STRING);
  bool is_dead = false;
  TF_ASSERT_OK(rendez_->Recv(KeyFoo(), args, &val, &is_dead));
  EXPECT_EQ("hello", V(val));
}

TEST_F(LocalRendezvousTest, RecvSend) {
  SchedClosure([this]() {
    Env::Default()->SleepForMicroseconds(10000);
    Rendezvous::Args args;
    TF_ASSERT_OK(rendez_->Send(KeyFoo(), args, V("hello"), false));
  });
  Tensor val(DT_STRING);
  bool is_dead = false;
  Rendezvous::Args args;
  TF_ASSERT_OK(rendez_->Recv(KeyFoo(), args, &val, &is_dead));
  EXPECT_EQ("hello", V(val));
}

TEST_F(LocalRendezvousTest, PingPong) {
  SchedClosure([this]() {
    Tensor t(DT_STRING);
    bool is_dead = false;
    Rendezvous::Args args;
    TF_ASSERT_OK(rendez_->Recv(KeyFoo(), args, &t, &is_dead));
    TF_ASSERT_OK(rendez_->Send(KeyBar(), args, t, is_dead));
  });
  Env::Default()->SleepForMicroseconds(1000000);
  Tensor val(DT_STRING);
  bool val_dead = false;
  Rendezvous::Args args;
  TF_ASSERT_OK(rendez_->Send(KeyFoo(), args, V("secret msg"), val_dead));
  TF_ASSERT_OK(rendez_->Recv(KeyBar(), args, &val, &val_dead));
  EXPECT_EQ("secret msg", V(val));
}

TEST_F(LocalRendezvousTest, CancelBeforeRecv) {
  auto* cm = new CancellationManager();
  Tensor val(DT_STRING);
  bool is_dead = false;
  Rendezvous::Args args;
  args.cancellation_manager = cm;
  cm->StartCancel();
  auto s = rendez_->Recv(KeyFoo(), args, &val, &is_dead);
  EXPECT_FALSE(s.ok());
  EXPECT_TRUE(errors::IsCancelled(s));
  EXPECT_EQ("RecvAsync is cancelled.", s.error_message());
  delete cm;
}

TEST_F(LocalRendezvousTest, CancelAfterRecv) {
  auto* cm = new CancellationManager();
  Notification n;
  SchedClosure([cm, &n]() {
    Env::Default()->SleepForMicroseconds(10000);
    cm->StartCancel();
    n.Notify();
  });
  Tensor val(DT_STRING);
  bool is_dead = false;
  Rendezvous::Args args;
  args.cancellation_manager = cm;
  auto s = rendez_->Recv(KeyFoo(), args, &val, &is_dead);
  EXPECT_FALSE(s.ok());
  EXPECT_TRUE(errors::IsCancelled(s));
  EXPECT_EQ("RecvAsync is cancelled.", s.error_message());
  n.WaitForNotification();
  delete cm;
}

TEST_F(LocalRendezvousTest, CancelEmptyQueue) {
  auto* cm = new CancellationManager();
  Notification n;
  SchedClosure([this, cm, &n]() {
    Env::Default()->SleepForMicroseconds(10000);
    Rendezvous::Args args;
    TF_ASSERT_OK(rendez_->Send(KeyFoo(), args, V("hello"), false));
    cm->StartCancel();
    n.Notify();
  });
  Tensor val(DT_STRING);
  bool is_dead = false;
  Rendezvous::Args args;
  args.cancellation_manager = cm;
  TF_ASSERT_OK(rendez_->Recv(KeyFoo(), args, &val, &is_dead));
  EXPECT_EQ("hello", V(val));
  n.WaitForNotification();
  delete cm;
}

TEST_F(LocalRendezvousTest, CancelMultiple) {
  auto* cm = new CancellationManager();
  SchedClosure([this, cm]() {
    Env::Default()->SleepForMicroseconds(10000);
    Rendezvous::Args args;
    cm->StartCancel();
    TF_ASSERT_OK(rendez_->Send(KeyFoo(), args, V("hello"), false));
    TF_ASSERT_OK(rendez_->Send(KeyFoo(), args, V("hello"), false));
  });
  Tensor val(DT_STRING);
  Rendezvous::Args args;
  Rendezvous::Args args_with_cancellation;
  args_with_cancellation.cancellation_manager = cm;
  Notification n0;
  Notification n1;
  Notification n2;
  Notification n3;
  Status s0;
  Status s1;
  Status s2;
  Status s3;

  rendez_->RecvAsync(
      KeyFoo(), args,
      [&n0, &s0](const Status& s, const Rendezvous::Args& send_args,
                 const Rendezvous::Args& recv_args, const Tensor& v,
                 const bool dead) {
        s0.Update(s);
        n0.Notify();
      });
  rendez_->RecvAsync(
      KeyFoo(), args_with_cancellation,
      [&n1, &s1](const Status& s, const Rendezvous::Args& send_args,
                 const Rendezvous::Args& recv_args, const Tensor& v,
                 const bool dead) {
        s1.Update(s);
        n1.Notify();
      });
  rendez_->RecvAsync(
      KeyFoo(), args,
      [&n2, &s2](const Status& s, const Rendezvous::Args& send_args,
                 const Rendezvous::Args& recv_args, const Tensor& v,
                 const bool dead) {
        s2.Update(s);
        n2.Notify();
      });
  rendez_->RecvAsync(
      KeyFoo(), args_with_cancellation,
      [&n3, &s3](const Status& s, const Rendezvous::Args& send_args,
                 const Rendezvous::Args& recv_args, const Tensor& v,
                 const bool dead) {
        s3.Update(s);
        n3.Notify();
      });
  n0.WaitForNotification();
  n1.WaitForNotification();
  n2.WaitForNotification();
  n3.WaitForNotification();
  TF_ASSERT_OK(s0);
  TF_ASSERT_OK(s2);
  EXPECT_FALSE(s1.ok());
  EXPECT_FALSE(s3.ok());

  delete cm;
}

// A simple structure that behaves a bit like a blocking counter.  The
// user that decrements counter to 0 does done.Notify(), and the main
// thread waits for done to be notified.
struct BlockingState {
  mutex lock;
  int counter = 0;
  Notification done;
};

TEST_F(LocalRendezvousTest, RandomSendRecv) {
  // We are scheduling 2*N closures in the this->threads_, which is
  // configured with only 16 threads. Furthermore, because the
  // threadpool may execute the closures in an arbitrary order, we
  // must use RecvAsync below. Otherwise, blocking Recv() may run
  // before all the Send() and deadlock.
  static const int N = 100;
  random::PhiloxRandom philox(testing::RandomSeed(), 17);
  random::SimplePhilox rnd(&philox);
  BlockingState state;
  state.counter = N;
  for (int i = 0; i < N; ++i) {
    int micros = 100 + rnd.Uniform(1000);
    SchedClosure([this, i, micros]() {
      Env::Default()->SleepForMicroseconds(micros);
      Rendezvous::Args args;
      TF_ASSERT_OK(rendez_->Send(MakeKey(strings::StrCat(i)), args,
                                 V(strings::StrCat(i)), false));
    });
    auto recv_done = [this, &state, i](const Status& status,
                                       const Rendezvous::Args& sender_args,
                                       const Rendezvous::Args& recver_args,
                                       const Tensor& val, const bool val_dead) {
      EXPECT_EQ(strings::StrCat(i), V(val));
      bool done = false;
      {
        mutex_lock l(state.lock);
        state.counter--;
        if (state.counter == 0) {
          done = true;
        }
      }
      if (done) {
        state.done.Notify();
      }
    };
    micros = 100 + rnd.Uniform(1000);
    SchedClosure([this, i, micros, recv_done]() {
      Env::Default()->SleepForMicroseconds(micros);
      rendez_->RecvAsync(MakeKey(strings::StrCat(i)), Rendezvous::Args(),
                         recv_done);
    });
  }

  state.done.WaitForNotification();
}

void RandomSleep() {
  if (std::rand() % 10 == 0) {
    Env::Default()->SleepForMicroseconds(1000);
  }
}

TEST_F(LocalRendezvousTest, MultiSends) {
  static const int N = 100;
  const auto& key_foo = KeyFoo();
  Rendezvous::Args args;
  SchedClosure([=]() {
    for (int i = 0; i < N; ++i) {
      TF_ASSERT_OK(rendez_->Send(key_foo, args, V(strings::StrCat(i)), false));
      RandomSleep();
    }
  });
  Tensor val;
  bool val_dead;
  for (int i = 0; i < N; ++i) {
    TF_ASSERT_OK(rendez_->Recv(key_foo, args, &val, &val_dead));
    RandomSleep();
  }
}

TEST_F(LocalRendezvousTest, RecvAbort) {
  rendez_->Ref();
  SchedClosure([this]() {
    rendez_->StartAbort(errors::Aborted(""));  // abort
    rendez_->Unref();
  });
  Tensor val(DT_STRING);
  bool val_dead = false;
  Rendezvous::Args args;
  Status status = rendez_->Recv(KeyFoo(), args, &val, &val_dead);
  EXPECT_TRUE(errors::IsAborted(status));
}

// Similar to RecvAbort. But this test case ensures the main thread
// Recv() call happens after StartAbort().
TEST_F(LocalRendezvousTest, RecvSleepAbort) {
  rendez_->Ref();
  SchedClosure([this]() {
    Env::Default()->SleepForMicroseconds(1000000);
    rendez_->StartAbort(errors::Aborted(""));  // abort
    rendez_->Unref();
  });
  Tensor val(DT_STRING);
  bool val_dead = false;
  Rendezvous::Args args;
  Status status = rendez_->Recv(KeyFoo(), args, &val, &val_dead);
  EXPECT_TRUE(errors::IsAborted(status));
}

TEST_F(LocalRendezvousTest, AbortThenRecvOrSend) {
  rendez_->StartAbort(errors::Aborted(""));
  Tensor val(DT_STRING);
  bool val_dead = false;
  Rendezvous::Args args;
  EXPECT_TRUE(errors::IsAborted(rendez_->Send(KeyFoo(), args, val, val_dead)));
  EXPECT_TRUE(
      errors::IsAborted(rendez_->Recv(KeyFoo(), args, &val, &val_dead)));
}

class DummyDeviceContext : public DeviceContext {
 public:
  explicit DummyDeviceContext(int stream_id) : stream_id_(stream_id) {}
  ~DummyDeviceContext() override {}
  int stream_id() const { return stream_id_; }

  void CopyTensorInSameDevice(const Tensor* input_tensor, Device* device,
                              Tensor* output_tensor,
                              StatusCallback done) const override {
    done(OkStatus());
  }

 private:
  const int stream_id_;
};

TEST_F(LocalRendezvousTest, TransferDummyDeviceContext) {
  Rendezvous::Args args;
  args.device_context = new DummyDeviceContext(123);

  TF_ASSERT_OK(rendez_->Send(KeyFoo(), args, V("hello"), false));

  Notification n;
  Rendezvous::Args args1;
  args1.device_context = new DummyDeviceContext(1);
  rendez_->RecvAsync(
      KeyFoo(), args1,
      [&n](const Status& s, const Rendezvous::Args& send_args,
           const Rendezvous::Args& recv_args, const Tensor& val, bool is_dead) {
        CHECK_EQ(123, dynamic_cast<const DummyDeviceContext*>(
                          send_args.device_context)
                          ->stream_id());
        n.Notify();
      });

  n.WaitForNotification();
  args.device_context->Unref();
  args1.device_context->Unref();
}

void BM_SendRecv(::testing::benchmark::State& state) {
  Rendezvous* rendez = NewLocalRendezvous();
  Tensor orig = V("val");
  Tensor val(DT_STRING, TensorShape({}));
  bool is_dead = false;
  Rendezvous::Args args;

  for (auto s : state) {
    TF_CHECK_OK(rendez->Send(KeyFoo(), args, orig, is_dead));
    TF_CHECK_OK(rendez->Recv(KeyFoo(), args, &val, &is_dead));
  }
  CHECK_EQ(V(val), V(orig));

  rendez->Unref();
}
BENCHMARK(BM_SendRecv);

void BM_RecvSend(::testing::benchmark::State& state) {
  Rendezvous* rendez = NewLocalRendezvous();
  Tensor orig = V("val");
  Tensor val(DT_STRING, TensorShape({}));
  bool is_dead = false;
  Rendezvous::Args args;

  for (auto s : state) {
    bool received = false;
    rendez->RecvAsync(
        KeyFoo(), args,
        [&val, &received](const Status& /*s*/,
                          const Rendezvous::Args& /*send_args*/,
                          const Rendezvous::Args& /*recv_args*/,
                          const Tensor& tensor, bool /*is_dead*/) {
          val = tensor;
          received = true;
        });
    TF_CHECK_OK(rendez->Send(KeyFoo(), args, orig, is_dead));
    CHECK(received);
  }
  CHECK_EQ(V(val), V(orig));

  rendez->Unref();
}
BENCHMARK(BM_RecvSend);

void BM_PingPong(::testing::benchmark::State& state) {
  const int messages_count = state.range(0);
  auto* cm = new CancellationManager();
  thread::ThreadPool* pool = new thread::ThreadPool(Env::Default(), "test", 1);

  // Benchmark loop
  // In each iteration:
  // The main thread sends "foo" for messages_count times and receives "bar"
  // for messages_count times.  The other thread sends "bar" for
  // messages_count times and receives "foo" for messages_count times.
  for (auto s : state) {
    Rendezvous* rendez = NewLocalRendezvous();
    pool->Schedule([rendez, messages_count]() {
      Tensor bar = V("bar");
      Tensor foo(DT_STRING, TensorShape({}));
      bool is_dead = false;
      Rendezvous::Args args;
      for (int i = 0; i < messages_count; ++i) {
        TF_CHECK_OK(rendez->Recv(KeyFoo(), args, &foo, &is_dead));
        TF_CHECK_OK(rendez->Send(KeyBar(), args, bar, is_dead));
      }
      CHECK_EQ("foo", V(foo));
    });
    Tensor foo = V("foo");
    Tensor bar(DT_STRING, TensorShape({}));
    bool is_dead = false;
    Rendezvous::Args args;
    args.cancellation_manager = cm;
    for (int i = 0; i < messages_count; ++i) {
      TF_CHECK_OK(rendez->Send(KeyFoo(), args, foo, is_dead));
      TF_CHECK_OK(rendez->Recv(KeyBar(), args, &bar, &is_dead));
    }
    CHECK_EQ("bar", V(bar));
  }
  state.SetItemsProcessed(messages_count * state.iterations());
  delete pool;
  delete cm;
}
BENCHMARK(BM_PingPong)->Arg(100)->Arg(200)->Arg(300);

}  // namespace
}  // namespace tensorflow


text:
#ifndef INCLUDE_ROBOT_H_
#define INCLUDE_ROBOT_H_

#include <Eigen/Eigen>
#include <vector>
#include <map.h>

#include <memory>
#include <string>
#include <functional>

#define RANGE (6.0)
#define DEAD (0.1)

typedef class Robot {
 public:
  Robot();
  void Init(std::string map);

  double step();
  void Draw();
  void Reset();
  void RegisterLaserFunc(std::function<void(double, double, double)> f);
  void RegisterOdomFunc(std::function<void(double, double, double)> f);

  void set_speed_left(double speed_left_);
  void set_speed_right(double speed_right_);
  void set_speed(double speed_left_, double speed_right_);
  void set_twist(double velocity, double omega);

  double theta();
  double distance();
  double odom_left();
  double odom_right();
  double radius();

 private:
  void PushHistry(Vector2d v);
  void Laser();
  void Odom();

 private:
  double time_;
  double radius_;

  // body
  double aim_speed_left_;
  double aim_speed_right_;
  double speed_left_;
  double speed_right_;
  Vector2d position_;
  Vector2d direction_;

  // radar
  double omega_;
  double theta_;
  double distance_;
  Vector2d shot_;

  // encoder
  double odom_left_;
  double odom_right_;

  std::vector<Vector2d> history_;

  std::function<void(double, double, double)> laser_func_;
  std::function<void(double, double, double)> odom_func_;

  const double laser_rate_ = 360 * 10;
  const double odom_rate_ = 100;
  double laser_waiting_time_;
  double odom_waiting_time_;
  double laser_tail_time_;
  double odom_tail_time_;

  std::unique_ptr<slamsim::Map> map_;
} * pRobot;

#endif  // INCLUDE_ROBOT_H_


text:
package VBPLTyping.TypeErrors;

import VBPLTyping.TypingModel.DataType;

/**
 * Created by Nyd on 2-3-2017.
 */
public class StatementTypeError extends RuntimeException {

    public StatementTypeError(int lineNumber, DataType expected, DataType found){
        super("Error at line " + lineNumber + ". Statement expected to be of type " + expected + ", found type " + found + ".");
    }
}