generate XFDF content
492910
def to_xfdf
      builder = Nokogiri::XML::Builder.new(encoding: 'UTF-8') do |xml|
        xml.xfdf('xmlns' => 'http://ns.adobe.com/xfdf/', 'xml:space' => 'preserve') {
          xml.f(href: options[:file]) if options[:file]
          xml.ids(original: options[:id], modified: options[:id]) if options[:id]
          xml.fields {
            @fields.each do |field, value|
              xml.field(name: field) {
                if value.is_a? Array
                  value.each { |item| xml.value(item.to_s) }
                else
                  xml.value(value.to_s)
                end
              }
            end
          }
        }
      end
      builder.to_xml(save_with: Nokogiri::XML::Node::SaveOptions::AS_XML)
    end
672861
public void exportAsFdf(FdfWriter writer) {
        for (Iterator it = fields.entrySet().iterator(); it.hasNext();) {
            Map.Entry entry = (Map.Entry)it.next();
            Item item = (Item)entry.getValue();
            String name = (String)entry.getKey();
            PdfObject v = item.getMerged(0).get(PdfName.V);
            if (v == null)
                continue;
            String value = getField(name);
            if (lastWasString)
                writer.setFieldAsString(name, value);
            else
                writer.setFieldAsName(name, value);
        }
    }
1072227
void generateAntIvyXml(Definition def, String outputDir)
   {
      try
      {
         FileWriter antfw = Utils.createFile("build.xml", outputDir);
         BuildIvyXmlGen bxGen = new BuildIvyXmlGen();
         bxGen.generate(def, antfw);
         antfw.close();

         FileWriter ivyfw = Utils.createFile("ivy.xml", outputDir);
         IvyXmlGen ixGen = new IvyXmlGen();
         ixGen.generate(def, ivyfw);
         ivyfw.close();

         FileWriter ivySettingsfw = Utils.createFile("ivy.settings.xml", outputDir);
         IvySettingsXmlGen isxGen = new IvySettingsXmlGen();
         isxGen.generate(def, ivySettingsfw);
         ivySettingsfw.close();
      }
      catch (IOException ioe)
      {
         ioe.printStackTrace();
      }
   }
792341
def generate(env):
    """"""
    global GhostscriptAction
    # The following try-except block enables us to use the Tool
    # in standalone mode (without the accompanying pdf.py),
    # whenever we need an explicit call of gs via the Gs()
    # Builder ...
    try:
        if GhostscriptAction is None:
            GhostscriptAction = SCons.Action.Action('$GSCOM', '$GSCOMSTR')
    
        from SCons.Tool import pdf
        pdf.generate(env)
    
        bld = env['BUILDERS']['PDF']
        bld.add_action('.ps', GhostscriptAction)
    except ImportError as e:
        pass

    gsbuilder = SCons.Builder.Builder(action = SCons.Action.Action('$GSCOM', '$GSCOMSTR'))
    env['BUILDERS']['Gs'] = gsbuilder
    
    env['GS']      = gs
    env['GSFLAGS'] = SCons.Util.CLVar('-dNOPAUSE -dBATCH -sDEVICE=pdfwrite')
    env['GSCOM']   = '$GS $GSFLAGS -sOutputFile=$TARGET $SOURCES'
190850
def xhtml(self, outfn=None, ext='.xhtml', css=None, **params):
        """"""
        from markdown import markdown
        from copy import deepcopy
        from bl.file import File
        from .xslt import XSLT
        from .rng import RNG
        from . import XML, PATH, etree
        rncfn = os.path.splitext(self.fn)[0] + '.rnc'
        rngfn = os.path.splitext(self.fn)[0] + '.rng'
        htmlfn = os.path.splitext(self.fn)[0] + '.html'
        if self.fn==rncfn or os.path.exists(rncfn):
            rngfn = Schema(rncfn).trang(ext='.rng')
        assert os.path.exists(rngfn)

        # convert all <r:define> elements into a <a:definition> blocks containing a compact syntax alternative
        rng = RNG(fn=rngfn)
        for define in rng.xpath(rng.root, "//r:define"):
            log.debug("%s %r" % (rng.tag_name(define), define.attrib))
            tempdefine = deepcopy(define)
            tempgrammar = deepcopy(rng.root); tempgrammar.text = '\n'
            for ch in tempgrammar.getchildren(): rng.remove(ch)
            tempgrammar.insert(0, tempdefine)
            for adoc in rng.xpath(tempdefine, ".//a:documentation | .//a:definition"):
                rng.remove(adoc)
            with tempfile.TemporaryDirectory() as tempdir:
                x = XML(fn=os.path.join(tempdir, 'define.rng'), root=tempgrammar)
                x.write()
                newfn = Schema(x.fn).trang(ext='.rnc')
                txt = open(newfn, 'rb').read().decode('utf-8')
                if '\n\n' in txt:
                    txt = txt[txt.index('\n\n')+1:].strip()
            adef = etree.Element("{%(a)s}definition" % RNG.NS)
            adef.text = txt
            adef.tail = '\n\t\t'
            log.debug(adef.text)
            annotations = rng.xpath(define, "a:*")
            if len(annotations) > 0:
                index = define.index(annotations[-1])+1
            else:
                index = 0
            define.insert(index, adef)
        rng.write()

        xslt = XSLT(fn=os.path.join(PATH, 'xslts', 'rng2md.xslt'))
        md = xslt.saxon9(rng.root, **params).strip()
        html_body = markdown(md, 
            output_format="xhtml5", 
            extensions=[                            # see https://python-markdown.github.io/extensions/
                'markdown.extensions.extra',    
                'markdown.extensions.admonition', 
                'markdown.extensions.headerid', 
                'markdown.extensions.sane_lists', 
                'markdown.extensions.toc']).strip()
        html_text = """<html><head><meta charset="UTF-8"/><style type="text/css">
            body {font-family:sans-serif;line-height:1.3}
            h1,h2,h3 {margin:1em 0 .25em 0}
            h1 {font-size:2rem;font-weight:normal;}
            h2 {font-size:1.2rem;font-weight:bold;}
            h3 {font-size:1.15rem;font-weight:normal;font-style:italic;}
            p {margin:0 0 .5rem 0;}
            p.subtitle {font-size:1.2rem;font-family:sans-serif;margin-bottom:1em}
            p.code {font-family:monospace;font-size:.6rem;color:#666;line-height:1.1}
            pre {font-family:monospace;font-size:.6rem;color:#666;line-height:1.1;margin-left:1.5rem;}
            hr {border:0;border-top:1px solid #999;margin:1rem 0;}
            </style></head><body>\n""" + html_body + """\n</body></html>"""
        html = XML(fn=htmlfn, root=html_text)
        return html
507337
def generate_file(fname, ns_func, dest_dir="."):
    """"""
    with open(pjoin(root, 'buildutils', 'templates', '%s' % fname), 'r') as f:
        tpl = f.read()
    out = tpl.format(**ns_func())
    dest = pjoin(dest_dir, fname)
    info("generating %s from template" % dest)
    with open(dest, 'w') as f:
        f.write(out)
731347
public function generateFdfFile($name)
    {
        $this->constrainSingleFile();
        $this->getCommand()->setOperation('generate_fdf');
        $this->_output = $name;
        return $this->execute();
    }
235115
def GenerarPDF(self, archivo="", dest="F"):
        ""
        try:
            self.template.render(archivo, dest=dest)
            return True
        except Exception, e:
            self.Excepcion = str(e)
            return False
283745
protected function _generateFiles() {
        foreach ($this->selectedArtifacts as $artifact) {
            $settings = $artifact->getGeneratorSettings(static::getKey());

            foreach ($this->getFileOrDirectorySettings($settings, "files") as $file)
                $this->_processFileSpecification(
                    $artifact, fphp\Specification\FileSpecification::fromArrayAndSettings($file, $settings));

            foreach ($this->getFileOrDirectorySettings($settings, "directories") as $directory) {
                $directorySpecification = fphp\Specification\DirectorySpecification::fromArrayAndSettings($directory, $settings);
                
                foreach ($directorySpecification->getFileSpecifications() as $fileSpecification)
                    $this->_processFileSpecification($artifact, $fileSpecification);
            }
        }
    }
608455
function xfer (res, files, cb) {
    var file = files.shift();

    if (!file) {
        return cb(null);
    }

    fs.createReadStream(file
    ).on("data", function (chunk) {
        res.write(chunk);
    }).on("error", cb
    ).on("close", function xferClose () {
        xfer(res, files, cb);
    });
}
811481
public function createStoredFieldsFiles()
    {
        $this->_fdxFile = $this->_directory->createFile($this->_name . '.fdx');
        $this->_fdtFile = $this->_directory->createFile($this->_name . '.fdt');

        $this->_files[] = $this->_name . '.fdx';
        $this->_files[] = $this->_name . '.fdt';
    }
1366575
function generatePDF(req, res, next) {
  req.appformsResultPayload = req.appformsResultPayload || {};

  //If there is already a submission result, render this. This is useful for cases where the submission is fetched from another database and rendered elsewhere.
  var existingSubmission = req.appformsResultPayload.data;

  var params = {
    _id: req.params.id,
    pdfExportDir: req.pdfExportDir,
    downloadUrl: '' + req.protocol + '://' + req.hostname,
    existingSubmission: existingSubmission,
    environment: req.environment,
    mbaasConf: req.mbaasConf,
    domain: req.user.domain,
    filesAreRemote: req.filesAreRemote,
    fileUriPath: req.fileUriPath,
    location: req.coreLocation,
    pdfTemplateLoc: req.pdfTemplateLoc,
    maxConcurrentPhantomPerWorker: req.maxConcurrentPhantomPerWorker
  };

  logger.debug("Middleware generatePDF ", {params: params});

  forms.generateSubmissionPdf(_.extend(params, req.connectionOptions), function(err, submissionPdfLocation) {
    if (err) {
      logger.error("Middleware generatePDF", {error: err});
      return next(err);
    }

    logger.debug("Middleware generatePDF ", {submissionPdfLocation: submissionPdfLocation});

    //Streaming the file as an attachment
    res.download(submissionPdfLocation, '' + req.params.id + ".pdf", function(fileDownloadError) {

      //Download Complete, remove the cached file
      fs.unlink(submissionPdfLocation, function() {
        if (fileDownloadError) {
          logger.error("Middleware generatePDF ", {error: fileDownloadError});
          //If the headers have not been sent to the client, can use the error handler
          if (!res.headersSent) {
            return next(fileDownloadError);
          }
        }
      });
    });
  });
}
639974
void generateMbeanXml(Definition def, String outputDir)
   {
      String mbeanName = def.getDefaultValue().toLowerCase(Locale.US);
      if (def.getRaPackage() != null && !def.getRaPackage().equals(""))
      {
         if (def.getRaPackage().indexOf('.') >= 0)
         {
            mbeanName = def.getRaPackage().substring(def.getRaPackage().lastIndexOf('.') + 1);
         }
         else
            mbeanName = def.getRaPackage();
      }

      try
      {
         outputDir = outputDir + File.separatorChar + "src" + File.separatorChar +
               "main" + File.separatorChar + "resources" + File.separatorChar + "jca";
         FileWriter mbfw = Utils.createFile(mbeanName + ".xml", outputDir);
         MbeanXmlGen mbGen = new MbeanXmlGen();
         mbGen.generate(def, mbfw);
         mbfw.close();
      }
      catch (IOException ioe)
      {
         ioe.printStackTrace();
      }
   }
27225
protected function buildXml()
  {
    if (empty($_POST['CKFinderCommand']) || $_POST['CKFinderCommand'] != 'true') {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }

    if (!extension_loaded('zip')) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_COMMAND);
    }

    $this->checkConnector();
    $this->checkRequest();

    if ( !$this->_currentFolder->checkAcl(CKFINDER_CONNECTOR_ACL_FILE_UPLOAD)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNAUTHORIZED);
    }

    if (!isset($_POST["fileName"])) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_NAME);
    }

    $fileName = CKFinder_Connector_Utils_FileSystem::convertToFilesystemEncoding($_POST["fileName"]);
    $resourceTypeInfo = $this->_currentFolder->getResourceTypeConfig();

    if (!$resourceTypeInfo->checkExtension($fileName)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION);
    }

    if (!CKFinder_Connector_Utils_FileSystem::checkFileName($fileName) || $resourceTypeInfo->checkIsHiddenFile($fileName)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_REQUEST);
    }

    $filePath = CKFinder_Connector_Utils_FileSystem::combinePaths($this->_currentFolder->getServerPath(), $fileName);

    if (!file_exists($filePath) || !is_file($filePath)) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_FILE_NOT_FOUND);
    }

    if (!is_writable(dirname($filePath))) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_ACCESS_DENIED);
    }

    if ( strtolower(pathinfo($fileName, PATHINFO_EXTENSION)) !== 'zip'){
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_INVALID_EXTENSION);
    }

    $zip = new ZipArchive();
    $result = $zip->open($filePath);
    if ($result !== TRUE) {
      $this->_errorHandler->throwError(CKFINDER_CONNECTOR_ERROR_UNKNOWN);
    }
    $this->zip = $zip;
    $this->filePath = $filePath;
    $this->_config =& CKFinder_Connector_Core_Factory::getInstance("Core_Config");

    // list of unzipped nodes
    $this->unzippedNodes = new CKFinder_Connector_Utils_XmlNode("UnzippedFiles");

    // list of files which could not be unzipped
    $this->skippedFilesNode = new CKFinder_Connector_Utils_XmlNode("Errors");
    $this->errorCode = CKFINDER_CONNECTOR_ERROR_NONE;
  }
708247
def fromXml(cls, xdata, filepath=''):
        
        module = None
        pkg_data = xdata.find('package')
        if pkg_data is not None:
            path = pkg_data.find('path').text
            name = pkg_data.find('name').text

            if filepath:
                path = os.path.join(filepath, path)

            path = os.path.abspath(path)
            sys.path.insert(0, path)
            sys.modules.pop(name, None)

            try:
                __import__(name)
                module = sys.modules[name]
            except (ImportError, KeyError):
                return None
        else:
            return None

        # generate the builder
        builder = cls(module)
        builder.loadXml(xdata, filepath=filepath)
        return builder
1287047
def write_libxc_docs_json(xcfuncs, jpath):
    """"""
    from copy import deepcopy
    xcfuncs = deepcopy(xcfuncs)

    # Remove XC_FAMILY from Family and XC_ from Kind to make strings more human-readable.
    for d in xcfuncs.values():
        d["Family"] = d["Family"].replace("XC_FAMILY_", "", 1)
        d["Kind"] = d["Kind"].replace("XC_", "", 1)

    # Build lightweight version with a subset of keys.
    for num, d in xcfuncs.items():
        xcfuncs[num] = {k: d[k] for k in ("Family", "Kind", "References")}
        # Descriptions are optional
        for opt in ("Description 1", "Description 2"):
            desc = d.get(opt)
            if desc is not None: xcfuncs[num][opt] = desc

    with open(jpath, "wt") as fh:
        json.dump(xcfuncs, fh)

    return xcfuncs
1009648
def _build_xrefs(self):
        '''
        
        '''
        xrefs = set()

        plugins = self.plugins()
        for plugin in plugins:
            for xref in plugin['xrefs'].split(', '):
                xrf = xref.replace('-', '_').split(':')[0]
                if xrf is not '':
                    xrefs.add(xrf)
        self._xrefs = list(xrefs)