/*
Main function which exports the data from one database to another.
327257
public void moveDataBetweenMarklogicDBs() {
    // Empty and query to retrieve the entire set of documents. This can be
    // replaced with any cts query narrowing the scope of documents to be
    // exported.
    String rawSearch = new StringBuilder()
        .append("<search:search ")
        .append("xmlns:search='http://marklogic.com/appservices/search' xmlns:cts='http://marklogic.com/cts'>")
        .append(ctsQuery)
        .append("</search:search>")
        .toString();
    ServerTransform transform = null;
    if ( !transformName.equals("") ) {
      transform = new ServerTransform(transformName);
    }
    QueryManager queryMgr = sourceClient.newQueryManager();
    RawCombinedQueryDefinition queryDef = queryMgr.newRawCombinedQueryDefinitionAs(Format.XML, rawSearch);

    // WriteBatcher for the destination DB to write the documents
    WriteBatcher destWriteBatcher = destMoveMgr.newWriteBatcher()
        .withBatchSize(batchSize)
        .withThreadCount(threadCount)
        .onBatchSuccess(
            batch -> System.out.println("Written " + batch.getJobWritesSoFar() + " documents into the target database"))
        .onBatchFailure((batch, throwable) -> throwable.printStackTrace());
    destMoveMgr.startJob(destWriteBatcher);

    ExportListener exportListener = new ExportListener()
        .withConsistentSnapshot()
        .onDocumentReady(record -> {
          /*
           * This is where you do a client side map (write one or more documents
           * per document read) or reduce (write one document per many documents
           * read) or filter (write certain documents which match a criteria)
           * Here we do a filter to export only customer documents.
           */
          if ( record.getUri().contains("customer") ) {
            destWriteBatcher.add("/exported" + record.getUri(), record.getMetadata(new StringHandle()),
                record.getContent(new StringHandle()).withFormat(record.getFormat()));
          }
        })
        .withMetadataCategory(Metadata.COLLECTIONS);

    // Read the documents with transform if a transform is specified - (in
    // database transform)
    if ( transform != null ) {
      exportListener.withTransform(transform);
    }

    // QueryBatcher for the source DB to query the documents to be exported.
    QueryBatcher sourceQueryBatcher = sourceMoveMgr.newQueryBatcher(queryDef)
        .withBatchSize(batchSize)
        .withThreadCount(threadCount)
        .onUrisReady(exportListener)
        .onQueryFailure(exception -> exception.printStackTrace());
    sourceMoveMgr.startJob(sourceQueryBatcher);
    // Wait till the query batcher completes.
    sourceQueryBatcher.awaitCompletion();
    sourceMoveMgr.stopJob(sourceQueryBatcher);

    // Wait till the write batcher completes
    destWriteBatcher.flushAndWait();
    destMoveMgr.stopJob(destWriteBatcher);
  }
204985
function main() {
	var project = parseSource( errBuf );

	if ( project && writeDictionary( project, errBuf ) ) {
		console.log( 'localization database correctly built' );
	} // if

	if ( errBuf.length ) {
		commons.outputErrors( errBuf, console.error );
		process.exit( 1 );
	} // if

	process.exit( 0 );
}
167558
function processDatabase(argv, outputBaseFile, db, done) {
  var templates = {
    header: fs.readFileSync(path.join(templatePath, 'webgl-header.cc'), 'utf8')
  };

  var zones = db.getZones();
  if (!zones.length) {
    console.log('No zones');
    done(1);
    return;
  }

  // TODO(benvanik): find the right zone.
  var zone = zones[0];

  // Build a step list.
  console.log("Building step list...");
  var eventList = zone.getEventList();
  var frameList = zone.getFrameList();
  var steps = wtf.replay.graphics.Step.constructStepsList(eventList, frameList);

  // Open bin file.
  var binFile = new BinFile(outputBaseFile + '.bin');

  console.log("Generating code...");
  var tempDir;
  if (argv['src_output']) {
    tempDir = argv['src_output'];
  } else {
    var tempDirObj = new tmp.Dir();
    tempDir = tempDirObj.path;
    process.on('exit', function() {
      tempDirObj.rmdir();
    });
  }
  if (!fs.existsSync(tempDir)) {
    fs.mkdirSync(tempDir);
  }

  // Add all steps.
  var ccFiles = [];
  for (var n = 0; n < steps.length; n++) {
    var step = steps[n];

    // Prep file.
    var output = [];
    output.push(templates.header);

    // Add step function.
    output.push('void step_' + n + '(Replay* replay) {');
    addStep(eventList, n, step, output, binFile);
    output.push('}');

    // Flush.
    var finalOutput = output.join(os.EOL);
    var ccFile = path.basename(outputBaseFile) + '_step_' + n + '.cc';
    ccFile = path.join(tempDir, ccFile);
    fs.writeFileSync(ccFile, finalOutput);
    ccFiles.push(ccFile);
  }

  // Build statics file.
  var output = [];
  output.push(templates.header);

  // Add step list variable.
  var stepFnList = [];
  for (var n = 0; n < steps.length; n++) {
    stepFnList.push('step_' + n + ',');
    output.push('extern void step_' + n + '(Replay* replay);');
  }
  output.push(
      'StepFunction __steps[] = { ' + stepFnList.join(' ') + ' };');
  output.push(
      'int __step_count = ' + stepFnList.length + ';');
  output.push('StepFunction* __get_steps() { return __steps; }');

  // Static info.
  output.push(
      'const char* __trace_name = "' +
          path.basename(outputBaseFile) + '";');
  output.push(
      'const char* __bin_name = "' +
          path.basename(outputBaseFile) + '.bin";');

  // Write output cc file.
  console.log("Writing .cc file...");
  var finalOutput = output.join(os.EOL);
  var ccFile = path.join(tempDir, path.basename(outputBaseFile) + '.cc');
  fs.writeFileSync(ccFile, finalOutput);
  ccFiles.push(ccFile);

  // Finish bin file.
  binFile.dispose();

  // Build!
  console.log("Building executable...");
  build(argv, tempDir, outputBaseFile, ccFiles, done);
}
164662
def export_datasources(print_stdout, datasource_file,
                       back_references, include_defaults):
    """"""
    data = dict_import_export.export_to_dict(
        session=db.session,
        recursive=True,
        back_references=back_references,
        include_defaults=include_defaults)
    if print_stdout or not datasource_file:
        yaml.safe_dump(data, stdout, default_flow_style=False)
    if datasource_file:
        logging.info('Exporting datasources to %s', datasource_file)
        with open(datasource_file, 'w') as data_stream:
            yaml.safe_dump(data, data_stream, default_flow_style=False)
132253
static void export(String path, DbConn cnx) throws JqmXmlException
    {
        if (cnx == null)
        {
            throw new IllegalArgumentException("database connection cannot be null");
        }
        export(path, JobDef.select(cnx, "jd_select_all"), cnx);
    }
1341302
public static void main(String[] args) {
    SparkSession spark = SparkSession
      .builder()
      .appName("Java Spark SQL data sources example")
      .config("spark.some.config.option", "some-value")
      .getOrCreate();

    runBasicDataSourceExample(spark);
    runBasicParquetExample(spark);
    runParquetSchemaMergingExample(spark);
    runJsonDatasetExample(spark);
    runJdbcDatasetExample(spark);

    spark.stop();
  }
1283331
function main() {
  var argv = require('yargs')
    .usage('Usage: $0 [options]')
    .example('$0 -s https://user:pass@host/db -b <bucket>', 'Backup db to bucket')
    .options({
      'source': { alias: 's', nargs: 1, demandOption: true, describe: 'Source database URL' },
      'bucket': { alias: 'b', nargs: 1, demandOption: true, describe: 'Destination bucket' },
      'prefix': { alias: 'p', nargs: 1, describe: 'Prefix for backup object key', default: 'couchbackup' },
      's3url': { nargs: 1, describe: 'S3 endpoint URL' },
      'awsprofile': { nargs: 1, describe: 'The profile section to use in the ~/.aws/credentials file', default: 'default' }
    })
    .help('h').alias('h', 'help')
    .epilog('Copyright (C) IBM 2017')
    .argv;

  const sourceUrl = argv.source;
  const backupName = new url.URL(sourceUrl).pathname.split('/').filter(function(x) { return x; }).join('-');
  const backupBucket = argv.bucket;
  const backupKeyPrefix = `${argv.prefix}-${backupName}`;
  const shallow = argv.shallow;

  const backupKey = `${backupKeyPrefix}-${new Date().toISOString()}`;

  const s3Endpoint = argv.s3url;
  const awsProfile = argv.awsprofile;

  // Creds are from ~/.aws/credentials, environment etc. (see S3 docs).
  const awsOpts = {
    signatureVersion: 'v4',
    credentials: new AWS.SharedIniFileCredentials({ profile: awsProfile })
  };
  if (typeof s3Endpoint !== 'undefined') {
    awsOpts.endpoint = new AWS.Endpoint(s3Endpoint);
  }
  const s3 = new AWS.S3(awsOpts);

  debug(`Creating a new backup of ${s(sourceUrl)} at ${backupBucket}/${backupKey}...`);
  bucketAccessible(s3, backupBucket)
    .then(() => {
      return backupToS3(sourceUrl, s3, backupBucket, backupKey, shallow);
    })
    .then(() => {
      debug('done.');
    })
    .catch((reason) => {
      debug(`Error: ${reason}`);
      process.exit(1);
    });
}
531418
def db_export(schema, uuid, object_filter, export_format, filename, pretty, all_schemata, omit):
    """"""

    internal_backup(schema, uuid, object_filter, export_format, filename, pretty, all_schemata, omit)
738073
function main() {
  config = createConfig(process.argv.slice(2));

  if (config.options.help) {
    config.options.showHelp(NODE_DEBUG_MODE);
    process.exit();
  }

  if (config.options.version) {
    config.options.showVersion();
    process.exit();
  }

  process.on('SIGINT', function() {
     process.exit();
  });

  startInspectorProcess(function(error, result) {
    if (error) {
      console.error(formatNodeInspectorError(error));
      process.exit(1);
    }

    var url = result.address.url;
    var isUnixSocket = result.address.isUnixSocket;

    startDebuggedProcess(function(error) {
      if (error) {
        console.error('Cannot start %s: %s', config.subproc.script, error.message || error);
        process.exit(2);
      }

      openBrowserAndPrintInfo(url, isUnixSocket);
    });
  });
}
506095
public static void main(String[] args) throws Exception {
        try (RocksDbWrapper db = RocksDbWrapper.openReadWrite("/tmp/rocksdb")) {
            db.put("demo", String.valueOf(System.currentTimeMillis()));
        }

        try (RocksDbWrapper db = RocksDbWrapper.openReadOnly("/tmp/rocksdb")) {
            byte[] data = db.get("demo1");
            System.out.println(new String(data));
            // db.setWriteOptions(RocksDbUtils.buildWriteOptions());
            // db.delete("demo");
        }
    }
824240
def db2server(dbfile, block_size, dbuser, dbpassword):
    """"""

    _db2server.main(dbfile,
                    write_reaction=True,
                    write_ase=True,
                    write_publication=True,
                    write_reaction_system=True,
                    block_size=block_size,
                    start_block=0,
                    user=dbuser,
                    password=dbpassword)
246372
def dump(db, f, **options):  # type: (canmatrix.CanMatrix, typing.IO, **typing.Any) -> None
    
    global enum_dict
    global enums
    sym_encoding = options.get('symExportEncoding', 'iso-8859-1')

    enum_dict = {}
    enums = "{ENUMS}\n"

    header = """FormatVersion=5.0 // Do not edit this line!
Title=\"canmatrix-Export\"
"""
    f.write(header.encode(sym_encoding))

    def send_receive(for_frame):
        return (
            for_frame.attributes.get('Sendable', 'True') == 'True',
            for_frame.attributes.get('Receivable', 'True') == 'True',
        )

    sections = collections.OrderedDict((
        ('SEND', tuple(f for f in db.frames if send_receive(f) == (True, False))),
        ('RECEIVE', tuple(f for f in db.frames if send_receive(f) == (False, True))),
        ('SENDRECEIVE', tuple(f for f in db.frames if send_receive(f) == (True, True))),
    ))

    output = '\n'

    for name, frames in sections.items():
        if len(frames) == 0:
            continue

        # Frames
        output += "{{{}}}\n\n".format(name)

        # trigger all frames
        for frame in frames:
            name = "[" + frame.name + "]\n"

            if frame.arbitration_id.extended == 1:
                id_type = "ID=%08Xh" % frame.arbitration_id.id
            else:
                id_type = "ID=%03Xh" % frame.arbitration_id.id
            if frame.comment is not None and len(frame.comment) > 0:
                id_type += "\t// " + \
                    frame.comment.replace('\n', ' ').replace('\r', ' ')
            id_type += "\n"
            if frame.arbitration_id.extended == 1:
                id_type += "Type=Extended\n"
            else:
                id_type += "Type=Standard\n"

            # check if frame has multiplexed signals
            multiplex = 0
            for signal in frame.signals:
                if signal.multiplex is not None:
                    multiplex = 1

            if multiplex == 1:
                # search for multiplexor in frame:
                for signal in frame.signals:
                    if signal.multiplex == 'Multiplexor':
                        mux_signal = signal

                # ticker all possible mux-groups as i (0 - 2^ (number of bits of multiplexor))
                first = 0
                for i in range(0, 1 << int(mux_signal.size)):
                    found = 0
                    mux_out = ""
                    # ticker all signals
                    for signal in frame.signals:
                        # if signal is in mux-group i
                        if signal.multiplex == i:
                            mux_out = name
                            if first == 0:
                                mux_out += id_type
                                first = 1
                            mux_out += "DLC=%d\n" % frame.size
                            if "GenMsgCycleTime" in db.frame_defines:
                                cycle_time = frame.attribute("GenMsgCycleTime", db=db)
                                if cycle_time is not None:
                                    mux_out += "CycleTime=" + str(cycle_time) + "\n"

                            mux_name = frame.mux_names.get(i, mux_signal.name + "%d" % i)

                            mux_out += "Mux=" + mux_name
                            start_bit = mux_signal.get_startbit()
                            s = str(i)
                            if len(s) > 1:
                                length = len(
                                    '{:X}'.format(int(mux_signal.calc_max()))
                                )
                                s = '{:0{}X}h'.format(i, length)
                            if not signal.is_little_endian:
                                # Motorola
                                mux_out += " %d,%d %s -m" % (start_bit, mux_signal.size, s)
                            else:
                                mux_out += " %d,%d %s" % (start_bit, mux_signal.size, s)
                            if not mux_out.endswith('h'):
                                mux_out += ' '
                            if i in mux_signal.comments:
                                comment = mux_signal.comments.get(i)
                                if len(comment) > 0:
                                    mux_out += '\t// ' + comment
                            mux_out += "\n"
                            found = 1
                            break

                    if found == 1:
                        for signal in frame.signals:
                            if signal.multiplex == i or signal.multiplex is None:
                                mux_out += create_signal(db, signal)
                        output += mux_out + "\n"

            else:
                # no multiplex signals in frame, just 'normal' signals
                output += name
                output += id_type
                output += "DLC=%d\n" % frame.size
                if "GenMsgCycleTime" in db.frame_defines:
                    cycle_time = frame.attribute("GenMsgCycleTime", db=db)
                    if cycle_time is not None:
                        output += "CycleTime=" + str(cycle_time) + "\n"
                for signal in frame.signals:
                    output += create_signal(db, signal)
                output += "\n"
    enums += '\n'.join(sorted(enum_dict.values()))
    # write output file
    f.write((enums + '\n').encode(sym_encoding))
    f.write(output.encode(sym_encoding))
43246
public function main()
    {
        $this->validate();

        $targetDatabase = $this->getTargetDatabase();

        $platform = $this->getGeneratorConfig()->getConfiguredPlatform();

        // Load the Data XML -> DB Name properties
        $map = new Properties();
        try {
            $map->load($this->getDataDbMap());
        } catch (IOException $ioe) {
            throw new BuildException("Cannot open and process the datadbmap!", $ioe);
        }

        // Parse each file in the data -> db map
        foreach ($map->keys() as $dataXMLFilename) {

            $dataXMLFile = new PhingFile($this->srcDir, $dataXMLFilename);

            // if file exists then proceed
            if ($dataXMLFile->exists()) {

                $dbname = $map->get($dataXMLFilename);

                $db = $this->getDatabase($dbname);

                if (!$db) {
                    throw new BuildException("Cannot find instantiated Database for name '$dbname' from datadbmap file.");
                }

                $db->setPlatform($platform);

                $outFile = $this->getMappedFile($dataXMLFilename);
                $sqlWriter = new FileWriter($outFile);

                $this->log("Creating SQL from XML data dump file: " . $dataXMLFile->getAbsolutePath());

                try {
                    $dataXmlParser = new XmlToDataSQL($db, $this->getGeneratorConfig(), $this->dbEncoding);
                    $dataXmlParser->transform($dataXMLFile, $sqlWriter);
                } catch (Exception $e) {
                    throw new BuildException("Exception parsing data XML: " . $e->getMessage());
                }

                // Place the generated SQL file(s)
                $p = new Properties();
                if ($this->getSqlDbMap()->exists()) {
                    $p->load($this->getSqlDbMap());
                }

                $p->setProperty($outFile->getName(), $db->getName());
                $p->store($this->getSqlDbMap(), "Sqlfile -> Database map");
            } else {
                $this->log("File '" . $dataXMLFile->getAbsolutePath() . "' in datadbmap does not exist, so skipping it.", Project::MSG_WARN);
            }
        } // foreach data xml file

    }
448353
def main(arguments=None):
    

    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="WARNING",
        options_first=False,
        projectName=False
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    from fundamentals.mysql import sqlite2mysql
    converter = sqlite2mysql(
        log=log,
        settings=settings,
        pathToSqlite=pathToSqliteDB,
        tablePrefix=tablePrefix,
        dbConn=dbConn
    )
    converter.convert_sqlite_to_mysql()

    return
1311120
function handleExport(resultString) {
    if (resultString === "") {
        process.exit(500);
    }

    let targetPath = path.join(currentDir, argv.exportOutput);
    fs.writeFileSync(targetPath, resultString);
    console.log("Finished writing csv file to:", targetPath);
}
707279
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="HMpTy"
    )
    arguments, settings, log, dbConn = su.setup()

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    if hostFlag:
        dbSettings = {
            'host': hostFlag,
            'user': userFlag,
            'password': passwdFlag,
            'db': dbNameFlag
        }
    elif settings:
        dbSettings = settings["database settings"]

    # CALL FUNCTIONS/OBJECTS
    if index:
        add_htm_ids_to_mysql_database_table(
            raColName=raCol,
            declColName=decCol,
            tableName=tableName,
            dbConn=dbConn,
            log=log,
            primaryIdColumnName=primaryIdCol,
            reindex=forceFlag,
            dbSettings=dbSettings
        )

    if search:
        cs = conesearch(
            log=log,
            dbConn=dbConn,
            tableName=tableName,
            columns=False,
            ra=ra,
            dec=dec,
            radiusArcsec=float(radius),
            separations=True,
            distinct=False,
            sqlWhere=False
        )
        matchIndies, matches = cs.search()
        if not renderFlag:
            print matches.table()
        elif renderFlag == "json":
            print matches.json()
        elif renderFlag == "csv":
            print matches.csv()
        elif renderFlag == "yaml":
            print matches.yaml()
        elif renderFlag == "md":
            print matches.markdown()
        elif renderFlag == "table":
            print matches.markdown()
        elif renderFlag == "mysql":
            print matches.mysql(tableName=resultsTable)

    if level:
        from HMpTy import HTM
        mesh = HTM(
            depth=int(level),
            log=log
        )

        htmids = mesh.lookup_id(ra, dec)
        print htmids[0]

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
579132
@Override
    public void exportDevice(final DeviceExportInfo info) throws DevFailed {
        final String[] array = info.toStringArray();
        final DeviceData argin = new DeviceData();
        argin.insert(array);
        database.command_inout("DbExportDevice", argin);
    }