Convert Neutral file format to Dolfin XML.
771822
def convertNeutral2Xml(infile, outfile=None):
    """"""

    f = open(infile, "r")
    lines = f.readlines()
    f.close()

    ncoords = int(lines[0])
    fdolf_coords = []
    for i in range(1, ncoords + 1):
        x, y, z = lines[i].split()
        fdolf_coords.append([float(x), float(y), float(z)])

    ntets = int(lines[ncoords + 1])
    idolf_tets = []
    for i in range(ncoords + 2, ncoords + ntets + 2):
        text = lines[i].split()
        v0, v1, v2, v3 = text[1], text[2], text[3], text[4]
        idolf_tets.append([int(v0) - 1, int(v1) - 1, int(v2) - 1, int(v3) - 1])

    if outfile:  # write dolfin xml
        outF = open(outfile, "w")
        outF.write('<?xml version="1.0" encoding="UTF-8"?>\n')
        outF.write('<dolfin xmlns:dolfin="http://www.fenicsproject.org">\n')
        outF.write('  <mesh celltype="tetrahedron" dim="3">\n')

        outF.write('    <vertices size="' + str(ncoords) + '">\n')
        for i in range(ncoords):
            x, y, z = fdolf_coords[i]
            outF.write('      <vertex index="'+str(i)
                       + '" x="'+str(x)+'" y="'+str(y)+'" z="'+str(z)+'"/>\n')
        outF.write('    </vertices>\n')

        outF.write('    <cells size="' + str(ntets) + '">\n')
        for i in range(ntets):
            v0, v1, v2, v3 = idolf_tets[i]
            outF.write('      <tetrahedron index="'+str(i)
                       + '" v0="'+str(v0)+'" v1="'+str(v1)+'" v2="'+str(v2)+'" v3="'+str(v3)+'"/>\n')
        outF.write('    </cells>\n')

        outF.write("  </mesh>\n")
        outF.write("</dolfin>\n")
        outF.close()
    return fdolf_coords, idolf_tets
158396
private Document toXML(Collection<ArchiveEntry> files) throws Exception
    {
        Document doc = new DOMDocument();

        Element packageElement = new DOMElement("package");
        doc.setRootElement(packageElement);

        Element infoElement = new DOMElement("infos");
        packageElement.add(infoElement);
        addInfoElements(infoElement);

        Element filesElement = new DOMElement(FILES_TAG);
        packageElement.add(filesElement);
        addFileElements(files, filesElement);

        return doc;
    }
1345160
def NewFile(self, filename, encoding, options):
        
        ret = libxml2mod.xmlReaderNewFile(self._o, filename, encoding, options)
        return ret
798855
function asNiceXml($filename = '', $level = 0) {
		if (is_numeric($level)) {
			$pad = str_pad('', $level * 1, "\t", STR_PAD_LEFT);
			$nl = "\n";
		} else {
			$pad = '';
			$nl = '';
		}
		$out = $pad . '<' . $this->getName();
		$attributes = $this->attributes();
		if ($attributes) {
			foreach ($attributes as $key => $value) {
				$out .= ' ' . $key . '="' . str_replace('"', '\"', (string)$value) . '"';
			}
		}
		$attributes = $this->attributes('xsi', true);
		if ($attributes) {
			foreach ($attributes as $key => $value) {
				$out .= ' xsi:' . $key . '="' . str_replace('"', '\"', (string)$value) . '"';
			}
		}
		if ($this->hasChildren()) {
			$out .= '>';
			$value = trim((string)$this);
			if (strlen($value)) {
				$out .= $this->xmlentities($value);
			}
			$out .= $nl;
			foreach ($this->children() as $child) {
				/** @var X $child */
				$out .= $child->asNiceXml('', is_numeric($level) ? $level + 1 : true);
			}
			$out .= $pad . '</' . $this->getName() . '>' . $nl;
		}
		else {
			$value = (string)$this;
			if (strlen($value)) {
				$out .= '>' . $this->xmlentities($value) . '</' . $this->getName() . '>' . $nl;
			}
			else {
				$out .= '/>' . $nl;
			}
		}
		if ((0 === $level || false === $level) && !empty($filename)) {
			file_put_contents($filename, $out);
		}
		return $out;
	}
991789
def to_xml(self):
        """"""
        if self.alias_hosted_zone_id != None and self.alias_dns_name != None:
            # Use alias
            body = self.AliasBody % (self.alias_hosted_zone_id, self.alias_dns_name)
        else:
            # Use resource record(s)
            records = ""
            for r in self.resource_records:
                records += self.ResourceRecordBody % r
            body = self.ResourceRecordsBody % {
                "ttl": self.ttl,
                "records": records,
            }
        weight = ""
        if self.identifier != None and self.weight != None:
            weight = self.WRRBody % {"identifier": self.identifier, "weight":
                    self.weight}
        params = {
            "name": self.name,
            "type": self.type,
            "weight": weight,
            "body": body,
        }
        return self.XMLBody % params
39593
def to_xml(self):
        """"""
        changesXML = ""
        for change in self.changes:
            changeParams = {"action": change[0], "record": change[1].to_xml()}
            changesXML += self.ChangeXML % changeParams
        params = {"comment": self.comment, "changes": changesXML}
        return self.ChangeResourceRecordSetsBody % params
476709
def xml(self, indent = ""):
        """"""
        xml = indent + "<OutputTemplate id=\"" + self.id + "\" format=\"" + self.formatclass.__name__ + "\"" + " label=\"" + self.label + "\""
        if self.formatclass.mimetype:
            xml +=" mimetype=\""+self.formatclass.mimetype+"\""
        if self.formatclass.schema:
            xml +=" schema=\""+clam.common.util.xmlescape(self.formatclass.schema)+"\""
        if self.filename:
            xml +=" filename=\""+clam.common.util.xmlescape(self.filename)+"\""
        if self.extension:
            xml +=" extension=\""+clam.common.util.xmlescape(self.extension)+"\""
        if self.parent:
            xml +=" parent=\""+clam.common.util.xmlescape(self.parent)+"\""
        if self.unique:
            xml +=" unique=\"yes\""
        else:
            xml +=" unique=\"no\""
        xml += ">\n"
        for metafield in self.metafields:
            xml += metafield.xml(indent + "    ") + "\n"

        xml += indent + "</OutputTemplate>"
        return xml
438624
def npz_convert(self, infile, item):
        """"""
        data = np.load(infile)
        labels = self._labels(data)
        features = data['features']
        self._write(item, labels, features)
1122449
def as_xml(self):
        
        # Build tree
        spacing = ("\n" if (self.pretty_xml) else "")
        root = Element('error', {'xmlns': I3F_NS})
        root.text = spacing
        e_parameter = Element('parameter', {})
        e_parameter.text = self.parameter
        e_parameter.tail = spacing
        root.append(e_parameter)
        if (self.text):
            e_text = Element('text', {})
            e_text.text = self.text
            e_text.tail = spacing
            root.append(e_text)
        # Write out as XML document to return
        tree = ElementTree(root)
        xml_buf = io.BytesIO()
        if (sys.version_info < (2, 7)):
            tree.write(xml_buf, encoding='UTF-8')
        else:
            tree.write(xml_buf, encoding='UTF-8',
                       xml_declaration=True, method='xml')
        return(xml_buf.getvalue().decode('utf-8'))
939587
def saveFormatFileTo(self, cur, encoding, format):
        
        if cur is None: cur__o = None
        else: cur__o = cur._o
        ret = libxml2mod.xmlSaveFormatFileTo(self._o, cur__o, encoding, format)
        return ret
86518
def _gen_xml(name,
             cpu,
             mem,
             diskp,
             nicp,
             hypervisor,
             os_type,
             arch,
             graphics=None,
             loader=None,
             **kwargs):
    '''
    
    '''
    mem = int(mem) * 1024  # MB
    context = {
        'hypervisor': hypervisor,
        'name': name,
        'cpu': six.text_type(cpu),
        'mem': six.text_type(mem),
    }
    if hypervisor in ['qemu', 'kvm']:
        context['controller_model'] = False
    elif hypervisor == 'vmware':
        # TODO: make bus and model parameterized, this works for 64-bit Linux
        context['controller_model'] = 'lsilogic'

    # By default, set the graphics to listen to all addresses
    if graphics:
        if 'listen' not in graphics:
            graphics['listen'] = {'type': 'address', 'address': '0.0.0.0'}
        elif 'address' not in graphics['listen'] and graphics['listen']['type'] == 'address':
            graphics['listen']['address'] = '0.0.0.0'

        # Graphics of type 'none' means no graphics device at all
        if graphics.get('type', 'none') == 'none':
            graphics = None
    context['graphics'] = graphics

    if loader and 'path' not in loader:
        log.info('`path` is a required property of `loader`, and cannot be found. Skipping loader configuration')
        loader = None
    elif loader:
        loader_attributes = []
        for key, val in loader.items():
            if key == 'path':
                continue
            loader_attributes.append("{key}='{val}'".format(key=key, val=val))
        loader['_attributes'] = ' '.join(loader_attributes)

    if 'boot_dev' in kwargs:
        context['boot_dev'] = []
        for dev in kwargs['boot_dev'].split():
            context['boot_dev'].append(dev)
    else:
        context['boot_dev'] = ['hd']

    context['loader'] = loader

    if os_type == 'xen':
        # Compute the Xen PV boot method
        if __grains__['os_family'] == 'Suse':
            context['kernel'] = '/usr/lib/grub2/x86_64-xen/grub.xen'
            context['boot_dev'] = []

    if 'serial_type' in kwargs:
        context['serial_type'] = kwargs['serial_type']
    if 'serial_type' in context and context['serial_type'] == 'tcp':
        if 'telnet_port' in kwargs:
            context['telnet_port'] = kwargs['telnet_port']
        else:
            context['telnet_port'] = 23023  # FIXME: use random unused port
    if 'serial_type' in context:
        if 'console' in kwargs:
            context['console'] = kwargs['console']
        else:
            context['console'] = True

    context['disks'] = []
    disk_bus_map = {'virtio': 'vd', 'xen': 'xvd', 'fdc': 'fd', 'ide': 'hd'}
    for i, disk in enumerate(diskp):
        prefix = disk_bus_map.get(disk['model'], 'sd')
        disk_context = {
            'device': disk.get('device', 'disk'),
            'target_dev': '{0}{1}'.format(prefix, string.ascii_lowercase[i]),
            'disk_bus': disk['model'],
            'type': disk['format'],
            'index': six.text_type(i),
        }
        if 'source_file' and disk['source_file']:
            disk_context['source_file'] = disk['source_file']

        if hypervisor in ['qemu', 'kvm', 'bhyve', 'xen']:
            disk_context['address'] = False
            disk_context['driver'] = True
        elif hypervisor in ['esxi', 'vmware']:
            disk_context['address'] = True
            disk_context['driver'] = False
        context['disks'].append(disk_context)
    context['nics'] = nicp

    context['os_type'] = os_type
    context['arch'] = arch

    fn_ = 'libvirt_domain.jinja'
    try:
        template = JINJA.get_template(fn_)
    except jinja2.exceptions.TemplateNotFound:
        log.error('Could not load template %s', fn_)
        return ''

    return template.render(**context)
1107144
def from_fs_path(path):
    """"""
    scheme = 'file'
    params, query, fragment = '', '', ''
    path, netloc = _normalize_win_path(path)
    return urlunparse((scheme, netloc, path, params, query, fragment))
1347838
def to_xml(opts={})
      exclude = opts[:exclude] || []
      exclude << :errors
      
      tag     = opts[:tag] || RSpreedly.underscore(self.class.to_s)
      inner   = opts[:inner]
      outer   = opts[:outer]      
      no_tag  = opts[:no_tag]
      
      xml = ""
      xml << "<#{outer}>" if outer
      xml << "<#{tag}>" unless no_tag
      xml << "<#{inner}>" if inner
      self.instance_variables.each do |var|
        name = var.to_s.gsub('@', '')
        next if exclude.include?(name.to_sym)
        value = self.instance_variable_get(var)
        if value.respond_to?(:to_xml)
          value = value.to_xml(:no_tag => (RSpreedly.underscore(value.class.to_s) == name)) 
        end
        xml << "<#{name}>#{value}</#{name}>"
      end
      xml << "</#{inner}>" if inner      
      xml << "</#{tag}>" unless no_tag
      xml << "</#{outer}>" if outer      
      xml
    end
867325
def tree_to_xml(self):
        """"""

        # Need to remove filter or hidden items will not be saved.
        self.filter_remove(remember=True)

        tree = self.treeview
        root = ET.Element('interface')
        items = tree.get_children()
        for item in items:
            node = self.tree_node_to_xml('', item)
            root.append(node)

        # restore filter
        self.filter_restore()

        return ET.ElementTree(root)
1307519
void generateAntXml(Definition def, String outputDir)
   {
      try
      {
         FileWriter antfw = Utils.createFile("build.xml", outputDir);
         BuildXmlGen bxGen = new BuildXmlGen();
         bxGen.generate(def, antfw);
         antfw.close();
      }
      catch (IOException ioe)
      {
         ioe.printStackTrace();
      }
   }
1223743
def pretty_xml(data):
    
    parsed_string = minidom.parseString(data.decode('utf-8'))
    return parsed_string.toprettyxml(indent='\t', encoding='utf-8')
344791
def to_file(f)
      result = client.query(last_statement, :stream => true, :cache_rows => false, :as => :array)
      escaped_fields = result.fields.map { |k| k.to_xs }

      f.write %{<?xml version="1.0" encoding="utf-8" ?>}
      f.write %{<resultset statement="#{config.execute.to_xs}" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">}
      result.each do |ary|
        next if ary.nil?
        f.write %{<row>}
        ary.each_with_index do |v, i|
          f.write %{<field name="#{escaped_fields[i]}"#{' xsi:nil="true"' if v.nil?}>#{v.to_s.to_xs}</field>}
        end
        f.write %{</row>}
      end
      f.write %{</resultset>}
      nil
    end