def validate_upcs(product_id, upcs, broken_gtins, broken_gtin_count): valid_upcs = [] for upc in upcs: if len(upc) in (6, 12): upc_digits = [int(x) for x in upc] for i in range(len(upc_digits[:-1])): if i % 2 == 0: upc_digits[i] = upc_digits[i] * 3 round_nearest_ten = int( roundup(float(sum(upc_digits[:-1])) / 10) * 10) if round_nearest_ten - sum(upc_digits[:-1]) == upc_digits[-1]: valid_upcs.append(upc) else: broken_gtins.writerow( [product_id, upc, 'UPC: Invalid Checkdigit']) broken_gtin_count += 1 elif len(upc) in range(7, 12): zeroes = '' add = 12 - len(upc) for i in range(add): zeroes += '0' upc = zeroes + upc try: upc_digits = [int(x) for x in upc] for i in range(len(upc_digits[:-1])): if i % 2 == 0: upc_digits[i] = upc_digits[i] * 3 round_nearest_ten = int( roundup(float(sum(upc_digits[:-1])) / 10) * 10) if round_nearest_ten - sum(upc_digits[:-1]) == upc_digits[-1]: valid_upcs.append(upc) else: upc = upc[len(zeroes):] broken_gtins.writerow( [product_id, upc, 'UPC: Invalid Length']) broken_gtin_count += 1 except ValueError: upc = upc[len(zeroes):] broken_gtins.writerow([product_id, upc, 'UPC: Invalid Length']) broken_gtin_count += 1 else: broken_gtins.writerow([product_id, upc, 'UPC: Invalid Length']) broken_gtin_count += 1 if len(valid_upcs) >= 1: x_upcs = objectify.SubElement(x_Product, "UPCs") # product_string_array.append(' ' + '<UPCs>' + '\n') for upc in valid_upcs: objectify.SubElement(x_upcs, "UPC") x_upcs.UPC = upc # product_string_array.append(' ' + '<UPC>' + upc + '</UPC>' + '\n') # product_string_array.append(' ' + '</UPCs>' + '\n') print(broken_gtin_count) return broken_gtin_count
def add_sub(conf, sub_category, sub_dic): '''A quick and dirty add-a-sub function''' if conf.xml.find('subscriptions') is None: objectify.SubElement(conf.xml, "subscriptions") new_sub = objectify.SubElement(conf.xml.subscriptions, "subscription") if sub_category: new_sub.set('category', sub_category) for key in sub_dic: setattr(new_sub, key, sub_dic[key]) write(conf)
def addAnnotation(ann, lbl, bbox): '''Adds a label 'lbl' with bounding box 'bbox' in the annotation xml ann ''' obj = objectify.SubElement(ann, 'object') obj.name = lbl obj.pose = 'Unspecified' obj.truncated = 0 obj.difficult = 0 bndbox = objectify.SubElement(obj, 'bndbox') bndbox.ymin, bndbox.xmin, bndbox.ymax, bndbox.xmax = bbox
def validate_eans(product_id, eans, broken_gtins): valid_eans = [] for ean in eans: if len(ean) in (8, 13): # if ean length is 8 or 13, validate ean_digits = [int(x) for x in ean] for i in range(len(ean_digits[:-1])): if len(ean) == 8: # xxx - what is going on here? if i % 2 == 0: ean_digits[i] = ean_digits[i] * 3 else: if i % 2 != 0: ean_digits[i] = ean_digits[i] * 3 round_nearest_ten = int( roundup(float(sum(ean_digits[:-1])) / 10) * 10) if round_nearest_ten - sum(ean_digits[:-1]) == ean_digits[-1]: valid_eans.append(ean) else: broken_gtins.writerow( [product_id, ean, 'EAN: Invalid Checkdigit']) # if ean length between 9 - 13, add leading zeros elif len(ean) in range(9, 13): zeroes = '' add = 13 - len(ean) for i in range(add): zeroes += '0' ean = zeroes + ean try: ean_digits = [int(x) for x in ean] for i in range(len(ean_digits[:-1])): if i % 2 != 0: ean_digits[i] = ean_digits[i] * 3 round_nearest_ten = int( roundup(float(sum(ean_digits[:-1])) / 10) * 10) if round_nearest_ten - sum(ean_digits[:-1]) == ean_digits[-1]: valid_eans.append(ean) else: ean = ean[len(zeroes):] broken_gtins.writerow( [product_id, ean, 'EAN: Invalid Length']) except ValueError: print(ean, 'too many zeroes?') ean = ean[len(zeroes):] broken_gtins.writerow([product_id, ean, 'EAN: Invalid Length']) else: broken_gtins.writerow([product_id, ean, 'EAN: Invalid Length']) if len(valid_eans) >= 1: x_eans = objectify.SubElement(x_Product, 'EANs') # product_string_array.append(' ' + '<EANs>' + '\n') for index, ean in enumerate(valid_eans): x_ean = objectify.SubElement(x_eans, 'EAN') x_ean[index] = ean
def __init__(self): # Set up namespaces nsmaps = {'xsi': "http://www.w3.org/2001/XMLSchema-instance"} ns = objectify.ElementMaker(annotate=False, namespace=None, nsmap=None) nsxsi = objectify.ElementMaker(annotate=False, namespace=nsmaps['xsi'], nsmap=nsmaps) self.root = ns.asdf() self.root.attrib['version'] = '0.1' self.header = objectify.SubElement(self.root, "header") self.scene_setup = objectify.SubElement(self.root, "scene_setup")
def insert(self, e, i=None, attrib=None, nsmap=None, **kwargs): u'''Insert a new child node. insert a new child node at the specified position. Arguments --------- e : str the new tag to be inserted. i : int, optional if i is integer : position of the new tag. else append to the end. attrib,nsmap,kwargs : optional attribs for the new tag. see also objectify.Element() or SubElement(). ''' v = objectify.SubElement(self._____o____, e, attrib=attrib, nsmap=nsmap, **kwargs) s = ObjectifiedElementProxy(v) if i is not None: self._____o____.insert(i, v) return s
def make_FormatHTML(resultados, search_engine, search): """ Funcion que devuelve el reporte en un archivo HTML si la bandera --format se encuentra activada. resultados: Lista de resultados obtenidos de la busqueda. search_engine: El buscador que se utilizo para la busqueda. search: La busqueda realizada """ if path.exists('Busquedas.html'): tree = objectify.parse('Busquedas.html') root = tree.getroot() body_doc = root.find('body') h2 = objectify.SubElement(body_doc, 'h2') h2._setText('Busqueda: "' + search + '"') div = etree.SubElement(body_doc, 'div') h3 = objectify.SubElement(div, 'h3') h3._setText('' + search_engine) for res in resultados: result = objectify.SubElement(div, 'a', href=res) result._setText(res.decode('utf-8')) br = etree.SubElement(div, 'br') with open('Busquedas.html', 'w') as archivo: tree.write(archivo) else: root = etree.Element('html') doc = etree.ElementTree(root) head_doc = etree.SubElement(root, 'head') title = etree.SubElement(head_doc, 'title') title.text = "Reporte de Busquedas" body_doc = etree.SubElement(root, 'body') h1 = etree.SubElement(body_doc, 'h1') h1.text = 'Reporte de Busquedas' h2 = etree.SubElement(body_doc, 'h2') h2.text = 'Busqueda: "' + search + '"' div = etree.SubElement(body_doc, 'h2') h3 = etree.SubElement(div, 'h3') h3.text = '' + search_engine for res in resultados: result = etree.SubElement(div, 'a', href=res) result.text = res.decode('utf-8') br = etree.SubElement(div, 'br') with open('Busquedas.html', 'w') as archivo: doc.write(archivo)
def test_nested_subelements_same_tags(): root = objectify.Element("root") # <root></root> b = objectify.SubElement(root, "b") # <root><b></b></root> a = objectify.SubElement(b, "a") # <root><b><a></a></b></root> a = objectify.SubElement(b, "a") # <root><b><a></a><a></a></b></root> objectify.SubElement(a, "c") # <root><b><a></a><a><c></c></a></b></root> objectify.SubElement( a, "c") # <root><b><a></a><a><c></c><c></c></a></b></root> assert lxml_to_dict(root) == { 'root': { 'b': { 'a': None, 'a1': { 'c': None, 'c1': None } } } }
def get_aligned_frames_xml(tokenized, frame_instances, root): # read DRG tuples = get_drg(tokenized) drgparser = drg.DRGParser() d = drgparser.parse_tup_lines(tuples) for instance_id, frame_instance in frame_instances.iteritems(): if len(frame_instance['roles']) > 0: if frame_instance['frame'] != "Unmapped": framebase_id = "{0}-{1}".format(frame_instance['frame'], mapping_net[frame_instance['synset']].split("#")[0].replace('-', '.')) else: log.info('No mapping found for synset {0}'.format(frame_instance['synset'])) continue tag_frameinstance = objectify.SubElement(root, "frameinstance") tag_frameinstance.attrib['id']=instance_id tag_frameinstance.attrib['type']=framebase_id tag_frameinstance.attrib['internalvariable']=frame_instance['variable'] for reificated_frame_var in d.reificated[frame_instance['variable']]: tag_framelexicalization = objectify.SubElement(tag_frameinstance, "framelexicalization") surface = [] unboxer.generate_from_referent(d, reificated_frame_var, surface, complete=False) tag_framelexicalization[0] = ' '.join(surface) tag_instancelexicalization = objectify.SubElement(tag_frameinstance, "instancelexicalization") surface = [] unboxer.generate_from_referent(d, reificated_frame_var, surface, complete=True) tag_instancelexicalization[0] = ' '.join(surface) tag_frameelements = objectify.SubElement(tag_frameinstance, "frameelements") for role, (variable, filler) in frame_instance['roles'].iteritems(): tag_frameelement = objectify.SubElement(tag_frameelements, "frameelement") tag_frameelement.attrib['role'] = role tag_frameelement.attrib['internalvariable'] = variable tag_concept = objectify.SubElement(tag_frameelement, "concept") tag_concept[0] = filler try: for reificated_role_var in d.reificated[variable]: # composed lexicalization surface = unboxer.generate_from_relation(d, reificated_frame_var, reificated_role_var) if surface != None: tag_rolelexicalization = objectify.SubElement(tag_frameelement, "rolelexicalization") tag_rolelexicalization[0] = surface # complete surface forms surface = [] unboxer.generate_from_referent(d, reificated_role_var, surface, complete=True) tag_conceptlexicalization = objectify.SubElement(tag_frameelement, "conceptlexicalization") tag_conceptlexicalization[0] = ' '.join(surface) except: log.error("error with DRG reification: {0}".format(variable)) objectify.deannotate(root, xsi_nil=True) etree.cleanup_namespaces(root) return etree.tostring(root, pretty_print=True)
def get_ldap_config(name, **kwargs): result, config_data = get_config(**kwargs) config = objectify.fromstring(config_data.encode('ascii')) # Find existing LDAP settings with specified key ... ldap_config = None for ldap_setting_iter in config.security.ldapSettings.getchildren(): if ldap_setting_iter.key.text == name: ldap_config = ldap_setting_iter break # ... and create new one if not exists if ldap_config is None: ldap_config = objectify.SubElement(config.security.ldapSettings, 'ldapSetting') objectify.SubElement(ldap_config, 'key')._setText(name) return result, etree.tostring(ldap_config)
def addElement(self, father, other_words): attrib = {'type': 'inflected'} form_ = objectify.Element(self.get_tag_with_ns('form'), nsmap=self.fullnamespase, attrib=attrib) form_.nsmap.pop('py') for idx, word in enumerate(other_words): orth_ = objectify.SubElement(form_, 'orth', nsmap=self.fullnamespase) orth_[idx] = word father.append(form_)
def SubElement(parent, nsptag_str, **extra): """ Return an lxml element having *nsptag_str*, newly added as a direct child of *parent*. The new element is appended to the sequence of children, so this method is not suitable if the child element must be inserted at a different position in the sequence. The class of the returned element is the custom element class for its tag, if one is defined. Additional named parameters defined on lxml ``makeelement()`` are accepted, such as attrib=attr_dct and e.g. ``visible='1'``. """ nsptag = NamespacePrefixedTag(nsptag_str) return objectify.SubElement(parent, nsptag.clark_name, nsmap=nsptag.nsmap, **extra)
def addToResultXMLStructured(self, xml, parentTagName, tagName, newTagType, subTagType="", subTagName=""): ''' add extra tags to the structured xml xml: xml in objectified format parentTagName: parent tag name tagName: tag name to be replaced newTagType: tag type to be addeed subTagType: sub tag type to be addeed subTagName: sub tag name to be addeed ''' for grp in xml.GRP: if grp.attrib["ID"] == parentTagName: for fld in grp.FLD: if fld.attrib["NAME"] == tagName: grp.remove(fld) newTag = objectify.SubElement(grp, newTagType, NAME=tagName) if len(subTagType) > 0: if len(subTagName) > 0: subTag = objectify.SubElement(newTag, subTagType, NAME=subTagName) else: subTag = objectify.SubElement( newTag, subTagType) return xml
def __getattr__(self, name): if name == '_____o____': return object.__getattribute__(name) if hasattr(self._____o____, name): e = getattr(self._____o____, name) if name in ('tag', 'pyval', 'text', 'attrib') or isinstance( e, (types.FunctionType, types.BuiltinFunctionType)): return e else: #if has no attr named name, created a new one. e = objectify.SubElement(self._____o____, name) return ObjectifiedElementProxy(e)
def __getitem__(self, name): if isinstance(name, int): return ObjectifiedElementProxy(self._____o____[name]) if isinstance(name, slice): return [ObjectifiedElementProxy(o) for o in self._____o____[name]] if isinstance(name, str): if name == '_____o____': return object.__getattribute__(name) o = self._____o____ try: e = o.__getitem__(name) except: e = objectify.SubElement(self._____o____, name) return ObjectifiedElementProxy(e) raise Exception
def importxml(): form = ImportXMLForm() if form.validate_on_submit(): fc = form.importXML.data #fileName = secure_filename(fc.filename) #xml schema check to be added and append to the curent xmlRoot fc.save(".\generated\DeviceList-temp.xml") fc.close() xmlschema_doc = etree.parse(".\static\device_schema.xsd") xmlschema = etree.XMLSchema(xmlschema_doc) try: importDoc = etree.parse(".\generated\DeviceList-temp.xml") except Exception: return render_template('ImportError.html') result = xmlschema.validate(importDoc) if (result!=True): return render_template('ImportError.html') importXmlRoot=importDoc.getroot() doc = etree.parse(".\generated\DeviceList-a.xml") xmlRoot = doc.getroot() for child in importXmlRoot: value = objectify.SubElement(child, "value") value.text = str(random.uniform(0,100)) xmlRoot.append(child) objectify.deannotate(xmlRoot) etree.cleanup_namespaces(xmlRoot) xmlfp = open('.\generated\DeviceList-a.xml', 'w') xmlstr = etree.tostring(xmlRoot, pretty_print=True, xml_declaration=True) xmlstr=xmlstr.decode("utf-8") xmlfp.write(xmlstr) xmlfp.close() return redirect(url_for('index')) return render_template('MAWSImport.html', form=form)
def mml2steps(mml): ''' Takes mml and converts it into a list of separate MML documents containing the mml code for each individual step. Converts rows in mtable into a list of basic mml expressions. ''' if not isinstance(mml, str): raise Exception('mml must be a string containing the math ML XML') step_trees = mml2steptrees(mml) steps = [] for step_tree in step_trees: math = objectify.Element('math') mstyle = objectify.SubElement(math, 'mstyle') mstyle.extend(step_tree.getchildren()) # take the newly build complete mathml object, clean it, string it objectify.deannotate(math, cleanup_namespaces=True) steps.append(etree.tostring(math).decode('UTF-8')) return steps
def test_many_subelements_same_tag(): root = objectify.Element("root") # <root></root> objectify.SubElement(root, "b") # <root><b></b></root> objectify.SubElement(root, "b") # <root><b></b><b></b></root> objectify.SubElement(root, "b") objectify.SubElement(root, "b") objectify.SubElement(root, "b") objectify.SubElement(root, "b") objectify.SubElement(root, "b") assert lxml_to_dict(root) == { 'root': { 'b': None, 'b1': None, 'b2': None, 'b3': None, 'b4': None, 'b5': None, 'b6': None } }
# If you just want a single text-value element (with no siblings of the same name), you can take a syntactic shortcut and simply assign to it: # # *(Under the hood this assigns a new child ``StringElement`` to that tag - if there are pre-existing elements with that same tag, it is assigned to the first position in the list)* # In[ ]: v.What.shortcut = 'some text assigned in a quick-and-dirty fashion' print(vp.prettystr(v.What)) # In general, though, you probably want to use [SubElement](http://lxml.de/objectify.html#the-lxml-objectify-api), # as this allows you to create multiple sibling-child elements of the same name, etc. # In[ ]: for i in range(5): objectify.SubElement(v.What, 'foo') v.What.foo[-1] = "foo{}".format(i) print("I have {} foos for you:".format(len(v.What.foo))) print(vp.prettystr(v.What)) # In[ ]: # Get rid of all the foo: del v.What.foo[:] # Alternatively, you can create elements independently, then append them to a parent (remember how lxml.objectify pretends elements are lists?) - this is occasionally useful if you want to write a function that returns an element, e.g. to create a new [Param](http://voevent-parse.readthedocs.org/en/master/reference.html#voeventparse.misc.Param) (but voevent-parse wraps that up for you already): # In[ ]: temp = objectify.Element('NonSchemaCompliantParam', attrib={'somekey': 'somevalue'})
def create_grb_voevent(grb_dic, conf_vo, what_com, atable): """ Create VO event with observation plan for a given telescope in the network :param gw_dic: dictionary with GRB infos :param conf_vo: dictionary to be used to fill header of VO event :param what_com: dictionary with common infos needed for VO creation :param atable: astropy table with observation plan and meta data :return: voevent object """ # get telescope name and role, will be used several time tel_name = what_com['tel_name'] obs_mode = what_com['obs_mode'] voevent = basic_grb_voevent(grb_dic, conf_vo, what_com) #GBM ground or final position if grb_dic["Packet_Type"] == 112 or grb_dic["Packet_Type"] == 115: pixloc = vp.Param(name="Loc_url", value=str(grb_dic["skymap"]["localization_name"]), ucd="meta.ref.url", dataType="string") pixloc.Description = "URL to retrieve location of the healpix skymap" voevent.What.append(pixloc) if tel_name != "": name_tel = vp.Param(name="Name_tel", value=str(tel_name), ucd="instr", dataType="string") name_tel.Description = "Name of the telescope used for the observation strategy" voevent.What.append(name_tel) if atable and atable[0]: # now prepare observation plan or galaxies list fields = objectify.Element("Table", name="Obs_plan") fields.Description = "Tiles for the observation plan" # first field is the identificaiton of the field # it will be different between tiling and galaxy targetting if obs_mode == "Tiling": field_id = objectify.SubElement(fields, "Field", name="Field_id", ucd="", unit="", dataType="string") field_id.Description = "ID of the field of FOV" tel_obsplan = np.transpose( np.array([ atable['rank_id'], atable['RA'], atable['DEC'], atable['Prob'] ])) else: field_id = objectify.SubElement(fields, "Field", name="Gal_id", ucd="", unit="", dataType="string") field_id.Description = "ID of the galaxy" # For galaxie we will uniformize how we name them based on catalogs gal_id = utils_too.uniformize_galnames(atable) tel_obsplan = np.transpose( np.array([ gal_id, atable['RAJ2000'], atable['DEJ2000'], atable['S'] ])) # right_asc = objectify.SubElement(fields, "Field", name="RA", ucd="pos.eq.ra ", unit="deg", dataType="float") right_asc = objectify.SubElement(fields, "Field", name="RA", ucd="pos.eq.ra ", unit="deg", dataType="float") right_asc.Description = "The right ascension at center of fov in equatorial coordinates" dec = objectify.SubElement(fields, "Field", name="Dec", ucd="pos.eq.ra ", unit="deg", dataType="float") dec.Description = "The declination at center of fov in equatorial coordinates" os_grade = objectify.SubElement(fields, "Field", name="Os_score", ucd="meta.number", unit="None", dataType="float") os_grade.Description = "Gives the importance of the tile/galaxy to observe" data = objectify.SubElement(fields, "Data") # loop on the observation plan # put a limit to 500 fields otherwise get an error when sending a VO event for i in np.arange(min(500, len(tel_obsplan))): table_row = objectify.SubElement(data, "TR") for j in np.arange(len(tel_obsplan[i])): # objectify.SubElement(TR, "TD",value=str(Tel_dic["OS"][i][j])) objectify.SubElement(table_row, 'TD') table_row.TD[-1] = str(tel_obsplan[i][j]) voevent.What.append(fields) grb_dic["dateobs"] = grb_dic["dateobs"].replace(tzinfo=pytz.utc) vp.add_where_when(voevent, coords=vp.Position2D( ra=grb_dic["ra"], dec=grb_dic["dec"], err=grb_dic["error"], units='deg', system=vp.definitions.sky_coord_system.utc_fk5_geo), obs_time=grb_dic["dateobs"], observatory_location=grb_dic["inst"]) # Check everything is schema compliant: vp.assert_valid_as_v2_0(voevent) return voevent
def update_final_report(config, criteria, stations, station, time, status = None, comment = None, results = None, score = None, correction = None): """ Ažurira finalni izveštaj sa pojedinačnim elementom ocene zadatka Mehanizam rada je takav da će menjati samo jedan <assignment> nod u XML fajlu i to onaj koji se tiče zadatka kojem se prijavljuju izmene u rezultatu. Ostatak sadržaja neće biti učitavan i menjan. config - globalna konfiguracija alata za pregled criteria - kriterijum pregleda zadatka (bodovanje, način izvršavanja itd.) stations - kolekcija računara i studenata koji su radili zadatak (ključ - oznaka računara, podatak - lista - broj indeksa i ime/prezime studenta) station - oznaka računara na kojem je zadatak urađen time - timestamp poslednje izmene na rezultatima status - status celog zadatka comment - komentar pregledača na zadatak results - lista tuple objekata TestResults - rezultat izvršenja testova score - procentualni učinak studenta na zadatku correction - korekcija koju je pregledač uveo """ print 'Azuriranje XML fajla sa izvestajem sa ispita: "{0}"'.format(config.FINAL_REPORT_FILENAME) try: criteria.total_points # Provera da li je definisana varijabla except NameError: criteria.total_points = 100 total_points_f = float(criteria.total_points) if not (results is None): total = 0.0 for r in results: if r.success: total += r.score # Ako fajl ne postoji, kreiraj korenski element: if not(path.isfile(config.FINAL_REPORT_FILENAME)): root = objectify.Element('assignments') else: with open(config.FINAL_REPORT_FILENAME) as f: xml = f.read() root = objectify.fromstring(xml) # Probaj pronaci <assignment> tag koji se odnosi na zadatu stanicu: assign = None for a in root.getchildren(): if a.get('station') == station: assign = a # Ako prethodno ne postoji takav <assignment>, kreiraj novi: if assign == None: assign = objectify.SubElement(root, 'assignment') # Podesi nove podatke: assign.set('station', station) assign['id'] = stations[station][0] assign['name'] = stations[station][1] # Podesi nove podatke: assign.time = time if not (results is None): assign['test-score'] = '{:.2f}'.format(total) if not (comment is None): assign['comment'] = comment if not (score is None): assign['direct-score'] = '{:.2f}'.format(score) assign['final-pct'] = '{:.2f}'.format(score) if not (correction is None): # Ako je zadata korekcija 0 - onda se korekcija ukida: if correction == 0: sub = assign.find('correction') if (sub is not None): assign.remove(sub) else: assign['correction'] = '{:+.2f}'.format(correction) final_number = 0 reason = u'nema uspešnih testova' if assign.find('test-score') is not None: final_number = float(assign['test-score']) reason = u'{:+.2f}% na uspešne testove'.format(final_number) if correction != 0: final_number = final_number + correction reason = reason + u' i {:+.2f}% korekcija'.format(correction) final = '{:.2f}'.format(final_number) points = int(round(final_number * (total_points_f / 100.0), 0)) assign['final-pct'] = final assign['final-points'] = points assign['reason'] = reason if not (results is None): # Ako je bilo direktno zadatog rezultata, nakon što su izvršeni automatski testovi, taj skor se briše: sub = assign.find('direct-score') if (sub is not None): assign.remove(sub) while True: sub = assign.find('tests') if (sub is None): break; assign.remove(sub) tests_root = objectify.SubElement(assign, 'tests') for r in results: test = objectify.SubElement(tests_root, 'test') test.attrib['name'] = r.name test['runs'] = r.runs test['passes'] = r.passes test['failures'] = r.failures test['test-fails'] = r.test_fails test['crashes'] = r.crashes test['time-outs'] = r.time_outs test['total-duration'] = '{:.2f}'.format(r.total_duration) test['max-duration'] = '{:.2f}'.format(r.max_duration) test['success'] = r.success test['score'] = '{:.2f}'.format(r.score) test['factor'] = r.factor executions = objectify.SubElement(test, 'executions') for e in r.executions: elem = objectify.SubElement(executions, 'passed') elem._setText(str(e).lower()) # Logika za odredjivanje broja poena, u odnosu na status rada i ostale parametre: if not (status is None): assign['status'] = status if status == ASSIGNMENT_STATUS_BLOCKED: final = '0' points = 0 reason = u'makar jedan od blokirajućih testova ne prolazi' elif status == ASSIGNMENT_STATUS_FAILS_TO_COMPILE: final = '0' points = 0 reason = u'projekat se ne kompajlira uspešno' elif status == ASSIGNMENT_STATUS_DIRECTLY_RATED: final = assign['direct-score'] final_number = float(assign['direct-score']) points = int(round(final_number * (total_points_f / 100.0), 0)) reason = u'direktno zadata ocena' elif status == ASSIGNMENT_STATUS_OK: final_number = float(assign['test-score']) reason = u'{0}% na uspešne testove'.format(final_number) sub = assign.find('correction') if (sub is not None): corr = float(assign['correction']) final_number = final_number + corr reason = reason + u' i {:+.2f}% korekcija'.format(corr) final = '{:.2f}'.format(final_number) points = int(round(final_number * (total_points_f / 100.0), 0)) elif status == ASSIGNMENT_STATUS_SKIPPED: final_number = 0 points = 0 final = '{:.2f}'.format(final_number) reason = u'rad je preskočen' else: util.fatal_error('''Interna greska: status "{0}" nema definisana pravila za bodovanje! Kontaktirati autora programa.'''.format(status)) assign['final-pct'] = final assign['final-points'] = points assign['reason'] = reason # Upiši izmenjen fajl: f = open(config.FINAL_REPORT_FILENAME, 'w') objectify.deannotate(root) # Skidanje objectify anotacija # Dodaje se XML zaglavlje u kojem se navodi UTF-8 kao upotrebljeno enkodiranje i referencira se XSLT dokument: f.write('<?xml version="1.0" encoding="UTF-8"?>\n<?xml-stylesheet type="text/xsl" href="{0}"?>\n' .format(config.FINAL_REPORT_XSLT_FILENAME)) f.write(etree.tostring(root, xml_declaration=False, encoding='utf-8', pretty_print=True)) f.close()
# product_string_array.append(' ' + '<UPC>' + upc + '</UPC>' + '\n') # product_string_array.append(' ' + '</UPCs>' + '\n') print(broken_gtin_count) return broken_gtin_count """ ** VALIDATE AND CLEAN FUNCTIONS END ** """ """ ** START READING ROWS ** """ broken_gtin_count = 0 urls = [] row_number = 0 x_Products = objectify.SubElement(xfeed, 'Products') for row in range(1, sheet.nrows): if sheet.cell(row, product_id_index).value != '': x_Product = objectify.SubElement(x_Products, 'Product') if type(sheet.cell(row, product_id_index).value) == str: product_id = sheet.cell(row, product_id_index).value if type(sheet.cell(row, product_id_index).value) == float: product_id = str(int(sheet.cell(row, product_id_index).value)) else: pass objectify.SubElement(x_Product, 'ExternalId') product_id = id_clean(product_id) x_Product.ExternalId = product_id if product_name_index is not None:
hr_file = open('/Users/gum/Desktop/to/hr.xml', 'r') hr_tree = objectify.parse(hr_file) hr_root = hr_tree.getroot() hr_arr = {} for lap in hr_root.Activities.Activity.Lap: for track in lap.Track: for point in track.Trackpoint: time = point.Time.pyval.rpartition('.')[0] + 'Z' hr_arr[time] = point.HeartRateBpm.Value gps_file = open('/Users/gum/Desktop/to/gps.gpx', 'r') #gps = gpxpy.parse(gps_file) gps_tree = objectify.parse(gps_file) gps_root = gps_tree.getroot() for trk in gps_root.trk: for trkseg in trk.trkseg: for trkpt in trkseg.trkpt: if '{0}'.format(trkpt.time) in hr_arr: hr = hr_arr['{0}'.format(trkpt.time)] # else: # hr = 100 ext1 = objectify.SubElement(trkpt, 'extensions') ext2 = objectify.SubElement(ext1, 'TrackPointExtension') ext3 = etree.Element("thisdoesntmatter") ext3.tag = "thisdoesntmattereither" ext3.text = str(hr) ext2.hr = ext3 print etree.tostring(gps_tree, pretty_print=True)
def set_ldap_config(name, uri, base=None, enabled=True, dn_pattern=None, manager_dn=None, manager_pass=None, search_subtree=True, search_filter='(&(objectClass=inetOrgPerson)(uid={0}))', attr_mail='mail', create_users=True, safe_search=True, **kwargs): result, config_data = get_config(**kwargs) config = objectify.fromstring(config_data.encode('ascii')) # NOTE! Elements must ber sorted in exact order! key_map = OrderedDict([ ('enabled', 'enabled'), ('ldapUrl', 'uri'), ('userDnPattern', 'dn_pattern'), ('search', ''), ('autoCreateUser', 'create_users'), ('emailAttribute', 'attr_mail'), ('ldapPoisoningProtection', 'safe_search'), ]) key_map_search = OrderedDict([ ('searchFilter', 'search_filter'), ('searchBase', 'base'), ('searchSubTree', 'search_subtree'), ('managerDn', 'manager_dn'), ('managerPassword', 'manager_pass'), ]) # Find existing LDAP settings with specified key ... ldap_config = None for ldap_setting_iter in config.security.ldapSettings.getchildren(): if ldap_setting_iter.key.text == name: ldap_config = ldap_setting_iter search_config = ldap_config.search break # ... and create new one if not exists if ldap_config is None: ldap_config = objectify.SubElement(config.security.ldapSettings, 'ldapSetting') objectify.SubElement(ldap_config, 'key')._setText(name) # LDAP options for xml_key, var_name in key_map.iteritems(): # Search subtree must follow element order if xml_key == 'search' and not hasattr(ldap_config, 'search'): search_config = objectify.SubElement(ldap_config, 'search') break if var_name in locals(): # Replace None with empty strings var_value = locals()[var_name] or '' if isinstance(var_value, bool): # Boolean values should be lowercased xml_text = str(var_value).lower() else: xml_text = str(var_value) if hasattr(ldap_config, xml_key): ldap_config[xml_key]._setText(xml_text) else: objectify.SubElement(ldap_config, xml_key)._setText(xml_text) # Search options (same code as above but using search_config) for xml_key, var_name in key_map_search.iteritems(): if var_name in locals(): # Replace None with empty strings var_value = locals()[var_name] or '' if isinstance(var_value, bool): # Boolean values should be lowercased xml_text = str(var_value).lower() else: xml_text = str(var_value) if hasattr(search_config, xml_key): search_config[xml_key]._setText(xml_text) else: objectify.SubElement(search_config, xml_key)._setText(xml_text) change_data = etree.tostring(config) return set_config(change_data, **kwargs)
def getResultXMLStructured(self, save=False, saveline=False, table="", lineCount=1, lineStart=1): ''' get web service xml structure for save, save line, and run from x3 objectified save: get structured xml for save saveline: get structured xml for line save table: specific table for line save lineCount: number of lines within a table to be created lineStart: start at line number for adding ''' param = "" description = self.getResultXML(objectified=True) for grp in description.ADXDATA.GRP: if "TYB" in grp.attrib: if grp.attrib["TYB"] == "Table": if save: if grp.attrib["NAM"] == table: tab = objectify.SubElement(description.ADXDATA, "TAB", ID=grp.attrib["NAM"]) lin = objectify.SubElement(tab, "LIN") for fld in grp.FLD: objectify.SubElement(lin, "FLD", NAME=fld.attrib["NAM"]) if saveline and grp.attrib["NAM"] == table: param = objectify.Element("PARAM") tab = objectify.SubElement(param, "TAB", ID=grp.attrib["NAM"]) for i in range(lineStart - 1, lineCount): lin = objectify.SubElement(tab, "LIN", NUM=str(i + 1)) for fld in grp.FLD: objectify.SubElement(lin, "FLD", NAME=fld.attrib["NAM"]) if "DIM" in grp.attrib: if int(grp.attrib["DIM"]) > 1: description.ADXDATA.remove(grp) else: grp.set("ID", grp.attrib["NAM"]) for fld in grp.FLD: fld.set("NAME", fld.attrib["NAM"]) else: grp.set("ID", grp.attrib["NAM"]) for fld in grp.FLD: fld.set("NAME", fld.attrib["NAM"]) if not saveline: param = description.ADXDATA objectify.deannotate(param, pytype=True, cleanup_namespaces=True) return param
import xlrd from datetime import datetime from re import sub from lxml import etree from lxml import objectify start = datetime.now() time = start.strftime('%Y-%m-%dT%H:%M:%S.%f') client_instance = 'bc-try' Feed = objectify.Element('Feed') xProducts = objectify.Element('Products') xProduct = objectify.Element('Product') objectify.SubElement(xProduct, 'Name') xProduct.Name = 'BCHANG' """ # initial object for E-factory tree generation p = objectify.E f = objectify.E ps = objectify.E Product = p.Product( p.name("Indian Motorcycle Balance Bike"), p.description('Indian Motorcycle riders of the future can get started riding their favorite brand with this Balance Bike'), p.imageUrl("military-dev.polarisindcms.com/globalassets/pga/apparel/youth/2863878.jpg/SmallThumbnail"), p.ProductPageUrl("store.indianmotorcycle.com/en-us/shop/apparel/gifts/juniors/2863878") )
def test_two_subelements_same_tag(): root = objectify.Element("root") # <root></root> objectify.SubElement(root, "b") # <root><b></b></root> objectify.SubElement(root, "b") # <root><b></b><b></b></root> assert lxml_to_dict(root) == {'root': {'b': None, 'b1': None}}
def test_one_subelement(): root = objectify.Element("root") # <root></root> objectify.SubElement(root, "b") # <root><b></b></root> assert lxml_to_dict(root) == {'root': {'b': None}}
def script_wizard(self, script='new', output_directory='./'): """ The script_wizard is designed to build a Dragon script file. The name and the functionality of this function is the same as available Script wizard in the Dragon Graphic User Interface. Note: All reported nodes are mandatory, except the <EXTERNAL> tag Note: Script for version 7 doesn't support fingerprints block Parameters ---------- script: string, optional (default="new") If "new" start with a new script. If you want to load an existing script, pass the filename with drs format. output_directory: string, optional (default = './') the path to the working directory to store output files. dragon: xml element Dragon script in xml format. drs: string Dragon script file name data_path: string The path+name of saved data file in any format. If saveType is 'block' or 'subblock' data_path is just the path to the directory that all data files have been saved. Returns ------- class parameters """ from lxml import objectify, etree if output_directory[-1] == '/': self.output_directory = output_directory else: self.output_directory = output_directory + '/' if not os.path.exists(self.output_directory): os.makedirs(self.output_directory) if script == 'new': if self.version == 6: self.dragon = objectify.Element( "DRAGON", version="%i.0.0" % self.version, script_version="1", generation_date=std_datetime_str('date').replace('-', '/')) OPTIONS = objectify.SubElement(self.dragon, "OPTIONS") OPTIONS.append( objectify.Element("CheckUpdates", value=bool_formatter(self.CheckUpdates))) OPTIONS.append( objectify.Element("SaveLayout", value=bool_formatter(self.SaveLayout))) OPTIONS.append( objectify.Element("ShowWorksheet", value=bool_formatter( self.ShowWorksheet))) OPTIONS.append( objectify.Element("Decimal_Separator", value=self.Decimal_Separator)) OPTIONS.append( objectify.Element("Missing_String", value=self.Missing_String)) OPTIONS.append( objectify.Element("DefaultMolFormat", value=self.DefaultMolFormat)) OPTIONS.append( objectify.Element("HelpBrowser", value=self.HelpBrowser)) OPTIONS.append( objectify.Element("RejectUnusualValence", value=bool_formatter( self.RejectUnusualValence))) OPTIONS.append( objectify.Element("Add2DHydrogens", value=bool_formatter( self.Add2DHydrogens))) OPTIONS.append( objectify.Element("MaxSRforAllCircuit", value=self.MaxSRforAllCircuit)) OPTIONS.append(objectify.Element("MaxSR", value=self.MaxSR)) OPTIONS.append( objectify.Element("MaxSRDetour", value=self.MaxSRDetour)) OPTIONS.append( objectify.Element("MaxAtomWalkPath", value=self.MaxAtomWalkPath)) OPTIONS.append( objectify.Element("LogPathWalk", value=bool_formatter(self.LogPathWalk))) OPTIONS.append( objectify.Element("LogEdge", value=bool_formatter(self.LogEdge))) Weights = objectify.SubElement(OPTIONS, "Weights") for weight in self.Weights: if weight not in [ "Mass", "VdWVolume", "Electronegativity", "Polarizability", "Ionization", "I-State" ]: msg = "'%s' is not a valid weight type." % weight raise ValueError(msg) Weights.append(objectify.Element('weight', name=weight)) OPTIONS.append( objectify.Element("SaveOnlyData", value=bool_formatter(self.SaveOnlyData))) OPTIONS.append( objectify.Element("SaveLabelsOnSeparateFile", value=bool_formatter( self.SaveLabelsOnSeparateFile))) OPTIONS.append( objectify.Element("SaveFormatBlock", value=self.SaveFormatBlock)) OPTIONS.append( objectify.Element("SaveFormatSubBlock", value=self.SaveFormatSubBlock)) OPTIONS.append( objectify.Element("SaveExcludeMisVal", value=bool_formatter( self.SaveExcludeMisVal))) OPTIONS.append( objectify.Element("SaveExcludeAllMisVal", value=bool_formatter( self.SaveExcludeAllMisVal))) OPTIONS.append( objectify.Element("SaveExcludeConst", value=bool_formatter( self.SaveExcludeConst))) OPTIONS.append( objectify.Element("SaveExcludeNearConst", value=bool_formatter( self.SaveExcludeNearConst))) OPTIONS.append( objectify.Element("SaveExcludeStdDev", value=bool_formatter( self.SaveExcludeStdDev))) OPTIONS.append( objectify.Element("SaveStdDevThreshold", value=self.SaveStdDevThreshold)) OPTIONS.append( objectify.Element("SaveExcludeCorrelated", value=bool_formatter( self.SaveExcludeCorrelated))) OPTIONS.append( objectify.Element("SaveCorrThreshold", value=self.SaveCorrThreshold)) OPTIONS.append( objectify.Element( "SaveExclusionOptionsToVariables", value=bool_formatter( self.SaveExclusionOptionsToVariables))) OPTIONS.append( objectify.Element("SaveExcludeMisMolecules", value=bool_formatter( self.SaveExcludeMisMolecules))) OPTIONS.append( objectify.Element("SaveExcludeRejectedMolecules", value=bool_formatter( self.SaveExcludeRejectedMolecules))) DESCRIPTORS = objectify.SubElement(self.dragon, "DESCRIPTORS") for i in self.blocks: if i < 1 or i > 29: msg = "block id must be in range 1 to 29." raise ValueError(msg) DESCRIPTORS.append( objectify.Element('block', id="%i" % i, SelectAll="true")) MOLFILES = objectify.SubElement(self.dragon, "MOLFILES") MOLFILES.append( objectify.Element("molInput", value=self.molInput)) if self.molInput == "stdin": if self.molInputFormat not in [ 'SYBYL', 'MDL', 'HYPERCHEM', 'SMILES', 'MACROMODEL' ]: msg = "'%s' is not a valid molInputFormat. Formats:['SYBYL','MDL','HYPERCHEM','SMILES','MACROMODEL']" % self.molInputFormat raise ValueError(msg) MOLFILES.append( objectify.Element("molInputFormat", value=self.molInputFormat)) elif self.molInput == "file": if isinstance(self.molFile, dict): for f in range(1, len(self.molFile) + 1): MOLFILES.append( objectify.Element( "molFile", value=self.molFile[f]['file'])) elif isinstance(self.molFile, str): MOLFILES.append( objectify.Element("molFile", value=self.molFile)) else: msg = 'Variable molInput can be either a string or a list' raise ValueError(msg) else: msg = "Enter a valid molInput: 'stdin' or 'file'" raise ValueError(msg) OUTPUT = objectify.SubElement(self.dragon, "OUTPUT") OUTPUT.append( objectify.Element("SaveStdOut", value=bool_formatter(self.SaveStdOut))) OUTPUT.append( objectify.Element("SaveProject", value=bool_formatter(self.SaveProject))) if self.SaveProject: OUTPUT.append( objectify.Element("SaveProjectFile", value=self.SaveProjectFile)) OUTPUT.append( objectify.Element("SaveFile", value=bool_formatter(self.SaveFile))) if self.SaveFile: OUTPUT.append( objectify.Element("SaveType", value=self.SaveType) ) # value = "[singlefile/block/subblock]" OUTPUT.append( objectify.Element("SaveFilePath", value=self.output_directory + self.SaveFilePath) ) #Specifies the file name for saving results as a plan text file(s), if the "singlefile" option is set; if "block" or "subblock" are set, specifies the path in which results files will be saved. OUTPUT.append(objectify.Element( "logMode", value=self.logMode)) # value = [none/stderr/file] if self.logMode == "file": OUTPUT.append( objectify.Element("logFile", value=self.output_directory + self.logFile)) if self.external: EXTERNAL = objectify.SubElement(self.dragon, "EXTERNAL") EXTERNAL.append( objectify.Element("fileName", value=self.fileName)) EXTERNAL.append( objectify.Element("delimiter", value=self.delimiter)) EXTERNAL.append( objectify.Element("consecutiveDelimiter", value=bool_formatter( self.consecutiveDelimiter))) EXTERNAL.append( objectify.Element("MissingValue", value=self.MissingValue)) self._save_script() elif self.version == 7: self.dragon = objectify.Element( "DRAGON", version="%i.0.0" % self.version, description="Dragon7 - FP1 - MD5270", script_version="1", generation_date=std_datetime_str('date').replace('-', '/')) OPTIONS = objectify.SubElement(self.dragon, "OPTIONS") OPTIONS.append( objectify.Element("CheckUpdates", value=bool_formatter(self.CheckUpdates))) OPTIONS.append( objectify.Element("PreserveTemporaryProjects", value=bool_formatter( self.PreserveTemporaryProjects))) OPTIONS.append( objectify.Element("SaveLayout", value=bool_formatter(self.SaveLayout))) # OPTIONS.append(objectify.Element("ShowWorksheet", value = bool_formatter(self.ShowWorksheet))) OPTIONS.append( objectify.Element("Decimal_Separator", value=self.Decimal_Separator)) if self.Missing_String == "NaN": self.Missing_String = "na" OPTIONS.append( objectify.Element("Missing_String", value=self.Missing_String)) OPTIONS.append( objectify.Element("DefaultMolFormat", value=self.DefaultMolFormat)) # OPTIONS.append(objectify.Element("HelpBrowser", value = self.HelpBrowser)) OPTIONS.append( objectify.Element("RejectDisconnectedStrucuture", value=bool_formatter( self.RejectDisconnectedStrucuture))) OPTIONS.append( objectify.Element("RetainBiggestFragment", value=bool_formatter( self.RetainBiggestFragment))) OPTIONS.append( objectify.Element("RejectUnusualValence", value=bool_formatter( self.RejectUnusualValence))) OPTIONS.append( objectify.Element("Add2DHydrogens", value=bool_formatter( self.Add2DHydrogens))) OPTIONS.append( objectify.Element( "DisconnectedCalculationOption", value=self.DisconnectedCalculationOption)) OPTIONS.append( objectify.Element("MaxSRforAllCircuit", value=self.MaxSRforAllCircuit)) # OPTIONS.appendm(objectify.Element("MaxSR", value = self.MaxSR)) OPTIONS.append( objectify.Element("MaxSRDetour", value=self.MaxSRDetour)) OPTIONS.append( objectify.Element("MaxAtomWalkPath", value=self.MaxAtomWalkPath)) OPTIONS.append( objectify.Element("RoundCoordinates", value=bool_formatter( self.RoundCoordinates))) OPTIONS.append( objectify.Element("RoundWeights", value=bool_formatter(self.RoundWeights))) OPTIONS.append( objectify.Element("LogPathWalk", value=bool_formatter(self.LogPathWalk))) OPTIONS.append( objectify.Element("LogEdge", value=bool_formatter(self.LogEdge))) Weights = objectify.SubElement(OPTIONS, "Weights") for weight in self.Weights: if weight not in [ "Mass", "VdWVolume", "Electronegativity", "Polarizability", "Ionization", "I-State" ]: msg = "'%s' is not a valid weight type." % weight raise ValueError(msg) Weights.append(objectify.Element('weight', name=weight)) OPTIONS.append( objectify.Element("SaveOnlyData", value=bool_formatter(self.SaveOnlyData))) OPTIONS.append( objectify.Element("SaveLabelsOnSeparateFile", value=bool_formatter( self.SaveLabelsOnSeparateFile))) OPTIONS.append( objectify.Element("SaveFormatBlock", value=self.SaveFormatBlock)) OPTIONS.append( objectify.Element("SaveFormatSubBlock", value=self.SaveFormatSubBlock)) OPTIONS.append( objectify.Element("SaveExcludeMisVal", value=bool_formatter( self.SaveExcludeMisVal))) OPTIONS.append( objectify.Element("SaveExcludeAllMisVal", value=bool_formatter( self.SaveExcludeAllMisVal))) OPTIONS.append( objectify.Element("SaveExcludeConst", value=bool_formatter( self.SaveExcludeConst))) OPTIONS.append( objectify.Element("SaveExcludeNearConst", value=bool_formatter( self.SaveExcludeNearConst))) OPTIONS.append( objectify.Element("SaveExcludeStdDev", value=bool_formatter( self.SaveExcludeStdDev))) OPTIONS.append( objectify.Element("SaveStdDevThreshold", value=self.SaveStdDevThreshold)) OPTIONS.append( objectify.Element("SaveExcludeCorrelated", value=bool_formatter( self.SaveExcludeCorrelated))) OPTIONS.append( objectify.Element("SaveCorrThreshold", value=self.SaveCorrThreshold)) OPTIONS.append( objectify.Element( "SaveExclusionOptionsToVariables", value=bool_formatter( self.SaveExclusionOptionsToVariables))) OPTIONS.append( objectify.Element("SaveExcludeMisMolecules", value=bool_formatter( self.SaveExcludeMisMolecules))) OPTIONS.append( objectify.Element("SaveExcludeRejectedMolecules", value=bool_formatter( self.SaveExcludeRejectedMolecules))) OPTIONS.append( objectify.Element("RoundDescriptorValues", value=bool_formatter( self.RoundDescriptorValues))) DESCRIPTORS = objectify.SubElement(self.dragon, "DESCRIPTORS") for i in self.blocks: if i < 1 or i > 30: msg = "block id must be in range 1 to 30." raise ValueError(msg) DESCRIPTORS.append( objectify.Element('block', id="%i" % i, SelectAll="true")) MOLFILES = objectify.SubElement(self.dragon, "MOLFILES") MOLFILES.append( objectify.Element("molInput", value=self.molInput)) if self.molInput == "stdin": if self.molInputFormat not in [ 'SYBYL', 'MDL', 'HYPERCHEM', 'SMILES', 'CML', 'MACROMODEL' ]: msg = "'%s' is not a valid molInputFormat. Formats:['SYBYL','MDL','HYPERCHEM','SMILES','CML','MACROMODEL']" % self.molInputFormat raise ValueError(msg) MOLFILES.append( objectify.Element("molInputFormat", value=self.molInputFormat)) elif self.molInput == "file": if isinstance(self.molFile, dict): for f in range(1, len(self.molFile) + 1): MOLFILES.append( objectify.Element( "molFile", value=self.molFile[f]['file'])) elif isinstance(self.molFile, str): MOLFILES.append( objectify.Element("molFile", value=self.molFile)) else: msg = 'Variable molInput can be either a string or a list' raise ValueError(msg) else: msg = "Enter a valid molInput: 'stdin' or 'file'" raise ValueError(msg) OUTPUT = objectify.SubElement(self.dragon, "OUTPUT") OUTPUT.append( objectify.Element("knimemode", value=bool_formatter(self.knimemode))) OUTPUT.append( objectify.Element("SaveStdOut", value=bool_formatter(self.SaveStdOut))) OUTPUT.append( objectify.Element("SaveProject", value=bool_formatter(self.SaveProject))) if self.SaveProject: OUTPUT.append( objectify.Element("SaveProjectFile", value=self.SaveProjectFile)) OUTPUT.append( objectify.Element("SaveFile", value=bool_formatter(self.SaveFile))) if self.SaveFile: OUTPUT.append( objectify.Element("SaveType", value=self.SaveType) ) # value = "[singlefile/block/subblock]" OUTPUT.append( objectify.Element("SaveFilePath", value=self.output_directory + self.SaveFilePath) ) #Specifies the file name for saving results as a plan text file(s), if the "singlefile" option is set; if "block" or "subblock" are set, specifies the path in which results files will be saved. OUTPUT.append(objectify.Element( "logMode", value=self.logMode)) # value = [none/stderr/file] if self.logMode == "file": OUTPUT.append( objectify.Element("logFile", value=self.output_directory + self.logFile)) if self.external: EXTERNAL = objectify.SubElement(self.dragon, "EXTERNAL") EXTERNAL.append( objectify.Element("fileName", value=self.fileName)) EXTERNAL.append( objectify.Element("delimiter", value=self.delimiter)) EXTERNAL.append( objectify.Element("consecutiveDelimiter", value=bool_formatter( self.consecutiveDelimiter))) EXTERNAL.append( objectify.Element("MissingValue", value=self.MissingValue)) self._save_script() else: msg = "Only version 6 and version 7 (newest version) are available in this module." warnings.warn(msg, Warning) else: doc = etree.parse(script) self.dragon = etree.tostring(doc) # dragon script : dragon self.dragon = objectify.fromstring(self.dragon) objectify.deannotate(self.dragon) etree.cleanup_namespaces(self.dragon) if self.dragon.attrib['version'][0] not in ['6', '7']: msg = "Dragon script is not labeled to the newest vesions of Dragon, 6 or 7. This may causes some problems." warnings.warn(msg, Warning) mandatory_nodes = ['OPTIONS', 'DESCRIPTORS', 'MOLFILES', 'OUTPUT'] reported_nodes = [ element.tag for element in self.dragon.iterchildren() ] if not set(reported_nodes).issuperset(set(mandatory_nodes)): msg = 'Dragon script does not contain all mandatory nodes, which are:%s' % str( mandatory_nodes) raise ValueError(msg) self.drs = script self.data_path = self.dragon.OUTPUT.SaveFilePath.attrib['value'] return self
from lxml import etree from lxml import objectify import redis import re hn = open('/etc/hostname') hostname = hn.readline()[:-1] + '.local' # drop triailing newline hostname_text = 'http://' + hostname r_text = redis.StrictRedis(host='localhost', port=6379, db=1) zeitgeist = r_text.randomkey() if zeitgeist is None: zeitgeist = 'redis is unavailable!' # here zeitgeist should be made XML-compliant via a truly opaque regex because:XML is nasty # create XML root = objectify.Element('service-group') t_name = objectify.SubElement(root, 'name') t_name.attrib['replace-wildcards'] = 'yes' t_name._setText(hostname_text) t_service = objectify.SubElement(root, 'service') tt_hostname = objectify.SubElement(t_service, 'host-name') tt_hostname._setText(hostname) tt_type = objectify.SubElement(t_service, 'type') tt_type._setText('_http._tcp') tt_port = objectify.SubElement(t_service, 'port') tt_port._setText('80') tt_txtrecord = objectify.SubElement(t_service, 'txt-record') d = 'path=/' + zeitgeist re.sub(u'[^\u0020-\uD7FF\u0009\u000A\u000D\uE000-\uFFFD\u10000-\u10FFFF]+', '', d) tt_txtrecord._setText(d) objectify.deannotate(root, cleanup_namespaces=True)