Exemplo n.º 1
0
def main():
    if len(sys.argv) < 4:
        print "Provide a directory name, which contains the checks."
        sys.exit(1)

    # Get header with schema version
    oval_config = sys.argv[1] + "/" + conf_file
    product = sys.argv[2]

    oval_schema_version = None
    runtime_oval_schema_version = os.getenv('RUNTIME_OVAL_VERSION', None)

    if os.path.isfile(oval_config):
        (config_oval_schema_version, multi_platform) = parse_conf_file(oval_config, product)
        if runtime_oval_schema_version is not None and \
           runtime_oval_schema_version != config_oval_schema_version:
            oval_schema_version = runtime_oval_schema_version
        else:
            oval_schema_version = config_oval_schema_version
        header = _header(oval_schema_version)
    else:
        print 'The directory specified does not contain the %s file!' % conf_file
        sys.exit(1)

    body = checks(product)

    # parse new file(string) as an ElementTree, so we can reorder elements
    # appropriately
    corrected_tree = ET.fromstring(header + body + footer)
    tree = add_platforms(corrected_tree, multi_platform)
    definitions = ET.Element("definitions")
    tests = ET.Element("tests")
    objects = ET.Element("objects")
    states = ET.Element("states")
    variables = ET.Element("variables")

    for childnode in tree.findall("./{http://oval.mitre.org/XMLSchema/oval-definitions-5}def-group/*"):
        if childnode.tag is ET.Comment:
            continue
        if childnode.tag.endswith("definition"):
            append(definitions, childnode)
        if childnode.tag.endswith("_test"):
            append(tests, childnode)
        if childnode.tag.endswith("_object"):
            append(objects, childnode)
        if childnode.tag.endswith("_state"):
            append(states, childnode)
        if childnode.tag.endswith("_variable"):
            append(variables, childnode)

    tree = ET.fromstring(header + footer)
    tree.append(definitions)
    tree.append(tests)
    tree.append(objects)
    tree.append(states)
    if list(variables):
        tree.append(variables)

    ET.dump(tree)
    sys.exit(0)
Exemplo n.º 2
0
def create_feed():
    root = etree.Element("rss")
    channel = etree.Element("channel")
    root.append(channel)

    title = etree.Element("title")
    title.text = URL
    link = etree.Element("link")
    link.text = URL_RSS_FILE
    channel.append(title)
    channel.append(link)

    image = etree.Element("image")
    url = etree.Element("url")
    url.text = FAVICON
    title = etree.Element("title")
    title.text = TITLE
    image.append(url)
    image.append(title)
    channel.append(image)

    language = etree.Element("language")
    language.text = "en"
    channel.append(language)
    write_to_file(root)
    etree.dump(root)
Exemplo n.º 3
0
def proc_persons(options, cred, persons):
    """
    Person-based import - one or more <Case> elements inside a <Cases>
    element inside each <Person>
    """
    ticker = Ticker('cases')
    for person_elem in persons:
        try:
            assert_tag(person_elem, 'Person')
            cases_elem = want_elem(person_elem, 'Cases')
            person_id = None
            for case_elem in cases_elem.getchildren():
                assert_tag(case_elem, 'Case')
                synd = find_syndrome(case_elem.get('syndrome'))
                case = cases.new_case(cred, synd.syndrome_id, 
                                      use_person_id=person_id)
                if person_id is None:
                    copy_node(person_elem, case.person)
                    case.person.data_src = options.data_src
                case.update()
                if person_id is None:
                    person_id = case.case_row.person_id
                proc_forms(options, synd, case, case_elem)
                ticker.tick()
        except Exception, e:
            dump(person_elem)
            raise
            cmdcommon.abort(e)
Exemplo n.º 4
0
 def __init__(self):
     page = etree.Element('svg')
     page.attrib['xmlns'] = "http://www.w3.org/2000/svg"
     page.attrib['version'] = "1.1"
     page.attrib['xlink'] = "http://www.w3.org/1999/xlink"
     page.attrib['width'] = "210mm"
     page.attrib['height'] = "297mm"
     page.attrib['viewBox'] = "-50.0 -50.0 4950.0 7214.80577065"
     doc = etree.ElementTree(page)
     print etree.tostring(page)
     #etree.dump(page)
     doc = etree.parse('t.html')
     root = doc.getroot()
     for i in root.attrib:
         print i
     #for i in root.iter():
         #print i
         #print i.tag
     defs = root.find('{http://www.w3.org/2000/svg}defs')
     etree.dump(defs)
     for i in defs.iter():
         #print i
         print i.tag
     style = defs.find('{http://www.w3.org/2000/svg}style')
     etree.dump(style)
     print etree.tostring(doc)
Exemplo n.º 5
0
def main():
    argparser = argparse.ArgumentParser()
    argparser.add_argument("payload", help="Path to payload as a file")
    argparser.add_argument("-v","--verbose", help="Verbose error output",action="store_true")
    args = argparser.parse_args()
    try:
        # Create vulnerable XML Parser
        # load_dtd is False by default
        # no_network is True by default
        # resolve_entities is False by default
        parser = etree.XMLParser(recover=False,
                                 dtd_validation=False,
                                 load_dtd=True,
                                 no_network=False,
                                 resolve_entities=True
                                 )

        tree = etree.parse(args.payload, parser=parser)
        # Output the whole XML
        etree.dump(tree.getroot())


    except Exception as err:
        print(err)
        if args.verbose:
            traceback.print_exc()
        else:
            print("If you wish more info execute this script with --verbose flag")
Exemplo n.º 6
0
def write_resource(resources_dict, filename, xml_resource_type, is_hex_string=False):
    root = etree.Element("resources")
    if len(colors) > 0:
        colorsPath = os.path.join(path, filename)
        # if not os.path.exists(colorsPath):
        #     os.mkdir(colorsPath)
        # # endif
        index = 1
        for resource in resources_dict:
            subelement = etree.SubElement(root, xml_resource_type)
            subelement.set("name", resource)
            if is_hex_string:
                print(resources_dict[resource])
                subelement.text = str(hex(resources_dict[resource])).replace("0x", "#")
            else:
                subelement.text = str(resources_dict[resource])
            # endif
            index += 1
        # endfor
        etree.dump(root)
        with open(colorsPath, 'w') as fp:
            xml_file_header = "<?xml version=\"1.0\" encoding=\"utf-8\"?>"
            fp.writelines([xml_file_header])
            fp.write(xml_file_header)
            fp.write(etree.tostring(root, encoding='unicode', pretty_print=True))
Exemplo n.º 7
0
def main(device_ip, peer_ip):
    config = ConfigDictionary()

    username = config.username()
    password = config.password()

    print (device_ip + " logging in as " + username)

    jdev = Device(user=username, host=device_ip, password=password)
    jdev.open(gather_facts=False)
    jdev.timeout=6000

    try:
        resultxml = jdev.rpc.get_route_information(table='inet.0',protocol='bgp',peer=peer_ip,extensive=True)

    except Exception as err:
        print "CMD:"   
        etree.dump(err.cmd)   
        print "RSP:"   
        etree.dump(err.rsp)

    for routexml in resultxml.findall('.//rt'):
        route = RouteData(routexml)
        print "destination: " + route.prefix() + "as-path: " + route.aspath()

    jdev.close()
Exemplo n.º 8
0
 def current_picture(self, node):
     ''' Internal function.  Debugging aid for the export module.'''
     if settings.DEBUG:
         print("Current XML Picture is")
         print("======================\n" * 2)
         ET.dump(node)
         print("======================\n" * 2)
Exemplo n.º 9
0
def main(device_ip, peer_ip):
    config = ConfigDictionary()

    username = config.username()
    password = config.password()

    print(device_ip + " logging in as " + username)

    jdev = Device(user=username, host=device_ip, password=password)
    jdev.open(gather_facts=False)
    jdev.timeout = 6000

    try:
        resultxml = jdev.rpc.get_route_information(table='inet.0',
                                                   protocol='bgp',
                                                   peer=peer_ip,
                                                   extensive=True)

    except Exception as err:
        print "CMD:"
        etree.dump(err.cmd)
        print "RSP:"
        etree.dump(err.rsp)

    for routexml in resultxml.findall('.//rt'):
        route = RouteData(routexml)
        print "destination: " + route.prefix() + "as-path: " + route.aspath()

    jdev.close()
Exemplo n.º 10
0
    def test_init(self):

        xml = XLIFFPageXML(self.filename)

        etree.dump(xml.element_tree.getroot())

        return
Exemplo n.º 11
0
 def current_picture(self, node):
     ''' Internal function.  Debugging aid for the export module.'''
     if settings.DEBUG:
         print "Current XML Picture is"
         print "======================\n" * 2
         ET.dump(node)
         print "======================\n" * 2
Exemplo n.º 12
0
def main(argv):
    if '-h' in argv or '--help' in argv:
        print('''Convert one or many libcheck XML reports into JUnit
compatible output (as understood by Jenkins)''')
        return 0
    print('''<!-- generated by check2junit.py
        the libcheck-XML to JUnit-Jenkins-style-XML converter -->''')
    etree.dump(mk_testsuites(argv[1:]))
    return 0
Exemplo n.º 13
0
    def work(self):
        self.parse()
        print self.src_cur
        #self.encoding = 'iso8859-1'
        xmlfile = open(self.src_cur)
        with xmlfile as xml_doc:
            context = iterparse(xml_doc, events=("start", "end"))

            #self.iter_context(context)
            indata = False
            if True:
            #try:
                for event, elem in context:
                    #print elem.tag
                    if elem.tag == self.DATASET_TAG:
                        if event == "start":
                            pass
                        #    data_in = Datensatz()
                        elif event == "end":
                            try:
                                data_in = Datensatz()
                                print "start FOR"
                                for child in elem:
                                    print child.tag,
                                    if child.text is None:
                                        val = None
                                    if type(child.text) == type(u""):
                                        val = child.text
                                    if type(child.text) == type(""):
                                        val = "STRING"
                                    #    val = child.text.decode(self.encoding)
                                    data_in.data[child.tag] = val
                                data_in.dump()
                                #etree.dump(elem)
                                print
                            except:
                                etree.dump(elem)
                    elif elem.tag == 'custLIS':
                        if event == "start":
                            print "START LIS"
                        elif event == "end":
                            print "custLIS ---"
                    if elem.getparent() is None:
                        break
                src_success = True
            '''
            except:
                src_success = False
                etree.dump(elem)
                sleep(3)
            '''
    
        
        print "src_success: "+str(src_success)
        print self.encoding
        return src_success
def main():
    if len(sys.argv) < 2:
        print "Provide a directory name, which contains the checks."
        sys.exit(1)

    # Get header with schema version
    oval_config = sys.argv[1] + "/" + conf_file

    if os.path.isfile(oval_config):
        header = _header(parse_conf_file(oval_config))
    else:
        print 'The directory specified does not contain the %s file!' % conf_file
        sys.exit(1)

    # concatenate all XML files in the checks directory, to create the
    # document body
    body = ""
    for filename in os.listdir(sys.argv[2]):
        if filename.endswith(".xml"):
            with open(sys.argv[2] + "/" + filename, 'r') as xml_file:
                body = body + xml_file.read()

    # parse new file(string) as an ElementTree, so we can reorder elements
    # appropriately
    tree = ET.fromstring(header + body + footer)
    definitions = ET.Element("definitions")
    tests = ET.Element("tests")
    objects = ET.Element("objects")
    states = ET.Element("states")
    variables = ET.Element("variables")

    for childnode in tree.findall(
            "./{http://oval.mitre.org/XMLSchema/oval-definitions-5}def-group/*"
    ):
        if childnode.tag is ET.Comment:
            continue
        if childnode.tag.endswith("definition"):
            append(definitions, childnode)
        if childnode.tag.endswith("_test"):
            append(tests, childnode)
        if childnode.tag.endswith("_object"):
            append(objects, childnode)
        if childnode.tag.endswith("_state"):
            append(states, childnode)
        if childnode.tag.endswith("_variable"):
            append(variables, childnode)

    tree = ET.fromstring(header + footer)
    tree.append(definitions)
    tree.append(tests)
    tree.append(objects)
    tree.append(states)
    tree.append(variables)

    ET.dump(tree)
    sys.exit(0)
Exemplo n.º 15
0
def main():
    if len(sys.argv) < 2:
        print "Provide a directory name, which contains the checks."
        sys.exit(1)

    # Get header with schema version
    oval_config = sys.argv[1] + "/" + conf_file

    if os.path.isfile(oval_config):
        (header, multi_platform) = parse_conf_file(oval_config)
        header = _header(header)
    else:
        print 'The directory specified does not contain the %s file!' % conf_file
        sys.exit(1)

    # concatenate all XML files in the checks directory, to create the
    # document body
    body = ""
    for filename in os.listdir(sys.argv[2]):
        if filename.endswith(".xml"):
            with open(sys.argv[2] + "/" + filename, 'r') as xml_file:
                body = body + xml_file.read()

    # parse new file(string) as an ElementTree, so we can reorder elements
    # appropriately
    corrected_tree = ET.fromstring(header + body + footer)
    tree = add_platforms(corrected_tree, multi_platform)
    definitions = ET.Element("definitions")
    tests = ET.Element("tests")
    objects = ET.Element("objects")
    states = ET.Element("states")
    variables = ET.Element("variables")

    for childnode in tree.findall("./{http://oval.mitre.org/XMLSchema/oval-definitions-5}def-group/*"):
        if childnode.tag is ET.Comment:
            continue
        if childnode.tag.endswith("definition"):
            append(definitions, childnode)
        if childnode.tag.endswith("_test"):
            append(tests, childnode)
        if childnode.tag.endswith("_object"):
            append(objects, childnode)
        if childnode.tag.endswith("_state"):
            append(states, childnode)
        if childnode.tag.endswith("_variable"):
            append(variables, childnode)

    tree = ET.fromstring(header + footer)
    tree.append(definitions)
    tree.append(tests)
    tree.append(objects)
    tree.append(states)
    tree.append(variables)

    ET.dump(tree)
    sys.exit(0)
 def addVendorExtension(self, name, tree_list):
     if self.vendorNamespace not in self.write.attrib.values():
         raise ValueError('ERROR: add VendorExtension after adding xmlns')
     utility.addVendorExtension(name, tree_list, self.elementRefPointer,
                                self.vendorNamespace)
     utility.write_on_file(self.write, self.tree)
     if self.verbosity == 0:
         print("INFO: ElementParameters VendorExtension added " + name)
         for tree in tree_list:
             etree.dump(tree)
Exemplo n.º 17
0
 def addVendorExtension(self, name, tree_list):
     if self.vendorNamespace not in self.write.attrib.values():
         raise ValueError(
             'ERROR: To insert VendorExtension first add xmlns')
     utility.addVendorExtension(name, tree_list, self.root,
                                self.vendorNamespace)
     utility.write_on_file(self.write, self.tree)
     if self.verbosity == 0:
         print("INFO: Scenario VendorExtension added " + name)
         for tree in tree_list:
             etree.dump(tree)
def main(peer_asn):
    list_peering_ips_of_target_asn = []

    config = ConfigDictionary()
    username = config.username()
    password = config.password()

    for router in config.get_list_of_router_names():
        jdev = Device(user=username,
                      host=config.get_router_ip(router),
                      password=password)
        jdev.open(gather_facts=False)
        jdev.timeout = 600

        try:
            resultxml = jdev.rpc.get_bgp_summary_information()
        except Exception as err:
            print "CMD:"
            etree.dump(err.cmd)
            print "RSP:"
            etree.dump(err.rsp)

        bgpsum = BgpData(resultxml)
        for thispeeringip in bgpsum.get_list_ipaddr_from_asn(peer_asn):
            list_peering_ips_of_target_asn.append(thispeeringip)

    print "all peering ips : " + str(list_peering_ips_of_target_asn)

    exchange = Exchange()
    list_sessions_configured_peeringdbid_exchanges_of_target_asn = []
    for peering_ip in list_peering_ips_of_target_asn:
        if not is_valid_ipv4_address(peering_ip):
            next
        else:
            peeringdb_id = exchange.get_exchange_from_peerip(
                peering_ip)['peeringdbid']
            list_sessions_configured_peeringdbid_exchanges_of_target_asn.append(
                peeringdb_id)

    # todo: pull this from config file
    list_my_exchanges = [
        26, 806, 87, 59, 33, 31, 804, 1, 255, 5, 359, 48, 387, 435, 583, 745,
        18, 777, 53, 297, 35, 70, 64, 60, 325, 587
    ]

    peeringdb = PeeringDBClient()
    list_their_exchanges = peeringdb.get_list_connected_ixp(peer_asn)

    mutual_exchanges = set(list_my_exchanges).intersection(
        list_their_exchanges)
    missing_exchanges = set(mutual_exchanges).difference(
        list_sessions_configured_peeringdbid_exchanges_of_target_asn)

    print "Missing exchanges are:" + str(missing_exchanges)
Exemplo n.º 19
0
    def make_metadata(self, echo=False):
        """Build CrossRef compliant batch of DOI metadata, and store it
        internally.

        Meant to be called before 'write_metadata'. Set echo=True
        to send doi_batch to STDOUT
        """
        self.papers_batch = self.make_papers_batch()
        self.slides_batch = self.make_slides_batch()
        if echo:
            print(xml.dump(self.papers_batch))
            print(xml.dump(self.slides_batch))
def getXMLTree(xmlString, debug=False):
	"""returns an libxml2 etree for xmlString, where, for convenience,
	all namespaces on elements are nuked.

	The libxml2 etree lets you do xpath searching using the xpath method.
	"""
	from lxml import etree as lxtree
	tree = lxtree.fromstring(_nukeNamespaces(xmlString))

	if debug:
		lxtree.dump(tree)
	return tree
Exemplo n.º 21
0
    def dump_thesaurus(self, name):
        thesaurus = Thesaurus.objects.filter(identifier=name).get()

        ns = {
            None: SKOS_URI,
            'rdf': RDF_URI,
            'xml': XML_URI,
            'dc': DC_URI,
            'dcterms': DCTERMS_URI
        }

        root = etree.Element(f"{RDF_NS}RDF", nsmap=ns)
        concept_scheme = etree.SubElement(root, f"{SKOS_NS}ConceptScheme")
        concept_scheme.set(f"{RDF_NS}about", thesaurus.about)

        # Default title
        # <dc:title xmlns:dc="http://purl.org/dc/elements/1.1/">GEMET - INSPIRE themes, version 1.0</dc:title>
        title = etree.SubElement(concept_scheme, f"{DC_NS}title")
        title.text = thesaurus.title

        # Localized titles
        # <dc:title xmlns:dc="http://purl.org/dc/elements/1.1/" xml:lang="en">Limitations on public access</dc:title>
        for ltitle in ThesaurusLabel.objects.filter(thesaurus=thesaurus).all():
            title = etree.SubElement(concept_scheme, f"{DC_NS}title")
            title.set(f"{XML_NS}lang", ltitle.lang)
            title.text = ltitle.label

        d = etree.SubElement(concept_scheme, f"{DCTERMS_NS}issued")
        d.text = thesaurus.date
        d = etree.SubElement(concept_scheme, f"{DCTERMS_NS}modified")
        d.text = thesaurus.date

        # Concepts
        for keyword in ThesaurusKeyword.objects.filter(
                thesaurus=thesaurus).all():
            concept = etree.SubElement(concept_scheme, f"{SKOS_NS}Concept")
            if keyword.about:
                concept.set(f"{RDF_NS}about", keyword.about)

            if keyword.alt_label:
                # <skos:altLabel>cp</skos:altLabel>
                label = etree.SubElement(concept, f"{SKOS_NS}altLabel")
                label.text = keyword.alt_label

            for label in ThesaurusKeywordLabel.objects.filter(
                    keyword=keyword).all():
                # <skos:prefLabel xml:lang="en">Geographical grid systems</skos:prefLabel>
                pref_label = etree.SubElement(concept, f"{SKOS_NS}prefLabel")
                pref_label.set(f"{XML_NS}lang", label.lang)
                pref_label.text = label.label

        etree.dump(root, pretty_print=True)
Exemplo n.º 22
0
def main():
    if len(sys.argv) < 4:
        print "Provide a directory name, which contains the checks."
        sys.exit(1)

    # Get header with schema version
    oval_config = sys.argv[1] + "/" + conf_file
    product = sys.argv[2]

    if os.path.isfile(oval_config):
        (header, multi_platform) = parse_conf_file(oval_config, product)
        header = _header(header)
    else:
        print 'The directory specified does not contain the %s file!' % conf_file
        sys.exit(1)

    body = checks(product)

    # parse new file(string) as an ElementTree, so we can reorder elements
    # appropriately
    corrected_tree = ET.fromstring(header + body + footer)
    tree = add_platforms(corrected_tree, multi_platform)
    definitions = ET.Element("definitions")
    tests = ET.Element("tests")
    objects = ET.Element("objects")
    states = ET.Element("states")
    variables = ET.Element("variables")

    for childnode in tree.findall("./{http://oval.mitre.org/XMLSchema/oval-definitions-5}def-group/*"):
        if childnode.tag is ET.Comment:
            continue
        if childnode.tag.endswith("definition"):
            append(definitions, childnode)
        if childnode.tag.endswith("_test"):
            append(tests, childnode)
        if childnode.tag.endswith("_object"):
            append(objects, childnode)
        if childnode.tag.endswith("_state"):
            append(states, childnode)
        if childnode.tag.endswith("_variable"):
            append(variables, childnode)

    tree = ET.fromstring(header + footer)
    tree.append(definitions)
    tree.append(tests)
    tree.append(objects)
    tree.append(states)
    if list(variables):
        tree.append(variables)

    ET.dump(tree)
    sys.exit(0)
Exemplo n.º 23
0
def disco_info(args):
    if not args.who:
        return self.subparser.format_usage()
    who = toJID(args.who)

    q = xmpp.Iq(typ="get", queryNS="http://jabber.org/protocol/disco#info", to=who)
    if args.node:
        q.setTagAttr("query", "node", args.node[0])
    tree = fromstring(str(q))
    print("--disco-info--")
    dump(tree)
    args.bot.cl.send(q)
    return "Sent info query"
Exemplo n.º 24
0
def TestConnection_resp():
    # build XML response message
    xmlmessage = etree.Element(MESSAGE_ID)     #root message type
    xmlmessage.text = TEST_MESSAGE

    content = etree.SubElement(xmlmessage, XML_TEXT)
    content.text = 'Test Connection Successful'
    xmlmessage.append(content)

    if my_debug2:
        print('* XML_TestConnection_resp:')
        etree.dump(xmlmessage)
    # convert xml tree to a string
    return etree.tostring(xmlmessage, encoding='UTF-8', method='xml')
Exemplo n.º 25
0
def main(peer_asn):
    list_peering_ips_of_target_asn = []

    config = ConfigDictionary("/home/andy/etc/pypeer.ini")
    username = config.username()
    password = config.password()

    for router in config.get_list_of_router_names():
        jdev = Device(user=username, host=config.get_router_ip(router),
                      password=password)
        jdev.open(gather_facts=False)
        jdev.timeout = 600

        try:
            resultxml = jdev.rpc.get_bgp_summary_information()
        except Exception as err:
            print "CMD:"
            etree.dump(err.cmd)
            print "RSP:"
            etree.dump(err.rsp)

        bgpsum = BgpData(resultxml)
        for thispeeringip in bgpsum.get_list_ipaddr_from_asn(peer_asn):
            list_peering_ips_of_target_asn.append(thispeeringip)

    exchange = Exchange()
    list_sessions_configured_peeringdbid_exchanges_of_target_asn = []
    for peering_ip in list_peering_ips_of_target_asn:
        if not is_valid_ipv4_address(peering_ip):
            next
        else:
            peeringdb_id = exchange.get_exchange_from_peerip(peering_ip)['peeringdbid']
            list_sessions_configured_peeringdbid_exchanges_of_target_asn.append(peeringdb_id)

    # todo: pull this from config file
    list_my_exchanges = [26, 806, 87, 59, 33, 31, 804, 1, 255, 5, 359, 48, 387,
                         435, 583, 745, 18, 777, 53, 297, 35, 70, 64, 60, 325,
                         587]

    peeringdb = PeeringDBClient()
    list_their_exchanges = peeringdb.get_list_connected_ixp(peer_asn)

    mutual_exchanges = set(list_my_exchanges).intersection(list_their_exchanges)
    missing_exchanges = set(mutual_exchanges).difference(list_sessions_configured_peeringdbid_exchanges_of_target_asn)

    print "Missing exchanges are:" + str(missing_exchanges)

    for pdbid in missing_exchanges:
        print str(pdbid) + ": " + peeringdb.get_name_of_ixp_from_pdbid(pdbid)
def main():
    parser = argparse.ArgumentParser()

    parser.add_argument("inputfile",
                        type=str,
                        help="the map file to be processed")
    #parser.add_argument("-o", "--outputfile", type=str, help="the file to write output to (stdout if missing)", default="")

    args = parser.parse_args()

    sldStore = xml_to_sld(args.inputfile)

    for layer in sldStore.layers:
        print layer
        ET.dump(sldStore.getLayer(layer))
Exemplo n.º 27
0
def disco_info(args):
    if not args.who:
        return self.subparser.format_usage()
    who = toJID(args.who)

    q = xmpp.Iq(typ="get",
                queryNS='http://jabber.org/protocol/disco#info',
                to=who)
    if args.node:
        q.setTagAttr('query', 'node', args.node[0])
    tree = fromstring(str(q))
    print("--disco-info--")
    dump(tree)
    args.bot.cl.send(q)
    return "Sent info query"
Exemplo n.º 28
0
def get_fpc_xpath(dev):
	fpcs_xpath=dev.rpc.get_fpc_information()
	pprint(etree.dump(fpcs_xpath))
	fpcs=fpcs_xpath.iter()
	for fpc in fpcs:
		if fpc.tag == 'fpc':
			print(fpc.findtext('slot'),fpc.findtext('state'), fpc.findtext('temperature'),fpc.findtext('cpu-total'))
Exemplo n.º 29
0
def _backwalkTitles(rec, xpath):
    titles = []
    xpathParts = xpath.split('/')
    while xpathParts[-1] != 'dsc':
        try:
            tn = rec.process_xpath(session, '/'.join(xpathParts) + '/did/unittitle')[0]
            t = flattenTexts(tn)
            titles.append(t.strip())
        except IndexError:
            print etree.dump(rec.process_xpath(session, '/'.join(xpathParts) + '/did')[0])
            raise
            
        xpathParts.pop(-1)
        
    titles.reverse()
    return titles
def main(peer_asn):
    list_peering_ips_of_target_asn = []

    config = ConfigDictionary("etc/pypeer.ini")
    username = config.username()
    password = config.password()

    for router in config.get_list_of_router_names():
        jdev = Device(user=username, host=config.get_router_ip(router),
                      password=password)
        jdev.open(gather_facts=False)
        jdev.timeout = 600

        try:
            resultxml = jdev.rpc.get_bgp_summary_information()
        except Exception as err:
            print "CMD:"
            etree.dump(err.cmd)
            print "RSP:"
            etree.dump(err.rsp)

        bgpsum = BgpData(resultxml)
        for thispeeringip in bgpsum.get_list_ipaddr_from_asn(peer_asn):
            list_peering_ips_of_target_asn.append(thispeeringip)

    exchange = Exchange()
    list_sessions_configured_peeringdbid_exchanges_of_target_asn = []
    for peering_ip in list_peering_ips_of_target_asn:
        if not is_valid_ipv4_address(peering_ip):
            next
        else:
            peeringdb_id = exchange.get_exchange_from_peerip(peering_ip)['peeringdbid']
            list_sessions_configured_peeringdbid_exchanges_of_target_asn.append(peeringdb_id)

    peeringdb = PeeringDBClient()
    peeringjson = PeeringDBParser(peeringdb.asn(peer_asn))
    list_their_exchanges = peeringjson.get_list_of_asn_exchanges()

    mutual_exchanges = set(config.get_list_of_connected_exchanges()).intersection(list_their_exchanges)
    missing_exchanges = set(mutual_exchanges).difference(list_sessions_configured_peeringdbid_exchanges_of_target_asn)

    print "Missing exchanges are:" + str(missing_exchanges)

    for pdbid in missing_exchanges:
        ixpparser    = PeeringDBParser(peeringdb.ixlan(pdbid))
        print str(pdbid) + ": " + ixpparser.get_name_of_ixorg_from_ixlan()
Exemplo n.º 31
0
def get_fpc_yml(dev):
	fpcs_xpath=dev.rpc.get_fpc_information()
	pprint(etree.dump(fpcs_xpath))
	user_defs=loadyaml('UserFPCTable.yml')
	globals().update(user_defs)
	user_table=UserFPCTable(dev)
	user_table.get()
	pprint(user_table.items())
Exemplo n.º 32
0
def main():
    if len(sys.argv) < 2:
        print "Provide a directory name, which contains the checks."
        sys.exit(1)

    # concatenate all XML files in the checks directory, to create the
    # document body
    body = ""
    for filename in os.listdir(sys.argv[1]):
        if filename.endswith(".xml"):
            with open(sys.argv[1] + "/" + filename, 'r') as xml_file:
                body = body + xml_file.read()

    # parse new file(string) as an ElementTree, so we can reorder elements
    # appropriately
    tree = ET.fromstring(header + body + footer)
    definitions = ET.Element("definitions")
    tests = ET.Element("tests")
    objects = ET.Element("objects")
    states = ET.Element("states")
    variables = ET.Element("variables")

    for childnode in tree.findall("./{http://oval.mitre.org/XMLSchema/oval-definitions-5}def-group/*"):
        if childnode.tag is ET.Comment:
            continue
        if childnode.tag.endswith("definition"):
            append(definitions, childnode)
        if childnode.tag.endswith("_test"):
            append(tests, childnode)
        if childnode.tag.endswith("_object"):
            append(objects, childnode)
        if childnode.tag.endswith("_state"):
            append(states, childnode)
        if childnode.tag.endswith("_variable"):
            append(variables, childnode)

    tree = ET.fromstring(header + footer)
    tree.append(definitions)
    tree.append(tests)
    tree.append(objects)
    tree.append(states)
    tree.append(variables)

    ET.dump(tree)
    sys.exit(0)
Exemplo n.º 33
0
def main(peer_asn, output):
    config = ConfigDictionary()
    username = config.username()
    password = config.password()

    local_preferences = config.get_list_of_localpref()

    for router in config.get_list_of_router_names():
        jdev = Device(user=username, host=config.get_router_ip(router), password=password)
        jdev.open(gather_facts=False)
        jdev.timeout = 600
        regex_asn = ".* " + peer_asn

        try:
            resultxml = jdev.rpc.get_route_information(table='inet.0',
                                                       aspath_regex=regex_asn,
                                                       extensive=True)

        except Exception as err:
            print "CMD:"
            etree.dump(err.cmd)
            print "RSP:"
            etree.dump(err.rsp)

        jdev.close()

        sorted_routes = {}
        sorted_routes["peer"] = []
        sorted_routes["peer-indirect"] = []
        sorted_routes["peer-routeserver"] = []
        sorted_routes["transit"] = []
        sorted_routes["customer"] = []
        sorted_routes["outofrange"] = []

        for routexml in resultxml.findall('.//rt'):
            route = RouteData(routexml)
            full_prefix = route.prefix()
            session_type = route.get_adjacency_type(local_preferences)
            sorted_routes[session_type].append(full_prefix)

        if output == 'machine':
            print json.dumps(sorted_routes)
        else:
            print "For " + router + " in " + config.get_router_location(router) + " Routes: " + str(len(sorted_routes["peer"])) + " via bilateral peering, " + str(len(sorted_routes["peer-routeserver"])) + " via peering at mlp, " + str(len(sorted_routes["peer-indirect"])) + " via peering in other cities " + str(len(sorted_routes["customer"])) + " via customer, and " + str(len(sorted_routes["transit"])) + " via transit."
def main():
    openerp = etree.Element("openerp")
    data = etree.SubElement(openerp, "data")
    data.set("noupdate", "1")

    cuentas_without_parents = _read_file()
    cuentas_with_parents = _calculate_parent_id(cuentas_without_parents)

    # len 3 = (Name, code, report_type)
    # len 4 = (Name, close_method, report_type, "")
    accounts = [
        ("Income View", "view", "income"), # A cobrar
        ("Expense View", "expense", "expense"), # A pagar
        ("Asset View", "asset", "asset"), # Banco
        ("Liability View", "liability", "liability"), # Egreso
        ("Tax", "unreconciled", "expense", ""), # Egreso
        ("Equity", "balance", "liability", ""), # Egreso
        ("Check", "balance", "asset", ""), # Egreso
    ]

    for account in accounts:
        _xml_record_type(account, data)
    _write_parents_xml(cuentas_with_parents, data)

    info = {
        "id" : "ve_chart_coop",
        "name" : "Venezuela Cooperative - Account",
        "account_root_id" : "account_cooperativa_0",
        "tax_code_root_id" : "",
        "bank_account_view_id" : "account_cooperativa_111201",
        "property_account_receivable" : "",
        "property_account_payable" : "",
        "property_account_expense_categ" : "",
        "property_account_income_categ" : "",
        "property_account_income_opening" : "",
        "property_account_expense_opening" : "",
        "complete_tax_set" : "False"
    }
    _xml_record_chart(info, data)

    etree.dump(openerp)
    xml_export.write(etree.tostring(openerp, pretty_print=True))
    xml_export.close()
Exemplo n.º 35
0
def main(device_ip, peer_asn, output):
    config = ConfigDictionary()
    username = config.username()
    password = config.password()

    jdev = Device(user=username, host=device_ip, password=password)
    jdev.open(gather_facts=False)
    jdev.timeout = 600
    regex_asn = ".* " + peer_asn

    try:
        resultxml = jdev.rpc.get_route_information(table='inet.0',
                                                   aspath_regex=regex_asn,
                                                   extensive=True)

    except Exception as err:
        print "CMD:"
        etree.dump(err.cmd)
        print "RSP:"
        etree.dump(err.rsp)

    jdev.close()

    sorted_routes = {}
    sorted_routes["peer"] = []
    sorted_routes["transit"] = []
    sorted_routes["customer"] = []
    sorted_routes["outofrange"] = []

    for routexml in resultxml.findall('.//rt'):
        route = RouteData(routexml)
        full_prefix = route.prefix()
        session_type = config.get_type_from_localpref(route.activelocalpref())
        sorted_routes[session_type].append(full_prefix)

    if output == 'machine':
        print json.dumps(sorted_routes)
    else:
        print "Number of routes: " + str(len(
            sorted_routes["peer"])) + " via peering, " + str(
                len(sorted_routes["customer"])) + " via customer, and " + str(
                    len(sorted_routes["transit"])
                ) + " via transit. (use -m for full output and breakdown)"
Exemplo n.º 36
0
def proc_cases(options, cred, cases):
    """
    Case-based import - single <Person> element contained within each <Case>
    """
    ticker = Ticker('cases')
    for case_elem in cases:
        try:
            assert_tag(case_elem, 'Case')
            person_elem = want_elem(case_elem, 'Person')
            synd = find_syndrome(case_elem.get('syndrome'))
            case = cases.new_case(cred, synd.syndrome_id)
            copy_node(person_elem, case.person)
            case.person.data_src = options.data_src
            case.update()
            proc_forms(options, synd, case, case_elem)
        except Exception, e:
            dump(case_elem)
            raise
            cmdcommon.abort(e)
        ticker.tick()
Exemplo n.º 37
0
def sendCmd(set_cmds, firecmd_to_router, filename, openmode, dpilog):
	commit_failed = 0
	if firecmd_to_router == 'yes':
		try:
			#Fire the commands using netconf
			cu.load(set_cmds, format='set')
			cu.commit()
		except Exception as err:
			print "CMD:"
			print etree.dump(err.cmd)
			print "RESPONSE:"
			print etree.dump(err.rsp)
			commit_failed = 1
	else:
			#Dump the output into a file
			result = open(filename, openmode)
			result.write(set_cmds)
			result.write("\n")
			result.close()
	return commit_failed
Exemplo n.º 38
0
def form(args):
    form = """<captcha xmlns="urn:xmpp:captcha">
        <x xmlns="jabber:x:data" type="form">
        <title>A form!</title>
        <instructions>Fill in the form</instructions>
        <field label="Text input" type="text_single" var="field-1"/>
        <field label="Pick one" type="list-single" var="field-2">
          <option label="First"><value>opt-1</value></option>
          <option label="Second"><value>opt-2</value></option>
        </field>
        </x>
        </captcha>"""
    f = xmpp.Message(
        to=args.frm, payload=[xmpp.simplexml.XML2Node("<body>Form attached</body>"), xmpp.simplexml.XML2Node(form)]
    )
    tree = fromstring(str(f))
    print("--form--")
    dump(tree)
    args.bot.cl.send(f)
    return "I hope you like it"
Exemplo n.º 39
0
    def make_metadata(self, echo=False):
        """Build CrossRef compliant batch of DOI metadata, and store it
        internally.

        Meant to be called before 'write_metadata'. Set echo=True
        to send doi_batch to STDOUT
        """
        self.make_head()
        self.make_body()
        if echo:
            print(xml.dump(self.doi_batch))
Exemplo n.º 40
0
def find_password(xml_string):
    root = etree.fromstring(xml_string)
    etree.dump(root)

    print(root.keys())

    if root.get('password'):
        return root.get('password')

    # check password in root
    if not root.get('password'):
        # check password in the child elements
        for num in range(len(root)):
            if len(root[num]) > 0:
                find_password(etree.tostring(root[num]))
            else:
                if 'password' in root[num].keys():
                    return root[num].get('password')
    else:
        return root.get('password')
Exemplo n.º 41
0
    def __init__(self, var_name, arg_element, connection_names):
        self.element = arg_element
        self.type = self.element.get("type")
        self.value = None
        self.name = None
        self.preprocess = None

        log.debug("Making GArg")
        log.debug(etree.dump(self.element))
        log.debug("End tree")

        log.debug("Type:", self.type)

        if self.type == "const":
            self.value = self.element.get("const")

        elif self.type == "DigitalWireInterface" \
                or self.type == "SPIInterface" \
                or self.type == "PWMInterface" \
                or self.type == "SerialInterface":

            literal = get_net_literal(self.element.get("net"), DIGITAL, connection_names)

            if literal == "None":
                literal = get_net_literal(self.element.get("net"), ANALOG, connection_names)

            self.name = (var_name + "_" + self.element.get("net")).upper()
            self.value = literal
            self.preprocess = "define"

        elif self.type == "AnalogWireInterface":
            self.name = (var_name + "_" + self.element.get("net")).upper()
            self.value = get_net_literal(self.element.get("net"), ANALOG, connection_names)
            assert self.value is not None
            self.preprocess = "define"

        elif self.type == "pointer" or self.type == "object":
            self.name = (var_name + "_" + self.element.get("class")).upper()
            self.class_name = self.element.get("class")
            self.factory_method = self.element.get("factory")
            self.preprocess = "factory"
            self.sub_args = []
            sub_arg_elements = self.element.findall("arg")

            for a in sub_arg_elements:
                self.sub_args.append(GArg(var_name, a, connection_names))

        else:
            assert False, "Unknown GArg type: " + str(self.type)

        log.debug(self.type is not None)
        assert (self.type is not None) and (self.name is not None) and (self.value is not None) and (
            self.preprocess is not None), str(self)
Exemplo n.º 42
0
def form(args):
    form = '''<captcha xmlns="urn:xmpp:captcha">
        <x xmlns="jabber:x:data" type="form">
        <title>A form!</title>
        <instructions>Fill in the form</instructions>
        <field label="Text input" type="text_single" var="field-1"/>
        <field label="Pick one" type="list-single" var="field-2">
          <option label="First"><value>opt-1</value></option>
          <option label="Second"><value>opt-2</value></option>
        </field>
        </x>
        </captcha>'''
    f = xmpp.Message(
        to=args.frm,
        payload=[xmpp.simplexml.XML2Node('<body>Form attached</body>'),
                 xmpp.simplexml.XML2Node(form)])
    tree = fromstring(str(f))
    print("--form--")
    dump(tree)
    args.bot.cl.send(f)
    return "I hope you like it"
Exemplo n.º 43
0
    def build_board_configuration_block(self):
        """
        Create wrapper for generation information about the current configuration
        """
        print('build_board_configuration_block: gen_num live_cells', self.gen_num, self.live_cells)  # TRACE DEBUG
        if self.blocks_wrapper is None:
            self.build_blocks_wrapper()
        blk = ET.Element(self.TAG_BLOCKS)
        blk.set(self.ATR_ID, random_id())
        gens = ET.SubElement(blk, self.TAG_GENERATIONS)
        gens.set(self.ATR_NEIGHBOURHOOD, self.GOL_NEIGHBOURHOOD)
        self.set_max_neighourhood()
        self.locate_board_neighbourhood()
        print('board_neighbourhood', self.board_bounding_box)  # DEBUG
        print(self.board[2])  # DEBUG

        self.active_block = blk
        self.gen_wrapper = gens

        ET.dump(self.blocks_wrapper)  # DEBUG
        ET.dump(blk)  # DEBUG
Exemplo n.º 44
0
    def create_fugitive_from_page(self, document, url):
        """
        Scrape HTML for fugitive info
        """
        tables = document.xpath(CSSSelector("table").path)

        if len(tables) != 2:
            print dump(tables[0])
            raise Exception("Expected two tables on detail page [%s]" % url)

        personal = tables[0]
        name, sex, race, dob, addr, junk = personal.xpath( CSSSelector('tr').path )
        name = name.xpath('td')[-1].text.strip()
        sex = sex.xpath('td')[-1].text.strip()
        race = race.xpath('td')[-1].text.strip()
        addr = addr.xpath('td')[-1].text.strip()
        dob = dob.xpath('td')[-1].text.strip()
        m,d,y = dob.split("/")
        dob = "%s-%s-%s" % (y,m,d)
        fugitive = (url, name, dob, sex, race, addr)
        return fugitive
Exemplo n.º 45
0
def main(device_ip, peer_asn, output):
    config = ConfigDictionary()
    username = config.username()
    password = config.password()

    jdev = Device(user=username, host=device_ip, password=password)
    jdev.open(gather_facts=False)
    jdev.timeout = 600
    regex_asn = ".* " + peer_asn

    try:
        resultxml = jdev.rpc.get_route_information(table='inet.0',
                                                   aspath_regex=regex_asn,
                                                   extensive=True)

    except Exception as err:
        print "CMD:"
        etree.dump(err.cmd)
        print "RSP:"
        etree.dump(err.rsp)

    jdev.close()

    sorted_routes = {}
    sorted_routes["peer"] = []
    sorted_routes["transit"] = []
    sorted_routes["customer"] = []
    sorted_routes["outofrange"] = []

    for routexml in resultxml.findall('.//rt'):
        route = RouteData(routexml)
        full_prefix = route.prefix()
        session_type = config.get_type_from_localpref(route.activelocalpref())
        sorted_routes[session_type].append(full_prefix)

    if output == 'machine':
        print json.dumps(sorted_routes)
    else:
        print "Number of routes: " + str(len(sorted_routes["peer"])) + " via peering, " + str(len(sorted_routes["customer"])) + " via customer, and " + str(len(sorted_routes["transit"])) + " via transit. (use -m for full output and breakdown)"
Exemplo n.º 46
0
def strip_status(format):
    strips = PowerUSBStrip.strips()
    
    if format == "text":
        print "%d device(s) connected" % len(strips)
        for i in range(0, len(strips)):
            strip = strips[i]
            strip.open()
            print "%d) %s" % (i, strip)
            strip.close()

    elif format == "xml":
        
        stripxml = etree.Element("powerstrips")
        for i in range(0, len(strips)):
            strip = strips[i]
            strip.open()
            stripxml.append(strip.xml())
            strip.close()

        etree.dump(stripxml, pretty_print=True)
        print ""
Exemplo n.º 47
0
def BuildAccountSummary(xmlstring):
    
    acct_data = [] 
    
    # extract card_nbr, card_PIN from XML data
    card_nbr = getTagContent(xmlstring, XML_CARD_NBR)

    if my_debug2:
        print('* BuildAccountSummary: returned accountNbr data:')
        for x in acct_data:
            print(x)

    if my_debug2:
        for obj in acct_data:
            print(" * acct_data: ", obj.acctNumber, obj.acctType, obj.acctBalance, obj.acctName)
    
    # Build XML message
    xmlmessage = etree.Element(MESSAGE_ID)
    xmlmessage.text = ACCOUNT_SUMMARY

    # add card number
    xmlcard_nbr = etree.SubElement(xmlmessage, XML_CARD_NBR)
    xmlcard_nbr.text = str(card_nbr)
    
    # loop through the card data and build the XML message
    # note: the text for XML_ACCT_COLLECTION must be done in 2 steps; can't do
    # a double assignment in one statement
    acct = etree.SubElement(xmlmessage, XML_ACCT_COLLECTION)
    for a in acct_data:
        etree.SubElement(acct, XML_FROM_ACCT_NBR).text = str(a.acctNumber)
        etree.SubElement(acct, XML_ACCT_TYPE).text = a.acctType
        etree.SubElement(acct, XML_ACCT_BAL).text = str(a.acctBalance)
        etree.SubElement(acct, XML_ACCT_NAME).text = a.acctName

    if my_debug2:
        print('* BuildAccountSummary:')
        etree.dump(xmlmessage)

    return etree.tostring(xmlmessage, encoding='UTF-8', method='xml') 
Exemplo n.º 48
0
def strip_status(format):
    strips = PowerUSBStrip.strips()

    if format == "text":
        print "%d device(s) connected" % len(strips)
        for i in range(0, len(strips)):
            strip = strips[i]
            strip.open()
            print "%d) %s" % (i, strip)
            strip.close()

    elif format == "xml":

        stripxml = etree.Element("powerstrips")
        for i in range(0, len(strips)):
            strip = strips[i]
            strip.open()
            stripxml.append(strip.xml())
            strip.close()

        etree.dump(stripxml, pretty_print=True)
        print ""
def main():
    list_peeringdbid_of_connected_exchanges = []

    config = ConfigDictionary("/home/andy/etc/pypeer.ini")
    username = config.username()
    password = config.password()
    exchange = Exchange()
    peeringdb = PeeringDBClient()

    for router in config.get_list_of_router_names():
        jdev = Device(user=username, host=config.get_router_ip(router),
                      password=password)
        jdev.open(gather_facts=False)
        jdev.timeout = 600

        try:
            resultxml = jdev.rpc.get_bgp_summary_information()
        except Exception as err:
            print "CMD:"
            etree.dump(err.cmd)
            print "RSP:"
            etree.dump(err.rsp)

        bgpsum = BgpData(resultxml)
        for thispeeringip in bgpsum.get_list_peering_ips():
            if not is_valid_ipv4_address(thispeeringip):
                next
            else:
                peeringdb_id = exchange.get_exchange_from_peerip(thispeeringip)['peeringdbid']
                if peeringdb_id==0:
                    next 
                elif peeringdb_id in list_peeringdbid_of_connected_exchanges:
                    next
                else:
                    list_peeringdbid_of_connected_exchanges.append(peeringdb_id)
                    ixpjson      = peeringdb.ixlan(peeringdb_id)
                    ixpparser    = PeeringDBParser(ixpjson)
                    print "%s: %s   # %s" % (peeringdb_id, router, ixpparser.get_name_of_ixorg_from_ixlan())
Exemplo n.º 50
0
 def get_rcp_command(self, command, get_xml=False):
     """
     Converts a junos cli command to its rpc equivalent
     :param command: junos command to convert
     :param get_xml: return command as xml tree
     :return: returns rpc comamnd as a string
     """
     result = self.conn.display_xml_rpc(command)
     if 'invalid command' in result:
         return 'Invalid command: {0}'.format(command)
     else:
         if get_xml:
             return etree.dump(result)
         return result.tag.replace('-', '_')
Exemplo n.º 51
0
    def gatePinToPad (self, part, gate, pin):
        debug = False
        
        log.debug("Mapping pin to pad.")
        part = self.getParts().find("part/[@name='"+part+"']")
        ET.dump(part)
        
        
        lib_name = part.get("library")
        deviceset_name = part.get("deviceset")

        if (deviceset_name is None): return None
        
        device_name = part.get("device")

        if (device_name is None): return None
        
        # check for dummy part, like ground symbol
        
        
        
        log.debug("Libraries available:")

        log.debug("libs:")
        #ET.dump(self.getLibraries())

        for l in self.getLibraries().findall("*"):
            log.debug(l.get("name"))
            
        log.debug("Looking for library:" +  lib_name)
        log.debug("xpath:" + "library/[@name='"+lib_name+"']")
        lib = self.getLibraries().find("library/[@name='"+lib_name+"']")
        log.debug("Got:" +  lib)
        
        log.debug("Looking for deviceset:" +  deviceset_name)
        deviceset = lib.find("devicesets/deviceset/[@name='"+deviceset_name+"']")
        log.debug("Got:" + deviceset)
        
        log.debug("Want:"+ device_name)
        device = deviceset.find("devices/device/[@name='"+device_name+"']")
        log.debug("Got:" + device)
        
        ET.dump(device)
        if device is None:
            device = deviceset.find("devices/device/[@name='"+device_name.upper()+"']")
            
        assert device is not None, "Could not find device: "+device_name+" in library: "+lib_name+" in deviceset:"+deviceset_name
        
        connect = device.find("connects/connect/[@gate='"+gate+"'][@pin='"+pin+"']")
        if connect is None: return None
        ET.dump(connect)
        
        pad = connect.get("pad")
        
        log.debug("Pad:" +  pad)
        
        return pad
Exemplo n.º 52
0
 def dump_xml(self):
     """
     Debugging aid to dump XML so that we can see what we have.
     """
     return etree.dump(self.song_xml)
Exemplo n.º 53
0
 def convert_default(self, node):
     print "Unimplemented element %s. Skipped." % (node.tag)
     dump(node)
     return self.convert_text_tail(node)
Exemplo n.º 54
0
# showing command: 'show version'

# Hostname: jnpr-dc-fw
# Model: junosv-firefly
# JUNOS Software Release [12.1X44-D10.4]


# you can also obtain the XML RPC for the associated command by
# doing this:

print "showing as XML RPC command:"
xml_cmd = jdev.cli("show version | display xml rpc")

# this is an actual XML element, so we can dump it for debug:
etree.dump(xml_cmd)

# showing as XML RPC command:
# <get-software-information>
# </get-software-information>

# you can then take that output then feed it back into the :rpc: metaexec

cmd_rsp = jdev.rpc(xml_cmd)

# now dump the XML response output;

print "showing as XML RPC response:"
etree.dump(cmd_rsp)

# showing as XML RPC response:
Exemplo n.º 55
0
def main(cuentas):
    openerp = etree.Element("openerp")
    data = etree.SubElement(openerp, "data")
    data.set("noupdate", "1")

    accounts = [
        ("Income View", "view", "income"), # A cobrar
        ("Expense View", "expense", "expense"), # A pagar
        ("Asset View", "asset", "asset"), # Banco
        ("Liability View", "liability", "liability"), # Egreso
        ("Tax", "unreconciled", "expense", ""), # Egreso
        ("Equity", "balance", "liability", ""), # Egreso
        ("Check", "balance", "asset", ""), # Egreso
    ]

    for account in accounts:
        _xml_record_type(account, data)

    _write_parents_xml(cuentas, data)

    cuentas_de_impuesto = [
            {'id' : 'iva', 'code' : '7.1.2', 'parent_id' : '71', 'name' : 'IVA', 'type' : 'other', 'user_type' : 7, 'reconcile' : 'True'},
    ]

    _write_parents_xml(cuentas_de_impuesto, data)

    codigos_de_impuestos =[
        #Impuesto de Facturas
            {"id" : "tax_code_coop", "name" : "Impuestos Cooperativas"},
            {"id" : "tax_code_balance_coop", "name" : "Balance de Impuestos", "parent_id" : "tax_code_coop"},
            #Impuesto Recibido
            {"id" : "tax_code_input" ,  "name" : "Impuesto Recibido", "parent_id" : "tax_code_balance_coop", "sign" : "-1"},
            {"id" : "tax_code_input_v", "name" : "Impuesto Recibido por Ventas",  "parent_id" : "tax_code_input"},
            #Impuesto Pagado
            {"id" : "tax_code_output" ,  "name" : "Impuesto Pagado", "parent_id" : "tax_code_balance_coop"},
            {"id" : "tax_code_output_c", "name" : "Impuesto Pagado por Compras",  "parent_id" : "tax_code_output"},
        #Base de Impuestos
            {"id" : "tax_code_base_coop", "name" : "Base de Impuestos", "parent_id" : "tax_code_coop"},
            #Base impuesto por compras
            {"id" : "tax_code_compras", "name" : "Impuesto por Compras", "parent_id" : "tax_code_base_coop"},
            {"id" : "tax_code_compras_12", "name" : "Impuesto 12%", "parent_id" : "tax_code_compras"},
            #Base de impuesto por ventas
            {"id" : "tax_code_ventas", "name" : "Impuesto por Ventas", "parent_id" : "tax_code_base_coop"},
            {"id" : "tax_code_ventas_0", "name" : "Impuesto 0%", "parent_id" : "tax_code_ventas"},
    ]

    for cdi in codigos_de_impuestos:
        _tax_code_template(cdi, data)

    info = {
        "id" : "ve_chart_coop",
        "name" : "Venezuela Cooperative - Account",
        "account_root_id" : "account_cooperativa_0",
        "tax_code_root_id" : "tax_code_coop",
        "bank_account_view_id" : "account_cooperativa_111201",
        "property_account_receivable" : "account_cooperativa_113101",
        "property_account_payable" : "account_cooperativa_212106",
        "property_account_expense_categ" : "account_cooperativa_511101",
        "property_account_income_categ" : "account_cooperativa_412101",
        "property_account_income_opening" : "",
        "property_account_expense_opening" : "",
        "complete_tax_set" : "True"
    }
    _xml_record_chart(info, data)

    impuestos = [
            #Impuesto 12%
            {'id' : "imp_compras_12", 'ref' : "ve_chart_coop", 'code' : 'impuesto_compras_12', 'name' : 'Impuesto para compras 12%', "eval" : "0.12", "type" : "percent", "account_collected_id" : "account_cooperativa_iva", "account_paid_id" : "account_cooperativa_iva", "base_code_id" : "tax_code_compras_12", "tax_code_id" : "tax_code_output_c", "ref_base_code_id" : "tax_code_compras_12", "ref_tax_code_id" : "tax_code_output_c", "type_tax_use" : "purchase"},
            #Impuesto 0%
            {'id' : "imp_ventas_0", 'ref' : "ve_chart_coop", 'code' : 'impuesto_ventas_0', 'name' : 'Impuesto para ventas 0%', "eval" : "0", "type" : "percent", "account_collected_id" : "account_cooperativa_iva", "account_paid_id" : "account_cooperativa_iva", "base_code_id" : "tax_code_ventas_0", "tax_code_id" : "tax_code_input_v", "ref_base_code_id" : "tax_code_ventas_0", "ref_tax_code_id" : "tax_code_input_v", "type_tax_use" : "sale"},
    ]

    for imp in impuestos:
        _tax_template(imp, data)

    #Fiscal Mapping
    fiscal_mapping = {"id" : "imp_fiscal_coop", "name" : "Impuesto Normal Cooperativas", "chart_template_id" : "ve_chart_coop"}

    _fiscal_mapping_template(fiscal_mapping, data)

    #Fiscal Taxes
    imp_fiscal = [
            {"id" : "imp_normal_coop", "position_id" : "imp_fiscal_coop", "tax_src_id" : "tax_cooperativa_imp_compras_12", "tax_dest_id" : "tax_cooperativa_imp_ventas_0" },
    ]

    for imf in imp_fiscal:
        _imp_fiscal_template(imf, data)

    etree.dump(openerp)
    xml_export.write(etree.tostring(openerp, pretty_print=True))
    xml_export.close()
Exemplo n.º 56
0
    measures = []
    for i, each_measure in enumerate(source.split('|')):
        elem = do_measure(each_measure)
        if elem is not None:
            elem.set('n', str(i + 1))
            measures.append(elem)

    # falsify everything into a valid structure
    section = ETree.Element('{}section'.format(_MEINS))
    [section.append(x) for x in measures]
    score = ETree.Element('{}score'.format(_MEINS))
    score.append(section)
    mdiv = ETree.Element('{}mdiv'.format(_MEINS))
    mdiv.append(score)
    body = ETree.Element('{}body'.format(_MEINS))
    body.append(mdiv)
    music = ETree.Element('{}music'.format(_MEINS))
    music.append(body)
    mei_elem = ETree.Element('{}mei'.format(_MEINS), {'meiversion': '2013'})
    mei_elem.append(music)

    print('here it is!\n')
    ETree.dump(mei_elem)

    print('\noutputting!\n')
    whole_doc = ETree.ElementTree(mei_elem)
    whole_doc.write('test_file.mei',
                    encoding='UTF-8',
                    xml_declaration=True,
                    pretty_print=True)