def createSVG(s, outfile, r = 1): src = parse(s.filename) new = Document() svg = src.getElementsByTagName('svg')[0] new.appendChild(svg) defs = new.getElementsByTagName('defs')[0] #rec0 = new.getElementById(s.rec_name) #print (rec0.appendChil) title = svg.getElementsByTagName('title')[0] if 'data-type' in title.attributes and title.attributes['data-type'].value == 'shape': s.shapegen(defs, new ) else: s.gen(r, defs, new ) svg = new.getElementsByTagName('svg')[0] #svg.appendChild(rect) #svg.setAttribute('width', "1000") #svg.setAttribute('height', "1000") #use = new.createElement('use') #use.setAttribute("xlink:href", "#fractal") #use.setAttribute("stroke-width", "4") #use.setAttribute("transform", "translate(100,-300) scale(8)") #use.setAttribute("stroke", "black") #use.setAttribute("stroke-width", "2") #svg.appendChild(use) with open(outfile, "w") as f: new.writexml(f, newl="\n", addindent=" ", indent=" ")
def parseXml(self, xmlRef: Document) -> InvoiceDocument: result = InvoiceDocument() result.header = self.parseHeader( xmlRef.getElementsByTagName("Invoice-Header")[0]) result.buyer = self.parseParty(xmlRef.getElementsByTagName("Buyer")[0]) result.seller = self.parseParty( xmlRef.getElementsByTagName("Seller")[0]) result.summary = self.parseSummary( xmlRef.getElementsByTagName("Invoice-Summary")[0]) result.lines = self.parseLines( xmlRef.getElementsByTagName("Line-Item")) result = self.processResult(result) return result
def parseXml(self, xmlRef: Document) -> InvoiceDocument: result = InvoiceDocument() result.header = self.parseHeader( xmlRef.getElementsByTagName("NAGLOWEK")[0]) result.buyer = self.parseParty( xmlRef.getElementsByTagName("ODBIORCA")[0]) result.seller = self.parseParty( xmlRef.getElementsByTagName("SPRZEDAWCA")[0]) result.summary = self.parseSummary( xmlRef.getElementsByTagName("NAGLOWEK")[0]) result.lines = self.parseLines(xmlRef.getElementsByTagName("POZYCJA")) result = self.processResult(result) return result
def convert_vector_drawable_xml(vd_xml: Document, color_map, viewbox_only): vd_node = vd_xml.getElementsByTagName('vector')[0] # create svg xml svg_xml = Document() svg_node = svg_xml.createElement('svg') svg_xml.appendChild(svg_node) # setup basic svg info svg_node.attributes['xmlns'] = 'http://www.w3.org/2000/svg' if not viewbox_only: svg_node.attributes['width'] = vd_node.attributes[ 'android:viewportWidth'].value svg_node.attributes['height'] = vd_node.attributes[ 'android:viewportHeight'].value svg_node.attributes['viewBox'] = '0 0 {} {}'.format( vd_node.attributes['android:viewportWidth'].value, vd_node.attributes['android:viewportHeight'].value) # iterate through all groups vd_groups = vd_xml.getElementsByTagName('group') for vd_group in vd_groups: # create the group svg_group = svg_xml.createElement('g') translate_x = translate_y = 0 if vd_group.hasAttribute('android:translateX'): translate_x = vd_group.attributes['android:translateX'].value if vd_group.hasAttribute('android:translateY'): translate_y = vd_group.attributes['android:translateY'].value if translate_x or translate_y: svg_group.attributes['transform'] = 'translate({},{})'.format( translate_x, translate_y) # iterate through all paths inside the group convert_paths(vd_group, svg_group, svg_xml, color_map) # append the group to the svg node svg_node.appendChild(svg_group) # iterate through all svg-level paths convert_paths(vd_node, svg_node, svg_xml, color_map) return svg_xml
def _get_labels_and_coordinates_dict( xmldoc: minidom.Document) -> Dict[str, Dict[str, str]]: """ Creates a mapping of node names and their coordinates. Args: xmldoc: xml information. Returns: Dict[str, Dict[str, str]] Dictionary of nodes and coordinates. """ template_coordinates = {} # type: Dict[str, Dict[str, str]] for graphic in xmldoc.getElementsByTagName('graphics'): if graphic.attributes.values( ) and graphic.parentNode.tagName == "node": rxnconID = _get_rxnconID(graphic.parentNode) if rxnconID not in template_coordinates: template_coordinates[rxnconID] = { "x": graphic.getAttribute('x'), "y": graphic.getAttribute('y'), "z": graphic.getAttribute('z') } else: raise AssertionError return template_coordinates
def write_inds_2_xml(inds, res_path): """ This function writes the individuals minidom Node into an XML file. Parameters ---------- inds : list of xml minidom Node All the individuals to be written to the xml file. res_path : str The file path of the XML file. """ #write an xml file doc = Document() root_node = doc.createElement("data") doc.appendChild(root_node) population = doc.createElement("population") root_node.appendChild(population) doc = xml.dom.minidom.parseString("<data><population></population></data>") parent_node = doc.getElementsByTagName("population")[0] for ind_node in inds: parent_node.appendChild(ind_node) f = open(res_path, "w") f.write(doc.toxml()) f.close()
def from_container(xmldoc: minidom.Document) -> Dict[str, Any]: metadata = {} keys = { "title": "Title", "episodeTitle": "EpisodeTitle", "description": "Description", "programId": "ProgramId", "seriesId": "SeriesId", "episodeNumber": "EpisodeNumber", "tvRating": "TvRating", "displayMajorNumber": "SourceChannel", "callsign": "SourceStation", "showingBits": "ShowingBits", "mpaaRating": "MpaaRating", } details = xmldoc.getElementsByTagName("Details")[0] for key in keys: data: Any = tag_data(details, keys[key]) if data: if key == "description": data = data.replace(TRIBUNE_CR, "").replace(ROVI_CR, "") if data.endswith(" *"): data = data[:-2] elif key == "tvRating": data = int(data) elif key == "displayMajorNumber": if "-" in data: data, metadata["displayMinorNumber"] = data.split("-") metadata[key] = data return metadata
def open(self, dom: Document, project: PyutProject): """ Open a file and create a diagram. Args: dom: The minidom document project: The UI Project to fill out """ self.__setupProgressDialog() umlFrame: UmlDiagramsFrame = cast(UmlDiagramsFrame, None) # avoid Pycharm warning root = self.__validateXmlVersion(dom) try: project.setCodePath(root.getAttribute("CodePath")) self.__updateProgressDialog(newMessage='Reading elements...', newGaugeValue=1) wxYield() toOgl: MiniDomToOglV10 = MiniDomToOglV10() for documentNode in dom.getElementsByTagName( PyutXmlConstants.ELEMENT_DOCUMENT): documentNode: Element = cast(Element, documentNode) docTypeStr: str = documentNode.getAttribute( PyutXmlConstants.ATTR_TYPE) self.__updateProgressDialog( newMessage= f'Determine Title for document type: {docTypeStr}', newGaugeValue=2) wxYield() docType: DiagramType = PyutConstants.diagramTypeFromString( docTypeStr) document: PyutDocument = project.newDocument(docType) document.title = self.__determineDocumentTitle(documentNode) umlFrame: UmlDiagramsFrame = self.__showAppropriateUmlFrame( document) self.__positionAndSetupDiagramFrame(umlFrame=umlFrame, documentNode=documentNode) self.__updateProgressDialog(newMessage='Start Conversion...', newGaugeValue=3) if docType == DiagramType.CLASS_DIAGRAM: self.__renderClassDiagram(documentNode, toOgl, umlFrame) elif docType == DiagramType.USECASE_DIAGRAM: self.__renderUseCaseDiagram(documentNode, toOgl, umlFrame) elif docType == DiagramType.SEQUENCE_DIAGRAM: self.__renderSequenceDiagram(documentNode, toOgl, umlFrame) self.__updateProgressDialog( newMessage='Conversion Complete...', newGaugeValue=4) except (ValueError, Exception) as e: self._dlgGauge.Destroy() PyutUtils.displayError(_(f"Can not load file {e}")) umlFrame.Refresh() return self.__cleanupProgressDialog(umlFrame)
def get_keywords(dom: Document) -> str: """Get the keywords of the svg file.""" desc_tags = dom.getElementsByTagName("desc") if len(desc_tags) > 0 and desc_tags[0].firstChild is not None: return desc_tags[0].firstChild.nodeValue.split(" ") else: return []
def _from_movie_nfo(xmldoc: minidom.Document) -> Dict[str, Any]: metadata: Dict[str, Any] = {} movie = xmldoc.getElementsByTagName("movie") if movie: movie = movie[0] else: return metadata items = { "description": "plot", "title": "title", "movieYear": "year", "starRating": "rating", "mpaaRating": "mpaa", } metadata["isEpisode"] = "false" for item in items: data = tag_data(movie, items[item]) if data: metadata[item] = data metadata["movieYear"] = "%04d" % int(metadata.get("movieYear", 0)) metadata = _nfo_vitems(movie, metadata) return metadata
def _extract_version(dom: minidom.Document, template_name: str) -> int: # If no meta pydoctor-template-version tag found, # it's most probably a placeholder template. version = -1 for meta in dom.getElementsByTagName("meta"): if meta.getAttribute("name") != "pydoctor-template-version": continue # Remove the meta tag as soon as found meta.parentNode.removeChild(meta) if not meta.hasAttribute("content"): warnings.warn( f"Could not read '{template_name}' template version: " f"the 'content' attribute is missing") continue version_str = meta.getAttribute("content") try: version = int(version_str) except ValueError: warnings.warn( f"Could not read '{template_name}' template version: " "the 'content' attribute must be an integer") else: break return version
def _from_episode_nfo(nfo_path: str, xmldoc: minidom.Document) -> Dict[str, Any]: metadata: Dict[str, Any] = {} items = { "description": "plot", "episodeTitle": "title", "seriesTitle": "showtitle", "originalAirDate": "aired", "starRating": "rating", "tvRating": "mpaa", } # find tvshow.nfo path = nfo_path while True: basepath = os.path.dirname(path) if path == basepath: break path = basepath tv_nfo = os.path.join(path, "tvshow.nfo") if os.path.exists(tv_nfo): metadata.update(_from_tvshow_nfo(tv_nfo)) break episode = xmldoc.getElementsByTagName("episodedetails") if episode: episode = episode[0] else: return metadata metadata["isEpisode"] = "true" for item in items: data = tag_data(episode, items[item]) if data: metadata[item] = data season = tag_data(episode, "displayseason") if not season or season == "-1": season = tag_data(episode, "season") if not season: season = "1" ep_num = tag_data(episode, "displayepisode") if not ep_num or ep_num == "-1": ep_num = tag_data(episode, "episode") if ep_num and ep_num != "-1": metadata["episodeNumber"] = "%d%02d" % (int(season), int(ep_num)) if "originalAirDate" in metadata: metadata["originalAirDate"] += "T00:00:00Z" metadata = _nfo_vitems(episode, metadata) return metadata
def from_alignment_minidom( dom: Document, *, prefix_map: PrefixMap, meta: MetadataType ) -> MappingSetDataFrame: """Read a minidom Document object. :param dom: XML (minidom) object :param prefix_map: A prefix map :param meta: Optional meta data :return: MappingSetDocument :raises ValueError: for alignment format: xml element said, but not set to yes. Only XML is supported! """ # FIXME: should be prefix_map = _check_prefix_map(prefix_map) _ensure_prefix_map(prefix_map) ms = _init_mapping_set(meta) mlist: List[Mapping] = [] # bad_attrs = {} alignments = dom.getElementsByTagName("Alignment") for n in alignments: for e in n.childNodes: if e.nodeType == Node.ELEMENT_NODE: node_name = e.nodeName if node_name == "map": cell = e.getElementsByTagName("Cell") for c_node in cell: mdict = _cell_element_values(c_node, prefix_map) if mdict: m = _prepare_mapping(mdict) mlist.append(m) else: logging.warning( f"While trying to prepare a mapping for {c_node}, something went wrong. " f"This usually happens when a critical prefix_map entry is missing." ) elif node_name == "xml": if e.firstChild.nodeValue != "yes": raise ValueError( "Alignment format: xml element said, but not set to yes. Only XML is supported!" ) elif node_name == "onto1": ms["subject_source_id"] = e.firstChild.nodeValue elif node_name == "onto2": ms["object_source_id"] = e.firstChild.nodeValue elif node_name == "uri1": ms["subject_source"] = e.firstChild.nodeValue elif node_name == "uri2": ms["object_source"] = e.firstChild.nodeValue ms.mappings = mlist # type: ignore _set_metadata_in_mapping_set(mapping_set=ms, metadata=meta) mapping_set_document = MappingSetDocument(mapping_set=ms, prefix_map=prefix_map) return to_mapping_set_dataframe(mapping_set_document)
def getDatosReceptor(CFDI: minidom.Document, configDict: dict): # Obtenemos configuración del Receptor try: configReceptor = configDict.get("clientesInfo") except Exception as e: raise ValueError( "El archivo de configuración tiene un error: {0}".format(e)) # Verificamos si el usuario quiere sobreescribir opciones try: useDefault = configReceptor.get("useDefault") except Exception as e: raise ValueError( "El archivo de configuración tiene un error: {0}".format(e)) # Obtenemos la raiz del documento Comprobante = CFDI.getElementsByTagName("cfdi:Comprobante")[0] ReceptorNode = Comprobante.getElementsByTagName("cfdi:Receptor")[0] # Creamos un diccionario con los datos del Receptor receptor = dict() # Nombre, RFC, Regimen, Domicilio y Contacto de receptor NombreReceptor = ReceptorNode.getAttribute("Nombre") RfcReceptor = ReceptorNode.getAttribute("Rfc") UsoReceptor = ReceptorNode.getAttribute("UsoCFDI") #Descripción uso CFDI del uso de CFDI UsoReceptor = "{0} - {1}".format( UsoReceptor, getCatalogoValue("usoCFDI", UsoReceptor, configDict)) DomicilioReceptor = "" receptor.update(NombreReceptor=NombreReceptor) receptor.update(RfcReceptor=RfcReceptor) receptor.update(UsoReceptor=UsoReceptor) receptor.update(DomicilioReceptor=DomicilioReceptor) # Si el usuario quiere sobreescribir if useDefault is False: if configReceptor["clientesDict"].get(RfcReceptor, None) is None: print("\tNo se encontró información para el cliente con RFC {0}". format(RfcReceptor)) else: NombreReceptor = configReceptor["clientesDict"].get( RfcReceptor, {}).get("nombre", "") DomicilioReceptor = configReceptor["clientesDict"].get( RfcReceptor, {}).get("domicilio", "") receptor.update(NombreReceptor=NombreReceptor) receptor.update(DomicilioReceptor=DomicilioReceptor) # Regresamos datos del receptor return receptor
def getDatosComprobante(CFDI: minidom.Document, configDict: dict): # Obtenemos la raiz del documento ComprobanteNode = CFDI.getElementsByTagName("cfdi:Comprobante")[0] # Creamos un diccionario con los datos de la factura comprobante = dict() # Certificado, fecha, forma de pago, lugar de expedición, método de pago, moneda, no. de certificado, # sello, subtotal, total, tipo de comprobante certificado = ComprobanteNode.getAttribute("Certificado") fecha = ComprobanteNode.getAttribute("Fecha") formaPago = ComprobanteNode.getAttribute("FormaPago") #Descripción de la forma de pago (Catálogo del SAT) formaPago = getCatalogoValue("formaPago", formaPago, configDict) lugarExpedicion = ComprobanteNode.getAttribute("LugarExpedicion") metodoPago = ComprobanteNode.getAttribute("MetodoPago") # Descripción del método de pago (Catálogo del SAT) metodoPago = getCatalogoValue("metodoPago", metodoPago, configDict) moneda = ComprobanteNode.getAttribute("Moneda") # Descripción de la moneda (Catálogo del SAT) moneda = "{0} ({1})".format(getCatalogoValue("moneda", moneda, configDict), moneda) numCertificado = ComprobanteNode.getAttribute("NoCertificado") sello = ComprobanteNode.getAttribute("Sello") subtotal = ComprobanteNode.getAttribute("SubTotal") total = ComprobanteNode.getAttribute("Total") tipoComprobante = ComprobanteNode.getAttribute("TipoDeComprobante") version = ComprobanteNode.getAttribute("Version") comprobante.update(Certificado=certificado) comprobante.update(Fecha=fecha) comprobante.update(FormaPago=formaPago) comprobante.update(LugarExpedicion=lugarExpedicion) comprobante.update(MetodoPago=metodoPago) comprobante.update(Moneda=moneda) comprobante.update(NoCertificado=numCertificado) comprobante.update(Sello=sello) comprobante.update(Subtotal=subtotal) comprobante.update(Total=total) comprobante.update(TipoDeComprobante=tipoComprobante) comprobante.update(Version=version) # Verificamos la versión del certificado if float(version) != 3.3: raise ValueError( "¡BeautifyCFDI se diseñó para trabajar con certificados versión 3.3!" ) return comprobante
def clear_switches(doc: minidom.Document): switches = doc.getElementsByTagName('switch') for s in switches: children = s.childNodes assert len(children) == 2 if children[0].tagName == 'g' and 'requiredFeatures' in children[ 0].attributes: s.parentNode.removeChild(s) s.unlink() continue assert children[0].tagName == 'foreignObject' assert children[1].tagName == 'text' c = children[1] s.removeChild(c) s.parentNode.insertBefore(c, s) s.parentNode.removeChild(s)
def getDatosEmisor(CFDI: minidom.Document, configDict: dict): # Obtenemos configuración del emisor try: configEmisor = configDict.get("userInfo") except Exception as e: raise ValueError( "El archivo de configuración tiene un error: {0}".format(e)) # Verificamos si el usuario quiere sobreescribir opciones try: useDefault = configEmisor.get("useDefault") except Exception as e: raise ValueError( "El archivo de configuración tiene un error: {0}".format(e)) # Obtenemos la raiz del documento Comprobante = CFDI.getElementsByTagName("cfdi:Comprobante")[0] EmisorNode = Comprobante.getElementsByTagName("cfdi:Emisor")[0] # Creamos un diccionario con los datos del emisor emisor = dict() # Nombre, RFC, Regimen, Domicilio y Contacto de emisor NombreEmisor = EmisorNode.getAttribute("Nombre") RfcEmisor = EmisorNode.getAttribute("Rfc") RegimenEmisor = EmisorNode.getAttribute("RegimenFiscal") # Descripción del regimen del emisor (catálogo del SAT) RegimenEmisor = "{0} - {1}".format( RegimenEmisor, getCatalogoValue("regimenFiscal", RegimenEmisor, configDict)) DomicilioEmisor = "" ContactoEmisor = "" emisor.update(NombreEmisor=NombreEmisor) emisor.update(RfcEmisor=RfcEmisor) emisor.update(RegimenEmisor=RegimenEmisor) emisor.update(DomicilioEmisor=DomicilioEmisor) emisor.update(ContactoEmisor=ContactoEmisor) # Si el usuario quiere sobreescribir if useDefault is False: emisor.update(NombreEmisor=configEmisor["user"].get("nombre")) emisor.update(DomicilioEmisor=configEmisor["user"].get("domicilio")) emisor.update(ContactoEmisor=configEmisor["user"].get("contacto")) # Regresamos datos del emisor return emisor
def write_inds_2_xml(inds, res_path): #write an xml file doc = Document() root_node = doc.createElement("data") doc.appendChild(root_node) population = doc.createElement("population") root_node.appendChild(population) doc = xml.dom.minidom.parseString("<data><population></population></data>") parent_node = doc.getElementsByTagName("population")[0] for ind_node in inds: parent_node.appendChild(ind_node) f = open(res_path, "w") f.write(doc.toxml()) f.close()
def UpdateLastSyncDate(self, LastSyncDate): userFile=self.GetUserLastFile(self.GetActualUser()) if not os.path.exists(userFile): doc=Document() root = doc.createElement("lastUpdate") root.setAttribute( 'datetime', '%s' % LastSyncDate ) doc.appendChild(root) else: doc = minidom.parse(userFile) root = doc.getElementsByTagName('lastUpdate')[0] root.setAttribute( 'datetime', '%s' % LastSyncDate ) doc.appendChild(root) #doc.unlink() doc.writexml( open(userFile, 'w'), indent=" ", addindent=" ", newl='\n') return LastSyncDate
def __validateXmlVersion(self, dom: Document) -> Element: """ Args: dom: The minidom Document Returns: The root element unless the XML version is incorrect """ root: Element = dom.getElementsByTagName(PyutXmlConstants.TOP_LEVEL_ELEMENT)[0] if root.hasAttribute(PyutXmlConstants.ATTR_VERSION): version = int(root.getAttribute(PyutXmlConstants.ATTR_VERSION)) else: version = 1 if version != PyutXml.VERSION: self.logger.error("Wrong version of the file loader") eMsg: str = f'This is version {PyutXml.VERSION} and the file version is {version}' self.logger.error(eMsg) raise Exception(f'VERSION_ERROR: {eMsg}') return root
def get_elements_from_xml( xml_doc: Document, tag_name: str, attributes: list[str], get_all: bool = False ) -> Union[list[dict[str, str]], dict[str, str]]: root_elements = xml_doc.getElementsByTagName(tag_name) result = [] for el in root_elements: attr_dict = {} for attr in attributes: attr_dict[attr] = ( el.attributes[attr].value if attr in el.attributes else f"{attr} no disponible" ) if get_all: result.append(attr_dict) else: return attr_dict return result
def findElements(document: Document, tagName, attrName='', attrValue=''): """ 查找document下的Elements :param document: document :param tagName: tagName :param attrName: attrName :param attrValue: attrValue :return: 查找到到元素列表 """ elements: [Element] = document.getElementsByTagName(tagName) res = [] if elements: for element in elements: if attrName: attribute = element.getAttribute(attrName) if attribute: if attrValue: if attribute == attrValue: res.append(element) else: res.append(element) else: res.append(element) return res
def add_classes(doc: minidom.Document): paths = doc.getElementsByTagName('path') add_stroke_classes(paths) add_fill_classes(paths) rects = doc.getElementsByTagName('rect') add_stroke_classes(rects) add_fill_classes(rects) ellipse = doc.getElementsByTagName('ellipse') add_stroke_classes(ellipse) add_fill_classes(ellipse) text = doc.getElementsByTagName('text') add_fill_classes(text) div = doc.getElementsByTagName('div') add_bg_classes(div) span = doc.getElementsByTagName('span') add_bg_classes(span)
class CCmdSet(): global DISCRIMINATOR, VERSION DISCRIMINATOR = 0x9530ed04 VERSION = 0x00020002 from xml.dom.minidom import Document #member var #header m_cmdname = '' m_msgtype = '' m_senderID = '' m_receiverID = '' m_resrcID = 0 m_usertag = '' m_status = 0 m_timeout = 0 m_contentID = '' m_cmdID = 0 #body m_params = [] #doc,riml,header,body,params doc = Document() # Create the <riml> base element riml = doc.createElement("riml") doc.appendChild(riml) # Create the main <header>, <body> <params>element header = doc.createElement("header") riml.appendChild(header) body = doc.createElement("body") riml.appendChild(body) params = doc.createElement("params") body.appendChild(params) def __init__(self, cmdname="", msgtype="", senderID="", receiverID="", resrcID=0, usertag="", status=0, timeout=0, contentID='', cmdID=0): from xml.dom.minidom import Document # Create the <riml> base element self.doc = Document() self.riml = self.doc.createElement("riml") self.doc.appendChild(self.riml) # Create the main <header>, <body> <params>element self.header = self.doc.createElement("header") self.riml.appendChild(self.header) self.body = self.doc.createElement("body") self.riml.appendChild(self.body) self.params = self.doc.createElement("params") self.body.appendChild(self.params) self.m_cmdname = cmdname self.m_msgtype = msgtype self.m_senderID = senderID self.m_receiverID = receiverID self.m_resrcID = resrcID self.m_usertag = usertag self.m_status = status self.m_timeout = timeout self.m_contentID = contentID self.m_cmdID = cmdID # Create the main <header> element verTag = self.doc.createElement("ver") cmdnameTag = self.doc.createElement("cmdname") msgtypeTag = self.doc.createElement("msgtype") senderIDTag = self.doc.createElement("senderID") receiverIDTag = self.doc.createElement("receiverID") resrcIDTag = self.doc.createElement("resrcID") usertagTag = self.doc.createElement("usertag") statusTag = self.doc.createElement("status") timeoutTag = self.doc.createElement("timeout") contentIDTag = self.doc.createElement("contentID") cmdIDTag = self.doc.createElement("cmdID") self.header.appendChild(verTag) self.header.appendChild(cmdnameTag) self.header.appendChild(msgtypeTag) self.header.appendChild(senderIDTag) self.header.appendChild(receiverIDTag) self.header.appendChild(resrcIDTag) self.header.appendChild(usertagTag) self.header.appendChild(statusTag) self.header.appendChild(timeoutTag) self.header.appendChild(contentIDTag) self.header.appendChild(cmdIDTag) ptext = self.doc.createTextNode("1.11.0000") verTag.appendChild(ptext) ptext = self.doc.createTextNode(self.m_cmdname) cmdnameTag.appendChild(ptext) ptext = self.doc.createTextNode(self.m_msgtype) msgtypeTag.appendChild(ptext) ptext = self.doc.createTextNode(self.m_senderID) senderIDTag.appendChild(ptext) ptext = self.doc.createTextNode(self.m_receiverID) receiverIDTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_resrcID)) resrcIDTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_usertag)) usertagTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_status)) statusTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_timeout)) timeoutTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_contentID)) contentIDTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_cmdID)) cmdIDTag.appendChild(ptext) def __del__(self): #print "Delete CmdSet Class" pass def setInt(self, Name, Value): paramTag = self.doc.createElement("param") self.params.appendChild(paramTag) nameTag = self.doc.createElement("name") paramTag.appendChild(nameTag) ptext = self.doc.createTextNode(str(Name)) nameTag.appendChild(ptext) typeTag = self.doc.createElement("type") paramTag.appendChild(typeTag) ptext = self.doc.createTextNode("int") typeTag.appendChild(ptext) valueTag = self.doc.createElement("value") paramTag.appendChild(valueTag) ptext = self.doc.createTextNode(str(Value)) valueTag.appendChild(ptext) self.parse(self.getCmdSet()) def setBool(self, Name, Value): paramTag = self.doc.createElement("param") self.params.appendChild(paramTag) nameTag = self.doc.createElement("name") paramTag.appendChild(nameTag) ptext = self.doc.createTextNode(str(Name)) nameTag.appendChild(ptext) typeTag = self.doc.createElement("type") paramTag.appendChild(typeTag) ptext = self.doc.createTextNode("bool") typeTag.appendChild(ptext) valueTag = self.doc.createElement("value") paramTag.appendChild(valueTag) ptext = self.doc.createTextNode(str(Value)) valueTag.appendChild(ptext) self.parse(self.getCmdSet()) def setString(self, Name, Value): paramTag = self.doc.createElement("param") self.params.appendChild(paramTag) nameTag = self.doc.createElement("name") paramTag.appendChild(nameTag) ptext = self.doc.createTextNode(str(Name)) nameTag.appendChild(ptext) typeTag = self.doc.createElement("type") paramTag.appendChild(typeTag) ptext = self.doc.createTextNode("string") typeTag.appendChild(ptext) valueTag = self.doc.createElement("value") paramTag.appendChild(valueTag) ptext = self.doc.createTextNode(str(Value)) valueTag.appendChild(ptext) self.parse(self.getCmdSet()) def setUInt(self, Name, Value): paramTag = self.doc.createElement("param") self.params.appendChild(paramTag) nameTag = self.doc.createElement("name") paramTag.appendChild(nameTag) ptext = self.doc.createTextNode(str(Name)) nameTag.appendChild(ptext) typeTag = self.doc.createElement("type") paramTag.appendChild(typeTag) ptext = self.doc.createTextNode("unsigned int") typeTag.appendChild(ptext) valueTag = self.doc.createElement("value") paramTag.appendChild(valueTag) ptext = self.doc.createTextNode(str(Value)) valueTag.appendChild(ptext) self.parse(self.getCmdSet()) def setFloat(self, Name, Value): paramTag = self.doc.createElement("param") self.params.appendChild(paramTag) nameTag = self.doc.createElement("name") paramTag.appendChild(nameTag) ptext = self.doc.createTextNode(str(Name)) nameTag.appendChild(ptext) typeTag = self.doc.createElement("type") paramTag.appendChild(typeTag) ptext = self.doc.createTextNode("float") typeTag.appendChild(ptext) valueTag = self.doc.createElement("value") paramTag.appendChild(valueTag) ptext = self.doc.createTextNode(str(Value)) valueTag.appendChild(ptext) self.parse(self.getCmdSet()) def printCmdSet(self): print self.doc.toprettyxml(indent=" ", encoding="euc-kr") def getCmdSet(self): return self.doc.toxml(encoding="euc-kr") #print self.doc.toprettyxml(indent=" ",encoding="euc-kr") #DataLength = len(self.doc.toxml(encoding="euc-kr")) #buffer = struct.pack('I I I %ds'%DataLength, DISCRIMINATOR, VERSION, DataLength,self.doc.toxml()) #return buffer def parse(self, data): from xml.dom.minidom import parseString global doc s = unicode(data, 'euc-kr').encode('utf-8') # euc-kr -> utf-8 s = s.replace("encoding=\"euc-kr\"", r"") doc = parseString(s) headerTag = doc.getElementsByTagName('header')[0] if headerTag.childNodes.length == 11: i = 0 while i < headerTag.childNodes.length: NodeName = headerTag.childNodes[i].nodeName if headerTag.childNodes[i].firstChild != None: NodeValue = headerTag.childNodes[i].firstChild.nodeValue else: NodeValue = 'None' if NodeName == "ver": ver = NodeValue elif NodeName == "cmdname": self.m_cmdname = NodeValue elif NodeName == "msgtype": self.m_msgtype = NodeValue elif NodeName == "senderID": self.m_senderID = NodeValue elif NodeName == "receiverID": self.m_receiverID = NodeValue elif NodeName == "usertag": self.m_usertag = (NodeValue) elif NodeName == "status": self.m_status = (NodeValue) elif NodeName == "timeout": self.m_timeout = (NodeValue) elif NodeName == "contentID": self.m_contentID = NodeValue elif NodeName == "cmdID": self.m_cmdID = (NodeValue) else: pass i += 1 bodyTag = doc.getElementsByTagName('body')[0] if bodyTag.childNodes.length > 0: paramList = bodyTag.getElementsByTagName('param') if paramList.length > 0: i = 0 while i < paramList.length: nameTag = paramList[i].getElementsByTagName('name') typeTag = paramList[i].getElementsByTagName('type') valueTag = paramList[i].getElementsByTagName('value') param = {} param['name'] = nameTag[0].firstChild.nodeValue param['type'] = typeTag[0].firstChild.nodeValue if valueTag[0].firstChild != None: if typeTag[0].firstChild.nodeValue == 'int': param['value'] = int( valueTag[0].firstChild.nodeValue) elif typeTag[0].firstChild.nodeValue == 'bool': param['value'] = bool( valueTag[0].firstChild.nodeValue) elif typeTag[0].firstChild.nodeValue == 'string': param['value'] = str( valueTag[0].firstChild.nodeValue.encode( 'utf-8')) elif typeTag[0].firstChild.nodeValue == 'float': param['value'] = float( valueTag[0].firstChild.nodeValue) elif typeTag[0].firstChild.nodeValue == 'unsigned int': param['value'] = int( valueTag[0].firstChild.nodeValue) else: param['value'] = valueTag[0].firstChild.nodeValue else: param['value'] = None if len(self.m_params) == 0: self.m_params.append(param) else: k = 0 appendFlag = False while k < (len(self.m_params)): if self.m_params[k]['name'] == param['name']: self.m_params[k]['type'] = param['type'] self.m_params[k]['value'] = param['value'] break k += 1 if k == len(self.m_params): self.m_params.append(param) i += 1 def setCmdName(self, value): self.m_cmdname = value pTag = self.doc.getElementsByTagName('cmdname')[0] pTag.firstChild.replaceWholeText(value) def setSenderID(self, value): self.m_senderID = value pTag = self.doc.getElementsByTagName('senderID')[0] pTag.firstChild.replaceWholeText(value) def setReceiverID(self, value): self.m_receiverID = value pTag = self.doc.getElementsByTagName('receiverID')[0] pTag.firstChild.replaceWholeText(value) def setMsgType(self, value): self.m_msgtype = value pTag = self.doc.getElementsByTagName('msgtype')[0] pTag.firstChild.replaceWholeText(value) def getValue(self, name): self.parse(self.getCmdSet()) Value = None for i in self.m_params: if i['name'] == name: Value = i['value'] return Value def getType(self, name): Type = None for i in self.m_params: if i['name'] == name: Type = i['type'] return Type def getArgList(self): ArgList = [] for i in self.m_params: ArgList.append(i['name']) return ArgList
class XMLcreator: # Tworzy nowy document xml def __init__(self, fopen=None): if(fopen): self.doc = parse(str(fopen)) self.proj_directory = os.path.dirname(os.path.realpath(str(fopen))) else: self.doc = Document() #Metoda sprawdzająca czy dany plik XML jest plikiem opisu projektu def isProjectFile(self): if self.doc.getElementsByTagName("FloorplanMaker"): return True else: return False def getDeviceDescriptor(self): fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0] project = fmaker.getElementsByTagName("Project")[0] des = project.getElementsByTagName("Description_file")[0] des_src = des.getAttribute("src") return '/'.join([self.proj_directory,des_src]) def getDeviceVersion(self): fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0] project = fmaker.getElementsByTagName("Project")[0] device = project.getElementsByTagName("Properties")[0] return device.getAttribute("model") def getEmulationMode(self): fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0] project = fmaker.getElementsByTagName("Project")[0] device = project.getElementsByTagName("Properties")[0] return device.getAttribute("mode") def getDesignFile(self): fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0] project = fmaker.getElementsByTagName("Project")[0] fl = project.getElementsByTagName("Design_file")[0] fl_src = fl.getAttribute("src") return '/'.join([self.proj_directory,fl_src]) def getProjectFile(self): fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0] project = fmaker.getElementsByTagName("Project")[0] fl = project.getElementsByTagName("Project_file")[0] fl_src = fl.getAttribute("scr") return fl_src def getProjectName(self): fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0] project = fmaker.getElementsByTagName("Project")[0] name = project.getAttribute("name") return name # Metoda tworząca pliku xml projektu def createNewProjectFile(self, project_name, project_file_dir, description_file_dir, device, mode): FloorplanMaker = self.doc.createElement("FloorplanMaker") FloorplanMaker.setAttribute("version","0.1") self.doc.appendChild(FloorplanMaker) # Tworzenie elementu project project = self.doc.createElement("Project") project.setAttribute("name", project_name) project.setAttribute("author", "Pawel") FloorplanMaker.appendChild(project) # Tworzenie elementu plik projektu fproject = self.doc.createElement("Project_file") fproject.setAttribute("src", project_name+'.xml') # Tworzenie elementu plik opisu płytki fdesign = self.doc.createElement("Description_file") fdesign.setAttribute("src", description_file_dir) # Tworzenie elementu device fproperties = self.doc.createElement("Properties") fproperties.setAttribute("model", device) fproperties.setAttribute("mode",mode) project.appendChild(fproject) project.appendChild(fdesign) project.appendChild(fproperties) # Zapisanie wygenerowanego opisu projektu do pliku # --DEBUGER_LINE-- # print self.doc.toprettyxml(indent=" ") plik = open(project_file_dir, "w+") self.doc.writexml(plik, indent="\n", addindent="\t") plik.close() def createSimulationSystemDescription(self, floorplan, oldNcd, newNcd, dir, device, mode): board = self.doc.createElement("board") board.setAttribute("version","0.1") board.setAttribute("device",device) board.setAttribute("mode",mode) self.doc.appendChild(board) input = self.doc.createElement("input") input.setAttribute("name",str(oldNcd)) board.appendChild(input) output = self.doc.createElement("output") output.setAttribute("name",str(newNcd)) board.appendChild(output) #Heaters list creating for h in floorplan.heaters: heater = self.doc.createElement("heater") heater.setAttribute("name", h[0]) heater.setAttribute("type", h[3]) heater.setAttribute("FMColor", str(h[2])) board.appendChild(heater) unit = floorplan.floorplan clbs = 0 for x in range(floorplan.cols): for y in range(floorplan.rows): if unit[y*floorplan.cols+x] == floorplan.indexOfHeater(h[0]): clb = self.doc.createElement("clb") clb.setAttribute("col",str(x)) clb.setAttribute("row",str(y)) heater.appendChild(clb) clbs = clbs + 1 print "heater {} : {} CLBS".format(h[0], clbs) #Thermometer list creating for key,t in floorplan.therms.iteritems(): thermometer = self.doc.createElement("thermometer") thermometer.setAttribute("name",key) thermometer.setAttribute("type",t["type"]) thermometer.setAttribute("col", str(t["x_pos"])) thermometer.setAttribute("row", str(t["y_pos"])) board.appendChild(thermometer) # # KSB: fix - genrilo.xml was placed in an incorrect place # concatenating paths requires os.path.join to be portable # plik = open(os.path.join(dir,"generilo.xml"),"w+") self.doc.writexml(plik, indent="\n", addindent="\t") plik.close() def addFloorplanFile(self): fmaker = self.doc.getElementsByTagName("FloorplanMaker")[0] project = fmaker.getElementsByTagName("Project")[0] name = project.getAttribute("name") fproject = project.getElementsByTagName("Project_file")[0] project_dir = fproject.getAttribute("src") project_dir = project_dir[:len(project_dir)-(len(name)+4)] # Tworzenie elementu plik projektu if(not(project.getElementsByTagName("Design_file"))): flproject = self.doc.createElement("Design_file") flproject.setAttribute("src", "generilo.xml") project.appendChild(flproject) plik = open(fproject.getAttribute("src"),"w+") self.doc.writexml(plik, indent="\n", addindent="\t") plik.close()
elem.setAttribute("ID", str(id)) # elem.setAttribute("Parent", str(parentId)) # visual test only elem.setAttribute("Name", name) # Check if not firstFound: if id == args.identity: # Add element which id is equal with args.identity (only once) root.appendChild(elem) firstFound = True else: if args.identity is None and parentId == 0: root.appendChild(elem) # direct child of root element # Finding parent of actual element by parentId elementList = doc.getElementsByTagName('Process') for parent in elementList: if parent.getAttribute('ID') == str(parentId): parent.appendChild(elem) break # Close connection with CIMOM conn.disconnect() # Write document, and after unlink it and close output XML file doc.writexml(output, addindent=" ", newl='\n') doc.unlink() output.close() except lmiwbem.lmiwbem_core.ConnectionError as connErr: print("(ERROR) You cannot connect to " + host)
from xml.dom.minidom import Document doc = Document() root = doc.createElement('root') doc.appendChild(root) main = doc.createElement('Text') main.setAttribute('id', "1") root.appendChild(main) text = doc.createTextNode('Some text here') main.appendChild(text) main2 = doc.createElement('Text') main2.setAttribute('id', "2") root.appendChild(main2) l = [e.getAttribute('id') for e in doc.getElementsByTagName('Text')] print l print doc.toprettyxml(indent='\t')
class XML_Parser: def __init__(self): self.charset = sys.getdefaultencoding() def init_vars(self): for d in self.dic: setattr(self, d, self.dic[d]) self.log.debug('XML Parser: Create variable self.%s needed...' % d) def build_xml(self): self.init_vars() self.doc = Document() self.root = self.doc.createElement('info') self.doc.appendChild(self.root) # create root attributes if hasattr(self, 'id'): self.root.setAttribute('id', self.id) # create child algo if hasattr(self, 'algorithm'): self.create_node_child('algorithm', self.root, self.algorithm) # create child generator if hasattr(self, 'generator'): self.create_node_child('generator', self.root, self.generator) # create childs files if hasattr(self, 'files'): self.build_array_for_node() self.xml = self.doc.toprettyxml(indent = ' ', encoding = self.charset) # pour créer le fichier def build_array_for_node(self): if 'shortpath' in self.files and self.files['shortpath']: array = self.files['shortpath'] elif 'base' in self.files and self.files['base']: array = self.files['base'] for k, v in array.items(): child = self.doc.createElement('file') self.root.appendChild(child) self.create_node_child('name', child, v) self.create_node_child('checksum', child, self.files['checksum'][k]) self.create_node_child('size', child, str(self.files['size'][k])) self.create_node_child('date', child, str(self.files['date'][k])) del(array) def create_node_child(self, element, parent, text): child = self.doc.createElement(element) parent.appendChild(child) txt = self.doc.createTextNode(text.strip()) child.appendChild(txt) # create child attribute if element == 'generator' and hasattr(self, 'version'): child.setAttribute('version', self.version.strip()) def get_dict_xml(self): if hasattr(self, 'xml'): return self.xml else: return False def read_xml(self, doc): # comment verifier si fichier XML ? if os.path.exists(doc) and os.path.isfile(doc) : self.doc = xml.dom.minidom.parse(doc) self.xml = dict() infos = ['algorithm', 'generator', 'id', 'version'] for info in infos: if info == 'id': self.xml[info] = self.doc.getElementsByTagName('info')[0].getAttribute(info).encode(self.charset) elif info == 'version': self.xml[info] = self.doc.getElementsByTagName('generator')[0].getAttribute(info).encode(self.charset) else: self.xml[info] = self.doc.getElementsByTagName(info)[0].firstChild.nodeValue.encode(self.charset) entries = ['checksum', 'date', 'name', 'size'] for entry in entries: self.xml[entry] = dict() x = 0 for node in self.doc.getElementsByTagName('file'): for entry in entries: if entry == 'size': value = int(node.getElementsByTagName(entry)[0].firstChild.nodeValue.encode(self.charset)) else: value = str(node.getElementsByTagName(entry)[0].firstChild.nodeValue.encode(self.charset)) self.xml[entry][x] = value x += 1 self.log.debug('XML File: %s' % self.xml) def save_xml(self, filename): try: f = open(filename, 'w') f.write(self.xml) f.close() except IOError as ioe: self.log.exception('Error to create document XML: %s' % ioe) return False def set_debug(self, entry): self.debug = bool(entry) def set_dict(self, entry): self.dic = dict(entry) def set_log(self, entry): self.log = entry
class delphinConstruction(object): def __init__(self, layers, str_destinationOfFile): self.__constructionLayers = layers self.__constructionFile = Document() #path definitions self.__scriptsPath = os.path.dirname(os.path.realpath(__file__)) self.__projectPath = os.path.dirname(os.path.normpath(self.__scriptsPath)) self.__projectFolder = os.path.join(self.__projectPath, "project") self.__resConPathAndName = os.path.join(self.__projectPath, "bin", "ResCon", "ResCon.jar") self.__createConstruction(str_destinationOfFile) def __createConstruction(self, str_destinationOfFile): #self.__constructionFile.toxml(encoding="UTF-8") self.__constructionFile.toprettyxml("\t", "\n\r", "UTF-8") construction = self.__constructionFile.createElement("DelphinProject") construction.setAttribute("xmlns", "http://www.bauklimatik-dresden.de") construction.setAttribute("xmlns:IBK", "http://www.bauklimatik-dresden.de/IBK") construction.setAttribute("fileVersion", "5.6.7") construction.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema") construction.setAttribute("xsi:schemaLocation", "http://www.bauklimatik-dresden.de DelphinProject.xsd") self.__constructionFile.appendChild(construction) projectInfo = self.__constructionFile.createElement("ProjectInfo") construction.appendChild(projectInfo) displayName = self.__constructionFile.createElement("DisplayName") projectInfo.appendChild(displayName) comment = self.__constructionFile.createElement("Comment") commentValue = self.__constructionFile.createTextNode("This template was made by ResCon") comment.appendChild(commentValue) projectInfo.appendChild(comment) materials = self.__constructionFile.createElement("Materials") construction.appendChild(materials) discretization = self.__constructionFile.createElement("Discretization") discretization.setAttribute("geometryType", "2D") construction.appendChild(discretization) xsteps = self.__constructionFile.createElement("XSteps") xsteps.setAttribute("unit", "m") discretization.appendChild(xsteps) assignments = self.__constructionFile.createElement("Assignments") construction.appendChild(assignments) materialList = Set() materialSourceDisplaynameDictionary = {} materialDisplaynameIdDictionary = {} for layer in self.__constructionLayers: if (layer.return_source() not in materialList): materialList.add(layer.return_source) #create material file str_destinationOfMaterialFile = str_destinationOfFile.replace("DB_Constructions","DB_Materials") self.__call_ResCon(layer.return_source(), str_destinationOfMaterialFile) materialFileName = self.__openCombinationsFile(layer.return_source()) str_fileName = "${Material Database}/"+materialFileName materialFileNameArray = materialFileName.split("_") str_displayName = materialFileNameArray[0] str_Id = materialFileNameArray[len(materialFileNameArray)-1] str_Id = str_Id.replace(".m6", "") materialSourceDisplaynameDictionary[layer.return_source] = str_displayName materialDisplaynameIdDictionary[str_displayName] = str_Id materialReferenceNode = self.__createMaterial(str_displayName, str_fileName) materials.appendChild(materialReferenceNode) xstepsValues = "" counter = 0 for layer in self.__constructionLayers: if (counter == 0 ): xstepsValues += layer.return_thickness() counter = 1 else: xstepsValues += " "+layer.return_thickness() xStepsValueNode = self.__constructionFile.createTextNode(xstepsValues) xsteps.appendChild(xStepsValueNode) layerOrder = 0 for layer in self.__constructionLayers: str_displayName = materialSourceDisplaynameDictionary[layer.return_source] str_id = materialDisplaynameIdDictionary[str_displayName] assignment = self.__createAssignment(str_displayName, str_id, layerOrder) assignments.appendChild(assignment) layerOrder += 1 def __createMaterial(self, str_displayName, str_fileName): materialReference = self.__constructionFile.createElement("MaterialReference") materialReference.setAttribute("displayName", str_displayName) materialReferenceContent = self.__constructionFile.createTextNode(str_fileName) materialReference.appendChild(materialReferenceContent) return materialReference def __createAssignment(self, str_displayName, str_id, str_order): assignment = self.__constructionFile.createElement("Assignment") assignment.setAttribute("location", "Element") assignment.setAttribute("type", "Material") reference = self.__constructionFile.createElement("Reference") reference.setAttribute("displayName", str_displayName) referenceID = self.__constructionFile.createTextNode(str_id) reference.appendChild(referenceID) assignment.appendChild(reference) rangeNode = self.__constructionFile.createElement("IBK:Range") rangeValue = self.__constructionFile.createTextNode(str(str_order)+" 0 "+str(str_order)+" 0") rangeNode.appendChild(rangeValue) assignment.appendChild(rangeNode) return assignment # purpose of this function: This function calls resource requesting java application ResCon # submitted variables: str_resource --> Predefined type definition of implemented resource types # defined are: # return values: True if ressource was created # False if not def __call_ResCon(self, str_sourceURI, str_destinationOfRoot): SF_keyWord = "ServiceFramework_Material" N_keyWord = "Nandrad_Material" targetDir = str_destinationOfRoot argList = [ "java", "-jar", self.__resConPathAndName, SF_keyWord, str_sourceURI, N_keyWord , targetDir ] # check: definition target directory? # call ResCon execution process try: executionProcess = subprocess.Popen(argList) # wait until process is terminated timeOut = 1.0 while executionProcess.poll() == None: time.sleep(timeOut) return True except Exception: print("SimulationMatrix: CallResCon: Undefined error while executing ResCon. Check list of arguments: ") print(argList) return False def __openCombinationsFile(self, str_source): materialName = "" try: combinations = os.path.join(os.getcwd(), "combinations.csv") fileObject = open(combinations, "r" ) except Exception as e: print("Error while parsing material file %s." % combinations) print e return False else: for line in fileObject.readlines(): pair = line.split(",") source = pair[0] destination = pair[1] #get value string and remove white spaces if( str_source == source ): pathOfNewMaterial = destination.split(os.sep) if (len(pathOfNewMaterial) > 1): materialName = pathOfNewMaterial[len(pathOfNewMaterial)-1] materialName = materialName.replace("\n","") else: pathOfNewMaterial = destination.split("\\") if (len(pathOfNewMaterial > 1)): materialName = pathOfNewMaterial[len(pathOfNewMaterial)-1] materialName = materialName.replace("\n","") else: pathOfNewMaterial = destination.split("/") materialName = pathOfNewMaterial[len(pathOfNewMaterial)-1] materialName = materialName.replace("\n","") return materialName def return_construction(self): return self.__constructionFile def add_displayName(self, str_displayName): displayName = self.__constructionFile.getElementsByTagName("DisplayName")[0] displayNameValue = self.__constructionFile.createTextNode(str_displayName) displayName.appendChild(displayNameValue)
class ValEventFilter(ValBaseFilter): """Child to implement filter Class specific to events""" def __init__(self, file_path, trid=None): """ Constructor for the inherited class specific to Events :param trid: Test Run ID :param file_path: Path XML filter setting file """ ValBaseFilter.__init__(self, file_path, trid) self._attribute_name_list = None def _GetAttributeValue(self, key, attribute_dict): # pylint: disable=R0201,C0103 """ Generic function to return value for the given key of dictionary :param key: Key of the dictionary :param attribute_dict: Dictionary :return: The corresponding value for the key in the dictionary """ if key in attribute_dict: return attribute_dict[key] else: return None def _GetEventFilterSqlExpression(self, ev_filter): # pylint: disable=C0103 """ Generic Function to build SQLBinaryExpression for the given Filter :param ev_filter: Minidom XML filter entry :return: SQLBinaryExpression representing filter for Database """ field_name = self._GetAttributeValue(FILTERDATA_FIELD, ev_filter) comp = self._GetAttributeValue(FILTERDATA_COMPARITOR, ev_filter) value = self.GetValue( self._GetAttributeValue(FILTERDATA_VALUE, ev_filter), self._GetAttributeValue(FILTERDATA_VTYPE, ev_filter)) if field_name in self._attribute_name_list: # if the field is Attribute name_cond = SQLBinaryExpr(COL_NAME_EVENTS_VIEW_NAME, OP_EQ, SQLLiteral(field_name)) val_cond = SQLBinaryExpr(COL_NAME_EVENTS_VIEW_VALUE, comp, value) return SQLBinaryExpr(name_cond, OP_AND, val_cond) elif field_name == FILTERDATA_ATTRIB_DURATION: # special case for event duration if it is not an attribute field_name = SQLBinaryExpr( SQLColumnExpr(SQLTableExpr(TABLE_NAME_EVENTS_ATTRIBUTES_VIEW), COL_NAME_EVENTS_VIEW_ENDABSTS), OP_SUB, SQLColumnExpr(SQLTableExpr(TABLE_NAME_EVENTS_ATTRIBUTES_VIEW), COL_NAME_EVENTS_VIEW_BEGINABSTS)) return SQLBinaryExpr(field_name, comp, value) def _SetAtttribute_list(self, dbi_val): # pylint: disable=C0103 """ Supporting function to initialize the list of attribute list registered in database :param dbi_val: Val Database interface object """ if dbi_val is not None: self._attribute_name_list = [] attribute_type_records = dbi_val.get_event_attribute_type() for attrib_rec in attribute_type_records: self._attribute_name_list.append( attrib_rec[COL_NAME_EVENT_ATTR_TYPES_NAME]) def Load(self, dbi_val, filtermap_name=None): # pylint: disable=C0103 """ Load filter data from Xml file :param dbi_val: Val Database interface reference :param filtermap_name: name of the filter map :return: if the no filtermap_name passed then only boolean status for decoding is return, if the filtermap_name is passed then statement is return, if the filtermap_name doesnt exist in config then NoneType is return """ self._SetAtttribute_list(dbi_val) load_status = self._DecodeEventFilters() if filtermap_name is None: return load_status else: statement = [] filter_mapdict = self.GetFilterMap(filtermap_name) if filter_mapdict is not None: for entry in filter_mapdict[FILTERMAPDATA_STATEMENT].split( " "): if entry.upper() not in FILTERMAPDATA_FILTER_JOINS: filter_dict = dict(self.GetFilter(entry)) filter_dict.pop(NAME) statement.append(filter_dict) else: statement.append(entry) return statement else: return None def Save(self, filtermap_name, statement, desc=" ", overwrite=False): # pylint: disable=C0103 """ Add/Update filter Entry if the filter is already existing then overwrite it :param filtermap_name: name of the filter map :type filtermap_name: string :param statement: filter data entries please refer to example at the end of dco String :type statement: list :param desc: description of filter :type desc: string :param overwrite: flag to overwrite the existing file :type overwrite: boolean :return: boolean True if the Save is successful example of statement passed from Assessment tool for saving:: statement = [{"field": "vehspeed", "comparitor": ">", "value": "22.22", "vtype": "float"}, "and", {"field": "assessment", "comparitor":"=", "value": "Invalid", "vtype": "str"}] """ filtermap_statement = "" if overwrite: self._dom = Document() event_filter = self._dom.createElement(ROOT_EVENT_FILTERING) event_filter.appendChild(self._dom.createElement(FILTERDATA)) event_filter.appendChild(self._dom.createElement(FILTERMAPDATA)) self._dom.appendChild(event_filter) self._dom.writexml(open(self._dom_file_path, 'wb'), " ", " ", "\n") self._dom.unlink() self._ReadXMLConfig() # Check if the filters already exist and delete it if self.GetFilterMap(filtermap_name) is not None: self.Delete(filtermap_name) for stat in statement: if type(stat) is dict: filter_dom = self._dom.createElement(FILTERDATA_FILTER) for key, value in stat.items(): filter_dom.setAttribute(key, value) filter_name = str(uuid4()) filter_dom.setAttribute(NAME, filter_name) self._dom.getElementsByTagName(FILTERDATA)[0].appendChild( filter_dom) filtermap_statement += filter_name elif stat.upper() in FILTERMAPDATA_FILTER_JOINS: filtermap_statement += " %s " % stat.upper() filtermap_dom = self._dom.createElement(FILTERMAPDATA_FILTERMAP) filtermap_dom.setAttribute(NAME, filtermap_name) filtermap_dom.setAttribute(FILTERMAPDATA_DESCRIPTION, desc) filtermap_dom.setAttribute(FILTERMAPDATA_STATEMENT, filtermap_statement) self._dom.getElementsByTagName(FILTERMAPDATA)[0].appendChild( filtermap_dom) self._dom.writexml(open(self._dom_file_path, 'wb'), " ", " ", "\n") return True def Delete(self, filtermap_name, save=False): # pylint: disable=C0103 """ Delete the filter of the specified name :param filtermap_name: Name of the Filter map :type filtermap_name: String :param save: flag to write changes into filter config XML file :type save: boolean :return: boolean True if the delete is successful """ if self.GetFilterMapDoms() is None: self._ReadXMLConfig() statement = self.GetFilterMap(filtermap_name)[FILTERMAPDATA_STATEMENT] for stat in statement.split(" "): if stat not in FILTERMAPDATA_FILTER_JOINS: filter_dom = self.GetFilterDoms(stat) self._dom.getElementsByTagName(FILTERDATA)[0].removeChild( filter_dom) filtermap_dom = self.GetFilterMapDoms(filtermap_name) self._dom.getElementsByTagName(FILTERMAPDATA)[0].removeChild( filtermap_dom) if save: self._dom.writexml(open(self._dom_file_path, 'wb'), " ", " ", "\n") self._ReadXMLConfig() return True def _DecodeEventFilters(self): # pylint: disable=C0103 """ Decode Filter XML filter setting file for EVENT and Prepare all the statements for Filtermaps """ self._ReadXMLConfig() filtermaps = self.GetFilterMaps() filters = self.GetFilters() for filtermap_key, filtermap_domdict in filtermaps.items(): # filtermap_dict = self._GetAttributeValue(filtermap) if FILTERMAPDATA_STATEMENT in filtermap_domdict: cond = None statement = filtermap_domdict[FILTERMAPDATA_STATEMENT].strip() relation = None for entry in statement.split(" "): if entry.upper() in FILTERMAPDATA_FILTER_JOINS: if cond is None: raise StandardError( "The filter configuration are invalid") else: relation = entry else: if cond is None: cond = self._GetEventFilterSqlExpression( filters[entry]) else: if relation is None: raise StandardError( "The filter configuration are invalid") else: cond = SQLBinaryExpr( cond, relation.upper(), self._GetEventFilterSqlExpression( filters[entry])) relation = None if self._trid is not None: if cond is not None: cond = SQLBinaryExpr( cond, OP_AND, SQLBinaryExpr(COL_NAME_EVENTS_VIEW_TRID, OP_EQ, self._trid)) else: cond = SQLBinaryExpr(COL_NAME_EVENTS_VIEW_TRID, OP_EQ, self._trid) self._cond[filtermap_key] = cond return True
def __add_metadata_to_document( self, music_data: minidom.Document, ) -> None: # Find MDB node mdb_nodes = music_data.getElementsByTagName('mdb') if len(mdb_nodes) != 1: raise Exception('Invalid XML file layout!') mdb = mdb_nodes[0] # Grab info infodict = self.__chart.metadata # Grab notes sections notedetails = self.__chart.notes # Parse out BPM bpms = self.__chart.bpms # Grab max and min BPM maxbpm = max([bpm for (_, bpm) in bpms]) minbpm = min([bpm for (_, bpm) in bpms]) def element(parent: Any, name: str, value: Optional[str]=None) -> Any: element = music_data.createElement(name) parent.appendChild(element) if value is not None: text = music_data.createTextNode(value) element.appendChild(text) return element # Create a single child with the right music ID music = element(mdb, 'music') music.setAttribute('id', str(self.__id)) # Create info section for metadata info = element(music, 'info') # Copypasta into info the various data we should have element(info, 'label', str(self.__id)) element(info, 'title_name', infodict.get('title', '')) element(info, 'title_yomigana', infodict.get('title_yomigana', '')) element(info, 'artist_name', infodict.get('artist', '')) element(info, 'artist_yomigana', infodict.get('artist_yomigana', '')) element(info, 'ascii', 'dummy') element(info, 'bpm_min', str(int(minbpm * 100))).setAttribute('__type', 'u32') element(info, 'bpm_max', str(int(maxbpm * 100))).setAttribute('__type', 'u32') element(info, 'distribution_date', datetime.date.strftime(datetime.datetime.now(), "%Y%m%d")).setAttribute('__type', 'u32') # type: ignore # TODO: Figure out what some of these should be element(info, 'volume', '75').setAttribute('__type', 'u16') element(info, 'bg_no', '0').setAttribute('__type', 'u16') element(info, 'genre', '16').setAttribute('__type', 'u8') element(info, 'is_fixed', '1').setAttribute('__type', 'u8') element(info, 'version', '1').setAttribute('__type', 'u8') element(info, 'demo_pri', '-2').setAttribute('__type', 's8') element(info, 'world', '0').setAttribute('__type', 'u8') element(info, 'tier', '-2').setAttribute('__type', 's8') element(info, 'license', infodict.get('license', '')) element(info, 'vmlink_phase', '0').setAttribute('__type', 's32') element(info, 'inf_ver', '0').setAttribute('__type', 'u8') # Create difficulties section difficulty = element(music, 'difficulty') for diffval in ['novice', 'advanced', 'exhaust', 'infinite']: root = element(difficulty, diffval) details = notedetails.get(diffval, {}) if diffval != 'infinite' else {} # type: Dict[str, Any] element(root, 'difnum', str(details.get('rating', '0'))).setAttribute('__type', 'u8') element(root, 'illustrator', infodict.get('credit')) element(root, 'effected_by', str(details.get('author'))) element(root, 'price', '-1').setAttribute('__type', 's32') element(root, 'limited', '1' if (diffval == 'infinite' or details.get('rating', '0') == '0') else '3').setAttribute('__type', 'u8')
class CCmdSet(): global DISCRIMINATOR,VERSION DISCRIMINATOR = 0x9530ed04 VERSION = 0x00020002 from xml.dom.minidom import Document #member var #header m_cmdname='' m_msgtype='' m_senderID='' m_receiverID='' m_resrcID = 0 m_usertag='' m_status= 0 m_timeout= 0 m_contentID='' m_cmdID=0 #body m_params = [] #doc,riml,header,body,params doc = Document() # Create the <riml> base element riml = doc.createElement("riml") doc.appendChild(riml) # Create the main <header>, <body> <params>element header = doc.createElement("header") riml.appendChild(header) body = doc.createElement("body") riml.appendChild(body) params = doc.createElement("params") body.appendChild(params) def __init__(self,cmdname = "",msgtype="",senderID="",receiverID="", resrcID = 0,usertag="",status = 0,timeout = 0, contentID='',cmdID =0): from xml.dom.minidom import Document # Create the <riml> base element self.doc = Document() self.riml = self.doc.createElement("riml") self.doc.appendChild(self.riml) # Create the main <header>, <body> <params>element self.header = self.doc.createElement("header") self.riml.appendChild(self.header) self.body = self.doc.createElement("body") self.riml.appendChild(self.body) self.params = self.doc.createElement("params") self.body.appendChild(self.params) self.m_cmdname = cmdname self.m_msgtype = msgtype self.m_senderID = senderID self.m_receiverID = receiverID self.m_resrcID = resrcID self.m_usertag = usertag self.m_status = status self.m_timeout = timeout self.m_contentID = contentID self.m_cmdID = cmdID # Create the main <header> element verTag = self.doc.createElement("ver") cmdnameTag = self.doc.createElement("cmdname") msgtypeTag = self.doc.createElement("msgtype") senderIDTag = self.doc.createElement("senderID") receiverIDTag = self.doc.createElement("receiverID") resrcIDTag = self.doc.createElement("resrcID") usertagTag = self.doc.createElement("usertag") statusTag = self.doc.createElement("status") timeoutTag = self.doc.createElement("timeout") contentIDTag = self.doc.createElement("contentID") cmdIDTag = self.doc.createElement("cmdID") self.header.appendChild(verTag) self.header.appendChild(cmdnameTag) self.header.appendChild(msgtypeTag) self.header.appendChild(senderIDTag) self.header.appendChild(receiverIDTag) self.header.appendChild(resrcIDTag) self.header.appendChild(usertagTag) self.header.appendChild(statusTag) self.header.appendChild(timeoutTag) self.header.appendChild(contentIDTag) self.header.appendChild(cmdIDTag) ptext = self.doc.createTextNode("1.11.0000") verTag.appendChild(ptext) ptext = self.doc.createTextNode(self.m_cmdname) cmdnameTag.appendChild(ptext) ptext = self.doc.createTextNode(self.m_msgtype) msgtypeTag.appendChild(ptext) ptext = self.doc.createTextNode(self.m_senderID) senderIDTag.appendChild(ptext) ptext = self.doc.createTextNode(self.m_receiverID) receiverIDTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_resrcID)) resrcIDTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_usertag)) usertagTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_status)) statusTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_timeout)) timeoutTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_contentID)) contentIDTag.appendChild(ptext) ptext = self.doc.createTextNode(str(self.m_cmdID)) cmdIDTag.appendChild(ptext) def __del__(self): #print "Delete CmdSet Class" pass def setInt(self,Name,Value): paramTag = self.doc.createElement("param") self.params.appendChild(paramTag) nameTag = self.doc.createElement("name") paramTag.appendChild(nameTag) ptext = self.doc.createTextNode(str(Name)) nameTag.appendChild(ptext) typeTag = self.doc.createElement("type") paramTag.appendChild(typeTag) ptext = self.doc.createTextNode("int") typeTag.appendChild(ptext) valueTag = self.doc.createElement("value") paramTag.appendChild(valueTag) ptext = self.doc.createTextNode(str(Value)) valueTag.appendChild(ptext) self.parse(self.getCmdSet()) def setBool(self,Name,Value): paramTag = self.doc.createElement("param") self.params.appendChild(paramTag) nameTag = self.doc.createElement("name") paramTag.appendChild(nameTag) ptext = self.doc.createTextNode(str(Name)) nameTag.appendChild(ptext) typeTag = self.doc.createElement("type") paramTag.appendChild(typeTag) ptext = self.doc.createTextNode("bool") typeTag.appendChild(ptext) valueTag = self.doc.createElement("value") paramTag.appendChild(valueTag) ptext = self.doc.createTextNode(str(Value)) valueTag.appendChild(ptext) self.parse(self.getCmdSet()) def setString(self,Name,Value): paramTag = self.doc.createElement("param") self.params.appendChild(paramTag) nameTag = self.doc.createElement("name") paramTag.appendChild(nameTag) ptext = self.doc.createTextNode(str(Name)) nameTag.appendChild(ptext) typeTag = self.doc.createElement("type") paramTag.appendChild(typeTag) ptext = self.doc.createTextNode("string") typeTag.appendChild(ptext) valueTag = self.doc.createElement("value") paramTag.appendChild(valueTag) ptext = self.doc.createTextNode(str(Value)) valueTag.appendChild(ptext) self.parse(self.getCmdSet()) def setUInt(self,Name,Value): paramTag = self.doc.createElement("param") self.params.appendChild(paramTag) nameTag = self.doc.createElement("name") paramTag.appendChild(nameTag) ptext = self.doc.createTextNode(str(Name)) nameTag.appendChild(ptext) typeTag = self.doc.createElement("type") paramTag.appendChild(typeTag) ptext = self.doc.createTextNode("unsigned int") typeTag.appendChild(ptext) valueTag = self.doc.createElement("value") paramTag.appendChild(valueTag) ptext = self.doc.createTextNode(str(Value)) valueTag.appendChild(ptext) self.parse(self.getCmdSet()) def setFloat(self,Name,Value): paramTag = self.doc.createElement("param") self.params.appendChild(paramTag) nameTag = self.doc.createElement("name") paramTag.appendChild(nameTag) ptext = self.doc.createTextNode(str(Name)) nameTag.appendChild(ptext) typeTag = self.doc.createElement("type") paramTag.appendChild(typeTag) ptext = self.doc.createTextNode("float") typeTag.appendChild(ptext) valueTag = self.doc.createElement("value") paramTag.appendChild(valueTag) ptext = self.doc.createTextNode(str(Value)) valueTag.appendChild(ptext) self.parse(self.getCmdSet()) def printCmdSet(self): print self.doc.toprettyxml(indent=" ",encoding="euc-kr") def getCmdSet(self): return self.doc.toxml(encoding="euc-kr") #print self.doc.toprettyxml(indent=" ",encoding="euc-kr") #DataLength = len(self.doc.toxml(encoding="euc-kr")) #buffer = struct.pack('I I I %ds'%DataLength, DISCRIMINATOR, VERSION, DataLength,self.doc.toxml()) #return buffer def parse(self,data): from xml.dom.minidom import parseString global doc s = unicode(data,'euc-kr').encode('utf-8') # euc-kr -> utf-8 s = s.replace("encoding=\"euc-kr\"", r"") doc = parseString(s) headerTag = doc.getElementsByTagName('header')[0] if headerTag.childNodes.length == 11: i=0 while i < headerTag.childNodes.length: NodeName = headerTag.childNodes[i].nodeName if headerTag.childNodes[i].firstChild != None: NodeValue = headerTag.childNodes[i].firstChild.nodeValue else: NodeValue = 'None' if NodeName == "ver": ver = NodeValue elif NodeName == "cmdname": self.m_cmdname = NodeValue elif NodeName == "msgtype": self.m_msgtype = NodeValue elif NodeName == "senderID": self.m_senderID = NodeValue elif NodeName == "receiverID": self.m_receiverID = NodeValue elif NodeName == "usertag": self.m_usertag = (NodeValue ) elif NodeName == "status": self.m_status = (NodeValue ) elif NodeName == "timeout": self.m_timeout = (NodeValue ) elif NodeName == "contentID": self.m_contentID = NodeValue elif NodeName == "cmdID": self.m_cmdID = (NodeValue ) else: pass i+=1 bodyTag = doc.getElementsByTagName('body')[0] if bodyTag.childNodes.length > 0: paramList = bodyTag.getElementsByTagName('param') if paramList.length > 0: i=0 while i < paramList.length: nameTag = paramList[i].getElementsByTagName('name') typeTag = paramList[i].getElementsByTagName('type') valueTag = paramList[i].getElementsByTagName('value') param = {} param['name'] = nameTag[0].firstChild.nodeValue param['type'] = typeTag[0].firstChild.nodeValue if valueTag[0].firstChild != None: if typeTag[0].firstChild.nodeValue == 'int': param['value'] = int(valueTag[0].firstChild.nodeValue) elif typeTag[0].firstChild.nodeValue == 'bool': param['value'] = bool(valueTag[0].firstChild.nodeValue) elif typeTag[0].firstChild.nodeValue == 'string': param['value'] = str(valueTag[0].firstChild.nodeValue.encode('utf-8')) elif typeTag[0].firstChild.nodeValue == 'float': param['value'] = float(valueTag[0].firstChild.nodeValue) elif typeTag[0].firstChild.nodeValue == 'unsigned int': param['value'] = int(valueTag[0].firstChild.nodeValue) else: param['value'] = valueTag[0].firstChild.nodeValue else: param['value'] = None if len(self.m_params) == 0: self.m_params.append(param) else: k = 0 appendFlag = False while k < (len(self.m_params)): if self.m_params[k]['name'] == param['name']: self.m_params[k]['type'] = param['type'] self.m_params[k]['value'] = param['value'] break; k+=1 if k == len(self.m_params): self.m_params.append(param) i+=1 def setCmdName(self,value): self.m_cmdname=value pTag = self.doc.getElementsByTagName('cmdname')[0] pTag.firstChild.replaceWholeText(value) def setSenderID(self,value): self.m_senderID=value pTag = self.doc.getElementsByTagName('senderID')[0] pTag.firstChild.replaceWholeText(value) def setReceiverID(self,value): self.m_receiverID=value pTag = self.doc.getElementsByTagName('receiverID')[0] pTag.firstChild.replaceWholeText(value) def setMsgType(self,value): self.m_msgtype=value pTag = self.doc.getElementsByTagName('msgtype')[0] pTag.firstChild.replaceWholeText(value) def getValue(self,name): self.parse(self.getCmdSet()) Value = None for i in self.m_params: if i['name'] == name: Value = i['value'] return Value def getType(self,name): Type = None for i in self.m_params: if i['name'] == name: Type = i['type'] return Type def getArgList(self): ArgList = [] for i in self.m_params: ArgList.append(i['name']) return ArgList
def generate_percentage_descriptors(input_xml_file, output_xml_file): number_of_shots = 1 if number_of_shots <= 0: return 0 # get the list of interaction and intervention speech_sequence = get_speech_sequence(input_xml_file, 2) write_interaction_intervention_list(input_xml_file, speech_sequence, 10) # classify the type of speakers classify_speakers(input_xml_file, 20, 20) if not os.path.exists(output_xml_file): dom_tree_out = create_descriptors_file(output_xml_file, number_of_shots) else: utility.remove_file(output_xml_file) dom_tree_out = create_descriptors_file(output_xml_file, number_of_shots) shot_number = 1 counter = 0 shot_descriptor_list = [] input_dom_tree = xml.dom.minidom.parse(input_xml_file) category_element = input_dom_tree.getElementsByTagName("Category") # print category_element category = category_element[0].firstChild.nodeValue duration_element = input_dom_tree.getElementsByTagName("Duration") # print duration_element video_duration = duration_element[0].firstChild.nodeValue shot_item = { "start": 0, "end": float(video_duration), "duration": float(video_duration) } start = shot_item["start"] end = shot_item["end"] duration = shot_item["duration"] shot_descriptors = dom_tree_out.createElement("Shot") shot_descriptors.setAttribute("start", str(start)) shot_descriptors.setAttribute("end", str(end)) shot_descriptors.setAttribute("duration", str(duration)) # print duration shot_descriptors.setAttribute("duration_percentage", str((duration * 100) / 11367)) shot_descriptors.setAttribute("shot_number", str(shot_number)) shot_descriptors.setAttribute("category", category) shot_number += 1 counter += 1 if end - start > 0: # region Interaction (get interaction percentage then add the values in the xml file) # print "get interaction percentage then add the values in the xml file:" # print 'start: {}'.format(datetime.datetime.now().time()) p_interaction = percentage_interaction(input_dom_tree, start, end) interaction_list = dom_tree_out.createElement("Interactions") inter2sp = dom_tree_out.createElement("Interaction") inter2sp.setAttribute("numberSpeakers", "2") inter2sp.appendChild( dom_tree_out.createTextNode( str(p_interaction["interaction2Speakers"]))) interaction_list.appendChild(inter2sp) inter3sp = dom_tree_out.createElement("Interaction") inter3sp.setAttribute("numberSpeakers", "3") inter3sp.appendChild( dom_tree_out.createTextNode( str(p_interaction["interaction3Speakers"]))) interaction_list.appendChild(inter3sp) inter4sp = dom_tree_out.createElement("Interaction") inter4sp.setAttribute("numberSpeakers", "4") inter4sp.appendChild( dom_tree_out.createTextNode( str(p_interaction["interaction4Speakers"]))) interaction_list.appendChild(inter4sp) inter5sp = dom_tree_out.createElement("Interaction") inter5sp.setAttribute("numberSpeakers", "4+") inter5sp.appendChild( dom_tree_out.createTextNode( str(p_interaction["interaction4+Speakers"]))) interaction_list.appendChild(inter5sp) shot_descriptors.appendChild(interaction_list) # print 'end: {}'.format(datetime.datetime.now().time()) # endregion # region Intervention (get intervention percentage and add them to the file) # print "get intervention percentage and add them to the file:" # print 'start: {}'.format(datetime.datetime.now().time()) p_intervention = percentage_intervention(input_dom_tree, start, end) intervention_list = dom_tree_out.createElement("Interventions") inter_short = dom_tree_out.createElement("Intervention") inter_short.setAttribute("type", "short") inter_short.appendChild( dom_tree_out.createTextNode(str(p_intervention["short"]))) inter_long = dom_tree_out.createElement("Intervention") inter_long.setAttribute("type", "long") inter_long.appendChild( dom_tree_out.createTextNode(str(p_intervention["long"]))) intervention_list.appendChild(inter_short) intervention_list.appendChild(inter_long) shot_descriptors.appendChild(intervention_list) # print 'end: {}'.format(datetime.datetime.now().time()) # endregion # region SpeakersTypeList (get speaker distribution and add the values to the xml) # print "get speaker distribution and add the values to the xml:" # print 'start: {}'.format(datetime.datetime.now().time()) p_speakers = percentage_speaker(input_dom_tree, start, end) speaker_type_list = dom_tree_out.createElement("SpeakersTypeList") sp_type = dom_tree_out.createElement("SpeakersType") punctual = dom_tree_out.createElement("Ponctuel") punctual.appendChild( dom_tree_out.createTextNode(str(p_speakers["ponctuel"]))) sp_type.appendChild(punctual) localise = dom_tree_out.createElement("Localise") localise.appendChild( dom_tree_out.createTextNode(str(p_speakers["localise"]))) sp_type.appendChild(localise) present = dom_tree_out.createElement("Present") present.appendChild( dom_tree_out.createTextNode(str(p_speakers["present"]))) sp_type.appendChild(present) regular = dom_tree_out.createElement("Regulier") regular.appendChild( dom_tree_out.createTextNode(str(p_speakers["regulier"]))) sp_type.appendChild(regular) important = dom_tree_out.createElement("Important") important.appendChild( dom_tree_out.createTextNode(str(p_speakers["important"]))) sp_type.appendChild(important) speaker_type_list.appendChild(sp_type) shot_descriptors.appendChild(speaker_type_list) # print 'end: {}'.format(datetime.datetime.now().time()) # endregion # region SpeakersDistribution (get speaker distribution over segments (how many speakers from the total # number is speaking during the segment) # print "get speaker distribution over segments (how many speakers from the total " \ # "number is speaking during the segment:" # print 'start: {}'.format(datetime.datetime.now().time()) d_speakers = get_speaker_distribution(input_dom_tree, start, end) d_speakers_list = dom_tree_out.createElement("SpeakersDistribution") d_speaker = dom_tree_out.createElement("SpeakerDistribution") d_speaker.appendChild(dom_tree_out.createTextNode(str(d_speakers))) d_speakers_list.appendChild(d_speaker) shot_descriptors.appendChild(d_speakers_list) # print 'end: {}'.format(datetime.datetime.now().time()) # endregion # region nbFacesList (get the list of nb of faces during segments) # print "get the list of nb of faces during segments " # print 'start: {}'.format(datetime.datetime.now().time()) nb_faces_result = get_number_of_faces_variation( input_dom_tree, start, end) nb_faces_list = dom_tree_out.createElement("nbFacesList") nb_faces = dom_tree_out.createElement("nbFaces") ls = list(nb_faces_result) mean = 0 sigma = 0 if len(ls) != 0: mean = np.mean(ls) sigma = np.std(ls) min_node = dom_tree_out.createElement("MeanNbFaces") min_node.appendChild(dom_tree_out.createTextNode(str(mean))) nb_faces.appendChild(min_node) max_node = dom_tree_out.createElement("StdNbFaces") max_node.appendChild(dom_tree_out.createTextNode(str(sigma))) nb_faces.appendChild(max_node) nb_faces_list.appendChild(nb_faces) shot_descriptors.appendChild(nb_faces_list) # print 'end: {}'.format(datetime.datetime.now().time()) # endregion # region IntensityVariation (get the list of intensity variations) # print "get the list of intensity variations " # print 'start: {}'.format(datetime.datetime.now().time()) list_intensity_variations_inter, \ list_intensity_variations_intra, \ nb_transitions = get_key_frames_inter_intra_segments_intensity_variation(input_dom_tree, start, end) intensity_var = dom_tree_out.createElement("IntensityVariation") shot_descriptors.appendChild(intensity_var) inter_intensity_variation_list = dom_tree_out.createElement( "InterIntensityVariationList") for intensity_variations_inter in list_intensity_variations_inter: i_variation = dom_tree_out.createElement("InterIntensityVariation") normalized_intensity_variations_inter = ( intensity_variations_inter * 100) / 255 txt_node = dom_tree_out.createTextNode( str(normalized_intensity_variations_inter)) i_variation.appendChild(txt_node) inter_intensity_variation_list.appendChild(i_variation) intensity_var.appendChild(inter_intensity_variation_list) intra_intensity_variation_list = dom_tree_out.createElement( "IntraIntensityVariationList") for intra_intensity_variation in list_intensity_variations_intra: i_variation = dom_tree_out.createElement("IntraIntensityVariation") normalized_intra_intensity_variation = (intra_intensity_variation * 100) / 255 txt_node = dom_tree_out.createTextNode( str(normalized_intra_intensity_variation)) i_variation.appendChild(txt_node) intra_intensity_variation_list.appendChild(i_variation) intensity_var.appendChild(intra_intensity_variation_list) nb_shot_transitions_list = dom_tree_out.createElement( "NumberShotTransitionList") nb_trans = dom_tree_out.createElement("NumberShotTransition") txt_node = dom_tree_out.createTextNode(str(nb_transitions * 100)) nb_trans.appendChild(txt_node) nb_shot_transitions_list.appendChild(nb_trans) shot_descriptors.appendChild(nb_shot_transitions_list) # print 'end: {}'.format(datetime.datetime.now().time()) # endregion # region Number Speaker Transition List # print "Number Speaker Transition List " # print 'start: {}'.format(datetime.datetime.now().time()) nb_speaker_transition = compute_number_speaker_switch_per_segment( input_dom_tree, start, end) nb_speaker_transition_list = dom_tree_out.createElement( "NumberSpeakerTransitionList") nb_trans = dom_tree_out.createElement("NumberSpeakerTransition") txt_node = dom_tree_out.createTextNode(str(nb_speaker_transition)) nb_trans.appendChild(txt_node) nb_speaker_transition_list.appendChild(nb_trans) shot_descriptors.appendChild(nb_speaker_transition_list) # print 'end: {}'.format(datetime.datetime.now().time()) # endregion # region Speech Music Alignment List # print "Speech Music Alignment List " # print 'start: {}'.format(datetime.datetime.now().time()) list_speech_music_combinations = get_speech_music_non_speech_non_music_percentage( input_dom_tree, start, end) s_m_ns_nm_list = dom_tree_out.createElement("SpeechMusicAlignmentList") alignment = dom_tree_out.createElement("SpeechMusicAlignment") s = dom_tree_out.createElement("Speech") s.appendChild( dom_tree_out.createTextNode( str(round(list_speech_music_combinations["P"], 2)))) alignment.appendChild(s) m = dom_tree_out.createElement("Music") m.appendChild( dom_tree_out.createTextNode( str(round(list_speech_music_combinations["M"], 2)))) alignment.appendChild(m) s_m = dom_tree_out.createElement("SpeechWithMusic") s_m.appendChild( dom_tree_out.createTextNode( str(round(list_speech_music_combinations["PM"], 2)))) alignment.appendChild(s_m) s_nm = dom_tree_out.createElement("SpeechWithNonMusic") s_nm.appendChild( dom_tree_out.createTextNode( str(round(list_speech_music_combinations["PNM"], 2)))) alignment.appendChild(s_nm) ns_m = dom_tree_out.createElement("NonSpeechWithMusic") ns_m.appendChild( dom_tree_out.createTextNode( str(round(list_speech_music_combinations["NPM"], 2)))) alignment.appendChild(ns_m) ns_nm = dom_tree_out.createElement("NonSpeechWithNonMusic") ns_nm.appendChild( dom_tree_out.createTextNode( str(round(list_speech_music_combinations["NPNM"], 2)))) alignment.appendChild(ns_nm) s_m_ns_nm_list.appendChild(alignment) shot_descriptors.appendChild(s_m_ns_nm_list) # print 'end: {}'.format(datetime.datetime.now().time()) # endregion # region get the list of words # print "get the list of words " # print 'start: {}'.format(datetime.datetime.now().time()) data = extract_text_data(input_dom_tree, start, end) shot_descriptors.appendChild(data) # print 'end: {}'.format(datetime.datetime.now().time()) # endregion shot_descriptor_list.append(shot_descriptors) # print "*************************************************************" if counter > 5: counter = 0 dom_tree_out = xml.dom.minidom.parse(output_xml_file) for sh in shot_descriptor_list: dom_tree_out.getElementsByTagName("Shots")[0].appendChild(sh) file_handle = codecs.open(output_xml_file, 'wb', 'utf8') dom_tree_out.writexml(file_handle) file_handle.close() shot_descriptor_list = [] dom_tree_out = Document() dom_tree_out = xml.dom.minidom.parse(output_xml_file) for sh in shot_descriptor_list: dom_tree_out.getElementsByTagName("Shots")[0].appendChild(sh) file_handle = codecs.open(output_xml_file, 'wb', 'utf8') dom_tree_out.writexml(file_handle) file_handle.close()
class CreateSLF(TagBase): def __init__(self, samples_amount, name, owner, nitrogen_use, dose_rate, external_dose_rate, protocol, reader_id, datecrea): self.xml = Document() self.slf = self.xml.createElement("SEQ") self.xml.appendChild(self.slf) self.name = self.xml.createElement("Name") self.status = self.xml.createElement("STATUS") self.datecrea = self.xml.createElement("Datecrea") self.datemod = self.xml.createElement("Datemod") self.owner = self.xml.createElement("Owner") self.samples_amount = self.xml.createElement("NMuestras") self.reader_id = self.xml.createElement("Reader_ID") self.nitrogen_use = self.xml.createElement("N2Flow") self.dose_rate = self.xml.createElement("Doserate") self.external_dose_rate = self.xml.createElement("ExtDoserate") self.protocol = self.xml.createElement("Protocol") self.seq = self.xml.createElement("seq") datemod = datetime.now() if (not datecrea) or datecrea is None: datecrea = datemod self.setTextNode(self.samples_amount, samples_amount) self.setTextNode(self.name, name) self.setTextNode(self.owner, owner) self.setTextNode(self.nitrogen_use, nitrogen_use) self.setTextNode(self.dose_rate, dose_rate) self.setTextNode(self.external_dose_rate, external_dose_rate) self.setTextNode(self.protocol, protocol) self.setTextNode(self.reader_id, reader_id) self.setTextNode(self.datecrea, datecrea) self.setTextNode(self.status, 'pend') self.setTextNode(self.datemod, datemod) self.slf.appendChild(self.name) self.slf.appendChild(self.status) self.slf.appendChild(self.datecrea) self.slf.appendChild(self.datemod) self.slf.appendChild(self.owner) self.slf.appendChild(self.samples_amount) self.slf.appendChild(self.reader_id) self.slf.appendChild(self.nitrogen_use) self.slf.appendChild(self.dose_rate) self.slf.appendChild(self.external_dose_rate) self.slf.appendChild(self.protocol) self.slf.appendChild(self.seq) def refreshDateMod(self): self.datemod.firstChild.data = str(datetime.now()) def createSample(self, id_): self.refreshDateMod() samples_ids = self.xml.getElementsByTagName("seq")[0].getElementsByTagName('Sample_ID') new_sample = Sample(id_).sample_id if len(samples_ids) > 0: for sample_id in samples_ids: value = sample_id.attributes['sample'].value if int(value) == int(id_): return sample_id if int(value) > int(id_): self.seq.insertBefore(new_sample, sample_id) return new_sample self.seq.appendChild(new_sample) return new_sample def createProcess(self, id_, parameters, data): self.refreshDateMod() process = Process(id_, parameters, data).process return process def createProcessOrder(self, sample_id, id_, type_, status, processes): self.refreshDateMod() process_order = ProcessOrder(id_, type_, status, processes).process_order sample_id.appendChild(process_order) return process_order def preview(self): return self.xml.toprettyxml(indent=" ") def save(self, path, rewrite=False): if os.path.exists(path): if os.path.isfile(path): ext = os.path.splitext(path)[-1] if ext not in ('.xml', '.slf',): raise ValueError('Incorrect format, must be a slf or xml file.') else: if rewrite: try: document = open(path, 'w') self.xml.writexml(document, addindent=' ', newl='\n', encoding='iso-8859-1') return True except: raise ValueError('Error while writing.') return False else: raise ValueError('Invalid file path.') else: dirname = os.path.dirname(path) if os.path.exists(dirname) or dirname == '': ext = os.path.splitext(path)[-1] if ext not in ('.xml', '.slf',): path += '.slf' document = open(path, 'w') self.xml.writexml(document, addindent=' ', newl='\n', encoding='iso-8859-1') return True else: raise ValueError('Directory "{0}" does not exist.'.format(dirname))
def SaveSettings(self, saveAccountDetails=None, savePassword=None, game=None): doc = None # Check if settings directory exists if not create if not os.path.exists(self.settingsDir): os.mkdir(self.settingsDir) if not self.osType.usingWindows: os.makedirs(self.settingsDir + "wine/prefix", exist_ok=True) # Check if settings file exists if not create new settings XML if os.path.exists(self.settingsFile): doc = defusedxml.minidom.parse(self.settingsFile) settingsNode = doc.getElementsByTagName("Settings") else: doc = Document() settingsNode = doc.createElementNS(EMPTY_NAMESPACE, "Settings") doc.appendChild(settingsNode) current_game = game if game else self.currentGame # Set default game to current game defaultGameNode = doc.getElementsByTagName("Default.Game") if len(defaultGameNode) > 0: defaultGameNode[0].firstChild.nodeValue = current_game else: defaultGameNode = doc.createElementNS(EMPTY_NAMESPACE, "Default.Game") defaultGameNode.appendChild(doc.createTextNode(current_game)) settingsNode.appendChild(defaultGameNode) # Remove old game block tempNode = doc.getElementsByTagName(current_game) if len(tempNode) > 0: doc.documentElement.removeChild(tempNode[0]) # Create new game block settingsNode = doc.getElementsByTagName("Settings")[0] gameConfigNode = doc.createElementNS(EMPTY_NAMESPACE, current_game) settingsNode.appendChild(gameConfigNode) # Some settings for test/preview clients are saved in normal client settings if current_game.endswith(".Test"): normalClientNode = self.getNormalClientNode(current_game, doc) if not normalClientNode: normalClientNode = doc.createElementNS(EMPTY_NAMESPACE, current_game) settingsNode.appendChild(normalClientNode) if not self.osType.usingWindows: tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Wine.Program") tempNode.appendChild(doc.createTextNode("%s" % (self.wineProg))) gameConfigNode.appendChild(tempNode) tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Wine.Debug") tempNode.appendChild(doc.createTextNode("%s" % (self.wineDebug))) gameConfigNode.appendChild(tempNode) if self.winePrefix != "": tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Wine.Prefix") tempNode.appendChild( doc.createTextNode("%s" % (self.winePrefix))) gameConfigNode.appendChild(tempNode) tempNode = doc.createElementNS(EMPTY_NAMESPACE, "HiRes") if self.hiResEnabled: tempNode.appendChild(doc.createTextNode("True")) else: tempNode.appendChild(doc.createTextNode("False")) gameConfigNode.appendChild(tempNode) tempNode = doc.createElementNS(EMPTY_NAMESPACE, "x64Client") if self.x64ClientEnabled: tempNode.appendChild(doc.createTextNode("True")) else: tempNode.appendChild(doc.createTextNode("False")) gameConfigNode.appendChild(tempNode) tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Game.Directory") tempNode.appendChild(doc.createTextNode("%s" % (self.gameDir))) gameConfigNode.appendChild(tempNode) tempNode = doc.createElementNS(EMPTY_NAMESPACE, "PatchClient") tempNode.appendChild(doc.createTextNode("%s" % (self.patchClient))) gameConfigNode.appendChild(tempNode) tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Language") tempNode.appendChild(doc.createTextNode("%s" % (self.language))) gameConfigNode.appendChild(tempNode) if saveAccountDetails: accountsNode = doc.createElementNS(EMPTY_NAMESPACE, "Accounts") # Adds all saved accounts with their account specific settings. for account in self.accountsDictionary: accountNode = doc.createElementNS(EMPTY_NAMESPACE, account) tempNode = doc.createElementNS(EMPTY_NAMESPACE, "World") tempNode.appendChild( doc.createTextNode("%s" % (self.accountsDictionary[account][0]))) accountNode.appendChild(tempNode) accountsNode.appendChild(accountNode) # Test/preview clients use normal client accounts. I.e they are # saved and loaded to and from the normal client node rather than the test node if current_game.endswith(".Test"): # Delete current accounts node if present. All accounts that were originally # there were loaded as if they were the test client's, so they are not lost. originalAccountsNode = normalClientNode.getElementsByTagName( "Accounts") if originalAccountsNode: normalClientNode.removeChild(originalAccountsNode[0]) normalClientNode.appendChild(accountsNode) else: gameConfigNode.appendChild(accountsNode) if savePassword: tempNode = doc.createElementNS(EMPTY_NAMESPACE, "Save.Password") tempNode.appendChild(doc.createTextNode("True")) gameConfigNode.appendChild(tempNode) startupScriptsNode = doc.createElementNS(EMPTY_NAMESPACE, "StartupScripts") for script in self.startupScripts: scriptNode = doc.createElementNS(EMPTY_NAMESPACE, "script") scriptNode.appendChild(doc.createTextNode("%s" % (script))) startupScriptsNode.appendChild(scriptNode) # Test/Preview clients store startup scripts in normal client settings, # because the add-ons folders are generally shared as well. if current_game.endswith(".Test"): # Delete current startup scripts node if present. All startup scripts # that were originally there were loaded as if they were the test client's, # so they are not lost. originalStartupScriptsNode = normalClientNode.getElementsByTagName( "StartupScripts") if originalStartupScriptsNode: normalClientNode.removeChild(originalStartupScriptsNode[0]) normalClientNode.appendChild(startupScriptsNode) else: gameConfigNode.appendChild(startupScriptsNode) # write new settings file with open(self.settingsFile, "w") as file: pretty_xml = prettify_xml(doc.toxml()) file.write(pretty_xml)
def get_path(dom: Document) -> str: """Get the path of the svg file.""" return dom.getElementsByTagName("path")[0].getAttribute("d")
progress_count = int(sys.argv[2]) log_msg = sys.argv[1] if os.path.exists(log_filename) == False: doc = Document() nodePS = doc.createElement("PROGRESS_STATUS") nodeP = doc.createElement("PROGRESS") txt = doc.createTextNode("0") nodeP.appendChild(txt) nodePS.appendChild(nodeP) doc.appendChild(nodePS) with open(log_filename, "w") as f: f.write(doc.toxml()) doc = xml.dom.minidom.parse(log_filename) progress = doc.getElementsByTagName("PROGRESS") txt = doc.createTextNode(str(int(progress[0].childNodes[0].data) + progress_count)) progress[0].replaceChild(txt, progress[0].childNodes[0]) txt = doc.createTextNode(log_msg) milestone = doc.createElement("MILESTONE") milestone.appendChild(txt) doc.childNodes[0].appendChild(milestone) with open(log_filename, "w") as f: f.write(doc.toxml())
class Xml: QUERYRESULT = "QueryResult" QUERY = "Query" RESPONSE = "Response" def __init__(self): self._doc = Document() self._rootNode = self._doc.createElement("Whois") self._doc.appendChild(self._rootNode) def save(self,name): with __builtin__.openany(name, "w") as file: loggerxml.debug("saving file %s" % name) file.write(self._doc.toxml()) # Adds a QueryResult node of a # specific name to root node. # A QueryResult node consists of # a Query Node and a Result Node. def addQueryResult(self, name, typeOf): loggerxml.debug("addQueryResult of name=%s" % (name)) # look for node with a specific name old = self.__lookForQueryResult(name) if (old == None): request = self._doc.createElement(Xml.QUERYRESULT) request.setAttribute("name", name) request.setAttribute("type",typeOf) self._rootNode.appendChild(request) else: return old return request # Searches a queryResult node due # to a given name. def __lookForQueryResult(self,name): old = self._doc.getElementsByTagName(Xml.QUERYRESULT) for node in old: if name == node.getAttribute("name"): return node return None def __lookForNodeByContent(self, parentNode, tag, content): nodes = parentNode.getElementsByTagName(tag) for node in nodes: if node.childNodes[0].nodeValue == content: return node return None # adds a QueryNode to root # it consists of major Query # properties and options def addQuery(self, parentNode, query=dict()): loggerxml.debug("addQuery %s" % str(query)) # check whether node only needs to # be extended if parentNode.hasChildNodes(): queryNode = parentNode.getElementsByTagName(Xml.QUERY)[0] else: queryNode = self._doc.createElement(Xml.QUERY) parentNode.appendChild(queryNode) # add child nodes queryNode = self.__addDictAsNodes(queryNode, query) return parentNode # Adds an ResultNode to the document. # The function gets a node to # add the host and a dictionary. def addResponse(self, parentNode, result=dict()): loggerxml.debug("addResponse %s" % str(result)) # look for existing 'response' nodes rnodes = parentNode.getElementsByTagName(Xml.RESPONSE) if len(rnodes) == 0: resultNode = self._doc.createElement(Xml.RESPONSE) parentNode.appendChild(resultNode) else: resultNode = rnodes[0] # add child nodes resultNode = self.__addDictAsNodes(resultNode, result) return parentNode # Adds a given dictionary to a node # given as parameter. This is relevant # for instance for Results and Host nodes. # It returns the modified node. def __addDictAsNodes(self, parentNode, dictionary=dict()): for key in dictionary: value = dictionary[key] # dictionary if type(value) == types.DictType: node = self.__lookForNodeByContent(parentNode, key, value) # if node already exists skip if (node != None): continue node = self._doc.createElement(key) parentNode.appendChild(node) self.__addDictAsNodes(node, value) # list if type(value) == types.ListType: for element in value: node = self.__lookForNodeByContent(parentNode, key, element) # if node already exists skip if (node != None): continue node = self.__createNode(key, element) parentNode.appendChild(node) # string elif type(value) == types.StringType: node = self.__lookForNodeByContent(parentNode, key, value) # if node already exists skip if (node != None): continue node = self.__createNode(key, value) parentNode.appendChild(node) return parentNode def __createNode(self, name, value): tmp = value try: value = value.decode("latin-1").encode("utf-8") except Exception as err: raise err loggerxml.warning("crashing error=%s" % value) value = tmp node = self._doc.createElement(cgi.escape(name)) text = self._doc.createTextNode(cgi.escape(value)) node.appendChild(text) return node
class CreateRLF(TagBase): def __init__(self, samples_amount, name, owner, nitrogen_use, dose_rate, external_dose_rate, protocol, status, reader_id, datecrea): self.xml = Document() self.rlf = self.xml.createElement("rlf") self.xml.appendChild(self.rlf) self.name = self.xml.createElement("name") self.status = self.xml.createElement("status") self.datecrea = self.xml.createElement("date_crea") self.datemod = self.xml.createElement("date_mod") self.owner = self.xml.createElement("owner") self.samples_amount = self.xml.createElement("samples_amount") self.reader_id = self.xml.createElement("reader_id") self.nitrogen_use = self.xml.createElement("N2_flow") self.dose_rate = self.xml.createElement("dose_rate") self.external_dose_rate = self.xml.createElement("external_dose_rate") self.protocol = self.xml.createElement("protocol") self.rep = self.xml.createElement("rep") datemod = datetime.now() if (not datecrea) or datecrea is None: datecrea = datemod self.setTextNode(self.samples_amount, samples_amount) self.setTextNode(self.name, name) self.setTextNode(self.owner, owner) self.setTextNode(self.nitrogen_use, nitrogen_use) self.setTextNode(self.dose_rate, dose_rate) self.setTextNode(self.external_dose_rate, external_dose_rate) self.setTextNode(self.protocol, protocol) self.setTextNode(self.reader_id, reader_id) self.setTextNode(self.datecrea, datecrea) self.setTextNode(self.status, status) self.setTextNode(self.datemod, datemod) self.rlf.appendChild(self.name) self.rlf.appendChild(self.status) self.rlf.appendChild(self.datecrea) self.rlf.appendChild(self.datemod) self.rlf.appendChild(self.owner) self.rlf.appendChild(self.samples_amount) self.rlf.appendChild(self.reader_id) self.rlf.appendChild(self.nitrogen_use) self.rlf.appendChild(self.dose_rate) self.rlf.appendChild(self.external_dose_rate) self.rlf.appendChild(self.protocol) self.rlf.appendChild(self.rep) def refreshDateMod(self): self.datemod.firstChild.data = str(datetime.now()) def createSample(self, id_): self.refreshDateMod() samples_ids = self.xml.getElementsByTagName("rep")[0].getElementsByTagName('sample_id') new_sample = Sample(id_).sample_id if len(samples_ids) > 0: for sample_id in samples_ids: value = sample_id.attributes['sample'].value if int(value) == int(id_): return sample_id if int(value) > int(id_): self.seq.insertBefore(new_sample, sample_id) return new_sample self.rep.appendChild(new_sample) return new_sample def createProcessOrder(self, sample_id, id_, ptype_, dtype_, curves, parameters): self.refreshDateMod() process_order = ProcessOrder(id_, ptype_, dtype_, curves, parameters).process_order sample_id.appendChild(process_order) return process_order def createCurve(self, number, signal_active, background_active, count_signal, low_signal, high_signal, count_background, low_background, high_background): self.refreshDateMod() curve = Curve(number, signal_active, background_active, count_signal, low_signal, high_signal, count_background, low_background, high_background).curve return curve def preview(self): return self.xml.toprettyxml(indent=" ") def save(self, path, rewrite=False): if os.path.exists(path): if os.path.isfile(path): ext = os.path.splitext(path)[-1] if ext not in ('.xml', '.rlf',): raise ValueError('Incorrect format, must be a rlf or xml file.') else: if rewrite: try: document = open(path, 'w') self.xml.writexml(document, addindent=' ', newl='\n', encoding='iso-8859-1') return True except: raise ValueError('Error while writing.') return False else: raise ValueError('Invalid file path.') else: dirname = os.path.dirname(path) if os.path.exists(dirname) or dirname == '': ext = os.path.splitext(path)[-1] if ext not in ('.xml', '.rlf',): path += '.rlf' document = open(path, 'w') self.xml.writexml(document, addindent=' ', newl='\n', encoding='iso-8859-1') return True else: raise ValueError('Directory "{0}" does not exist.'.format(dirname))