Primary method providing a template for exporting the contents of an archive
491542
protected void doExport() {
        // Get archive
        final Archive<?> archive = getArchive();
        if (log.isLoggable(Level.FINE)) {
            log.fine("Exporting archive - " + archive.getName());
        }

        // Obtain the root
        final Node rootNode = archive.get(ArchivePaths.root());

        // Recursively process the root children
        for (Node child : rootNode.getChildren()) {
            processNode(child);
        }
    }
1188591
def _write_template(upgrade_file, name, depends_on, repository, auto=False):
    """"""
    if auto:
        # Ensure all models are loaded
        from invenio_db import models
        list(models)
        template_args = produce_upgrade_operations()
        operations_str = template_args['upgrades']
        import_str = template_args['imports']
    else:
        operations_str = "    pass"
        import_str = ""

    with open(upgrade_file, 'w') as f:
        f.write(UPGRADE_TEMPLATE % {
            'depends_on': depends_on,
            'repository': repository,
            'year': date.today().year,
            'operations': operations_str,
            'imports': import_str,
            'cls': ''.join(w.capitalize() or '_' for w in name.split('_'))
        })
408071
def export(path=None, user_content=False, context=None,
           username=None, password=None, render_offline=False,
           render_wide=False, render_inline=True, out_filename=None,
           api_url=None, title=None, quiet=False, grip_class=None):
    
    export_to_stdout = out_filename == '-'
    if out_filename is None:
        if path == '-':
            export_to_stdout = True
        else:
            filetitle, _ = os.path.splitext(
                os.path.relpath(DirectoryReader(path).root_filename))
            out_filename = '{0}.html'.format(filetitle)

    if not export_to_stdout and not quiet:
        print('Exporting to', out_filename, file=sys.stderr)

    page = render_page(path, user_content, context, username, password,
                       render_offline, render_wide, render_inline, api_url,
                       title, None, quiet, grip_class)

    if export_to_stdout:
        try:
            print(page)
        except IOError as ex:
            if ex.errno != 0 and ex.errno != errno.EPIPE:
                raise
    else:
        with io.open(out_filename, 'w', encoding='utf-8') as f:
            f.write(page)
211572
def _fetch_templates(src):
    '''
    
    '''
    templates = []
    log.debug('Listing contents of %s', src)
    for item in os.listdir(src):
        s = os.path.join(src, item)
        if os.path.isdir(s):
            template_path = os.path.join(s, TEMPLATE_FILE_NAME)
            if os.path.isfile(template_path):
                templates.append(_get_template(template_path, item))
            else:
                log.debug("Directory does not contain %s %s", template_path,
                          TEMPLATE_FILE_NAME)
    return templates
688500
function generateCustomOutput(outputConfig) {

			// Accesses context
			var context = prepareBaseTemplateContext();
			_.extend(context, outputConfig.context);

			// Prepares config attributes related to template filepath
			var templatePath = outputConfig.template;
			var extension = path.extname(templatePath);
			var syntax = outputConfig.syntax || '';

			// Renders template with given context
			var template = readTemplate(templatePath, syntax, extension);
			var output = renderTemplate(template, context);

			// Prepares config attributes related to destination filepath
			var dest = outputConfig.dest || o.dest;

			var filepath;
			var destParent;
			var destName;

			if (path.extname(dest) === '') {
				// If user specifies a directory, filename should be same as template
				destParent = dest;
				destName = path.basename(outputConfig.template);
				filepath = path.join(dest, destName);
			}
			else {
				// If user specifies a file, that is our filepath
				destParent = path.dirname(dest);
				filepath = dest;
			}

			// Ensure existence of parent directory and output to file as desired
			mkdirp.sync(destParent);
			fs.writeFileSync(filepath, output);
		}
193173
def export(self, filename, fmt="DER"):
        
        f = open(filename, "wb")
        if fmt == "DER":
            f.write(self.der)
        elif fmt == "PEM":
            f.write(self.pem)
        f.close()
156858
function archiveResource(resource, primary, archive) {
        if (!resource.archive) { return true; }

        var name = resource.name;

        primary.bind(name);
        archive.bind(name);

        // get the archive criteria
        var criteria = resource.archive();

        log.info('Getting archive docs for ' + name);

        // find all the documents that match the archive criteria
        return getDocsToArchive(criteria, primary[name])
            .then(function (docs) {

                log.info('Found ' + docs.length + ' ' + name + ' docs to archive');

                // insert all of the documents into the archive database
                var deferred = Q.defer();
                archive[name].insert(docs, function (err, results) {
                    err ? deferred.reject(err) : deferred.resolve(results);
                });
                return deferred.promise;
            })
            .then(function () {

                log.info('Docs inserted into archive DB for ' + name + '. Now deleting docs in main db');

                // delete the data from the primary database
                var deferred = Q.defer();
                primary[name].remove(criteria, function (err, results) {

                    log.info('Deleting docs complete for ' + name);

                    err ? deferred.reject(err) : deferred.resolve(results);
                });
                return deferred.promise;

            });
    }
1121936
def export(string, template=None, **extra):
    

    def wrapped(f):
        endpoint = (f.__module__ + "." + f.__name__)[16:]
        if template is not None:
            old_f = f

            def f(**kwargs):
                rv = old_f(**kwargs)
                if not isinstance(rv, Response):
                    rv = TemplateResponse(template, **(rv or {}))
                return rv

            f.__name__ = old_f.__name__
            f.__doc__ = old_f.__doc__
        exported_views[endpoint] = (f, string, extra)
        return f

    return wrapped
772443
def load_template(path_or_buffer):
    '''
    '''

    from itertools import groupby
    from operator import itemgetter

    path_or_buffer = _stringify_path(path_or_buffer)

    if is_file_like(path_or_buffer):
        templates = json.load(path_or_buffer)
    else:
        with open(path_or_buffer, 'r') as f:
            templates = json.load(f)

    options = []

    grouper = itemgetter('page', 'extraction_method')

    for key, grp in groupby(sorted(templates, key=grouper), grouper):
        tmp_options = [_convert_template_option(e) for e in grp]

        if len(tmp_options) == 1:
            options.append(tmp_options[0])
            continue

        option = tmp_options[0]
        areas = [e.get('area') for e in tmp_options]
        option['area'] = areas
        option['multiple_tables'] = True
        options.append(option)

    return options
1060933
def _create_archive(archive, filenames, verbosity=0, interactive=True,
                    program=None, format=None, compression=None):
    """"""
    if format is None:
        format, compression = get_archive_format(archive)
    check_archive_format(format, compression)
    program = find_archive_program(format, 'create', program=program)
    check_program_compression(archive, 'create', program, compression)
    get_archive_cmdlist = get_archive_cmdlist_func(program, 'create', format)
    origarchive = None
    if os.path.basename(program) == 'arc' and \
       ".arc" in archive and not archive.endswith(".arc"):
        # the arc program mangles the archive name if it contains ".arc"
        origarchive = archive
        archive = util.tmpfile(dir=os.path.dirname(archive), suffix=".arc")
    cmdlist = get_archive_cmdlist(archive, compression, program, verbosity, interactive, filenames)
    if cmdlist:
        # an empty command list means the get_archive_cmdlist() function
        # already handled the command (eg. when it's a builtin Python
        # function)
        run_archive_cmdlist(cmdlist, verbosity=verbosity)
    if origarchive:
        shutil.move(archive, origarchive)
691411
@Override
    public void exportTo(final OutputStream target) throws ArchiveExportException, IllegalArgumentException {
        // Precondition checks
        if (target == null) {
            throw new IllegalArgumentException("Target must be specified");
        }

        // Get Stream
        final InputStream in = this.exportAsInputStream();

        try {
            // Write out
            try {
                IOUtil.copy(in, target);
            } catch (final IOException e) {
                throw new ArchiveExportException("Error encountered in exporting archive to " + target, e);
            }
        } finally {
            // Close
            try {
                in.close();
            } catch (final IOException ioe) {
                // Just log
                log.warning("Could not close " + in + ": " + ioe);
            }
        }
    }
343133
def export(self, timestamp=None, info={}):
        
        tval = tuple(time.localtime()) if timestamp is None else timestamp
        tstamp = time.strftime(self.timestamp_format, tval)

        info = dict(info, timestamp=tstamp)
        export_name = self._format(self.export_name, info)
        files = [((self._format(base, info), ext), val)
                 for ((base, ext), val) in self._files.items()]
        root = os.path.abspath(self.root)
        # Make directory and populate if multiple files and not packed
        if len(self) > 1 and not self.pack:
            self._directory_archive(export_name, files, root)
        elif len(files) == 1:
            self._single_file_archive(export_name, files, root)
        elif self.archive_format == 'zip':
            self._zip_archive(export_name, files, root)
        elif self.archive_format == 'tar':
            self._tar_archive(export_name, files, root)
        if self.flush_archive:
            self._files = OrderedDict()
898858
def export(self, storage_client, overwrite=True):
        
        '''
            
        '''
        
        title = '%s.export' % self.__class__.__name__
        
    # validate storage client
        method_list = [ 'save', 'load', 'list', 'export', 'delete', 'remove', '_import', 'collection_name' ]
        for method in method_list:
            if not getattr(storage_client, method, None):
                from labpack.parsing.grammar import join_words
                raise ValueError('%s(storage_client=...) must be a client object with %s methods.' % (title, join_words(method_list)))
            
    # walk collection folder to find files
        import os
        count = 0
        skipped = 0
        for file_path in self._walk():
            path_segments = file_path.split(os.sep)
            record_key = os.path.join(*path_segments)
            record_key = record_key.replace('\\','/')
            file_path = '/%s' % file_path
            
    # retrieve data and metadata
            try:
                metadata, response = self.dropbox.files_download(file_path)
            except:
                raise DropboxConnectionError(title)
            record_data = response.content
            client_modified = metadata.client_modified
            
    # import record into storage client
            last_modified = 0.0
            if client_modified:
                from dateutil.tz import tzutc
                from labpack.records.time import labDT
                last_modified = labDT.fromPython(client_modified.replace(tzinfo=tzutc())).epoch()
            outcome = storage_client._import(record_key, record_data, overwrite=overwrite, last_modified=last_modified)
            if outcome:
                count += 1
            else:
                skipped += 1
            
    # report outcome
        plural = ''
        skip_insert = ''
        new_folder = storage_client.collection_name
        if count != 1:
            plural = 's'
        if skipped > 0:
            skip_plural = ''
            if skipped > 1:
                skip_plural = 's'
            skip_insert = ' %s record%s skipped to avoid overwrite.' % (str(skipped), skip_plural)
        exit_msg = '%s record%s exported to %s.%s' % (str(count), plural, new_folder, skip_insert)
        return exit_msg
842852
function createFiles (files, argv, templates, cb) {
  if (!templates) {
    const parent = path.resolve(module.parent.filename)
    templates = path.join(parent, '../templates')
  }

  const dir = argv.directory
  parallel(files.map(mapFn), cb)

  function mapFn (file) {
    const tempDir = path.resolve(templates)
    const inFile = path.join(tempDir, file.replace(/^\./, '_.'))
    const outFile = path.resolve(path.join(dir, file))

    return function (done) {
      fs.createReadStream(inFile)
        .pipe(through(transform))
        .pipe(fs.createWriteStream(outFile))
        .on('error', done)
        .on('finish', function () {
          process.stdout.write('write: ' + outFile + '\n')
          done()
        })

      function transform (chunk, enc, cb) {
        const str = chunk.toString()
        const mt = mustache.render(str, argv)
        cb(null, mt)
      }
    }
  }
}
14795
def export(self, storage_client, overwrite=True):
        
        '''
            
        '''
        
        title = '%s.export' % self.__class__.__name__
        
    # validate storage client
        method_list = [ 'save', 'load', 'list', 'export', 'delete', 'remove', '_import', 'collection_name' ]
        for method in method_list:
            if not getattr(storage_client, method, None):
                from labpack.parsing.grammar import join_words
                raise ValueError('%s(storage_client=...) must be a client object with %s methods.' % (title, join_words(method_list)))
            
    # walk collection folder to find files
        import os
        count = 0
        skipped = 0
        for file_path, file_id in self._walk():
            path_segments = file_path.split(os.sep)
            record_key = os.path.join(*path_segments)
            record_key = record_key.replace('\\','/')
            
    # retrieve data and metadata
            try:
                record_data = self.drive.get_media(fileId=file_id).execute()
            except:
                raise DriveConnectionError(title)
            try:
                file = self.drive.get(fileId=file_id, fields='modifiedTime').execute()
                client_modified = file.get('modifiedTime', '')
            except:
                raise DriveConnectionError(title)
            
    # import record into storage client
            last_modified = 0.0
            if client_modified:
                from labpack.records.time import labDT
                last_modified = labDT.fromISO(client_modified).epoch()
            outcome = storage_client._import(record_key, record_data, overwrite=overwrite, last_modified=last_modified)
            if outcome:
                count += 1
            else:
                skipped += 1
            
    # report outcome
        plural = ''
        skip_insert = ''
        new_folder = storage_client.collection_name
        if count != 1:
            plural = 's'
        if skipped > 0:
            skip_plural = ''
            if skipped > 1:
                skip_plural = 's'
            skip_insert = ' %s record%s skipped to avoid overwrite.' % (str(skipped), skip_plural)
        exit_msg = '%s record%s exported to %s.%s' % (str(count), plural, new_folder, skip_insert)
        return exit_msg
1288704
async def blob(self, elem=None, elem_type=None, params=None):
        
        elem_type = elem_type if elem_type else elem.__class__
        if hasattr(elem_type, "serialize_archive"):
            elem = elem_type() if elem is None else elem
            return await elem.serialize_archive(
                self, elem=elem, elem_type=elem_type, params=params
            )

        if self.writing:
            return await dump_blob(
                self.iobj, elem=elem, elem_type=elem_type, params=params
            )
        else:
            return await load_blob(
                self.iobj, elem_type=elem_type, params=params, elem=elem
            )
631691
def export(self, filename, fmt="DER"):
        
        f = open(filename, "wb")
        f.write(self.output(fmt))
        f.close()