text:
var assert = require('assert');
var async = require('async');
var domain = require('domain');

var helper = require('../../test-helper');
var Client = require('../../../lib/client');
var Host = require('../../../lib/host').Host;
var clientOptions = require('../../../lib/client-options');
var utils = require('../../../lib/utils');
var errors = require('../../../lib/errors');
var types = require('../../../lib/types');

var RoundRobinPolicy = require('../../../lib/policies/load-balancing.js').RoundRobinPolicy;

describe('Client', function () {
  this.timeout(120000);
  describe('#connect()', function () {
    before(helper.ccmHelper.start(3));
    after(helper.ccmHelper.remove);
    it('should discover all hosts in the ring and hosts object can be serializable', function (done) {
      var client = newInstance();
      client.connect(function (err) {
        if (err) return done(err);
        assert.strictEqual(client.hosts.length, 3);
        assert.strictEqual(client.hosts.values().length, 3);
        assert.strictEqual(client.hosts.keys().length, 3);
        assert.doesNotThrow(function () {
          //It should be serializable
          JSON.stringify(client.hosts);
        });
        client.shutdown(done);
      });
    });
    it('should retrieve the cassandra version of the hosts', function (done) {
      var client = newInstance();
      client.connect(function (err) {
        if (err) return done(err);
        assert.strictEqual(client.hosts.length, 3);
        client.hosts.values().forEach(function (h) {
          assert.strictEqual(typeof h.cassandraVersion, 'string');
          assert.strictEqual(
            h.cassandraVersion.split('.').slice(0, 2).join('.'),
            helper.getCassandraVersion().split('.').slice(0, 2).join('.'));
        });
        client.shutdown(done);
      });
    });
    it('should fail if the contact points can not be resolved', function (done) {
      var client = newInstance({contactPoints: ['not-a-host']});
      client.connect(function (err) {
        assert.ok(err);
        helper.assertInstanceOf(err, errors.NoHostAvailableError);
        client.shutdown(function (err) {
          assert.ifError(err);
          done();
        });
      });
    });
    it('should fail if the contact points can not be reached', function (done) {
      var client = newInstance({contactPoints: ['1.1.1.1']});
      client.connect(function (err) {
        assert.ok(err);
        helper.assertInstanceOf(err, errors.NoHostAvailableError);
        done();
      });
    });
    it('should fail if the keyspace does not exists', function (done) {
      var client = newInstance({ keyspace: 'ks_does_not_exists'});
      client.connect(function (err) {
        helper.assertInstanceOf(err, Error);
        client.shutdown(function (err) {
          assert.ifError(err);
          done();
        });
      });
    });
    it('should select a tokenizer', function (done) {
      var client = newInstance();
      client.connect(function (err) {
        if (err) return done(err);
        helper.assertInstanceOf(client.metadata.tokenizer, require('../../../lib/tokenizer.js').Murmur3Tokenizer);
        client.shutdown(done);
      });
    });
    it('should allow multiple parallel calls to connect', function (done) {
      var client = newInstance();
      async.times(100, function (n, next) {
        client.connect(next);
      }, function (err) {
        assert.ifError(err);
        client.shutdown(done);
      });
    });
    it('should resolve host names', function (done) {
      var client = new Client(utils.extend({}, helper.baseOptions, {contactPoints: ['localhost']}));
      client.connect(function (err) {
        assert.ifError(err);
        assert.strictEqual(client.hosts.length, 3);
        client.hosts.forEach(function (h) {
          assert.notEqual(h.address, 'localhost');
        });
        client.shutdown(done);
      });
    });
    it('should fail if the keyspace does not exists', function (done) {
      var client = new Client(utils.extend({}, helper.baseOptions, {keyspace: 'not-existent-ks'}));
      async.times(10, function (n, next) {
        client.connect(function (err) {
          assert.ok(err);
          //Not very nice way to check but here it is
          //Does the message contains Keyspace
          assert.ok(err.message.toLowerCase().indexOf('keyspace') >= 0, 'Message mismatch, was: ' + err.message);
          next();
        });
      }, function (err) {
        assert.ifError(err);
        client.shutdown(done);
      });
    });
    it('should not use contactPoints that are not part of peers', function (done) {
      var contactPoints = helper.baseOptions.contactPoints.slice(0);
      contactPoints.push('host-not-existent-not-peer');
      contactPoints.push('1.1.1.1');
      var client = newInstance({contactPoints: contactPoints});
      client.connect(function (err) {
        assert.ifError(err);
        //the 3 original hosts
        assert.strictEqual(client.hosts.length, 3);
        var hosts = client.hosts.keys();
        assert.strictEqual(hosts[0], contactPoints[0] + ':9042');
        assert.notEqual(hosts[1], contactPoints[1] + ':9042');
        assert.notEqual(hosts[2], contactPoints[1] + ':9042');
        assert.notEqual(hosts[1], contactPoints[2] + ':9042');
        assert.notEqual(hosts[2], contactPoints[2] + ':9042');
        client.shutdown(done);
      });
    });
    it('should use the default pooling options according to the protocol version', function (done) {
      var client = newInstance();
      client.connect(function (err) {
        assert.ifError(err);
        assert.ok(client.options.pooling.coreConnectionsPerHost);
        if (client.controlConnection.protocolVersion < 3) {
          helper.assertValueEqual(client.options.pooling.coreConnectionsPerHost, clientOptions.coreConnectionsPerHostV2);
        }
        else {
          helper.assertValueEqual(client.options.pooling.coreConnectionsPerHost, clientOptions.coreConnectionsPerHostV3);
        }
        async.times(10, function (n, next) {
          client.execute('SELECT key FROM system.local', next);
        }, function (err) {
          if (err) return done(err);
          assert.strictEqual(client.hosts.values()[0].pool.connections.length, client.options.pooling.coreConnectionsPerHost[types.distance.local]);
          client.shutdown(done);
        });
      });
    });
    it('should override default pooling options when specified', function (done) {
      var client = newInstance({ pooling: {
        coreConnectionsPerHost: { '0': 4 }
      }});
      client.connect(function (err) {
        assert.ifError(err);
        assert.ok(client.options.pooling.coreConnectionsPerHost);
        var defaults = clientOptions.coreConnectionsPerHostV3;
        if (client.controlConnection.protocolVersion < 3) {
          defaults = clientOptions.coreConnectionsPerHostV2;
        }
        assert.ok(client.options.pooling.coreConnectionsPerHost[types.distance.local], 4);
        assert.ok(client.options.pooling.coreConnectionsPerHost[types.distance.remote], defaults[types.distance.remote]);
        async.times(50, function (n, next) {
          client.execute('SELECT key FROM system.local', next);
        }, function (err) {
          if (err) return done(err);
          assert.strictEqual(client.hosts.values()[0].pool.connections.length, client.options.pooling.coreConnectionsPerHost[types.distance.local]);
          client.shutdown(done);
        });
      });
    });
    it('should not fail when switching keyspace and a contact point is not valid', function (done) {
      var client = new Client({
        contactPoints: ['1.1.1.1', helper.baseOptions.contactPoints[0]],
        keyspace: 'system'
      });
      client.connect(function (err) {
        assert.ifError(err);
        client.shutdown(done);
      });
    });
    it('should open connections to all hosts when warmup is set', function (done) {
      var connectionsPerHost = {};
      connectionsPerHost[types.distance.local]  = 3;
      connectionsPerHost[types.distance.remote] = 1;
      var client = newInstance({ pooling: { warmup: true, coreConnectionsPerHost: connectionsPerHost}});
      client.connect(function (err) {
        assert.ifError(err);
        assert.strictEqual(client.hosts.length, 3);
        client.hosts.forEach(function (host) {
          assert.strictEqual(host.pool.connections.length, 3);
        });
        client.shutdown(done);
      });
    });
    it('should only warmup connections for hosts with local distance', function (done) {
      var lbPolicy = new RoundRobinPolicy();
      lbPolicy.getDistance = function (host) {
        //noinspection JSCheckFunctionSignatures
        var id = helper.lastOctetOf(host.address);
        if(id == '1') {
          return types.distance.local;
        } else if(id == '2') {
          return types.distance.remote;
        }
        return types.distance.ignored;
      };

      var connectionsPerHost = {};
      connectionsPerHost[types.distance.local]  = 3;
      connectionsPerHost[types.distance.remote] = 1;
      var client = newInstance({
        policies: { loadBalancing: lbPolicy },
        pooling: { warmup: true, coreConnectionsPerHost: connectionsPerHost}
      });
      client.connect(function (err) {
        assert.ifError(err);
        assert.strictEqual(client.hosts.length, 3);
        client.hosts.forEach(function (host) {
          var id = helper.lastOctetOf(host);
          if(id == '1') {
            assert.strictEqual(host.pool.connections.length, 3);
          } else {
            assert.strictEqual(host.pool.connections.length, 0);
          }
        });
        client.shutdown(done);
      });
    });
  });
  describe('#connect() with auth', function () {
    before(function (done) {
      async.series([
        function (next) {
          //it wont hurt to remove
          helper.ccmHelper.exec(['remove'], function () {
            //ignore error
            next();
          });
        },
        function (next) {
          helper.ccmHelper.exec(['create', 'test', '-v', helper.getCassandraVersion()], next);
        },
        function (next) {
          helper.ccmHelper.exec(['updateconf', "authenticator: PasswordAuthenticator"], next);
        },
        function (next) {
          helper.ccmHelper.exec(['populate', '-n', '2'], next);
        },
        function (next) {
          helper.ccmHelper.exec(['start'], function () {
            //It takes a while for Cassandra to create the default user account
            setTimeout(function () {next();}, 25000);
          });
        }
      ], done)
    });
    after(helper.ccmHelper.remove);
    var PlainTextAuthProvider = require('../../../lib/auth/plain-text-auth-provider.js');
    it('should connect using the plain text authenticator', function (done) {
      var options = {authProvider: new PlainTextAuthProvider('cassandra', 'cassandra')};
      var client = newInstance(options);
      async.times(100, function (n, next) {
        client.connect(next);
      }, function (err) {
        done(err);
      });
    });
    it('should connect using the plain text authenticator when calling execute', function (done) {
      var options = {authProvider: new PlainTextAuthProvider('cassandra', 'cassandra'), keyspace: 'system'};
      var client = newInstance(options);
      async.times(100, function (n, next) {
        client.execute('SELECT * FROM schema_keyspaces', next);
      }, function (err) {
        done(err);
      });
    });
    it('should return an AuthenticationError', function (done) {
      var options = {authProvider: new PlainTextAuthProvider('not___EXISTS', 'not___EXISTS'), keyspace: 'system'};
      var client = newInstance(options);
      async.timesSeries(10, function (n, next) {
        client.connect(function (err) {
          assert.ok(err);
          helper.assertInstanceOf(err, errors.NoHostAvailableError);
          assert.ok(err.innerErrors);
          helper.assertInstanceOf(helper.values(err.innerErrors)[0], errors.AuthenticationError);
          next();
        });
      }, done);
    });
    it('should return an AuthenticationError when calling execute', function (done) {
      var options = {authProvider: new PlainTextAuthProvider('not___EXISTS', 'not___EXISTS'), keyspace: 'system'};
      var client = newInstance(options);
      async.times(10, function (n, next) {
        client.execute('SELECT * FROM schema_keyspaces', function (err) {
          assert.ok(err);
          helper.assertInstanceOf(err, errors.NoHostAvailableError);
          assert.ok(err.innerErrors);
          helper.assertInstanceOf(helper.values(err.innerErrors)[0], errors.AuthenticationError);
          next();
        });
      }, done);
    });
  });
  describe('#connect() with ssl', function () {
    before(helper.ccmHelper.start(1, {ssl: true}));
    after(helper.ccmHelper.remove);
    it('should connect to a ssl enabled cluster', function (done) {
      var client = newInstance({sslOptions: {}});
      client.connect(function (err) {
        assert.ifError(err);
        assert.strictEqual(client.hosts.length, 1);
        done();
      });
    });
  });
  describe('#execute()', function () {
    before(helper.ccmHelper.start(3));
    after(helper.ccmHelper.remove);
    it('should use the keyspace provided', function (done) {
      var client = new Client(utils.extend({}, helper.baseOptions, {keyspace: 'system'}));
      //on all hosts
      async.times(10, function (n, next) {
        assert.strictEqual(client.keyspace, 'system');
        //A query in the system ks
        client.execute('SELECT * FROM schema_keyspaces', function (err, result) {
          assert.ifError(err);
          assert.ok(result.rows);
          assert.ok(result.rows.length > 0);
          next();
        });
      }, done);
    });
    it('should fail to execute if the keyspace does not exists', function (done) {
      var client = new Client(utils.extend({}, helper.baseOptions, {keyspace: 'NOT____EXISTS'}));
      //on all hosts
      async.times(10, function (n, next) {
        //No matter what, the keyspace does not exists
        client.execute('SELECT * FROM system.schema_keyspaces', function (err) {
          helper.assertInstanceOf(err, Error);
          next();
        });
      }, done);
    });
    it('should change the active keyspace after USE statement', function (done) {
      var client = newInstance();
      client.execute('USE system', function (err) {
        if (err) return done(err);
        assert.strictEqual(client.keyspace, 'system');
        //all next queries, the instance should still "be" in the system keyspace
        async.times(100, function (n, next) {
          client.execute('SELECT * FROM schema_keyspaces', [], next);
        }, done)
      });
    });
    it('should return ResponseError when executing USE with a wrong keyspace', function (done) {
      var client = newInstance();
      client.execute('USE ks_not_exist', function (err) {
        assert.ok(err instanceof errors.ResponseError);
        assert.equal(client.keyspace, null);
        done();
      });
    });
    it('should create the amount of connections determined by the options', function (done) {
      var options = {
        pooling: {
          coreConnectionsPerHost: {
            '0': 3,
            '1': 0,
            '2': 0
          }
        }
      };
      var client = new Client(utils.extend({}, helper.baseOptions, options));
      //execute a couple of queries
      async.times(100, function (n, next) {
        setTimeout(function () {
          client.execute('SELECT * FROM system.schema_keyspaces', next);
          }, 100 + n * 2)
      }, function (err) {
        if (err) return done(err);
        assert.strictEqual(client.hosts.length, 3);
        var hosts = client.hosts.slice(0);
        assert.strictEqual(hosts[0].pool.coreConnectionsLength, 3);
        assert.strictEqual(hosts[1].pool.coreConnectionsLength, 3);
        assert.strictEqual(hosts[0].pool.connections.length, 3);
        assert.strictEqual(hosts[1].pool.connections.length, 3);
        done(err);
      });
    });
    it('should maintain the domain in the callbacks', function (done) {
      var unexpectedErrors = [];
      var errors = [];
      var domains = [
        //2 domains because there are more than 2 hosts as an uncaught error
        //will blow up the host pool, by design
        //But we need to test prepared and unprepared
        domain.create(),
        domain.create()
      ];
      var fatherDomain = domain.create();
      var childDomain = domain.create();
      var client1 = new Client(helper.baseOptions);
      var client2 = new Client(helper.baseOptions);
      async.series([
        client1.connect.bind(client1),
        client2.connect.bind(client1),
        function executeABunchOfTimes1(next) {
          async.times(10, function (n, timesNext) {
            client1.execute('SELECT * FROM system.local', timesNext);
          }, next);
        },
        function executeABunchOfTimes2(next) {
          async.times(10, function (n, timesNext) {
            client2.execute('SELECT * FROM system.local', timesNext);
          }, next);
        },
        function blowUpSingleDomain(next) {
          var EventEmitter = require('events').EventEmitter;
          async.timesSeries(domains.length, function (n, timesNext) {
            var waiting = 1;
            var d = domains[n];
            d.add(new EventEmitter());
            d.on('error', function (err) {
              errors.push([err.toString(), n.toString()]);
              setImmediate(function () {
                //OK, this line might result in an output message (!?)
                d.dispose();
              });
            });
            d.run(function() {
              client1.execute('SELECT * FROM system.local', [], {prepare: n % 2}, function (err) {
                waiting = 0;
                if (err) {
                  unexpectedErrors.push(err);
                }
                throw new Error('From domain ' + n);
              });
            });
            function wait() {
              if (waiting > 0) {
                waiting++;
                if (waiting > 100) {
                  return timesNext(new Error('Timed out'));
                }
                return setTimeout(wait, 50);
              }
              //Delay to allow throw
              setTimeout(function () {
                timesNext();
              }, 100);
            }
            wait();
          }, next);
        },
        function nestedDomain(next) {
          var waiting = true;
          fatherDomain.on('error', function (err) {
            errors.push([err.toString(), 'father']);
          });
          fatherDomain.run(function () {
            childDomain.on('error', function (err) {
              errors.push([err.toString(), 'child']);
            });
            childDomain.run(function() {
              client2.execute('SELECT * FROM system.local', function (err) {
                waiting = false;
                if (err) {
                  unexpectedErrors.push(err);
                }
                throw new Error('From domain child');
              });
            });
          });
          function wait() {
            if (waiting) {
              return setTimeout(wait, 50);
            }
            //Delay to allow throw
            setTimeout(next, 100);
          }
          wait();
        },
        function assertResults(next) {
          assert.strictEqual(unexpectedErrors.length, 0, 'Unexpected errors: ' + unexpectedErrors[0]);
          //assert.strictEqual(errors.length, domains.length + 1);
          errors.forEach(function (item) {
            assert.strictEqual(item[0], 'Error: From domain ' + item[1]);
          });
          next();
        }
      ], done);
    });
    it('should wait for schema agreement before calling back', function (done) {
      var queries = [
        "CREATE KEYSPACE ks1 WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};",
        "CREATE TABLE ks1.tbl1 (id uuid PRIMARY KEY, value text)",
        "SELECT * FROM ks1.tbl1",
        "SELECT * FROM ks1.tbl1 where id = d54cb06d-d168-45a0-b1b2-9f5c75435d3d",
        "CREATE KEYSPACE ks2 WITH replication = {'class': 'SimpleStrategy', 'replication_factor' : 3};",
        "CREATE TABLE ks2.tbl2 (id uuid PRIMARY KEY, value text)",
        "SELECT * FROM ks2.tbl2",
        "SELECT * FROM ks2.tbl2",
        "CREATE TABLE ks2.tbl3 (id uuid PRIMARY KEY, value text)",
        "SELECT * FROM ks2.tbl3",
        "SELECT * FROM ks2.tbl3",
        "CREATE TABLE ks2.tbl4 (id uuid PRIMARY KEY, value text)",
        "SELECT * FROM ks2.tbl4",
        "SELECT * FROM ks2.tbl4",
        "SELECT * FROM ks2.tbl4"
      ];
      var client = newInstance();
      //warmup first
      async.timesSeries(10, function (n, next) {
        client.execute('SELECT key FROM system.local', next);
      }, function (err) {
        assert.ifError(err);
        async.eachSeries(queries, function (query, next) {
          client.execute(query, next);
        }, done);
      });
    });
  });
  describe('failover', function () {
    beforeEach(helper.ccmHelper.start(3));
    afterEach(helper.ccmHelper.remove);
    it('should failover after a node goes down', function (done) {
      var client = newInstance();
      var hosts = {};
      var hostsDown = [];
      client.on('hostDown', function (h) {
        hostsDown.push(h);
      });
      async.series([
        function warmUpPool(seriesNext) {
          async.times(100, function (n, next) {
            client.execute('SELECT * FROM system.schema_keyspaces', function (err, result) {
              assert.ifError(err);
              hosts[result.info.queriedHost] = true;
              next();
            });
          }, seriesNext);
        },
        function killNode(seriesNext) {
          setTimeout(function () {
            helper.ccmHelper.exec(['node1', 'stop', '--not-gently']);
            seriesNext();
          }, 0);
        },
        function testCase(seriesNext) {
          //3 hosts alive
          assert.strictEqual(Object.keys(hosts).length, 3);
          var counter = 0;
          async.times(1000, function (i, next) {
            client.execute('SELECT * FROM system.schema_keyspaces', function (err) {
              counter++;
              assert.ifError(err);
              next();
            });
          }, function (err) {
            assert.ifError(err);
            //Only 2 hosts alive at the end
            assert.strictEqual(
              client.hosts.slice(0).reduce(function (val, h) {
                return val + (h.isUp() ? 1 : 0);
              }, 0),
              2);
            assert.ok(hostsDown.length >= 1, "Expected at least 1 host down" +
              " event.");
            //Ensure each down event is for the stopped host.  We may get
            //multiple down events for the same host on a control connection.
            hostsDown.forEach(function (downHost) {
              assert.strictEqual(helper.lastOctetOf(downHost), '1');
            });
            seriesNext();
          });
        }
      ], done);
    });
    it('should failover when a node goes down with some outstanding requests', function (done) {
      var options = utils.extend({}, helper.baseOptions);
      options.pooling = {
        coreConnectionsPerHost: {
          '0': 1,
          '1': 1,
          '2': 0
        }
      };
      var client = new Client(options);
      var hosts = {};
      var query = 'SELECT * FROM system.schema_keyspaces';
      async.series([
        function warmUpPool(seriesNext) {
          async.times(10, function (n, next) {
            client.execute(query, function (err, result) {
              assert.ifError(err);
              hosts[result.info.queriedHost] = true;
              next();
            });
          }, seriesNext);
        },
        function testCase(seriesNext) {
          //3 hosts alive
          assert.strictEqual(Object.keys(hosts).length, 3);
          var counter = 0;
          var issued = 0;
          var killed = false;
          async.times(500, function (n, next) {
            if (n === 10) {
              //kill a node when there are some outstanding requests
              helper.ccmHelper.exec(['node2', 'stop', '--not-gently'], function (err) {
                killed = true;
                assert.ifError(err);
                //do a couple of more queries
                async.times(10, function (n, next2) {
                  client.execute(query, next2);
                }, next);
              });
              return;
            }
            if (killed) {
              //Don't issue more requests
              return next();
            }
            issued++;
            client.execute(query, function (err) {
              assert.ifError(err);
              counter++;
              next();
            });
          }, function (err) {
            assert.ifError(err);
            //Only 2 hosts alive at the end
            assert.strictEqual(
              client.hosts.slice(0).reduce(function (val, h) {
                return val + (h.isUp() ? 1 : 0);
              }, 0),
              2);
            seriesNext();
          });
        }
      ], done);
    });
    it('should warn but not fail when warmup is enable and a node is down', function (done) {
      async.series([
        helper.toTask(helper.ccmHelper.exec, null, ['node2', 'stop']),
        function (next) {
          var warnings = [];
          var client = newInstance({ pooling: { warmup: true } });
          client.on('log', function (level, className, message) {
            if (level !== 'warning' || className !== 'Client') return;
            warnings.push(message);
          });
          client.connect(function (err) {
            assert.ifError(err);
            assert.strictEqual(warnings.length, 1);
            assert.ok(warnings[0].indexOf('pool') >= 0, 'warning does not contains the word pool: ' + warnings[0]);
            client.shutdown(next);
          });
        }
      ], done);
    });
    it('should connect when first contact point is down', function (done) {
      async.series([
        helper.toTask(helper.ccmHelper.exec, null, ['node1', 'stop']),
        function (next) {
          var client = newInstance({ contactPoints: ['127.0.0.1', '127.0.0.2'], pooling: { warmup: true } });
          client.connect(function (err) {
            assert.ifError(err);
            client.shutdown(next);
          });
        }
      ], done);
    });
  });
  describe('events', function () {
    //noinspection JSPotentiallyInvalidUsageOfThis
    this.timeout(600000);
    var is1x = helper.getCassandraVersion().charAt(0) === '1';
    beforeEach(helper.ccmHelper.start(2));
    afterEach(helper.ccmHelper.remove);
    it('should emit hostUp hostDown', function (done) {
      var client = newInstance();
      var hostsWentUp = [];
      var hostsWentDown = [];
      async.series([
        client.connect.bind(client),
        function addListeners(next) {
          client.on('hostUp', hostsWentUp.push.bind(hostsWentUp));
          client.on('hostDown', hostsWentDown.push.bind(hostsWentDown));
          next();
        },
        helper.toTask(helper.ccmHelper.stopNode, null, 2),
        helper.toTask(helper.ccmHelper.startNode, null, 2),
        function wait1s(next) {
          // If C* 1.x, we wait slightly before checking the listener
          // because the node is marked UP just before the listeners are
          // called since CCM considers the node up as soon as other nodes
          // have seen it up, at which point they would send the
          // notification on the control connection so there is a very small
          // race here that is not evident at C* 2.x+.
          if(is1x) {
            setTimeout(next, 1000);
          } else {
            next();
          }
        },
        function checkResults(next) {
          assert.strictEqual(hostsWentUp.length, 1);
          helper.assertInstanceOf(hostsWentUp[0], Host);
          assert.strictEqual(helper.lastOctetOf(hostsWentUp[0]), '2');

          // Special exception for C* 1.x, as it may send duplicate down events
          // for a single host.
          if(!is1x) {
            assert.strictEqual(hostsWentDown.length, 1);
          }
          hostsWentDown.forEach(function(downHost) {
            helper.assertInstanceOf(downHost, Host);
            assert.strictEqual(helper.lastOctetOf(downHost), '2');
          });
          next();
        },
        client.shutdown.bind(client)
      ], done);
    });
    it('should emit hostAdd hostRemove', function (done) {
      var client = newInstance();
      var hostsAdded = [];
      var hostsRemoved = [];
      function trace(message) {
        return (function (next) {
          helper.trace(message);
          next();
        });
      }
      async.series([
        client.connect.bind(client),
        function addListeners(next) {
          client.on('hostAdd', hostsAdded.push.bind(hostsAdded));
          client.on('hostRemove', hostsRemoved.push.bind(hostsRemoved));
          next();
        },
        trace('Bootstrapping node 3'),
        helper.toTask(helper.ccmHelper.bootstrapNode, null, 3),
        trace('Starting newly bootstrapped node 3'),
        helper.toTask(helper.ccmHelper.startNode, null, 3),
        trace('Decommissioning node 2'),
        helper.toTask(helper.ccmHelper.decommissionNode, null, 2),
        trace('Stopping node 2'),
        helper.toTask(helper.ccmHelper.stopNode, null, 2),
        function checkResults(next) {
          helper.trace('Checking results');
          assert.strictEqual(hostsAdded.length, 1);
          assert.strictEqual(hostsRemoved.length, 1);
          helper.assertInstanceOf(hostsAdded[0], Host);
          helper.assertInstanceOf(hostsRemoved[0], Host);
          assert.strictEqual(helper.lastOctetOf(hostsAdded[0]), '3');
          assert.strictEqual(helper.lastOctetOf(hostsRemoved[0]), '2');
          next();
        },
        client.shutdown.bind(client)
      ], done);
    });
  });
  describe('#shutdown()', function () {
    before(helper.ccmHelper.start(2));
    after(helper.ccmHelper.remove);
    it('should close all connections to all hosts', function (done) {
      var client = newInstance();
      async.series([
        client.connect.bind(client),
        function makeSomeQueries(next) {
          //to ensure that the pool is all up!
          async.times(100, function (n, timesNext) {
            client.execute('SELECT * FROM system.schema_keyspaces', timesNext);
          }, next);
        },
        function shutDown(next) {
          var hosts = client.hosts.slice(0);
          assert.strictEqual(hosts.length, 2);
          assert.ok(hosts[0].pool.connections.length > 0);
          assert.ok(hosts[1].pool.connections.length > 0);
          assert.ok(!hosts[0].pool.shuttingDown);
          assert.ok(!hosts[1].pool.shuttingDown);
          client.shutdown(next);
        },
        function checkPool(next) {
          var hosts = client.hosts.slice(0);
          assert.strictEqual(hosts.length, 2);
          assert.strictEqual(hosts[0].pool.connections.length, 0);
          assert.strictEqual(hosts[1].pool.connections.length, 0);
          next();
        }
      ], done);
    });
  });
});

/** @returns {Client}  */
function newInstance(options) {
  return new Client(utils.extend({}, helper.baseOptions, options));
}


text:
package org.elasticsearch.client.core;

import org.elasticsearch.action.support.IndicesOptions;
import org.elasticsearch.client.Validatable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.xcontent.ToXContentObject;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.index.query.QueryBuilder;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.internal.SearchContext;

import java.io.IOException;
import java.util.Arrays;
import java.util.Objects;

import static org.elasticsearch.action.search.SearchRequest.DEFAULT_INDICES_OPTIONS;

/**
 * Encapsulates a request to _count API against one, several or all indices.
 */
public final class CountRequest implements Validatable, ToXContentObject {

    private String[] indices = Strings.EMPTY_ARRAY;
    private String[] types = Strings.EMPTY_ARRAY;
    private String routing;
    private String preference;
    private QueryBuilder query;
    private IndicesOptions indicesOptions = DEFAULT_INDICES_OPTIONS;
    private int terminateAfter = SearchContext.DEFAULT_TERMINATE_AFTER;
    private Float minScore;

    public CountRequest() {}

    /**
     * Constructs a new count request against the indices. No indices provided here means that count will execute on all indices.
     */
    public CountRequest(String... indices) {
        indices(indices);
    }

    /**
     * Constructs a new search request against the provided indices with the given search source.
     *
     * @deprecated The count api only supports a query. Use {@link #CountRequest(String[], QueryBuilder)} instead.
     */
    @Deprecated
    public CountRequest(String[] indices, SearchSourceBuilder searchSourceBuilder) {
        indices(indices);
        this.query = Objects.requireNonNull(searchSourceBuilder, "source must not be null").query();
    }

    /**
     * Constructs a new search request against the provided indices with the given query.
     */
    public CountRequest(String[] indices, QueryBuilder query) {
        indices(indices);
        this.query = Objects.requireNonNull(query, "query must not be null");;
    }

    /**
     * Sets the indices the count will be executed on.
     */
    public CountRequest indices(String... indices) {
        Objects.requireNonNull(indices, "indices must not be null");
        for (String index : indices) {
            Objects.requireNonNull(index, "index must not be null");
        }
        this.indices = indices;
        return this;
    }

    /**
     * The source of the count request.
     *
     * @deprecated The count api only supports a query. Use {@link #query(QueryBuilder)} instead.
     */
    @Deprecated
    public CountRequest source(SearchSourceBuilder searchSourceBuilder) {
        this.query = Objects.requireNonNull(searchSourceBuilder, "source must not be null").query();
        return this;
    }

    /**
     * Sets the query to execute for this count request.
     */
    public CountRequest query(QueryBuilder query) {
        this.query = Objects.requireNonNull(query, "query must not be null");
        return this;
    }

    /**
     * The document types to execute the count against. Defaults to be executed against all types.
     *
     * @deprecated Types are in the process of being removed. Instead of using a type, prefer to
     * filter on a field on the document.
     */
    @Deprecated
    public CountRequest types(String... types) {
        Objects.requireNonNull(types, "types must not be null");
        for (String type : types) {
            Objects.requireNonNull(type, "type must not be null");
        }
        this.types = types;
        return this;
    }

    /**
     * The routing values to control the shards that the search will be executed on.
     */
    public CountRequest routing(String routing) {
        this.routing = routing;
        return this;
    }

    /**
     * A comma separated list of routing values to control the shards the count will be executed on.
     */
    public CountRequest routing(String... routings) {
        this.routing = Strings.arrayToCommaDelimitedString(routings);
        return this;
    }

    /**
     * Returns the indices options used to resolve indices. They tell for instance whether a single index is accepted, whether an empty
     * array will be converted to _all, and how wildcards will be expanded if needed.
     *
     * @see org.elasticsearch.action.support.IndicesOptions
     */
    public CountRequest indicesOptions(IndicesOptions indicesOptions) {
        this.indicesOptions = Objects.requireNonNull(indicesOptions, "indicesOptions must not be null");
        return this;
    }

    /**
     * Sets the preference to execute the count. Defaults to randomize across shards. Can be set to {@code _local} to prefer local shards
     * or a custom value, which guarantees that the same order will be used across different requests.
     */
    public CountRequest preference(String preference) {
        this.preference = preference;
        return this;
    }

    public IndicesOptions indicesOptions() {
        return this.indicesOptions;
    }

    public String routing() {
        return this.routing;
    }

    public String preference() {
        return this.preference;
    }

    public String[] indices() {
        return Arrays.copyOf(this.indices, this.indices.length);
    }

    public Float minScore() {
        return minScore;
    }

    public CountRequest minScore(Float minScore) {
        this.minScore = minScore;
        return this;
    }

    public int terminateAfter() {
        return this.terminateAfter;
    }

    public CountRequest terminateAfter(int terminateAfter) {
        if (terminateAfter < 0) {
            throw new IllegalArgumentException("terminateAfter must be > 0");
        }
        this.terminateAfter = terminateAfter;
        return this;
    }

    /**
     * @deprecated Types are in the process of being removed. Instead of using a type, prefer to
     * filter on a field on the document.
     */
    @Deprecated
    public String[] types() {
        return Arrays.copyOf(this.types, this.types.length);
    }

    /**
     * @return the source builder
     * @deprecated The count api only supports a query. Use {@link #query()} instead.
     */
    @Deprecated
    public SearchSourceBuilder source() {
        return new SearchSourceBuilder().query(query);
    }

    /**
     * @return The provided query to execute with the count request or
     * null if no query was provided.
     */
    public QueryBuilder query() {
        return query;
    }

    @Override
    public XContentBuilder toXContent(XContentBuilder builder, Params params) throws IOException {
        builder.startObject();
        if (query != null) {
            builder.field("query", query);
        }
        builder.endObject();
        return builder;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        CountRequest that = (CountRequest) o;
        return Objects.equals(indicesOptions, that.indicesOptions) &&
            Arrays.equals(indices, that.indices) &&
            Arrays.equals(types, that.types) &&
            Objects.equals(routing, that.routing) &&
            Objects.equals(preference, that.preference) &&
            Objects.equals(terminateAfter, that.terminateAfter) &&
            Objects.equals(minScore, that.minScore) &&
            Objects.equals(query, that.query);
    }

    @Override
    public int hashCode() {
        int result = Objects.hash(indicesOptions, routing, preference, terminateAfter, minScore, query);
        result = 31 * result + Arrays.hashCode(indices);
        result = 31 * result + Arrays.hashCode(types);
        return result;
    }
}

redpajama_set_name: RedPajamaGithub


text:
echo `date`

cd /home/fw/projectdir

expect -c "
    set timeout 10

    spawn git add -A

    spawn git commit -m 'cron auto commit'

    spawn git fetch origin -p

    spawn git rebase origin master

    spawn git push origin master

    expect {
        "Username" { send \"myname\r\"; exp_continue }
        "Password" { send \"passwd\r\" }
    };

    expect eof;
"

echo "Done"


text:
layout: post
title: "2doodle"
description: ""
category: "old"
tags: []
---

[2doodle website](http://2doodle.us/)

[hackMIT submission](http://hackmit.challengepost.com/submissions/17977-2doodle)


text:
<?php

// autoload_namespaces.php @generated by Composer

$vendorDir = dirname(dirname(__FILE__));
$baseDir = dirname($vendorDir);

return array(
    'Twig_' => array($vendorDir . '/twig/twig/lib'),
    'QueryPath' => array($vendorDir . '/querypath/querypath/src'),
);


text:
A CHIP-8 emulator written in Rust. (No audio)

# Prerequisites
- SDL2 library: see rust-sdl2 for installation instructions (https://github.com/AngryLawyer/rust-sdl2)

# TODO
- [ ] Modularize struct Chip8
- [ ] Improve timings
- [ ] Use timers for cycle accuracy


text:
package sttp.client3.impl.monix

import monix.eval.Task
import sttp.capabilities.monix.MonixStreams
import sttp.client3.SttpBackend

class FetchMonixStreamingTest extends MonixStreamingTest {
  override val backend: SttpBackend[Task, MonixStreams] = FetchMonixBackend()

  override protected def supportsStreamingMultipartParts: Boolean = false
}


text:
package com.ruletechgames.serverSocket;

import com.ruletechgames.proto.serverSocketProtos;
import com.ruletechgames.types.hybridIntMap;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.HashMap;

/**
 * Created by Michael on 8/12/2016.
 */
public class masterSocket extends Thread {

    protected static boolean serverContinue = true;
    protected Socket clientSocket;
    ServerSocket serverSocket = null;
    HashMap<hybridIntMap, Integer>serverTable = new HashMap<hybridIntMap, Integer>();

    public static void startServer() throws IOException {
        ServerSocket serverSocket = null;

        try {
            serverSocket = new ServerSocket(10008);
            System.out.println("Connection Socket Created");
            try {
                while (serverContinue) {
                    serverSocket.setSoTimeout(10000);
                    System.out.println("Waiting for Connection");
                    try {
                        new masterSocket(serverSocket.accept());
                    } catch (SocketTimeoutException ste) {
                        System.out.println("Timeout Occurred");
                    }
                }
            } catch (IOException e) {
                System.err.println("Accept failed.");
                System.exit(1);
            }
        } catch (IOException e) {
            System.err.println("Could not listen on port: 10008.");
            System.exit(1);
        } finally {
            try {
                System.out.println("Closing Server Connection Socket");
                serverSocket.close();
            } catch (IOException e) {
                System.err.println("Could not close port: 10008.");
                System.exit(1);
            }
        }
    }

    private masterSocket(Socket clientSoc) {
        clientSocket = clientSoc;
        start();
    }

    public void run() {
        System.out.println("New Communication Thread Started");

        try {
            PrintWriter out = new PrintWriter(clientSocket.getOutputStream(),
                    true);
            BufferedReader in = new BufferedReader(
                    new InputStreamReader(clientSocket.getInputStream()));
            String inputLine;

            while ((inputLine = in.readLine()) != null) {
                String input2 = inputLine.replaceAll("\\s+", "");
                System.out.println("Server: " + input2);
                System.out.println("Server: " + inputLine);

                if (inputLine.equals("RTG_HELLO_MASTER")) {
                    serverSocketProtos.helloMasterServer.Builder helloServer = serverSocketProtos.helloMasterServer.newBuilder();
                    serverSocketProtos.helloMasterServer.parseFrom(clientSocket.getInputStream());
                    String serverType = helloServer.getServerType().toString();
                    String ip = helloServer.getIp().toString();
                    int serveID = helloServer.getServerID();
                    int serverPort = helloServer.getPort();
                    if (!(ip == null))
                    {
                        serverTable.put(new hybridIntMap(serverType,ip,serverPort), serveID);
                    }

                }
            }

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


text:
"""Marathon mock endpoint"""

import copy
import logging

from exceptions import EndpointException
from mocker.endpoints.recording import (
    RecordingHTTPRequestHandler,
    RecordingTcpIpEndpoint,
)

# pylint: disable=C0103
log = logging.getLogger(__name__)

SCHEDULER_APP_TEMPLATE = {
    "id": "/scheduler-alwaysthere",
    "cmd": ("cd /opt/bitnami/nginx && harpoon initialize nginx && "
            "rm -rf /opt/bitnami/nginx/html && ln -s "
            "/mnt/mesos/sandbox/hello-nginx-master/ /opt/bitnami/nginx/html "
            "&& harpoon start --foreground nginx"),
    "args": None,
    "user": None,
    "env": {},
    "instances": 1,
    "cpus": 1,
    "mem": 1024,
    "disk": 0,
    "gpus": 0,
    "executor": "",
    "constraints": [],
    "uris": [
        "https://github.com/mesosphere/hello-nginx/archive/master.zip"
    ],
    "fetch": [
        {
            "uri": "https://github.com/mesosphere/hello-nginx/archive/master.zip",
            "extract": True,
            "executable": False,
            "cache": False
        }
    ],
    "storeUrls": [],
    "backoffSeconds": 1,
    "backoffFactor": 1.15,
    "maxLaunchDelaySeconds": 3600,
    "container": {
        "type": "DOCKER",
        "volumes": [],
        "docker": {
            "image": "bitnami/nginx:1.10.2-r0",
            "network": "BRIDGE",
            "portMappings": [
                {
                    "containerPort": 80,
                    "hostPort": 0,
                    "servicePort": 10000,
                    "protocol": "tcp",
                    "labels": {}
                },
                {
                    "containerPort": 443,
                    "hostPort": 0,
                    "servicePort": 10001,
                    "protocol": "tcp",
                    "labels": {}
                }
            ],
            "privileged": False,
            "parameters": [],
            "forcePullImage": False
        }
    },
    "healthChecks": [
        {
            "gracePeriodSeconds": 300,
            "intervalSeconds": 60,
            "timeoutSeconds": 20,
            "maxConsecutiveFailures": 3,
            "delaySeconds": 15,
            "command": {
                "value": "harpoon status nginx | grep -q 'com.bitnami.nginx is running'"
            },
            "protocol": "COMMAND"
        }
    ],
    "readinessChecks": [],
    "dependencies": [],
    "upgradeStrategy": {
        "minimumHealthCapacity": 1,
        "maximumOverCapacity": 1
    },
    "labels": {
        "DCOS_PACKAGE_RELEASE": "5",
        "DCOS_SERVICE_SCHEME": "http",
        "DCOS_PACKAGE_SOURCE": "https://universe.mesosphere.com/repo",
        "DCOS_PACKAGE_METADATA": "blah, blah, bleh",
        "DCOS_PACKAGE_REGISTRY_VERSION": "2.0",
        "DCOS_SERVICE_NAME": "scheduler-alwaysthere",
        "DCOS_SERVICE_PORT_INDEX": "0",
        "DCOS_PACKAGE_VERSION": "1.10.2",
        "DCOS_PACKAGE_NAME": "nginx",
        "DCOS_PACKAGE_IS_FRAMEWORK": "false"
    },
    "ipAddress": None,
    "version": "2017-01-16T15:48:18.007Z",
    "residency": None,
    "secrets": {},
    "taskKillGracePeriodSeconds": None,
    "unreachableStrategy": {
        "inactiveAfterSeconds": 900,
        "expungeAfterSeconds": 604800
    },
    "killSelection": "YOUNGEST_FIRST",
    "acceptedResourceRoles": [
        "*"
    ],
    "ports": [
        16000,
    ],
    "portDefinitions": [
        {
            "port": 16000,
            "protocol": "tcp",
            "labels": {}
        },
    ],
    "requirePorts": False,
    "versionInfo": {
        "lastScalingAt": "2017-01-16T15:48:18.007Z",
        "lastConfigChangeAt": "2017-01-16T15:48:18.007Z"
    },
    "tasksStaged": 0,
    "tasksRunning": 1,
    "tasksHealthy": 1,
    "tasksUnhealthy": 0,
    "deployments": [],
    "tasks": [
        {
            "ipAddresses": [
                {
                    "ipAddress": "127.0.0.1",
                    "protocol": "IPv4"
                }
            ],
            "stagedAt": "2017-01-16T15:48:18.463Z",
            "state": "TASK_RUNNING",
            "ports": [
                16000,
            ],
            "startedAt": "2017-01-16T15:48:42.061Z",
            "version": "2017-01-16T15:48:18.007Z",
            "id": "nginx.333d80f4-dc03-11e6-b993-e248be6c2f96",
            "appId": "/scheduler-alwaysthere",
            "slaveId": "8ad5a85c-c14b-4cca-a089-b9dc006e7286-S0",
            "host": "127.0.0.1",
            "healthCheckResults": [
                {
                    "alive": True,
                    "consecutiveFailures": 0,
                    "firstSuccess": "2017-01-16T15:48:59.141Z",
                    "lastFailure": None,
                    "lastSuccess": "2017-01-16T15:48:59.141Z",
                    "lastFailureCause": None,
                    "instanceId": "nginx.marathon-333d80f4-dc03-11e6-b993-e248be6c2f96"
                }
            ]
        }
    ]
}

def app_from_template(app_id, port, ip="127.0.0.1", scheme="http"):
    """Create a Marathon app entry basing on the supplied data and the template

    Arguments:
        app_id (string): app ID that the new app should have
        port (string): TCP/IP port that the app should pretend to have
        ip (string): IP address that the new apps hould pretend to listen on
        scheme (string): scheme that given service uses

    Returns:
        App dict mimicing the one returned by Marathon
    """
    res = copy.deepcopy(SCHEDULER_APP_TEMPLATE)
    res['id'] = '/' + app_id
    res['labels']['DCOS_SERVICE_NAME'] = app_id
    res['labels']['DCOS_SERVICE_SCHEME'] = scheme
    res['portDefinitions'][0]['port'] = port
    res['ports'] = [port]
    res['tasks'][0]['appId'] = app_id
    res['tasks'][0]['ports'] = [port]
    res['tasks'][0]['host'] = ip
    res['tasks'][0]['ipAddresses'][0]['ipAddress'] = ip

    return res

SCHEDULER_APP_ALWAYSTHERE = \
    app_from_template('scheduler-alwaysthere', 16000)
SCHEDULER_APP_ALWAYSTHERE_DIFFERENTPORT = \
    app_from_template('scheduler-alwaysthere', 16001, ip="127.0.0.15")
SCHEDULER_APP_ALWAYSTHERE_NEST1 = \
    app_from_template('nest1/scheduler-alwaysthere', 17000)
SCHEDULER_APP_ALWAYSTHERE_NEST2 =  \
    app_from_template('nest2/nest1/scheduler-alwaysthere', 18000)
SCHEDULER_APP_ONLYMARATHON_NEST2 =  \
    app_from_template('nest2/nest1/scheduler-onlymarathon', 18001)

# pylint: disable=R0903
class MarathonHTTPRequestHandler(RecordingHTTPRequestHandler):
    """A very simple request handler that simply replies with static(empty) list
       of applications to the client

    Most probably it will be extended with some extra logic as tests are
    being added.
    """
    def _calculate_response(self, base_path, url_args, body_args=None):
        """Reply with empty list of apps for the '/v2/apps' request

        Please refer to the description of the BaseHTTPRequestHandler class
        for details on the arguments and return value of this method.

        Raises:
            EndpointException: request URL path is unsupported
        """
        if base_path in ['/v2/reflect/me', '/']:
            # A test URI that is used by tests. In some cases it is impossible
            # to reuse /v2/apps path.
            return self._reflect_request(base_path, url_args, body_args)

        if base_path not in ['/v2/apps', "/v2/leader"]:
            msg = "Path `{}` is not supported yet".format(base_path)
            blob = msg.encode('utf-8')
            raise EndpointException(code=500, reason=blob)

        ctx = self.server.context

        status = 200
        content_type = 'application/json'
        with ctx.lock:
            if base_path == '/v2/apps':
                blob = self._convert_data_to_blob(ctx.data['endpoint-content'])
            elif base_path == '/v2/leader':
                if ctx.data['leader-content'] is None:
                    msg = "Marathon leader unknown"
                    blob = msg.encode('utf-8')
                    content_type = 'text/plain; charset=utf-8'
                    status = 404
                elif isinstance(ctx.data['leader-content'], str):
                    blob = ctx.data['leader-content'].encode('utf-8')
                    content_type = 'text/plain; charset=utf-8'
                else:
                    blob = self._convert_data_to_blob(ctx.data['leader-content'])

        return status, content_type, blob

# pylint: disable=R0903,C0103
class MarathonEndpoint(RecordingTcpIpEndpoint):
    """An endpoint that mimics DC/OS root Marathon"""
    def __init__(self, port, ip=''):
        super().__init__(port, ip, MarathonHTTPRequestHandler)
        self.__context_init()

    def reset(self, *_):
        """Reset the endpoint to the default/initial state."""
        with self._context.lock:
            super().reset()
            self.__context_init()

    def set_apps_response(self, apps):
        """Change the response content for apps endpoint

        Arguments:
            apps (dict): a dict of marathon app dicts describing mocked
                apps
        """
        with self._context.lock:
            self._context.data["endpoint-content"] = apps

    def remove_leader(self, *_):
        """Change the endpoint output so that it simulates absence of the Marathon
           leader node.
        """
        with self._context.lock:
            self._context.data["leader-content"] = None

    def change_leader(self, new_leader):
        """Change the endpoint output so that it responds with a non-default
           Marathon leader node.
        """
        with self._context.lock:
            self._context.data["leader-content"] = {"leader": new_leader}

    def break_leader_reply(self, *_):
        """Change the endpoint output so that it responds with a broken
           reply to a query for Marathon leader node.

           NOTE: We cannot just use `always_bork` here as we need a more fine-grained
           control on what we are breaking. E.G. cache tests need to have apps
           endpoint up and running while testing broken leader endpoint and
           vice-versa.
        """
        with self._context.lock:
            self._context.data["leader-content"] = 'blah blah buh buh'

    def __context_init(self):
        """Helper function meant to initialize all the data relevant to this
           particular type of endpoint"""
        self._context.data["endpoint-content"] = copy.deepcopy({"apps": [
            SCHEDULER_APP_ALWAYSTHERE,
            SCHEDULER_APP_ALWAYSTHERE_NEST1,
            SCHEDULER_APP_ALWAYSTHERE_NEST2,
            SCHEDULER_APP_ONLYMARATHON_NEST2,
            ]})
        self._context.data["leader-content"] = {"leader": "127.0.0.2:80"}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package wvlet.airframe
import java.util.Properties
import wvlet.airframe.config.Config.REPORT_UNUSED_PROPERTIES
import wvlet.airframe.surface.Surface
import wvlet.log.{LogSupport, Logger}

/**
  */
package object config {
  private val logger = Logger("wvlet.airframe.config")

  implicit class ConfigurableDesign(d: Design) extends ConfigPackageCompat {
    def showConfig: Design = {
      processConfig { c => logger.info(c.printConfig) }
    }

    /**
      * Process Config
      */
    def processConfig(configProcessor: Config => Unit): Design = {
      configProcessor(currentConfig)
      d
    }

    // Get config binded in the design.
    def getConfig: Option[Config] = {
      d.getDesignConfig.options.get("config").map(_.asInstanceOf[Config])
    }

    def currentConfig: Config = {
      getConfig match {
        case Some(c) => c
        case None    => Config()
      }
    }

    def withConfig(c: Config): Design = {
      d.withOption("config", c)
    }

    def withConfigEnv(env: String, defaultEnv: String = "default"): Design = {
      d.withConfig(currentConfig.withEnv(env, defaultEnv))
    }

    def withConfigPaths(configPaths: Seq[String]): Design = {
      d.withConfig(currentConfig.withConfigPaths(configPaths))
    }

    private[config] def bindConfigInternal[A](surface: Surface, config: A)(implicit sourceCode: SourceCode): Design = {
      val configHolder = currentConfig.registerOfSurface[A](surface, config)
      d.withConfig(configHolder)
        .bind(surface)(sourceCode).toInstance(config)
    }

    private[config] def bindConfigFromYamlInternal[A](
        surface: Surface,
        yamlFile: String
    )(implicit sourceCode: SourceCode): Design = {
      val configHolder = currentConfig.registerFromYaml[A](surface, yamlFile)
      d.withConfig(configHolder)
        .bind(surface)(sourceCode).toInstance(configHolder.ofSurface[A](surface))
    }

    private[config] def bindConfigFromYamlInternal[A](surface: Surface, yamlFile: String, defaultValue: => A)(implicit
        sourceCode: SourceCode
    ): Design = {
      val configHolder = currentConfig.registerFromYamlOrElse[A](surface, yamlFile, defaultValue)
      val newConfig    = configHolder.ofSurface[A](surface)
      d.withConfig(configHolder)
        .bind(surface)(sourceCode).toInstance(newConfig)
    }

    /**
      * Override a subset of the configuration parameters, registered to the design.
      */
    def overrideConfigParams(
        props: Map[String, Any],
        onUnusedProperties: Properties => Unit = REPORT_UNUSED_PROPERTIES
    )(implicit sourceCode: SourceCode): Design = {
      overrideConfig { c => c.overrideWith(props, onUnusedProperties) }
    }

    /**
      * Override a subset of the configuration parameters, registered to the design.
      */
    def overrideConfigParamsWithProperties(
        props: Properties,
        onUnusedProperties: Properties => Unit = REPORT_UNUSED_PROPERTIES
    ): Design = {
      overrideConfig { c => c.overrideWithProperties(props, onUnusedProperties) }
    }

    /**
      * Override a subset of the configuration parameters, registered to the design.
      */
    def overrideConfigWithPropertiesFile(
        propertiesFile: String,
        onUnusedProperties: Properties => Unit = REPORT_UNUSED_PROPERTIES
    )(implicit sourceCode: SourceCode): Design = {
      overrideConfig { c => c.overrideWithPropertiesFile(propertiesFile, onUnusedProperties) }
    }

    private def overrideConfig(f: Config => Config)(implicit sourceCode: SourceCode): Design = {
      val configHolder = f(currentConfig)
      val d2           = d.withConfig(configHolder)

      // Override already bounded config instances
      val d3 = configHolder.getAll.foldLeft(d2) { (d: Design, c: ConfigHolder) =>
        d.bind(c.tpe)(sourceCode).toInstance(c.value)
      }
      d3
    }
  }
}


text: Base de datos para los doctores


text:
"""
test_utils
------------

Tests for `cookiecutter.utils` module.
"""

import os
import pytest
import stat
import sys

from cookiecutter import utils

def make_readonly(path):
    """Helper function that is called in the tests to change the access
    permissions of the given file.
    """
    mode = os.stat(path).st_mode
    os.chmod(path, mode & ~stat.S_IWRITE)

def test_rmtree():
    os.mkdir('foo')
    with open('foo/bar', "w") as f:
        f.write("Test data")
    make_readonly('foo/bar')
    utils.rmtree('foo')
    assert not os.path.exists('foo')

def test_make_sure_path_exists():
    if sys.platform.startswith('win'):
        existing_directory = os.path.abspath(os.curdir)
        uncreatable_directory = 'a*b'
    else:
        existing_directory = '/usr/'
        uncreatable_directory = '/this-doesnt-exist-and-cant-be-created/'

    assert utils.make_sure_path_exists(existing_directory)
    assert utils.make_sure_path_exists('tests/blah')
    assert utils.make_sure_path_exists('tests/trailingslash/')
    assert not utils.make_sure_path_exists(uncreatable_directory)
    utils.rmtree('tests/blah/')
    utils.rmtree('tests/trailingslash/')

def test_workin():
    cwd = os.getcwd()
    ch_to = 'tests/files'

    class TestException(Exception):
        pass

    def test_work_in():
        with utils.work_in(ch_to):
            test_dir = os.path.join(cwd, ch_to).replace("/", os.sep)
            assert test_dir == os.getcwd()
            raise TestException()

    # Make sure we return to the correct folder
    assert cwd == os.getcwd()

    # Make sure that exceptions are still bubbled up
    with pytest.raises(TestException):
        test_work_in()


text:
<!DOCTYPE html>

    <meta http-equiv="refresh" content="0;URL=fn.SDL_SetTextureBlendMode.html">

Redirecting to fn.SDL_SetTextureBlendMode.html...


text:
function getCourse(courseId) {
  for(c in courses){

    if (courses[c].id == courseId) {
      return courses[c];
    }

  }
}

function existsCourse(courseId) {
  for(c in courses) {
    if (courses[c].id == courseId) {
      return true;
    }
  }

  return false;
}

function getFirstCourseId() {
  return 1;
}

function getLastCourseId() {
    return 10;
}


text:
begin work;

UPDATE citation SET journal = 'Organisms Diversity & Evolution'
WHERE journal = 'Organisms, Diversity and Evolution'
OR journal = 'Organisms Diversity and Evolution';

-- should result in about 11 changes

commit;


text:
@implementation NSValueTransformer (MTLInversionAdditions)

- (NSValueTransformer *)mtl_invertedTransformer {
	NSParameterAssert(self.class.allowsReverseTransformation);

	if ([self conformsToProtocol:@protocol(MTLTransformerErrorHandling)]) {
		NSParameterAssert([self respondsToSelector:@selector(reverseTransformedValue:success:error:)]);

		id<MTLTransformerErrorHandling> errorHandlingSelf = (id)self;

		return [MTLValueTransformer transformerUsingForwardBlock:^(id value, BOOL *success, NSError **error) {
			return [errorHandlingSelf reverseTransformedValue:value success:success error:error];
		} reverseBlock:^(id value, BOOL *success, NSError **error) {
			return [errorHandlingSelf transformedValue:value success:success error:error];
		}];
	} else {
		return [MTLValueTransformer transformerUsingForwardBlock:^(id value, BOOL *success, NSError **error) {
			return [self reverseTransformedValue:value];
		} reverseBlock:^(id value, BOOL *success, NSError **error) {
			return [self transformedValue:value];
		}];
	}
}

@end


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Micol. Veg. Medit. 12(2): 107 (1997)

#### Original name
Sebacina plumbea Bres. & Torrend

### Remarks
null


text:
<?php
// Generated by ZF2's ./bin/classmap_generator.php
return array(
    'WwtgRealEstate\Module'                        => __DIR__ . '/Module.php',
    'WwtgRealEstate\Controller\ResidentController' => __DIR__ . '/src/WwtgRealEstate/Controller/ResidentController.php',
    'WwtgRealEstateTest\Framework\TestCase'        => __DIR__ . '/tests/WwtgRealEstate/Framework/TestCase.php',
    'WwtgRealEstateTest\SampleTest'                => __DIR__ . '/tests/WwtgRealEstate/SampleTest.php',
);


text:
'use strict';

/* Services */

// Demonstrate how to register services
// In this case it is a simple value service.
angular.module('myApp.services', []).factory('faye', function(){
  return new Faye.Client('http://dampfturbine.arrowsoft.de:8001/');
})


text:
/* -*- mode: c; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/* tests/plugorder.c - Test harness to display the order of loaded plugins */
/*
 * Copyright (C) 2013 by the Massachusetts Institute of Technology.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * * Redistributions of source code must retain the above copyright
 *   notice, this list of conditions and the following disclaimer.
 *
 * * Redistributions in binary form must reproduce the above copyright
 *   notice, this list of conditions and the following disclaimer in
 *   the documentation and/or other materials provided with the
 *   distribution.
 *
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
 * FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
 * COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 */

/*
 * This file registers a few dummy built-in pwqual modules, then prints out the
 * order of pwqual modules returned by k5_plugin_load_all.  The choice of the
 * pwqual interface is mostly arbitrary; it is an interface which libkrb5
 * itself doesn't use, for which we have a test module.
 */

#include "k5-int.h"
#include <krb5/pwqual_plugin.h>

static krb5_context ctx;

static void
check(krb5_error_code code)
{
    const char *errmsg;

    if (code) {
        errmsg = krb5_get_error_message(ctx, code);
        fprintf(stderr, "%s\n", errmsg);
        krb5_free_error_message(ctx, errmsg);
        exit(1);
    }
}

static krb5_error_code
blt1(krb5_context context, int maj_ver, int min_ver, krb5_plugin_vtable vtable)
{
    ((krb5_pwqual_vtable)vtable)->name = "blt1";
    return 0;
}

static krb5_error_code
blt2(krb5_context context, int maj_ver, int min_ver, krb5_plugin_vtable vtable)
{
    ((krb5_pwqual_vtable)vtable)->name = "blt2";
    return 0;
}

static krb5_error_code
blt3(krb5_context context, int maj_ver, int min_ver, krb5_plugin_vtable vtable)
{
    ((krb5_pwqual_vtable)vtable)->name = "blt3";
    return 0;
}

int
main()
{
    krb5_plugin_initvt_fn *modules = NULL, *mod;
    struct krb5_pwqual_vtable_st vt;

    check(krb5_init_context(&ctx));
    check(k5_plugin_register(ctx, PLUGIN_INTERFACE_PWQUAL, "blt1", blt1));
    check(k5_plugin_register(ctx, PLUGIN_INTERFACE_PWQUAL, "blt2", blt2));
    check(k5_plugin_register(ctx, PLUGIN_INTERFACE_PWQUAL, "blt3", blt3));
    check(k5_plugin_load_all(ctx, PLUGIN_INTERFACE_PWQUAL, &modules));
    for (mod = modules; *mod != NULL; mod++) {
        check((*mod)(ctx, 1, 1, (krb5_plugin_vtable)&vt));
        printf("%s\n", vt.name);
    }
    return 0;
}


text:
package org.ovirt.engine.api.restapi.resource;

import static org.easymock.EasyMock.anyObject;
import static org.easymock.EasyMock.eq;
import static org.easymock.EasyMock.expect;

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

import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.Response;
import javax.ws.rs.core.UriInfo;

import org.junit.Ignore;
import org.junit.Test;
import org.ovirt.engine.api.model.Fault;
import org.ovirt.engine.api.model.MacPool;
import org.ovirt.engine.core.common.action.MacPoolParameters;
import org.ovirt.engine.core.common.action.VdcActionType;
import org.ovirt.engine.core.common.queries.IdQueryParameters;
import org.ovirt.engine.core.common.queries.VdcQueryParametersBase;
import org.ovirt.engine.core.common.queries.VdcQueryReturnValue;
import org.ovirt.engine.core.common.queries.VdcQueryType;
import org.ovirt.engine.core.compat.Guid;

public class BackendMacPoolsResourceTest
        extends AbstractBackendCollectionResourceTest<MacPool, org.ovirt.engine.core.common.businessentities.MacPool, BackendMacPoolsResource> {

    protected static final Guid MAC_POOL_ID = GUIDS[0];
    private VdcQueryType listQueryType;
    private Class<? extends VdcQueryParametersBase> listQueryParamsClass;

    public BackendMacPoolsResourceTest() {
        super(new BackendMacPoolsResource(), null, "");
        this.listQueryType = VdcQueryType.GetAllMacPools;
        this.listQueryParamsClass = VdcQueryParametersBase.class;
    }

    @Override
    protected List<MacPool> getCollection() {
        return collection.list().getMacPools();
    }

    @Test
    public void testAddMacPool() throws Exception {
        setUriInfo(setUpBasicUriExpectations());
        setUpCreationExpectations(VdcActionType.AddMacPool,
                MacPoolParameters.class,
                new String[] {},
                new Object[] {},
                true,
                true,
                GUIDS[0],
                VdcQueryType.GetMacPoolById,
                IdQueryParameters.class,
                new String[] { "Id" },
                new Object[] { Guid.Empty },
                getEntity(0));
        MacPool model = getModel(0);

        Response response = collection.add(model);
        assertEquals(201, response.getStatus());
        assertTrue(response.getEntity() instanceof MacPool);
        verifyModel((MacPool) response.getEntity(), 0);
    }

    @Test
    public void testAddMacPoolCantDo() throws Exception {
        doTestBadAddMacPool(false, true, CANT_DO);
    }

    @Test
    public void testAddMacPoolFailure() throws Exception {
        doTestBadAddMacPool(true, false, FAILURE);
    }

    private void doTestBadAddMacPool(boolean valid, boolean success, String detail) throws Exception {
        setUriInfo(setUpActionExpectations(VdcActionType.AddMacPool,
                MacPoolParameters.class,
                new String[] {},
                new Object[] {},
                valid,
                success));
        MacPool model = getModel(0);

        try {
            collection.add(model);
            fail("expected WebApplicationException");
        } catch (WebApplicationException wae) {
            verifyFault(wae, detail);
        }
    }

    @Test
    public void testAddIncompleteParameters() throws Exception {
        MacPool model = createIncompleteMacPool();
        setUriInfo(setUpBasicUriExpectations());
        control.replay();
        try {
            collection.add(model);
            fail("expected WebApplicationException on incomplete parameters");
        } catch (WebApplicationException wae) {
            verifyIncompleteException(wae, "MacPool", "add", getIncompleteFields());
        }
    }

    protected String[] getIncompleteFields() {
        return new String[] { "name" };
    }

    protected MacPool createIncompleteMacPool() {
        MacPool macPool = new MacPool();
        return macPool;
    }

    @Test
    @Ignore
    @Override
    public void testQuery() throws Exception {
    }

    @Override
    @Test
    public void testList() throws Exception {
        UriInfo uriInfo = setUpUriExpectations(null);
        setUpMacPoolsQueryExpectations(null);
        control.replay();
        collection.setUriInfo(uriInfo);
        verifyCollection(getCollection());
    }

    @Override
    @Test
    public void testListFailure() throws Exception {
        setUpMacPoolsQueryExpectations(FAILURE);
        UriInfo uriInfo = setUpUriExpectations(null);
        collection.setUriInfo(uriInfo);
        control.replay();

        try {
            getCollection();
            fail("expected WebApplicationException");
        } catch (WebApplicationException wae) {
            assertTrue(wae.getResponse().getEntity() instanceof Fault);
            assertEquals(mockl10n(FAILURE), ((Fault) wae.getResponse().getEntity()).getDetail());
        }
    }

    @Override
    @Test
    public void testListCrash() throws Exception {
        Throwable t = new RuntimeException(FAILURE);
        setUpMacPoolsQueryExpectations(t);

        UriInfo uriInfo = setUpUriExpectations(null);
        collection.setUriInfo(uriInfo);

        control.replay();

        try {
            getCollection();
            fail("expected WebApplicationException");
        } catch (WebApplicationException wae) {
            verifyFault(wae, BACKEND_FAILED_SERVER_LOCALE, t);
        }
    }

    @Override
    @Test
    public void testListCrashClientLocale() throws Exception {
        UriInfo uriInfo = setUpUriExpectations(null);
        locales.add(CLIENT_LOCALE);

        Throwable t = new RuntimeException(FAILURE);
        setUpMacPoolsQueryExpectations(t);
        collection.setUriInfo(uriInfo);

        control.replay();
        try {
            getCollection();
            fail("expected WebApplicationException");
        } catch (WebApplicationException wae) {
            verifyFault(wae, BACKEND_FAILED_CLIENT_LOCALE, t);
        } finally {
            locales.clear();
        }
    }

    private void setUpMacPoolsQueryExpectations(Object failure) {
        VdcQueryReturnValue queryResult = control.createMock(VdcQueryReturnValue.class);
        expect(queryResult.getSucceeded()).andReturn(failure == null).anyTimes();
        List<org.ovirt.engine.core.common.businessentities.MacPool> entities = new ArrayList<>();

        if (failure == null) {
            for (int i = 0; i < NAMES.length; i++) {
                entities.add(getEntity(i));
            }
            expect(queryResult.getReturnValue()).andReturn(entities).anyTimes();
        } else {
            if (failure instanceof String) {
                expect(queryResult.getExceptionString()).andReturn((String) failure).anyTimes();
                setUpL10nExpectations((String) failure);
            } else if (failure instanceof Exception) {
                expect(backend.runQuery(eq(listQueryType),
                        anyObject(listQueryParamsClass))).andThrow((Exception) failure).anyTimes();
                return;
            }
        }
        expect(backend.runQuery(eq(listQueryType), anyObject(listQueryParamsClass))).andReturn(
                queryResult);
    }

    static MacPool getModel(int index) {
        MacPool model = new MacPool();
        model.setId(GUIDS[index].toString());
        model.setName(NAMES[index]);
        model.setDescription(DESCRIPTIONS[index]);
        return model;
    }

    protected List<org.ovirt.engine.core.common.businessentities.MacPool> getEntityList() {
        List<org.ovirt.engine.core.common.businessentities.MacPool> entities = new ArrayList<>();
        for (int i = 0; i < NAMES.length; i++) {
            entities.add(getEntity(i));
        }

        return entities;
    }

    @Override
    protected org.ovirt.engine.core.common.businessentities.MacPool getEntity(int index) {
        return setUpEntityExpectations(control.createMock(org.ovirt.engine.core.common.businessentities.MacPool.class),
                index);
    }

    static org.ovirt.engine.core.common.businessentities.MacPool setUpEntityExpectations(org.ovirt.engine.core.common.businessentities.MacPool entity,
            int index) {
        expect(entity.getId()).andReturn(GUIDS[index]).anyTimes();
        expect(entity.getName()).andReturn(NAMES[index]).anyTimes();
        expect(entity.getDescription()).andReturn(DESCRIPTIONS[index]).anyTimes();
        return entity;
    }
}


text:
package com.dumptruckman.tools.permission;

import org.bukkit.Bukkit;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.Permission;
import org.bukkit.permissions.PermissionDefault;
import org.bukkit.plugin.Plugin;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

public class Perm {

    /**
     * Permission for debug command.
     */
    public static final Perm COMMAND_DEBUG = new Perm.Builder("debug")
            .desc("Spams the console a bunch.").def(PermissionDefault.OP).build();
    /**
     * Permission for reload command.
     */
    public static final Perm COMMAND_RELOAD = new Perm.Builder("reload")
            .desc("Reloads the config file.").def(PermissionDefault.OP).build();

    private String name;
    private final String description;
    private final Map<String, Boolean> children;
    private final PermissionDefault permissionDefault;

    private Permission permission = null;

    private Perm(String name, String description, Map<String, Boolean> children, PermissionDefault permissionDefault) {
        this.name = name;
        this.description = description;
        this.children = children;
        this.permissionDefault = permissionDefault;
    }

    public final void setName(String name) {
        if (permission != null) {
            throw new IllegalStateException("Permission already finalized!");
        }
        this.name = name;
    }

    public final String getName() {
        return this.name;
    }

    public final String getDescription() {
        return this.description;
    }

    public final Map<String, Boolean> getChildren() {
        return this.children;
    }

    public final PermissionDefault getPermissionDefault() {
        return this.permissionDefault;
    }

    /**
     * Checks if the sender has the node in question.
     *
     * @param sender CommandSender to check permission for.
     * @return True if sender has the permission.
     */
    public final boolean hasPermission(CommandSender sender) throws IllegalStateException {
        return sender.hasPermission(getPermission());
    }

    public final Permission getPermission() throws IllegalStateException {
        if (!Perm.isRegistered(this)) {
            if (plugin == null) {
                throw new IllegalStateException("Plugin must be registered first!");
            }
            setName(plugin.getDescription().getName() + "." + getName());
            this.permission = new Permission(this.name, this.description, this.permissionDefault, this.children);
            Bukkit.getPluginManager().addPermission(this.permission);
            registeredPerms.add(this);
        }
        return this.permission;
    }

    public static class Builder {

        String name;
        private String description = "";
        private Map<String, Boolean> children = new HashMap<String, Boolean>();
        private PermissionDefault permissionDefault = PermissionDefault.OP;

        public Builder(String permName) {
            this.name = permName;
        }

        public Builder desc(String description) {
            this.description = description;
            return this;
        }

        public Builder child(String name, Boolean state) {
            children.put(name, state);
            return this;
        }

        public Builder def(PermissionDefault permissionDefault) {
            this.permissionDefault = permissionDefault;
            return this;
        }

        public Perm build() {
            return new Perm(this.name, this.description, this.children, this.permissionDefault);
        }
    }

    private static Plugin plugin = null;

    /**
     * Registers all Permission to the plugin.
     *
     * @param plugin Plugin to register permissions to.
     */
    public static void registerPlugin(Plugin plugin) {
        if (Perm.plugin != null) {
            throw new IllegalStateException("May not register another plugin!");
        }
        Perm.plugin = plugin;
    }

    static final Set<Perm> registeredPerms = new HashSet<Perm>();

    private static boolean isRegistered(Perm perm) {
        return registeredPerms.contains(perm);
    }
}


text:
	<meta http-equiv="content-type" content="text/html; charset=utf-8">
     <title>Magic Mirror Config</title>
           <link rel="stylesheet" type="text/css" href="css/main.css">

						<input type="button" id="lefteyebutton" name="Text 1" value="left eye" onclick="righteye=false; lefteye=true;">
						<input type="button" id="righteyebutton" name="Text 1" value="right eye" onclick="righteye=true; lefteye=false;">

						x=<input name="le_x" id="le_x" type="text" value="" size="3" maxlength="6" disabled="disabled"> y=<input name="le_y" id="le_y" type="text" value="" size="3" maxlength="6" disabled="disabled">
						x=<input name="re_x" id="re_x" type="text" value="" size="3" maxlength="6" disabled="disabled"> y=<input name="re_y" id="re_y" type="text" value="" size="3" maxlength="6" disabled="disabled">
						<input type="button" id="submit" name="eyes" value="Save" disabled="disabled" onclick="sendeyes();">


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

<title>Overview (apache-cassandra API)</title>
<meta name="date" content="2016-04-28">
<link rel="stylesheet" type="text/css" href="stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Packages

Package
Description

org.apache.cassandra.auth

org.apache.cassandra.cache

org.apache.cassandra.client

org.apache.cassandra.concurrent

org.apache.cassandra.config

org.apache.cassandra.cql3

org.apache.cassandra.cql3.functions

org.apache.cassandra.cql3.restrictions

org.apache.cassandra.cql3.selection

org.apache.cassandra.cql3.statements

org.apache.cassandra.db

org.apache.cassandra.db.columniterator

org.apache.cassandra.db.commitlog

org.apache.cassandra.db.compaction

org.apache.cassandra.db.compaction.writers

org.apache.cassandra.db.composites

org.apache.cassandra.db.context

org.apache.cassandra.db.filter

org.apache.cassandra.db.index

org.apache.cassandra.db.index.composites

org.apache.cassandra.db.index.keys

org.apache.cassandra.db.lifecycle

org.apache.cassandra.db.marshal

org.apache.cassandra.dht

org.apache.cassandra.exceptions

org.apache.cassandra.gms

org.apache.cassandra.hadoop

org.apache.cassandra.hadoop.cql3

org.apache.cassandra.hadoop.pig

org.apache.cassandra.io

org.apache.cassandra.io.compress

org.apache.cassandra.io.sstable

org.apache.cassandra.io.sstable.format

org.apache.cassandra.io.sstable.format.big

org.apache.cassandra.io.sstable.metadata

org.apache.cassandra.io.util

org.apache.cassandra.locator

org.apache.cassandra.metrics

org.apache.cassandra.net

org.apache.cassandra.notifications

org.apache.cassandra.repair

org.apache.cassandra.repair.messages

org.apache.cassandra.scheduler

org.apache.cassandra.schema

org.apache.cassandra.security

org.apache.cassandra.serializers

org.apache.cassandra.service

org.apache.cassandra.service.pager

org.apache.cassandra.service.paxos

org.apache.cassandra.streaming

org.apache.cassandra.streaming.compress

org.apache.cassandra.streaming.management

org.apache.cassandra.streaming.messages

org.apache.cassandra.thrift

org.apache.cassandra.tools

org.apache.cassandra.tools.nodetool

org.apache.cassandra.tracing

org.apache.cassandra.transport

org.apache.cassandra.transport.messages

org.apache.cassandra.triggers

org.apache.cassandra.utils

org.apache.cassandra.utils.btree

org.apache.cassandra.utils.concurrent

org.apache.cassandra.utils.memory

org.apache.cassandra.utils.obs

org.apache.cassandra.utils.progress

org.apache.cassandra.utils.progress.jmx

org.apache.cassandra.utils.vint

Overview

Package

Class

Use

Tree

Deprecated

Index

Help

Prev

Next

Frames

No Frames

All Classes

Copyright © 2016 The Apache Software Foundation


text:
test -f /usr/share/acpi-support/key-constants || exit 0

. /usr/share/acpi-support/power-funcs

if [ -f /var/lib/acpi-support/screen-rotation ] ; then
  ROTATION=`cat /var/lib/acpi-support/screen-rotation`
fi

case "$ROTATION" in
	right)
	NEW_ROTATION="normal"
	;;
	*)
	NEW_ROTATION="right"
	;;
esac

for x in /tmp/.X11-unix/*; do
	displaynum=`echo $x | sed s#/tmp/.X11-unix/X##`
	getXuser;
	if [ x"$XAUTHORITY" != x"" ]; then
	    export DISPLAY=":$displaynum"
	    /usr/bin/xrandr -o $NEW_ROTATION && echo $NEW_ROTATION > /var/lib/acpi-support/screen-rotation
	fi
done


text:
Jack and the Elastic Beanstalk

Jack is a tool to manage AWS Elastic Beanstalk environments. Jack is a wrapper tool around the aws eb cli3 tool. Jack allows you to create environments using the saved template configuration file generated by eb config save. Jack moves these generated config file to the jack/cfg folder of your project and manages the config files from there.

Jack provides a jack apply command to update the Elastic Beanstalk environment. Before uploading the new configuration to Elastic Beanstalk jack first downloads the current configuration and then does a diff on the changes that you are about apply. This gives a helpful preview of exactly what will be changed. This is particularly helpful when changes are made through the Elastic Beanstalk GUI by multiple developers and are out of sync with what you thought they were.


text:
from PyQt4 import Qt
from PyQt4 import QtCore
from lttngc import model
from collections import OrderedDict
from lttngc.items import EventItem

class QLttngcObjectsListModel(Qt.QAbstractListModel):
    def __init__(self, active_icon, inactive_icon):
        super().__init__()
        self._active_icon = active_icon
        self._inactive_icon = inactive_icon
        self._items = []
        self._obj_to_row = {}

    def parent(self, child):
        return Qt.QModelIndex()

    def _items_count(self):
        return len(self._items)

    def rowCount(self, parent):
        if not parent.isValid():
            return self._items_count()
        else:
            return 0

    def data(self, index, role):
        if not index.isValid():
            return

        row = index.row()
        item = self._items[row]

        if role == QtCore.Qt.DisplayRole:
            return item.display_name
        elif role == QtCore.Qt.DecorationRole:
            return item.icon
        elif role == QtCore.Qt.ToolTipRole:
            return item.tool_tip
        elif role == QtCore.Qt.StatusTipRole:
            return item.status_tip

    def get_item_at_row(self, index):
        if index < len(self._items):
            return self._items[index]

    def _get_item_from_obj(self, obj):
        if obj in self._obj_to_row:
            row = self._obj_to_row[obj]

            return self._items[row]

    def _add_item(self, item):
        obj = item.obj
        self._items.append(item)
        self._obj_to_row[obj] = len(self._items) - 1

    def _remove_item(self, row):
        obj = self._items[row].obj
        del self._obj_to_row[obj]
        del self._items[row]

    def _update_obj_to_row(self):
        for i, item in enumerate(self._items):
            self._obj_to_row[item.obj] = i

    def _update_with_objects(self, objects):
        valid_objects = set()

        # update and insert new objects
        for obj in objects:
            item = self._get_item_from_obj(obj)

            if item is None:
                new_pos = self._items_count()
                self.beginInsertRows(Qt.QModelIndex(), new_pos, new_pos)
                item = self._obj_class(obj, self._active_icon,
                                       self._inactive_icon)
                self._add_item(item)
                self.endInsertRows()
            else:
                item.obj = obj

            valid_objects.add(obj)

        # remove invalid objects
        for i in reversed(range(len(self._items))):
            obj = self._items[i].obj

            if obj not in valid_objects:
                self.beginRemoveRows(Qt.QModelIndex(), i, i)
                self._remove_item(i)
                self.endRemoveRows()

        self._update_obj_to_row()
        self.dataChanged.emit(Qt.QModelIndex(), Qt.QModelIndex())

    @property
    def objects(self):
        return [item.obj for item in self._items]


text:
title: Tutorial pictures
keywords:
tags:
sidebar: doc_sidebar
published: true
permalink: tutorial_pictures.html
summary: File with tutorial pictures.
---
This file has pictures we use in the tutorial. It's not included in the Table of Contents, but doesn't contain any secrets either.

![open-editchart](images/tut_edit_chart.png)

![add filter](images/tut_add_filter.png)


text:
//======= Copyright (c) Valve Corporation, All rights reserved. ===============
//
// Purpose: Base class for all the objects that the player can teleport to
//
//=============================================================================

using UnityEngine;

namespace Valve.VR.InteractionSystem
{
	//-------------------------------------------------------------------------
	public abstract class TeleportMarkerBase : MonoBehaviour
	{
		public bool locked = false;
		public bool markerActive = true;

		//-------------------------------------------------
		public virtual bool showReticle
		{
			get
			{
				return true;
			}
		}

		//-------------------------------------------------
		public void SetLocked( bool locked )
		{
			this.locked = locked;

			UpdateVisuals();
		}

		//-------------------------------------------------
		public virtual void TeleportPlayer( Vector3 pointedAtPosition )
		{
		}

		//-------------------------------------------------
		public abstract void UpdateVisuals();

		//-------------------------------------------------
		public abstract void Highlight( bool highlight );

		//-------------------------------------------------
		public abstract void SetAlpha( float tintAlpha, float alphaPercent );

		//-------------------------------------------------
		public abstract bool ShouldActivate( Vector3 playerPosition );

		//-------------------------------------------------
		public abstract bool ShouldMovePlayer();
	}
}


text:
package com.netflix.ndbench.core.config;

import com.netflix.archaius.api.annotations.Configuration;
import com.netflix.archaius.api.annotations.DefaultValue;
import com.netflix.archaius.api.annotations.PropertyName;
import com.netflix.ndbench.api.plugin.common.NdBenchConstants;

/**
 * @author vchella
 */
@Configuration(prefix = NdBenchConstants.PROP_NAMESPACE)
public interface IConfiguration {

    void initialize();

    // SAMPLE DATA CONFIG
    @DefaultValue("1000")
    int getNumKeys();

    @DefaultValue("100")
    int getNumValues();

    @DefaultValue("128")
    int getDataSize();

    @DefaultValue("false")
    boolean isPreloadKeys();

    @DefaultValue("0.5")
    double getZipfExponent();

    // NUM WORKERS
    default int getNumWriters() {
        return Runtime.getRuntime().availableProcessors() * 4;
    }

    default int getNumReaders() {
        return Runtime.getRuntime().availableProcessors() * 4;
    }

    //Backfill Settings
    @DefaultValue("1")
    //This configuration usually represents number of workers on your ndbench cluster working on backfill
    int getBackfillKeySlots();

    // TEST CASE CONFIG
    @DefaultValue("true")
    boolean isWriteEnabled();

    @DefaultValue("true")
    boolean isReadEnabled();

    //Workers Config
    @DefaultValue("5")
    int getStatsUpdateFreqSeconds();

    @DefaultValue("200")
    int getStatsResetFreqSeconds();

    //DataGenerator Configs
    @DefaultValue("false")
    boolean isUseVariableDataSize();

    @DefaultValue("1000")
    int getDataSizeLowerBound();

    @DefaultValue("5000")
    int getDataSizeUpperBound();

    @DefaultValue("false")
    boolean isGenerateChecksum();

    @DefaultValue("false")
    boolean isValidateChecksum();

    //Tunable configs
    @DefaultValue("100")
    int getReadRateLimit();

    @DefaultValue("100")
    @PropertyName(name= NdBenchConstants.WRITE_RATE_LIMIT)
    int getWriteRateLimit();

    @DefaultValue("false")
    boolean isAutoTuneEnabled();

    @DefaultValue("60")
    Integer getAutoTuneRampPeriodMillisecs();

    @DefaultValue("1")
    Integer getAutoTuneIncrementIntervalMillisecs();

    @DefaultValue("1000")
    Integer getAutoTuneFinalWriteRate();

    /**
     *
     * Threshold write failure ratio beyond which no auto-tune increase will occur. By default if failure rate is
     * grows larger than 1% auto tune triggered rate increases will cease.
     *
     */
    @DefaultValue("0.01")
    Float getAutoTuneWriteFailureRatioThreshold();
}


text:
// Generated by the protocol buffer compiler.  DO NOT EDIT!
// source: google/cloud/gkehub/v1beta/configmanagement/configmanagement.proto

package com.google.cloud.gkehub.configmanagement.v1beta;

public interface ConfigSyncOrBuilder
    extends
    // @@protoc_insertion_point(interface_extends:google.cloud.gkehub.configmanagement.v1beta.ConfigSync)
    com.google.protobuf.MessageOrBuilder {

  /**
   *
   *
   *

   * Git repo configuration for the cluster.
   *

   *
   * .google.cloud.gkehub.configmanagement.v1beta.GitConfig git = 7;
   *
   * @return Whether the git field is set.
   */
  boolean hasGit();
  /**
   *
   *
   *

   * Git repo configuration for the cluster.
   *

   *
   * .google.cloud.gkehub.configmanagement.v1beta.GitConfig git = 7;
   *
   * @return The git.
   */
  com.google.cloud.gkehub.configmanagement.v1beta.GitConfig getGit();
  /**
   *
   *
   *

   * Git repo configuration for the cluster.
   *

   *
   * .google.cloud.gkehub.configmanagement.v1beta.GitConfig git = 7;
   */
  com.google.cloud.gkehub.configmanagement.v1beta.GitConfigOrBuilder getGitOrBuilder();

  /**
   *
   *
   *

   * Specifies whether the Config Sync Repo is
   * in "hierarchical" or "unstructured" mode.
   *

   *
   * string source_format = 8;
   *
   * @return The sourceFormat.
   */
  java.lang.String getSourceFormat();
  /**
   *
   *
   *

   * Specifies whether the Config Sync Repo is
   * in "hierarchical" or "unstructured" mode.
   *

   *
   * string source_format = 8;
   *
   * @return The bytes for sourceFormat.
   */
  com.google.protobuf.ByteString getSourceFormatBytes();
}


text:
package com.kant.design.patterns.bridge;

/**
 *
 * @author shaskant
 *
 */
public interface Color {
	public void applyColor();
}