Runs the command-line client for the specified database.
518879
def shell(database='default'):
    

    target = engine[database]
    dialect = engine[database].dialect.name

    if dialect == 'mysql':
        args = ['mysql']

        if target.url.username:
            args += ['--user=%s' % target.url.username]

        if target.url.password:
            args += ['--password=%s' % target.url.password]

        if 'unix_socket' in target.url.query:
            args += ["--socket=%s" % target.url.query['unix_socket']]

        elif target.url.host:
            args += ["--host=%s" % target.url.host]

            if target.url.port:
                args += ["--port=%s" % target.url.port]

        if target.url.database:
            args += [target.url.database]

    elif dialect == 'sqlite':
        args = ['sqlite3', target.url.database]

    else:  # pragma: nocoverage
        raise RuntimeError(
            'Database shell not available for the dialect %r' % dialect)

    os.execvp(args[0], args)
118426
private void run(String[] args) {
        if (args.length != 2) {
            usage();
        }
        
        System.out.println("Opening Doradus server: " + args[0] + ":" + args[1]);
        try (DoradusClient client = new DoradusClient(args[0], Integer.parseInt(args[1]))) {
            deleteApplication(client);
            createApplication(client);
            addData(client);
            queryData(client);
            deleteData(client);
        }
    }
291177
def run_server(self):
        
        app = build_app()
        run(app, host='localhost', port=self.port)
784165
def main(argv=sys.argv):
    """"""
    if len(argv) < 2:
        usage(argv)

    config_uri = argv[1]

    setup_logging(config_uri)

    settings = get_appsettings(config_uri)

    engine = engine_from_config(settings, "sqlalchemy.")

    DBSession.configure(bind=engine)

    Base.metadata.create_all(engine)

    for i in range(30):
        with transaction.manager:
            address = Address(description="Address#2" + str(i).rjust(2, "0"))

            DBSession.add(address)

            user = User(
                name="User#1" + str(i).rjust(2, "0"),
                birthday=date(1980 + i % 8, i % 12 + 1, i % 10 + 1))

            user.address = address

            DBSession.add(user)
340752
def run_server(dbpath=os.path.expanduser(config.dbserver.file),
               dbhostport=None, loglevel='WARN'):
    
    if dbhostport:  # assume a string of the form "dbhost:port"
        dbhost, port = dbhostport.split(':')
        addr = (dbhost, int(port))
    else:
        addr = (config.dbserver.listen, DBSERVER_PORT)

    # create the db directory if needed
    dirname = os.path.dirname(dbpath)
    if not os.path.exists(dirname):
        os.makedirs(dirname)

    # create and upgrade the db if needed
    db('PRAGMA foreign_keys = ON')  # honor ON DELETE CASCADE
    actions.upgrade_db(db)
    # the line below is needed to work around a very subtle bug of sqlite;
    # we need new connections, see https://github.com/gem/oq-engine/pull/3002
    db.close()

    # reset any computation left in the 'executing' state
    actions.reset_is_running(db)

    # configure logging and start the server
    logging.basicConfig(level=getattr(logging, loglevel))
    DbServer(db, addr).start()
182499
def run(command, options, args):
    """"""

    if command == "backend":
        subprocess.call(("sqlite3", db_path))

    if command == "add":
        dp = pdt.Calendar()
        due = mktime(dp.parse(options.due)[0]) if options.due else None
        print "added tasks..."
        [Task(desc, due).add() for desc in args]
        return

    filters = args if len(args) else None
    rows    = Query(filters, options).find()
    tasks   = [Task(r["desc"], r["due"]) for r in rows]

    if command == "list":
        for t in tasks:
            print "\t *", t

    if command == "done":
        print "done with..."
        finished_tasks = []
        for t in tasks: 
            finished = t.done()
            if finished:
                finished_tasks.append(t)

        if not finished_tasks:
            return

        print ""
        print "finished tasks:"
        for t in finished_tasks:
            print "\t X", t
    
    if command == "remove":
        print "remove..."
        removed_tasks = []
        for t in tasks: 
            removed = t.remove()
            if removed:
                removed_tasks.append(t)
    
        if not removed_tasks:
            return
    
        print ""
        print "removed tasks:"
        for t in removed_tasks:
            print "\t RM", t
1370624
def run(client, outputs, no_output, success_codes, isolation, command_line):
    """"""
    working_dir = client.repo.working_dir
    mapped_std = _mapped_std_streams(client.candidate_paths)
    factory = CommandLineToolFactory(
        command_line=command_line,
        directory=os.getcwd(),
        working_dir=working_dir,
        successCodes=success_codes,
        **{
            name: os.path.relpath(path, working_dir)
            for name, path in mapped_std.items()
        }
    )

    with client.with_workflow_storage() as wf:
        with factory.watch(
            client, no_output=no_output, outputs=outputs
        ) as tool:
            # Make sure all inputs are pulled from a storage.
            client.pull_paths_from_storage(
                *(
                    path
                    for _, path in tool.iter_input_files(client.workflow_path)
                )
            )

            returncode = call(
                factory.command_line,
                cwd=os.getcwd(),
                **{key: getattr(sys, key)
                   for key in mapped_std.keys()},
            )

            if returncode not in (success_codes or {0}):
                raise errors.InvalidSuccessCode(
                    returncode, success_codes=success_codes
                )

            sys.stdout.flush()
            sys.stderr.flush()

            wf.add_step(run=tool)
723427
def run(self):
        """"""
        i = 0
        operation_count = int(self._parameters['operationcount'])
        while i < operation_count:
            i += 1
            weight = random.uniform(0, self._total_weight)
            for j in range(len(self._weights)):
                if weight <= self._weights[j]:
                    do_operation(self._database, self._keys,
                                 self._parameters['table'],
                                 self._operations[j], self._latencies_ms)
                    break
1310818
def handle(self, *args, **options):
        
        database = getattr(
                settings, 'LIQUIMIGRATE_DATABASE', options['database'])

        try:
            dbsettings = databases[database]
        except KeyError:
            raise CommandError("don't know such a connection: %s" % database)

        verbosity = int(options.get('verbosity'))

        # get driver
        driver_class = (
                options.get('driver')
                or dbsettings.get('ENGINE').split('.')[-1])
        dbtag, driver, classpath = LIQUIBASE_DRIVERS.get(
                            driver_class, (None, None, None))

        classpath = options.get('classpath') or classpath

        if driver is None:
            raise CommandError(
                "unsupported db driver '%s'\n"
                "available drivers: %s" % (
                    driver_class, ' '.join(LIQUIBASE_DRIVERS.keys())))

        # command options
        changelog_file = (
                options.get('changelog_file')
                or _get_changelog_file(options['database']))
        username = options.get('username') or dbsettings.get('USER') or ''
        password = options.get('password') or dbsettings.get('PASSWORD') or ''
        url = options.get('url') or _get_url_for_db(dbtag, dbsettings)

        command = options['command']
        cmdargs = {
            'jar': LIQUIBASE_JAR,
            'changelog_file': changelog_file,
            'username': username,
            'password': password,
            'command': command,
            'driver': driver,
            'classpath': classpath,
            'url': url,
            'args': ' '.join(args),
        }

        cmdline = "java -jar %(jar)s --changeLogFile %(changelog_file)s \
--username=%(username)s --password=%(password)s \
--driver=%(driver)s --classpath=%(classpath)s --url=%(url)s \
%(command)s %(args)s" % (cmdargs)

        if verbosity > 0:
            print("changelog file: %s" % (changelog_file,))
            print("executing: %s" % (cmdline,))

        created_models = None   # we dont know it

        if emit_pre_migrate_signal and not options.get('no_signals'):
            if django_19_or_newer:
                emit_pre_migrate_signal(
                        1, options.get('interactive'), database)
            else:
                emit_pre_migrate_signal(
                    created_models, 1, options.get('interactive'), database)

        rc = os.system(cmdline)

        if rc == 0:

            try:
                if not options.get('no_signals'):
                    if emit_post_migrate_signal:
                        if django_19_or_newer:
                            emit_post_migrate_signal(
                                0, options.get('interactive'), database)
                        else:
                            emit_post_migrate_signal(
                                created_models, 0,
                                options.get('interactive'), database)
                    elif emit_post_sync_signal:
                        emit_post_sync_signal(
                                created_models, 0,
                                options.get('interactive'), database)

                if not django_19_or_newer:
                    call_command(
                        'loaddata', 'initial_data', verbosity=1,
                        database=database)
            except TypeError:
                # singledb (1.1 and older)
                emit_post_sync_signal(
                        created_models, 0, options.get('interactive'))

                call_command(
                        'loaddata', 'initial_data', verbosity=0)
        else:
            raise CommandError('Liquibase returned an error code %s' % rc)
328287
def run():
    """"""

    command = sys.argv[1].strip().lower()
    print('[COMMAND]:', command)

    if command == 'test':
        return run_test()
    elif command == 'build':
        return run_build()
    elif command == 'up':
        return run_container()
    elif command == 'serve':
        import cauldron
        cauldron.run_server(port=5010, public=True)
364876
def run():
    """"""
    
    # Grab server args
    args = client_helper.grab_server_args()

    # Start up workbench connection
    workbench = zerorpc.Client(timeout=300, heartbeat=60)
    workbench.connect('tcp://'+args['server']+':'+args['port'])

    # Upload the file into workbench
    my_file = os.path.join(os.path.dirname(os.path.realpath(__file__)),
                           '../data/pe/bad/033d91aae8ad29ed9fbb858179271232')
    with open(my_file,'rb') as f:

        # Throw file into workbench
        filename = os.path.basename(my_file)
        raw_bytes = f.read()
        md5 = workbench.store_sample(raw_bytes, filename, 'exe')
        results = workbench.work_request('view', md5)
        print 'Filename: %s' % filename
        pprint.pprint(results)
544156
def run():
    """"""
    # create a arg parser and configure it.
    parser = argparse.ArgumentParser(description='SharQ Server.')
    parser.add_argument('-c', '--config', action='store', required=True,
                        help='Absolute path of the SharQ configuration file.',
                        dest='sharq_config')
    parser.add_argument('-gc', '--gunicorn-config', action='store', required=False,
                        help='Gunicorn configuration file.',
                        dest='gunicorn_config')
    parser.add_argument('--version', action='version', version='SharQ Server %s' % __version__)
    args = parser.parse_args()

    # read the configuration file and set gunicorn options.
    config_parser = ConfigParser.SafeConfigParser()
    # get the full path of the config file.
    sharq_config  = os.path.abspath(args.sharq_config)
    config_parser.read(sharq_config)

    host = config_parser.get('sharq-server', 'host')
    port = config_parser.get('sharq-server', 'port')
    bind = '%s:%s' % (host, port)
    try:
        workers = config_parser.get('sharq-server', 'workers')
    except ConfigParser.NoOptionError:
        workers = number_of_workers()

    try:
        accesslog = config_parser.get('sharq-server', 'accesslog')
    except ConfigParser.NoOptionError:
        accesslog = None

    options = {
        'bind': bind,
        'workers': workers,
        'worker_class': 'gevent'  # required for sharq to function.
    }
    if accesslog:
        options.update({
            'accesslog': accesslog
        })

    if args.gunicorn_config:
        gunicorn_config = os.path.abspath(args.gunicorn_config)
        options.update({
            'config': gunicorn_config
        })

    print """
      ___ _              ___    ___
     / __| |_  __ _ _ _ / _ \  / __| ___ _ ___ _____ _ _
     \__ \ ' \/ _` | '_| (_) | \__ \/ -_) '_\ V / -_) '_|
     |___/_||_\__,_|_|  \__\_\ |___/\___|_|  \_/\___|_|

    Version: %s

    Listening on: %s
    """ % (__version__, bind)
    server = setup_server(sharq_config)
    SharQServerApplicationRunner(server.app, options).run()
21916
def run(connection)
      connection.public_send(verb, path) do |request|
        request.params = params
        request.headers[:content_type] = Command::JSON_CONTENT_TYPE
        request.body = MultiJson.dump(body)
      end
    end
905974
function query(queryString, args, callback) {
  getClient(function (err, client) {
    if (err) { callback(err); }

    if (!client) {
      callback('Could not connect to the database');
    }
    else {
      runQuery(client, queryString, args, callback);
    }
  });
}
1305404
def Run(self):
    """"""
    global DB  # pylint: disable=global-statement
    global REL_DB  # pylint: disable=global-statement
    global BLOBS  # pylint: disable=global-statement

    if flags.FLAGS.list_storage:
      self._ListStorageOptions()
      sys.exit(0)

    try:
      cls = DataStore.GetPlugin(config.CONFIG["Datastore.implementation"])
    except KeyError:
      msg = ("No Storage System %s found." %
             config.CONFIG["Datastore.implementation"])
      if config.CONFIG["Datastore.implementation"] == "SqliteDataStore":
        msg = "The SQLite datastore is no longer supported."
      print(msg)
      print("Available options:")
      self._ListStorageOptions()
      raise ValueError(msg)

    DB = cls()  # pylint: disable=g-bad-name
    DB.Initialize()
    atexit.register(DB.Flush)
    monitor_port = config.CONFIG["Monitoring.http_port"]
    if monitor_port != 0:
      DB.InitializeMonitorThread()

    # Initialize the blobstore.
    blobstore_name = config.CONFIG.Get("Blobstore.implementation")
    try:
      cls = blob_store.REGISTRY[blobstore_name]
    except KeyError:
      raise ValueError("No blob store %s found." % blobstore_name)
    BLOBS = blob_store.BlobStoreValidationWrapper(cls())

    # Initialize a relational DB if configured.
    rel_db_name = config.CONFIG["Database.implementation"]
    if not rel_db_name:
      return

    try:
      cls = registry_init.REGISTRY[rel_db_name]
    except KeyError:
      raise ValueError("Database %s not found." % rel_db_name)
    logging.info("Using database implementation %s", rel_db_name)
    REL_DB = db.DatabaseValidationWrapper(cls())
710918
public function runAction()
    {
        try {
            $this->commandBus->dispatch(CreateDefaultProcessingConfigFile::in(ConfigLocation::fromPath(Definition::getSystemConfigDir())));

            $sqliteDbFile = SqliteDbFile::initializeFromDist(Definition::getEventStoreSqliteDbFile());

            $esConfigLocation = ConfigLocation::fromPath(Definition::getSystemConfigDir());

            $this->commandBus->dispatch(InitializeEventStore::setUpWithSqliteDbAdapter($sqliteDbFile, $esConfigLocation));

        } catch (\Exception $ex) {
            $this->commandBus->dispatch(UndoSystemSetUp::removeConfigs(
                Definition::getSystemConfigDir(),
                Definition::getSystemConfigDir(),
                Definition::getEventStoreSqliteDbFile()
            ));

            throw $ex;
        }

        return $this->redirect()->toRoute('prooph.link/system_config');
    }
761671
def run(self):
        
        self.print_message("\nBeginning database replacement process.\n")

        if self.args.source_settings:
            settings = self.parse_db_settings(self.args.source_settings)
            self.initialize_db_args(settings, 'source')

        if self.args.settings:
            settings = self.parse_db_settings(self.args.settings)
            self.initialize_db_args(settings, 'destination')

        if self.args.capture:
            self.capture_heroku_database()

        file_url = self.args.url
        if self.args.source_app:
            self.print_message("Sourcing data from backup for Heroku app '%s'"
                               % self.args.source_app)
            file_url = self.get_file_url_for_heroku_app(self.args.source_app)

        if self.args.destination_app:
            self.replace_heroku_db(file_url)
        elif self.databases['destination']['name']:
            self.replace_postgres_db(file_url)

        self.print_message("\nDone.\n\nDon't forget to update the Django Site entry if necessary!")