def getConfigStyleDict(): styledict = {} #initialize the new styledict # get the tree from the style.xml file tree = xmlparse("config" + QDir.separator() + "style.xml").getroot() for styletype in tree: # iterate over the types of widget styletype_key = styletype.tag.lower() if styletype.tag.lower().startswith("default-") else styletype.tag styledict[styletype_key] = {} # create a new dictionary for the style-type for state in States: styledict[styletype_key][state] = {} styledict[styletype_key]['normal'] = {} styledict[styletype_key]['durations'] = {} for styledef_or_statedef in styletype: if styledef_or_statedef.tag.lower() in States: for styledef in styledef_or_statedef: styledict[styletype_key][styledef_or_statedef.tag.lower()][styledef.tag.lower()] = getValue(styledef) elif styledef_or_statedef.tag.lower() in StateTransitions: if styledef_or_statedef.get('time') is None: raise StyleError(styletype.tag + " => " + styledef_or_statedef.tag + " must have 'time' attribute") styledict[styletype_key]['durations'][styledef_or_statedef.tag.lower()] = int(styledef_or_statedef.get('time')) else: for state in States: styledict[styletype_key][state][styledef_or_statedef.tag.lower()] = getValue(styledef_or_statedef) styledict[styletype_key]['normal'][styledef_or_statedef.tag.lower()] = getValue(styledef_or_statedef) return styledict
def svn(self, *cmd): command = " ".join(self.pre) command = command + " " + " ".join(list(cmd)) command = command + " " + " ".join([self.root]) pipe = Popen(command.split(" "), stdout=PIPE) try: data = pipe.communicate()[0] except IOError: data = "" return xmlparse(StringIO(data.decode()))
def parse_interface(interfacename): tree = xmlparse("views" + QDir.separator() + interfacename + ".xml").getroot() # get the tree Compiler.current_interfacename = interfacename # set the current interfacename imported = [] # this is the list of interfaces to parse after this one Compiler.code += "from PySide.QtGui import *\nfrom PySide.QtCore import *\n" # import PySide Compiler.code += "from oxide.widgets.all import *\n" # import Oxide if interfacename == Compiler.start: # if this is the start interface, create a QApplication Compiler.code += "import sys\n" # using sys.argv, Compiler.code += "app = OxideApplication(sys.argv)\n" # create a QApplication add_util_funcs() # add the utility functions add_model(interfacename,"__main__") # now add the model code to the output file for element in tree: # iterate through the elements in the tree if element.tag.lower() == "animations": # here we handle the special 'animations' tag Compiler.to_be_own_class = False # there is no way that we're in the resources tag here for animation in element: # go through each animation parse_animation(animation) # and parse it elif element.tag.lower() == "window": # here we handle the window Compiler.to_be_own_class = False # there is no way that we're in the resources tag here parse_toplevel(element) # using parse_window elif element.tag.lower() == "resources": Compiler.to_be_own_class = True for child in element: Compiler.direct_resources_child = True parse_abstract_element(child) Compiler.direct_resources_child = False Compiler.direct_resources_child = False elif element.tag.lower() == "import": Compiler.code += "import " + element.get('interface') + "\n" imported.append(element.get('interface')) if interfacename == Compiler.start: # to finish up, if this is the start file Compiler.code += "sys.exit(app.exec_())\n" # run the application # now it has come time to put the code on the filesystem if not QDir("bin").exists(): # if the 'bin' folder doesn't exist QDir().mkdir("bin") # create it interfacefile = open(Compiler.gendir + QDir.separator() + interfacename + ".py", 'w') interfacefile.write(Compiler.code) # write Compiler.code to the file Compiler.code = "" # reset Compiler.code for interface in imported: parse_interface(interface)
def _ParseXMLFile(self, file_name, entity_type): """Parses the given XML file, returning the root ElementTree, or None if there is some sort of problem.""" from os.path import join as joinpath from xml.etree.ElementTree import parse as xmlparse if self._is_verbose: print('=== Processing %s file "%s"' % (entity_type, file_name)) path = joinpath(self._xml_directory, file_name) try: return xmlparse(path).getroot() except: print('*** Unable to parse XML from "%s"' % path) return None
def parse_upf(fname): """Parse UPF pseudopotential from file descriptor. Return a dictionary with the parsed data. UPF is a custom format with some XML tags in it. The files are not well-formed XML. We will just do some custom parsing rather than involving an xml library. """ pp = {} try: root = xmlparse(fname).getroot() except ParseError: # Typical! Non-well-formed file full of probable FORTRAN output. # We'll try to insert our own header and see if things go well. root = fromstring('\n'.join(['<xml>', open(fname).read(), '</xml>'])) header_element = root.find('PP_HEADER') header = header_element.attrib # v201 is the sensible version. # There are other files out there and we will have to deal with their # inconsistencies in the most horrendous way conceivable: by if-statements. v201 = (root.attrib.get('version') == '2.0.1') def toarray(element): attr = element.attrib numbers = map(float, element.text.split()) if attr: assert attr['type'] == 'real' assert int(attr['size']) == len(numbers) icut = attr.get('cutoff_radius_index') # XXX There's also something called ultrasoft_cutoff_radius if icut is not None: numbers = numbers[:int(icut)] return np.array(numbers) if v201: for key, val in header.items(): header[key] = val.strip() # some values have whitespace... for key in ['is_paw', 'is_coulomb', 'has_so', 'has_wfc', 'has_gipaw', 'paw_as_gipaw', 'core_correction']: header[key] = {'F': False, 'T': True}[header[key]] for key in ['z_valence', 'total_psenergy', 'wfc_cutoff', 'rho_cutoff']: header[key] = float(header[key]) for key in ['l_max', 'l_max_rho', 'mesh_size', 'number_of_wfc', 'number_of_proj']: header[key] = int(header[key]) else: assert len(header) == 0 # This is the crappy format. headerlines = [line for line in header_element.text.strip().splitlines()] #header['version'] = headerlines[0].split()[0] header['element'] = headerlines[1].split()[0] #header['has_nlcc'] = {'T': True, 'F': False}[headerlines[3].split()[0]] #assert not header['has_nlcc'] # XC functional? header['z_valence'] = float(headerlines[5].split()[0]) header['total_psenergy'] = float(headerlines[6].split()[0]) # cutoffs? header['l_max'] = int(headerlines[8].split()[0]) header['mesh_size'] = int(headerlines[9].split()[0]) nwfs, nprojectors = headerlines[10].split()[:2] header['number_of_wfc'] = int(nwfs) header['number_of_proj'] = int(nprojectors) pp['header'] = header mesh_element = root.find('PP_MESH') pp['r'] = toarray(mesh_element.find('PP_R')) pp['rab'] = toarray(mesh_element.find('PP_RAB')) # Convert to Hartree from Rydberg. pp['vlocal'] = 0.5 * toarray(root.find('PP_LOCAL')) nonlocal = root.find('PP_NONLOCAL') pp['projectors'] = [] for element in nonlocal: if element.tag.startswith('PP_BETA'): if '.' in element.tag: name, num = element.tag.split('.') assert name == 'PP_BETA' attr = element.attrib proj = UPFStateSpec(int(attr['index']), attr['label'], int(attr['angular_momentum']), toarray(element)) assert num == attr['index'] else: tokens = element.text.split() metadata = tokens[:5] values = map(float, tokens[5:]) npts = int(metadata[4]) assert npts == len(values), (npts, len(values)) while values[-1] == 0.0: values.pop() proj = UPFStateSpec(int(tokens[0]), '??', int(tokens[1]), np.array(values)) pp['projectors'].append(proj) else: if v201: assert element.tag == 'PP_DIJ' # XXX probably measured in Rydberg. pp['DIJ'] = 0.5 * toarray(element) else: lines = element.text.strip().splitlines() nnonzero = int(lines[0].split()[0]) nproj = pp['header']['number_of_proj'] D_ij = np.zeros((nproj, nproj)) for n in range(1, nnonzero + 1): tokens = lines[n].split() i = int(tokens[0]) - 1 j = int(tokens[1]) - 1 D = float(tokens[2]) D_ij[i, j] = D D_ij[j, i] = D assert len(lines) == 1 + nnonzero # XXX probably measured in Rydberg. pp['DIJ'] = 0.5 * D_ij pswfc_element = root.find('PP_PSWFC') pp['states'] = [] if v201: for element in pswfc_element: attr = element.attrib name = element.tag state = UPFStateSpec(int(attr['index']), attr['label'], int(attr['l']), toarray(element), float(attr['occupation']), int(attr['n'])) pp['states'].append(state) else: state_data = [] for line in pswfc_element.text.splitlines()[1:]: if line.endswith('Wavefunction'): values = [] state_data.append((line, values)) else: values.extend(map(float, line.split())) for header, values in state_data: label, l, occupation, wfstring = header.split() assert wfstring == 'Wavefunction' state = UPFStateSpec(None, label, int(l), np.array(values), occupation=float(occupation)) pp['states'].append(state) #print repr(lines[0]) #assert len(pp['states']) > 0 pp['rhoatom'] = toarray(root.find('PP_RHOATOM')) return pp
def parse(self): """ parse the xml in self.path and return the gtk translation """ dom = xmlparse(self.path) root = dom.getroot() self.add_element(root, self.gtkwin) # start the recursive parsing
def parse_upf(fname): """Parse UPF pseudopotential from file descriptor. Return a dictionary with the parsed data. UPF is a custom format with some XML tags in it. The files are not well-formed XML. We will just do some custom parsing rather than involving an xml library. """ pp = {} try: root = xmlparse(fname).getroot() except ParseError: # Typical! Non-well-formed file full of probable FORTRAN output. # We'll try to insert our own header and see if things go well. root = fromstring('\n'.join(['<xml>', open(fname).read(), '</xml>'])) pp['fname'] = fname header_element = root.find('PP_HEADER') header = header_element.attrib # v201 is the sensible version. # There are other files out there and we will have to deal with their # inconsistencies in the most horrendous way conceivable: by if-statements. v201 = (root.attrib.get('version') == '2.0.1') def toarray(element): attr = element.attrib numbers = map(float, element.text.split()) if attr: assert attr['type'] == 'real' assert int(attr['size']) == len(numbers) icut = attr.get('cutoff_radius_index') # XXX There's also something called ultrasoft_cutoff_radius if icut is not None: numbers = numbers[:int(icut)] return np.array(numbers) if v201: for key, val in header.items(): header[key] = val.strip() # some values have whitespace... for key in [ 'is_paw', 'is_coulomb', 'has_so', 'has_wfc', 'has_gipaw', 'paw_as_gipaw', 'core_correction' ]: header[key] = {'F': False, 'T': True}[header[key]] for key in ['z_valence', 'total_psenergy', 'wfc_cutoff', 'rho_cutoff']: header[key] = float(header[key]) for key in [ 'l_max', 'l_max_rho', 'mesh_size', 'number_of_wfc', 'number_of_proj' ]: header[key] = int(header[key]) else: assert len(header) == 0 # This is the crappy format. headerlines = [ line for line in header_element.text.strip().splitlines() ] #header['version'] = headerlines[0].split()[0] header['element'] = headerlines[1].split()[0] #header['has_nlcc'] = {'T': True, 'F': False} ......... #assert not header['has_nlcc'] # XC functional? header['z_valence'] = float(headerlines[5].split()[0]) header['total_psenergy'] = float(headerlines[6].split()[0]) # cutoffs? header['l_max'] = int(headerlines[8].split()[0]) header['mesh_size'] = int(headerlines[9].split()[0]) nwfs, nprojectors = headerlines[10].split()[:2] header['number_of_wfc'] = int(nwfs) header['number_of_proj'] = int(nprojectors) info_element = root.find('PP_INFO') pp['info'] = info_element.text pp['header'] = header mesh_element = root.find('PP_MESH') pp['r'] = toarray(mesh_element.find('PP_R')) pp['rab'] = toarray(mesh_element.find('PP_RAB')) # Convert to Hartree from Rydberg. pp['vlocal'] = 0.5 * toarray(root.find('PP_LOCAL')) nonlocal = root.find('PP_NONLOCAL') pp['projectors'] = [] for element in nonlocal: if element.tag.startswith('PP_BETA'): if '.' in element.tag: name, num = element.tag.split('.') assert name == 'PP_BETA' attr = element.attrib proj = UPFStateSpec(int(attr['index']), attr['label'], int(attr['angular_momentum']), toarray(element)) assert num == attr['index'] else: tokens = element.text.split() metadata = tokens[:5] values = map(float, tokens[5:]) npts = int(metadata[4]) assert npts == len(values), (npts, len(values)) while values[-1] == 0.0: values.pop() proj = UPFStateSpec(int(tokens[0]), '??', int(tokens[1]), np.array(values)) pp['projectors'].append(proj) else: if v201: assert element.tag == 'PP_DIJ', element.tag # XXX probably measured in Rydberg. pp['DIJ'] = 0.5 * toarray(element) else: lines = element.text.strip().splitlines() nnonzero = int(lines[0].split()[0]) nproj = pp['header']['number_of_proj'] D_ij = np.zeros((nproj, nproj)) for n in range(1, nnonzero + 1): tokens = lines[n].split() i = int(tokens[0]) - 1 j = int(tokens[1]) - 1 D = float(tokens[2]) D_ij[i, j] = D D_ij[j, i] = D assert len(lines) == 1 + nnonzero # XXX probably measured in Rydberg. pp['DIJ'] = 0.5 * D_ij pswfc_element = root.find('PP_PSWFC') pp['states'] = [] if v201: for element in pswfc_element: attr = element.attrib name = element.tag state = UPFStateSpec(int(attr['index']), attr['label'], int(attr['l']), toarray(element), float(attr['occupation']), int(attr['n'])) pp['states'].append(state) else: state_data = [] for line in pswfc_element.text.splitlines()[1:]: if line.endswith('Wavefunction'): values = [] state_data.append((line, values)) else: values.extend(map(float, line.split())) for header, values in state_data: label, l, occupation, wfstring = header.split() assert wfstring == 'Wavefunction' state = UPFStateSpec(None, label, int(l), np.array(values), occupation=float(occupation)) pp['states'].append(state) #print repr(lines[0]) #assert len(pp['states']) > 0 pp['rhoatom'] = toarray(root.find('PP_RHOATOM')) return pp
def compile(interfacename, dist=False): # @ReservedAssignment code = "" mainWindowId = None code += "from PySide.QtGui import *\nfrom PySide.QtCore import *\nimport sys\n" if interfacename == app.manifest['start']: code += "app = QApplication(sys.argv)\n" a = captan.style.parseStyle() code += "app.setStyleSheet('''" + a + "''')\n" print a # only create a QApplication if it is the main file for filename in [ f for f in os.listdir("views") if os.path.isfile(os.path.join("views",f)) ]: if not filename == interfacename + ".xml" and interfacename == app.manifest['start']: code += "import " if not dist: code += "bin." code += ".".join(filename.split(".")[:-1]) + " as " + ".".join(filename.split(".")[:-1]) + "\n" code += getFuncs(interfacename) if interfacename == app.manifest['start']: try: # call the end function if it exists exec "models." + interfacename + ".init" code += "init(sys.argv)\n" except: pass # init should only be called for the main file tree = xmlparse("views" + QDir.separator() + interfacename + '.xml') tree = tree.getroot() # get the tree for element in tree: # parse the top-level tags if element.tag.lower() == "window": # the MainWindow if element.get("id") is None: captan.children.addDefaultId(element) mainWindowId = element.get("id") code += parseWindow(element, tree, mainWindowId, interfacename) # delegate the task to captan.main.parseWindow elif element.tag.lower() == "buffer": code += parseBuffer(element,interfacename) if mainWindowId is not None: # show the MainWindow, if there is one code += mainWindowId + ".show()\n" if interfacename == app.manifest['start']: # execute the app if it is the main view code += "APP_RESULT = app.exec_()\n" # execute the application and get the result try: # call the end function if it exists exec "models." + interfacename + ".end" code += "end(APP_RESULT)\n" except: pass code += "sys.exit(APP_RESULT)\n" f = open(getProjectFile(interfacename + ".py"),'w') f.write(code)
with open(".ipcache", "r") as f: oldip = f.read(15).strip() f.close() print("cached ip is: " + oldip) if newip != oldip: # ip not same, update dns # view rrid req = request.Request(URL_LISTDNS.format(NAMESILO_KEY), headers=hdr) # print(URL_LISTDNS.format(NAMESILO_KEY)) try: resp = request.urlopen(req) except Exception as ex: print(ex) sys.exit(1) doc = xmlparse(resp) allrecords = doc.findall("reply/resource_record") for record in allrecords: if record.find("host").text == "hpc.xyzjdays.xyz": NAMESILO_RRID = record.find("record_id").text print("record id is: " + NAMESILO_RRID) break if NAMESILO_RRID != "": # update dns req = request.Request(URL_UPDATENDS.format(NAMESILO_KEY, NAMESILO_RRID, newip), headers=hdr) try: resp = request.urlopen(req) except Exception as ex:
import argparse from sys import exit parser = argparse.ArgumentParser(description='Fetch values.xml from poseidon device and try to parse it') parser.add_argument('--host', help='the host to check') args = parser.parse_args() if not args.host: print Exception('You need to specify a hostname') exit(-1) link = 'http://%s/values.xml' % args.host poseidonxml = httpget(link) if poseidonxml.status_code == 200: xml = xmlparse(poseidonxml.text) devicename = xml.findall('Agent/DeviceName').pop().text senset = xml.findall('SenSet').pop() print('%s:' % devicename) for child in senset.getchildren(): sensor = { 'id': child.findall('ID').pop().text, 'name': child.findall('Name').pop().text, 'min': child.findall('Min').pop().text, 'max': child.findall('Max').pop().text, 'units': child.findall('Units').pop().text, 'value': child.findall('Value').pop().text, } print(sensor) else: print("Something went wrong. Status: %s" % poseidonxml.status_code)