Initialize an Influxdb database client
510759
def influx_init(self, url, port, user, pwd, db):
        
        try:
            cli = DataFrameClient(url, port, user, pwd, db)
            self.influx_cli = cli
        except Exception as e:
            self.err(e, self.influx_init,
                     "Can not initialize Influxdb database")
774038
def initialize_schema(connection):
  
  cursor = connection.cursor()
  cursor.execute("PRAGMA application_id={}".format(_TENSORBOARD_APPLICATION_ID))
  cursor.execute("PRAGMA user_version={}".format(_TENSORBOARD_USER_VERSION))
  with connection:
    for statement in _SCHEMA_STATEMENTS:
      lines = statement.strip('\n').split('\n')
      message = lines[0] + ('...' if len(lines) > 1 else '')
      logger.debug('Running DB init statement: %s', message)
      cursor.execute(statement)
124794
def init_db(dbURL, pwd_salt_size=None, pwd_rounds=None):
    '''
    '''
    if not dbURL:
        dbURL = 'sqlite:///:memory:'
    logging.getLogger(__name__).debug("Initializing database: {}".format(dict(url=dbURL,
                                                                              pwd_salt_size=pwd_salt_size,
                                                                              pwd_rounds=pwd_rounds)))
    try:
        db = init_proxy(dbURL)
        global pwdCryptCtx
        pwdCryptCtx = gen_crypt_context(salt_size=pwd_salt_size, rounds=pwd_rounds)
        create_tables(db)
        return db
    except Exception as e:
        e.args = (e.args[0] + ' [users database]',)
        raise
17835
def init(self, conn):
        
        base = self.read_scripts()[0]['fname']
        logging.info('Creating the initial schema from %s',  base)
        apply_sql_script(conn, os.path.join(self.upgrade_dir, base))
        self.install_versioning(conn)
216880
def Init():
  """"""
  global INIT_RAN
  if INIT_RAN:
    return

  # Set up a temporary syslog handler so we have somewhere to log problems
  # with ConfigInit() which needs to happen before we can start our create our
  # proper logging setup.
  syslog_logger = logging.getLogger("TempLogger")
  if os.path.exists("/dev/log"):
    handler = logging.handlers.SysLogHandler(address="/dev/log")
  else:
    handler = logging.handlers.SysLogHandler()
  syslog_logger.addHandler(handler)

  try:
    config_lib.SetPlatformArchContext()
    config_lib.ParseConfigCommandLine()
  except config_lib.Error:
    syslog_logger.exception("Died during config initialization")
    raise

  metric_metadata = server_metrics.GetMetadata()
  metric_metadata.extend(communicator.GetMetricMetadata())

  stats_collector = prometheus_stats_collector.PrometheusStatsCollector(
      metric_metadata, registry=prometheus_client.REGISTRY)
  stats_collector_instance.Set(stats_collector)

  server_logging.ServerLoggingStartupInit()

  bs_registry_init.RegisterBlobStores()
  all_decoders.Register()
  all_parsers.Register()
  registry.Init()

  # Exempt config updater from this check because it is the one responsible for
  # setting the variable.
  if not config.CONFIG.ContextApplied("ConfigUpdater Context"):
    if not config.CONFIG.Get("Server.initialized"):
      raise RuntimeError("Config not initialized, run \"grr_config_updater"
                         " initialize\". If the server is already configured,"
                         " add \"Server.initialized: True\" to your config.")

  INIT_RAN = True
514256
def main(host='localhost', port=8086):
    """"""
    user = 'root'
    password = 'root'
    dbname = 'example'
    dbuser = 'smly'
    dbuser_password = 'my_secret_password'
    query = 'select Float_value from cpu_load_short;'
    query_where = 'select Int_value from cpu_load_short where host=$host;'
    bind_params = {'host': 'server01'}
    json_body = [
        {
            "measurement": "cpu_load_short",
            "tags": {
                "host": "server01",
                "region": "us-west"
            },
            "time": "2009-11-10T23:00:00Z",
            "fields": {
                "Float_value": 0.64,
                "Int_value": 3,
                "String_value": "Text",
                "Bool_value": True
            }
        }
    ]

    client = InfluxDBClient(host, port, user, password, dbname)

    print("Create database: " + dbname)
    client.create_database(dbname)

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

    print("Switch user: " + dbuser)
    client.switch_user(dbuser, dbuser_password)

    print("Write points: {0}".format(json_body))
    client.write_points(json_body)

    print("Querying data: " + query)
    result = client.query(query)

    print("Result: {0}".format(result))

    print("Querying data: " + query_where)
    result = client.query(query_where, bind_params=bind_params)

    print("Result: {0}".format(result))

    print("Switch user: " + user)
    client.switch_user(user, password)

    print("Drop database: " + dbname)
    client.drop_database(dbname)
353759
def db(ctx):
    """"""

    from hfos import database
    database.initialize(ctx.obj['dbhost'], ctx.obj['dbname'])
    ctx.obj['db'] = database
804890
def _send(self):
        
        # Check to see if we have a valid socket. If not, try to connect.
        try:
            if self.influx is None:
                self.log.debug("InfluxdbHandler: Socket is not connected. "
                               "Reconnecting.")
                self._connect()
            if self.influx is None:
                self.log.debug("InfluxdbHandler: Reconnect failed.")
            else:
                # build metrics data
                metrics = []
                for path in self.batch:
                    metrics.append({
                        "points": self.batch[path],
                        "name": path,
                        "columns": ["time", "value"]})
                # Send data to influxdb
                self.log.debug("InfluxdbHandler: writing %d series of data",
                               len(metrics))
                self.influx.write_points(metrics,
                                         time_precision=self.time_precision)

                # empty batch buffer
                self.batch = {}
                self.batch_count = 0
                self.time_multiplier = 1

        except Exception:
            self._close()
            if self.time_multiplier < 5:
                self.time_multiplier += 1
            self._throttle_error(
                "InfluxdbHandler: Error sending metrics, waiting for %ds.",
                2**self.time_multiplier)
            raise
486259
def init(self):
        """"""
        if not self.export_enable:
            return None

        try:
            db = potsdb.Client(self.host,
                               port=int(self.port),
                               check_host=True)
        except Exception as e:
            logger.critical("Cannot connect to OpenTSDB server %s:%s (%s)" % (self.host, self.port, e))
            sys.exit(2)

        return db
920946
public function init()
    {
        if ($this->isEnabled()) {
            $this->client = \PHPDaemon\Clients\Valve\Pool::getInstance();
            $this->db = \MongoClient::getInstance();
            $this->servers = $this->db->{$this->config->dbname->value . '.servers'};
        }
    }
379892
def __run(db_name,argv):
    
    tango.Util.set_use_db(False)
    util = tango.Util(argv)
    __monkey_patch_util(util)
    __monkey_patch_database_class()

    dbi = DbInter()
    util.set_interceptors(dbi)

    def post_init_cb():
        logging.debug("post_init_cb()")
        util = tango.Util.instance()
        dserver = util.get_dserver_device()
        dserver_name = dserver.get_name()
        dserver_ior = util.get_dserver_ior(dserver)
        dbase = util.get_device_by_name(db_name)
        dbase_name = dbase.get_name()
        dbase_ior = util.get_device_ior(dbase)
        host = util.get_host_name()
        pid = util.get_pid_str()
        version = util.get_version_str()
        DbExportDevice(dbase, [dserver_name, dserver_ior, host, pid, version])
        DbExportDevice(dbase, [dbase_name, dbase_ior, host, pid, version])

    run((DataBase,), args=argv, util=util, post_init_callback=post_init_cb,
        green_mode=GreenMode.Gevent, verbose=True)
964929
@PostConstruct
    public void initDatabase() {
        MongoDBInit.LOGGER.info("initializing MongoDB");
        String dbName = System.getProperty("mongodb.name");
        if (dbName == null) {
            throw new RuntimeException("Missing database name; Set system property 'mongodb.name'");
        }
        MongoDatabase db = this.mongo.getDatabase(dbName);

        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources("classpath*:mongodb/*.ndjson");
            MongoDBInit.LOGGER.info("Scanning for collection data");
            for (Resource res : resources) {
                String filename = res.getFilename();
                String collection = filename.substring(0, filename.length() - 7);
                MongoDBInit.LOGGER.info("Found collection file: {}", collection);
                MongoCollection<DBObject> dbCollection = db.getCollection(collection, DBObject.class);
                try (Scanner scan = new Scanner(res.getInputStream(), "UTF-8")) {
                    int lines = 0;
                    while (scan.hasNextLine()) {
                        String json = scan.nextLine();
                        Object parse = JSON.parse(json);
                        if (parse instanceof DBObject) {
                            DBObject dbObject = (DBObject) parse;
                            dbCollection.insertOne(dbObject);
                        } else {
                            MongoDBInit.LOGGER.error("Invalid object found: {}", parse);
                            throw new RuntimeException("Invalid object");
                        }
                        lines++;
                    }
                    MongoDBInit.LOGGER.info("Imported {} objects into collection {}", lines, collection);
                }
            }
        } catch (IOException e) {
            throw new RuntimeException("Error importing objects", e);
        }
    }
650661
def init(directory=None, multidb=False):
    """"""
    if directory is None:
        directory = current_app.extensions['migrate'].directory
    config = Config()
    config.set_main_option('script_location', directory)
    config.config_file_name = os.path.join(directory, 'alembic.ini')
    config = current_app.extensions['migrate'].\
        migrate.call_configure_callbacks(config)
    if multidb:
        command.init(config, directory, 'flask-multidb')
    else:
        command.init(config, directory, 'flask')
1201436
def initdb():
    """"""
    from plnt.database import Blog, session

    make_app().init_database()
    # and now fill in some python blogs everybody should read (shamelessly
    # added my own blog too)
    blogs = [
        Blog(
            "Armin Ronacher",
            "http://lucumr.pocoo.org/",
            "http://lucumr.pocoo.org/cogitations/feed/",
        ),
        Blog(
            "Georg Brandl",
            "http://pyside.blogspot.com/",
            "http://pyside.blogspot.com/feeds/posts/default",
        ),
        Blog(
            "Ian Bicking",
            "http://blog.ianbicking.org/",
            "http://blog.ianbicking.org/feed/",
        ),
        Blog(
            "Amir Salihefendic", "http://amix.dk/", "http://feeds.feedburner.com/amixdk"
        ),
        Blog(
            "Christopher Lenz",
            "http://www.cmlenz.net/blog/",
            "http://www.cmlenz.net/blog/atom.xml",
        ),
        Blog(
            "Frederick Lundh",
            "http://online.effbot.org/",
            "http://online.effbot.org/rss.xml",
        ),
    ]
    # okay. got tired here.  if someone feels that he is missing, drop me
    # a line ;-)
    for blog in blogs:
        session.add(blog)
    session.commit()
    click.echo("Initialized database, now run manage-plnt.py sync to get the posts")
116241
def _influxdb_url(self):
        
        url = "{0}/db/{1}/series".format(self.influxdb.url.rstrip('/'), self.config.dbname)

        if self.influxdb.user and self.influxdb.password:
            url += "?u={0}&p={1}".format(self.influxdb.user, self.influxdb.password)

        return url
987223
def init(conf):
    

    logger = logging.getLogger(__name__)

    # Initialize mimetypes library
    mimetypes.init([pkg_resources.resource_filename('ehforwarderbot', 'mimetypes')])

    # Initialize all channels
    # (Load libraries and modules and init them)

    for i in conf['slave_channels']:
        logger.log(99, "\x1b[0;37;46m %s \x1b[0m", _("Initializing slave {}...").format(i))

        cls = utils.locate_module(i, 'slave')
        telemetry_set_metadata({i: cls.__version__})
        instance_id = i.split('#', 1)[1:]
        instance_id = (instance_id and instance_id[0]) or None
        coordinator.add_channel(cls(instance_id=instance_id))

        logger.log(99, "\x1b[0;37;42m %s \x1b[0m",
                   _("Slave channel {name} ({id}) # {instance_id} is initialized.")
                   .format(name=cls.channel_name, id=cls.channel_id,
                           instance_id=instance_id or _("Default profile")))

    logger.log(99, "\x1b[0;37;46m %s \x1b[0m",
               _("Initializing master {}...").format(conf['master_channel']))
    instance_id = conf['master_channel'].split('#', 1)[1:]
    instance_id = (instance_id and instance_id[0]) or None
    module = utils.locate_module(conf['master_channel'], 'master')
    coordinator.add_channel(module(instance_id=instance_id))
    telemetry_set_metadata({conf['master_channel']: module.__version__})
    logger.log(99, "\x1b[0;37;42m %s \x1b[0m",
               _("Master channel {name} ({id}) # {instance_id} is initialized.")
               .format(name=coordinator.master.channel_name,
                       id=coordinator.master.channel_id,
                       instance_id=instance_id or _("Default profile")))

    logger.log(99, "\x1b[1;37;42m %s \x1b[0m", _("All channels initialized."))
    for i in conf['middlewares']:
        logger.log(99, "\x1b[0;37;46m %s \x1b[0m", _("Initializing middleware {}...").format(i))
        cls = utils.locate_module(i, 'middleware')
        telemetry_set_metadata({i: cls.__version__})

        instance_id = i.split('#', 1)[1:]
        instance_id = (instance_id and instance_id[0]) or None
        coordinator.add_middleware(cls(instance_id=instance_id))
        logger.log(99, "\x1b[0;37;42m %s \x1b[0m",
                   _("Middleware {name} ({id}) # {instance_id} is initialized.")
                   .format(name=cls.middleware_name, id=cls.middleware_id,
                           instance_id=instance_id or _("Default profile")))

    logger.log(99, "\x1b[1;37;42m %s \x1b[0m", _("All middlewares are initialized."))

    coordinator.master_thread = threading.Thread(target=coordinator.master.poll)
    coordinator.slave_threads = {key: threading.Thread(target=coordinator.slaves[key].poll)
                                 for key in coordinator.slaves}
140586
def initialize(g, app):
    
    if 'DATABASES' in app.config and 'POSTGRESQL' in app.config['DATABASES']:
        # Database connection established for console commands
        for k, v in app.config['DATABASES']['POSTGRESQL'].items():
            init_db_conn(k, v)

        if 'test' not in sys.argv:
            # Establish a new connection every request
            @app.before_request
            def before_request():
                """
                Assign postgresql connection pool to the global
                flask object at the beginning of every request
                """
                # inject stack context if not testing
                from flask import _app_ctx_stack
                for k, v in app.config['DATABASES']['POSTGRESQL'].items():
                    init_db_conn(k, v, scopefunc=_app_ctx_stack)
                g.postgresql_pool = pool

            # avoid to close connections if testing
            @app.teardown_request
            def teardown_request(exception):
                """
                Releasing connection after finish request, not required in unit
                testing
                """
                pool = getattr(g, 'postgresql_pool', None)
                if pool is not None:
                    for k, v in pool.connections.items():
                        v.session.remove()
        else:
            @app.before_request
            def before_request():
                """
                Assign postgresql connection pool to the global
                flask object at the beginning of every request
                """
                for k, v in app.config['DATABASES']['POSTGRESQL'].items():
                    init_db_conn(k, v)
                g.postgresql_pool = pool