text:
'use strict';
const expect = require('chai').expect;
const UssdMenu = require('../lib/ussd-menu');

describe('UssdMenu', function () {
    let menu,
        args = {
            phoneNumber: '+2547123456789',
            serviceCode: '111',
            sessionId: 'sfdsfdsafdsf',
            text: ''
        };
    beforeEach(function () {
        menu = new UssdMenu();
    });

    describe('States', function () {

        it('should create start state', function () {
            menu.startState({
                run: function () {
                    menu.con('1. Next');
                },
                next: {
                    '1': 'next'
                }
            });

            let state = menu.states[UssdMenu.START_STATE];
            expect(state).to.be.an('object');
            expect(state.next).to.be.an('object');
            expect(state.next['1']).to.equal('next');
            expect(state.run).to.be.a('function');
        });

        it('should create states', function () {
            menu.state('state1', {
                run: function () {
                    menu.con('1. State 2');
                },
                next: {
                    '1': 'state2'
                }
            });

            menu.state('state2', {
                run: function () {
                    menu.end('End.');
                }
            });

            let state = menu.states['state1'];
            expect(state).to.be.an('object');
            expect(state.next).to.be.an('object');
            expect(state.next['1']).to.equal('state2');
            expect(state.run).to.be.a('function');

            state = menu.states['state2'];
            expect(state).to.be.an('object');
            expect(state.run).to.be.a('function');
        });
    });

    describe('State Resolution', function () {

        it('should run the start state if no empty rule exists', function (done) {
            args.text = '';
            menu.startState({
                run: function () {
                    done();
                },
                next: {
                    '1': 'state2'
                }
            });

            menu.run(args);
        });

        it('should follow the empty rule on the start state if declared', function (done) {

            args.text = '';
            menu.startState({
                run: function () {
                    done('Error: start state called');
                },
                next: {
                    '': 'state1'
                }
            });

            menu.state('state1', {
                run: function () {
                    done();
                }
            });

            menu.run(args);
        });

        it('should pass the state to the run function', function (done) {

            args.text = '1';
            menu.startState({
                next: {
                    '1': 'state1'
                }
            });
            menu.state('state1', {
                run: function (state) {
                    expect(state.val).to.equal('1');
                    expect(menu.val).to.equal('1');
                    expect(state.menu).to.equal(menu);
                    expect(state.menu.args).to.deep.equal(args);
                    done();
                }
            });

            menu.run(args);
        });

        it('should resolve simple string rules', function (done) {

            args.text = '1*4';
            menu.startState({
                next: {
                    '1': 'state1'
                }
            });

            menu.state('state1', {
                next: {
                    '4': 'state1.4'
                }
            });

            menu.state('state1.4', {
                run: function (state) {
                    expect(state.val).to.equal('4');
                    done();
                }
            });

            menu.run(args);
        });

        it('should resolve regex rules when starting with *', function (done) {

            args.text = '1*James';
            menu.startState({
                next: {
                    '1': 'state1'
                }
            });

            menu.state('state1', {
                next: {
                    '*\\w+': 'state1.name'
                }
            });

            menu.state('state1.name', {
                run: function (state) {
                    expect(state.val).to.equal('James');
                    done();
                }
            });

            menu.run(args);
        });

        it('should resolve regex first if declared before conflicting rule', function (done) {

            args.text = 'input';
            menu.startState({
                next: {
                    '*\\w+': 'state1',
                    'input': 'state2' // conflicts with \w+ regex
                }
            });

            menu.state('state1', {
                run: function (state) {
                    expect(state.val).to.equal('input');
                    done();
                }
            });

            menu.state('state2', {
                run: function (state) {
                    done('state2 not supposed to be called');
                }
            });

            menu.run(args);
        });

        it('should not resolve regex first if declared after conflicting rule', function (done) {

            args.text = 'rule';
            menu.startState({
                next: {
                    'rule': 'state1',
                    '*\\w+': 'state2'
                }
            });

            menu.state('state1', {
                run: function (state) {
                    expect(state.val).to.equal('rule');
                    done();
                }
            });

            menu.state('state2', {
                run: function (state) {
                    done('state2 not supposed to be called');
                }
            });

            menu.run(args);
        });

        it('should successfully resolve state based on sync function', function (done) {

            args.text = '1';
            menu.startState({
                next: {
                    '1': function () {
                        return 'state1';
                    }
                }
            });

            menu.state('state1', {
                run: function (state) {
                    expect(state.val).to.equal('1');
                    done();
                }
            });

            menu.run(args);
        });

        it('should successfully resolve state based on async function using callback', function (done) {

            args.text = '1';
            menu.startState({
                next: {
                    '1': function (callback) {
                        return callback('state1');
                    }
                }
            });

            menu.state('state1', {
                run: function (state) {
                    expect(state.val).to.equal('1');
                    done();
                }
            });

            menu.run(args);
        });

        it('should successfully resolve state based on async function using promise', function (done) {

            args.text = '1';
            menu.startState({
                next: {
                    '1': function () {
                        return new Promise((resolve, reject) => {
                            return resolve('state1');
                        });
                    }
                }
            });

            menu.state('state1', {
                run: function (state) {
                    expect(state.val).to.equal('1');
                    done();
                }
            });

            menu.run(args);
        });

        it('should fall back to declared default if link not found', function (done) {
            args.text = '1*invalid';
            menu.startState({
                next: {
                    '1': 'state1'
                }
            });

            menu.state('state1', {
                next: {
                    '1': 'state1.1',
                    '2': 'state1.2',
                },

                defaultNext: 'state1.default'
            });

            menu.state('state1.default', {
                run: function (state) {
                    expect(state.val).to.equal('invalid');
                    done();
                }
            });

            menu.run(args);
        });

        if ('should use same state as default if no default is declared', function (done) {
            args.text = '1*invalid';
            menu.startState({
                next: {
                    '1': 'state1'
                }
            });

            menu.state('state1', {
                run: function (state) {
                    expect(state.val).to.equal('invalid');
                    done();
                },
                next: {
                    '1': 'state1.1',
                    '2': 'state1.2',
                }
            });
        });

        it('should redirect to a different state using the go method', function (done) {
            args.text = '1';
            menu.startState({
                next: {
                    '1': 'state1',
                    '2': 'state2'
                }
            });
            menu.state('state1', {
                run: function (state) {
                    menu.go('state2');
                }
            });
            menu.state('state2', {
                run: function (state) {
                    expect(state.val).to.equal('1'); //retains the val of the referring state
                    expect(menu.val).to.equal('1');
                    done();
                }
            });
            menu.run(args);

        });

        it('should redirect to the start state using goStart method', function (done) {
            args.text = '1';
            menu.startState({
                run: function (state) {
                    expect(state.val).to.equal('1');
                    expect(menu.val).to.equal('1');
                    done();
                },
                next: {
                    '1': 'state1',
                    '2': 'state2'
                }
            });
            menu.state('state1', {
                run: function (state) {
                    menu.goStart();
                }
            });

            menu.run(args);
        });

    });

    describe('Response', function () {
        let args = {
            phoneNumber: '+254123456789',
            serviceCode: '111',
            sessionId: 'dsfsfsdfsd',
            text: ''
        };
        it('should successfully return a CON response', function (done) {

            let message = 'Choose option';
            menu.startState({
                run: function () {
                    menu.con(message);
                }
            });

            menu.run(args, function (res) {
                expect(res).to.equal('CON ' + message);
                done();
            });
        });

        it('should successfully return an END response', function (done) {

            let message = 'Thank you';
            menu.startState({
                run: function () {
                    menu.end(message);
                }
            });
            menu.run(args, function (res) {
                expect(res).to.equal('END ' + message);
                done();
            });
        });

    });

    describe('Sessions', function () {

        describe('Callback-based config', function () {
            let menu;
            let session;
            let args = {
                serviceCode: '*111#',
                phoneNumber: '123456',
                sessionId: '324errw44we'
            };
            let config = {
                start: (id, cb) => {
                    if (!(id in session)) session[id] = {};
                    cb();
                },
                end: (id, cb) => {
                    delete session[id];
                    cb();
                },
                get: (id, key, cb) => {
                    let val = session[id][key];
                    cb(null, val);
                },
                set: (id, key, val, cb) => {
                    session[id][key] = val;
                    cb();
                }
            };

            it('should manage session using promises', function (done) {
                session = {};
                menu = new UssdMenu();
                menu.sessionConfig(config);
                menu.startState({
                    run: () => {
                        menu.session.set('name', 'Habbes').then(() => {
                            expect(session[args.sessionId].name).to.equal('Habbes');
                            menu.con('Next');
                        })
                            .catch(err => {
                                done(err);
                            });
                    },
                    next: {
                        '1': 'state1'
                    }
                });

                menu.state('state1', {
                    run: () => {
                        menu.session.get('name').then(val => {
                            expect(val).to.equal('Habbes');
                            menu.end();
                        })
                            .catch(err => {
                                console.log('STATE1 error', err);
                                done(err);
                            });
                    }
                });

                args.text = '';
                menu.run(args, () => {
                    expect(session[args.sessionId]).to.deep.equal({ name: 'Habbes' });
                    args.text = '1';
                    menu.run(args, () => {
                        process.nextTick(() => {
                            // expect session to be deleted
                            expect(session[args.sessionId]).to.not.be.ok;
                            done();
                        });

                    });
                });

            });

            it('should manage session using callbacks', function (done) {
                session = {};
                menu = new UssdMenu();
                menu.sessionConfig(config);
                menu.startState({
                    run: () => {
                        menu.session.set('name', 'Habbes', err => {
                            if (err) return done(err);
                            expect(session[args.sessionId].name).to.equal('Habbes');
                            menu.con('Next');
                        });
                    },
                    next: {
                        '1': 'state1'
                    }
                });

                menu.state('state1', {
                    run: () => {
                        menu.session.get('name', (err, val) => {
                            if (err) return done(err);
                            expect(val).to.equal('Habbes');
                            menu.end();
                        });
                    }
                });

                args.text = '';
                menu.run(args, () => {
                    expect(session[args.sessionId]).to.deep.equal({ name: 'Habbes' });
                    args.text = '1';
                    menu.run(args, _ => {
                        process.nextTick(() => {
                            // expect session to be deleted
                            expect(session[args.sessionId]).to.not.be.ok;
                            done();
                        });

                    });
                });

            });

        });

        describe('Promise-based config', function () {
            let menu;
            let session;
            let args = {
                serviceCode: '*111#',
                phoneNumber: '123456',
                sessionId: '324errw44we'
            };
            let config = {
                start: (id) => {
                    return new Promise((resolve, reject) => {
                        if (!(id in session)) session[id] = {};
                        return resolve();
                    });
                },
                end: (id) => {
                    return new Promise((resolve, reject) => {
                        delete session[id];
                        return resolve();
                    });
                },
                get: (id, key) => {
                    return new Promise((resolve, reject) => {
                        let val = session[id][key];
                        return resolve(val);
                    });
                },
                set: (id, key, val) => {
                    return new Promise((resolve, reject) => {
                        session[id][key] = val;
                        return resolve();
                    });
                }
            };

            it('should manage session using promises', function (done) {
                session = {};
                menu = new UssdMenu();
                menu.sessionConfig(config);
                menu.startState({
                    run: () => {
                        menu.session.set('name', 'Habbes').then(() => {
                            expect(session[args.sessionId].name).to.equal('Habbes');
                            menu.con('Next');
                        })
                            .catch(done);
                    },
                    next: {
                        '1': 'state1'
                    }
                });

                menu.state('state1', {
                    run: () => {
                        menu.session.get('name').then(val => {
                            expect(val).to.equal('Habbes');
                            menu.end();
                        })
                            .catch(done);
                    }
                });

                args.text = '';
                menu.run(args, () => {
                    expect(session[args.sessionId]).to.deep.equal({ name: 'Habbes' });
                    args.text = '1';
                    menu.run(args, _ => {
                        process.nextTick(() => {
                            // expect session to be deleted
                            expect(session[args.sessionId]).to.not.be.ok;
                            done();
                        });

                    });
                });

            });

            it('should manage session using callbacks', function (done) {
                session = {};
                menu = new UssdMenu();
                menu.sessionConfig(config);
                menu.startState({
                    run: () => {
                        menu.session.set('name', 'Habbes', err => {
                            if (err) return done(err);
                            expect(session[args.sessionId].name).to.equal('Habbes');
                            menu.con('Next');
                        });
                    },
                    next: {
                        '1': 'state1'
                    }
                });

                menu.state('state1', {
                    run: () => {
                        menu.session.get('name', (err, val) => {
                            if (err) return done(err);
                            expect(val).to.equal('Habbes');
                            menu.end();
                        });
                    }
                });

                args.text = '';
                menu.run(args, () => {
                    expect(session[args.sessionId]).to.deep.equal({ name: 'Habbes' });
                    args.text = '1';
                    menu.run(args, _ => {
                        process.nextTick(() => {
                            // expect session to be deleted
                            expect(session[args.sessionId]).to.not.be.ok;
                            done();
                        });

                    });
                });

            });

        });

    });

    describe('Error handling', function () {

        it('should emit error when route cannot be reached', function (done) {
            menu = new UssdMenu();
            menu.startState({
                run: () => {
                    menu.con('Next');
                },
                next: {
                    '1': 'unknown'
                }
            });
            args.text = '1';
            menu.on('error', err => {
                expect(err).to.be.an('error');
                done();
            });
            menu.run(args);
        });

        it('should emit error when run function not defined on matched route', function (done) {
            menu = new UssdMenu();
            menu.startState({
                run: () => {
                    menu.con('Next');
                },
                next: {
                    '1': 'state1'
                }
            });
            menu.state('state1', {});
            args.text = '1';
            menu.on('error', err => {
                expect(err).to.be.an('error');
                done();
            });
            menu.run(args);

        });

        describe('Session Handler errors', function () {

            it('should emit error when session start handler returns error in callback', function (done) {
                let config = {
                    start: (sessionId, cb) => {
                        cb(new Error('start error'));
                    },
                };

                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('start error');
                    done();
                });
                menu.sessionConfig(config);
                menu.run(args);

            });

            it('should emit error when session start handler returns error in promise', function (done) {
                let config = {
                    start: () => {
                        return new Promise((resolve, reject) => {
                            return reject(new Error('start error'))
                        });
                    },
                };

                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('start error');
                    done();
                });
                menu.sessionConfig(config);
                menu.run(args);

            });

            it('should emit error when session start handler throws error in promise', function (done) {
                let config = {
                    start: () => {
                        return new Promise(() => {
                            throw new Error('start error');
                        });
                    },
                };

                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('start error');
                    done();
                });
                menu.sessionConfig(config);
                menu.run(args);

            });

            it('should emit error when set handler returns error in callback', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    set: (sessionId, key, val, cb) => {
                        cb(new Error('set error'));
                    },
                };
                menu.sessionConfig(config);
                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('set error');
                    done();
                });

                menu.startState({
                    run: () => {
                        menu.session.set('key', 'value');
                    }
                });
                menu.run(args);

            });

            it('should emit error when set handler returns error in promise', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    set: () => {
                        return new Promise((resolve, reject) => {
                            reject(new Error('set error'));
                        });
                    },
                };
                menu.sessionConfig(config);
                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('set error');
                    done();
                });

                menu.startState({
                    run: () => {
                        menu.session.set('key', 'value');
                    }
                });
                menu.run(args);

            });

            it('should emit error when set handler throws error in promise', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    set: () => {
                        return new Promise(() => {
                            throw new Error('set error');
                        });
                    },
                };
                menu.sessionConfig(config);
                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('set error');
                    done();
                });

                menu.startState({
                    run: () => {
                        menu.session.set('key', 'value');
                    }
                });
                menu.run(args);

            });

            it('should pass error in callback to session.set when set handler passes error to callback', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    set: (id, key, val, cb) => {
                        cb(new Error('set error'));
                    },
                };
                menu.sessionConfig(config);

                menu.startState({
                    run: () => {
                        menu.session.set('key', 'value', err => {
                            expect(err).to.be.an('error');
                            expect(err.message).to.equal('set error');
                            done();
                        });
                    }
                });
                menu.run(args);
            });

            it('should catch error in promise in session.set when set handler passes error to callback', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    set: (id, key, val, cb) => {
                        cb(new Error('set error'));
                    },
                };
                menu.sessionConfig(config);

                menu.startState({
                    run: () => {
                        menu.session.set('key', 'value')
                            .catch(err => {
                                expect(err).to.be.an('error');
                                expect(err.message).to.equal('set error');
                                done();
                            });
                    }
                });
                menu.run(args);
            });

            it('should pass error in callback to session.set when set handler rejects error in promise', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    set: () => {
                        return new Promise((resolve, reject) => {
                            reject(new Error('set error'));
                        });
                    },
                };
                menu.sessionConfig(config);

                menu.startState({
                    run: () => {
                        menu.session.set('key', 'value', err => {
                            expect(err).to.be.an('error');
                            expect(err.message).to.equal('set error');
                            done();
                        });
                    }
                });
                menu.run(args);
            });

            it('should catch error in promise in session.set when set handler rejects error in promise', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    set: () => {
                        return new Promise((resolve, reject) => {
                            reject(new Error('set error'));
                        });
                    },
                };
                menu.sessionConfig(config);

                menu.startState({
                    run: () => {
                        menu.session.set('key', 'value')
                            .catch(err => {
                                expect(err).to.be.an('error');
                                expect(err.message).to.equal('set error');
                                done();
                            });
                    }
                });
                menu.run(args);
            });

            it('should emit error when get handler returns error in callback', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    get: (sessionId, key, cb) => {
                        cb(new Error('set error'));
                    },
                };
                menu.sessionConfig(config);
                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('set error');
                    done();
                });

                menu.startState({
                    run: () => {
                        menu.session.get('key');
                    }
                });
                menu.run(args);

            });

            it('should emit error when get handler returns error in promise', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    get: () => {
                        return new Promise((resolve, reject) => {
                            return reject(new Error('set error'));
                        });
                    },
                };
                menu.sessionConfig(config);
                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('set error');
                    done();
                });

                menu.startState({
                    run: () => {
                        menu.session.get('key');
                    }
                });
                menu.run(args);

            });

            it('should emit error when get handler throws error in promise', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    get: () => {
                        return new Promise(() => {
                            throw new Error('set error');
                        });
                    },
                };
                menu.sessionConfig(config);
                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('set error');
                    done();
                });

                menu.startState({
                    run: () => {
                        menu.session.get('key');
                    }
                });
                menu.run(args);

            });

            it('should pass error in callback to session.get when get handler passes error to callback', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    get: (id, key, cb) => {
                        cb(new Error('get error'));
                    },
                };
                menu.sessionConfig(config);

                menu.startState({
                    run: () => {
                        menu.session.get('key', err => {
                            expect(err).to.be.an('error');
                            expect(err.message).to.equal('get error');
                            done();
                        });
                    }
                });
                menu.run(args);
            });

            it('should catch error in promise in session.get when get handler passes error to callback', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    get: (id, key, cb) => {
                        cb(new Error('get error'));
                    },
                };
                menu.sessionConfig(config);

                menu.startState({
                    run: () => {
                        menu.session.get('key')
                            .catch(err => {
                                expect(err).to.be.an('error');
                                expect(err.message).to.equal('get error');
                                done();
                            });
                    }
                });
                menu.run(args);
            });

            it('should pass error in callback to session.get when get handler rejects error in promise', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    get: () => {
                        return new Promise((resolve, reject) => {
                            reject(new Error('get error'));
                        });
                    },
                };
                menu.sessionConfig(config);

                menu.startState({
                    run: () => {
                        menu.session.get('key', err => {
                            expect(err).to.be.an('error');
                            expect(err.message).to.equal('get error');
                            done();
                        });
                    }
                });
                menu.run(args);
            });

            it('should catch error in promise in session.get when get handler passes error to callback', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    get: () => {
                        return new Promise((resolve, reject) => {
                            reject(new Error('get error'));
                        });
                    },
                };
                menu.sessionConfig(config);

                menu.startState({
                    run: () => {
                        menu.session.get('key')
                            .catch(err => {
                                expect(err).to.be.an('error');
                                expect(err.message).to.equal('get error');
                                done();
                            });
                    }
                });
                menu.run(args);
            });

            // SESSION END HANDLER

            it('should emit error when session end handler returns error in callback', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    end: (id, cb) => {
                        cb(new Error('end error'));
                    }
                };

                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('end error');
                    done();
                });
                menu.sessionConfig(config);
                menu.startState({
                    run: () => {
                        menu.end();
                    }
                });
                menu.run(args);

            });

            it('should emit error when session end handler returns error in promise', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    end: () => {
                        return new Promise((resolve, reject) => {
                            return reject(new Error('end error'));
                        });
                    }
                };

                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('end error');
                    done();
                });
                menu.sessionConfig(config);
                menu.startState({
                    run: () => {
                        menu.end();
                    }
                });
                menu.run(args);

            });

            it('should emit error when session end handler throws error in promise', function (done) {
                let config = {
                    start: (id, cb) => {
                        cb();
                    },
                    end: () => {
                        return new Promise(() => {
                            throw new Error('end error');
                        });
                    }
                };

                menu.on('error', err => {
                    expect(err).to.be.an('error');
                    expect(err.message).to.equal('end error');
                    done();
                });
                menu.sessionConfig(config);
                menu.startState({
                    run: () => {
                        menu.end();
                    }
                });
                menu.run(args);

            });

        });

    });

    describe('Hubtel Support', function () {
        let menu;
        let session = {};
        let args;

        let config = {
            start: (id) => {
                return new Promise((resolve, reject) => {
                    if (!(id in session)) session[id] = {};
                    return resolve();
                });
            },
            end: (id) => {
                return new Promise((resolve, reject) => {
                    delete session[id];
                    return resolve();
                });
            },
            get: (id, key) => {
                return new Promise((resolve, reject) => {
                    let val = session[id][key];
                    return resolve(val);
                });
            },
            set: (id, key, val) => {
                return new Promise((resolve, reject) => {
                    session[id][key] = val;
                    return resolve();
                });
            }
        };

        beforeEach(function () {
            menu = new UssdMenu({ provider: 'hubtel' });
            session = {};
            args = {
                Mobile: '233208183783',
                SessionId: 'bd7bc392496b4b28af2033ba83f5e400',
                ServiceCode: '713*4',
                Type: 'Response',
                Message: '',
                Operator: 'MTN',
                Sequence: 2
            };
        });

        it('should emit error when invalid provider in menu config', function (done) {
            try {
                menu = new UssdMenu({ provider: 'otherTelco' });
            } catch (err) {
                expect(err).to.be.an('error');
                done();
            }
        });

        it('should emit error when session config not set up', function (done) {
            menu = new UssdMenu({ provider: 'hubtel' });
            menu.startState({
                run: () => {
                    menu.con('Next');
                }
            });
            menu.on('error', err => {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('Session config required for Hubtel provider');
                done();
            });
            menu.run(args);
        });

        it('should emit error if unable to map route', function (done) {
            menu = new UssdMenu({ provider: 'hubtel' });
            args.Message = '1';
            args.Type = 'Initiation';

            let config = {
                start: (id, cb) => {
                    cb();
                },
                get: (id, key) => {
                    return new Promise((resolve, reject) => {
                        let val = session[id][key];
                        return resolve(val);
                    });
                },
                set: (id, key, val) => {
                    return new Promise((resolve, reject) => {
                        if (key === 'route') {
                            return reject('Cannot set route key');
                        } else {
                            session[id][key] = val;
                            return resolve();
                        }
                    });
                },
                end: () => {
                    return new Promise((resolve, reject) => {
                        return reject(new Error('end error'));
                    });
                }
            };

            menu.sessionConfig(config);
            menu.startState({
                run: () => {
                    menu.con('Next');
                },
                next: {
                    '1': 'state1'
                }
            });
            menu.on('error', err => {
                expect(err).to.be.an('error');
                expect(err.message).to.equal('Cannot set route key');
                done();
            });

            menu.run(args);

        });

        it('should map incoming hubtel request to menu.args', function (done) {
            menu.sessionConfig(config);

            args.Message = '1';
            menu.startState({
                next: {
                    '1': 'state1'
                }
            });
            menu.state('state1', {
                run: function (state) {
                    expect(state.menu.args.phoneNumber).to.equal(`+${args.Mobile}`);
                    expect(state.menu.args.sessionId).to.equal(args.SessionId);
                    expect(state.menu.args.serviceCode).to.equal(args.ServiceCode);
                    expect(state.menu.args.text).to.equal(args.Message);
                    expect(state.val).to.equal(args.Message);
                    expect(menu.val).to.equal(args.Message);
                    done();
                }
            });

            menu.run(args);
        });
        it('should override message from Initiation call with empty string if no extra params', function(done) {
            menu.sessionConfig(config);
            const initArgs = Object.assign(args, {
                Sequence: 1,
                Message: '*713*4#',
                Type: 'Initiation',
            });

            menu.startState({
                run: function (state) {
                    expect(menu.val).to.equal('');
                    expect(state.menu.args.text).to.equal('');
                    done();
                }
            });

            menu.run(initArgs);
        });

        it('should map Message from Initiation call to a route if extra params', function(done) {
            menu.sessionConfig(config);
            const initArgs = Object.assign(args, {
                Sequence: 1,
                Message: '*713*4*3*5#',
                Type: 'Initiation',
            });

            menu.startState({
                run: function(state){
                    // Should not reach this function
                    expect(10).to.equal(20);
                },
                next: {
                    '3': 'state1'
                }
            });
            menu.state('state1', {
                run: function(state){
                    // Should not reach this function
                    expect(15).to.equal(5);
                },
                next: {
                    '5': 'state2'
                }
            });

            menu.state('state2', {
                run: function(state){
                    expect(state.menu.args.phoneNumber).to.equal(`+${args.Mobile}`);
                    expect(state.menu.args.sessionId).to.equal(args.SessionId);
                    expect(state.menu.args.serviceCode).to.equal(args.ServiceCode);
                    expect(state.menu.args.text).to.equal('3*5');
                    done();
                },
                next: {
                    // Should not reach here
                    '*\\d+': 'state1'
                }
            });

            menu.run(initArgs);
        });

        it('should return Response object from menu.con', function(done) {
            menu.sessionConfig(config);
            menu.startState({
                run: () => {
                    menu.con('Next');
                },
            });

            menu.run(args, res => {
                expect(res).to.be.an('object');
                expect(res.Message).to.equal('Next');
                expect(res.Type).to.equal('Response');
                done();
            });
        });

        it('should return Release object from menu.end', function (done) {
            menu.sessionConfig(config);
            menu.startState({
                run: () => {
                    menu.end('End');
                },
            });

            menu.run(args, res => {
                expect(res).to.be.an('object');
                expect(res.Message).to.equal('End');
                expect(res.Type).to.equal('Release');
                done();
            });
        });

        it('should be able to map first text to route', function (done) {
            menu.sessionConfig(config);

            const testResponse = 'state1 response';

            menu.startState({
                run: () => {
                    menu.con('Next');
                },
                next: {
                    '1': 'state1'
                }
            });
            menu.state('state1', {
                run: () => {
                    menu.con(testResponse);
                }
            });

            menu.run(args, () => {
                expect(session[args.SessionId].route).to.equal('');
                args.Message = '1';
                menu.run(args, res => {
                    process.nextTick(() => {
                        // expect session to be deleted
                        expect(res.Message).to.equal(testResponse);
                        expect(session[args.SessionId].route).to.equal(args.Message);
                        done();
                    });
                });
            });
        });
        it('should be able to map text after first sequence to route', function (done) {
            menu.sessionConfig(config);

            const initArgs = Object.assign({}, args, {
                Sequence: 1,
                Message: '*713*4#',
                Type: 'Initiation',
            });
            const firstResponseArgs = Object.assign({}, args, {
                Sequence: 2,
                Message: '1',
            });
            const secondResponseArgs = Object.assign({}, args, {
                Sequence: 3,
                Message: '3',
            });

            const testResponse = 'state1 response';
            const test2Response = 'state2 response';

            menu.startState({
                run: () => {
                    menu.con('Next');
                },
                next: {
                    '1': 'state1'
                }
            });
            menu.state('state1', {
                run: () => {
                    menu.con(testResponse);
                },
                next: {
                    '3': 'state2'
                }
            });

            menu.state('state2', {
                run: () => {
                    menu.end(test2Response);
                }
            });

            menu.run(initArgs, initResponse => {
                expect(session[args.SessionId].route).to.equal('');
                expect(initResponse.Message).to.equal('Next');
                expect(initResponse.Type).to.equal('Response');
                menu.run(firstResponseArgs, res => {
                    // expect session to be deleted
                    expect(res.Message).to.equal(testResponse);
                    expect(res.Type).to.equal('Response');
                    menu.run(secondResponseArgs, res2 => {
                        expect(res2.Message).to.equal(test2Response);
                        expect(res2.Type).to.equal('Release');
                        expect(session[args.SessionId].route).to.equal('1*3');
                        done();
                    });
                });
            });
        });

    });
    describe("Menu Run Returns Promise", function () {
        it('menu.run should return a resolvable promise', function (done) {
            let message = 'It works!';
            menu.startState({
                run: function () {
                    menu.end(message);
                }
            });
            menu.run(args).then(function (res) {
                expect(res).to.equal('END ' + message);
                done();
            });
        });

    });

});


text:
import React, { Component } from 'react';
import PropTypes from 'prop-types';

class FinancialReport extends Component {
  render() {
    return (

{this.props.name}

    );
  }
}

FinancialReport.propTypes = {
  name: PropTypes.string.isRequired,
  url: PropTypes.string.isRequired,
};

export default FinancialReport;

redpajama_set_name: RedPajamaGithub


text:
package it.elasticsearch.models;

import static org.fest.assertions.Assertions.assertThat;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import org.junit.Test;

public class ComputedHappinessTest {

	private double score = 7.;
	private double relevance = 1.;

	@Test
	public void shouldToStringProduceNicePrint() {
		// given
		Map<String, Object> inputMap = new HashMap<String, Object>();
		inputMap.put(ComputedHappiness.SCORE_KEY, score);
		inputMap.put(ComputedHappiness.RELEVANCE_KEY, relevance);

		// when
		ComputedHappiness happiness = new ComputedHappiness(score, relevance);

		// then
		assertThat(happiness.toString()).isEqualTo(inputMap.toString());
	}

	@Test
	public void shouldToMapReturnValidMap() throws IOException {
		// given
		Map<String, Object> expectedMap = new HashMap<String, Object>();
		expectedMap.put(ComputedHappiness.SCORE_KEY, score);
		expectedMap.put(ComputedHappiness.RELEVANCE_KEY, relevance);

		ComputedHappiness happiness = new ComputedHappiness(score, relevance);

		// when
		Map<String, Object> map = happiness.toMap();

		// then
		assertThat(map).isNotNull();
		assertThat(map).isEqualTo(expectedMap);
	}

	@Test
	public void shouldToMapReturnValidMapForGeolocalized() throws IOException {
		// given
		double lat = 40.75;
		double lng = -74.0;

		Map<String, Object> expectedMap = new HashMap<String, Object>();
		expectedMap.put(ComputedHappiness.SCORE_KEY, score);
		expectedMap.put(ComputedHappiness.RELEVANCE_KEY, relevance);
		expectedMap.put(ComputedHappiness.LATITUDE_KEY, lat);
		expectedMap.put(ComputedHappiness.LONGITUDE_KEY, lng);

		ComputedHappiness happiness = new ComputedHappiness(score, relevance, lat, lng);

		// when
		Map<String, Object> map = happiness.toMap();

		// then
		assertThat(map).isNotNull();
		assertThat(map).isEqualTo(expectedMap);
	}

	@Test
	public void shouldToMapReturnValidMapForGeolocalizedWithState() throws IOException {
		// given
		double lat = 40.75;
		double lng = -74.0;
		String stateId = "NY";
		String stateName = "New York";

		Map<String, Object> expectedState = new HashMap<String, Object>();
		expectedState.put(USAState.STATEID_KEY, stateId);
		expectedState.put(USAState.STATENAME_KEY, stateName);

		Map<String, Object> expectedMap = new HashMap<String, Object>();
		expectedMap.put(ComputedHappiness.SCORE_KEY, score);
		expectedMap.put(ComputedHappiness.RELEVANCE_KEY, relevance);
		expectedMap.put(ComputedHappiness.LATITUDE_KEY, lat);
		expectedMap.put(ComputedHappiness.LONGITUDE_KEY, lng);
		expectedMap.put(ComputedHappiness.STATE_KEY, expectedState);

		USAState state = new USAState(stateId, stateName);
		ComputedHappiness happiness = new ComputedHappiness(score, relevance, lat, lng);
		happiness.setState(state);

		// when
		Map<String, Object> map = happiness.toMap();

		// then
		assertThat(map).isNotNull();
		assertThat(map).isEqualTo(expectedMap);
	}
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/run/v2/job.proto

package com.google.cloud.run.v2;

public interface ExecutionReferenceOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.run.v2.ExecutionReference)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Name of the execution.
   *

   *
   * string name = 1 [(.google.api.resource_reference) = { ... }
   *
   * @return The name.
   */
  java.lang.String getName();
  /**
   *
   *
   *

   * Name of the execution.
   *

   *
   * string name = 1 [(.google.api.resource_reference) = { ... }
   *
   * @return The bytes for name.
   */
  com.google.protobuf.ByteString getNameBytes();

  /**
   *
   *
   *

   * Creation timestamp of the execution.
   *

   *
   * .google.protobuf.Timestamp create_time = 2;
   *
   * @return Whether the createTime field is set.
   */
  boolean hasCreateTime();
  /**
   *
   *
   *

   * Creation timestamp of the execution.
   *

   *
   * .google.protobuf.Timestamp create_time = 2;
   *
   * @return The createTime.
   */
  com.google.protobuf.Timestamp getCreateTime();
  /**
   *
   *
   *

   * Creation timestamp of the execution.
   *

   *
   * .google.protobuf.Timestamp create_time = 2;
   */
  com.google.protobuf.TimestampOrBuilder getCreateTimeOrBuilder();

  /**
   *
   *
   *

   * Creation timestamp of the execution.
   *

   *
   * .google.protobuf.Timestamp completion_time = 3;
   *
   * @return Whether the completionTime field is set.
   */
  boolean hasCompletionTime();
  /**
   *
   *
   *

   * Creation timestamp of the execution.
   *

   *
   * .google.protobuf.Timestamp completion_time = 3;
   *
   * @return The completionTime.
   */
  com.google.protobuf.Timestamp getCompletionTime();
  /**
   *
   *
   *

   * Creation timestamp of the execution.
   *

   *
   * .google.protobuf.Timestamp completion_time = 3;
   */
  com.google.protobuf.TimestampOrBuilder getCompletionTimeOrBuilder();
}


text:
package main

import (
	//for extracting service credentials from VCAP_SERVICES
	//"github.com/cloudfoundry-community/go-cfenv"

	"github.com/HouzuoGuo/tiedot/db"
	"github.com/amsokol/kendo-ui-echo-samples/api/persistence"
	"github.com/amsokol/kendo-ui-echo-samples/api/rest"
	"github.com/amsokol/kendo-ui-echo-samples/fakedata"
	"github.com/labstack/echo"
	mw "github.com/labstack/echo/middleware"
	"github.com/tylerb/graceful"
	"log"
	"os"
	"time"
)

const (
	DEFAULT_PORT = "8080"
	DEFAULT_HOST = "localhost"
)

func main() {
	var port string
	if port = os.Getenv("VCAP_APP_PORT"); len(port) == 0 {
		port = DEFAULT_PORT
	}

	var host string
	if host = os.Getenv("VCAP_APP_HOST"); len(host) == 0 {
		host = DEFAULT_HOST
	}

	// prepare folder for DB with sample data
	dir := "./.fakedata-db"
	os.RemoveAll(dir)
	defer os.RemoveAll(dir)

	var tiedot *db.DB
	var err error

	// init sample data
	if tiedot, err = db.OpenDB(dir); err != nil {
		log.Panic(err)
	}
	defer tiedot.Close()

	// init sample data
	if err = fakedata.AddData(tiedot); err != nil {
		log.Panic(err)
	}

	// init persistence stores
	rest.SetProductStore(data.GetProductStore(tiedot))

	// Echo instance
	e := echo.New()

	// Static test web pages
	e.Static("/", "website")
	e.Index("website/index.html")

	// Customization
	e.SetDebug(true)

	// Middleware
	e.Use(mw.Logger())
	e.Use(mw.Recover())

	// Routes
	routes(e)

	s := e.Server(host + ":" + port)

	// HTTP2 is currently enabled by default in echo.New(). To override TLS handshake errors
	// you will need to override the TLSConfig for the server so it does not attempt to validate
	// the connection using TLS as required by HTTP2
	s.TLSConfig = nil

	// Start server
	log.Printf("Starting app on %+v:%+v\n", host, port)
	graceful.ListenAndServe(s, 5*time.Second)
}

func routes(e *echo.Echo) {
	e.Get("/products", rest.GetProducts)
}


text:
<?php

/**
 * core
 *
 * @version 1.0
 * @package Flow
 *
 */

namespace Core\Flow;

use Core\Flow\Exception\FlowException;

/**
 * Flow project config
 *
 *
 */
class Project extends \Core\Frame\Abstracts\Base
{

    public $model;

    public function __construct($id = null) {
        if(is_null($id)){
            return;
        }
        $this->model = Models\Project::find($id);
        if(!$this->model){
            throw new FlowException("流程项目id有误");
        }
        parent::__construct();
    }

    /**
     * create a new flow
     */
    public function create(){
        $flow = new Flow();
        $flow->create($this)->addAcceptedUser($this->user_id);
        return $flow;
    }
}


text:
package scalabpe.plugin

import scala.xml.Node

import scalabpe.core.Closable
import scalabpe.core.Logging
import scalabpe.core.RegDisHook
import scalabpe.core.Router

class RegDisHookSample(val router: Router, val cfgNode: Node) extends Logging with RegDisHook with Closable {

    log.info("regdis hook created")

    def updateXml(xml: String): String = {
        log.info("updateXml called")
        xml
    }

    def close(): Unit = {
        log.info("regdis hook closed")
    }
}


text:
package org.gridsphere.layout;

import org.gridsphere.layout.event.PortletComponentEvent;
import org.gridsphere.layout.event.PortletTabEvent;
import org.gridsphere.layout.event.PortletTabListener;
import org.gridsphere.portletcontainer.GridSphereEvent;
import org.gridsphere.services.core.persistence.PersistenceManagerException;

import javax.portlet.PortletRequest;
import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

/**
 * The PortletTabbedPane represents the visual portlet tabbed pane interface
 * and is a container for a {@link org.gridsphere.layout.PortletTab}.
 */
public abstract class PortletNavMenu extends BasePortletComponent implements Serializable, PortletTabListener, Cloneable {

    private List<PortletTab> tabs = new ArrayList<PortletTab>();

    private String layoutDescriptor = null;

    //private transient TabbedPaneView tabbedPaneView = null;

    /**
     * Constructs an instance of PortletTabbedPane
     */
    public PortletNavMenu() {
    }

    public void setLayoutDescriptor(String layoutDescriptor) {
        this.layoutDescriptor = layoutDescriptor;
    }

    public String getLayoutDescriptor() {
        return layoutDescriptor;
    }

    /**
     * Returns the selected tab if none exists, return null
     *
     * @return the selected portlet tab
     */
    public PortletTab getSelectedTab() {
        for (int i = 0; i < tabs.size(); i++) {
            PortletTab tab = (PortletTab) tabs.get(i);
            if (tab.isSelected()) {
                return tab;
            }
        }
        return null;
    }

    /**
     * Returns the index of the supplied tab or -1 if not found
     *
     * @param tab the tab to get the index of
     * @return the index of the supplied tab
     */
    public int getIndexOfTab(PortletTab tab) {
        for (int i = 0; i < tabs.size(); i++) {
            PortletTab atab = (PortletTab) tabs.get(i);
            if (tab.equals(atab)) return i;
        }
        return -1;
    }

    /**
     * Sets the selected portlet tab in this tabbed pane
     *
     * @param tab the selected portlet tab
     */
    public void setSelectedPortletTab(PortletTab tab) {
        PortletTab portletTab;
        for (int i = 0; i < tabs.size(); i++) {
            portletTab = (PortletTab) tabs.get(i);
            if (portletTab.getComponentID() == tab.getComponentID()) {
                //System.err.println("set tab=" + portletTab.toString());
                portletTab.setSelected(true);
            } else {
                portletTab.setSelected(false);
            }
        }
    }

    /**
     * Sets the selected portlet tab in this tabbed pane
     *
     * @param index tab the selected portlet tab index
     */
    public void setSelectedPortletTabIndex(int index) {
        PortletTab portletTab;
        for (int i = 0; i < tabs.size(); i++) {
            portletTab = (PortletTab) tabs.get(i);
            if (index == i) {
                portletTab.setSelected(true);
            } else {
                portletTab.setSelected(false);
            }
        }
    }

    /**
     * Returns the tab with the supplied title
     *
     * @param label the tab label
     * @return the tab associated with this title
     */
    public PortletTab getPortletTab(String label) {
        for (PortletTab tab : tabs) {
            if (tab.getLabel().equals(label)) return tab;
        }
        return null;
    }

    /**
     * Return the tab contained by this tabbed pane by index
     *
     * @param index the tab index
     * @return the portlet tab
     */
    public PortletTab getPortletTabAt(int index) {
        if (index >= tabs.size()) return null;
        return (PortletTab) tabs.get(index);
    }

    public int getTabCount() {
        return tabs.size();
    }

    public void insertTab(PortletTab tab, int index) {
        if ((index >= 0) || index < tabs.size()) tabs.add(index, tab);
    }

    /**
     * Adds a new portlet tab to the tabbed pane
     *
     * @param tab a portlet tab to add
     */
    public void addTab(PortletTab tab) {
        tabs.add(tab);
    }

    /**
     * Removes a portlet tab from the tabbed pane
     *
     * @param tab the portlet tab to remove
     */
    public void removeTab(PortletTab tab) {
        for (int i = 0; i < tabs.size(); i++) {
            PortletTab atab = tabs.get(i);
            if (atab.getComponentID() == tab.getComponentID()) {
                tabs.remove(atab);
                i = tabs.size();
            }
        }
    }

    /**
     * Removes a portlet tab from the tabbed pane at the specified index
     *
     * @param index the index of the tab to remove
     */
    public synchronized void removeTabAt(int index) {
        tabs.remove(index);
    }

    /**
     * Removes all portlet tabs from the tabbed pane
     */
    public synchronized void removeAll() {
        for (int i = 0; i < tabs.size(); i++) {
            tabs.remove(i);
        }
    }

    /**
     * Sets the portlet tabs in the tabbed pane
     *
     * @param tabs an ArrayList containing the portlet tabs to add
     */
    public void setPortletTabs(List<PortletTab> tabs) {
        this.tabs = tabs;

    }

    /**
     * Returns a list containing the portlet tabs
     *
     * @return a list containing the portlet tabs
     */
    public List<PortletTab> getPortletTabs() {
        return tabs;
    }

    public PortletTab getLastPortletTab() {
        return (PortletTab) tabs.get(tabs.size() - 1);
    }

    /**
     * Initializes the portlet tabbed pane component. Since the components are isolated
     * after Castor unmarshalls from XML, the ordering is determined by a
     * passed in List containing the previous portlet components in the tree.
     *
     * @param list a list of component identifiers
     * @return a list of updated component identifiers
     * @see org.gridsphere.layout.ComponentIdentifier
     */
    public List<ComponentIdentifier> init(PortletRequest req, List<ComponentIdentifier> list) {

        list = super.init(req, list);

        ComponentIdentifier compId = new ComponentIdentifier();
        compId.setPortletComponent(this);
        compId.setComponentID(list.size());
        compId.setComponentLabel(label);
        compId.setClassName(this.getClass().getName());
        list.add(compId);

        for (PortletTab tab : tabs) {
            list = tab.init(req, list);
            tab.addComponentListener(this);
            tab.setParentComponent(this);
        }

        PortletTab tab = this.getSelectedTab();

        if (tab == null) {
            tab = this.getPortletTabAt(0);
            if (tab != null) this.setSelectedPortletTab(tab);
        }

        return list;
    }

    /**
     * Gives notification that a portlet tab event has occured
     *
     * @param event the portlet tab event
     */
    public void handlePortletTabEvent(PortletTabEvent event) {
        if (event.getAction().equals(PortletTabEvent.TabAction.TAB_SELECTED)) {
            PortletTab selectedTab = (PortletTab) event.getPortletComponent();
            this.setSelectedPortletTab(selectedTab);
        }
    }

    /**
     * Gives notification that a portlet tab event has occured
     *
     * @param event the portlet tab event
     */
    public void actionPerformed(GridSphereEvent event) {

        super.actionPerformed(event);

        PortletComponentEvent compEvt = event.getLastRenderEvent();
        if ((compEvt != null) && (compEvt instanceof PortletTabEvent)) {
            PortletTabEvent tabEvent = (PortletTabEvent) compEvt;
            handlePortletTabEvent(tabEvent);
        }

        Iterator it = listeners.iterator();
        PortletComponent comp;

        while (it.hasNext()) {
            comp = (PortletComponent) it.next();
            event.addNewRenderEvent(compEvt);
            comp.actionPerformed(event);
        }

    }

    /**
     * Renders the portlet frame component
     *
     * @param event a gridsphere event
     */
    public abstract void doRender(GridSphereEvent event);

    public void remove(PortletComponent pc) {
        if (pc instanceof PortletTab) {
            tabs.remove((PortletTab) pc);
            if (tabs.isEmpty()) parent.remove(this);
        }
    }

    public void save() throws IOException {
        try {
            PortletLayoutDescriptor.saveLayoutComponent(this, layoutDescriptor, LAYOUT_MAPPING_PATH);
        } catch (PersistenceManagerException e) {
            throw new IOException("Unable to save user's tabbed pane: " + e.getMessage());
        }
    }

    public Object clone() throws CloneNotSupportedException {
        PortletNavMenu t = (PortletNavMenu) super.clone();
        t.style = this.style;
        t.tabs = new ArrayList<PortletTab>(tabs.size());
        for (int i = 0; i < tabs.size(); i++) {
            PortletTab tab = (PortletTab) tabs.get(i);
            t.tabs.add((PortletTab) tab.clone());
        }
        return t;
    }

}


text:
Get Type Basic Information
==========================

.. index::
   single: NumericTraits

Synopsis
--------

Get some basic information about a plain old data (POD) type, in this case the
*float* type.

Results
-------

Output::

  Min: 1.17549e-38
  Max: 3.40282e+38
  Zero: 0
  ZeroValue: 0
  Is -1 negative? 1
  Is 1 negative? 0
  One: 1
  Epsilon: 1.19209e-07
  Infinity: inf
  Good

Code
----

Python
......

.. literalinclude:: Code.py
   :language: python
   :lines: 1, 16-

C++
...

.. literalinclude:: Code.cxx
   :lines: 18-

Classes demonstrated
--------------------

.. breathelink:: itk::NumericTraits


text:
#pragma once

#ifndef GEODE_TSSTXSTATEWRAPPER_H_
#define GEODE_TSSTXSTATEWRAPPER_H_

/*
 * TSSTXStateWrapper.hpp
 *
 *  Created on: 09-Feb-2011
 *      Author: ankurs
 */

#include <ace/TSS_T.h>
#include "TXId.hpp"

namespace apache {
namespace geode {
namespace client {
class TXState;

class TSSTXStateWrapper {
 public:
  TSSTXStateWrapper();
  virtual ~TSSTXStateWrapper();

  static ACE_TSS<TSSTXStateWrapper> s_geodeTSSTXState;
  TXState* getTXState() { return m_txState; }
  void setTXState(TXState* conn) { m_txState = conn; }

 private:
  TXState* m_txState;
  TSSTXStateWrapper& operator=(const TSSTXStateWrapper&);
  TSSTXStateWrapper(const TSSTXStateWrapper&);
};
}  // namespace client
}  // namespace geode
}  // namespace apache

#endif  // GEODE_TSSTXSTATEWRAPPER_H_


text:
package com.fly.firefly.ui.activity.BookingFlight;

import android.app.FragmentManager;
import android.os.Bundle;
import android.util.Log;

import com.fly.firefly.AnalyticsApplication;
import com.fly.firefly.MainFragmentActivity;
import com.fly.firefly.R;
import com.fly.firefly.ui.activity.FragmentContainerActivity;
import com.fly.firefly.ui.fragment.BookingFlight.PaymentFlightFragment;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.Tracker;

import butterknife.ButterKnife;

//import android.view.WindowManager;

public class PaymentFlightActivity extends MainFragmentActivity implements FragmentContainerActivity {

    private Tracker mTracker;
    FragmentManager fragmentManager = getFragmentManager();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.inject(this);
        AnalyticsApplication application = (AnalyticsApplication) getApplication();
        mTracker = application.getDefaultTracker();
        fragmentManager.beginTransaction().add(R.id.main_activity_fragment_container, PaymentFlightFragment.newInstance()).commit();

        hideTitle();
    }

    @Override
    public void onBackPressed() {
        if (fragmentManager.getBackStackEntryCount() > 0) {
            fragmentManager.popBackStack();
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        // presenter.onResume();
        Log.i("Page Name", "Setting screen name: " + "Payment Flight");
        mTracker.setScreenName("Payment Flight" + "A");
        mTracker.send(new HitBuilders.ScreenViewBuilder().build());
    }

    @Override
    public int getFragmentContainerId() {
        return R.id.main_activity_fragment_container;
    }
}


text:
{% if site.owner.gitterroom %}
<script>
  ((window.gitter = {}).chat = {}).options = {
    room: '{{ site.owner.gitterroom }}',
    activationElement: '#sidecar-target',
    showChatByDefault: false
  };
</script>
<script src="https://sidecar.gitter.im/dist/sidecar.v1.js" async defer></script>
{% endif %}


text:
require 'jdbc/postgres'

Jdbc::Postgres.load_driver

# Ruby module to support the load of Snowplow events into PostgreSQL.
module Snowplow
  module StorageLoader
    module PostgresLoader

      # Constants for the load process
      EVENT_FILES = "part-*"
      EVENT_FIELD_SEPARATOR = "	"
      NULL_STRING = ""
      QUOTE_CHAR = "\\x01"
      ESCAPE_CHAR = "\\x02"

      # Loads the Snowplow event files into Postgres.
      #
      # Parameters:
      # +events_dir+:: the directory holding the event files to load
      # +target+:: the configuration options for this target
      # +skip_steps+:: Array of steps to skip
      # +include_steps+:: Array of optional steps to include
      def load_events(events_dir, target, skip_steps, include_steps, snowplow_tracking_enabled)
        puts "Loading Snowplow events into #{target[:name]} (PostgreSQL database)..."

        event_files = get_event_files(events_dir)
        status = copy_via_stdin(target, event_files)

        unless status == []
          error_message = "#{status[1]} error loading #{status[0]}: #{status[2]}"
          if snowplow_tracking_enabled
            Monitoring::Snowplow.instance.track_load_failed(error_message)
          end
          raise DatabaseLoadError, error_message
        end

        if snowplow_tracking_enabled
          Monitoring::Snowplow.instance.track_load_succeeded()
        end

        post_processing = nil
        unless skip_steps.include?('analyze')
          post_processing = "ANALYZE "
        end
        if include_steps.include?('vacuum')
          post_processing = "VACUUM " + (post_processing || "")
        end

        unless post_processing.nil?
          status = execute_queries(target, [ "#{post_processing}#{target[:table]};" ] )
          unless status == []
            raise DatabaseLoadError, "#{status[1]} error executing #{status[0]}: #{status[2]}"
          end
        end
      end
      module_function :load_events

      # Adapted from:  https://bitbucket.org/ged/ruby-pg/raw/9812218e0654caa58f8604838bc368434f7b3828/sample/copyfrom.rb
      #
      # Execute a series of copies from stdin by streaming the given files
      # directly into the postgres copy statement.  Stops as soon as an error
      # is encountered.  At that point, it returns a 'tuple' of the error class
      # and message and the file that caused the error.
      #
      # Parameters:
      # +target+:: the configuration options for this target
      # +files+:: the data files to copy into the database
      def copy_via_stdin(target, files)
        puts "Opening database connection ..."

        conn = get_connection(target)

        conn.setAutoCommit(false)

        copy_statement = "COPY #{target[:table]} FROM STDIN WITH CSV ESCAPE E'#{ESCAPE_CHAR}' QUOTE E'#{QUOTE_CHAR}' DELIMITER '#{EVENT_FIELD_SEPARATOR}' NULL '#{NULL_STRING}'"

        status = []

        files.each do |file|
          puts "Running COPY command with data from: #{file}"
          begin
            copy_manager = org.postgresql.copy.CopyManager.new(conn)
            file_reader = java.io.FileReader.new(file)
            copy_manager.copyIn(copy_statement, file_reader)
          rescue Java::JavaSql::SQLException, Java::JavaSql::SQLTimeoutException => err
            status = [file, err.class, err.message]
            break
          end
        end

        if status == []
          conn.commit()
        else
          conn.rollback()
        end

        conn.close()

        return status
      end
      module_function :copy_via_stdin

      # Converts a set of queries into a
      # single Redshift read-write
      # transaction.
      #
      # Parameters:
      # +target+:: the configuration options for this target
      # +queries+:: the Redshift queries to execute sequentially
      #
      # Returns either an empty list on success, or on failure
      # a list of the form [query, err_class, err_message]
      def execute_transaction(target, queries)

        transaction = (
          [ "BEGIN;" ] +

          queries +

          [ "COMMIT;" ]
        ).join("\n")

        execute_queries(target, [ transaction ])
      end
      module_function :execute_transaction

      # Execute a chain of SQL commands, stopping as soon as
      # an error is encountered. At that point, it returns a
      # 'tuple' of the error class and message and the command
      # that caused the error
      #
      # Parameters:
      # +target+:: the configuration options for this target
      # +queries+:: the Redshift queries to execute sequentially
      #
      # Returns either an empty list on success, or on failure
      # a list of the form [query, err_class, err_message]
      def execute_queries(target, queries)

        conn = get_connection(target)

        status = []
        queries.each do |q|
          begin
            conn.createStatement.executeUpdate(q)
          rescue Java::JavaSql::SQLException, Java::JavaSql::SQLTimeoutException => err
            status = [q, err.class, err.message]
            break
          end
        end

        conn.close()
        return status
      end
      module_function :execute_queries

      # Get a java.sql.Connection to a database
      def self.get_connection(target)
        connection_url = "jdbc:postgresql://#{target[:host]}:#{target[:port]}/#{target[:database]}"

        props = java.util.Properties.new
        props.set_property :user, target[:username]
        props.set_property :password, target[:password]
        props.set_property :sslmode, target.fetch(:ssl_mode, "disable")
        props.set_property :tcpKeepAlive, "true" # TODO: make this configurable if any adverse effects

        # Used instead of Java::JavaSql::DriverManager.getConnection to prevent "no suitable driver found" error
        org.postgresql.Driver.new.connect(connection_url, props)
      end

      private

      # Return the list of event files.
      #
      # Parameters:
      # +events_dir+:: the directory holding the event files to load
      #
      # Returns the array of cold files
      def get_event_files(events_dir)

        Dir[File.join(events_dir, '**', 'atomic-events', EVENT_FILES)].select { |f|
          File.file?(f) # In case of a dir ending in .tsv
        }
      end
      module_function :get_event_files

    end
  end
end


text:
'use strict'

var regex = /(\d+)/

/**
 * @param {String} a networkinterface name
 * @param {String} b networkinterface name
 * @returns {Number} ordering
 */
function networkinterfaceCompare(a, b) {
  var less = -1
  var greater = 1
  var equal = 0

  var aStrings = a.split(regex)
  var bStrings = b.split(regex)

  while (aStrings.length && bStrings.length) {
    var aString = aStrings.shift()
    var bString = bStrings.shift()

    var aNum = parseInt(aString, 10)
    var bNum = parseInt(bString, 10)

    // do a numeric comparison if both values are numbers
    if (!isNaN(aNum) && !isNaN(bNum)) {
      if (aNum < bNum) {
        return less
      } else if (aNum > bNum) {
        return greater
      }
    // otherwise fallback to an alphabetic comparison
    } else {
      if (aString < bString) {
        return less
      } else if (aString > bString) {
        return greater
      }
    }
  }

  return equal
}

module.exports = networkinterfaceCompare


text:
@implementation XHCFTitleButton

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        self.titleLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:16];
        [self setTitleColor:kColor3333 forState:UIControlStateNormal];
        [self setTitleColor:kColorfefe forState:UIControlStateSelected];
        [self setBackgroundImage:[self imageWithColor:kColor5622] forState:UIControlStateSelected];
    }
    return self;
}

- (void)setHighlighted:(BOOL)highlighted
{ // 只要重写了这个方法,按钮就无法进入highlighted状态

}

- (UIImage *)imageWithColor:(UIColor *)color {
    CGRect rect = CGRectMake(0.0f, 0.0f, 1.0f, 1.0f);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();

    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);

    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    return image;
}

@end


text:
  A true Brahmana goes scatheless, though he have killed father and
  mother, and two holy kings, and an eminent man besides. 295


text:
	<link rel="stylesheet" href="css/lib/bootstrap-table/bootstrap-table.min.css">
	<link rel="stylesheet" href="css/lib/bootstrap-table/dragtable.css">
//= template/head-end.html

	//= template/header.html

	//= template/side-menu.html

					Reorder columns

								ID
								Item Name
								Item Price

	//= template/footer.html

//= template/foot.html


text:
package com.emc.vipr.model.sys.healthmonitor;

public class NodeHardwareInfo {
    public static enum NodeHardwareInfoType {
        CPUCOUNT,
        CPUFREQ,
        MEMORY,
        DISK;
    }
}


text:
layout: post
title:  "Hello World"
date:   2017-09-5 13:46:40 +0700
categories: Announcements
tags: Hi
---

Hi, perkenalkan nama saya adalah Pratama Bayu Widagdo. Ini merupakan situs dan blog personal milik saya. Penjelasan singkat mengenai resume dan portfolio saya bisa dilihat di halaman muka situs ini.

Pada kesempatan yang akan datang, blog ini akan dipenuhi perihal tentang desain, teknologi, pengalaman, dan edukasi, terutama yang sedang saya kerjakan. Semoga adanya blog ini dapat memberikan referensi bagi orang lain yang sedang mencari atau mengerjakan hal yang serupa.


text: from pylab import *


text:
<resources>

    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

    <style name="AppTheme.NoActionBar">
        <item name="windowActionBar">false</item>
        <item name="windowNoTitle">true</item>
    </style>

    <style name="AppTheme.AppBarOverlay" parent="ThemeOverlay.AppCompat.Dark.ActionBar" />

    <style name="AppTheme.PopupOverlay" parent="ThemeOverlay.AppCompat.Light" />

    <style name="TitleStyle" parent="TextAppearance.AppCompat.Title">
        <item name="android:textSize">@dimen/text_size_large</item>
        <item name="android:textStyle">bold</item>
    </style>

    <style name="SubTitleStyle" parent="TextAppearance.AppCompat.Subhead">
        <item name="android:textSize">@dimen/text_size_medium</item>
    </style>

</resources>


text:
<?php
/**
 * Notes on the implications of the structure:
 * - States have to be defined before defining grammars
 * - Transitions have to be defined before adding transition listeners
 *
 * @category    Xi
 * @package     Xi_State
 * @author      Eevert Saukkokoski <eevert.saukkokoski@brainalliance.com>
 */
class Xi_State_Machine
{
    /**
     * @var array { name: Xi_State }
     */
    protected $_states = array();

    /**
     * @var false|Xi_State current state
     */
    protected $_state;

    /**
     * @var Xi_Stack
     */
    protected $_stack;

    /**
     * @var Xi_Stack
     */
    protected $_output;

    /**
     * @var string
     */
    protected $_initialState;

    /**
     * @var string
     */
    protected $_input;

    /**
     * @param array valid states, the first of which will be set as initial
     * @return void
     */
    public function __construct(array $states = null)
    {
        if (null === $states) {
            $states = array('init');
        }

        foreach ($states as $state) {
            $this->_states[$state] = new Xi_State($state);
        }
        $this->_initialState = reset($states);
        $this->reset();
    }

    /**
     * Set initial state
     *
     * @param string state
     * @return Xi_State_Machine
     */
    public function setInitialState($state)
    {
        $this->_initialState = $this->getState($state)->getName();
        return $this;
    }

    /**
     * Reset machine: set state to initial state, format stack and input
     *
     * @return Xi_State_Machine
     */
    public function reset()
    {
        $this->_state = $this->getState($this->_initialState);
        $this->_stack = new Xi_Stack;
        $this->_output = new Xi_Stack;
        $this->_input = null;

        return $this;
    }

    /**
     * @return array valid states
     */
    public function getStates()
    {
        return array_keys($this->_states);
    }

    /**
     * Record a grammar for this state machine
     *
     * @return Xi_State_Grammar
     */
    public function record()
    {
        return new Xi_State_Grammar($this);
    }

    /**
     * Set current state
     *
     * @param string state
     * @return Xi_State_Machine
     */
    protected function _setState($state)
    {
        $this->_state = $this->getState($state);
        return $this;
    }

    /**
     * Get state by name or the current one if not specified.
     *
     * @param null|string
     * @return Xi_State
     */
    public function getState($state = null)
    {
        if (null === $state) {
            return $this->_state;
        }
        if (!isset($this->_states[$state])) {
            throw new Xi_State_Machine_Exception(sprintf('Unknown state "%s"', $state));
        }
        return $this->_states[$state];
    }

    /**
     * @return mixed last processed input
     */
    public function getInput()
    {
        return $this->_input;
    }

    /**
     * @return Xi_Stack
     */
    public function getStack()
    {
        return $this->_stack;
    }

    /**
     * @return Xi_Stack
     */
    public function getOutput()
    {
        return $this->_output;
    }

    /**
     * Process input
     *
     * @param mixed input
     * @return false|string result state or false if no transitions applied
     */
    public function process($input)
    {
        $this->_input = $input;
        $currentState = $this->getState();
        if ($transition = $currentState->process($this)) {
            if ($currentState->getName() != $transition->getTargetState()) {
                $currentState->notifyExit($this);
            }

            $newState = $this->_setState($transition->getTargetState())->getState();
            $transition->notify($this);

            if ($currentState->getName() != $newState->getName()) {
                $newState->notifyEntry($this);
            }
            return $this->getState()->getName();
        }
        return false;
    }

    public function halt($message = null)
    {
        throw new Xi_State_Machine_Exception('Input was not accepted' . isset($message) ? ': ' . $message : '');
    }
}


text:
<!DOCTYPE html>

  <title>#9a Textures - wrong circular face</title>
  <link rel="stylesheet" href="main.css" type="text/css" media="all" />

Back to main page

<canvas id="canvas" style="border:none" width="720" height="690"></canvas>


text:
using System;
using System.Collections.Generic;

namespace NUnit.Framework
{
    class ValueSourceAttribute : Attribute
    {
        public ValueSourceAttribute(string name) { }
        public ValueSourceAttribute(Type t, string name) { }
    }

    class TestCaseSourceAttribute : Attribute
    {
        public TestCaseSourceAttribute(string name) { }
        public TestCaseSourceAttribute(Type t, string name) { }
    }

    class TestFixtureAttribute : Attribute
    {
    }

    class TestAttribute : Attribute
    {
    }
}

namespace NUnitTests
{
    using NUnit.Framework;

    class MyTestSources
    {
        IEnumerable<int> Source()
        {
            yield return 1;
        }

        object[] TestCases = { 1 };
    }

    [TestFixture]
    class MyTestSuite
    {
        IEnumerable<int> Source()
        {
            yield return 1;
        }

        object[] TestCases = { 1 };

        [Test]
        public void Test1([ValueSource("Source")] int n)
        {
        }

        [Test]
        public void Test2([ValueSource(typeof(MyTestSources), "Source")] int n)
        {
        }

        [Test, TestCaseSource("TestCases")]
        public void Test3(int n)
        {
        }

        [Test, TestCaseSource(typeof(MyTestSources), "TestCases")]
        public void Test4(int n)
        {
        }

        [Test, TestCaseSource("PropertyTestCases")]
        public void Test5(int n)
        {
        }

        object[] PropertyTestCases { get; set; }
    }
}


text:
#ifndef __CNXK_RTE_FLOW_H__
#define __CNXK_RTE_FLOW_H__

#include <rte_flow_driver.h>
#include <rte_malloc.h>

#include "cnxk_ethdev.h"
#include "roc_api.h"
#include "roc_npc_priv.h"

struct cnxk_rte_flow_term_info {
	uint16_t item_type;
	uint16_t item_size;
};

struct roc_npc_flow *cnxk_flow_create(struct rte_eth_dev *dev,
				      const struct rte_flow_attr *attr,
				      const struct rte_flow_item pattern[],
				      const struct rte_flow_action actions[],
				      struct rte_flow_error *error);
int cnxk_flow_destroy(struct rte_eth_dev *dev, struct roc_npc_flow *flow,
		      struct rte_flow_error *error);

#endif /* __CNXK_RTE_FLOW_H__ */


text:
<ion-navbar *navbar>
    <ion-title>{{titulo}}</ion-title>
    <ion-buttons end>
        <button (click)="salvar()">
        Salvar
    </button>
    </ion-buttons>
</ion-navbar>

<ion-content class="cards-bg rota-create">

    <ion-card class="adv-map">

            <button danger fab fab-right fab-top class="fab-map">
                <ion-icon name='pin'></ion-icon>
            </button>

        <ion-list>
            <ion-item-divider light>Informações da Rota</ion-item-divider>
            <ion-item>
                <ion-label stacked dark style="font-size: 0.875em;">Saída</ion-label>
                <ion-textarea type="text" placeholder="Ex. RIbeirão Preto"></ion-textarea>
            </ion-item>
            <ion-item>
                <ion-label dark style="font-size: 0.875em;">Data</ion-label>
                <ion-datetime displayFormat="DD/MM/YYYY" pickerFormat="DD MMM YYYY" cancelText="Cancelar" doneText="OK"></ion-datetime>
            </ion-item>
            <ion-item>
                <ion-label stacked dark style="font-size: 0.875em;">Chegada</ion-label>
                <ion-textarea type="text" placeholder="Ex. São Carlos"></ion-textarea>
            </ion-item>
            <ion-item>
                <ion-label dark style="font-size: 0.875em;">Data</ion-label>
                <ion-datetime displayFormat="DD/MM/YYYY" pickerFormat="DD MMM YYYY" cancelText="Cancelar" doneText="OK"></ion-datetime>
            </ion-item>
            <ion-item-divider light>Ponto de Interesse</ion-item-divider>
            <ion-item>
                <ion-label dark style="font-size: 0.875em;">Tipo</ion-label>
                <ion-select>
                    <ion-option value="Ponto de Interesse 1">Ponto de Interesse 1</ion-option>
                    <ion-option value="Ponto de Interesse 2">Ponto de Interesse 2</ion-option>
                    <ion-option value="Ponto de Interesse 3">Ponto de Interesse 3</ion-option>
                    <ion-option value="Ponto de Interesse 4">Ponto de Interesse 4</ion-option>
                    <ion-option value="Ponto de Interesse 5">Ponto de Interesse 5</ion-option>
                </ion-select>
            </ion-item>
            <ion-item>
                <ion-label stacked dark style="font-size: 0.875em;">Descrição</ion-label>
                <ion-textarea type="text" placeholder="Ex. Restaurante Tempero Maneiro"></ion-textarea>
            </ion-item>
            <ion-item>
                <ion-label stacked dark style="font-size: 0.875em;">Observação</ion-label>
                <ion-textarea type="text" placeholder="Ex. Encontro com amigos da faculdade"></ion-textarea>
            </ion-item>
            <ion-item-divider light>Meio de Transporte</ion-item-divider>
            <ion-item>
                <ion-label dark style="font-size: 0.875em;">Tipo de Transporte</ion-label>
                <ion-select>
                    <ion-option value="Meio de Transporte 1">Meio de Transporte 1</ion-option>
                    <ion-option value="Meio de Transporte 2">Meio de Transporte 2</ion-option>
                    <ion-option value="Meio de Transporte 3">Meio de Transporte 3</ion-option>
                    <ion-option value="Meio de Transporte 4">Meio de Transporte 4</ion-option>
                    <ion-option value="Meio de Transporte 5">Meio de Transporte 5</ion-option>
                </ion-select>
            </ion-item>
            <ion-item>
                <ion-label stacked dark style="font-size: 0.875em;">Descrição</ion-label>
                <ion-textarea type="text" placeholder="Ex. Restaurante Tempero Maneiro"></ion-textarea>
            </ion-item>
        </ion-list>
    </ion-card>

</ion-content>


text:
namespace _05.JSet
{
    using System;
    using System.Collections.Generic;
    using _04.JHashTable;

    /// <summary>
    /// A new shiny set of elements
    /// </summary>
    /// <typeparam name="T">The type of elements in the JSet</typeparam>
    public class JSet<T> : IEnumerable<T>
    {
        private JHashTable<int, T> elements;

        /// <summary>
        /// Empty Constructor that initializes the JSet
        /// </summary>
        public JSet()
        {
            this.elements = new JHashTable<int, T>();
        }

        /// <summary>
        /// Add a new <typeparamref name="T"/> element to the JSet
        /// </summary>
        /// <param name="element">The element to add to the JSet</param>
        public void Add(T element)
        {
            this.elements.Add(element.GetHashCode(), element);
        }

        /// <summary>
        /// Removes a <typeparamref name="T"/> element from the JSet
        /// </summary>
        /// <param name="element">The element to remove from the JSet</param>
        public void Remove(T element)
        {
            this.elements.Remove(element.GetHashCode());
        }

        /// <summary>
        /// Finds a <typeparamref name="T"/> value by givven <typeparamref name="K"/> key
        /// </summary>
        /// <param name="element">The element to search for</param>
        /// <returns><typeparamref name="T"/> value or default</returns>
        public T Find(T element)
        {
            T returnedElement;
            if(this.elements.Find(element.GetHashCode(), out returnedElement))
            {
                return returnedElement;
            }

            return default(T);
        }

        /// <summary>
        /// The number of elements in the JSet
        /// </summary>
        /// <returns><typeparamref name="int"/>The total elements in the JSet</returns>
        public int Count
        {
            get
            {
                return this.elements.Count;
            }
        }

        /// <summary>
        /// Cleares all the elements from the JSet
        /// </summary>
        public void Clear()
        {
            this.elements.Clear();
        }

        /// <summary>
        /// Produces a JSet of <typeparamref name="T"/> values intersected with another JSet <typeparamref name="K"/> key
        /// </summary>
        /// <param name="other">The other JSet to intersect with</param>
        /// <returns><typeparamref name="JSet<T>"/></returns>
        public JSet<T> Intersect(JSet<T> other)
        {
            JSet<T> newSet = new JSet<T>();

            foreach (var element in this)
            {
                foreach (var otherElement in other)
                {
                    if (element.Equals(otherElement))
                    {
                        newSet.Add(element);
                    }
                }
            }

            return newSet;
        }

        /// <summary>
        /// Produces a JSet of <typeparamref name="T"/> values united with another JSet <typeparamref name="K"/> key
        /// </summary>
        /// <param name="other">The other JSet to union with</param>
        /// <returns><typeparamref name="JSet<T>"/></returns>
        public JSet<T> Union(JSet<T> other)
        {
            JSet<T> newSet = new JSet<T>();

            foreach (var element in this)
            {
                newSet.Add(element);
            }

            foreach (var element in other)
            {
                newSet.Add(element);
            }

            return newSet;
        }

        public IEnumerator<T> GetEnumerator()
        {
            foreach (var pair in this.elements)
            {
                yield return pair.Value;
            }
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return this.GetEnumerator();
        }

        public override string ToString()
        {
            return string.Join(", ", this);
        }
    }
}


text:
package com.annimon.stream.function;

/**
 * Represents a function which produces result from {@code long}-valued input argument.
 *
 * @param <R> the type of the result of the function
 * @param <E> the type of the exception
 *
 * @since 1.1.7
 * @see LongFunction
 */
public interface ThrowableLongFunction<R, E extends Throwable> {

    /**
     * Applies this function to the given argument.
     *
     * @param value  the function argument
     * @return the function result
     * @throws E an exception
     */
    R apply(long value) throws E;
}