text:
'use strict';
const expect = require('chai').expect;
const sinon = require('sinon');
const proxyquire = require('proxyquire').noCallThru();
const configStub = require('../../utils/config-stub');
const setupEnv = require('../../utils/env');
const Promise = require('bluebird');
const path = require('path');
const fs = require('fs-extra');

const modulePath = '../../../lib/commands/update';
const errors = require('../../../lib/errors');
const Instance = require('../../../lib/instance');

describe('Unit: Commands > Update', function () {
    describe('run', function () {
        it('doesn\'t run tasks if no new versions are available', function () {
            const UpdateCommand = require(modulePath);
            const config = configStub();
            config.get.withArgs('cli-version').returns('1.0.0-beta.1');
            config.get.withArgs('active-version').returns('1.0.0');
            const ui = {log: sinon.stub(), listr: sinon.stub(), run: sinon.stub()};
            const system = {getInstance: sinon.stub()};
            ui.run.callsFake(fn => fn());

            class TestInstance extends Instance {
                get cliConfig() { return config; }
            }
            const fakeInstance = sinon.stub(new TestInstance(ui, system, '/var/www/ghost'));
            system.getInstance.returns(fakeInstance);
            fakeInstance.running.returns(true);
            const cmdInstance = new UpdateCommand(ui, system);
            const versionStub = sinon.stub(cmdInstance, 'version').resolves(false);

            return cmdInstance.run({version: '1.0.0', force: false, zip: ''}).then(() => {
                expect(ui.run.calledOnce).to.be.true;
                expect(versionStub.calledOnce).to.be.true;
                expect(versionStub.args[0][0]).to.deep.equal({
                    version: '1.0.0',
                    force: false,
                    instance: fakeInstance,
                    activeVersion: '1.0.0',
                    zip: ''
                });
                expect(ui.log.calledTwice).to.be.true;
                expect(ui.log.args[0][0]).to.match(/install is using out\-of\-date configuration/);
                expect(ui.log.args[1][0]).to.match(/up to date/);
                expect(ui.listr.called).to.be.false;
                expect(fakeInstance.running.calledOnce).to.be.true;
                expect(fakeInstance.loadRunningEnvironment.calledOnce).to.be.true;
                expect(fakeInstance.checkEnvironment.calledOnce).to.be.true;
            });
        });

        it('rejects if rollback is passed and no previous version exists', function () {
            const UpdateCommand = require(modulePath);
            const config = configStub();
            config.get.withArgs('cli-version').returns('1.0.0');
            config.get.withArgs('active-version').returns('1.0.0');
            config.get.withArgs('previous-version').returns(null);
            const ui = {log: sinon.stub(), listr: sinon.stub(), run: sinon.stub()};
            const system = {getInstance: sinon.stub()};
            ui.run.callsFake(fn => fn());

            class TestInstance extends Instance {
                get cliConfig() { return config; }
            }
            const fakeInstance = sinon.stub(new TestInstance(ui, system, '/var/www/ghost'));
            system.getInstance.returns(fakeInstance);
            fakeInstance.running.returns(true);
            const cmdInstance = new UpdateCommand(ui, system);
            const versionStub = sinon.stub(cmdInstance, 'version').resolves(false);

            return cmdInstance.run({rollback: true}).then(() => {
                expect(false, 'error should have been thrown').to.be.true;
            }).catch((error) => {
                expect(error).to.be.an.instanceof(Error);
                expect(error.message).to.equal('No previous version found');
                expect(ui.run.called).to.be.false;
                expect(versionStub.called).to.be.false;
                expect(ui.log.called).to.be.false;
                expect(ui.listr.called).to.be.false;
            });
        });

        it('populates context with correct data if rollback is passed and previous version exists', function () {
            const UpdateCommand = require(modulePath);
            const config = configStub();
            config.get.withArgs('cli-version').returns('1.0.0');
            config.get.withArgs('active-version').returns('1.1.0');
            config.get.withArgs('previous-version').returns('1.0.0');
            const ui = {log: sinon.stub(), listr: sinon.stub(), run: sinon.stub()};
            const system = {getInstance: sinon.stub()};
            ui.run.callsFake(fn => fn());

            class TestInstance extends Instance {
                get cliConfig() { return config; }
            }
            const fakeInstance = sinon.stub(new TestInstance(ui, system, '/var/www/ghost'));
            system.getInstance.returns(fakeInstance);
            fakeInstance.running.returns(false);
            const cmdInstance = new UpdateCommand(ui, system);
            const versionStub = sinon.stub(cmdInstance, 'version').resolves(false);
            const cwdStub = sinon.stub(process, 'cwd').returns(fakeInstance.dir);

            return cmdInstance.run({rollback: true, force: false, zip: ''}).then(() => {
                cwdStub.restore();

                expect(ui.run.calledOnce).to.be.true;
                expect(versionStub.calledOnce).to.be.true;
                expect(versionStub.args[0][0]).to.deep.equal({
                    version: '1.0.0',
                    force: false,
                    instance: fakeInstance,
                    activeVersion: '1.1.0',
                    installPath: '/var/www/ghost/versions/1.0.0',
                    rollback: true,
                    zip: ''
                });
                expect(ui.log.calledOnce).to.be.true;
                expect(ui.log.args[0][0]).to.match(/up to date/);
                expect(ui.listr.called).to.be.false;
                expect(fakeInstance.running.calledOnce).to.be.true;
                expect(fakeInstance.loadRunningEnvironment.called).to.be.false;
                expect(fakeInstance.checkEnvironment.calledOnce).to.be.true;
            });
        });

        it('runs all tasks if rollback is false and running is true', function () {
            const migrateStub = sinon.stub().resolves();
            const UpdateCommand = proxyquire(modulePath, {
                '../tasks/migrate': migrateStub
            });
            const config = configStub();
            config.get.withArgs('cli-version').returns('1.0.0');
            config.get.withArgs('active-version').returns('1.0.0');
            const ui = {log: sinon.stub(), listr: sinon.stub(), run: sinon.stub()};
            const system = {getInstance: sinon.stub()};
            ui.run.callsFake(fn => fn());
            ui.listr.callsFake((tasks, ctx) => {
                return Promise.each(tasks, (task) => {
                    if (task.skip && task.skip(ctx)) {
                        return;
                    }

                    return task.task(ctx);
                });
            });

            class TestInstance extends Instance {
                get cliConfig() { return config; }
            }
            const fakeInstance = sinon.stub(new TestInstance(ui, system, '/var/www/ghost'));
            system.getInstance.returns(fakeInstance);
            fakeInstance.running.returns(true);
            const cmdInstance = new UpdateCommand(ui, system);
            const versionStub = sinon.stub(cmdInstance, 'version').resolves(true);
            const stopStub = sinon.stub(cmdInstance, 'stop').resolves();
            const restartStub = sinon.stub(cmdInstance, 'restart').resolves();
            const linkStub = sinon.stub(cmdInstance, 'link').resolves();
            const cwdStub = sinon.stub(process, 'cwd').returns(fakeInstance.dir);
            const downloadStub = sinon.stub(cmdInstance, 'downloadAndUpdate');
            const removeOldVersionsStub = sinon.stub(cmdInstance, 'removeOldVersions');

            return cmdInstance.run({version: '1.1.0', rollback: false, force: false}).then(() => {
                cwdStub.restore();

                expect(ui.run.calledOnce).to.be.true;
                expect(versionStub.calledOnce).to.be.true;
                expect(ui.log.called).to.be.false;
                expect(ui.listr.called).to.be.true;

                expect(downloadStub.calledOnce).to.be.true;
                expect(stopStub.calledOnce).to.be.true;
                expect(linkStub.calledOnce).to.be.true;
                expect(migrateStub.calledOnce).to.be.true;
                expect(restartStub.calledOnce).to.be.true;
                expect(removeOldVersionsStub.calledOnce).to.be.true;
            });
        })

        it('skips download, migrate, and removeOldVersion tasks if rollback is true', function () {
            const migrateStub = sinon.stub().resolves();
            const UpdateCommand = proxyquire(modulePath, {
                '../tasks/migrate': migrateStub
            });
            const config = configStub();
            config.get.withArgs('cli-version').returns('1.0.0');
            config.get.withArgs('active-version').returns('1.1.0');
            config.get.withArgs('previous-version').returns('1.0.0');
            const ui = {log: sinon.stub(), listr: sinon.stub(), run: sinon.stub()};
            const system = {getInstance: sinon.stub()};
            ui.run.callsFake(fn => fn());
            ui.listr.callsFake((tasks, ctx) => {
                return Promise.each(tasks, (task) => {
                    if (task.skip && task.skip(ctx)) {
                        return;
                    }

                    return task.task(ctx);
                });
            });

            class TestInstance extends Instance {
                get cliConfig() { return config; }
            }
            const fakeInstance = sinon.stub(new TestInstance(ui, system, '/var/www/ghost'));
            system.getInstance.returns(fakeInstance);
            fakeInstance.running.returns(false);
            const cmdInstance = new UpdateCommand(ui, system);
            const versionStub = sinon.stub(cmdInstance, 'version').resolves(true);
            sinon.stub(cmdInstance, 'stop').resolves();
            sinon.stub(cmdInstance, 'restart').resolves();
            sinon.stub(cmdInstance, 'link').resolves();
            const cwdStub = sinon.stub(process, 'cwd').returns(fakeInstance.dir);
            const downloadStub = sinon.stub(cmdInstance, 'downloadAndUpdate');
            const removeOldVersionsStub = sinon.stub(cmdInstance, 'removeOldVersions');

            return cmdInstance.run({rollback: true, force: false, zip: ''}).then(() => {
                cwdStub.restore();
                const expectedCtx = {
                    version: '1.0.0',
                    force: false,
                    instance: fakeInstance,
                    activeVersion: '1.1.0',
                    installPath: '/var/www/ghost/versions/1.0.0',
                    rollback: true,
                    zip: ''
                };

                expect(ui.run.calledOnce).to.be.true;
                expect(versionStub.calledOnce).to.be.true;
                expect(versionStub.args[0][0]).to.deep.equal(expectedCtx);
                expect(ui.log.called).to.be.false;
                expect(ui.listr.called).to.be.true;

                expect(downloadStub.called).to.be.false;
                expect(migrateStub.called).to.be.false;
                expect(removeOldVersionsStub.called).to.be.false;
            });
        });

        it('skips stop task if running returns false', function () {
            const migrateStub = sinon.stub().resolves();
            const UpdateCommand = proxyquire(modulePath, {
                '../tasks/migrate': migrateStub
            });
            const config = configStub();
            config.get.withArgs('cli-version').returns('1.0.0');
            config.get.withArgs('active-version').returns('1.1.0');
            config.get.withArgs('previous-version').returns('1.0.0');
            const ui = {log: sinon.stub(), listr: sinon.stub(), run: sinon.stub()};
            const system = {getInstance: sinon.stub()};
            ui.run.callsFake(fn => fn());
            ui.listr.callsFake((tasks, ctx) => {
                return Promise.each(tasks, (task) => {
                    if (task.skip && task.skip(ctx)) {
                        return;
                    }

                    return task.task(ctx);
                });
            });

            class TestInstance extends Instance {
                get cliConfig() { return config; }
            }
            const fakeInstance = sinon.stub(new TestInstance(ui, system, '/var/www/ghost'));
            system.getInstance.returns(fakeInstance);
            fakeInstance.running.returns(false);
            const cmdInstance = new UpdateCommand(ui, system);
            const versionStub = sinon.stub(cmdInstance, 'version').resolves(true);
            const stopStub = sinon.stub(cmdInstance, 'stop').resolves();
            sinon.stub(cmdInstance, 'restart').resolves();
            sinon.stub(cmdInstance, 'link').resolves();
            const cwdStub = sinon.stub(process, 'cwd').returns(fakeInstance.dir);
            sinon.stub(cmdInstance, 'downloadAndUpdate');
            sinon.stub(cmdInstance, 'removeOldVersions');

            return cmdInstance.run({rollback: true, force: false, zip: ''}).then(() => {
                cwdStub.restore();
                const expectedCtx = {
                    version: '1.0.0',
                    force: false,
                    instance: fakeInstance,
                    activeVersion: '1.1.0',
                    installPath: '/var/www/ghost/versions/1.0.0',
                    rollback: true,
                    zip: ''
                };

                expect(ui.run.calledOnce).to.be.true;
                expect(versionStub.calledOnce).to.be.true;
                expect(versionStub.args[0][0]).to.deep.equal(expectedCtx);
                expect(ui.log.called).to.be.false;
                expect(ui.listr.called).to.be.true;

                expect(stopStub.called).to.be.false;
            });
        });
    });

    describe('downloadAndUpdate task', function () {
        it('runs yarnInstall task, sets title', function () {
            const yarnInstallStub = sinon.stub().resolves();
            const UpdateCommand = proxyquire(modulePath, {
                '../tasks/yarn-install': yarnInstallStub
            });
            const instance = new UpdateCommand({}, {});
            const env = setupEnv();
            const ctx = {
                installPath: path.join(env.dir, 'versions/1.0.0'),
                version: '1.0.0'
            };
            const task = {};

            return instance.downloadAndUpdate(ctx, task).then(() => {
                expect(yarnInstallStub.calledOnce).to.be.true;
                expect(task.title).to.equal('Downloading and updating Ghost to v1.0.0');
                env.cleanup();
            });
        });

        it('skips if install path exists and force is false', function () {
            const yarnInstallStub = sinon.stub().resolves();
            const UpdateCommand = proxyquire(modulePath, {
                '../tasks/yarn-install': yarnInstallStub
            });
            const instance = new UpdateCommand({}, {});
            const envCfg = {
                dirs: ['versions/1.0.0', 'versions/1.0.1'],
                links: [['versions/1.0.0', 'current']]
            };
            const env = setupEnv(envCfg);
            const ctx = {
                installPath: path.join(env.dir, 'versions/1.0.1'),
                force: false
            };
            const task = {skip: sinon.stub()};

            expect(fs.existsSync(ctx.installPath)).to.be.true;

            return instance.downloadAndUpdate(ctx, task).then(() => {
                expect(fs.existsSync(ctx.installPath)).to.be.true;
                expect(yarnInstallStub.called).to.be.false;
                expect(task.skip.calledOnce).to.be.true;

                env.cleanup();
            });
        });

        it('removes install path if it exists and force is true', function () {
            const yarnInstallStub = sinon.stub().resolves();
            const UpdateCommand = proxyquire(modulePath, {
                '../tasks/yarn-install': yarnInstallStub
            });
            const instance = new UpdateCommand({}, {});
            const envCfg = {
                dirs: ['versions/1.0.0', 'versions/1.0.1'],
                links: [['versions/1.0.0', 'current']]
            };
            const env = setupEnv(envCfg);
            const ctx = {
                installPath: path.join(env.dir, 'versions/1.0.1'),
                force: true
            };

            expect(fs.existsSync(ctx.installPath)).to.be.true;

            return instance.downloadAndUpdate(ctx, {}).then(() => {
                expect(fs.existsSync(ctx.installPath)).to.be.false;
                expect(yarnInstallStub.calledOnce).to.be.true;

                env.cleanup();
            });
        });
    });

    describe('stop task', function () {
        it('runs stop command', function () {
            const UpdateCommand = proxyquire(modulePath, {
                './stop': {StopCommand: true}
            });
            const instance = new UpdateCommand({}, {});
            const runCommandStub = sinon.stub(instance, 'runCommand').resolves();

            return instance.stop().then(() => {
                expect(runCommandStub.calledOnce).to.be.true;
                expect(runCommandStub.args[0][0]).to.deep.equal({StopCommand: true});
                expect(runCommandStub.args[0][1]).to.deep.equal({quiet: true});
            });
        });

        it('swallows SystemError with "no instance running" message', function () {
            const UpdateCommand = proxyquire(modulePath, {
                './stop': {StopCommand: true}
            });
            const instance = new UpdateCommand({}, {});
            const runCommandStub = sinon.stub(instance, 'runCommand').rejects(new errors.SystemError(
                'No running Ghost instance found here'
            ));

            return instance.stop().then(() => {
                expect(runCommandStub.calledOnce).to.be.true;
                expect(runCommandStub.args[0][0]).to.deep.equal({StopCommand: true});
                expect(runCommandStub.args[0][1]).to.deep.equal({quiet: true});
            });
        });

        it('rethrows any unexpected error', function () {
            const UpdateCommand = proxyquire(modulePath, {
                './stop': {StopCommand: true}
            });
            const instance = new UpdateCommand({}, {});
            const runCommandStub = sinon.stub(instance, 'runCommand').rejects(new Error('uh-oh'));

            return instance.stop().then(() => {
                expect(false, 'error should have been thrown').to.be.true;
            }).catch((error) => {
                expect(error).to.be.an.instanceof(Error);
                expect(error.message).to.equal('uh-oh');
                expect(runCommandStub.calledOnce).to.be.true;
                expect(runCommandStub.args[0][0]).to.deep.equal({StopCommand: true});
                expect(runCommandStub.args[0][1]).to.deep.equal({quiet: true});
            });
        });
    });

    it('restart task runs start command', function () {
        const UpdateCommand = proxyquire(modulePath, {
            './start': {StartCommand: true}
        });
        const instance = new UpdateCommand({}, {});
        const runCommandStub = sinon.stub(instance, 'runCommand').resolves();

        return instance.restart().then(() => {
            expect(runCommandStub.calledOnce).to.be.true;
            expect(runCommandStub.args[0][0]).to.deep.equal({StartCommand: true});
            expect(runCommandStub.args[0][1]).to.deep.equal({quiet: true});
        });
    });

    describe('removeOldVersions', function () {
        it('skips if there are 5 or fewer versions installed', function () {
            const dirs = [
                'versions/1.4.0',
                'versions/1.5.0',
                'versions/1.5.1',
                'versions/1.5.2'
            ];
            const env = setupEnv({dirs: dirs});
            const UpdateCommand = require(modulePath);
            const instance = new UpdateCommand({}, {});
            const cwdStub = sinon.stub(process, 'cwd').returns(env.dir);
            const skipStub = sinon.stub();

            return instance.removeOldVersions({}, {skip: skipStub}).then(() => {
                cwdStub.restore();
                expect(skipStub.calledOnce).to.be.true;

                dirs.forEach((version) => {
                    expect(fs.existsSync(path.join(env.dir, version))).to.be.true;
                });

                env.cleanup();
            });
        });

        it('keeps only the 5 most recent versions', function () {
            const envCfg = {
                dirs: [
                    'versions/1.0.0-beta.2',
                    'versions/1.0.0-RC.1',
                    'versions/1.0.0',
                    'versions/1.0.2',
                    'versions/1.1.0',
                    'versions/1.2.0',
                    'versions/1.3.0',
                    'versions/1.4.0',
                    'versions/1.5.0'
                ]
            };
            const env = setupEnv(envCfg);
            const UpdateCommand = require(modulePath);
            const instance = new UpdateCommand({}, {});
            const cwdStub = sinon.stub(process, 'cwd').returns(env.dir);
            const keptVersions = [
                '1.1.0',
                '1.2.0',
                '1.3.0',
                '1.4.0',
                '1.5.0'
            ];
            const removedVersions = [
                '1.0.0-beta.2',
                '1.0.0-RC.1',
                '1.0.0',
                '1.0.2'
            ];

            return instance.removeOldVersions().then(() => {
                cwdStub.restore();

                keptVersions.forEach((version) => {
                    expect(fs.existsSync(path.join(env.dir, 'versions', version))).to.be.true;
                });

                removedVersions.forEach((version) => {
                    expect(fs.existsSync(path.join(env.dir, 'versions', version))).to.be.false;
                });

                env.cleanup();
            });
        });
    });

    describe('version', function () {
        it('resolves with true if rollback is true', function () {
            const UpdateCommand = require(modulePath);
            const instance = new UpdateCommand({}, {});

            return instance.version({rollback: true}).then((result) => {
                expect(result).to.be.true;
            });
        });

        it('calls resolveVersion util with correct args and sets version and installPath in context', function () {
            const resolveVersion = sinon.stub().resolves('1.0.1');
            const UpdateCommand = proxyquire(modulePath, {
                '../utils/resolve-version': resolveVersion
            });
            const instance = new UpdateCommand({}, {});
            const context = {
                rollback: false,
                force: false,
                version: null,
                activeVersion: '1.0.0'
            };
            const cwdStub = sinon.stub(process, 'cwd').returns('/var/www/ghost');

            return instance.version(context).then((result) => {
                expect(result).to.be.true;
                expect(resolveVersion.calledOnce).to.be.true;
                expect(resolveVersion.calledWithExactly(null, '1.0.0')).to.be.true;
                expect(context.version).to.equal('1.0.1');
                expect(context.installPath).to.equal('/var/www/ghost/versions/1.0.1');
                cwdStub.restore();
            });
        });

        it('calls versionFromZip resolver with zip path if zip is passed', function () {
            const resolveVersion = sinon.stub().resolves('1.0.1');
            const zipVersion = sinon.stub().resolves('1.1.0');
            const UpdateCommand = proxyquire(modulePath, {
                '../utils/resolve-version': resolveVersion,
                '../utils/version-from-zip': zipVersion
            });
            const instance = new UpdateCommand({}, {});
            const context = {
                rollback: false,
                force: false,
                version: null,
                activeVersion: '1.0.0',
                zip: '/some/zip/file.zip'
            };
            const cwdStub = sinon.stub(process, 'cwd').returns('/var/www/ghost');

            return instance.version(context).then((result) => {
                expect(result).to.be.true;
                expect(resolveVersion.called).to.be.false;
                expect(zipVersion.calledOnce).to.be.true;
                expect(zipVersion.calledWithExactly('/some/zip/file.zip', '1.0.0')).to.be.true;
                expect(context.version).to.equal('1.1.0');
                expect(context.installPath).to.equal('/var/www/ghost/versions/1.1.0');
                cwdStub.restore();
            });
        });

        it('swallows CliErrors from resolveVersion util', function () {
            const resolveVersion = sinon.stub().rejects(new errors.CliError('No valid versions found'));
            const UpdateCommand = proxyquire(modulePath, {
                '../utils/resolve-version': resolveVersion
            });
            const instance = new UpdateCommand({}, {});
            const context = {
                rollback: false,
                force: true,
                version: null,
                activeVersion: '1.0.0'
            };

            return instance.version(context).then((result) => {
                expect(result).to.be.false;
                expect(resolveVersion.calledOnce).to.be.true;
                expect(resolveVersion.calledWithExactly(null, null)).to.be.true;
            });
        });

        it('re-throws non CliErrors from resolveVersion util', function () {
            const resolveVersion = sinon.stub().callsFake(() => {
                // sinon's reject handling doesn't work quite well enough
                // for this so we do it manually
                return Promise.reject(new Error('something bad'));
            });
            const UpdateCommand = proxyquire(modulePath, {
                '../utils/resolve-version': resolveVersion
            });
            const instance = new UpdateCommand({}, {});
            const context = {
                rollback: false,
                force: true,
                version: null,
                activeVersion: '1.0.0'
            };

            return instance.version(context).then(() => {
                expect(false, 'error should have been thrown').to.be.true;
            }).catch((error) => {
                expect(error).to.be.an.instanceof(Error);
                expect(error.message).to.equal('something bad');
                expect(resolveVersion.calledOnce).to.be.true;
                expect(resolveVersion.calledWithExactly(null, null)).to.be.true;
            });
        });
    });

    describe('link', function () {
        const UpdateCommand = require(modulePath);

        it('does things correctly with normal upgrade', function () {
            const instance = new UpdateCommand({}, {});
            const envCfg = {
                dirs: ['versions/1.0.0', 'versions/1.0.1'],
                links: [['versions/1.0.0', 'current']]
            }
            const env = setupEnv(envCfg);
            const cwdStub = sinon.stub(process, 'cwd').returns(env.dir);
            const config = configStub();
            config.get.withArgs('active-version').returns('1.0.0');
            const context = {
                installPath: path.join(env.dir, 'versions/1.0.1'),
                version: '1.0.1',
                rollback: false,
                instance: {
                    cliConfig: config
                }
            };

            instance.link(context);
            expect(fs.readlinkSync(path.join(env.dir, 'current'))).to.equal(path.join(env.dir, 'versions/1.0.1'));
            expect(config.set.calledTwice).to.be.true;
            expect(config.set.calledWithExactly('previous-version', '1.0.0')).to.be.true;
            expect(config.set.calledWithExactly('active-version', '1.0.1')).to.be.true;
            expect(config.save.calledOnce).to.be.true;

            cwdStub.restore();
            env.cleanup();
        });

        it('does things correctly with rollback', function () {
            const instance = new UpdateCommand({}, {});
            const envCfg = {
                dirs: ['versions/1.0.0', 'versions/1.0.1'],
                links: [['versions/1.0.1', 'current']]
            }
            const env = setupEnv(envCfg);
            const cwdStub = sinon.stub(process, 'cwd').returns(env.dir);
            const config = configStub();
            config.get.withArgs('active-version').returns('1.0.1');
            const context = {
                installPath: path.join(env.dir, 'versions/1.0.0'),
                version: '1.0.0',
                rollback: true,
                instance: {
                    cliConfig: config
                }
            };

            instance.link(context);
            expect(fs.readlinkSync(path.join(env.dir, 'current'))).to.equal(path.join(env.dir, 'versions/1.0.0'));
            expect(config.set.calledTwice).to.be.true;
            expect(config.set.calledWithExactly('previous-version', null)).to.be.true;
            expect(config.set.calledWithExactly('active-version', '1.0.0')).to.be.true;
            expect(config.save.calledOnce).to.be.true;

            cwdStub.restore();
            env.cleanup();
        });
    });
});


text:
<?php
/**
 * @author    MyBB Group
 * @version   2.0.0
 * @package   mybb/core
 * @license   http://www.mybb.com/licenses/bsd3 BSD-3
 */

namespace MyBB\Core\Http\Controllers\Api;

use League\Fractal\Manager;
use MyBB\Core\Database\Repositories\TopicRepositoryInterface;
use MyBB\Core\Http\Requests;
use MyBB\Core\Transformers\TopicTransformer;

class TopicApiController extends AbstractApiController
{
    /**
     * @var TopicRepositoryInterface
     */
    protected $topicRepository;

    /**
     * @param TopicRepositoryInterface $topicRepository
     * @param Manager $fractal
     */
    public function __construct(TopicRepositoryInterface $topicRepository, Manager $fractal)
    {
        parent::__construct($fractal);
        $this->topicRepository = $topicRepository;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index()
    {
        $topics = $this->topicRepository->all();

        if (!$topics) {
            // TODO: respond with error
        }

        return $this->respondWithCollection($topics, new TopicTransformer);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create()
    {
        //
    }

    /**
     * Store a newly created resource in storage.
     *
     * @return Response
     */
    public function store()
    {
        //
    }

    /**
     * Display the specified resource.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function update($id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int $id
     *
     * @return Response
     */
    public function destroy($id)
    {
        //
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="@style/NavPage"
    android:orientation="vertical" >

    <TextView
        style="@style/TitleText"
        android:text="@string/pay_by_wx_title" />

    <Button
        android:id="@+id/unifiedorder_btn"
        style="@style/MMLineActionButton"
        android:layout_margin="10dp"
        android:text="@string/unifiedorder_v3_wx" />

    <Button
            android:id="@+id/appay_pre_btn"
            style="@style/MMLineActionButton"
            android:layout_margin="10dp"
            android:text="@string/pay__pre_by_wxap" />
    <Button
            android:id="@+id/appay_btn"
            style="@style/MMLineActionButton"
            android:layout_margin="10dp"
            android:text="@string/pay_by_wxap" />

    <TextView
        android:id="@+id/editText_prepay_id"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        >
    </TextView>

</LinearLayout>


text:
$(window).scroll(function(){
  var height = $(window).scrollTop();
  if(height  > 55) {
    $("nav").addClass("shrinknav");
  }
  else {
    $("nav").removeClass("shrinknav");
  }
});

$(document).ready(function() {
  $('body').css('display', 'none');
  $('body').fadeIn(1000);

  if ($(window).width() < 900){
    $("#navhome").html('home');
    $("#navplans").html('attach_money');
    $("#navfeatures").html('whatshot');
    $("#navpreview").html('ondemand_video');
    $("#navcontact").html('phone_in_talk');
  }
  else {
    $("#navhome").html('HOME');
    $("#navplans").html('PLANS');
    $("#navfeatures").html("FEATURES");
    $("#navpreview").html('PREVIEW');
    $("#navcontact").html('GET IN TOUCH');
  }

  $('nav ul li a').click(function() {
    event.preventDefault();
    newLocation = this.href;
    if (endsWith(newLocation,"#")==false){
      $('body').fadeOut(1000, newpage);
    }
  });

  $('.handle').on('click', function() {
  		$('nav ul').toggleClass('autoShow');
  	})
  $('nav ul li').on('click', function(){
  	$('nav ul').toggleClass('autoShow');
  })

  if ($(window).width() <988){
    $(".col33").removeClass("paddright2");
    $(".col33").removeClass("paddleft2");
  }

  $(window).resize(function() {
    if ($(window).width() <988){
      $(".col33").removeClass("paddright2");
      $(".col33").removeClass("paddleft2");
    }
    else{
      if ($(".col33").hasClass("paddleft2")==false){
        $(".col33").addClass("paddright2");
        $(".col33").addClass("paddleft2");
      }
    }

    if ($(window).width() < 900){
      $("#navhome").html('home');
      $("#navplans").html('attach_money');
      $("#navfeatures").html('whatshot');
      $("#navpreview").html('ondemand_video');
      $("#navcontact").html('phone_in_talk');
    }
    else {
      $("#navhome").html('HOME');
      $("#navplans").html('PLANS');
      $("#navfeatures").html('FEATURES');
      $("#navpreview").html('PREVIEW');
      $("#navcontact").html('GET IN TOUCH');
    }
  });

  function newpage() {
    window.location = newLocation;
  }
});

function endsWith(str, suffix) {
    return str.indexOf(suffix, str.length - suffix.length) !== -1;
}


text:
struct CompareScoreMN
{
    bool operator()(const std::pair<arith_uint256, const CDeterministicMNCPtr&>& t1,
                    const std::pair<arith_uint256, const CDeterministicMNCPtr&>& t2) const
    {
        return (t1.first != t2.first) ? (t1.first < t2.first) : (t1.second->collateralOutpoint < t2.second->collateralOutpoint);
    }
};

void CMasternodeUtils::ProcessMasternodeConnections(CConnman& connman)
{
    std::vector<CDeterministicMNCPtr> vecDmns; // will be empty when no wallet
#ifdef ENABLE_WALLET
    privateSendClient.GetMixingMasternodesInfo(vecDmns);
#endif // ENABLE_WALLET

    // Don't disconnect masternode connections when we have less then the desired amount of outbound nodes
    int nonMasternodeCount = 0;
    connman.ForEachNode(CConnman::AllNodes, [&](CNode* pnode) {
        if (!pnode->fInbound && !pnode->fFeeler && !pnode->m_manual_connection && !pnode->fMasternode) {
            nonMasternodeCount++;
        }
    });
    if (nonMasternodeCount < connman.GetMaxOutboundNodeCount()) {
        return;
    }

    connman.ForEachNode(CConnman::AllNodes, [&](CNode* pnode) {
        if (pnode->fMasternode && !connman.IsMasternodeQuorumNode(pnode)) {
#ifdef ENABLE_WALLET
            bool fFound = false;
            for (const auto& dmn : vecDmns) {
                if (pnode->addr == dmn->pdmnState->addr) {
                    fFound = true;
                    break;
                }
            }
            if (fFound) return; // do NOT disconnect mixing masternodes
#endif // ENABLE_WALLET
            if (fLogIPs) {
                LogPrintf("Closing Masternode connection: peer=%d, addr=%s\n", pnode->GetId(), pnode->addr.ToString());
            } else {
                LogPrintf("Closing Masternode connection: peer=%d\n", pnode->GetId());
            }
            pnode->fDisconnect = true;
        }
    });
}

void CMasternodeUtils::DoMaintenance(CConnman& connman)
{
    if(!masternodeSync.IsBlockchainSynced() || ShutdownRequested())
        return;

    static unsigned int nTick = 0;

    nTick++;

    if(nTick % 60 == 0) {
        ProcessMasternodeConnections(connman);
    }
}


text:
<?php
// File Security Check
if (!defined('ABSPATH'))
    exit;

class WP_Email_Template_Less
{
	public $plugin_name = 'wp_email_template';
	public $css_file_name = 'wp_email_template';
	public $plugin_folder = WP_EMAIL_TEMPLATE_FOLDER;
	public $plugin_dir = WP_EMAIL_TEMPLATE_DIR;

    /*-----------------------------------------------------------------------------------*/
    /* Constructor */
    /*-----------------------------------------------------------------------------------*/
    public function __construct()
    {
		add_action( $this->plugin_name.'_after_settings_save_reset', array ($this, 'plugin_build_sass') );
		add_action( 'wp_enqueue_scripts', array ($this, 'apply_style_css_fontend') , 9 );
    }

	public function apply_style_css_fontend()
	{
		$_upload_dir = wp_upload_dir();
		if ( file_exists( $_upload_dir['basedir'] . '/sass/' . $this->css_file_name . '.min.css' ) ) {
			wp_enqueue_style( 'a3' . $this->css_file_name, str_replace( array('http:','https:'), '', $_upload_dir['baseurl'] ) . '/sass/' . $this->css_file_name . '.min.css', array(), $this->get_css_file_version() );
        }
	}

	public function plugin_build_sass()
    {
		$sass = $this->sass_content_data();
		$this->plugin_compile_less_mincss( $sass );
        $this->set_css_file_version();
	}
    public function custom_filesystem_method( $method = '') {
        return 'direct';
    }

	public function plugin_compile_less_mincss( $sass, $css_file_name = '' )
    {
        // just filter when compile less file
        add_filter( 'filesystem_method', array( $this, 'custom_filesystem_method' ) );

        $form_url = wp_nonce_url( esc_url( add_query_arg( 'compile-sass', 'true' ) ), 'compile-sass' );

        if ( ! function_exists( 'request_filesystem_credentials' ) ) {
            require_once( ABSPATH . 'wp-admin/includes/file.php' );
        }

        if ( false === ( $creds = request_filesystem_credentials( $form_url, '', false, false, null ) ) ) {
            return true;
        }

        if ( ! WP_Filesystem( $creds ) ) {
            // our credentials were no good, ask the user for them again
            request_filesystem_credentials( $form_url, '', true );
            return true;
        }

        global $wp_filesystem;

		@ini_set( 'display_errors', false );
        $_upload_dir = wp_upload_dir();
        $wp_filesystem->chmod($_upload_dir['basedir'], 0755);
        if (! $wp_filesystem->is_dir($_upload_dir['basedir'] . '/sass')) {
            $wp_filesystem->mkdir($_upload_dir['basedir'] . '/sass', 0755);
        } else {
            $wp_filesystem->chmod($_upload_dir['basedir'] . '/sass', 0755);
        }

		if ( trim( $css_file_name ) == '' ) $css_file_name = $this->css_file_name;

        if ( $css_file_name == '' )
            return;

		if ( $this->plugin_folder == '' )
            return;

        $filename = $css_file_name;

        if (!file_exists($_upload_dir['basedir'] . '/sass/' . $filename . '.less')) {
            $wp_filesystem->put_contents($_upload_dir['basedir'] . '/sass/' . $filename . '.less', '', 0644 );
            $wp_filesystem->put_contents($_upload_dir['basedir'] . '/sass/' . $filename . '.css', '', 0644);
            $wp_filesystem->put_contents($_upload_dir['basedir'] . '/sass/' . $filename . '.min.css', '', 0644);
        }

        $mixins = $this->css_file_name . '_mixins';
        if( !file_exists( $_upload_dir['basedir'].'/sass/'.$mixins.'.less' ) ){
            $mixinsless = $this->plugin_dir.'/admin/less/assets/css/mixins.less';
            $a3rev_mixins_less = $_upload_dir['basedir'].'/sass/'.$mixins.'.less';
            $wp_filesystem->copy($mixinsless, $a3rev_mixins_less, true );
        }

        $files = array_diff(scandir($_upload_dir['basedir'] . '/sass'), array(
            '.',
            '..'
        ));
        if ($files) {
            foreach ($files as $file) {
                $wp_filesystem->chmod($_upload_dir['basedir'] . '/sass/' . $file, 0644);
            }
        }

        $sass_data = '';

        if ($sass != '') {

            $sass_data = '@import "'.$mixins.'.less";' . "\n";

            $sass_data .= $sass;

            $sass_data = str_replace(':;', ': transparent;', $sass_data);
            $sass_data = str_replace(': ;', ': transparent;', $sass_data);
            $sass_data = str_replace(': !important', ': transparent !important', $sass_data);
            $sass_data = str_replace(':px', ':0px', $sass_data);
            $sass_data = str_replace(': px', ': 0px', $sass_data);

            $less_file = $_upload_dir['basedir'] . '/sass/' . $filename . '.less';
            if (is_writable($less_file)) {

                if (!class_exists('Compile_Less_Sass'))
                    include( dirname( __FILE__ ) . '/compile_less_sass_class.php');
                $wp_filesystem->put_contents($less_file, $sass_data, 0644);
                $css_file     = $_upload_dir['basedir'] . '/sass/' . $filename . '.css';
                $css_min_file = $_upload_dir['basedir'] . '/sass/' . $filename . '.min.css';
                $compile      = new Compile_Less_Sass;
                $compile->compileLessFile($less_file, $css_file, $css_min_file);
            }
        }
    }

    public function sass_content_data()
    {
		do_action($this->plugin_name . '_get_all_settings');

        ob_start();
		include( $this->plugin_dir. '/templates/customized_style.php' );
		$sass = ob_get_clean();
		$sass = str_replace( '<style>', '', str_replace( '</style>', '', $sass ) );
		$sass = str_replace( '<style type="text/css">', '', str_replace( '</style>', '', $sass ) );

        // Start Less
        $sass_ext = '';

        $sass_ext = apply_filters( $this->plugin_name.'_build_sass', $sass_ext );

        if ($sass_ext != '')
            $sass .= "\n" . $sass_ext;

        return $sass;
    }

    public function set_css_file_version( $css_file_name = '' ) {
        if ( trim( $css_file_name ) == '' ) {
            $css_file_name = $this->css_file_name;
        }

        if ( $css_file_name == '' ) {
            return false;
        }

        update_option( $css_file_name . '_style_version', time() );
    }

    public function get_css_file_version( $css_file_name = '' ) {
        if ( trim( $css_file_name ) == '' ) {
            $css_file_name = $this->css_file_name;
        }

        if ( $css_file_name == '' ) {
            return false;
        }

        $version_number = get_option( $css_file_name . '_style_version', time() );

        return $version_number;
    }
}
global $wp_email_template_less;
$wp_email_template_less = new WP_Email_Template_Less();
?>


text:
package jk_5.nailed.api.scoreboard;

import javax.annotation.Nonnull;

/**
 * This represents an objective in the scoreboard system.
 * An objective is a score type that can be displayed on the client gui
 * The individual scores can be set for either players or other names (this depends on the user of the api)
 *
 * @author jk-5
 */
public interface Objective {

    /**
     * Get the unique id for this Objective.
     *
     * @return The unique id for this objective. This id may be chosen upon creation in `ScoreboardManager#getOrCreateObjective(String)}`
     */
    @Nonnull
    String getId();

    /**
     * Get the display name for this objective. Note that this may be formatted (color, bold, italic).
     *
     * @return The displayName of this Objective.
     */
    @Nonnull
    String getDisplayName();

    /**
     * Sets the displayName of this Objective.
     * Note that the displayName may not be bigger than 32.
     *
     * @param displayName The new displayName for this objective.
     * @throws IllegalArgumentException When the displayName is longer than 32.
     */
    void setDisplayName(@Nonnull String displayName);

    /**
     * Gets the score object for the specified name, or creating one if it doesn't already exist.
     * Note that the name may not be bigger than 16.
     *
     * @param name The name of the score object. (should not be longer than 16).
     * @return The score object.
     * @throws IllegalArgumentException When the name is longer than 16.
     */
    @Nonnull Score getScore(@Nonnull String name);

    /**
     * Removes the score from the objective.
     *
     * @param score The score to remove.
     */
    void removeScore(@Nonnull Score score);
}


text:
<?php
/**
 * AttwFramework
 *
 * @author Gabriel Jacinto <gamjj74@hotmail.com>
 * @license MIT License
 * @link http://attwframework.github.io
*/

namespace Attw\Logger;

class LogLevel
{
    const EMERGENCY = 'emergency';
    const ALERT     = 'alert';
    const CRITICAL  = 'critical';
    const ERROR     = 'error';
    const WARNING   = 'warning';
    const NOTICE    = 'notice';
    const INFO      = 'info';
    const DEBUG     = 'debug';
}


text:
$LOAD_PATH.unshift File.dirname(__FILE__) + '/../lib'

require 'test/unit'
require 'cards'
require 'set'

class CardTest < Test::Unit::TestCase
	def setup
		@ace_of_clubs = Cards::Card.new('Ace', 'Clubs')
		@ace_of_spades = Cards::Card.new('Ace', 'Spades')
		@two_of_clubs = Cards::Card.new(2, 'Clubs')
		@three_of_diamonds = Cards::Card.new(3, 'Diamonds')
	end

	def test_equality
		ace_of_clubs = Cards::Card.new('Ace', 'Clubs')

		assert_equal(@ace_of_clubs, ace_of_clubs)
		assert_not_equal(@ace_of_clubs, @ace_of_spades)
		assert_not_equal(@ace_of_clubs, @two_of_clubs)
	end

	def test_comparison
		assert(@ace_of_clubs < @two_of_clubs, 'Ace not greater than or equal to two' )
		assert(@three_of_diamonds > @two_of_clubs, 'Two not less than or equal to three')

		assert_equal(@ace_of_clubs <=> @ace_of_spades, 0, 'Ace of Clubs not greater than or less than Ace of Spades')
	end

	def test_tostring
		assert_match(/\bace\b.+\bclubs\b/i, @ace_of_clubs.to_s)
	end
end

class DeckTest < Test::Unit::TestCase
	def setup
		@deck = Cards::Deck.new
		@set = Set.new
	end

	def test_draw
		52.times do
			@set << @deck.draw
		end

		assert(@set.size == 52, '52 different cards not drawn.')
	end

	def test_reset
		52.times { @deck.draw }

		@deck.reset

		cards = []
		52.times { cards << @deck.draw }

		assert(cards.size == 52, 'Deck not reset correctly.')
	end
end


text:
package android

import java.io.File

import android.Keys.PackagingOptions
import com.android.builder.core.AndroidBuilder
import com.android.sdklib.BuildToolInfo

object Aggregate {
  private[android] case class Retrolambda(enable: Boolean,
                                          classpath: Seq[File],
                                          builder: AndroidBuilder)

  private[android] case class AndroidTest(debugIncludesTests: Boolean,
                                          instrumentTestRunner: String,
                                          instrumentTestTimeout: Int,
                                          apkbuildDebug: Boolean,
                                          externalDependencyClassPathInTest: Seq[File],
                                          externalDependencyClasspathInCompile: Seq[File],
                                          packagingOptions: PackagingOptions,
                                          libraryProject: Boolean)

  private[android] case class Apkbuild(packagingOptions: PackagingOptions,
                                       apkbuildDebug: Boolean,
                                       dex: File,
                                       predex: Seq[(File,File)],
                                       collectJni: Seq[File],
                                       resourceShrinker: File)

  private[android] case class Manifest(applicationId: String,
                                       versionName: Option[String],
                                       versionCode: Option[Int],
                                       minSdkVersion: String,
                                       targetSdkVersion: String,
                                       placeholders: Map[String,String])

  private[android] case class Dex(inputs: (Boolean,Seq[File]),
                                  maxHeap: String,
                                  multi: Boolean,
                                  mainFileClassesConfig: File,
                                  minimizeMainFile: Boolean,
                                  buildTools: BuildToolInfo,
                                  additionalParams: Seq[String])

  private[android] case class Proguard(useProguard: Boolean,
                                       useProguardInDebug: Boolean,
                                       proguardScala: Boolean,
                                       proguardConfig: Seq[String],
                                       proguardOptions: Seq[String],
                                       proguardCache: Seq[String])

}


text:
/* net/atm/atmarp.h - RFC1577 ATM ARP */

/* Written 1995-2000 by Werner Almesberger, EPFL LRC/ICA */

#ifndef _ATMCLIP_H
#define _ATMCLIP_H

#include <linux/netdevice.h>
#include <linux/atm.h>
#include <linux/atmdev.h>
#include <linux/atmarp.h>
#include <linux/spinlock.h>
#include <net/neighbour.h>

#define CLIP_VCC(vcc) ((struct clip_vcc *) ((vcc)->user_back))
#define NEIGH2ENTRY(neigh) ((struct atmarp_entry *) (neigh)->primary_key)

struct sk_buff;

struct clip_vcc {
	struct atm_vcc	*vcc;		/* VCC descriptor */
	struct atmarp_entry *entry;	/* ATMARP table entry, NULL if IP addr.
					   isn't known yet */
	int		xoff;		/* 1 if send buffer is full */
	unsigned char	encap;		/* 0: NULL, 1: LLC/SNAP */
	unsigned long	last_use;	/* last send or receive operation */
	unsigned long	idle_timeout;	/* keep open idle for so many jiffies*/
	void (*old_push)(struct atm_vcc *vcc,struct sk_buff *skb);
					/* keep old push fn for chaining */
	void (*old_pop)(struct atm_vcc *vcc,struct sk_buff *skb);
					/* keep old pop fn for chaining */
	struct clip_vcc	*next;		/* next VCC */
};

struct atmarp_entry {
	__be32		ip;		/* IP address */
	struct clip_vcc	*vccs;		/* active VCCs; NULL if resolution is
					   pending */
	unsigned long	expires;	/* entry expiration time */
	struct neighbour *neigh;	/* neighbour back-pointer */
};

#define PRIV(dev) ((struct clip_priv *) netdev_priv(dev))

struct clip_priv {
	int number;			/* for convenience ... */
	spinlock_t xoff_lock;		/* ensures that pop is atomic (SMP) */
	struct net_device *next;	/* next CLIP interface */
};

extern struct neigh_table *clip_tbl_hook;

#endif


text:
Allows the developer to load objects only when required in an easy, thread-safe, simple way.

### Syntax
```csharp
var instance = new Lazy<<class_name>>([init_function]);
```

|               | Option        | Description                                        |
| :-----------: | ------------- | -------------------------------------------------- |
| :exclamation: | class_name    | The class to be instantiated                       |
|               | init_function | The function to be used to initialize the instance |

### Example
```csharp
public class AutomaticGuid
{
    public Guid ID { get; private set; }

    public AutomaticGuid()
    {
        Console.WriteLine("Generating a new Guid");
        ID = Guid.NewGuid();
    }
}

var instance = new Lazy<AutomaticGuid>();

// outputs false
Console.WriteLine(instance.IsValueCreated);

// outputs Generating a new Guid
var value = instance.Value;

// outputs true
Console.WriteLine(instance.IsValueCreated);
```

### Output
![Output](https://cloud.githubusercontent.com/assets/19519411/20394080/e477fcbe-aca3-11e6-8811-34301b687cab.png)

### References
Lazy Constructor \([https://msdn.microsoft.com/en-us/library/dd642329(v=vs.110).aspx](https://msdn.microsoft.com/en-us/library/dd642329(v=vs.110).aspx)\)

### Tags
[#tip](../../tips.md)
[#c#](../csharp.md)
[#concurrency](concurrency.md)


text:
package com.twitter.parrot.integration

import org.jboss.netty.handler.codec.http.HttpResponse
import com.twitter.logging.Logger
import com.twitter.ostrich.stats.Stats
import com.twitter.parrot.config.ParrotServerConfig
import com.twitter.parrot.server.ParrotRequest
import com.twitter.parrot.server.ParrotService
import com.twitter.parrot.util.UriParser
import com.twitter.util.Return
import com.twitter.util.Throw
import com.twitter.parrot.processor.RecordProcessor
import com.twitter.finagle.tracing.Trace

/**
 * This processor just takes a line-separated list of URIs and turns them into requests, for instance:
 * /search.json?q=%23playerofseason&since_id=68317051210563584&rpp=30
 * needs to have the target scheme, host, and port included, but otherwise is a complete URL
 * Empty lines and lines starting with '#' will be ignored.
 */

class TestRecordProcessor(service: ParrotService[ParrotRequest, HttpResponse],
  config: ParrotServerConfig[ParrotRequest, HttpResponse])
  extends RecordProcessor {
  private[this] val log = Logger.get(getClass)
  private[this] var exceptionCount = 0
  private[this] val hostHeader = Some((config.httpHostHeader, config.httpHostHeaderPort))
  var responded = 0
  var properlyShutDown = false

  def processLines(lines: Seq[String]) {
    log.trace("SimpleRecordProcessor.processLines: processing %d lines", lines.size)
    for(line <- lines) {
      Trace.traceService("Parrot", "TestRecordProcessor.processLines") {
        val p = UriParser(line)
        log.trace("SimpleRecordProcessor.processLines: line is %s", line)
        UriParser(line) match {
          case Return(uri) =>
            if (!uri.path.isEmpty && !line.startsWith("#"))
              service(new ParrotRequest(hostHeader, Nil, uri, line)) respond { response =>
                log.debug("response was %s", response.toString)
                responded += 1
            }
          case Throw(t) =>
            if (exceptionCount < 3)
              log.warning("exception\n\t%s\nwhile processing line\n\t%s",t.getMessage(), line)
            else if (exceptionCount == 3) log.warning("more exceptions ...")
            exceptionCount += 1
            Stats.incr("bad_lines")
            Stats.incr("bad_lines/" + t.getClass.getName)
        }
      }
    }
  }
  override def shutdown() {
    properlyShutDown = true
  }
}


text:
helloworld
==========

Initial repo


text:
import Component from '../component.js';

/**
 * Component for elements which have async attribute content.
 *
 * {@link https://akilijs.com/docs/components#docs_image,_iframe,_embed,_audio,_video,_track,_source,_object}
 *
 * @tag url
 * @selector [url],[urlset]
 * @attr {string} [url] - source link
 * @attr {string} [urlset] - source link set
 * @attr {boolean} [hidden-error] - hide the failed request picture
 * @attr {string} [loading] - loading type: "lazy", "viewport"
 */
export default class Url extends Component {
  static matches = '[url],[urlset]';
  static booleanAttributes = ['hidden-error'];

  constructor(...args) {
    super(...args);
    this.urlAttribute = 'src';
    this.handlerAttribute = this.el.hasAttribute('urlset')? 'urlset': 'url';
    this.elOpacity = getComputedStyle(this.el).opacity;
  }

  created() {
    this.viewport = false;
    this.cancelable = false;
    this.observer = null;
    this.finished = false;
    this.cancelling = false;
    this.onLoadListener = this.onLoad.bind(this);
    this.onErrorListener = this.onError.bind(this);
    this.el.addEventListener('load', this.onLoadListener);
    this.el.addEventListener('error', this.onErrorListener);
    this.createUrlAttribute();
  }

  compiled() {
    this.attr('loading', this.setLoading);
    this.attr(this.handlerAttribute, this.setUrl);
  }

  removed() {
    this.observer && this.observer.disconnect();
  }

  createUrlAttribute() {
    if(this.handlerAttribute == 'urlset') {
      this.urlAttribute + 'set';
    }
  }

  onLoad() {
    if(this.isRemoved) {
      return;
    }

    this.attrs.hiddenError && (this.el.style.opacity = this.elOpacity);
    this.finished = true;
    this.cancelling = false;
  }

  onError() {
    if(this.isRemoved) {
      return;
    }

    this.attrs.hiddenError && (this.el.style.opacity = 0);
    !this.cancelling && (this.finished = true);
  }

  intersectionHandler(entries) {
    const entry = entries[0];
    this.isIntersecting = entry.isIntersecting;

    if(!entry.isIntersecting && !this.finished) {
      this.cancelling = true;
      this.attrs[this.urlAttribute] = '';
      return;
    }

    if(!this.finished) {
      this.cancelling = false;
      this.attrs[this.urlAttribute] = this.attrs[this.handlerAttribute];
    }
  }

  setLoading(value) {
    this.viewport = value == 'viewport';

    if(!this.viewport) {
      this.observer && this.observer.disconnect();
      delete this.isIntersecting;
      return;
    }

    this.observer = new IntersectionObserver(this.intersectionHandler.bind(this));
    this.observer.observe(this.el);
  }

  setUrl(url) {
    this.finished = false;
    this.cancelling = false;

    if(this.viewport && !this.isIntersecting) {
      return;
    }

    this.attrs[this.urlAttribute] = url;
  }
}


text:
@interface CJNavigationController ()

@end

@implementation CJNavigationController

+ (void)initialize
{
    UINavigationBar *appearance = [UINavigationBar appearance];

    // 设置导航栏背景
    [appearance setBackgroundImage:[UIImage imageNamed:@"top_navigation_background"] forBarMetrics:UIBarMetricsDefault];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    [self setValue:[[CJNavigationBar alloc] init] forKey:@"navigationBar"];
}

@end


text:
import React, { PropTypes } from 'react';
import { css, StyleSheet } from 'aphrodite/no-important';
import styles from './styles';
import ScreenReaderOnly from '../ScreenReaderOnly';
import colors from './colors';
import sizes from './sizes';

function Spinner ({ className, size, color, ...props }) {
	props.className = css(
		classes.base,
		classes[size],
		className
	);

	return (

			<span className={`${css(classes.dot, classes['size__' + size], classes['color__' + color], classes.dot__first)}`} />
			<span className={`${css(classes.dot, classes['size__' + size], classes['color__' + color], classes.dot__second)}`} />
			<span className={`${css(classes.dot, classes['size__' + size], classes['color__' + color], classes.dot__third)}`} />
			<ScreenReaderOnly>Loading...</ScreenReaderOnly>

	);
};

Spinner.propTypes = {
	color: PropTypes.oneOf(colors),
	size: PropTypes.oneOf(sizes),
};
Spinner.defaultProps = {
	size: 'medium',
	color: 'default',
};

const classes = StyleSheet.create(styles);

module.exports = Spinner;


text:
package org.prototype.primecount.core.controller;

final class PrimeChecker
{
    private static final int FIRST_PRIME = 2;
    private static final int ZERO = 0;

    private PrimeChecker()
    {
        super();
    }

    public static boolean isPrime(final int integer)
    {
        boolean prime = true; //NOPMD
        if (isIntegerLessThanFirstPrime(integer))
        {
            prime = false;
        }
        else if (isIntegerEqualsFirstPrime(integer)) /**anyway no need for this check as prime is set to true*/
        {
            prime = true;
        }
        else
        {
            final int max = (int) Math.ceil(Math.sqrt(integer));
            int nextInt = FIRST_PRIME;
            while (nextInt <= max)
            {
                if (isThisModoluThatEqualsZero(integer, nextInt))
                {
                    prime = false;
                    break;
                }
                nextInt++;
            }
        }
        return prime;
    }

    private static boolean isThisModoluThatEqualsZero(final int integer, final int that)
    {
        return ZERO == integer % that;
    }

    private static boolean isIntegerEqualsFirstPrime(final int integer)
    {
        return FIRST_PRIME == integer;
    }

    private static boolean isIntegerLessThanFirstPrime(final int integer)
    {
        return FIRST_PRIME > integer;
    }
}


text:
package io.openex.rest.comcheck.form;

import com.fasterxml.jackson.annotation.JsonProperty;

import javax.validation.constraints.NotBlank;
import java.time.Instant;
import java.util.ArrayList;
import java.util.List;

import static io.openex.config.AppConfig.MANDATORY_MESSAGE;

public class ComcheckInput {
    @NotBlank(message = MANDATORY_MESSAGE)
    @JsonProperty("comcheck_name")
    private String name;

    @JsonProperty("comcheck_end_date")
    private Instant end;

    @JsonProperty("comcheck_subject")
    private String subject;

    @JsonProperty("comcheck_message")
    private String message;

    @JsonProperty("comcheck_audiences")
    private List<String> audienceIds = new ArrayList<>();

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public List<String> getAudienceIds() {
        return audienceIds;
    }

    public void setAudienceIds(List<String> audienceIds) {
        this.audienceIds = audienceIds;
    }

    public Instant getEnd() {
        return end;
    }

    public void setEnd(Instant end) {
        this.end = end;
    }

    public String getSubject() {
        return subject;
    }

    public void setSubject(String subject) {
        this.subject = subject;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }
}


text:
package play.utils;

import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

public class PThreadFactory implements ThreadFactory {

    final ThreadGroup group;
    final AtomicInteger threadNumber = new AtomicInteger(1);
    final String namePrefix;

    public PThreadFactory(String poolName) {
        SecurityManager s = System.getSecurityManager();
        group = (s != null) ? s.getThreadGroup() : Thread.currentThread().getThreadGroup();
        namePrefix = poolName + "-thread-";
    }

    public Thread newThread(Runnable r) {
        Thread t = new Thread(group, r, namePrefix + threadNumber.getAndIncrement(), 0);
        if (t.isDaemon()) {
            t.setDaemon(false);
        }
        if (t.getPriority() != Thread.NORM_PRIORITY) {
            t.setPriority(Thread.NORM_PRIORITY);
        }
        return t;
    }
}


text:
package com.microsoftopentechnologies.intellij.helpers;

import com.intellij.openapi.components.ApplicationComponent;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.microsoftopentechnologies.intellij.helpers.azure.AzureCmdException;
import sun.misc.IOUtils;

import javax.swing.*;
import javax.xml.bind.DatatypeConverter;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;

public class AndroidStudioHelper {
    private static final String mobileServicesTemplateName = "AzureServicesActivity";
    private static final String officeTemplateName = "Office365Activity";

    public static void newActivityTemplateManager(boolean deleteTemplates, Object caller) throws IOException, InterruptedException {
        String templatePath = URLDecoder.decode(ApplicationComponent.class.getResource("").getPath().replace("file:/", ""), "UTF-8");
        templatePath = templatePath.replace("/", File.separator);
        templatePath = templatePath.substring(0, templatePath.indexOf(File.separator + "lib"));
        templatePath = templatePath + File.separator + "plugins" + File.separator + "android" + File.separator;
        templatePath = templatePath + "lib" + File.separator + "templates" + File.separator + "activities" + File.separator;

        if (System.getProperty("os.name").toLowerCase().startsWith("mac") && !templatePath.startsWith(File.separator)) {
            templatePath = File.separator + templatePath;
        }

        if (deleteTemplates || !new File(templatePath + mobileServicesTemplateName).exists()) {
            String tmpDir = getTempLocation();
            copyResourcesRecursively(new File(tmpDir));

            tmpDir = tmpDir + "MobileServiceTemplate" + File.separator;

            if (System.getProperty("os.name").toLowerCase().startsWith("windows")) {
                try {

                    if (deleteTemplates) {
                        VirtualFile mobileTemplate = LocalFileSystem.getInstance().findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
                        VirtualFile officeTemplate = LocalFileSystem.getInstance().findFileByIoFile(new File(templatePath + officeTemplateName));

                        if (mobileTemplate != null)
                            mobileTemplate.delete(caller);

                        if (officeTemplate != null)
                            officeTemplate.delete(caller);

                    }

                    copyFolder(new File(tmpDir + mobileServicesTemplateName), new File(templatePath + mobileServicesTemplateName));
                    copyFolder(new File(tmpDir + officeTemplateName), new File(templatePath + officeTemplateName));

                } catch (IOException ex) {

                    String parameterFormat = "<Copy originPath='%s' targetPath='%s' deleteTarget='%s'/>";

                    StringBuilder sb = new StringBuilder();
                    sb.append("<WindowsTemplateCopyParameters>");
                    sb.append(String.format(parameterFormat, tmpDir + mobileServicesTemplateName, templatePath + mobileServicesTemplateName, deleteTemplates ? "true" : "false"));
                    sb.append(String.format(parameterFormat, tmpDir + officeTemplateName, templatePath + officeTemplateName, deleteTemplates ? "true" : "false"));
                    sb.append("</WindowsTemplateCopyParameters>");
                    String param = DatatypeConverter.printBase64Binary(sb.toString().getBytes("UTF-8"));

                    String[] tmpCmd = {
                            "cmd",
                            "/c",
                            tmpDir + "WindowsTemplateCopy.exe",
                            param,
                    };

                    ArrayList<String> tempenvlist = new ArrayList<String>();
                    for (String envval : System.getenv().keySet())
                        tempenvlist.add(String.format("%s=%s", envval, System.getenv().get(envval)));

                    tempenvlist.add("PRECOMPILE_STREAMLINE_FILES=1");
                    String[] env = new String[tempenvlist.size()];
                    tempenvlist.toArray(env);

                    Runtime rt = Runtime.getRuntime();
                    Process proc = rt.exec(tmpCmd, env, new File(tmpDir));
                    int errorCode = proc.waitFor();

                    //wait for elevate command to finish
                    Thread.sleep(3000);

                    if (!new File(templatePath + mobileServicesTemplateName).exists() || errorCode != 0)
                        UIHelper.showException("Error copying template files. Please refer to documentation to copy manually.", new Exception());
                }
            } else if (System.getProperty("os.name").toLowerCase().startsWith("mac")) {

                String[] deleteAndCopy = {
                        "osascript",
                        "-e",
                        "do shell script \"rm -r \\\"/" + templatePath + mobileServicesTemplateName + "\\\"\" with administrator privileges",
                        "-e",
                        "do shell script \"rm -r \\\"/" + templatePath + officeTemplateName + "\\\"\" with administrator privileges",
                        "-e",
                        "do shell script \"cp -Rp \\\"" + tmpDir + mobileServicesTemplateName + "\\\" \\\"/" + templatePath + "\\\"\" with administrator privileges",
                        "-e",
                        "do shell script \"cp -Rp \\\"" + tmpDir + officeTemplateName + "\\\" \\\"/" + templatePath + "\\\"\" with administrator privileges"
                };

                String[] copy = {
                        "osascript",
                        "-e",
                        "do shell script \"cp -Rp \\\"" + tmpDir + mobileServicesTemplateName + "\\\" \\\"/" + templatePath + "\\\"\" with administrator privileges",
                        "-e",
                        "do shell script \"cp -Rp \\\"" + tmpDir + officeTemplateName + "\\\" \\\"/" + templatePath + "\\\"\" with administrator privileges"
                };

                exec(deleteTemplates ? deleteAndCopy : copy, tmpDir);
            } else {
                try {

                    if (deleteTemplates) {
                        VirtualFile mobileTemplate = LocalFileSystem.getInstance().findFileByIoFile(new File(templatePath + mobileServicesTemplateName));
                        VirtualFile officeTemplate = LocalFileSystem.getInstance().findFileByIoFile(new File(templatePath + officeTemplateName));

                        if (mobileTemplate != null)
                            mobileTemplate.delete(caller);

                        if (officeTemplate != null)
                            officeTemplate.delete(caller);

                    }

                    copyFolder(new File(tmpDir + mobileServicesTemplateName), new File(templatePath + mobileServicesTemplateName));
                    copyFolder(new File(tmpDir + officeTemplateName), new File(templatePath + officeTemplateName));

                } catch (IOException ex) {

                    JPasswordField pf = new JPasswordField();
                    int okCxl = JOptionPane.showConfirmDialog(null, pf, "To copy Microsoft Services templates, the plugin needs your password:", JOptionPane.OK_CANCEL_OPTION, JOptionPane.PLAIN_MESSAGE);

                    if (okCxl == JOptionPane.OK_OPTION) {
                        String password = new String(pf.getPassword());

                        exec(new String[]{
                                "echo",
                                password,
                                "|",
                                "sudo",
                                "-S",
                                "rm",
                                "-r",
                                tmpDir + mobileServicesTemplateName,
                                templatePath + mobileServicesTemplateName
                        }, tmpDir);

                        exec(new String[]{
                                "echo",
                                password,
                                "|",
                                "sudo",
                                "-S",
                                "rm",
                                "-r",
                                tmpDir + officeTemplateName,
                                templatePath + officeTemplateName
                        }, tmpDir);

                        exec(new String[]{
                                "echo",
                                password,
                                "|",
                                "sudo",
                                "-S",
                                "cp",
                                "-Rp",
                                tmpDir + mobileServicesTemplateName,
                                templatePath + mobileServicesTemplateName
                        }, tmpDir);

                        exec(new String[]{
                                "echo",
                                password,
                                "|",
                                "sudo",
                                "-S",
                                "cp",
                                "-Rp",
                                tmpDir + officeTemplateName,
                                templatePath + officeTemplateName
                        }, tmpDir);
                    }
                }
            }
        }
    }

    private static void copyResourcesRecursively(File targetDir) throws IOException {
        InputStream fileList = ServiceCodeReferenceHelper.getTemplateResource("MobileServiceTemplate/fileList.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(fileList));

        String line;
        while ((line = in.readLine()) != null) {

            String[] pathParts = line.split("/");
            String fileName = pathParts[pathParts.length - 1];
            String path = line.replace(fileName, "");

            String targetPath = targetDir.getAbsolutePath() + File.separator
                    + "MobileServiceTemplate" + File.separator
                    + path.replace("/", File.separator);

            File targetFolder = new File(targetPath);
            targetFolder.mkdirs();

            File targetFile = new File(targetFolder, fileName);
            targetFile.createNewFile();
            targetFile.setWritable(true);

            InputStream inputStream = ServiceCodeReferenceHelper.getTemplateResource("MobileServiceTemplate/" + line);

            byte[] content = IOUtils.readFully(inputStream, -1, true);

            FileOutputStream fileOutputStream = new FileOutputStream(targetFile);
            fileOutputStream.write(content);
            fileOutputStream.flush();
            fileOutputStream.close();

        }
    }

    private static void exec(String[] cmd, String tmpdir) throws IOException, InterruptedException {
        String[] env = new String[]{"PRECOMPILE_STREAMLINE_FILES=1"};

        Runtime rt = Runtime.getRuntime();
        Process proc = rt.exec(cmd, env, new File(tmpdir));

        // any error message?
        StreamGobbler errorGobbler = new StreamGobbler(proc.getErrorStream(), true);

        // kick them off
        errorGobbler.start();

        proc.waitFor();
    }

    private static String getTempLocation() {

        String tmpdir = System.getProperty("java.io.tmpdir");
        StringBuilder sb = new StringBuilder();
        sb.append(tmpdir);

        if (!tmpdir.endsWith(File.separator))
            sb.append(File.separator);

        sb.append("TempAzure");
        sb.append(File.separator);

        return sb.toString();
    }

    private static class StreamGobbler extends Thread {
        InputStream is;
        boolean isError;

        public StreamGobbler(InputStream is, boolean isError) {
            this.is = is;
            this.isError = isError;
        }

        public void run() {
            try {
                InputStreamReader isr = new InputStreamReader(is);
                BufferedReader br = new BufferedReader(isr);
                String line;
                StringBuilder sb = new StringBuilder();
                while ((line = br.readLine()) != null) {
                    sb.append(line).append("\n");
                }

                is.close();

                String streamContent = sb.toString();

                if (isError && !streamContent.isEmpty())
                    UIHelper.showException("Error copying Microsoft Services templates", new AzureCmdException("Error copying Microsoft Services templates", "Error: " + streamContent));

            } catch (IOException ioe) {
                UIHelper.showException("Error copying Microsoft Services templates", ioe);
            }
        }
    }

    public static void copyFolder(File src, File dest)
            throws IOException {

        if (src.isDirectory()) {

            //if directory not exists, create it
            if (!dest.exists()) {
                dest.mkdir();
            }

            //list all the directory contents
            String files[] = src.list();

            for (String file : files) {
                //construct the src and dest file structure
                File srcFile = new File(src, file);
                File destFile = new File(dest, file);
                //recursive copy
                copyFolder(srcFile, destFile);
            }

        } else {
            InputStream in = new FileInputStream(src);
            OutputStream out = new FileOutputStream(dest);

            byte[] buffer = new byte[1024];

            int length;
            //copy the file content in bytes
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }

            in.close();
            out.close();
        }
    }
}


text:
//  Copyright (c) 2005, Regents of the University of California
//  All rights reserved.
//
//  Redistribution and use in source and binary forms, with or without
//  modification, are permitted provided that the following conditions are
//  met:
//
//    * Redistributions of source code must retain the above copyright notice,
//  this list of conditions and the following disclaimer.
//    * Redistributions in binary form must reproduce the above copyright
//  notice, this list of conditions and the following disclaimer in the
//  documentation and/or other materials provided with the distribution.
//    * Neither the name of the University of California, San Diego (UCSD) nor
//  the names of its contributors may be used to endorse or promote products
//  derived from this software without specific prior written permission.
//
//  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS
//  IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
//  THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
//  PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
//  CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
//  EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
//  PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
//  PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
//  LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
//  NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
//  SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
//
//  FILE
//  GeneralRandomAccessFile.java  -  edu.sdsc.grid.io.GeneralRandomAccessFile
//
//  CLASS HIERARCHY
//  java.lang.Object
//      |
//      +-java.io.InputStream
//          |
//          +-edu.sdsc.grid.io.GeneralFileInputStream
//              |
//              +-edu.sdsc.grid.io.RemoteFileInputStream
//
//
//  PRINCIPAL AUTHOR
//  Lucas Gilbert, SDSC/UCSD
//
//
package edu.sdsc.grid.io;

import java.io.*;

/**
 * A GeneralFileInputStream obtains input bytes from a file in a file system.
 * What files are available depends on the host environment.
 *

 * GeneralFileInputStream is meant for reading streams of raw bytes such as
 * image data.
 *

 * The original intention for this class was to subclass
 * java.io.FileInputStream. But that is not currently the case.
 *

 *
 * @author Lucas Gilbert
 * @since JARGON1.4
 */
public abstract class RemoteFileInputStream extends GeneralFileInputStream {
	/**
	 * Creates a RemoteFileInputStream by opening a connection to
	 * an actual file, the file named by the path name name in the
	 * file system. A new FileDescriptor object is created to
	 * represent this file connection.
	 *

	 * First, if there is a security manager, its checkRead method
	 * is called with the name argument as its argument.
	 *

	 * If the named file does not exist, is a directory rather than a regular
	 * file, or for some other reason cannot be opened for reading then a
	 * IOException is thrown.
	 *
	 * @param name
	 *            the system-dependent file name.
	 * @exception IOException
	 *                if the file does not exist, is a directory rather than a
	 *                regular file, or for some other reason cannot be opened
	 *                for reading.
	 */
	public RemoteFileInputStream(GeneralFileSystem fileSystem, String name)
			throws IOException {
		super(fileSystem, name);
	}

	/**
	 * Creates a RemoteFileInputStream by opening a connection to
	 * an actual file, the file named by the File object
	 * file in the file system. A new FileDescriptor
	 * object is created to represent this file connection.
	 *

	 * First, if there is a security manager, its checkRead method
	 * is called with the path represented by the file argument as
	 * its argument.
	 *

	 * If the named file does not exist, is a directory rather than a regular
	 * file, or for some other reason cannot be opened for reading then a
	 * IOException is thrown.
	 *
	 * @param file
	 *            the file to be opened for reading.
	 * @exception IOException
	 *                if the file does not exist, is a directory rather than a
	 *                regular file, or for some other reason cannot be opened
	 *                for reading.
	 * @see java.io.File#getPath()
	 */
	public RemoteFileInputStream(GeneralFile file) throws IOException {
		super(file);
	}
}


text:
from __future__ import annotations

import re
from collections.abc import Iterable, Iterator, Sequence
from re import Match, Pattern
from typing import Final, Any

from .mime import MessageHeader

__all__ = ['ThreadKey']

class ThreadKey(Iterable[str]):
    """Represents a hashable key used to link messages as members of the same
    thread.

    The thread key is composed of a single message ID from the ``Message-Id``,
    ``In-Reply-To``, or ``References`` headers, along with a normalized version
    of the ``Subject`` header. If two messages share a single thread key, they
    should be assigned the same
    :attr:`~pymap.interfaces.message.MessageInterface.thread_id`.

    Args:
        msg_id: The message ID bytestring.
        subject: The normalized subject bytestring.

    """

    _pattern = re.compile(r'<[^>]*>')
    _whitespace = re.compile(r'\s+')
    _fwd_pattern = re.compile(r'\s*fwd\s*:\s*', re.I)
    _re_pattern = re.compile(r'\s*re\s*:\s*', re.I)
    _listtag_pattern = re.compile(r'\s*\[.*?\]\s*')

    __slots__ = ['_pair', '__weakref__']

    def __init__(self, msg_id: str, subject: str) -> None:
        super().__init__()
        self._pair: Final = (msg_id, subject)

    def __eq__(self, other: Any) -> bool:
        if isinstance(other, ThreadKey):
            return self._pair == other._pair
        return super().__eq__(other)

    def __hash__(self) -> int:
        return hash(self._pair)

    def __iter__(self) -> Iterator[str]:
        return iter(self._pair)

    @classmethod
    def _encode(cls, value: str) -> str:
        return cls._whitespace.sub('', value)

    @classmethod
    def _first_match(cls, value: str, *patterns: Pattern[str]) \
            -> Match[str] | None:
        for pattern in patterns:
            match = pattern.match(value)
            if match is not None:
                return match
        return None

    @classmethod
    def _subject(cls, value: str) -> str:
        match = cls._first_match(
            value, cls._fwd_pattern, cls._re_pattern, cls._listtag_pattern)
        if match is None:
            return cls._whitespace.sub(' ', value.strip())
        else:
            return cls._subject(value[match.end(0):])

    @classmethod
    def get_all(cls, header: MessageHeader) -> Sequence[ThreadKey]:
        """Return all the thread keys from the message headers.

        Args:
            header: The message header.

        """
        ret: list[ThreadKey] = []
        message_id = header.parsed.message_id
        in_reply_to = header.parsed.in_reply_to
        references = header.parsed.references
        subject = header.parsed.subject
        subject_key = cls._subject(str(subject)) if subject else ''
        if message_id is not None:
            match = cls._pattern.search(str(message_id))
            if match is not None:
                ret.append(cls(cls._encode(match.group(0)), subject_key))
        if in_reply_to is not None:
            for match in cls._pattern.finditer(str(in_reply_to)):
                ret.append(cls(cls._encode(match.group(0)), subject_key))
        if references is not None:
            for match in cls._pattern.finditer(str(references)):
                ret.append(cls(cls._encode(match.group(0)), subject_key))
        return ret


text:
Capistrano::Configuration.instance(:must_exist).load do
  set :shared_item_path, -> { "#{fetch :shared_path}/items" }

  namespace :item do
    desc '[internal] Symlink all items'
    task :link, :roles => :app do
      link_items fetch(:shared_item_path),
        fetch(:latest_release)
    end

    desc '[internal] Setup shared items'
    task :setup, :roles => :app do
      fetch(:shared_items, []).each do |item|
        item_shared_path = "#{fetch :shared_item_path}/#{item.gsub /\//, ','}"
        item_public_path = "#{fetch :latest_release}/#{item}"

        unless remote_file_exists? item_shared_path
          if remote_file_exists? "#{item_public_path}.default"
            run "#{try_sudo} cp #{item_public_path}.default #{item_shared_path}"
            logger.important "#{item_public_path}.default copied to #{item_shared_path}"
          else
            write '', item_shared_path
            logger.important "#{item_shared_path} has been initialized with an empty file"
          end
        end
      end
    end
  end

  # Internal Dependencies
  before 'item:link', 'item:setup'

  # External Dependencies
  before 'deploy:restart', 'item:link'
end


text:
<TITLE>JPetStore Demo</TITLE>
<META content="text/html; charset=windows-1252" http-equiv=Content-Type>

      <FORM action="shop/searchProducts.shtml">
      <INPUT name=keyword size=14> <INPUT border=0
      src="images/search.gif"
      type=image> </FORM>

Welcome to JPetStore 4

Enter the Store


text:
#ifndef __GROW_H__
#define __GROW_H__

void *grow_nodata(int *nrequested, int *sizep, void *bufp,
		  int inisize, void *bufini, size_t typesize);
void *grow_withdata(int *nrequested, int *nexisting,
		    int *sizep, void *bufp,
		    int inisize, void *bufini, size_t typesize);
void *grow_withtail(int *nrequested, int *nexisting, char **startp,
		    int *sizep, void *bufp,
		    int inisize, void *bufini, size_t typesize);

#endif


text:
<?xml version='1.0' encoding='UTF-8' standalone='no'?>
<doxygen xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="compound.xsd" version="1.8.6">
  <compounddef id="structboost_1_1geometry_1_1resolve__variant_1_1within_3_01_geometry1_00_01boost_1_1variant_3_01_f59c49c769f8a7ba44e1981f5f6b7912" kind="struct" prot="public">
    <compoundname>boost::geometry::resolve_variant::within< Geometry1, boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)> ></compoundname>
    <includes local="no">within.hpp</includes>
    <innerclass refid="structboost_1_1geometry_1_1resolve__variant_1_1within_3_01_geometry1_00_01boost_1_1variant_3_01_fe6f419073623544800edee6cc0fea81" prot="public">boost::geometry::resolve_variant::within< Geometry1, boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)> >::visitor</innerclass>
    <templateparamlist>
      <param>
        <type>typename Geometry1</type>
      </param>
      <param>
        <type>BOOST_VARIANT_ENUM_PARAMS(typename T)</type>
      </param>
    </templateparamlist>
      <sectiondef kind="public-static-func">
      <memberdef kind="function" id="structboost_1_1geometry_1_1resolve__variant_1_1within_3_01_geometry1_00_01boost_1_1variant_3_01_f59c49c769f8a7ba44e1981f5f6b7912_1a5c0f8421a7f93d7effaf03a51e8d7417" prot="public" static="yes" const="no" explicit="no" inline="yes" virt="non-virtual">
        <templateparamlist>
          <param>
            <type>typename Strategy</type>
          </param>
        </templateparamlist>
        <type>bool</type>
        <definition>static bool boost::geometry::resolve_variant::within< Geometry1, boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)> >::apply</definition>
        <argsstring>(Geometry1 const &geometry1, boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)> const &geometry2, Strategy const &strategy)</argsstring>
        <name>apply</name>
        <param>
          <type>Geometry1 const &</type>
          <declname>geometry1</declname>
        </param>
        <param>
          <type>boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)> const &</type>
          <declname>geometry2</declname>
        </param>
        <param>
          <type>Strategy const &</type>
          <declname>strategy</declname>
        </param>
        <briefdescription>
        </briefdescription>
        <detaileddescription>
        </detaileddescription>
        <inbodydescription>
        </inbodydescription>
        <location file="/home/travis/build/boostorg/boost/boost/geometry/algorithms/within.hpp" line="411" column="1" bodyfile="/home/travis/build/boostorg/boost/boost/geometry/algorithms/within.hpp" bodystart="411" bodyend="418"/>
      </memberdef>
      </sectiondef>
    <briefdescription>
    </briefdescription>
    <detaileddescription>
    </detaileddescription>
    <location file="/home/travis/build/boostorg/boost/boost/geometry/algorithms/within.hpp" line="388" column="1" bodyfile="/home/travis/build/boostorg/boost/boost/geometry/algorithms/within.hpp" bodystart="387" bodyend="419"/>
    <listofallmembers>
      <member refid="structboost_1_1geometry_1_1resolve__variant_1_1within_3_01_geometry1_00_01boost_1_1variant_3_01_f59c49c769f8a7ba44e1981f5f6b7912_1a5c0f8421a7f93d7effaf03a51e8d7417" prot="public" virt="non-virtual"><scope>boost::geometry::resolve_variant::within< Geometry1, boost::variant< BOOST_VARIANT_ENUM_PARAMS(T)> ></scope><name>apply</name></member>
    </listofallmembers>
  </compounddef>
</doxygen>


text:
layout:     post
title:      "Project Name"
date:       2016-12-09 12:00:00 +0100
categories: school_project
thumb:      http://placehold.it/350x150
---
Projects
- We are doomed
- Chicken run
-

Devblog
- Scratch effect (Jose's project)
- Progress bar Unity
- AirConsole integration
- Arduino/Unity connection
- Wwise integration
- UI/Scene transition effects
- Particle effects with sprites

- A* (but it's Sebastian Lague tutorial but in 3D)


text:
using UnityEngine;
using Facebook.Unity;
using UnityEngine.UI;
using System.Collections.Generic;

class FBTest : MonoBehaviour
{
    [SerializeField]
    GameObject testTimer;

    private void FixedUpdate()
    {
        testTimer.GetComponent<Text>().text = "";
        testTimer.GetComponent<Text>().text += PlayerPrefs.GetInt("Crystals");
    }
}


text:
/*jslint node: true */
"use strict";
var assert = require('assert')
, _ = require('underscore')
, xml = require('../index.js')
;

describe('value', function () {
    it('should return the text content of an element', function () {
        assert.equal(xml.value(xml.elt('monkey', [xml.text('kitten')])), 'kitten');
    });
});


text:
package com.amazonaws.services.codedeploy.model.transform;

import javax.annotation.Generated;

import com.amazonaws.SdkClientException;
import com.amazonaws.services.codedeploy.model.*;

import com.amazonaws.protocol.*;
import com.amazonaws.annotation.SdkInternalApi;

/**
 * BlueGreenDeploymentConfigurationMarshaller
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
@SdkInternalApi
public class BlueGreenDeploymentConfigurationMarshaller {

    private static final MarshallingInfo<StructuredPojo> TERMINATEBLUEINSTANCESONDEPLOYMENTSUCCESS_BINDING = MarshallingInfo
            .builder(MarshallingType.STRUCTURED).marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("terminateBlueInstancesOnDeploymentSuccess")
            .build();
    private static final MarshallingInfo<StructuredPojo> DEPLOYMENTREADYOPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("deploymentReadyOption").build();
    private static final MarshallingInfo<StructuredPojo> GREENFLEETPROVISIONINGOPTION_BINDING = MarshallingInfo.builder(MarshallingType.STRUCTURED)
            .marshallLocation(MarshallLocation.PAYLOAD).marshallLocationName("greenFleetProvisioningOption").build();

    private static final BlueGreenDeploymentConfigurationMarshaller instance = new BlueGreenDeploymentConfigurationMarshaller();

    public static BlueGreenDeploymentConfigurationMarshaller getInstance() {
        return instance;
    }

    /**
     * Marshall the given parameter object.
     */
    public void marshall(BlueGreenDeploymentConfiguration blueGreenDeploymentConfiguration, ProtocolMarshaller protocolMarshaller) {

        if (blueGreenDeploymentConfiguration == null) {
            throw new SdkClientException("Invalid argument passed to marshall(...)");
        }

        try {
            protocolMarshaller.marshall(blueGreenDeploymentConfiguration.getTerminateBlueInstancesOnDeploymentSuccess(),
                    TERMINATEBLUEINSTANCESONDEPLOYMENTSUCCESS_BINDING);
            protocolMarshaller.marshall(blueGreenDeploymentConfiguration.getDeploymentReadyOption(), DEPLOYMENTREADYOPTION_BINDING);
            protocolMarshaller.marshall(blueGreenDeploymentConfiguration.getGreenFleetProvisioningOption(), GREENFLEETPROVISIONINGOPTION_BINDING);
        } catch (Exception e) {
            throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e);
        }
    }

}


text:
layout: default
order: 1
ref: libros/duende_del_lugar/
img: /img/0a3/duende.jpg
---


text:
package sbt

import java.io.File
import java.net.{ URI, URL }
import scala.xml.NodeSeq
import org.apache.ivy.plugins.resolver.{ DependencyResolver, IBiblioResolver }
import org.apache.ivy.util.url.CredentialsStore
import sbt.serialization._

/** Additional information about a project module */
final case class ModuleInfo(nameFormal: String, description: String = "", homepage: Option[URL] = None, startYear: Option[Int] = None, licenses: Seq[(String, URL)] = Nil, organizationName: String = "", organizationHomepage: Option[URL] = None, scmInfo: Option[ScmInfo] = None, developers: Seq[Developer] = Seq()) {
  def this(nameFormal: String, description: String, homepage: Option[URL], startYear: Option[Int], licenses: Seq[(String, URL)], organizationName: String, organizationHomepage: Option[URL], scmInfo: Option[ScmInfo]) =
    this(nameFormal, description, homepage, startYear, licenses, organizationName, organizationHomepage, scmInfo, Seq())
  def formally(name: String) = copy(nameFormal = name)
  def describing(desc: String, home: Option[URL]) = copy(description = desc, homepage = home)
  def licensed(lics: (String, URL)*) = copy(licenses = lics)
  def organization(name: String, home: Option[URL]) = copy(organizationName = name, organizationHomepage = home)
}

/** Basic SCM information for a project module */
final case class ScmInfo(browseUrl: URL, connection: String, devConnection: Option[String] = None)

final case class Developer(id: String, name: String, email: String, url: URL)

/** Rule to exclude unwanted dependencies pulled in transitively by a module. */
final case class ExclusionRule(organization: String = "*", name: String = "*", artifact: String = "*", configurations: Seq[String] = Nil)
object ExclusionRule {
  implicit val pickler: Pickler[ExclusionRule] with Unpickler[ExclusionRule] = PicklerUnpickler.generate[ExclusionRule]
}

final case class ModuleConfiguration(organization: String, name: String, revision: String, resolver: Resolver)
object ModuleConfiguration {
  def apply(org: String, resolver: Resolver): ModuleConfiguration = apply(org, "*", "*", resolver)
  def apply(org: String, name: String, resolver: Resolver): ModuleConfiguration = ModuleConfiguration(org, name, "*", resolver)
}

final case class ConflictManager(name: String, organization: String = "*", module: String = "*")

/** See http://ant.apache.org/ivy/history/latest-milestone/settings/conflict-managers.html for details of the different conflict managers.*/
object ConflictManager {
  val all = ConflictManager("all")
  val latestTime = ConflictManager("latest-time")
  val latestRevision = ConflictManager("latest-revision")
  val latestCompatible = ConflictManager("latest-compatible")
  val strict = ConflictManager("strict")
  val default = latestRevision
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Uses of Class org.apache.jena.ontology.OntologyException (Apache Jena)</title>
<meta name="date" content="2015-12-08">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Uses of Class
org.apache.jena.ontology.OntologyException

Packages that use OntologyException

Package
Description

org.apache.jena.ontology

                        Provides a set of abstractions and convenience classes for accessing and manipluating ontologies
                        represented in RDF.

Uses of OntologyException in org.apache.jena.ontology

Subclasses of OntologyException in org.apache.jena.ontology

Modifier and Type
Class and Description

class
ConversionException

 Exception that is thrown when an ontology resource is converted to another
 facet, using as(), and the requested conversion is not
 possible.

class
LanguageConsistencyException

 An exception that denotes some inconsistency between the arguments to a method
 in the ontology API, and the language definition for a given ontology profile.

class
ProfileException

 Exception that is raised when an ontology operation is attempted that is
 not present in the language profile for the current ontology model.

Skip navigation links

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Licenced under the Apache License, Version 2.0