Python clean node

20 Python code examples are found related to " clean node". You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.
Example 1
Source File: cleanxml.py    From gtg with GNU General Public License v3.0 6 votes vote down vote up
def cleanNode(currentNode, indent, newl):
    myfilter = indent + newl
    if currentNode.hasChildNodes:
        toremove = []
        for node in currentNode.childNodes:
            if node.nodeType == 3:
                val = node.nodeValue.lstrip(myfilter).strip(myfilter)
                if val == "":
                    toremove.append(node)
                else:
                    node.nodeValue = val
        # now we remove the nodes that were empty
        for n in toremove:
            currentNode.removeChild(n)
        for node in currentNode.childNodes:
            cleanNode(node, indent, newl) 
Example 2
Source File: post_clean.py    From getbook with GNU Affero General Public License v3.0 6 votes vote down vote up
def clean_node(node):
    if is_blank_element(node):
        node.extract()
        return

    if is_ignored_elements(node):
        node.extract()
        return

    if node.name == 'table':
        table_codeblock(node)
    elif node.name == 'a':
        href = node.get('href', '')
        if href == '#' or href.lower().startswith('javascript:'):
            node.name = 'span'

    if node:
        unwrap_useless_tag(node)

    if node:
        clean_mess(node)
    return node 
Example 3
Source File: __init__.py    From maas with GNU Affero General Public License v3.0 6 votes vote down vote up
def clean_numa_node(self):
        index = self.cleaned_data["numa_node"]
        if not self.node.is_machine:
            if index is None:
                return None
            raise ValidationError(
                "Only interfaces for machines are linked to a NUMA node"
            )

        if index is None:
            index = self.instance.numa_node.index if self.is_update else 0

        try:
            self.cleaned_data["numa_node"] = self.node.numanode_set.get(
                index=index
            )
        except NUMANode.DoesNotExist:
            raise ValidationError("Invalid NUMA node")
        return self.cleaned_data["numa_node"] 
Example 4
Source File: whitelist.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def clean_tag_node(self, doc, tag):
        # first, whitelist the contents of this tag

        # NB tag.contents will change while this iteration is running, so we need
        # to capture the initial state into a static list() and iterate over that
        # to avoid losing our place in the sequence.
        for child in list(tag.contents):
            self.clean_node(doc, child)

        # see if there is a rule in element_rules for this tag type
        try:
            rule = self.element_rules[tag.name]
        except KeyError:
            # don't recognise this tag name, so KILL IT WITH FIRE
            tag.unwrap()
            return

        # apply the rule
        rule(tag) 
Example 5
Source File: whitelist.py    From wagtail with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def clean_string_node(self, doc, node):
        # Remove comments
        if isinstance(node, Comment):
            node.extract()
            return

        # by default, nothing needs to be done to whitelist string nodes
        pass 
Example 6
Source File: graph.py    From DeepDeepParser with Apache License 2.0 6 votes vote down vote up
def clean_inorder_node_traversal(self):
    traversal = self.inorder_node_traversal(self.root_index)
    alignments = [self.nodes[i].alignment for i in traversal]
    alignment_list = sorted(list(set(alignments)))
    # For every alignment index, records best group length and index.
    groups_per_alignment = {} 
    for a in alignment_list:
      groups_per_alignment[a] = (0, -1)

    align = alignments[0]
    group_start = 0
    for j in xrange(1, len(alignments) + 1):
      if j == len(alignments) or alignments[j] <> align:
        group_length = j - group_start
        if group_length > groups_per_alignment[align][0]: 
          groups_per_alignment[align] = (group_length, group_start)
        if j < len(alignments):
          align = alignments[j]
          group_start = j

    # Finds index of best group for each alignment.
    alignment_group_indexes = [groups_per_alignment[a][1] for a in alignments]
    sorted_traversal = [t for (a, r, t) in sorted(zip(
        alignment_group_indexes, range(len(traversal)), traversal))]
    return sorted_traversal 
Example 7
Source File: common.py    From opsbro with MIT License 5 votes vote down vote up
def clean_node(node):
    """Split and normalize a node name from an ismaster response."""
    host, port = partition_node(node)

    # Normalize hostname to lowercase, since DNS is case-insensitive:
    # http://tools.ietf.org/html/rfc4343
    # This prevents useless rediscovery if "foo.com" is in the seed list but
    # "FOO.com" is in the ismaster response.
    return host.lower(), port 
Example 8
Source File: cassandra.py    From PerfKitBenchmarker with Apache License 2.0 5 votes vote down vote up
def CleanNode(vm):
  """Remove Cassandra data from 'vm'.

  Args:
    vm: VirtualMachine. VM to clean.
  """
  if vm.OS_TYPE == os_types.JUJU:
    return

  data_path = posixpath.join(vm.GetScratchDir(), 'cassandra')
  vm.RemoteCommand('rm -rf {0}'.format(data_path)) 
Example 9
Source File: interface.py    From maas with GNU Affero General Public License v3.0 5 votes vote down vote up
def clean_parents_all_same_node(self, parents):
        if parents:
            parent_nodes = set(parent.get_node() for parent in parents)
            if len(parent_nodes) > 1:
                msg = "Parents are related to different nodes."
                set_form_error(self, "name", msg) 
Example 10
Source File: workflow_helpers.py    From avos with Apache License 2.0 5 votes vote down vote up
def clean_node_group(node_group):
    node_group_copy = dict((key, value)
                           for key, value in node_group.items() if value)

    for key in ["id", "created_at", "updated_at"]:
        if key in node_group_copy:
            node_group_copy.pop(key)

    return node_group_copy 
Example 11
Source File: objects.py    From Simulator with GNU General Public License v3.0 5 votes vote down vote up
def clean_node(self):
        self.orders = []
        self.order_num = 0
        self.drivers = {}
        self.idle_driver_num = 0
        self.offline_driver_num = 0 
Example 12
Source File: widgets.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def cleanNode(self, node):
        """
        Do your part, prevent infinite recursion!
        """
        if not DEBUG:
            if node.attributes.has_key('model'):
                del node.attributes['model']
            if node.attributes.has_key('view'):
                del node.attributes['view']
            if node.attributes.has_key('controller'):
                del node.attributes['controller']
        return node 
Example 13
Source File: module.py    From opsbro with MIT License 5 votes vote down vote up
def clean_node_files(self, nid):
        cfgp, shap = self.__get_node_cfg_sha_paths(nid)
        if os.path.exists(cfgp):
            try:
                os.unlink(cfgp)
                # We did remove a file, reload shinken so
                self.reload_flag = True
            except IOError as exp:
                self.logger.error('Cannot remove deprecated file %s' % cfgp)
        if os.path.exists(shap):
            try:
                os.unlink(shap)
            except IOError as exp:
                self.logger.error('Cannot remove deprecated file %s' % shap) 
Example 14
Source File: whitelist.py    From wagtail with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def clean_node(self, doc, node):
        """Clean a BeautifulSoup document in-place"""
        if isinstance(node, NavigableString):
            self.clean_string_node(doc, node)
        elif isinstance(node, Tag):
            self.clean_tag_node(doc, node)
        # This branch is here in case node is a BeautifulSoup object that does
        # not inherit from NavigableString or Tag. I can't find any examples
        # of such a thing at the moment, so this branch is untested.
        else:  # pragma: no cover
            self.clean_unknown_node(doc, node) 
Example 15
Source File: io_import_images_as_planes.py    From Fluid-Designer with GNU General Public License v3.0 5 votes vote down vote up
def clean_node_tree(node_tree):
    nodes = node_tree.nodes
    for node in nodes:
        if not node.type == 'OUTPUT_MATERIAL':
            nodes.remove(node)
    return node_tree.nodes[0]


# -----------------------------------------------------------------------------
# Operator 
Example 16
Source File: __init__.py    From blender-plugin with Apache License 2.0 4 votes vote down vote up
def clean_node_hierarchy(objects):
        """
        Removes the useless nodes in a hierarchy
        TODO: Keep the transform (might impact Yup/Zup)
        """
        # Find the parent object
        root = None
        for object in objects:
            if object.parent is None:
                root = object
        if root is None:
            return None
        root_name = root.name

        # Go down its hierarchy until one child has multiple children, or a single mesh
        # Keep the name while deleting objects in the hierarchy
        diverges = False
        while diverges==False:
            children = root.children
            if children is not None:

                if len(children)>1:
                    diverges = True
                    root.name = root_name

                if len(children)==1:
                    if children[0].type != "EMPTY":
                        diverges = True
                        root.name = root_name
                        if children[0].type == "MESH": # should always be the case
                            matrixcopy = children[0].matrix_world.copy()
                            children[0].parent = None
                            children[0].matrix_world = matrixcopy
                            bpy.data.objects.remove(root)
                            children[0].name = root_name

                    elif children[0].type == "EMPTY":
                        diverges = False
                        matrixcopy = children[0].matrix_world.copy()
                        children[0].parent = None
                        children[0].matrix_world = matrixcopy
                        bpy.data.objects.remove(root)
                        root = children[0]
            else:
                break

        # Select the root Empty node
        root.select_set(True)