Beispiel #1
0
def write(ink, filename):
    """Save strokes to a inkml file

    Reference:
        https://www.w3.org/TR/InkML/
    Args:
        ink: list of strokes where each stroke is a list of (x, y) tuples
             or an array[len, 2]
        filename (str): filename to save (should end on ".inkml")

    Returns:
        None
    """
    root = ET.Element("ink")
    root.set('xmlns', 'http://www.w3.org/2003/InkML')
    root.append(ET.Comment("created by neo pen (github.com/antemons/neo-pen)"))

    for stroke in ink:
        trace = ET.SubElement(root, "trace")
        for dot in stroke:
            if trace.text is None:
                trace.text = ("{} {}".format(*dot))
            else:
                trace.text += (", {} {}".format(*dot))

    tree = ET.ElementTree(root)
    with open(filename, "w") as f:
        f.write(minidom.parseString(ET.tostring(root)).toprettyxml())
Beispiel #2
0
def start_xml(script_start_time):
    # Concatenate the script arguments to a string
    scriptargs = ""
    for argnum in range(0, len(sys.argv)):
        scriptargs = scriptargs + " " + str(sys.argv[argnum])

    # Set some vars used to mimic the official nmap file format
    nmaprun_attribs = {
        'scanner': sys.argv[0],
        'args': scriptargs,
        'start': str(script_start_time),
        'version': '1.0',
        'xmloutputversion': '1.04'
    }

    nmaprun = ET.Element('nmaprun', nmaprun_attribs)

    # Append a comment prior to starting root xml
    comment = ET.Comment('Generated by Glens nmap XML merger (gnxmerge)')
    nmaprun.append(comment)

    nmaprun_verbose_attribs = {'level': '0'}
    nmaprun_debug_attribs = {'level': '0'}
    nmaprun_verbose = ET.SubElement(nmaprun, 'verbose',
                                    nmaprun_verbose_attribs)
    nmaprun_debug = ET.SubElement(nmaprun, 'debug', nmaprun_debug_attribs)

    return nmaprun
    def insertNewSeriesInXML(self, origImageList, newImageList,
                     studyID, newSeriesID, seriesID, suffix):
        try:
            currentStudy = self.getStudy(studyID)
            newAttributes = {'id':newSeriesID, 
                                'parentID':seriesID,
                                'typeID':suffix}
                   
            #Add new series to study to hold new images
            newSeries = ET.SubElement(currentStudy, 'series', newAttributes)           
            comment = ET.Comment('This series holds a whole series of new images')
            newSeries.append(comment)
            #Get image date & time from original image
            for index, imageNewName in enumerate(newImageList): #origImageList
                #imageLabel = self.getImageLabel(studyID, seriesID, imageName)
                imageTime = self.getImageTime(studyID, seriesID)# , imageName)
                imageDate = self.getImageDate(studyID, seriesID)#, imageName)
                newImage = ET.SubElement(newSeries,'image')
                #Add child nodes of the image element
                labelNewImage = ET.SubElement(newImage, 'label')
                labelNewImage.text = str(index + 1).zfill(6)
                nameNewImage = ET.SubElement(newImage, 'name')
                nameNewImage.text = imageNewName
                timeNewImage = ET.SubElement(newImage, 'time')
                timeNewImage.text = imageTime
                dateNewImage = ET.SubElement(newImage, 'date')
                dateNewImage.text = imageDate

            self.tree.write(self.fullFilePath)
        except Exception as e:
            print('Error in WeaselXMLReader.insertNewSeriesInXML: ' + str(e)) 
            logger.error('Error in WeaselXMLReader.insertNewSeriesInXML: ' + str(e))
Beispiel #4
0
    def _add_metadata(self, root):
        md = self.metadata

        # Add Inkscape style rdf meta data
        root.set("xmlns:dc", "http://purl.org/dc/elements/1.1/")
        root.set("xmlns:cc", "http://creativecommons.org/ns#")
        root.set("xmlns:rdf","http://www.w3.org/1999/02/22-rdf-syntax-ns#")

        title = "{group} - {name}".format(**md)
        date = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")

        m = self._addTag(root, "metadata", '\n', True)
        r = ET.SubElement(m, 'rdf:RDF')
        w = ET.SubElement(r, 'cc:Work')
        w.text = '\n'

        self._addTag(w, 'dc:title', title)
        self._addTag(w, 'dc:date', date)

        if "url" in md and md["url"]:
            self._addTag(w, 'dc:source', md["url"])
        else:
            self._addTag(w, 'dc:source', md["cli"])

        desc = md["short_description"] or ""
        if "description" in md and md["description"]:
            desc += "\n\n" + md["description"]
        desc += "\n\nCreated with Boxes.py (https://festi.info/boxes.py)\n"
        desc += "Command line: %s\n" % md["cli"]
        if md["url"]:
            desc += "Url: %s\n" % md["url"]
            desc += "SettingsUrl: %s\n" % md["url"].replace("&render=1", "")
        self._addTag(w, 'dc:description', desc)

        # title
        self._addTag(root, "title", md["name"], True)

        # Add XML comment
        txt = """
{name} - {short_description}
""".format(**md)
        if md["description"]:
            txt += """

{description}

""".format(**md)
        txt += """
Created with Boxes.py (https://festi.info/boxes.py)
Creation date: {date}
""".format(date=date, **md)

        txt += "Command line (remove spaces between dashes): %s\n" % md["cli"].replace("--", "- -")

        if md["url"]:
            txt += "Url: %s\n" % md["url"]
            txt += "SettingsUrl: %s\n" % md["url"].replace("&render=1", "")
        m = ET.Comment(txt)
        m.tail = '\n'
        root.insert(0, m)
Beispiel #5
0
def comment(text):
    """Comment factory. Return an elementree comment to append somewhere.
	
	:type text: str
	:rtype: elementtree comment
	"""
    return etree.Comment(text)
Beispiel #6
0
def exportShortcut(widget, scheme, schemeName, filename):
    """Saves shortcuts to a file."""
    lst = {}
    for item in widget.items():
        col = item.collection.name
        if not col in lst:
            lst[col] = {}
        if not item.isDefault(scheme):
            lst[col][item.name] = item.shortcuts(scheme)

    root = ET.Element('frescobaldi-shortcut')
    root.set('name', schemeName)
    comment = ET.Comment(_comment.format(appinfo=appinfo))
    root.append(comment)
    d = ET.ElementTree(root)

    for col, shortcuts in lst.items():
        if not shortcuts:
            continue
        colElt = ET.Element('collection')
        colElt.set('name', col)
        root.append(colElt)
        for name, shortList in shortcuts.items():
            nameElt = ET.Element('name')
            nameElt.set('name', name)
            colElt.append(nameElt)
            for seq in shortList:
                shortcutElt = ET.Element('shortcut')
                shortcutElt.text = seq.toString()
                nameElt.append(shortcutElt)

    indentXml(root)
    d.write(filename, 'UTF-8')
Beispiel #7
0
    def generate(self):

        # generate root element
        root_elem = ET.Element(self.root_metadata['name'])
        for attr_name, attr_value in self.root_metadata['attrs'].items():
            root_elem.set(attr_name, attr_value)

        comment = ET.Comment('SiteMap generated for DeliveryHero challenge')
        root_elem.append(comment)

        # generate children
        for path, obj in self.website_content.items():
            # url (element)
            url = self.build_url(self.prefix, self.domain, path)
            url_elem = ET.SubElement(root_elem, self.url_metadata['name'])

            # loc (url)
            url_child_elem = ET.SubElement(url_elem, 'loc')
            url_child_elem.text = url

            # lastmod (datetime)
            url_child_elem = ET.SubElement(url_elem, 'lastmod')
            url_child_elem.text = obj.get('lastmod')

        # output it as well
        output = self.prettify(root_elem)
        print '\n' + output + '\n'

        filename = 'sitemap.xml'
        print "# Generating %s file..." % filename
        output_file = open(filename, 'w')
        output_file.write('<?xml version="1.0" encoding="UTF-8"?>')
        output_file.write(output)
        output_file.close()
        print "# Done!"
Beispiel #8
0
    def generate_nzb(self):
        filename = '%s.nzb' % (SafeFilename(self._current_dir))

        self.logger.info('Begin generation of %s', filename)

        gentime = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime())
        root = ET.Element('nzb')
        root.append(
            ET.Comment('Generated by newsmangler v%s at %s' %
                       (NM_VERSION, gentime)))

        for subject, msgids in self._msgids.items():
            posttime = msgids.pop(0)

            # file
            f = ET.SubElement(
                root, 'file', {
                    'poster': self.conf['posting']['from'],
                    'date': str(posttime),
                    'subject': subject,
                })

            # newsgroups
            groups = ET.SubElement(f, 'groups')
            for newsgroup in self.newsgroup.split(','):
                group = ET.SubElement(groups, 'group')
                group.text = newsgroup

            # segments
            segments = ET.SubElement(f, 'segments')
            temp = [(m._partnum, m, article_size)
                    for m, article_size in msgids]
            temp.sort()
            for partnum, article, article_size in temp:
                segment = ET.SubElement(segments, 'segment', {
                    'bytes': str(article_size),
                    'number': str(partnum),
                })
                segment.text = str(article.headers['Message-ID'][1:-1])

        with open(filename, 'w') as nzbfile:
            ET.ElementTree(root).write(nzbfile, xml_declaration=True)

        self.logger.info('End generation of %s', filename)

        #Copying NZB to different location
        end_folder = self.conf['posting']['final_folder']
        if end_folder:
            self.logger.info(
                'Copying NZB file, %s, to config defined location,',
                end_folder)
            endNzb = os.path.join(end_folder, filename)
            shutil.copyfile(filename, endNzb)
            if os.path.isfile(endNzb):
                self.logger.info('Finished copying NZB file')
                os.remove(filename)
                self.logger.info('Deleteing original NZB file after copied')
Beispiel #9
0
    def setUp(self):
        # Use c-based or pure python ElementTree impl based on test class
        if self.__class__ == TestcElementTreeNodes:
            if not self.adapter_class.is_available():
                self.skipTest("C-based ElementTree library is not installed"
                              " or is too outdated to be supported by xml4h")
            import xml.etree.cElementTree as ET
        else:
            if not self.adapter_class.is_available():
                self.skipTest(
                    "Pure Python ElementTree library is not installed"
                    " or is not too outdated to be supported by xml4h")
            import xml.etree.ElementTree as ET

        # Build a DOM using minidom for testing
        self.root_elem = ET.Element('{urn:test}DocRoot')
        doc = ET.ElementTree(self.root_elem)

        self.elem1 = ET.Element(u'元素1')
        self.elem1.attrib['xmlns:ns1'] = 'urn:ns1'
        self.elem1.attrib['a'] = '1'
        self.elem1.attrib['{urn:ns1}b'] = '2'
        self.elem2 = ET.Element('Element2')
        self.elem3 = ET.Element('{urn:ns1}Element3')
        self.elem3.attrib['xmlns'] = 'urn:ns1'
        self.elem4 = ET.Element('{urn:ns1}Element4')
        self.elem3.attrib['xmlns'] = 'urn:ns1'
        self.elem2_second = ET.Element('Element2')
        self.elem3_second = ET.Element('{urn:ns2}Element3')
        self.elem3_second.attrib['xmlns:ns2'] = 'urn:ns2'

        self.text_node = xml4h.impls.xml_etree_elementtree.ElementTreeText(
            'Some text', self.elem1)
        self.elem1.text = self.text_node.text
        self.cdata_node = xml4h.impls.xml_etree_elementtree.ElementTreeText(
            'Some cdata', self.elem2, is_cdata=True)
        self.elem2.text = self.cdata_node.text
        self.comment_node = ET.Comment('A comment')
        self.instruction_node = ET.ProcessingInstruction(
            'pi-target', 'pi-data')
        self.root_elem.append(self.elem1)
        self.root_elem.append(self.elem2)
        self.root_elem.append(self.elem3)
        self.root_elem.append(self.elem4)
        self.elem3.append(self.elem2_second)
        self.elem2_second.append(self.comment_node)
        self.elem4.append(self.elem3_second)
        self.elem3_second.append(self.instruction_node)

        self.doc = doc
        self.xml4h_doc = self.adapter_class.wrap_document(doc)
        self.xml4h_root = self.xml4h_doc.root
        self.xml4h_text = self.adapter_class.wrap_node(self.text_node,
                                                       self.doc)
Beispiel #10
0
    def addMetadata(self, md):
        txt = """
{name} - {description}
Created with Boxes.py (https://festi.info/boxes.py)
Creation date: {date}
""".format(date=datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S") , **md)

        txt += "Command line (remove spaces beteen dashes): %s\n" % md["cli"].replace("--", "- -")

        if md["url"]:
            txt+= "Url: %s\n" % md["url"]
            txt+= "SettingsUrl: %s\n" % re.sub(r"&render=[01]", "", md["url"])
        m = ElementTree.Comment(txt)
        self.tree.getroot().insert(0, m)
Beispiel #11
0
def do_addrepos(self, subcmd, opts, myproject, targetproject):
    """${cmd_name}: Configures a project with repositories that build against
    all the repositories in another project, with matching architectures

    This command creates a set of repositories in a project each with a single
    path that builds only against one repository of another project.
    
    ${cmd_usage}
    ${cmd_option_list}
    """
    path = quote_plus(myproject),
    kind = 'prj'
    data = meta_exists(metatype=kind,
                       path_args=path,
                       template_args=None,
                       create_new=False)
    if data:
        root = ET.fromstring(''.join(data))
        repos = {}
        for repo in get_repos_of_project(conf.config['apiurl'], targetproject):
            if repo.name not in repos:
                repos[repo.name] = []
            repos[repo.name].append(repo.arch)

        if not repos:
            print "osc: no repositories found in %s" % targetproject
            return False

        comment_element = ET.Comment(
            text="Repositories to build against project %s" % targetproject)
        root.append(comment_element)
        for reponame, archs in repos.iteritems():
            if not archs:
                print "no archs enabled in %s, skipping" % reponame
                continue
            new_reponame = "%s_%s_%s" % (targetproject.replace(
                ":", "_"), reponame, "_".join(archs))
            repo_element = ET.Element('repository', name=new_reponame)
            repo_element.append(
                ET.Element('path', repository=reponame, project=targetproject))
            for arch in archs:
                arch_element = ET.Element('arch')
                arch_element.text = arch
                repo_element.append(arch_element)
            root.append(repo_element)
    else:
        print "osc: an error occured"

    xmlindent(root)
    edit_meta(metatype=kind, path_args=path, edit=True, data=ET.tostring(root))
Beispiel #12
0
def xml_comment(text):
    """Create a new XML comment element.

    Parameters
    ----------
    text : :class:`str`
        The comment.

    Returns
    -------
    :func:`~xml.etree.ElementTree.Comment`
        A special element that is an XML comment.
    """
    return cElementTree.Comment(text)
Beispiel #13
0
    def writeHLTConfigFile(self, smk_psk_Name):
        """ Writes HLT config file"""
        if self.__HLTFile is None:
            return

        # HLT XML
        xHLTMenu = etree.Element("HLT_MENU",
                                 menu_name=smk_psk_Name["smkName"],
                                 prescale_set_name=smk_psk_Name["pskName"])

        # comments
        xHLTMenu.append(
            etree.Comment(
                'File is auto-generated by python config class, may be overwritten'
            ))
        xHLTMenu.append(
            etree.Comment('No. of HLT chains:' + str(len(self.theHLTChains))))

        self.markUsedSequences()

        # make xml sequences
        xSequenceList = etree.SubElement(xHLTMenu, 'SEQUENCE_LIST')
        for s in self.theSeqLists:
            s.xml(xSequenceList)

        # make xml chains
        xChainList = etree.SubElement(xHLTMenu, 'CHAIN_LIST')
        for c in self.theHLTChains:
            c.xml(xChainList)

        # write out the xml as a file
        file = open(self.__HLTFile, mode="wt")
        # etree does not support pretty printing, use minidom for this
        file.write(
            minidom.parseString(etree.tostring(xHLTMenu)).toprettyxml('  '))
        file.close()
        log.info("Wrote %s", self.__HLTFile)
Beispiel #14
0
def createXML(file, packages):
    root = ET.Element('packages')
    date = datetime.now().strftime("%Y-%m-%d %H:%M")
    root.set('date', date)  # Set File Date
    comment = ET.Comment('Generated by python....')
    root.append(comment)
    for entry in packages:
        package = ET.Element('package')
        package.set('id', entry[0])
        package.set('version', entry[1])
        root.append(package)
    xml = "<?xml version='1.0' encoding='UTF-8'?>" + ET.tostring(root, encoding='utf-8', method='xml')
    outputfile = open(file, 'w')
    xmlpp.pprint(xml, output=outputfile)
    outputfile.close()
Beispiel #15
0
 def okButton(self):
     # ENV CONFIG
     ros_TB4_IP_Value = self.ros_TB4_IP.text()
     ros_Master_IP_Value = self.ros_Master_IP.text()
     ros_Master_URI_Value = self.ros_Master_URI.text()
     ros_Hostname_Value = self.ros_TB4_Hostname.text()
     ros_TB4_Namespace_Value = self.ros_TB4_Namespace.text()
     # SSH CONNECTION
     ssh_TB4_IP_Value = self.ssh_TB4_IP.text()
     ssh_TB4_User_Value = self.ssh_TB4_User.text()
     ssh_TB4_Password_Value = self.ssh_TB4_Password.text()
     ssh_TB4_Port_Value = self.ssh_TB4_Port.text()
     # XML CREATION
     environmentXMLFile = et.Element('TB4_Settings')
     comment = et.Comment("TB4 ROS Environment and Configuration Variables")
     environmentXMLFile.append(comment)
     environmentConfig = et.SubElement(environmentXMLFile, 'TB4_MY_IP')
     environmentConfig.text = str(ros_TB4_IP_Value)
     environmentConfig = et.SubElement(environmentXMLFile, 'ROS_MASTER_IP')
     environmentConfig.text = str(ros_Master_IP_Value)
     environmentConfig = et.SubElement(environmentXMLFile, 'ROS_MASTER_URI')
     environmentConfig.text = str(ros_Master_URI_Value)
     environmentConfig = et.SubElement(environmentXMLFile, 'TB4_ROS_HOSTNAME')
     environmentConfig.text = str(ros_Hostname_Value)
     environmentConfig = et.SubElement(environmentXMLFile, 'TB4_ROS_NAMESPACE')
     environmentConfig.text = str(ros_TB4_Namespace_Value)
     environmentConfig = et.SubElement(environmentXMLFile, 'SSH_TB4_IP')
     environmentConfig.text = str(ssh_TB4_IP_Value)
     environmentConfig = et.SubElement(environmentXMLFile, 'SSH_TB4_USERNAME')
     environmentConfig.text = str(ssh_TB4_User_Value)
     environmentConfig = et.SubElement(environmentXMLFile, 'SSH_TB4_PASSWORD')
     environmentConfig.text = str(ssh_TB4_Password_Value)
     environmentConfig = et.SubElement(environmentXMLFile, 'SSH_TB4_PORT')
     environmentConfig.text = str(ssh_TB4_Port_Value)
     tree = et.ElementTree(environmentXMLFile)
     tree.write('tb4Settings.xml', encoding='utf8')
     # CHANGE THE PLACEHOLDER
     _translate = QtCore.QCoreApplication.translate
     self.ros_TB4_IP.setPlaceholderText(_translate("robotFourConfig", ros_TB4_IP_Value))
     self.ros_Master_IP.setPlaceholderText(_translate("robotFourConfig", ros_Master_IP_Value))
     self.ros_Master_URI.setPlaceholderText(_translate("robotFourConfig", ros_Master_URI_Value))
     self.ros_TB4_Hostname.setPlaceholderText(_translate("robotFourConfig", ros_Hostname_Value))
     self.ros_TB4_Namespace.setPlaceholderText(_translate("robotFourConfig", ros_TB4_Namespace_Value))
     self.ssh_TB4_IP.setPlaceholderText(_translate("robotFourConfig", ssh_TB4_IP_Value))
     self.ssh_TB4_User.setPlaceholderText(_translate("robotFourConfig", ssh_TB4_User_Value))
     self.ssh_TB4_Password.setPlaceholderText(_translate("robotFourConfig", ssh_TB4_Password_Value))
     self.ssh_TB4_Port.setPlaceholderText(_translate("robotFourConfig", ssh_TB4_Port_Value))
     sucessDialog()
Beispiel #16
0
def exportTheme(widget, schemeName, filename):
    """Saves the colors theme to a file."""
    tfd = widget.currentSchemeData()
    root = ET.Element('frescobaldi-theme')
    root.set('name', schemeName)
    comment = ET.Comment(_comment.format(appinfo=appinfo))
    root.append(comment)
    d = ET.ElementTree(root)

    font = tfd.font
    fontfamily = font.family()
    fontsize = str(font.pointSizeF())
    fontElt = ET.Element('font', {
        'fontFamily': fontfamily,
        'fontSize': fontsize
    })
    root.append(fontElt)

    baseColors = ET.Element('baseColors')
    for name, color in tfd.baseColors.items():
        elt = ET.Element(name)
        elt.set('color', color.name())
        baseColors.append(elt)

    defaultStyles = ET.Element('defaultStyles')
    for name, fmt in tfd.defaultStyles.items():
        elt = styleToElt(fmt, name)
        if elt is not None:
            defaultStyles.append(elt)

    allStyles = ET.Element('allStyles')
    for name, styles in tfd.allStyles.items():
        subElt = ET.Element(name)
        for name, fmt in styles.items():
            elt = styleToElt(fmt, name)
            if elt is not None:
                subElt.append(elt)
        if list(subElt):
            allStyles.append(subElt)
    root.append(baseColors)
    root.append(defaultStyles)
    root.append(allStyles)

    indentXml(root)
    d.write(filename, 'UTF-8')
Beispiel #17
0
 def __init__(self, config, patient_alias, patient_guid, timestamp, duration):
     self.guid = str(uuid.uuid1())
     self.root = ET.Element("session")
     self.root.set("timestamp", str(timestamp))
     self.root.set("duration", str(duration))
     self.root.set("version", config.SYSTEM_VERSION)
     self.root.set("guid", self.guid)
     self.root.append(ET.Comment("Generated: %s" % time.asctime()))
     self.zone = ET.SubElement(self.root, "zone")
     self.zone.set("alias", "default")
     self.zone.set("guid", config.ZONE_GUID)
     self.station = ET.SubElement(self.root, "station")
     self.station.set("alias", "default");
     self.station.set("guid", config.STATION_GUID)
     self.patient = ET.SubElement(self.root, "patient")
     self.patient.set("alias", patient_alias)
     self.patient.set("guid", patient_guid)
     self.hardware = ET.SubElement(self.root, "hardware")
Beispiel #18
0
def create_xml(lines, fname, display=True):
    root = ET.Element("root")
    tree = ET.ElementTree(root)

    for line in lines:
        (expression_name, expression) = process_line(line)
        root.append(ET.Comment(line))
        parsed_expression = expr.parseString(expression)[0]
        expression_node = ET.SubElement(root,
                                        "variable",
                                        value=expression_name)
        add_expression(expression_node, parsed_expression)

    xml_string = tree.write(fname)

    if display:
        xml_string = ET.tostring(root, encoding='utf-8')
        pretty_print(xml_string)
Beispiel #19
0
    def generate_nzb(self):
        filename = 'newsmangler_%s.nzb' % (SafeFilename(self._current_dir))

        self.logger.info('Begin generation of %s', filename)

        gentime = time.strftime('%Y-%m-%d %H:%M:%S UTC', time.gmtime())
        root = ET.Element('nzb')
        root.append(
            ET.Comment('Generated by newsmangler v%s at %s' %
                       (NM_VERSION, gentime)))

        for subject, msgids in self._msgids.items():
            posttime = msgids.pop(0)

            # file
            f = ET.SubElement(
                root, 'file', {
                    'poster': self.conf['posting']['from'],
                    'date': str(posttime),
                    'subject': subject,
                })

            # newsgroups
            groups = ET.SubElement(f, 'groups')
            for newsgroup in self.newsgroup.split(','):
                group = ET.SubElement(groups, 'group')
                group.text = newsgroup

            # segments
            segments = ET.SubElement(f, 'segments')
            temp = [(m._partnum, m, article_size)
                    for m, article_size in msgids]
            temp.sort()
            for partnum, article, article_size in temp:
                segment = ET.SubElement(segments, 'segment', {
                    'bytes': str(article_size),
                    'number': str(partnum),
                })
                segment.text = str(article.headers['Message-ID'][1:-1])

        with open(filename, 'w') as nzbfile:
            ET.ElementTree(root).write(nzbfile, xml_declaration=True)

        self.logger.info('End generation of %s', filename)
Beispiel #20
0
def constroi_xml(paragrafos_anotados, capitulo=1):
    tree = ET.parse(TEI)
    root = tree.getroot()
    root.insert(0, ET.Comment(COMMENT))
    body = tree.getiterator("body")[0]
    div = ET.SubElement(body, "div", type="chap", n="%d" % capitulo)
    t, s, p = 1, 1, 1
    for para in paragrafos_anotados:
        elemento_p = ET.SubElement(div, 'p', n="%d" % p)
        p += 1
        for sent in para:
            elemento_s = ET.SubElement(elemento_p, 's', n="%d" % s)
            s += 1
            for palavra, etiqueta in sent:
                elemento_w = ET.SubElement(elemento_s, 'w', type=etiqueta)
                elemento_w.text = palavra
                elemento_w.set("xml:id", "w%d" % t)
                t += 1
    return tree
def run():
    # read xls file
    wkb = xlrd.open_workbook('test/students.xls')
    sheet = wkb.sheets()[0]
    data = defaultdict(list)
    for row in range(sheet.nrows):
        for col in range(1, sheet.ncols):
            data[str(row + 1)].append(sheet.cell(row, col).value)
    students_data = json.dumps(data, indent=4, ensure_ascii=False)

    # write xml file
    root = ET.Element('root')
    tree = ET.ElementTree(root)
    students = ET.SubElement(root, 'students')
    comment = ET.Comment(u'{space}学生信息表 "id" : [名字, 数学, 语文, 英文]{space}'.format(
        space=os.linesep))
    students.text = students_data
    students.insert(1, comment)
    tree.write('test/students.xml', encoding='utf-8', xml_declaration=True)
    def construct_graphml(self):

        graphml = ET.Element("graphml",
                             xmlns="http://graphml.graphdrawing.org/xmlns")
        graphml.set("xmlns:java",
                    "http://www.yworks.com/xml/yfiles-common/1.0/java")
        graphml.set(
            "xmlns:sys",
            "http://www.yworks.com/xml/yfiles-common/markup/primitives/2.0")
        graphml.set("xmlns:x",
                    "http://www.yworks.com/xml/yfiles-common/markup/2.0")
        graphml.set("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance")
        graphml.set("xmlns:y", "http://www.yworks.com/xml/graphml")
        graphml.set("xmlns:yed", "http://www.yworks.com/xml/yed/3")
        graphml.set(
            "xsi:schemaLocation",
            "http://graphml.graphdrawing.org/xmlns http://www.yworks.com/xml/schema/graphml/1.1/ygraphml.xsd"
        )
        comment = ET.Comment('Graphml file Converted from Tex Code')
        graphml.append(comment)
        node_key = ET.SubElement(graphml, "key", id="data_node")
        node_key.set("for", "node")
        node_key.set("yfiles.type", "nodegraphics")

        edge_key = ET.SubElement(graphml, "key", id="data_edge")
        edge_key.set("for", "edge")
        edge_key.set("yfiles.type", "edgegraphics")

        graph = ET.SubElement(graphml,
                              "graph",
                              edgedefault=self.directed,
                              id=self.graph_id)

        for node_id in self.nodes:
            node = self.nodes[node_id].convert()
            graph.append(node)

        for edge_id in self.edges:
            edge = self.edges[edge_id].convert()
            graph.append(edge)

        self.graphml = graphml
Beispiel #23
0
    def exportWeights(self, weights={}, fileName=None, printPretty=True):
        """
        Generate an XML document
        """
        # TO DO: Add pretty print option flag - will build this into qt widget ui

        startTime = time.time()

        # Write to XML using cElementTree
        root = cElement.Element("root")
        mesh = cElement.SubElement(root, 'mesh', {'name': self.selName})

        for (vertId, subWeights) in weights.iteritems():
            vertIdElem = cElement.SubElement(
                mesh, 'vertId', {
                    'index': str(vertId),
                    'path': '%s.vtx[%s]' % (self.selName, str(vertId))
                })
            for (infIndex, infWeight) in subWeights.iteritems():
                cElement.SubElement(vertIdElem, 'inf', {
                    'idx': str(infIndex),
                    'weight': str(infWeight)
                })

        endComment = cElement.Comment('eof')
        root.append(endComment)

        if not fileName:
            fileName = self.defaultFileName

        f = open(fileName, 'w')

        if printPretty:
            f.write(self.prettify(root))
        else:
            cElement.ElementTree(root).write(f)

        f.close()

        endTime = time.time()
        print("Export weights took %g seconds" % (endTime - startTime))
Beispiel #24
0
def save(names, filename):
    """Saves the named snippets to a file."""
    root = ET.Element('snippets')
    root.text = '\n\n'
    root.tail = '\n'
    d = ET.ElementTree(root)

    comment = ET.Comment(_comment.format(appinfo=appinfo))
    comment.tail = '\n\n'
    root.append(comment)

    for name in names:
        snippet = ET.Element('snippet')
        snippet.set('id', name)
        snippet.text = '\n'
        snippet.tail = '\n\n'

        title = ET.Element('title')
        title.text = snippets.title(name, False)
        title.tail = '\n'

        shortcuts = ET.Element('shortcuts')
        ss = model.shortcuts(name)
        if ss:
            shortcuts.text = '\n'
            for s in ss:
                shortcut = ET.Element('shortcut')
                shortcut.text = s.toString()
                shortcut.tail = '\n'
                shortcuts.append(shortcut)
        shortcuts.tail = '\n'

        body = ET.Element('body')
        body.text = snippets.text(name)
        body.tail = '\n'

        snippet.append(title)
        snippet.append(shortcuts)
        snippet.append(body)
        root.append(snippet)
    d.write(filename, "UTF-8")
Beispiel #25
0
def construct_XML_doc(attribs):
    config = load_yaml_config()
    action_name = attribs.pop('action_name', None)
    
    oozie = ET.Element('workflow-app', xmlns=config.get('xmlns_workflow'))
    
    comment = ET.Comment('This Oozie workflow was generated using Sqoopy.\n \\\
    If you are having difficulties with running this Oozie job then contact\n \\\
    Diederik from the Analytics Team.')
    
    oozie.append(comment)
    
    start = ET.SubElement(oozie, 'start', to='%s' % action_name)
    action = ET.SubElement(oozie, 'action', name='%s' % action_name)
    
    sqoop = ET.SubElement(action, 'sqoop', xmlns=config.get('xmlns_sqoop'))
    jobtracker = ET.SubElement(sqoop, 'job-tracker')
    jobtracker.text = '${jobTracker}'
    namenode = ET.SubElement(sqoop, 'name-node')
    namenode.text = '${nameNode}'
    configuration = ET.SubElement(sqoop, 'configuration')
    property = ET.SubElement(configuration, 'property')
    name = ET.SubElement(property, 'name')
    name.text = 'oozie.use.system.libpath'
    value = ET.SubElement(property, 'value')
    value.text = 'true'
    archive = ET.SubElement(sqoop, 'archive')
    archive.text = config.get('archive')
    
    write_args(sqoop, attribs)
    
    ok = ET.SubElement(action, 'ok', to='end')
    error = ET.SubElement(action, 'error', to='kill')

    kill = ET.SubElement(oozie, 'kill', name='kill')
    message = ET.SubElement(kill, 'message')
    message.text = 'Action failed, error message[${wf:errorMessage(wf:lastErrorNode())}]'

    end = ET.SubElement(oozie, 'end', name='end')
    
    write_xml(oozie, action_name)
 def _create_shelf(self):
     """Create toolbar folder and dummy shelf file"""
     toolbar_dir = self._makedir(os.path.join(self._source_dir(),
                                              "toolbar"))
     shelf_file = os.path.join(toolbar_dir, "{0}.shelf".format(self._name))
     sesi_comment = (
         "This file contains definitions of shelves, toolbars, and tools.\n"
         "It should not be hand-edited when it is being used by the\n"
         "application. Note, that two definitions of the same element are\n"
         "not allowed in a single file. ")
     doc = ET.Element("shelfDocument")
     ET.SubElement(doc,
                   "toolshelf",
                   name=self._name,
                   label=self._tool_title())
     comment = ET.Comment(sesi_comment)
     doc.insert(0, comment)
     # declaration = """<?xml version="1.0" encoding="UTF-8"?>"""
     xmlstr = minidom.parseString(ET.tostring(doc)).toprettyxml(indent="  ")
     with open(shelf_file, "w") as file_:
         file_.write(xmlstr)
    def rollup_header_footer(self, context):
        """Include CodeMirror library only when a code tag is present."""

        if oeditor.CAN_HIGHLIGHT_CODE.value:
            header = tags.html_string_to_element_tree(
                '<script src="%s/lib/codemirror.js"></script>'
                '<link rel="stylesheet" href="%s/lib/codemirror.css">'
                '<script src="%s/addon/mode/loadmode.js"></script>'
                '<link rel="stylesheet" href="%s/code_tags.css">' %
                (CODEMIRROR_URI, CODEMIRROR_URI, CODEMIRROR_URI,
                 CODETAGS_RESOURCES_URI))
            footer = tags.html_string_to_element_tree(
                '<script src="%s/code_tags.js">'
                '</script>' % CODETAGS_RESOURCES_URI)
        else:
            header = cElementTree.Element('link')
            header.attrib['rel'] = 'stylesheet'
            header.attrib['href'] = '%s/code_tags_no_highlight.css' % (
                CODETAGS_RESOURCES_URI)
            footer = cElementTree.Comment('Empty footer')

        return (header, footer)
Beispiel #28
0
def DOM2ET(domelem):
    """Converts a DOM node object of type element to an ElementTree Element.

    domelem: DOM node object of type element (domelem.nodeType == domelem.ELEMENT_NODE)

    returns an 'equivalent' ElementTree Element
    """
    # make some local variables for fast processing
    tyCDATA = domelem.CDATA_SECTION_NODE
    tyTEXT = domelem.TEXT_NODE
    tyPI = domelem.PROCESSING_INSTRUCTION_NODE
    tyCOMMENT = domelem.COMMENT_NODE
    tyELEMENT = domelem.ELEMENT_NODE
    # calculate the attributes of the domelem
    attribs = domelem.attributes
    attrs = dict((x.name, x.value) for x in (attribs.item(i) for i in range(attribs.length)))
    # build the ET Element
    etelem = ET.Element(domelem.tagName, attrs)
    last = None # to differentiate between 'text' and 'tail'
    for node in domelem.childNodes:
        nodeType = node.nodeType
        if (tyTEXT == nodeType or tyCDATA == nodeType) and node.data:
            data = node.data
            if last is None: etelem.text = etelem.text + data if etelem.text else data
            else: last.tail = last.tail + data if last.tail else data
        elif tyELEMENT == nodeType:
            last = DOM2ET(node)
            etelem.append(last)
        elif tyCOMMENT == nodeType:
            last = ET.Comment(node.data)
            etelem.append(last)
        elif tyPI == nodeType:
            last = ET.ProcessingInstruction(node.target, node.data)
            etelem.append(last)

    return etelem
Beispiel #29
0
 def rollup_header_footer(self, context):
     header = cElementTree.Comment('Empty header')
     footer = cElementTree.Element('script')
     footer.attrib['src'] = (
         '/modules/questionnaire/resources/js/questionnaire.js')
     return (header, footer)
Beispiel #30
0
def insertXMLHeaders (mustpass, doc):
	if mustpass.project.copyright != None:
		doc.insert(0, ElementTree.Comment(mustpass.project.copyright))
	doc.insert(1, ElementTree.Comment(GENERATED_FILE_WARNING))