text:
const { constants, expectEvent, expectRevert, time } = require('@openzeppelin/test-helpers');
const { ZERO_BYTES32 } = constants;

const { expect } = require('chai');

const TimelockController = artifacts.require('TimelockController');
const CallReceiverMock = artifacts.require('CallReceiverMock');
const Implementation2 = artifacts.require('Implementation2');
const MINDELAY = time.duration.days(1);

function genOperation (target, value, data, predecessor, salt) {
  const id = web3.utils.keccak256(web3.eth.abi.encodeParameters([
    'address',
    'uint256',
    'bytes',
    'uint256',
    'bytes32',
  ], [
    target,
    value,
    data,
    predecessor,
    salt,
  ]));
  return { id, target, value, data, predecessor, salt };
}

function genOperationBatch (targets, values, datas, predecessor, salt) {
  const id = web3.utils.keccak256(web3.eth.abi.encodeParameters([
    'address[]',
    'uint256[]',
    'bytes[]',
    'uint256',
    'bytes32',
  ], [
    targets,
    values,
    datas,
    predecessor,
    salt,
  ]));
  return { id, targets, values, datas, predecessor, salt };
}

contract('TimelockController', function (accounts) {
  const [ admin, proposer, executor, other ] = accounts;

  beforeEach(async function () {
    // Deploy new timelock
    this.timelock = await TimelockController.new(
      MINDELAY,
      [ proposer ],
      [ executor ],
      { from: admin },
    );
    this.TIMELOCK_ADMIN_ROLE = await this.timelock.TIMELOCK_ADMIN_ROLE();
    this.PROPOSER_ROLE = await this.timelock.PROPOSER_ROLE();
    this.EXECUTOR_ROLE = await this.timelock.EXECUTOR_ROLE();
    // Mocks
    this.callreceivermock = await CallReceiverMock.new({ from: admin });
    this.implementation2 = await Implementation2.new({ from: admin });
  });

  it('initial state', async function () {
    expect(await this.timelock.getMinDelay()).to.be.bignumber.equal(MINDELAY);
  });

  describe('methods', function () {
    describe('operation hashing', function () {
      it('hashOperation', async function () {
        this.operation = genOperation(
          '0x29cebefe301c6ce1bb36b58654fea275e1cacc83',
          '0xf94fdd6e21da21d2',
          '0xa3bc5104',
          '0xba41db3be0a9929145cfe480bd0f1f003689104d275ae912099f925df424ef94',
          '0x60d9109846ab510ed75c15f979ae366a8a2ace11d34ba9788c13ac296db50e6e',
        );
        expect(await this.timelock.hashOperation(
          this.operation.target,
          this.operation.value,
          this.operation.data,
          this.operation.predecessor,
          this.operation.salt,
        )).to.be.equal(this.operation.id);
      });

      it('hashOperationBatch', async function () {
        this.operation = genOperationBatch(
          Array(8).fill('0x2d5f21620e56531c1d59c2df9b8e95d129571f71'),
          Array(8).fill('0x2b993cfce932ccee'),
          Array(8).fill('0xcf51966b'),
          '0xce8f45069cc71d25f71ba05062de1a3974f9849b004de64a70998bca9d29c2e7',
          '0x8952d74c110f72bfe5accdf828c74d53a7dfb71235dfa8a1e8c75d8576b372ff',
        );
        expect(await this.timelock.hashOperationBatch(
          this.operation.targets,
          this.operation.values,
          this.operation.datas,
          this.operation.predecessor,
          this.operation.salt,
        )).to.be.equal(this.operation.id);
      });
    });
    describe('simple', function () {
      describe('schedule', function () {
        beforeEach(async function () {
          this.operation = genOperation(
            '0x31754f590B97fD975Eb86938f18Cc304E264D2F2',
            0,
            '0x3bf92ccc',
            ZERO_BYTES32,
            '0x025e7b0be353a74631ad648c667493c0e1cd31caa4cc2d3520fdc171ea0cc726',
          );
        });

        it('proposer can schedule', async function () {
          const receipt = await this.timelock.schedule(
            this.operation.target,
            this.operation.value,
            this.operation.data,
            this.operation.predecessor,
            this.operation.salt,
            MINDELAY,
            { from: proposer },
          );
          expectEvent(receipt, 'CallScheduled', {
            id: this.operation.id,
            index: web3.utils.toBN(0),
            target: this.operation.target,
            value: web3.utils.toBN(this.operation.value),
            data: this.operation.data,
            predecessor: this.operation.predecessor,
            delay: MINDELAY,
          });

          const block = await web3.eth.getBlock(receipt.receipt.blockHash);

          expect(await this.timelock.getTimestamp(this.operation.id))
            .to.be.bignumber.equal(web3.utils.toBN(block.timestamp).add(MINDELAY));
        });

        it('prevent overwritting active operation', async function () {
          await this.timelock.schedule(
            this.operation.target,
            this.operation.value,
            this.operation.data,
            this.operation.predecessor,
            this.operation.salt,
            MINDELAY,
            { from: proposer },
          );

          await expectRevert(
            this.timelock.schedule(
              this.operation.target,
              this.operation.value,
              this.operation.data,
              this.operation.predecessor,
              this.operation.salt,
              MINDELAY,
              { from: proposer },
            ),
            'TimelockController: operation already scheduled',
          );
        });

        it('prevent non-proposer from commiting', async function () {
          await expectRevert(
            this.timelock.schedule(
              this.operation.target,
              this.operation.value,
              this.operation.data,
              this.operation.predecessor,
              this.operation.salt,
              MINDELAY,
              { from: other },
            ),
            `AccessControl: account ${other.toLowerCase()} is missing role ${this.PROPOSER_ROLE}`,
          );
        });

        it('enforce minimum delay', async function () {
          await expectRevert(
            this.timelock.schedule(
              this.operation.target,
              this.operation.value,
              this.operation.data,
              this.operation.predecessor,
              this.operation.salt,
              MINDELAY - 1,
              { from: proposer },
            ),
            'TimelockController: insufficient delay',
          );
        });
      });

      describe('execute', function () {
        beforeEach(async function () {
          this.operation = genOperation(
            '0xAe22104DCD970750610E6FE15E623468A98b15f7',
            0,
            '0x13e414de',
            ZERO_BYTES32,
            '0xc1059ed2dc130227aa1d1d539ac94c641306905c020436c636e19e3fab56fc7f',
          );
        });

        it('revert if operation is not scheduled', async function () {
          await expectRevert(
            this.timelock.execute(
              this.operation.target,
              this.operation.value,
              this.operation.data,
              this.operation.predecessor,
              this.operation.salt,
              { from: executor },
            ),
            'TimelockController: operation is not ready',
          );
        });

        describe('with scheduled operation', function () {
          beforeEach(async function () {
            ({ receipt: this.receipt, logs: this.logs } = await this.timelock.schedule(
              this.operation.target,
              this.operation.value,
              this.operation.data,
              this.operation.predecessor,
              this.operation.salt,
              MINDELAY,
              { from: proposer },
            ));
          });

          it('revert if execution comes too early 1/2', async function () {
            await expectRevert(
              this.timelock.execute(
                this.operation.target,
                this.operation.value,
                this.operation.data,
                this.operation.predecessor,
                this.operation.salt,
                { from: executor },
              ),
              'TimelockController: operation is not ready',
            );
          });

          it('revert if execution comes too early 2/2', async function () {
            const timestamp = await this.timelock.getTimestamp(this.operation.id);
            await time.increaseTo(timestamp - 5); // -1 is too tight, test sometime fails

            await expectRevert(
              this.timelock.execute(
                this.operation.target,
                this.operation.value,
                this.operation.data,
                this.operation.predecessor,
                this.operation.salt,
                { from: executor },
              ),
              'TimelockController: operation is not ready',
            );
          });

          describe('on time', function () {
            beforeEach(async function () {
              const timestamp = await this.timelock.getTimestamp(this.operation.id);
              await time.increaseTo(timestamp);
            });

            it('executor can reveal', async function () {
              const receipt = await this.timelock.execute(
                this.operation.target,
                this.operation.value,
                this.operation.data,
                this.operation.predecessor,
                this.operation.salt,
                { from: executor },
              );
              expectEvent(receipt, 'CallExecuted', {
                id: this.operation.id,
                index: web3.utils.toBN(0),
                target: this.operation.target,
                value: web3.utils.toBN(this.operation.value),
                data: this.operation.data,
              });
            });

            it('prevent non-executor from revealing', async function () {
              await expectRevert(
                this.timelock.execute(
                  this.operation.target,
                  this.operation.value,
                  this.operation.data,
                  this.operation.predecessor,
                  this.operation.salt,
                  { from: other },
                ),
                `AccessControl: account ${other.toLowerCase()} is missing role ${this.EXECUTOR_ROLE}`,
              );
            });
          });
        });
      });
    });

    describe('batch', function () {
      describe('schedule', function () {
        beforeEach(async function () {
          this.operation = genOperationBatch(
            Array(8).fill('0xEd912250835c812D4516BBD80BdaEA1bB63a293C'),
            Array(8).fill(0),
            Array(8).fill('0x2fcb7a88'),
            ZERO_BYTES32,
            '0x6cf9d042ade5de78bed9ffd075eb4b2a4f6b1736932c2dc8af517d6e066f51f5',
          );
        });

        it('proposer can schedule', async function () {
          const receipt = await this.timelock.scheduleBatch(
            this.operation.targets,
            this.operation.values,
            this.operation.datas,
            this.operation.predecessor,
            this.operation.salt,
            MINDELAY,
            { from: proposer },
          );
          for (const i in this.operation.targets) {
            expectEvent(receipt, 'CallScheduled', {
              id: this.operation.id,
              index: web3.utils.toBN(i),
              target: this.operation.targets[i],
              value: web3.utils.toBN(this.operation.values[i]),
              data: this.operation.datas[i],
              predecessor: this.operation.predecessor,
              delay: MINDELAY,
            });
          }

          const block = await web3.eth.getBlock(receipt.receipt.blockHash);

          expect(await this.timelock.getTimestamp(this.operation.id))
            .to.be.bignumber.equal(web3.utils.toBN(block.timestamp).add(MINDELAY));
        });

        it('prevent overwritting active operation', async function () {
          await this.timelock.scheduleBatch(
            this.operation.targets,
            this.operation.values,
            this.operation.datas,
            this.operation.predecessor,
            this.operation.salt,
            MINDELAY,
            { from: proposer },
          );

          await expectRevert(
            this.timelock.scheduleBatch(
              this.operation.targets,
              this.operation.values,
              this.operation.datas,
              this.operation.predecessor,
              this.operation.salt,
              MINDELAY,
              { from: proposer },
            ),
            'TimelockController: operation already scheduled',
          );
        });

        it('length of batch parameter must match #1', async function () {
          await expectRevert(
            this.timelock.scheduleBatch(
              this.operation.targets,
              [],
              this.operation.datas,
              this.operation.predecessor,
              this.operation.salt,
              MINDELAY,
              { from: proposer },
            ),
            'TimelockController: length mismatch',
          );
        });

        it('length of batch parameter must match #1', async function () {
          await expectRevert(
            this.timelock.scheduleBatch(
              this.operation.targets,
              this.operation.values,
              [],
              this.operation.predecessor,
              this.operation.salt,
              MINDELAY,
              { from: proposer },
            ),
            'TimelockController: length mismatch',
          );
        });

        it('prevent non-proposer from commiting', async function () {
          await expectRevert(
            this.timelock.scheduleBatch(
              this.operation.targets,
              this.operation.values,
              this.operation.datas,
              this.operation.predecessor,
              this.operation.salt,
              MINDELAY,
              { from: other },
            ),
            `AccessControl: account ${other.toLowerCase()} is missing role ${this.PROPOSER_ROLE}`,
          );
        });

        it('enforce minimum delay', async function () {
          await expectRevert(
            this.timelock.scheduleBatch(
              this.operation.targets,
              this.operation.values,
              this.operation.datas,
              this.operation.predecessor,
              this.operation.salt,
              MINDELAY - 1,
              { from: proposer },
            ),
            'TimelockController: insufficient delay',
          );
        });
      });

      describe('execute', function () {
        beforeEach(async function () {
          this.operation = genOperationBatch(
            Array(8).fill('0x76E53CcEb05131Ef5248553bEBDb8F70536830b1'),
            Array(8).fill(0),
            Array(8).fill('0x58a60f63'),
            ZERO_BYTES32,
            '0x9545eeabc7a7586689191f78a5532443698538e54211b5bd4d7dc0fc0102b5c7',
          );
        });

        it('revert if operation is not scheduled', async function () {
          await expectRevert(
            this.timelock.executeBatch(
              this.operation.targets,
              this.operation.values,
              this.operation.datas,
              this.operation.predecessor,
              this.operation.salt,
              { from: executor },
            ),
            'TimelockController: operation is not ready',
          );
        });

        describe('with scheduled operation', function () {
          beforeEach(async function () {
            ({ receipt: this.receipt, logs: this.logs } = await this.timelock.scheduleBatch(
              this.operation.targets,
              this.operation.values,
              this.operation.datas,
              this.operation.predecessor,
              this.operation.salt,
              MINDELAY,
              { from: proposer },
            ));
          });

          it('revert if execution comes too early 1/2', async function () {
            await expectRevert(
              this.timelock.executeBatch(
                this.operation.targets,
                this.operation.values,
                this.operation.datas,
                this.operation.predecessor,
                this.operation.salt,
                { from: executor },
              ),
              'TimelockController: operation is not ready',
            );
          });

          it('revert if execution comes too early 2/2', async function () {
            const timestamp = await this.timelock.getTimestamp(this.operation.id);
            await time.increaseTo(timestamp - 5); // -1 is to tight, test sometime fails

            await expectRevert(
              this.timelock.executeBatch(
                this.operation.targets,
                this.operation.values,
                this.operation.datas,
                this.operation.predecessor,
                this.operation.salt,
                { from: executor },
              ),
              'TimelockController: operation is not ready',
            );
          });

          describe('on time', function () {
            beforeEach(async function () {
              const timestamp = await this.timelock.getTimestamp(this.operation.id);
              await time.increaseTo(timestamp);
            });

            it('executor can reveal', async function () {
              const receipt = await this.timelock.executeBatch(
                this.operation.targets,
                this.operation.values,
                this.operation.datas,
                this.operation.predecessor,
                this.operation.salt,
                { from: executor },
              );
              for (const i in this.operation.targets) {
                expectEvent(receipt, 'CallExecuted', {
                  id: this.operation.id,
                  index: web3.utils.toBN(i),
                  target: this.operation.targets[i],
                  value: web3.utils.toBN(this.operation.values[i]),
                  data: this.operation.datas[i],
                });
              }
            });

            it('prevent non-executor from revealing', async function () {
              await expectRevert(
                this.timelock.executeBatch(
                  this.operation.targets,
                  this.operation.values,
                  this.operation.datas,
                  this.operation.predecessor,
                  this.operation.salt,
                  { from: other },
                ),
                `AccessControl: account ${other.toLowerCase()} is missing role ${this.EXECUTOR_ROLE}`,
              );
            });

            it('length mismatch #1', async function () {
              await expectRevert(
                this.timelock.executeBatch(
                  [],
                  this.operation.values,
                  this.operation.datas,
                  this.operation.predecessor,
                  this.operation.salt,
                  { from: executor },
                ),
                'TimelockController: length mismatch',
              );
            });

            it('length mismatch #2', async function () {
              await expectRevert(
                this.timelock.executeBatch(
                  this.operation.targets,
                  [],
                  this.operation.datas,
                  this.operation.predecessor,
                  this.operation.salt,
                  { from: executor },
                ),
                'TimelockController: length mismatch',
              );
            });

            it('length mismatch #3', async function () {
              await expectRevert(
                this.timelock.executeBatch(
                  this.operation.targets,
                  this.operation.values,
                  [],
                  this.operation.predecessor,
                  this.operation.salt,
                  { from: executor },
                ),
                'TimelockController: length mismatch',
              );
            });
          });
        });

        it('partial execution', async function () {
          const operation = genOperationBatch(
            [
              this.callreceivermock.address,
              this.callreceivermock.address,
              this.callreceivermock.address,
            ],
            [
              0,
              0,
              0,
            ],
            [
              this.callreceivermock.contract.methods.mockFunction().encodeABI(),
              this.callreceivermock.contract.methods.mockFunctionThrows().encodeABI(),
              this.callreceivermock.contract.methods.mockFunction().encodeABI(),
            ],
            ZERO_BYTES32,
            '0x8ac04aa0d6d66b8812fb41d39638d37af0a9ab11da507afd65c509f8ed079d3e',
          );

          await this.timelock.scheduleBatch(
            operation.targets,
            operation.values,
            operation.datas,
            operation.predecessor,
            operation.salt,
            MINDELAY,
            { from: proposer },
          );
          await time.increase(MINDELAY);
          await expectRevert(
            this.timelock.executeBatch(
              operation.targets,
              operation.values,
              operation.datas,
              operation.predecessor,
              operation.salt,
              { from: executor },
            ),
            'TimelockController: underlying transaction reverted',
          );
        });
      });
    });

    describe('cancel', function () {
      beforeEach(async function () {
        this.operation = genOperation(
          '0xC6837c44AA376dbe1d2709F13879E040CAb653ca',
          0,
          '0x296e58dd',
          ZERO_BYTES32,
          '0xa2485763600634800df9fc9646fb2c112cf98649c55f63dd1d9c7d13a64399d9',
        );
        ({ receipt: this.receipt, logs: this.logs } = await this.timelock.schedule(
          this.operation.target,
          this.operation.value,
          this.operation.data,
          this.operation.predecessor,
          this.operation.salt,
          MINDELAY,
          { from: proposer },
        ));
      });

      it('proposer can cancel', async function () {
        const receipt = await this.timelock.cancel(this.operation.id, { from: proposer });
        expectEvent(receipt, 'Cancelled', { id: this.operation.id });
      });

      it('cannot cancel invalid operation', async function () {
        await expectRevert(
          this.timelock.cancel(constants.ZERO_BYTES32, { from: proposer }),
          'TimelockController: operation cannot be cancelled',
        );
      });

      it('prevent non-proposer from canceling', async function () {
        await expectRevert(
          this.timelock.cancel(this.operation.id, { from: other }),
          `AccessControl: account ${other.toLowerCase()} is missing role ${this.PROPOSER_ROLE}`,
        );
      });
    });
  });

  describe('maintenance', function () {
    it('prevent unauthorized maintenance', async function () {
      await expectRevert(
        this.timelock.updateDelay(0, { from: other }),
        'TimelockController: caller must be timelock',
      );
    });

    it('timelock scheduled maintenance', async function () {
      const newDelay = time.duration.hours(6);
      const operation = genOperation(
        this.timelock.address,
        0,
        this.timelock.contract.methods.updateDelay(newDelay.toString()).encodeABI(),
        ZERO_BYTES32,
        '0xf8e775b2c5f4d66fb5c7fa800f35ef518c262b6014b3c0aee6ea21bff157f108',
      );

      await this.timelock.schedule(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        MINDELAY,
        { from: proposer },
      );
      await time.increase(MINDELAY);
      const receipt = await this.timelock.execute(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        { from: executor },
      );
      expectEvent(receipt, 'MinDelayChange', { newDuration: newDelay.toString(), oldDuration: MINDELAY });

      expect(await this.timelock.getMinDelay()).to.be.bignumber.equal(newDelay);
    });
  });

  describe('dependency', function () {
    beforeEach(async function () {
      this.operation1 = genOperation(
        '0xdE66bD4c97304200A95aE0AadA32d6d01A867E39',
        0,
        '0x01dc731a',
        ZERO_BYTES32,
        '0x64e932133c7677402ead2926f86205e2ca4686aebecf5a8077627092b9bb2feb',
      );
      this.operation2 = genOperation(
        '0x3c7944a3F1ee7fc8c5A5134ba7c79D11c3A1FCa3',
        0,
        '0x8f531849',
        this.operation1.id,
        '0x036e1311cac523f9548e6461e29fb1f8f9196b91910a41711ea22f5de48df07d',
      );
      await this.timelock.schedule(
        this.operation1.target,
        this.operation1.value,
        this.operation1.data,
        this.operation1.predecessor,
        this.operation1.salt,
        MINDELAY,
        { from: proposer },
      );
      await this.timelock.schedule(
        this.operation2.target,
        this.operation2.value,
        this.operation2.data,
        this.operation2.predecessor,
        this.operation2.salt,
        MINDELAY,
        { from: proposer },
      );
      await time.increase(MINDELAY);
    });

    it('cannot execute before dependency', async function () {
      await expectRevert(
        this.timelock.execute(
          this.operation2.target,
          this.operation2.value,
          this.operation2.data,
          this.operation2.predecessor,
          this.operation2.salt,
          { from: executor },
        ),
        'TimelockController: missing dependency',
      );
    });

    it('can execute after dependency', async function () {
      await this.timelock.execute(
        this.operation1.target,
        this.operation1.value,
        this.operation1.data,
        this.operation1.predecessor,
        this.operation1.salt,
        { from: executor },
      );
      await this.timelock.execute(
        this.operation2.target,
        this.operation2.value,
        this.operation2.data,
        this.operation2.predecessor,
        this.operation2.salt,
        { from: executor },
      );
    });
  });

  describe('usage scenario', function () {
    this.timeout(10000);

    it('call', async function () {
      const operation = genOperation(
        this.implementation2.address,
        0,
        this.implementation2.contract.methods.setValue(42).encodeABI(),
        ZERO_BYTES32,
        '0x8043596363daefc89977b25f9d9b4d06c3910959ef0c4d213557a903e1b555e2',
      );

      await this.timelock.schedule(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        MINDELAY,
        { from: proposer },
      );
      await time.increase(MINDELAY);
      await this.timelock.execute(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        { from: executor },
      );

      expect(await this.implementation2.getValue()).to.be.bignumber.equal(web3.utils.toBN(42));
    });

    it('call reverting', async function () {
      const operation = genOperation(
        this.callreceivermock.address,
        0,
        this.callreceivermock.contract.methods.mockFunctionRevertsNoReason().encodeABI(),
        ZERO_BYTES32,
        '0xb1b1b276fdf1a28d1e00537ea73b04d56639128b08063c1a2f70a52e38cba693',
      );

      await this.timelock.schedule(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        MINDELAY,
        { from: proposer },
      );
      await time.increase(MINDELAY);
      await expectRevert(
        this.timelock.execute(
          operation.target,
          operation.value,
          operation.data,
          operation.predecessor,
          operation.salt,
          { from: executor },
        ),
        'TimelockController: underlying transaction reverted',
      );
    });

    it('call throw', async function () {
      const operation = genOperation(
        this.callreceivermock.address,
        0,
        this.callreceivermock.contract.methods.mockFunctionThrows().encodeABI(),
        ZERO_BYTES32,
        '0xe5ca79f295fc8327ee8a765fe19afb58f4a0cbc5053642bfdd7e73bc68e0fc67',
      );

      await this.timelock.schedule(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        MINDELAY,
        { from: proposer },
      );
      await time.increase(MINDELAY);
      await expectRevert(
        this.timelock.execute(
          operation.target,
          operation.value,
          operation.data,
          operation.predecessor,
          operation.salt,
          { from: executor },
        ),
        'TimelockController: underlying transaction reverted',
      );
    });

    it('call out of gas', async function () {
      const operation = genOperation(
        this.callreceivermock.address,
        0,
        this.callreceivermock.contract.methods.mockFunctionOutOfGas().encodeABI(),
        ZERO_BYTES32,
        '0xf3274ce7c394c5b629d5215723563a744b817e1730cca5587c567099a14578fd',
      );

      await this.timelock.schedule(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        MINDELAY,
        { from: proposer },
      );
      await time.increase(MINDELAY);
      await expectRevert(
        this.timelock.execute(
          operation.target,
          operation.value,
          operation.data,
          operation.predecessor,
          operation.salt,
          { from: executor, gas: '70000' },
        ),
        'TimelockController: underlying transaction reverted',
      );
    });

    it('call payable with eth', async function () {
      const operation = genOperation(
        this.callreceivermock.address,
        1,
        this.callreceivermock.contract.methods.mockFunction().encodeABI(),
        ZERO_BYTES32,
        '0x5ab73cd33477dcd36c1e05e28362719d0ed59a7b9ff14939de63a43073dc1f44',
      );

      await this.timelock.schedule(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        MINDELAY,
        { from: proposer },
      );
      await time.increase(MINDELAY);

      expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0));
      expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0));

      await this.timelock.execute(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        { from: executor, value: 1 },
      );

      expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0));
      expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(1));
    });

    it('call nonpayable with eth', async function () {
      const operation = genOperation(
        this.callreceivermock.address,
        1,
        this.callreceivermock.contract.methods.mockFunctionNonPayable().encodeABI(),
        ZERO_BYTES32,
        '0xb78edbd920c7867f187e5aa6294ae5a656cfbf0dea1ccdca3751b740d0f2bdf8',
      );

      await this.timelock.schedule(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        MINDELAY,
        { from: proposer },
      );
      await time.increase(MINDELAY);

      expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0));
      expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0));

      await expectRevert(
        this.timelock.execute(
          operation.target,
          operation.value,
          operation.data,
          operation.predecessor,
          operation.salt,
          { from: executor },
        ),
        'TimelockController: underlying transaction reverted',
      );

      expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0));
      expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0));
    });

    it('call reverting with eth', async function () {
      const operation = genOperation(
        this.callreceivermock.address,
        1,
        this.callreceivermock.contract.methods.mockFunctionRevertsNoReason().encodeABI(),
        ZERO_BYTES32,
        '0xdedb4563ef0095db01d81d3f2decf57cf83e4a72aa792af14c43a792b56f4de6',
      );

      await this.timelock.schedule(
        operation.target,
        operation.value,
        operation.data,
        operation.predecessor,
        operation.salt,
        MINDELAY,
        { from: proposer },
      );
      await time.increase(MINDELAY);

      expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0));
      expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0));

      await expectRevert(
        this.timelock.execute(
          operation.target,
          operation.value,
          operation.data,
          operation.predecessor,
          operation.salt,
          { from: executor },
        ),
        'TimelockController: underlying transaction reverted',
      );

      expect(await web3.eth.getBalance(this.timelock.address)).to.be.bignumber.equal(web3.utils.toBN(0));
      expect(await web3.eth.getBalance(this.callreceivermock.address)).to.be.bignumber.equal(web3.utils.toBN(0));
    });
  });
});


text:
<?php

namespace PayMaya\Test\API;

use PayMaya\API\Customization;

class CustomizationTest extends \PHPUnit_Framework_TestCase
{
	public static function getObject()
	{
		$customization = new Customization();
		$customization->logoUrl = "https://cdn.paymaya.com/production/checkout_api/customization_example/yourlogo.svg";
		$customization->iconUrl = "https://cdn.paymaya.com/production/checkout_api/customization_example/youricon.ico";
		$customization->appleTouchIconUrl = "https://cdn.paymaya.com/production/checkout_api/customization_example/youricon_ios.ico";
		$customization->customTitle = "Checkout Page Title";
		$customization->colorScheme = "#368d5c";
		return $customization;
	}

	public function testRemove()
	{
		$obj = self::getObject();
		$obj->remove();
		$this->assertNull($obj->logoUrl);
		$this->assertNull($obj->iconUrl);
		$this->assertNull($obj->appleTouchIconUrl);
		$this->assertNull($obj->customTitle);
		$this->assertNull($obj->colorScheme);
	}

	public function testInitialization()
	{
		$obj = self::getObject();
		$this->assertEquals($obj->logoUrl, "https://cdn.paymaya.com/production/checkout_api/customization_example/yourlogo.svg");
		$this->assertEquals($obj->iconUrl, "https://cdn.paymaya.com/production/checkout_api/customization_example/youricon.ico");
		$this->assertEquals($obj->appleTouchIconUrl, "https://cdn.paymaya.com/production/checkout_api/customization_example/youricon_ios.ico");
		$this->assertEquals($obj->customTitle, "Checkout Page Title");
		$this->assertEquals($obj->colorScheme, "#368d5c");
		return $obj;
	}

	/**
	 * @depends testInitialization
	 */
	public function testSet($obj)
	{
		$obj->set();
		$this->assertEquals($obj->logoUrl, "https://cdn.paymaya.com/production/checkout_api/customization_example/yourlogo.svg");
		$this->assertEquals($obj->iconUrl, "https://cdn.paymaya.com/production/checkout_api/customization_example/youricon.ico");
		$this->assertEquals($obj->appleTouchIconUrl, "https://cdn.paymaya.com/production/checkout_api/customization_example/youricon_ios.ico");
		$this->assertEquals($obj->customTitle, "Checkout Page Title");
		$this->assertEquals($obj->colorScheme, "#368d5c");
		return $obj;
	}

	/**
	 * @depends testSet
	 */
	public function testGet($obj)
	{
		$obj->get();
		$this->assertEquals($obj->logoUrl, "https://cdn.paymaya.com/production/checkout_api/customization_example/yourlogo.svg");
		$this->assertEquals($obj->iconUrl, "https://cdn.paymaya.com/production/checkout_api/customization_example/youricon.ico");
		$this->assertEquals($obj->appleTouchIconUrl, "https://cdn.paymaya.com/production/checkout_api/customization_example/youricon_ios.ico");
		$this->assertEquals($obj->customTitle, "Checkout Page Title");
		$this->assertEquals($obj->colorScheme, "#368d5c");
		return $obj;
	}
}

redpajama_set_name: RedPajamaGithub


text:
package gov.hhs.fha.nhinc.connectmgr.nhinendpointmanager;

import static org.junit.Assert.assertTrue;

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

import org.junit.Test;

import gov.hhs.fha.nhinc.nhinclib.NhincConstants.GATEWAY_API_LEVEL;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants.NHIN_SERVICE_NAMES;
import gov.hhs.fha.nhinc.nhinclib.NhincConstants.UDDI_SPEC_VERSION;

/**
 * @author mweaver
 *
 */
public class PDNhinEndpointManagerMockTest extends AbstractNhinEndpointManagerMockTest {

    /*-----------------Setup Methods---------------*/

    @Override
    protected NHIN_SERVICE_NAMES getService() {
        return NHIN_SERVICE_NAMES.PATIENT_DISCOVERY;
    }

    /**
     * Setup expectations for 1.0 specs
     */
    @Override
    protected void set2010Expectations() {
        expectConnectionManagerCache10();
    }

    /**
     * Setup expectations for 2.0 specs
     */
    @Override
    protected void set2011Expectations() {
        expectConnectionManagerCache20();
    }

    /**
     * Setup for both PD specs
     */
    @Override
    protected void expectConnectionManagerCacheBoth() {
        List<UDDI_SPEC_VERSION> list = new ArrayList<UDDI_SPEC_VERSION>();
        list.add(UDDI_SPEC_VERSION.SPEC_1_0);
        list.add(UDDI_SPEC_VERSION.SPEC_2_0);

        expectConnectionManagerCache(list);
    }

    protected void expectConnectionManagerCacheMisconfiguration() {
        List<UDDI_SPEC_VERSION> list = new ArrayList<UDDI_SPEC_VERSION>();
        list.add(UDDI_SPEC_VERSION.SPEC_3_0);

        expectConnectionManagerCache(list);
    }

    /**
     * Test misconfigured target
     */
    @Test
    public void testTargetIsMisconfigured() {
        expectConnectionManagerCacheMisconfiguration();

        GATEWAY_API_LEVEL level = mockNhinEndpointManager.getApiVersion(HCID, getService());
        assertTrue(level == GATEWAY_API_LEVEL.LEVEL_g1);
        context.assertIsSatisfied();
    }

}


text:
using System;

using JetBrains.Annotations;

using Tauco.Dicom.Shared;

namespace Tauco.Dicom.Network
{
    /// <summary>
    /// Provides method for creating new instance of <see cref="DicomQuery{TInfo}" />.
    /// </summary>
    /// <typeparam name="TInfo">Dicom info type the <see cref="DicomQuery{TInfo}" /> should be created for</typeparam>
    internal class DicomQueryProvider<TInfo> : IDicomQueryProvider<TInfo> where TInfo : IDicomInfo, new()
    {
        private readonly IGeneralizedInfoProvider mGeneralizedInfoProvider;
        private readonly IDicomDataLoader<TInfo> mDicomDataLoader;

        /// <summary>
        /// Initializes new instance of <see cref="DicomQueryProvider{TInfo}" />
        /// </summary>
        /// <param name="generalizedInfoProvider">Provides method for obtaining single instance of every implementation of <see cref="IDicomInfo"/></param>
        /// <param name="dicomDataLoader"></param>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="generalizedInfoProvider"/> is <see langword="null" /> -or-
        /// <paramref name="dicomDataLoader"/> is <see langword="null" />
        /// </exception>
        public DicomQueryProvider([NotNull] IGeneralizedInfoProvider generalizedInfoProvider, [NotNull] IDicomDataLoader<TInfo> dicomDataLoader)
        {
            if (generalizedInfoProvider == null)
            {
                throw new ArgumentNullException(nameof(generalizedInfoProvider));
            }

            if (dicomDataLoader == null)
            {
                throw new ArgumentNullException(nameof(dicomDataLoader));
            }

            mGeneralizedInfoProvider = generalizedInfoProvider;
            mDicomDataLoader = dicomDataLoader;
        }

        /// <summary>
        /// Gets new instance of <see cref="DicomQuery{TInfo}"/>.
        /// </summary>
        /// <returns>New instance of <see cref="DicomQuery{TInfo}"/></returns>
        public DicomQuery<TInfo> GetDicomQuery()
        {
            return new DicomQuery<TInfo>(mGeneralizedInfoProvider, mDicomDataLoader, new WhereCollection<TInfo>(new DicomMapping(typeof(TInfo))));
        }
    }
}


text:
{% extends "account_base.html" %}
{% block title %}Connected Accounts{% endblock %}

{% block head %}
{% load socialaccount %}

{% endblock%}

{% block content %}
{% load get_last_message %}

								// ExampleSite

		{% if form.accounts %}

				Connected Accounts

			<form class = "ui large form disconnect" method="post" action="{% url 'socialaccount_connections' %}">
				{% csrf_token %}

					{% for base_account in form.accounts reversed %}
					{% with base_account.get_provider_account as account %}

								<input id="id_account_{{ base_account.id }}" type="radio" name="account" value="{{ base_account.id }}"/>

									{% if base_account.provider == 'patreon'%}

									{% elif base_account.provider == 'facebook' %}

									{% endif %}
									{{ account.account.date_joined }}

					{% endwith %}
					{% endfor %}

				<button type="submit">Disconnect</button>
			</form>
			{% with messages|get_last_message as last_message %}
			{% if form.non_field_errors or last_message and last_message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}

					{% if last_message and last_message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}

{{ last_message }}

					{% endif %}

					{% for error in form.non_field_errors %}

{{ error }}

					{% endfor %}

			{% endif %}
			{% endwith %}

		{% elif messages %}
		{% with messages|get_last_message as last_message %}
		{% if last_message.level == DEFAULT_MESSAGE_LEVELS.ERROR %}

{{ last_message }}

		{% endif %}
		{% endwith %}
		{% endif %}

				Connect an account

						Patreon

						facebook

	      Change password

{% endblock %}


text:
var validator = require('utils/validator');

App.MainAlertDefinitionDetailsController = Em.Controller.extend({

  name: 'mainAlertDefinitionDetailsController',

  alerts: function () {
    return App.AlertInstanceLocal.find().toArray()
        .filterProperty('definitionId', this.get('content.id'));
  }.property('App.router.mainAlertInstancesController.isLoaded', 'App.router.mainAlertInstancesController.reload'),

  // stores object with editing form data (label)
  editing: Em.Object.create({
    label: Em.Object.create({
      name: 'label',
      isEditing: false,
      value: '',
      originalValue: '',
      isError: false,
      bindingValue: 'content.label'
    })
  }),

  /**
   * Host to count of alerts on this host during last day map
   * @type {Object}
   */
  lastDayAlertsCount: null,

  /**
   * List of all group names related to alert definition
   * @type {Array}
   */
  groupsList: Em.computed.mapBy('content.groups', 'displayName'),

  /**
   * Validation function to define if label field populated correctly
   * @method labelValidation
   */
  labelValidation: function () {
    this.set('editing.label.isError', !this.get('editing.label.value').trim());
  }.observes('editing.label.value'),

  /**
   * Set init values for variables
   */
  clearStep: function () {
    var editing = this.get('editing');
    Em.keys(editing).forEach(function (key) {
      editing.get(key).set('isEditing', false);
    });
  },

  /**
   * Load alert instances for current alertDefinition
   * Start updating loaded data
   * @method loadAlertInstances
   */
  loadAlertInstances: function () {
    App.router.get('mainAlertInstancesController').loadAlertInstancesByAlertDefinition(this.get('content.id'));
    App.router.set('mainAlertInstancesController.isUpdating', true);
    this.loadAlertInstancesHistory();
  },

  /**
   * Load alert instances history data
   * used to count instances number of the last 24 hour
   * @method loadAlertInstancesHistory
   */
  loadAlertInstancesHistory: function () {
    this.set('lastDayAlertsCount', null);
    return App.ajax.send({
      name: 'alerts.get_instances_history',
      sender: this,
      data: {
        definitionName: this.get('content.name'),
        timestamp: App.dateTime() - 86400000 // timestamp for time 24-hours ago
      },
      success: 'loadAlertInstancesHistorySuccess'
    });
  },

  /**
   * Success-callback for loadAlertInstancesHistory
   */
  loadAlertInstancesHistorySuccess: function (data) {
    var lastDayAlertsCount = {};
    data.items.forEach(function (alert) {
      if (!lastDayAlertsCount[alert.AlertHistory.host_name]) {
        lastDayAlertsCount[alert.AlertHistory.host_name] = 1;
      } else {
        lastDayAlertsCount[alert.AlertHistory.host_name] += 1;
      }
    });
    this.set('lastDayAlertsCount', lastDayAlertsCount);
  },

  /**
   * Edit button handler
   * @param {object} event
   * @method edit
   */
  edit: function (event) {
    var element = event.context;
    var value = this.get(element.get('bindingValue'));
    element.set('originalValue', value);
    element.set('value', value);
    element.set('isEditing', true);
  },

  /**
   * Cancel button handler
   * @param {object} event
   * @method cancelEdit
   */
  cancelEdit: function (event) {
    var element = event.context;
    element.set('value', element.get('originalValue'));
    element.set('isEditing', false);
  },

  /**
   * Save button handler, could save label of alert definition
   * @param {object} event
   * @returns {$.ajax}
   * @method saveEdit
   */
  saveEdit: function (event) {
    var element = event.context;
    this.set(element.get('bindingValue'), element.get('value'));
    element.set('isEditing', false);

    var data = Em.Object.create({});
    var property_name = "AlertDefinition/" + element.get('name');
    data.set(property_name, element.get('value'));
    var alertDefinition_id = this.get('content.id');
    return App.ajax.send({
      name: 'alerts.update_alert_definition',
      sender: this,
      data: {
        id: alertDefinition_id,
        data: data
      }
    });
  },

  /**
   * Onclick handler for save button on Save popup
   * Save changes of label and configs
   */
  saveLabelAndConfigs: function () {
    var configsController = App.router.get('mainAlertDefinitionConfigsController');
    if (configsController.get('canEdit')) {
      configsController.saveConfigs();
    }
    if (this.get('editing.label.isEditing')) {
      this.saveEdit({
        context: this.get('editing.label')
      });
    }
  },

  /**
   * "Delete" button handler
   * @param {object} event
   * @method deleteAlertDefinition
   */
  deleteAlertDefinition: function (event) {
    var alertDefinition = this.get('content');
    var self = this;
    App.showConfirmationPopup(function () {
      App.ajax.send({
        name: 'alerts.delete_alert_definition',
        sender: self,
        success: 'deleteAlertDefinitionSuccess',
        error: 'deleteAlertDefinitionError',
        data: {
          id: alertDefinition.get('id')
        }
      });
    }, null, function () {
    });
  },

  /**
   * Success-callback for deleteAlertDefinition
   * @method deleteAlertDefinitionSuccess
   */
  deleteAlertDefinitionSuccess: function () {
    App.router.transitionTo('main.alerts.index');
  },

  /**
   * Error-callback for deleteAlertDefinition
   * @method deleteAlertDefinitionError
   */
  deleteAlertDefinitionError: function (xhr, textStatus, errorThrown, opt) {
    xhr.responseText = "{\"message\": \"" + xhr.statusText + "\"}";
    App.ajax.defaultErrorHandler(xhr, opt.url, 'DELETE', xhr.status);
  },

  /**
   * "Disable / Enable" button handler
   * @method toggleState
   */
  toggleState: function () {
    var alertDefinition = this.get('content');
    var self = this;
    var bodyMessage = Em.Object.create({
      confirmMsg: alertDefinition.get('enabled') ? Em.I18n.t('alerts.table.state.enabled.confirm.msg') : Em.I18n.t('alerts.table.state.disabled.confirm.msg'),
      confirmButton: alertDefinition.get('enabled') ? Em.I18n.t('alerts.table.state.enabled.confirm.btn') : Em.I18n.t('alerts.table.state.disabled.confirm.btn')
    });

    return App.showConfirmationFeedBackPopup(function (query) {
      self.toggleDefinitionState(alertDefinition);
    }, bodyMessage);
  },

  /**
   * Enable/disable alertDefinition
   * @param {object} alertDefinition
   * @param {string} property
   * @returns {$.ajax}
   * @method toggleDefinitionState
   */
  toggleDefinitionState: function (alertDefinition) {
    var newState = !alertDefinition.get('enabled');
    alertDefinition.set('enabled', newState);
    return App.ajax.send({
      name: 'alerts.update_alert_definition',
      sender: this,
      data: {
        id: alertDefinition.get('id'),
        data: {
          "AlertDefinition/enabled": newState
        }
      }
    });
  },

  globalAlertsRepeatTolerance: function () {
    return App.router.get('clusterController.clusterEnv.properties.alerts_repeat_tolerance') || "1";
  }.property('App.router.clusterController.clusterEnv'),

  enableRepeatTolerance: function (enable) {
    var alertDefinition = this.get('content');
    alertDefinition.set('repeat_tolerance_enabled', enable);
    return App.ajax.send({
      name: 'alerts.update_alert_definition',
      sender: this,
      data: {
        id: alertDefinition.get('id'),
        data: {
          "AlertDefinition/repeat_tolerance_enabled": enable
        }
      }
    });
  },

  editRepeatTolerance: function () {
    var self = this;
    var alertDefinition = this.get('content');

    var alertsRepeatTolerance = App.router.get('clusterController.clusterEnv.properties.alerts_repeat_tolerance') || "1";

    return App.ModalPopup.show({
      classNames: ['fourty-percent-width-modal'],
      header: Em.I18n.t('alerts.actions.editRepeatTolerance.header'),
      primary: Em.I18n.t('common.save'),
      secondary: Em.I18n.t('common.cancel'),
      inputValue: self.get('content.repeat_tolerance_enabled') ? (self.get('content.repeat_tolerance') || 1) : alertsRepeatTolerance,
      errorMessage: Em.I18n.t('alerts.actions.editRepeatTolerance.error'),
      isInvalid: function () {
        var intValue = Number(this.get('inputValue'));
        return this.get('inputValue') !== 'DEBUG' && (!validator.isValidInt(intValue) || intValue < 1 || intValue > 99);
      }.property('inputValue'),
      isChanged: function () {
        return Number(this.get('inputValue')) != alertsRepeatTolerance;
      }.property('inputValue'),
      doRestoreDefaultValue: function () {
        this.set('inputValue', alertsRepeatTolerance);
        this.$('[data-toggle=tooltip]').tooltip('destroy');
      },
      disablePrimary: Em.computed.alias('isInvalid'),
      onPrimary: function () {
        if (this.get('isInvalid')) {
          return;
        }
        var input = this.get('inputValue');
        self.set('content.repeat_tolerance', input);
        self.enableRepeatTolerance(input != alertsRepeatTolerance);
        App.ajax.send({
          name: 'alerts.update_alert_definition',
          sender: self,
          data: {
            id: alertDefinition.get('id'),
            data: {
              "AlertDefinition/repeat_tolerance": input
            }
          }
        });
        this.hide();
      },
      didInsertElement: function () {
        this._super();
        App.tooltip(this.$('[data-toggle=tooltip]'));
      },
      bodyClass: Ember.View.extend({
        templateName: require('templates/common/modal_popups/prompt_popup'),
        title: Em.I18n.t('alerts.actions.editRepeatTolerance.title'),
        description: Em.I18n.t('alerts.actions.editRepeatTolerance.description'),
        label: Em.I18n.t('alerts.actions.editRepeatTolerance.label')
      })
    });
  },

  /**
   * Define if label or configs are in edit mode
   * @type {Boolean}
   */
  isEditing: Em.computed.or('editing.label.isEditing', 'App.router.mainAlertDefinitionConfigsController.canEdit'),

  /**
   * If some configs or label are changed and user navigates away, show this popup with propose to save changes
   * @param {String} path
   * @method showSavePopup
   */
  showSavePopup: function (callback) {
    var self = this;
    return App.ModalPopup.show({
      header: Em.I18n.t('common.warning'),
      bodyClass: Em.View.extend({
        template: Ember.Handlebars.compile('{{t alerts.saveChanges}}')
      }),
      primary: Em.I18n.t('common.save'),
      secondary: Em.I18n.t('common.discard'),
      third: Em.I18n.t('common.cancel'),
      disablePrimary: Em.computed.or('App.router.mainAlertDefinitionDetailsController.editing.label.isError', 'App.router.mainAlertDefinitionConfigsController.hasErrors'),
      onPrimary: function () {
        self.saveLabelAndConfigs();
        callback();
        this.hide();
      },
      onSecondary: function () {
        callback();
        this.hide();
      },
      onThird: function () {
        this.hide();
      }
    });
  }

});


text:
package org.darkphoenixs.pool.redis;

import org.apache.commons.pool2.impl.DefaultPooledObject;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import redis.clients.jedis.HostAndPort;
import redis.clients.jedis.Jedis;

import java.io.IOException;
import java.net.ServerSocket;
import java.util.Properties;

public class RedisConnectionFactoryOldTest {

    @Before
    public void before() throws Exception {

        Thread th = new Thread(new Runnable() {

            private ServerSocket serverSocket;

            @Override
            public void run() {

                try {
                    serverSocket = new ServerSocket(RedisConfig.DEFAULT_PORT);

                    serverSocket.accept();

                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });

        th.setDaemon(true);

        th.start();
    }

    @Test
    public void test_0() throws Exception {

        Properties prop = new Properties();

        RedisConnectionFactoryOld factory;

        try {
            factory = new RedisConnectionFactoryOld(prop);

        } catch (Exception e) {
        }

        prop.setProperty(RedisConfig.ADDRESS_PROPERTY, RedisConfig.DEFAULT_HOST
                + ":" + RedisConfig.DEFAULT_PORT);
        prop.setProperty(RedisConfig.CONN_TIMEOUT_PROPERTY,
                RedisConfig.DEFAULT_TIMEOUT + "");
        prop.setProperty(RedisConfig.SO_TIMEOUT_PROPERTY,
                RedisConfig.DEFAULT_TIMEOUT + "");
        prop.setProperty(RedisConfig.DATABASE_PROPERTY,
                RedisConfig.DEFAULT_DATABASE + "");
        prop.setProperty(RedisConfig.CLIENTNAME_PROPERTY, "Test");
        prop.setProperty(RedisConfig.PASSWORD_PROPERTY, "Test");

        factory = new RedisConnectionFactoryOld(prop);

        factory = new RedisConnectionFactoryOld(RedisConfig.DEFAULT_HOST, 1233,
                RedisConfig.DEFAULT_TIMEOUT, RedisConfig.DEFAULT_TIMEOUT,
                "Test", 1, "Test");

        factory.setHostAndPort(new HostAndPort(RedisConfig.DEFAULT_HOST,
                RedisConfig.DEFAULT_PORT));

        try {
            factory.makeObject();

        } catch (Exception e) {
        }

        try {
            factory.activateObject(new DefaultPooledObject<Jedis>(null));
        } catch (Exception e) {
        }

        try {
            factory.validateObject(new DefaultPooledObject<Jedis>(null));
        } catch (Exception e) {
        }

        try {
            factory.passivateObject(new DefaultPooledObject<Jedis>(null));
        } catch (Exception e) {
        }

        try {
            factory.destroyObject(new DefaultPooledObject<Jedis>(null));
        } catch (Exception e) {
        }
    }

    @Test
    public void test_1() throws Exception {

        RedisConnectionFactoryOld factory = new RedisConnectionFactoryOld(
                RedisConfig.DEFAULT_HOST, RedisConfig.DEFAULT_PORT,
                RedisConfig.DEFAULT_TIMEOUT, RedisConfig.DEFAULT_TIMEOUT,
                RedisConfig.DEFAULT_PASSWORD, RedisConfig.DEFAULT_DATABASE,
                RedisConfig.DEFAULT_CLIENTNAME);

        factory.validateObject(new DefaultPooledObject<Jedis>(factory
                .makeObject().getObject()));

        factory.destroyObject(new DefaultPooledObject<Jedis>(factory
                .makeObject().getObject()));
    }

    @Test
    public void test_2() throws Exception {

        RedisConnectionFactoryOld factory = new RedisConnectionFactoryOld(
                RedisConfig.DEFAULT_HOST, RedisConfig.DEFAULT_PORT,
                RedisConfig.DEFAULT_TIMEOUT, RedisConfig.DEFAULT_TIMEOUT,
                RedisConfig.DEFAULT_PASSWORD, RedisConfig.DEFAULT_DATABASE,
                RedisConfig.DEFAULT_CLIENTNAME);

        try {
            factory.activateObject(new DefaultPooledObject<Jedis>(new Jedis()));
        } catch (Exception e) {
        }
        try {
            factory.validateObject(new DefaultPooledObject<Jedis>(new Jedis()));
        } catch (Exception e) {
        }
        try {
            factory.passivateObject(new DefaultPooledObject<Jedis>(new Jedis()));

        } catch (Exception e) {
        }
        try {
            factory.destroyObject(new DefaultPooledObject<Jedis>(new Jedis()));
        } catch (Exception e) {
        }

        RedisConnectionFactoryOld factory2 = new RedisConnectionFactoryOld(
                RedisConfig.DEFAULT_HOST, RedisConfig.DEFAULT_PORT,
                RedisConfig.DEFAULT_TIMEOUT, RedisConfig.DEFAULT_TIMEOUT,
                RedisConfig.DEFAULT_PASSWORD, 2, RedisConfig.DEFAULT_CLIENTNAME);

        try {
            factory2.activateObject(new DefaultPooledObject<Jedis>(
                    new JedisConn(RedisConfig.DEFAULT_HOST,
                            RedisConfig.DEFAULT_PORT)));
        } catch (Exception e) {
        }

        try {
            factory2.destroyObject(new DefaultPooledObject<Jedis>(
                    new JedisConn2(RedisConfig.DEFAULT_HOST,
                            RedisConfig.DEFAULT_PORT)));
        } catch (Exception e) {
        }

        try {
            factory2.destroyObject(new DefaultPooledObject<Jedis>(
                    new JedisConn(RedisConfig.DEFAULT_HOST,
                            RedisConfig.DEFAULT_PORT)));
        } catch (Exception e) {
        }

    }

    @Test
    public void test_3() throws Exception {

        RedisConnectionFactoryOld factory3 = new RedisConnectionFactoryOld(
                "localhost", 1234, RedisConfig.DEFAULT_TIMEOUT,
                RedisConfig.DEFAULT_TIMEOUT, RedisConfig.DEFAULT_PASSWORD,
                RedisConfig.DEFAULT_DATABASE, RedisConfig.DEFAULT_CLIENTNAME);

        try {
            boolean rev = factory3
                    .validateObject(new DefaultPooledObject<Jedis>(
                            new JedisConn4("localhost", 1234)));

            Assert.assertFalse(rev);

        } catch (Exception e) {
        }

        try {
            boolean rev = factory3
                    .validateObject(new DefaultPooledObject<Jedis>(
                            new JedisConn(RedisConfig.DEFAULT_HOST, 1234)));
            Assert.assertTrue(rev);

        } catch (Exception e) {
        }

        try {
            boolean rev = factory3
                    .validateObject(new DefaultPooledObject<Jedis>(
                            new JedisConn2(RedisConfig.DEFAULT_HOST, 1233)));
            Assert.assertFalse(rev);

        } catch (Exception e) {
        }

        try {
            boolean rev = factory3
                    .validateObject(new DefaultPooledObject<Jedis>(
                            new JedisConn3("localhost", 1234)));

            Assert.assertFalse(rev);

        } catch (Exception e) {
        }

        try {
            boolean rev = factory3
                    .validateObject(new DefaultPooledObject<Jedis>(
                            new JedisConn3("1.1.1.1", 1234)));

            Assert.assertFalse(rev);

        } catch (Exception e) {
        }

    }

    @Test
    public void test_4() throws Exception {

        RedisConnectionFactoryOld factory = new RedisConnectionFactoryOld(
                RedisConfig.DEFAULT_HOST, RedisConfig.DEFAULT_PORT,
                RedisConfig.DEFAULT_TIMEOUT, RedisConfig.DEFAULT_TIMEOUT,
                "test", RedisConfig.DEFAULT_DATABASE,
                RedisConfig.DEFAULT_CLIENTNAME);
        try {
            factory.makeObject();
        } catch (Exception e) {
        }

        factory = new RedisConnectionFactoryOld(RedisConfig.DEFAULT_HOST,
                RedisConfig.DEFAULT_PORT, RedisConfig.DEFAULT_TIMEOUT,
                RedisConfig.DEFAULT_TIMEOUT, RedisConfig.DEFAULT_PASSWORD, 3,
                RedisConfig.DEFAULT_CLIENTNAME);
        try {
            factory.makeObject();
        } catch (Exception e) {
        }

        factory = new RedisConnectionFactoryOld(RedisConfig.DEFAULT_HOST,
                RedisConfig.DEFAULT_PORT, RedisConfig.DEFAULT_TIMEOUT,
                RedisConfig.DEFAULT_TIMEOUT, RedisConfig.DEFAULT_PASSWORD,
                RedisConfig.DEFAULT_DATABASE, "test");
        try {
            factory.makeObject();
        } catch (Exception e) {
        }
    }
}


text:
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns:p="http://www.springframework.org/schema/p"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans-2.0.xsd">

    <bean id="ValidProtoSubTypeQual" parent="ValidProtoSubTypeQual-parentBean" />
    <bean id="ValidProtoSubTypeQual-parentBean" abstract="true" parent="BusinessObjectEntry">
        <property name="businessObjectClass" value="org.kuali.kra.irb.actions.submit.ValidProtoSubTypeQual" />
		<property name="objectLabel" value="Valid Protocol Submission Type Qualifier"/>
        <property name="inquiryDefinition" >
            <ref bean="ValidProtoSubTypeQual-inquiryDefinition" />
        </property>
        <property name="lookupDefinition" >
            <ref bean="ValidProtoSubTypeQual-lookupDefinition" />
        </property>
        <property name="titleAttribute" value="validProtoSubTypeQualId" />
        <property name="attributes" >
            <list>
                <ref bean="ValidProtoSubTypeQual-validProtoSubTypeQualId" />
                <ref bean="ValidProtoSubTypeQual-submissionTypeCode" />
                <ref bean="ValidProtoSubTypeQual-submissionTypeQualCode" />
                <ref bean="ValidProtoSubTypeQual-submissionType.description" />
                <ref bean="ValidProtoSubTypeQual-submissionTypeQualifier.description" />
                <ref bean="ValidProtoSubTypeQual-versionNumber" />
            </list>
        </property>
    </bean>

    <bean id="ValidProtoSubTypeQual-validProtoSubTypeQualId" parent="ValidProtoSubTypeQual-validProtoSubTypeQualId-parentBean" />
    <bean id="ValidProtoSubTypeQual-validProtoSubTypeQualId-parentBean" abstract="true" parent="AttributeDefinition" >
        <property name="name" value="validProtoSubTypeQualId" />
        <property name="forceUppercase" value="false" />
        <property name="label" value="Valid Proto Sub Type Qual Id" />
        <property name="shortLabel" value="Valid Proto Sub Type Qual Id" />
        <property name="maxLength" value="12" />
        <property name="validationPattern" >
            <bean parent="NumericValidationPattern" />
        </property>
        <property name="control" >
            <bean parent="TextControlDefinition"
                p:size="12" />
        </property>
        <property name="summary" value="Valid Proto Sub Type Qual Id" />
        <property name="description" value="Valid Proto Sub Type Qual Id" />
    </bean>

    <bean id="ValidProtoSubTypeQual-submissionTypeCode" parent="ValidProtoSubTypeQual-submissionTypeCode-parentBean" />
    <bean id="ValidProtoSubTypeQual-submissionTypeCode-parentBean" abstract="true" parent="AttributeDefinition" >
        <property name="name" value="submissionTypeCode" />
        <property name="forceUppercase" value="false" />
        <property name="label" value="Submission Type" />
        <property name="shortLabel" value="Submission Type" />
        <property name="maxLength" value="3" />
        <property name="validationPattern" >
            <bean parent="AlphaNumericValidationPattern" />
        </property>
        <property name="control" >
			<bean parent="SelectControlDefinition"
            	p:businessObjectClass="org.kuali.kra.irb.actions.submit.ProtocolSubmissionType"
            	p:valuesFinderClass="org.kuali.kra.lookup.keyvalue.ExtendedPersistableBusinessObjectValuesFinder"
            	p:includeKeyInLabel="false"
            	p:keyAttribute="submissionTypeCode"
            	p:labelAttribute="description" />
        </property>
        <property name="summary" value="Submission Type Code" />
        <property name="description" value="Submission Type Code" />
    </bean>

    <bean id="ValidProtoSubTypeQual-submissionTypeQualCode" parent="ValidProtoSubTypeQual-submissionTypeQualCode-parentBean" />
    <bean id="ValidProtoSubTypeQual-submissionTypeQualCode-parentBean" abstract="true" parent="AttributeDefinition" >
        <property name="name" value="submissionTypeQualCode" />
        <property name="forceUppercase" value="false" />
        <property name="label" value="Submission Type Qualifier" />
        <property name="shortLabel" value="Submission Type Qualifier" />
        <property name="maxLength" value="3" />
        <property name="validationPattern" >
            <bean parent="AlphaNumericValidationPattern" />
        </property>
        <property name="control" >
      		<bean parent="SelectControlDefinition"
            	p:businessObjectClass="org.kuali.kra.irb.actions.submit.ProtocolSubmissionQualifierType"
            	p:valuesFinderClass="org.kuali.kra.lookup.keyvalue.ExtendedPersistableBusinessObjectValuesFinder"
            	p:includeKeyInLabel="false"
            	p:keyAttribute="submissionQualifierTypeCode"
            	p:labelAttribute="description" />
        </property>
        <property name="summary" value="Submission Type Qual Code" />
        <property name="description" value="Submission Type Qual Code" />
    </bean>

 <bean id="ValidProtoSubTypeQual-submissionTypeQualifier.description" parent="ValidProtoSubTypeQual-submissionTypeQualifier.description-parentBean" />

  <bean id="ValidProtoSubTypeQual-submissionTypeQualifier.description-parentBean" abstract="true" parent="ProtocolSubmissionQualifierType-description">
    <property name="name" value="submissionTypeQualifier.description" />
    <property name="label" value="Submission Qualifier Type" />
    <property name="shortLabel" value="Submission Qualifier Type" />
  </bean>

  <bean id="ValidProtoSubTypeQual-submissionType.description" parent="ValidProtoSubTypeQual-submissionType.description-parentBean" />

  <bean id="ValidProtoSubTypeQual-submissionType.description-parentBean" abstract="true" parent="ProtocolSubmissionType-description">
    <property name="name" value="submissionType.description" />
    <property name="label" value="Submission Type" />
    <property name="shortLabel" value="Submission Type" />
 </bean>

    <bean id="ValidProtoSubTypeQual-versionNumber" parent="ValidProtoSubTypeQual-versionNumber-parentBean" />
    <bean id="ValidProtoSubTypeQual-versionNumber-parentBean" abstract="true" parent="AttributeReferenceDummy-versionNumber">
    </bean>

    <bean id="ValidProtoSubTypeQual-inquiryDefinition" parent="ValidProtoSubTypeQual-inquiryDefinition-parentBean" />
    <bean id="ValidProtoSubTypeQual-inquiryDefinition-parentBean" abstract="true" parent="InquiryDefinition">
        <property name="title" value="Valid Proto Sub Type Qual Id" />
        <property name="inquirySections" >
            <list>
                <bean parent="InquirySectionDefinition">
                    <property name="title" value="Valid Protocol Submission Type Qualifier Id" />
                    <property name="numberOfColumns" value="1" />
                    <property name="inquiryFields" >
                        <list>
                            <bean parent="FieldDefinition"
                                p:attributeName="validProtoSubTypeQualId"
                                p:forceInquiry="true" />
                            <bean parent="FieldDefinition"
                                p:attributeName="submissionTypeCode" />
                            <bean parent="FieldDefinition"
                                p:attributeName="submissionTypeQualCode" />
                        </list>
                    </property>
                </bean>
            </list>
        </property>
    </bean>

    <bean id="ValidProtoSubTypeQual-lookupDefinition" parent="ValidProtoSubTypeQual-lookupDefinition-parentBean" />
    <bean id="ValidProtoSubTypeQual-lookupDefinition-parentBean" abstract="true" parent="LookupDefinition">
        <property name="title" value="Valid Protocol Submission Type Qualifier Lookup" />
        <property name="menubar" value="Main" />
        <property name="defaultSort" >
            <bean parent="SortDefinition" >
        </bean>
        </property>
        <property name="lookupFields" >
            <list>

                <bean parent="FieldDefinition"
                    p:attributeName="submissionTypeCode" />
                <bean parent="FieldDefinition"
                    p:attributeName="submissionTypeQualCode" />
            </list>
        </property>
        <property name="resultFields" >
            <list>
                <bean parent="FieldDefinition"
                    p:attributeName="validProtoSubTypeQualId"
                    p:forceInquiry="true" />
                <bean parent="FieldDefinition"
                    p:attributeName="submissionType.description" />
                <bean parent="FieldDefinition"
                    p:attributeName="submissionTypeQualifier.description" />
            </list>
        </property>
    </bean>
</beans>


text:
<?php namespace EC\Forms;
defined('_ESPADA') or die(NO_ACCESS);

use E, EC, EC\Forms;

class VEmail extends Forms\VField
{

    public function __construct($args = [])
    {
        parent::__construct($args, [
            'required' => true
        ]);
    }

    protected function _validate(&$value)
    {
        $args = $this->getArgs();

        if ($value === '') {
            if ($args['required'])
                $this->error(EC\HText::_('Forms:fields.notSet'));

            return;
        }

        if (!filter_var($value, FILTER_VALIDATE_EMAIL))
			$this->error(EC\HText::_('Forms:fields.email_WrongFormat'));
    }

}


text:
<!DOCTYPE html>
<meta charset="utf-8">
<title>CSS Test Reference</title>
<link rel="author" title="Steinar H. Gunderson" href="mailto:sesse@chromium.org">

There should be a square with a white-to-green gradient and some text below.

This text should be green


text:
package ec;
import ec.util.*;

/*
 * ECDefaults.java
 *
 * Created: Thu Jan 20 16:49:57 2000
 * By: Sean Luke
 */

/**
 * @author Sean Luke
 * @version 1.0
 */

public final class ECDefaults implements DefaultsForm
    {
    public static final String P_EC = "ec";

    /** Returns the default base. */
    public static final Parameter base()
        {
        return new Parameter(P_EC);
        }
    }


text:
package org.apache.camel.cdi;

import java.util.concurrent.atomic.AtomicInteger;

import org.apache.camel.impl.DefaultCamelContextNameStrategy;
import org.apache.camel.spi.CamelContextNameStrategy;

/**
 * A {@link CamelContextNameStrategy} for Camel contexts that are managed by Camel CDI.
 *
 * As opposed to {@link org.apache.camel.impl.DefaultCamelContextNameStrategy},
 * this implementation does not increment the suffix for proxies that are created
 * each time a contextual reference to a normal-scoped bean is retrieved.
 *
 * It is used by Camel CDI for custom Camel context beans that do not override
 * the context name nor the naming strategy.
 *
 * @see CamelContextNameStrategy
 */
@Vetoed
final class CdiCamelContextNameStrategy extends DefaultCamelContextNameStrategy implements CamelContextNameStrategy {

    private static final AtomicInteger CONTEXT_COUNTER = new AtomicInteger(0);

    @Override
    public String getNextName() {
        return "camel" + "-" + CONTEXT_COUNTER.incrementAndGet();
    }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using QuantConnect.Algorithm.CSharp;
using QuantConnect.Indicators;
using QuantConnect.Orders;

namespace QuantConnect
{
    class MultiSymbolStrategy : BaseStrategy
    {
        #region Fields

        private decimal _tolerance;
        private decimal _revertPCT;
        private RevertPositionCheck _checkRevertPosition;

        #region made public for debug

        public bool TriggerCrossOverITrend = false;
        public bool TriggerCrossUnderITrend = false;
        public bool ExitFromLong = false;
        public bool ExitFromShort = false;

        public Indicator _price;
        public SimpleMovingAverage sma;
        public Momentum SMAMomentum;
        public RollingWindow<decimal> MomentumWindow;
        public bool IsActive = true;
        public int TradeAttempts = 0;
        public OrderStatus Status = OrderStatus.None;

        #endregion made public for debug

        #endregion Fields

        #region Constructors

        /// <summary>
        /// Initializes a new instance of the <see cref="ITrendStrategy"/> class.
        /// </summary>
        /// <param name="period">The period of the Instantaneous trend.</param>
        public MultiSymbolStrategy(Indicator price, int period, decimal tolerance = 0.001m, decimal revetPct = 1.0015m,
            RevertPositionCheck checkRevertPosition = RevertPositionCheck.vsTrigger)
        {
            _price = price;
            sma = new SimpleMovingAverage(period).Of(price);
            SMAMomentum = new Momentum(2).Of(sma);
            MomentumWindow = new RollingWindow<decimal>(2);

            Position = StockState.noInvested;
            EntryPrice = null;
            ActualSignal = OrderSignal.doNothing;

            _tolerance = tolerance;
            _revertPCT = revetPct;
            _checkRevertPosition = checkRevertPosition;

            SMAMomentum.Updated += (object sender, IndicatorDataPoint updated) =>
            {
                if (SMAMomentum.IsReady) MomentumWindow.Add(SMAMomentum.Current.Value);
                if (MomentumWindow.IsReady) CheckSignal();
            };
        }

        #endregion Constructors
        #region Methods

        /// <summary>
        /// Checks If the strategy throws a operation signal.
        /// </summary>
        /// <returns>An OrderSignal with the proper actualSignal to operate.</returns>
        public override void CheckSignal()
        {
            TriggerCrossOverITrend = MomentumWindow[1] < 0 &&
                                     MomentumWindow[0] > 0 &&
                                     Math.Abs(MomentumWindow[0] - MomentumWindow[1]) >= _tolerance;

            TriggerCrossUnderITrend = MomentumWindow[1] > 0 &&
                                      MomentumWindow[0] < 0 &&
                                      Math.Abs(MomentumWindow[0] - MomentumWindow[1]) >= _tolerance;

            if (_checkRevertPosition == RevertPositionCheck.vsTrigger)
            {
                ExitFromLong = (EntryPrice != null) ? sma + SMAMomentum < EntryPrice / _revertPCT : false;
                ExitFromShort = (EntryPrice != null) ? sma + SMAMomentum > EntryPrice * _revertPCT : false;
            }
            else if (_checkRevertPosition == RevertPositionCheck.vsClosePrice)
            {
                ExitFromLong = (EntryPrice != null) ? _price < EntryPrice / _revertPCT : false;
                ExitFromShort = (EntryPrice != null) ? _price > EntryPrice * _revertPCT : false;
            }

            OrderSignal actualSignal;

            switch (Position)
            {
                case StockState.noInvested:
                    if (TriggerCrossOverITrend) actualSignal = OrderSignal.goLongLimit;
                    else if (TriggerCrossUnderITrend) actualSignal = OrderSignal.goShortLimit;
                    else actualSignal = OrderSignal.doNothing;
                    break;

                case StockState.longPosition:
                    if (TriggerCrossUnderITrend) actualSignal = OrderSignal.closeLong;
                    else if (ExitFromLong) actualSignal = OrderSignal.revertToShort;
                    else actualSignal = OrderSignal.doNothing;
                    break;

                case StockState.shortPosition:
                    if (TriggerCrossOverITrend) actualSignal = OrderSignal.closeShort;
                    else if (ExitFromShort) actualSignal = OrderSignal.revertToLong;
                    else actualSignal = OrderSignal.doNothing;
                    break;

                default: actualSignal = OrderSignal.doNothing;
                    break;
            }
            ActualSignal = actualSignal;
        }

        public void Reset()
        {
            // Not resetting the ITrend increases returns
            sma.Reset();
            SMAMomentum.Reset();
            MomentumWindow.Reset();
        }

        #endregion Methods

    }

}


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
null

#### Original name
Melanospora arachnophila Fuckel

### Remarks
null


text:
namespace BrianChristyWedding.Migrations
{
    using System.CodeDom.Compiler;
    using System.Data.Entity.Migrations;
    using System.Data.Entity.Migrations.Infrastructure;
    using System.Resources;

    [GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
    public sealed partial class RsvpAttendingFlag : IMigrationMetadata
    {
        private readonly ResourceManager Resources = new ResourceManager(typeof(RsvpAttendingFlag));

        string IMigrationMetadata.Id
        {
            get { return "201602161644382_RsvpAttendingFlag"; }
        }

        string IMigrationMetadata.Source
        {
            get { return null; }
        }

        string IMigrationMetadata.Target
        {
            get { return Resources.GetString("Target"); }
        }
    }
}


text:
package sse

import (
	"bytes"
	"encoding/json"
	"net/http"
)

var (
	jsonNil = []byte("null")
)

// AnyEventFeed represents an event feed which does not return events
// which have their own byte marshall method.  Instead, encoding/json
// is used to marshal the events.
type AnyEventFeed interface {
	GetEventChan(clientCloseChan <-chan struct{}) <-chan interface{}
}

type jsonEncoderFeed struct {
	anyFeed   AnyEventFeed
	closeChan <-chan struct{}
}

type jsonEvent struct {
	data interface{}
}

func (je jsonEvent) GetData() ([]byte, error) {
	data, err := json.Marshal(je.data)
	if err == nil {
		if bytes.Equal(data, jsonNil) {
			return nil, nil
		}
	}
	return data, err
}

// NewJSONEncoderFeed converts an 'AnyEventFeed' to an EventFeed by
// marshalling each of the events returned via the EventFeed via
// encoding/json.
func NewJSONEncoderFeed(anyEventFeed AnyEventFeed) EventFeed {
	return &jsonEncoderFeed{
		anyFeed: anyEventFeed,
	}
}

// GetEventChan returns an SSE-compatible event feed, satisfying the EventFeed interface.
func (jea *jsonEncoderFeed) GetEventChan(clientCloseChan <-chan struct{}) <-chan SinkEvent {
	anyFeedClosedChan := make(chan struct{})
	jsonEventChan := jea.anyFeed.GetEventChan(anyFeedClosedChan)
	eventChan := make(chan SinkEvent)
	go func() {
	anyEventLoop:
		for {
			select {
			case _, ok := <-clientCloseChan:
				if !ok {
					close(anyFeedClosedChan)
					clientCloseChan = nil
				}
			case event, ok := <-jsonEventChan:
				if !ok {
					if eventChan != nil {
						close(eventChan)
						eventChan = nil
					}
					break anyEventLoop
				}
				eventChan <- &jsonEvent{event}
			}
		}
	}()
	return eventChan
}

// SinkJSONEvents is a wrapped-up handler for responding with anything
// that encoding/json can marshal, that you can happily `return` to in
// a net/http handler.
func SinkJSONEvents(w http.ResponseWriter, code int, feed AnyEventFeed) error {
	return SinkEvents(w, code, NewJSONEncoderFeed(feed))
}


text:
using DeveImageOptimizer.Helpers;
using DeveImageOptimizer.ImageOperations;
using SixLabors.ImageSharp;
using SixLabors.ImageSharp.PixelFormats;
using System;
using System.IO;
using System.Threading.Tasks;
using Xunit;

namespace DeveImageOptimizer.Tests.TestHelpers
{
    public static class ImageComparerAndWriteOutputDifferences
    {
        public static async Task<int> CompareTheseImagesAndWriteResultToOutputAsync(string image1, string image2, string investigationname, string outputImageName)
        {
            var outputDir = Path.Combine(FolderHelperMethods.Internal_TempForTestDirectory.Value, investigationname);
            Directory.CreateDirectory(outputDir);

            var outputImage = Path.Combine(outputDir, outputImageName + ".png");
            var outputImage2 = Path.Combine(outputDir, outputImageName + "2.png");

            int pixelsWrong = 0;

            using (var img1 = Image.Load<Rgba32>(image1))
            using (var img2 = Image.Load<Rgba32>(image2))
            {
                Assert.Equal(img1.Width, img2.Width);
                Assert.Equal(img1.Height, img2.Height);

                using (var outputImg = new Image<Rgba32>(img1.Width, img1.Height))
                using (var outputImg2 = new Image<Rgba32>(img1.Width, img1.Height))
                {
                    for (int y = 0; y < img1.Height; y++)
                    {
                        for (int x = 0; x < img1.Width; x++)
                        {
                            var pixel1 = img1[x, y];
                            var pixel2 = img2[x, y];

                            if (pixel1 != pixel2 && (pixel1.A != 0 || pixel2.A != 0))
                            {
                                outputImg[x, y] = new Rgba32(255, 0, 0);
                                outputImg2[x, y] = new Rgba32(255, 0, 0);
                                pixelsWrong++;
                            }
                            else
                            {
                                outputImg[x, y] = pixel1;
                                outputImg2[x, y] = new Rgba32(255, 255, 255);
                            }
                        }
                    }

                    using (var fs = new FileStream(outputImage, FileMode.Create))
                    {
                        outputImg.SaveAsPng(fs);
                    }

                    using (var fs = new FileStream(outputImage2, FileMode.Create))
                    {
                        outputImg2.SaveAsPng(fs);
                    }
                }
            }

            var imageIsEqual = await ImageComparer.AreImagesEqualAsync(image1, image2);
            //If this fails something is wrong in either the ImageEqual method or this test method
            Assert.Equal(imageIsEqual, pixelsWrong == 0);

            Console.WriteLine($"Image Comparison: Compared: {image1} to {image2} Pixels wrong: {pixelsWrong}");
            return pixelsWrong;
        }
    }
}


text:
layout: page
title: About
---

I'm a student from the UK currently working on my BA in Mathematics. In my spare time I enjoy programming, playing the piano and writing music, climbing rocks and working towards becoming an astronaut.


text:
const Content1 = () => {
  return
LazyContent1 - with Suspense
;
};

export default Content1;


text:
package com.adaptris.core.ftp;

public class FtpSslConsumerTest extends FtpConsumerCase {

  private static final String BASE_DIR_KEY = "FtpsConsumerExamples.baseDir";

  public FtpSslConsumerTest(String name) {
    super(name);
    if (PROPERTIES.getProperty(BASE_DIR_KEY) != null) {
      setBaseDir(PROPERTIES.getProperty(BASE_DIR_KEY));
    }
  }

  @Override
  protected FtpSslConnection createConnectionForExamples() {
    return FtpExampleHelper.ftpSslConnection();
  }

  @Override
  protected String getScheme() {
    return "ftps";
  }

}


text:
var initPhotoSwipeFromDOM = function(gallerySelector) {

    // parse slide data (url, title, size ...) from DOM elements
    // (children of gallerySelector)
    var parseThumbnailElements = function(el) {
        var thumbElements = el.childNodes,
            numNodes = thumbElements.length,
            items = [],
            figureEl,
            linkEl,
            size,
            item;

        for(var i = 0; i < numNodes; i++) {

            figureEl = thumbElements[i]; // <figure> element

            // include only element nodes
            if(figureEl.nodeType !== 1) {
                continue;
            }

            linkEl = figureEl.children[0]; // <a> element

            size = linkEl.getAttribute('data-size').split('x');

            // create slide object
            item = {
                src: linkEl.getAttribute('href'),
                w: parseInt(size[0], 10),
                h: parseInt(size[1], 10)
            };

            if(figureEl.children.length > 1) {
                // <figcaption> content
                item.title = figureEl.children[1].innerHTML;
            }

            if(linkEl.children.length > 0) {
                // <img> thumbnail element, retrieving thumbnail url
                item.msrc = linkEl.children[0].getAttribute('src');
            }

            item.el = figureEl; // save link to element for getThumbBoundsFn
            items.push(item);
        }

        return items;
    };

    // find nearest parent element
    var closest = function closest(el, fn) {
        return el && ( fn(el) ? el : closest(el.parentNode, fn) );
    };

    // triggers when user clicks on thumbnail
    var onThumbnailsClick = function(e) {
        e = e || window.event;
        e.preventDefault ? e.preventDefault() : e.returnValue = false;

        var eTarget = e.target || e.srcElement;

        // find root element of slide
        var clickedListItem = closest(eTarget, function(el) {
            return (el.tagName && el.tagName.toUpperCase() === 'FIGURE');
        });

        if(!clickedListItem) {
            return;
        }

        // find index of clicked item by looping through all child nodes
        // alternatively, you may define index via data- attribute
        var clickedGallery = clickedListItem.parentNode,
            childNodes = clickedListItem.parentNode.childNodes,
            numChildNodes = childNodes.length,
            nodeIndex = 0,
            index;

        for (var i = 0; i < numChildNodes; i++) {
            if(childNodes[i].nodeType !== 1) {
                continue;
            }

            if(childNodes[i] === clickedListItem) {
                index = nodeIndex;
                break;
            }
            nodeIndex++;
        }

        if(index >= 0) {
            // open PhotoSwipe if valid index found
            openPhotoSwipe( index, clickedGallery );
        }
        return false;
    };

    // parse picture index and gallery index from URL (#&pid=1&gid=2)
    var photoswipeParseHash = function() {
        var hash = window.location.hash.substring(1),
        params = {};

        if(hash.length < 5) {
            return params;
        }

        var vars = hash.split('&');
        for (var i = 0; i < vars.length; i++) {
            if(!vars[i]) {
                continue;
            }
            var pair = vars[i].split('=');
            if(pair.length < 2) {
                continue;
            }
            params[pair[0]] = pair[1];
        }

        if(params.gid) {
            params.gid = parseInt(params.gid, 10);
        }

        return params;
    };

    var openPhotoSwipe = function(index, galleryElement, disableAnimation, fromURL) {
        var pswpElement = document.querySelectorAll('.pswp')[0],
            gallery,
            options,
            items;

        items = parseThumbnailElements(galleryElement);

        // define options (if needed)
        options = {

            // define gallery index (for URL)
            galleryUID: galleryElement.getAttribute('data-pswp-uid'),

            getThumbBoundsFn: function(index) {
                // See Options -> getThumbBoundsFn section of documentation for more info
                var thumbnail = items[index].el.getElementsByTagName('img')[0], // find thumbnail
                    pageYScroll = window.pageYOffset || document.documentElement.scrollTop,
                    rect = thumbnail.getBoundingClientRect();

                return {x:rect.left, y:rect.top + pageYScroll, w:rect.width};
            }

        };

        // PhotoSwipe opened from URL
        if(fromURL) {
            if(options.galleryPIDs) {
                // parse real index when custom PIDs are used
                // http://photoswipe.com/documentation/faq.html#custom-pid-in-url
                for(var j = 0; j < items.length; j++) {
                    if(items[j].pid == index) {
                        options.index = j;
                        break;
                    }
                }
            } else {
                // in URL indexes start from 1
                options.index = parseInt(index, 10) - 1;
            }
        } else {
            options.index = parseInt(index, 10);
        }

        // exit if index not found
        if( isNaN(options.index) ) {
            return;
        }

        if(disableAnimation) {
            options.showAnimationDuration = 0;
        }

        // Pass data to PhotoSwipe and initialize it
        gallery = new PhotoSwipe( pswpElement, PhotoSwipeUI_Default, items, options);
        gallery.init();
    };

    // loop through all gallery elements and bind events
    var galleryElements = document.querySelectorAll( gallerySelector );

    for(var i = 0, l = galleryElements.length; i < l; i++) {
        galleryElements[i].setAttribute('data-pswp-uid', i+1);
        galleryElements[i].onclick = onThumbnailsClick;
    }

    // Parse URL and open gallery if it contains #&pid=3&gid=1
    var hashData = photoswipeParseHash();
    if(hashData.pid && hashData.gid) {
        openPhotoSwipe( hashData.pid ,  galleryElements[ hashData.gid - 1 ], true, true );
    }
};

// execute above function
initPhotoSwipeFromDOM('.my-gallery');


text:
bossman
-------

Develop Procfile based applications.

Bossman is similar to [David Dollar's](http://daviddollar.org/) [Foreman](http://ddollar.github.com/foreman/), only it's meant to be more oriented towards development than towards actual production use (i.e., develop with Bossman, deploy on Heroku, etc). At the time of this writing it has no benefit over Foreman, but I have some ideas I'd like to explore with it in the future.

It's written in Python/Twisted, it's MIT licensed, and I'm [`@aknin`](http://twitter.com/#!/aknin), if you want to talk.


text:
"use strict";

function isGlobalWeb3() {
  if (typeof window === "undefined") return false;
  if (!window) return false;
  if (!window.ethereum) {
    if (window.web3 && window.web3.currentProvider) return true;
    return false;
  }
  return true;
}

module.exports = isGlobalWeb3;


text:
/**
 * Webpack configuration file
 **/
const fs = require('fs');
const path = require('path');
const webpack = require('webpack');
const postcssImport = require('postcss-import');
const postcssCssNext = require('postcss-cssnext');
const postcssBR = require('postcss-browser-reporter');
const postcssR = require('postcss-reporter');

const isProd = process.env.NODE_ENV === 'production';

function HashBundlePlugin() {}

HashBundlePlugin.prototype.apply = (compiler) => {
  compiler.plugin('done', (statsData) => {
    const stats = statsData.toJson();

    if (!stats.errors.length) {
      const htmlFileName = 'index.html';
      const html = fs.readFileSync(path.join(__dirname, htmlFileName), 'utf8');
      const htmlOutput = html.replace(/\/build\/.?bundle\.js/, `${'/build/'}${stats.hash}${'.bundle.js'}`);

      fs.writeFileSync(path.join(__dirname, htmlFileName), htmlOutput);
    }
  });
};

const config = {
  entry: ['babel-polyfill', path.resolve(__dirname, 'src')],
  output: {
    filename: `${isProd ? '[hash].' : ''}bundle.js`,
    path: path.resolve(__dirname, 'build'),
    publicPath: 'build/',
  },
  resolve: {
    extensions: ['.jsx', '.js', '.css', '.json'],
    modules: [
      path.resolve(__dirname, 'src'),
      path.resolve(__dirname, 'assets'),
      path.resolve(__dirname, 'node_modules'),
    ],
  },
  context: __dirname,
  module: {
    rules: [{
      test: /\.css$/,
      loader: 'style-loader!css-loader?modules&importLoaders=1&localIdentName=[path]___[name]__[local]___[hash:base64:5]!postcss-loader',
      exclude: /node_modules\/c3/,
    }, {
      test: /\.css$/,
      loader: 'style-loader!css-loader',
      include: /node_modules\/c3/,
    }, {
      test: /\.woff(2)?(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      loader: 'url-loader?limit=10000&minetype=application/font-woff&name=[hash].[ext]',
    }, {
      test: /\.(ttf|eot|svg|jpg|gif|png)(\?v=[0-9]\.[0-9]\.[0-9])?$/,
      loader: 'file-loader?name=[hash].[ext]',
    }, {
      test: /\.(js|jsx)$/,
      exclude: /(node_modules)/,
      loader: 'babel-loader',
    }],
  },
  plugins: [
    new webpack.LoaderOptionsPlugin({
      options: {
        postcss: [
          postcssImport({
            addDependencyTo: webpack,
          }),
          postcssCssNext(),
          postcssBR(),
          postcssR(),
        ],
      },
    }),
    new webpack.DefinePlugin({
      'process.env': {
        NODE_ENV: JSON.stringify(process.env.NODE_ENV),
      },
      API_HOST: JSON.stringify(process.env.API_HOST || 'https://api.opendota.com'),
    }),
  ],
  devServer: {
    contentBase: __dirname,
    host: '0.0.0.0',
    port: Number(process.env.PORT) || 8080,
    historyApiFallback: true,
  },
};

if (!isProd) {
  config.devtool = 'eval-source-map';
  config.devServer.hot = true;

  config.entry = [
    'react-hot-loader/patch',
    `webpack-dev-server/client?http://${config.devServer.host}:${config.devServer.port}`,
    'webpack/hot/only-dev-server', // "only" prevents reload on syntax errors
    'babel-polyfill',
    path.resolve(__dirname, 'src'),
  ];

  config.plugins.push(new webpack.HotModuleReplacementPlugin());
  config.plugins.push(new webpack.NamedModulesPlugin());
} else {
  config.plugins.push(new webpack.LoaderOptionsPlugin({
    minimize: true,
    debug: false,
  }));

  config.plugins.push(new webpack.optimize.UglifyJsPlugin({
    compress: {
      warnings: false,
    },
    output: {
      comments: false,
    },
    sourceMap: false,
  }));

  config.plugins.push(new HashBundlePlugin());
}

module.exports = config;