예제 #1
0
    def _insert_node(self, root, k, v, key_attr=None):
        element = SubElement(root, k)
        if v is None:
            element.attrib[u'xsi:nil'] = u'true'
        elif not isinstance(v, (list, dict)):
            element.text = text_type(v)
        else:
            if isinstance(v, list):
                it = enumerate(v)
            else:
                it = v.items()
            for key, value in it:
                self._insert_node(element, self._value_tag, value, key)

        if key_attr is not None:
            element.attrib[self._key_attr] = text_type(key_attr)
예제 #2
0
def _classify_subgroup(elements: list,
                       row: Element,
                       is_math_mode: bool = False) -> None:
    iterable = iter(range(len(elements)))
    for i in iterable:
        element = elements[i]
        if isinstance(element, list):
            _row = SubElement(row, "mrow")
            _classify_subgroup(element, _row, is_math_mode)
            is_math_mode = False
        elif element in COMMANDS:
            _convert_command(element, elements, i, iterable, row)
        elif element.startswith(r"\math"):
            is_math_mode = True
        else:
            _classify(element, row, is_math_mode)
예제 #3
0
 def create_listing(self, req, out_content_type, info, metadata,
                    container_list, container):
     list_meta = get_param(req, 'list_meta', 'f').lower() in TRUE_VALUES
     resp_headers = {
         'X-Container-Object-Count': info['object_count'],
         'X-Container-Bytes-Used': info['bytes_used'],
         'X-Timestamp': info['created_at'],
         'X-PUT-Timestamp': info['put_timestamp'],
     }
     for key, (value, timestamp) in metadata.iteritems():
         if value and (key.lower() in self.save_headers or
                       is_sys_or_user_meta('container', key)):
             resp_headers[key] = value
     ret = Response(request=req, headers=resp_headers,
                    content_type=out_content_type, charset='utf-8')
     if out_content_type == 'application/json':
         ret.body = json.dumps([self.update_data_record(record, list_meta)
                                for record in container_list])
     elif out_content_type.endswith('/xml'):
         doc = Element('container', name=container.decode('utf-8'))
         for obj in container_list:
             record = self.update_data_record(obj, list_meta)
             if 'subdir' in record:
                 name = record['subdir'].decode('utf-8')
                 sub = SubElement(doc, 'subdir', name=name)
                 SubElement(sub, 'name').text = name
             else:
                 obj_element = SubElement(doc, 'object')
                 for field in ["name", "hash", "bytes", "content_type",
                               "last_modified"]:
                     SubElement(obj_element, field).text = str(
                         record.pop(field)).decode('utf-8')
                 for field in sorted(record):
                     if list_meta and field == 'metadata':
                         meta = SubElement(obj_element, field)
                         for k, v in record[field].iteritems():
                             SubElement(meta, k).text = str(
                                 v.decode('utf-8'))
                     else:
                         SubElement(obj_element, field).text = str(
                             record[field]).decode('utf-8')
         ret.body = tostring(doc, encoding='UTF-8').replace(
             "<?xml version='1.0' encoding='UTF-8'?>",
             '<?xml version="1.0" encoding="UTF-8"?>', 1)
     else:
         if not container_list:
             return HTTPNoContent(request=req, headers=resp_headers)
         ret.body = '\n'.join(rec[0] for rec in container_list) + '\n'
     return ret
예제 #4
0
    def __init__(self,
                 graph=None,
                 encoding='utf-8',
                 prettyprint=True,
                 version='1.2draft'):
        try:
            import xml.etree.ElementTree as ET
        except ImportError:
            raise ImportError('GEXF writer requires '
                              'xml.elementtree.ElementTree')
        self.prettyprint = prettyprint
        self.encoding = encoding
        self.set_version(version)
        self.xml = Element(
            'gexf', {
                'xmlns': self.NS_GEXF,
                'xmlns:xsi': self.NS_XSI,
                'xsi:schemaLocation': self.SCHEMALOCATION,
                'version': self.VERSION
            })

        # Make meta element a non-graph element
        # Also add lastmodifieddate as attribute, not tag
        meta_element = Element('meta')
        subelement_text = 'NetworkX {}'.format(nx.__version__)
        SubElement(meta_element, 'creator').text = subelement_text
        meta_element.set('lastmodifieddate', time.strftime('%Y-%m-%d'))
        self.xml.append(meta_element)

        ET.register_namespace('viz', self.NS_VIZ)

        # counters for edge and attribute identifiers
        self.edge_id = itertools.count()
        self.attr_id = itertools.count()
        self.all_edge_ids = set()
        # default attributes are stored in dictionaries
        self.attr = {}
        self.attr['node'] = {}
        self.attr['edge'] = {}
        self.attr['node']['dynamic'] = {}
        self.attr['node']['static'] = {}
        self.attr['edge']['dynamic'] = {}
        self.attr['edge']['static'] = {}

        if graph is not None:
            self.add_graph(graph)
예제 #5
0
    def export_data(self, db, file, nodeids):
        nodeids = db.listnodes()

        nodes = db.getnodes(nodeids)
        root = Element("PwmanXmlList", version="3.0")
        for n in nodes:
            sub = SubElement(root, "Node")
            SubElement(sub, "username").text = n.get_username()
            SubElement(sub, "password").text = n.get_password()
            SubElement(sub, "url").text = n.get_url()
            SubElement(sub, "notes").text = n.get_notes()
            tagelement = SubElement(sub, "tags")
            for t in n.get_tags():
                SubElement(tagelement, "name").text = t.get_name()

        ElementTree(root).write(file)
예제 #6
0
파일: converter.py 프로젝트: ACAA06/Sympy
def _convert_command(
    element: str,
    elements: List[Any],
    index: int,
    iterable: Iterator[int],
    parent: Element,
):
    _get_prefix_element(element, parent)
    if element == r"\substack":
        parent = SubElement(parent, "mstyle", scriptlevel="1")
    params, tag, attributes = COMMANDS[element]
    new_parent = SubElement(parent, tag, attributes)
    alignment = ""
    if element in MATRICES and (element.endswith("*") or element == r"\array"):
        index += 1
        alignment = elements[index]
        next(iterable)
    if element in (r"\lim", r"\inf", r"\sup", r"\max", r"\min"):
        limit = SubElement(new_parent, "mo")
        limit.text = element[1:]
    for j in range(params):
        index += 1
        param = elements[index]
        if element == "_" and index == 1 and param == r"\sum":
            new_parent.tag = "munder"
            _classify(param, new_parent)
        elif element == r"\left" or element == r"\right":
            if param == ".":
                pass
            else:
                symbol = convert_symbol(param)
                new_parent.text = param if symbol is None else "&#x{};".format(
                    symbol)
        elif element == r"\array":
            _convert_array_content(param, new_parent, alignment)
        elif element in MATRICES:
            _convert_matrix_content(param, new_parent, alignment,
                                    element == r"\substack")
        else:
            if isinstance(param, list):
                _parent = SubElement(new_parent, "mrow")
                _classify_subgroup(param, _parent)
            else:
                _classify(param, new_parent)
    _get_postfix_element(element, parent)
    if element in (r"\overline", r"\bar"):
        mo = SubElement(new_parent, "mo", stretchy="true")
        mo.text = "&#x000AF;"
    elif element == r"\underline":
        mo = SubElement(new_parent, "mo", stretchy="true")
        mo.text = "&#x00332;"
    [next(iterable) for _ in range(params)]
예제 #7
0
 def process_row(self, row):
     if not row.vmdb_id in self.instance.keys():
         self.add_station(row.vmdb_id, row.station_name)
     if not row.data_time in self.resultOf[row.vmdb_id].keys():
         self.add_timestamp(row.vmdb_id, row.data_time)
     if row.data_symbol in (
             'WDM',
             'WD',
             'RH',
             'VI',
     ):
         value = str(int(row.data_value))
     else:
         value = str(row.data_value)
     SubElement(self.resultOf[row.vmdb_id][row.data_time],
                "value",
                code=row.data_symbol,
                no=str(row.data_number)).text = value
예제 #8
0
    async def send_xml(self, xml_dict):
        data_root = Element('msg')
        data_root.set('t', 'sys')

        sub_element_parent = data_root
        for sub_element, sub_element_attribute in xml_dict.items():
            sub_element_object = SubElement(sub_element_parent, sub_element)

            if type(xml_dict[sub_element]) is dict:
                for sub_element_attribute_key, sub_element_attribute_value in xml_dict[sub_element].items():
                    sub_element_object.set(sub_element_attribute_key, sub_element_attribute_value)
            else:
                sub_element_object.text = xml_dict[sub_element]

            sub_element_parent = sub_element_object

        xml_data = tostring(data_root)
        await self.send_line(xml_data.decode('utf-8'))
예제 #9
0
 def process_row(self, row):
     formatted_value = format_value(row.data_value, row.data_symbol)
     if formatted_value is None:
         return None
     self.update_datex2index(row.vmdb_id, row.data_time, row.datex_id, row.data_number)
     if (row.vmdb_id, row.data_time) not in self.resultOf:
         measurements = SubElement(self.payload, "siteMeasurements")
         SubElement(measurements, "measurementSiteReference", targetClass="MeasurementSiteRecord", id="GB_HA_%i" % row.vmdb_id)
         SubElement(measurements, "measurementTimeDefault").text = row.data_time.strftime('%Y-%m-%dT%H:%M:%S+00:00')
         self.resultOf[(row.vmdb_id, row.data_time)] = SubElement(measurements, "siteMeasurementsExtension")
     metdata = SubElement(self.resultOf[(row.vmdb_id, row.data_time)], "metData", index=str(row.datex_id))
     metdata.attrib['xsi:type'] = row.xsitype
     innertag = SubElement(metdata, row.xmltagname)
     innertag.text = formatted_value
예제 #10
0
def _convert_group(nodes: Iterable[Node], parent: Element, font: Optional[Dict[str, Optional[str]]] = None) -> None:
    _font = font
    for node in nodes:
        token = node.token
        if token in (*commands.MSTYLE_SIZES, *commands.STYLES):
            node = Node(token=token, children=tuple(n for n in nodes))
            _convert_command(node, parent, _font)
        elif token in commands.CONVERSION_MAP or token in (commands.MOD, commands.PMOD):
            _convert_command(node, parent, _font)
        elif token in commands.LOCAL_FONTS and node.children is not None:
            _convert_group(iter(node.children), parent, commands.LOCAL_FONTS[token])
        elif token.startswith(commands.MATH) and node.children is not None:
            _convert_group(iter(node.children), parent, _font)
        elif token in commands.GLOBAL_FONTS.keys():
            _font = commands.GLOBAL_FONTS.get(token)
        elif node.children is None:
            _convert_symbol(node, parent, _font)
        elif node.children is not None:
            attributes = node.attributes or {}
            _row = SubElement(parent, "mrow", attrib=attributes)
            _convert_group(iter(node.children), _row, _font)
예제 #11
0
def _append_postfix_element(node: Node, parent: Element) -> None:
    size = "2.047em"
    if parent.attrib.get("displaystyle") == "false" or node.token == commands.TBINOM:
        size = "1.2em"
    if node.token in (r"\pmatrix", commands.PMOD):
        _convert_and_append_command(r"\rparen", parent)
    elif node.token in (commands.BINOM, commands.DBINOM, commands.TBINOM):
        _convert_and_append_command(r"\rparen", parent, {"minsize": size, "maxsize": size})
    elif node.token == r"\bmatrix":
        _convert_and_append_command(r"\rbrack", parent)
    elif node.token == r"\Bmatrix":
        _convert_and_append_command(r"\rbrace", parent)
    elif node.token == r"\vmatrix":
        _convert_and_append_command(r"\vert", parent)
    elif node.token == r"\Vmatrix":
        _convert_and_append_command(r"\Vert", parent)
    elif node.token in (commands.FRAC, commands.GENFRAC) and node.delimiter is not None and node.delimiter[1] != ".":
        # TODO: use 1.2em if inline
        _convert_and_append_command(node.delimiter[1], parent, {"minsize": size, "maxsize": size})
    elif node.token == commands.SKEW and node.attributes is not None:
        SubElement(parent, "mspace", width="-" + node.attributes["width"])
예제 #12
0
    def hazardDetails(self, details, atts):
        root = Element('ihis')
        ele = SubElement(root, "hazard_details")
        self._addAttributes(ele, atts)
        if details is not None:
            for hazCode, actions, category in details:
                pe = SubElement(ele, "hazard_detail")
                hazCodeE = SubElement(pe, "hazard_code")
                hazCodeE.text = hazCode
                ae = SubElement(pe, "action_codes")
                for action in actions:
                    ase = SubElement(ae, "action_code")
                    ase.text = action
                ce = SubElement(pe, "hazard_category")
                ce.text = category

        return ElementTree.tostring(root)
예제 #13
0
    def _create_service_list(self):
        device_services = self.device.services
        if len(device_services) > 0:
            service_list_element = SubElement(self.device_element,
                                              "serviceList")
            for k, device_service in device_services.items():
                service_element = SubElement(service_list_element, "service")
                element = SubElement(service_element, "serviceType")
                element.text = device_service.service_type

                element = SubElement(service_element, "serviceId")
                element.text = device_service.id

                element = SubElement(service_element, "SCPDURL")
                element.text = device_service.scpd_url

                element = SubElement(service_element, "controlURL")
                element.text = device_service.control_url

                element = SubElement(service_element, "eventSubURL")
                element.text = device_service.event_sub_url

                element = SubElement(service_element, "presentationURL")
                element.text = device_service.presentation_url
예제 #14
0
파일: tei.py 프로젝트: karlb/wikdict-gen
def single_tei_entry(x, to_lang):
    # entry
    entry = Element("entry")
    form = SubElement(entry, "form")
    orth = SubElement(form, "orth")
    if x["pronuns"]:
        for p in x["pronuns"]:
            pron = SubElement(form, "pron")
            pron.text = p
    is_suffix = x["part_of_speech"] == "suffix" or (
        x["part_of_speech"] in ("", None) and x["written_rep"].startswith("-")
    )
    if is_suffix:
        # assert x['written_rep'].startswith('-')
        orth.text = x["written_rep"][1:]
        pos_text = "suffix"
    else:
        orth.text = x["written_rep"]
        pos_text = pos_mapping.get(x["part_of_speech"], (x["part_of_speech"], None))[0]

    # inflected forms
    if x["inflected_forms"]:
        infl_form = SubElement(form, "form", {"type": "infl"})
        for infl_form_row in x["inflected_forms"]:
            attrs = {"wikdict:show": "true"} if infl_form_row["rank"] else {}
            SubElement(infl_form, "orth", attrs).text = infl_form_row["other_written"]

    # gramGrp
    gram_grp = Element("gramGrp")
    if pos_text:
        pos = SubElement(gram_grp, "pos")
        pos.text = pos_text
    if x["gender"]:
        gen = SubElement(gram_grp, "gen")
        gen.text = gender_mapping[x["gender"].lower()]
    if list(gram_grp):
        entry.append(gram_grp)

    add_senses(entry, x, to_lang, is_suffix)

    return entry
예제 #15
0
def updateXMLbbox(xml_path, to_xml_path, addbox):
    tree = ET.parse(xml_path)
    root = tree.getroot()
    node_object = Element('object')
    node_name = SubElement(node_object, 'name')
    node_name.text = 'hand'
    node_difficult = SubElement(node_object, 'difficult')
    node_difficult.text = '0'
    node_difficult = SubElement(node_object, 'flag')
    node_difficult.text = '0'
    node_bndbox = SubElement(node_object, 'bndbox')
    node_xmin = SubElement(node_bndbox, 'xmin')
    node_xmin.text = str(int(addbox[0]))
    node_ymin = SubElement(node_bndbox, 'ymin')
    node_ymin.text = str(int(addbox[1]))
    node_xmax = SubElement(node_bndbox, 'xmax')
    node_xmax.text = str(int(addbox[2]))
    node_ymax = SubElement(node_bndbox, 'ymax')
    node_ymax.text = str(int(addbox[3]))
    root.append(node_object)
    tree.write(os.path.join(to_xml_path,
                            xml_path.split('/')[-1]),
               encoding='utf-8')
    return True
예제 #16
0
    def _create_icon_list(self):
        #<device><iconList>
        device_icons = self.device.icons
        if len(device_icons) > 0:
            icon_list_element = SubElement(self.device_element, "iconList")
            for device_icon in device_icons:
                icon_element = SubElement(icon_list_element, "icon")
                element = SubElement(icon_element, "mimetype")
                element.text = device_icon.get_mimetype()

                element = SubElement(icon_element, "width")
                element.text = device_icon.get_width()

                element = SubElement(icon_element, "height")
                element.text = device_icon.get_height()

                element = SubElement(icon_element, "depth")
                element.text = device_icon.get_depth()

                element = SubElement(icon_element, "url")
                element.text = device_icon.get_url()
예제 #17
0
    def asXml(self, parentnode, authed=False):
        from xml.etree.cElementTree import SubElement
        me = SubElement(parentnode, "user")
        xmlpopulate(me, self.player_obj)

        if authed:
            me.set("x_addrstring", self.ipaddress)
        else:
            me.set("address", "")

        if self.channel.server.hasUserTexture(self.userid):
            from views import showTexture
            from django.core.urlresolvers import reverse
            textureurl = reverse(showTexture,
                                 kwargs={
                                     'server': self.channel.server.id,
                                     'userid': self.userid
                                 })
            me.set('x_texture',
                   "http://" + Site.objects.get_current().domain + textureurl)

        if self.mumbleuser and self.mumbleuser.gravatar:
            me.set('x_gravatar', self.mumbleuser.gravatar)
예제 #18
0
def WriteDialogToFile(filename, props):
    """Write the props to the file

    props can be either a dialog of a dictionary
    """
    # if we are passed in a wrapped handle then
    # get the properties
    try:
        props[0].keys()
    except (TypeError, AttributeError):
        props = controls.GetDialogPropsFromHandle(props)

    # build a tree structure
    root = Element("DIALOG")
    root.set("_version_", "2.0")
    for ctrl in props:
        ctrlelem = SubElement(root, "CONTROL")
        for name, value in sorted(ctrl.items()):
            _SetNodeProps(ctrlelem, name, value)

    # wrap it in an ElementTree instance, and save as XML
    tree = ElementTree(root)
    tree.write(filename, encoding="utf-8")
예제 #19
0
    def to_xml(self, xml_doc=None):
        """
        This method returns the xml element node for the current object
        with it's hierarchy.

        Args:
            xml_doc: document to which the Mo attributes are added.
                    Can be None.
            option: not required for Generic Mo class object

        Example:
            from ucsmsdk.ucsmo import GenericMo\n
            args = {"a": 1, "b": 2, "c":3}\n
            obj = GenericMo("testLsA", "org-root", **args)\n
            obj1 = GenericMo("testLsB", "org-root", **args)\n
            obj.add_child(obj1)\n
            elem = obj.write_xml()\n

            import ucsmsdk.ucsxmlcodec as xc\n
            xc.to_xml_str(elem)\n

        Output:
            '<testLsA a="1" b="2" c="3" dn="org-root/" rn="">\n
                <testLsB a="1" b="2" c="3" dn="org-root/" rn="" />\n
            </testLsA>'
        """

        if xml_doc is None:
            xml_obj = Element(ucscentralgenutils.word_l(self._class_id))
        else:
            xml_obj = SubElement(xml_doc,
                                 ucscentralgenutils.word_l(self._class_id))
        for key in self.__dict__:
            if not key.startswith('_'):
                xml_obj.set(key, getattr(self, key))
        self.child_to_xml(xml_obj)
        return xml_obj
예제 #20
0
    def generate(self, tasks):
        top = Element('pnml')

        child = SubElement(top, 'net',
                           attrib={'id': "net1", 'type': "http://www.pnml.org/version-2009/grammar/pnmlcoremodel"})

        page = SubElement(child, 'page',
                          attrib={'id': "n0"})
        index = 0
        for task in tasks:
            place = SubElement(page, 'place',
                               attrib={'id': "p" + str(index)})

            name = SubElement(place, 'name')
            text = SubElement(name, 'text')
            text.text = task.name
            index += 1

        finalmarkings = SubElement(child, 'finalmarkings')
        markings = SubElement(finalmarkings, 'markings')
        tree = ElementTree(top)
        return prettify(top)
예제 #21
0
def _classify(_element: str,
              parent: Element,
              is_math_mode: bool = False) -> None:
    symbol = convert_symbol(_element)
    if re.match(r"\d+(.\d+)?", _element):
        mn = SubElement(parent, "mn")
        mn.text = _element
    elif len(_element) and _element in "<>&":
        mo = SubElement(parent, "mo")
        mo.text = {"<": "&lt;", ">": "&gt;", "&": "&amp;"}[_element]
    elif len(_element) and _element in "+-*/()=":
        mo = SubElement(parent, "mo")
        mo.text = _element if symbol is None else "&#x{};".format(symbol)
        if _element in "()":
            mo.attrib["stretchy"] = "false"
    elif (symbol and (int(symbol, 16) in range(int("2200", 16),
                                               int("22FF", 16) + 1)
                      or int(symbol, 16) in range(int("2190", 16),
                                                  int("21FF", 16) + 1))
          or symbol == "."):
        mo = SubElement(parent, "mo")
        mo.text = "&#x{};".format(symbol)
    elif _element.startswith("\\"):
        tag = SubElement(parent, "mo" if is_math_mode else "mi")
        if symbol:
            tag.text = "&#x{};".format(symbol)
        elif _element in (
                r"\log",
                r"\ln",
                r"\tan",
                r"\sec",
                r"\cos",
                r"\sin",
                r"\cot",
                r"\csc",
        ):
            tag.text = _element[1:]
        else:
            tag.text = _element
    else:
        tag = SubElement(parent, "mo" if is_math_mode else "mi")
        tag.text = _element
예제 #22
0
def sitemap(all_links, url):
    split_url = url.split('://')
    urlset = Element('urlset',
                     xmlns='http://www.sitemaps.org/schemas/sitemap/0.9')
    count = 0
    while count < len(all_links):
        today = datetime.now().strftime('%Y-%M-%d')
        urls = SubElement(urlset, "url")
        if all_links[count] is None:
            SubElement(urls, "loc").text = url
        elif split_url[0] in all_links[count]:
            SubElement(urls, "loc").text = str(all_links[count])
        else:
            SubElement(urls, "loc").text = url + str(all_links[count])

        SubElement(urls, "lastmod").text = str(today)
        SubElement(urls, "priority").text = "1.00"
        count += 1
    else:
        tree = ElementTree(urlset)
        tree.write(split_url[1] + ".xml")
        print('Ваша карта сайта готова!')
        print(count, 'ссылок было найдено')
예제 #23
0
def dump_debate(debate, path, url=None):
    root = Element('debate')
    root.set('duration', str(debate.duration))
    if url:
        root.set('url', url)

    # speakers
    speakers_element = SubElement(root, 'speakers')
    for speaker in debate.speakers:
        speaker_element = SubElement(speakers_element, 'speaker')
        speaker_element.set('name', speaker.name)
        speaker_element.set('position',
                            'for' if speaker.stand_for else 'against')
        if speaker.description:
            desc_element = SubElement(speaker_element, 'description')
            desc_element.text = speaker.description

        if speaker.bio:
            bio_element = SubElement(speaker_element, 'bio')
            bio_element.text = speaker.bio

    # results
    __add_results__(root, debate.results)

    # transcript
    transcript_element = SubElement(root, 'transcript')
    for paragraph in debate.transcript_paragraphs:
        p_element = SubElement(transcript_element, 'p')
        p_element.text = paragraph.text
        p_element.set('start', str(paragraph.start_time))
        p_element.set('is_meta', str(paragraph.is_meta).lower())
        p_element.set('speaker', paragraph.speaker.name)

        if paragraph.end_time:
            p_element.set('end', str(paragraph.end_time))

    ElementTree(root).write(path)
예제 #24
0
 def add_meta(self, G, graph_element):
     # add meta element with creator and date
     meta_element = Element('meta')
     SubElement(meta_element, 'creator').text = 'NetworkX {}' % (nx.__version__,)
     SubElement(meta_element, 'lastmodified').text = time.strftime('%d/%m/%Y')
     graph_element.append(meta_element)
예제 #25
0
    def createLayout(self, elem):
        # Qt v4.3 introduced setContentsMargins() and separate values for each
        # of the four margins which are specified as separate properties.  This
        # doesn't really fit the way we parse the tree (why aren't the values
        # passed as attributes of a single property?) so we create a new
        # property and inject it.  However, if we find that they have all been
        # specified and have the same value then we inject a different property
        # that is compatible with older versions of Qt.
        left = self.wprops.getProperty(elem, 'leftMargin', -1)
        top = self.wprops.getProperty(elem, 'topMargin', -1)
        right = self.wprops.getProperty(elem, 'rightMargin', -1)
        bottom = self.wprops.getProperty(elem, 'bottomMargin', -1)

        # Count the number of properties and if they had the same value.
        def comp_property(m, so_far=-2, nr=0):
            if m >= 0:
                nr += 1

                if so_far == -2:
                    so_far = m
                elif so_far != m:
                    so_far = -1

            return so_far, nr

        margin, nr_margins = comp_property(left)
        margin, nr_margins = comp_property(top, margin, nr_margins)
        margin, nr_margins = comp_property(right, margin, nr_margins)
        margin, nr_margins = comp_property(bottom, margin, nr_margins)

        if nr_margins > 0:
            if nr_margins == 4 and margin >= 0:
                # We can inject the old margin property.
                me = SubElement(elem, 'property', name='margin')
                SubElement(me, 'number').text = str(margin)
            else:
                # We have to inject the new internal property.
                cme = SubElement(elem, 'property', name='pyuicContentsMargins')
                SubElement(cme, 'number').text = str(left)
                SubElement(cme, 'number').text = str(top)
                SubElement(cme, 'number').text = str(right)
                SubElement(cme, 'number').text = str(bottom)
        elif self.layout_widget:
            margin = self.wprops.getProperty(elem, 'margin', -1)
            if margin < 0:
                # The layouts of layout widgets have no margin.
                me = SubElement(elem, 'property', name='margin')
                SubElement(me, 'number').text = '0'

            # In case there are any nested layouts.
            self.layout_widget = False

        # We do the same for setHorizontalSpacing() and setVerticalSpacing().
        horiz = self.wprops.getProperty(elem, 'horizontalSpacing', -1)
        vert = self.wprops.getProperty(elem, 'verticalSpacing', -1)

        if horiz >= 0 or vert >= 0:
            # We inject the new internal property.
            cme = SubElement(elem, 'property', name='pyuicSpacing')
            SubElement(cme, 'number').text = str(horiz)
            SubElement(cme, 'number').text = str(vert)

        classname = elem.attrib["class"]
        if self.stack.topIsLayout():
            parent = None
        else:
            parent = self.stack.topwidget
        if "name" not in elem.attrib:
            elem.attrib["name"] = classname[1:].lower()
        self.stack.push(self.setupObject(classname, parent, elem))
        self.traverseWidgetTree(elem)

        layout = self.stack.popLayout()
        self.configureLayout(elem, layout)

        if self.stack.topIsLayout():
            top_layout = self.stack.peek()
            gp = elem.attrib["grid-position"]

            if isinstance(top_layout, QtWidgets.QFormLayout):
                top_layout.setLayout(gp[0], self._form_layout_role(gp), layout)
            else:
                top_layout.addLayout(layout, *gp)
예제 #26
0
def create_new_epg(args, original_epg_filename, m3u_entries):
    output_str("creating new xml epg for {} m3u items".format(len(m3u_entries)))
    try:
        original_tree = parse(original_epg_filename)
        original_root = original_tree.getroot()

        new_root = Element("tv")
        new_root.set("source-info-name", "py-m3u-epg-editor")
        new_root.set("generator-info-name", "py-m3u-epg-editor")
        new_root.set("generator-info-url", "py-m3u-epg-editor")

        # create a channel element for every channel present in the m3u
        for channel in original_root.iter('channel'):
            channel_id = channel.get("id")
            if any(x.tvg_id == channel_id for x in m3u_entries):
                output_str("creating channel element for {}".format(channel_id))
                new_channel = SubElement(new_root, "channel")
                new_channel.set("id", channel_id)
                for elem in channel:
                    new_elem = SubElement(new_channel, elem.tag)
                    new_elem.text = elem.text
                    for attr_key in elem.keys():
                        attr_val = elem.get(attr_key)
                        new_elem.set(attr_key, attr_val)

        # now copy all programme elements from the original epg for every channel present in the m3u
        no_epg_channels = []
        for entry in m3u_entries:
            if entry.tvg_id is not None and entry.tvg_id != "" and entry.tvg_id != "None":
                output_str("creating programme elements for {}".format(entry.tvg_name))
                channel_xpath = 'programme[@channel="' + entry.tvg_id + '"]'
                channel_programmes = original_tree.findall(channel_xpath)
                if len(channel_programmes) > 0:
                    for elem in channel_programmes:
                        if is_in_range(args, elem):
                            programme = SubElement(new_root, elem.tag)
                            for attr_key in elem.keys():
                                attr_val = elem.get(attr_key)
                                programme.set(attr_key, attr_val)
                            for sub_elem in elem:
                                new_elem = SubElement(programme, sub_elem.tag)
                                new_elem.text = sub_elem.text
                                for attr_key in sub_elem.keys():
                                    attr_val = sub_elem.get(attr_key)
                                    new_elem.set(attr_key, attr_val)
                else:
                    no_epg_channels.append(entry)
            else:
                no_epg_channels.append(entry)

        indent(new_root)
        tree = ElementTree(new_root)

        if len(no_epg_channels) > 0:
            save_no_epg_channels(args, no_epg_channels)

        return tree
    except:
        # likely a mangled xml parse exception
        e = sys.exc_info()[0]
        output_str("epg creation failure: {0}".format(e))
        return None
예제 #27
0
 def __create_root(self):
     self.xml_root_element = Element('root')
     SubElement(self.xml_root_element, 'items')
예제 #28
0
 def GET(self, req):
     """Handle HTTP GET request."""
     drive, part, account, container, obj = split_and_validate_path(
         req, 4, 5, True)
     path = get_param(req, 'path')
     prefix = get_param(req, 'prefix')
     delimiter = get_param(req, 'delimiter')
     if delimiter and (len(delimiter) > 1 or ord(delimiter) > 254):
         # delimiters can be made more flexible later
         return HTTPPreconditionFailed(body='Bad delimiter')
     marker = get_param(req, 'marker', '')
     end_marker = get_param(req, 'end_marker')
     limit = CONTAINER_LISTING_LIMIT
     given_limit = get_param(req, 'limit')
     if given_limit and given_limit.isdigit():
         limit = int(given_limit)
         if limit > CONTAINER_LISTING_LIMIT:
             return HTTPPreconditionFailed(request=req,
                                           body='Maximum limit is %d' %
                                           CONTAINER_LISTING_LIMIT)
     out_content_type = get_listing_content_type(req)
     if self.mount_check and not check_mount(self.root, drive):
         return HTTPInsufficientStorage(drive=drive, request=req)
     broker = self._get_container_broker(drive,
                                         part,
                                         account,
                                         container,
                                         pending_timeout=0.1,
                                         stale_reads_ok=True)
     if broker.is_deleted():
         return HTTPNotFound(request=req)
     info = broker.get_info()
     resp_headers = {
         'X-Container-Object-Count': info['object_count'],
         'X-Container-Bytes-Used': info['bytes_used'],
         'X-Timestamp': info['created_at'],
         'X-PUT-Timestamp': info['put_timestamp'],
     }
     for key, (value, timestamp) in broker.metadata.iteritems():
         if value and (key.lower() in self.save_headers
                       or is_sys_or_user_meta('container', key)):
             resp_headers[key] = value
     ret = Response(request=req,
                    headers=resp_headers,
                    content_type=out_content_type,
                    charset='utf-8')
     container_list = broker.list_objects_iter(limit, marker, end_marker,
                                               prefix, delimiter, path)
     if out_content_type == 'application/json':
         ret.body = json.dumps(
             [self.update_data_record(record) for record in container_list])
     elif out_content_type.endswith('/xml'):
         doc = Element('container', name=container.decode('utf-8'))
         for obj in container_list:
             record = self.update_data_record(obj)
             if 'subdir' in record:
                 name = record['subdir'].decode('utf-8')
                 sub = SubElement(doc, 'subdir', name=name)
                 SubElement(sub, 'name').text = name
             else:
                 obj_element = SubElement(doc, 'object')
                 for field in [
                         "name", "hash", "bytes", "content_type",
                         "last_modified"
                 ]:
                     SubElement(obj_element, field).text = str(
                         record.pop(field)).decode('utf-8')
                 for field in sorted(record):
                     SubElement(obj_element, field).text = str(
                         record[field]).decode('utf-8')
         ret.body = tostring(doc, encoding='UTF-8').replace(
             "<?xml version='1.0' encoding='UTF-8'?>",
             '<?xml version="1.0" encoding="UTF-8"?>', 1)
     else:
         if not container_list:
             return HTTPNoContent(request=req, headers=resp_headers)
         ret.body = '\n'.join(rec[0] for rec in container_list) + '\n'
     return ret
예제 #29
0
 def getranges(rangelist, root):
     for r in rangelist:
         rangeelem = SubElement(root, 'range')
         rangeelem.set('from', str(r[0]))
         rangeelem.set('to', str(r[1]))
예제 #30
0
파일: xmltv.py 프로젝트: lakedai/xsltv
    def addProgramme(self, programme):
        """
        Add a single XMLTV 'programme'

        Arguments:

          'programme' -- A dict representing XMLTV data
        """
        p = SubElement(self.root, 'programme')

        # programme attributes
        for attr in ('start', 'channel'):
            if attr in programme:
                self.setattr(p, attr, programme[attr])
            else:
                raise ValueError("'programme' must contain '%s' attribute" %
                                 attr)

        for attr in ('stop', 'pdc-start', 'vps-start', 'showview', 'videoplus',
                     'clumpidx'):
            if attr in programme:
                self.setattr(p, attr, programme[attr])

        for title in programme['title']:
            t = SubElement(p, 'title')
            self.settext(t, title)

        # Sub-title and description
        for element in ('sub-title', 'desc'):
            self.set_zero_ormore(programme, element, p)

        # Credits
        if 'credits' in programme:
            c = SubElement(p, 'credits')
            for credtype in ('director', 'actor', 'writer', 'adapter',
                             'producer', 'presenter', 'commentator', 'guest'):
                if credtype in programme['credits']:
                    for name in programme['credits'][credtype]:
                        cred = SubElement(c, credtype)
                        self.settext(cred, name, with_lang=False)

        # Date
        if 'date' in programme:
            d = SubElement(p, 'date')
            self.settext(d, programme['date'], with_lang=False)

        # Category
        self.set_zero_ormore(programme, 'category', p)

        # Language and original language
        for element in ('language', 'orig-language'):
            self.set_zero_orone(programme, element, p)

        # Length
        if 'length' in programme:
            l = SubElement(p, 'length')
            self.setattr(l, 'units', programme['length']['units'])
            self.settext(l, programme['length']['length'], with_lang=False)

        # Icon
        if 'icon' in programme:
            self.seticons(p, programme['icon'])

        # URL
        if 'url' in programme:
            for url in programme['url']:
                u = SubElement(p, 'url')
                self.settext(u, url, with_lang=False)

        # Country
        self.set_zero_ormore(programme, 'country', p)

        # Episode-num
        if 'episode-num' in programme:
            for epnum in programme['episode-num']:
                e = SubElement(p, 'episode-num')
                self.setattr(e, 'system', epnum[1])
                self.settext(e, epnum[0], with_lang=False)

        # Video details
        if 'video' in programme:
            e = SubElement(p, 'video')
            for videlem in ('aspect', 'quality'):
                if videlem in programme['video']:
                    v = SubElement(e, videlem)
                    self.settext(v,
                                 programme['video'][videlem],
                                 with_lang=False)
            for attr in ('present', 'colour'):
                if attr in programme['video']:
                    a = SubElement(e, attr)
                    if programme['video'][attr]:
                        self.settext(a, 'yes', with_lang=False)
                    else:
                        self.settext(a, 'no', with_lang=False)

        # Audio details
        if 'audio' in programme:
            a = SubElement(p, 'audio')
            if 'stereo' in programme['audio']:
                s = SubElement(a, 'stereo')
                self.settext(s, programme['audio']['stereo'], with_lang=False)
            if 'present' in programme['audio']:
                p = SubElement(a, 'present')
                if programme['audio']['present']:
                    self.settext(p, 'yes', with_lang=False)
                else:
                    self.settext(p, 'no', with_lang=False)

        # Previously shown
        if 'previously-shown' in programme:
            ps = SubElement(p, 'previously-shown')
            for attr in ('start', 'channel'):
                if attr in programme['previously-shown']:
                    self.setattr(ps, attr, programme['previously-shown'][attr])

        # Premiere / last chance
        for element in ('premiere', 'last-chance'):
            self.set_zero_orone(programme, element, p)

        # New
        if 'new' in programme:
            n = SubElement(p, 'new')

        # Subtitles
        if 'subtitles' in programme:
            for subtitles in programme['subtitles']:
                s = SubElement(p, 'subtitles')
                if 'type' in subtitles:
                    self.setattr(s, 'type', subtitles['type'])
                if 'language' in subtitles:
                    l = SubElement(s, 'language')
                    self.settext(l, subtitles['language'])

        # Rating
        if 'rating' in programme:
            for rating in programme['rating']:
                r = SubElement(p, 'rating')
                if 'system' in rating:
                    self.setattr(r, 'system', rating['system'])
                v = SubElement(r, 'value')
                self.settext(v, rating['value'], with_lang=False)
                if 'icon' in rating:
                    self.seticons(r, rating['icon'])

        # Star rating
        if 'star-rating' in programme:
            for star_rating in programme['star-rating']:
                sr = SubElement(p, 'star-rating')
                if 'system' in star_rating:
                    self.setattr(sr, 'system', star_rating['system'])
                v = SubElement(sr, 'value')
                self.settext(v, star_rating['value'], with_lang=False)
                if 'icon' in star_rating:
                    self.seticons(sr, star_rating['icon'])

        # Review
        if 'review' in programme:
            for review in programme['review']:
                r = SubElement(p, 'review')
                for attr in ('type', 'source', 'reviewer'):
                    if attr in review:
                        self.setattr(r, attr, review[attr])
                v = SubElement(r, 'value')
                self.settext(v, review['value'], with_lang=False)