Instantiate a connection to the backend.
490112
def main(host='localhost', port=8086, nb_day=15):
    """"""
    nb_day = 15  # number of day to generate time series
    timeinterval_min = 5  # create an event every x minutes
    total_minutes = 1440 * nb_day
    total_records = int(total_minutes / timeinterval_min)
    now = datetime.datetime.today()
    metric = "server_data.cpu_idle"
    series = []

    for i in range(0, total_records):
        past_date = now - datetime.timedelta(minutes=i * timeinterval_min)
        value = random.randint(0, 200)
        hostName = "server-%d" % random.randint(1, 5)
        # pointValues = [int(past_date.strftime('%s')), value, hostName]
        pointValues = {
            "time": int(past_date.strftime('%s')),
            "measurement": metric,
            "fields": {
                "value": value,
            },
            "tags": {
                "hostName": hostName,
            },
        }
        series.append(pointValues)

    print(series)

    client = InfluxDBClient(host, port, USER, PASSWORD, DBNAME)

    print("Create database: " + DBNAME)
    try:
        client.create_database(DBNAME)
    except InfluxDBClientError:
        # Drop and create
        client.drop_database(DBNAME)
        client.create_database(DBNAME)

    print("Create a retention policy")
    retention_policy = 'server_data'
    client.create_retention_policy(retention_policy, '3d', 3, default=True)

    print("Write points #: {0}".format(total_records))
    client.write_points(series, retention_policy=retention_policy)

    time.sleep(2)

    query = "SELECT MEAN(value) FROM {} WHERE \
            time > now() - 10d GROUP BY time(500m)".format(metric)
    result = client.query(query, database=DBNAME)
    print(result)
    print("Result: {0}".format(result))

    print("Drop database: {}".format(DBNAME))
    client.drop_database(DBNAME)
845037
def _create_connection(self, future):
        
        LOGGER.debug('Creating a new connection for %s', self.pid)

        # Create a new PostgreSQL connection
        kwargs = utils.uri_to_kwargs(self._uri)

        try:
            connection = self._psycopg2_connect(kwargs)
        except (psycopg2.Error, OSError, socket.error) as error:
            future.set_exception(error)
            return

        # Add the connection for use in _poll_connection
        fd = connection.fileno()
        self._connections[fd] = connection

        def on_connected(cf):
            """Invoked by the IOLoop when the future is complete for the
            connection

            :param Future cf: The future for the initial connection

            """
            if cf.exception():
                self._cleanup_fd(fd, True)
                future.set_exception(cf.exception())

            else:

                try:
                    # Add the connection to the pool
                    LOGGER.debug('Connection established for %s', self.pid)
                    self._pool_manager.add(self.pid, connection)
                except (ValueError, pool.PoolException) as err:
                    LOGGER.exception('Failed to add %r to the pool', self.pid)
                    self._cleanup_fd(fd)
                    future.set_exception(err)
                    return

                self._pool_manager.lock(self.pid, connection, self)

                # Added in because psycopg2cffi connects and leaves the
                # connection in a weird state: consts.STATUS_DATESTYLE,
                # returning from Connection._setup without setting the state
                # as const.STATUS_OK
                if utils.PYPY:
                    connection.status = extensions.STATUS_READY

                # Register the custom data types
                self._register_unicode(connection)
                self._register_uuid(connection)

                # Set the future result
                future.set_result(connection)

        # Add a future that fires once connected
        self._futures[fd] = concurrent.Future()
        self._ioloop.add_future(self._futures[fd], on_connected)

        # Add the connection to the IOLoop
        self._ioloop.add_handler(connection.fileno(),
                                 self._on_io_events,
                                 ioloop.IOLoop.WRITE)
1297421
def connect(self):
        """"""
        self._socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self._socket.settimeout(self._connect_timeout)
        SocketError.wrap(self._socket.connect, (self.host, self.port))
        self._socket.settimeout(None)
        self._socket_file = self._socket.makefile('rb')
59085
def _call_backend(self, method, default, *args, **kwargs):
        """"""
        meth = getattr(self.backend, method, None)
        if meth is None:
            return default
        else:
            return meth(*args, **kwargs)
144519
function connect(options) {
  // Default driver is MySQL.
  activeBackend = options.driver || 'mysql';

  // Save the connection options for later use.
  connectionOptions = options;

  if (activeBackend === 'mysql') {
    // Save a reference to the MySQL client object for later use.
    activeDb = mysql.createClient(options);

    if (activeDb !== null) {
      activeDb.on('error', function (err) {
        console.log(err);
      });
    }
  }

  return activeDb;
}
1172315
async def setup(self):
        """"""
        while True:
            fut = self.loop.create_connection(
                lambda: SW16Protocol(
                    self,
                    disconnect_callback=self.handle_disconnect_callback,
                    loop=self.loop, logger=self.logger),
                host=self.host,
                port=self.port)
            try:
                self.transport, self.protocol = \
                    await asyncio.wait_for(fut, timeout=self.timeout)
            except asyncio.TimeoutError:
                self.logger.warning("Could not connect due to timeout error.")
            except OSError as exc:
                self.logger.warning("Could not connect due to error: %s",
                                    str(exc))
            else:
                self.is_connected = True
                if self.reconnect_callback:
                    self.reconnect_callback()
                break
            await asyncio.sleep(self.reconnect_interval)
1355401
def backend_add(cls, name, backend):
        
        oper = cls.call(
            'hosting.rproxy.server.create', cls.usable_id(name), backend)
        cls.echo('Adding backend %s:%s into webaccelerator' %
                 (backend['ip'], backend['port']))
        cls.display_progress(oper)
        cls.echo('Backend added')
        return oper
1205485
function CreateConnection (backend, credentials) {


    backend.Debug (4, "MySQL creating connection [%s]", backend.uid);
    backend.base = mysql.createConnection(credentials);

    // register event for asynchronous server errors
    backend.base.on('error', function(err) {
        backend.Debug (1, "MySQL server error=[%s]", err);

        // Sever was restarted or network connection was lost let restart connection
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
            console.log ("retry" + backend.uid)
            backend.Debug.call (backend,3, "MySQL connection lost [%s/%d] automatic connect retry in 10s]", backend.uid);
            setTimeout(function () {CreateConnection (backend, credentials);}, MYSQL_RECONNECT_TIMER);
        } else {
            throw err;  // server variable configures this)
        }
    });

    // force an initial connectiion at object construction time
    backend.base.connect (function(err) {
        if (err) {
            backend.Debug.call (backend,1, "MySQL connection fail [%s] automatic connect retry in 10s]", err);
            setTimeout(function () {CreateConnection (backend, credentials);}, MYSQL_RECONNECT_TIMER);

        } else {
            backend.Debug.call (backend,5,"MySQL Connect Done [%s]",  backend.uid);
        }
    });
}
538401
def new_connection
      Connection.new(Backburner.configuration.beanstalk_url) { |conn| Backburner::Hooks.invoke_hook_events(self, :on_reconnect, conn) }
    end
773061
def add_backend(self, backend):
        ""
        if backend in self.get_backends():
            return
        backend_link, created = BackendLink.all_tenants.get_or_create(backend=backend)
        self.backendlink_set.add(backend_link)
98558
def createConnection(self):
        """"""
        uri = self.reader.createConnection()
        return Pyro.core.getAttrProxyForURI(uri)
884353
def connect(self):
        """"""
        self._client = self._create_client()
        self._db = getattr(self._client, self._db_name)
        self._generic_dao = GenericDAO(self._client, self._db_name)
1017363
def connect(self):
    """"""
    if self.sock is not None:
      return
    backoff = 0.01
    while True:
      try:
        sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.settimeout(5)
        sock.connect((self.host, self.port))
        self.sock = sock
        return
      except socket.error:
        time.sleep(random.uniform(0, 2.0*backoff))
        backoff = min(backoff*2.0, 5.0)
1201780
function (backend) {

    backend.Debug (4, "MySQL creating connection [%s]", backend.uid);
    backend.base = mysql.createConnection(backend.opts);
    backend.count ++;
      
    // register event for asynchronous server errors
    backend.base.on('error', function(err) {
        backend.Debug (1, "MySQL server error=[%s]", err);
        // Sever was restarted or network connection was lost let restart connection
        if(err.code === 'PROTOCOL_CONNECTION_LOST') {
             backend.Debug (4, "MySQL connection lost [%s/%d] automatic connect retry in 10s]", backend.uid, backend.count);
             setTimeout(function () {CreateConnection (backend);}, MYSQL_RECONNECT_TIMER);  
             
        } else { 
            throw err;  // server variable configures this)
        };
    });
    
    // force an initial connectiion at object construction time
    backend.base.connect (function(err) {
        if (err) {
             backend.Debug (4, "MySQL connection fail [%s/%d] automatic connect retry in 10s]", backend.uid, backend.count);
             setTimeout(function () {CreateConnection (backend);}, MYSQL_RECONNECT_TIMER);  
            
        } else {
            backend.Debug (5,"MySQL Connect Done [%s]",  backend.uid);
        }
    });
}
64273
private function connect()
    {
        $this->conn = parent::getConn();
        $this->create = $this->conn->prepare($this->create);
    }
912642
function CreateConnection (backend) {

    backend.Debug (4, "MongoDB creating connection [%s]", backend.uid);
    MongoClient.connect(backend.uid, function (err, db) {
        if (err) {
            backend.Debug (0, "Fail to connect to MongoDB: %s err=[%s]", backend.uid, err)
        } else {
            backend.Debug (4, "Connected to MongoDB: %s", backend.uid)
            backend.base = db;
        }
    });
}
726361
def initiate(self, database=None, journaler=None, *backends):
        '''
        
        '''
        return self._initiate(database=database, journaler=journaler,
                              backends=backends)