Merge child nodes with direction preserved. (#7448)
964066
function mergeChildren( from, into, refNode, forward ) {
		var child, itemDir;
		while ( ( child = from[ forward ? 'getLast' : 'getFirst' ]( elementType ) ) ) {
			if ( ( itemDir = child.getDirection( 1 ) ) !== into.getDirection( 1 ) )
				child.setAttribute( 'dir', itemDir );

			child.remove();

			refNode ? child[ forward ? 'insertBefore' : 'insertAfter' ]( refNode ) : into.append( child, forward );
		}
	}
179446
def merge_nodes(self, n1: str, n2: str, same_polarity: bool = True):
        

        for p in self.predecessors(n1):
            for st in self[p][n1]["InfluenceStatements"]:
                if not same_polarity:
                    st.obj_delta["polarity"] = -st.obj_delta["polarity"]
                st.obj.db_refs["UN"][0] = (n2, st.obj.db_refs["UN"][0][1])

            if not self.has_edge(p, n2):
                self.add_edge(p, n2)
                self[p][n2]["InfluenceStatements"] = self[p][n1][
                    "InfluenceStatements"
                ]

            else:
                self[p][n2]["InfluenceStatements"] += self[p][n1][
                    "InfluenceStatements"
                ]

        for s in self.successors(n1):
            for st in self.edges[n1, s]["InfluenceStatements"]:
                if not same_polarity:
                    st.subj_delta["polarity"] = -st.subj_delta["polarity"]
                st.subj.db_refs["UN"][0] = (n2, st.subj.db_refs["UN"][0][1])

            if not self.has_edge(n2, s):
                self.add_edge(n2, s)
                self[n2][s]["InfluenceStatements"] = self[n1][s][
                    "InfluenceStatements"
                ]
            else:
                self[n2][s]["InfluenceStatements"] += self[n1][s][
                    "InfluenceStatements"
                ]

        self.remove_node(n1)
809852
private static Rectangle2d union(AbstractGISTreeSetNode<?, ?> node, Rectangle2afp<?, ?, ?, ?, ?, ?> shape) {
		final Rectangle2d b = getNodeBuildingBounds(node);
		b.setUnion(shape);
		normalize(b, shape);
		return b;
	}
603000
@Override
    public TreeNode processMerge(TreeNode node) {

        DefaultMutableTreeNode masterNode = (DefaultMutableTreeNode) node;

        // if master and slave are the same object return the
        // masterNode
        if (masterNode.equals(slaveTopNode)) {
            return masterNode;
        }

        // If there are not children in slaveTopNode return the
        // masterNode
        if (slaveTopNode.getChildCount() == 0) {
            return masterNode;
        }

        mergeNodes(masterNode, slaveTopNode);
        return masterNode;
    }
813781
private void treeShap(R feat, float[] phi,
                        N node, S nodeStat, int unique_depth,
                        PathPointer parent_unique_path,
                        float parent_zero_fraction,
                        float parent_one_fraction, int parent_feature_index,
                        int condition, int condition_feature,
                        float condition_fraction) {

    // stop if we have no getWeight coming down to us
    if (condition_fraction == 0) return;

    // extend the unique path
    PathPointer unique_path = parent_unique_path.move(unique_depth);

    if (condition == 0 || condition_feature != parent_feature_index) {
      extendPath(unique_path, unique_depth, parent_zero_fraction,
              parent_one_fraction, parent_feature_index);
    }
    final int split_index = node.getSplitIndex();

    // leaf node
    if (node.isLeaf()) {
      for (int i = 1; i <= unique_depth; ++i) {
        final float w = unwoundPathSum(unique_path, unique_depth, i);
        final PathElement el = unique_path.get(i);
        phi[el.feature_index] += w * (el.one_fraction - el.zero_fraction)
                * node.getLeafValue() * condition_fraction;
      }

      // internal node
    } else {
      // find which branch is "hot" (meaning x would follow it)
      final int hot_index = node.next(feat);
      final int cold_index = hot_index == node.getLeftChildIndex() ? node.getRightChildIndex() : node.getLeftChildIndex();
      final float w = nodeStat.getWeight();
      final float hot_zero_fraction = stats[hot_index].getWeight() / w;
      final float cold_zero_fraction = stats[cold_index].getWeight() / w;
      float incoming_zero_fraction = 1;
      float incoming_one_fraction = 1;

      // see if we have already split on this feature,
      // if so we undo that split so we can redo it for this node
      int path_index = 0;
      for (; path_index <= unique_depth; ++path_index) {
        if (unique_path.get(path_index).feature_index == split_index)
          break;
      }
      if (path_index != unique_depth + 1) {
        incoming_zero_fraction = unique_path.get(path_index).zero_fraction;
        incoming_one_fraction = unique_path.get(path_index).one_fraction;
        unwindPath(unique_path, unique_depth, path_index);
        unique_depth -= 1;
      }

      // divide up the condition_fraction among the recursive calls
      float hot_condition_fraction = condition_fraction;
      float cold_condition_fraction = condition_fraction;
      if (condition > 0 && split_index == condition_feature) {
        cold_condition_fraction = 0;
        unique_depth -= 1;
      } else if (condition < 0 && split_index == condition_feature) {
        hot_condition_fraction *= hot_zero_fraction;
        cold_condition_fraction *= cold_zero_fraction;
        unique_depth -= 1;
      }

      treeShap(feat, phi, nodes[hot_index], stats[hot_index], unique_depth + 1, unique_path,
              hot_zero_fraction * incoming_zero_fraction, incoming_one_fraction,
              split_index, condition, condition_feature, hot_condition_fraction);

      treeShap(feat, phi, nodes[cold_index], stats[cold_index], unique_depth + 1, unique_path,
              cold_zero_fraction * incoming_zero_fraction, 0,
              split_index, condition, condition_feature, cold_condition_fraction);
    }
  }
1164238
private Node<T> moveRedRight(Node<T> h) {
        // assert (h != null);
        // assert isRed(h) && !isRed(h.right) && !isRed(h.right.left);
        flipColors(h);
        if (h.left.left != null && h.left.left.red) { 
            h = rotateRight(h);
            flipColors(h);
        }
        return h;
    }
332213
def _edge_both_nodes(nodes: List[Node]):
        """"""
        node_ids = [node.id for node in nodes]

        return and_(
            Edge.source_id.in_(node_ids),
            Edge.target_id.in_(node_ids),
        )
1300010
public static String merge(String parent, String child) {
	if (child.length() <= 2) {
	    if (child.length() == 0) return parent;
	    if (child.equals(".")) return parent;
	    if (child.equals("..")) child = "../";
	}

	parent = translatePath(parent, true, false);
	child = prettifyPath(child);// child.replace('\\', '/');

	if (child.startsWith("./")) child = child.substring(2);
	if (StringUtil.startsWith(child, '/')) return parent.concat(child);
	if (!StringUtil.startsWith(child, '.')) return parent.concat("/").concat(child);

	while (child.startsWith("../")) {
	    parent = pathRemoveLast(parent);
	    child = child.substring(3);
	}
	if (StringUtil.startsWith(child, '/')) return parent.concat(child);
	return parent.concat("/").concat(child);
    }
44365
public void toLeftJoin() {
        assert((m_leftNode != null && m_rightNode != null) || (m_leftNode == null && m_rightNode == null));
        if (m_leftNode == null && m_rightNode == null) {
            // End of recursion
            return;
        }
        // recursive calls
        if (m_leftNode instanceof BranchNode) {
            ((BranchNode)m_leftNode).toLeftJoin();
        }
        if (m_rightNode instanceof BranchNode) {
            ((BranchNode)m_rightNode).toLeftJoin();
        }

        // Swap own children
        if (m_joinType == JoinType.RIGHT) {
            JoinNode node = m_rightNode;
            m_rightNode = m_leftNode;
            m_leftNode = node;
            m_joinType = JoinType.LEFT;
        }
    }
502207
def _precedence_parens(self, node, child, is_left=True):
        """"""
        if self._should_wrap(node, child, is_left):
            return "(%s)" % child.accept(self)

        return child.accept(self)
731904
public V merge(V a, V b) {
        final V aHead = componentOf(a);
        final V bHead = componentOf(b);
        if (aHead.equals(bHead)) return aHead;
        // add the shorter tree underneath the taller tree
        final int aRank = ranks.getOrDefault(aHead, 0);
        final int bRank = ranks.getOrDefault(bHead, 0);
        if (aRank > bRank) {
            parents.put(bHead, aHead);
            return aHead;
        } else if (bRank > aRank) {
            parents.put(aHead, bHead);
            return bHead;
        } else {
            // whoops, the tree got taller
            parents.put(bHead, aHead);
            ranks.put(aHead, aRank + 1);
            return aHead;
        }
    }
1098136
function moveTopDown(node, dx, dy) {
        var nodes = node.union(node.descendants());

        nodes.filter(":childless").positions(function (node, i) {
            if(typeof node === "number") {
              node = i;
            }
            var pos = node.position();
            return {
                x: pos.x + dx,
                y: pos.y + dy
            };
        });
    }
582065
function updateChildren (newNode, oldNode) {
  // if (DEBUG) {
  //   console.log(
  //   'updateChildren\nold\n  %s\nnew\n  %s',
  //   oldNode && oldNode.outerHTML,
  //   newNode && newNode.outerHTML
  // )
  // }
  var oldChild, newChild, morphed, oldMatch

  // The offset is only ever increased, and used for [i - offset] in the loop
  var offset = 0

  for (var i = 0; ; i++) {
    oldChild = oldNode.childNodes[i]
    newChild = newNode.childNodes[i - offset]
    // if (DEBUG) {
    //   console.log(
    //   '===\n- old\n  %s\n- new\n  %s',
    //   oldChild && oldChild.outerHTML,
    //   newChild && newChild.outerHTML
    // )
    // }
    // Both nodes are empty, do nothing
    if (!oldChild && !newChild) {
      break

    // There is no new child, remove old
    } else if (!newChild) {
      oldNode.removeChild(oldChild)
      i--

    // There is no old child, add new
    } else if (!oldChild) {
      oldNode.appendChild(newChild)
      offset++

    // Both nodes are the same, morph
    } else if (same(newChild, oldChild)) {
      morphed = walk(newChild, oldChild)
      if (morphed !== oldChild) {
        oldNode.replaceChild(morphed, oldChild)
        offset++
      }

    // Both nodes do not share an ID or a placeholder, try reorder
    } else {
      oldMatch = null

      // Try and find a similar node somewhere in the tree
      for (var j = i; j < oldNode.childNodes.length; j++) {
        if (same(oldNode.childNodes[j], newChild)) {
          oldMatch = oldNode.childNodes[j]
          break
        }
      }

      // If there was a node with the same ID or placeholder in the old list
      if (oldMatch) {
        morphed = walk(newChild, oldMatch)
        if (morphed !== oldMatch) offset++
        oldNode.insertBefore(morphed, oldChild)

      // It's safe to morph two nodes in-place if neither has an ID
      } else if (!newChild.id && !oldChild.id) {
        morphed = walk(newChild, oldChild)
        if (morphed !== oldChild) {
          oldNode.replaceChild(morphed, oldChild)
          offset++
        }

      // Insert the node at the index if we couldn't morph or find a matching node
      } else {
        oldNode.insertBefore(newChild, oldChild)
        offset++
      }
    }
  }
}
4102
def merge_adjacent(dom, tag_name):
    
    for node in dom.getElementsByTagName(tag_name):
        prev_sib = node.previousSibling
        if prev_sib and prev_sib.nodeName == node.tagName:
            for child in list(node.childNodes):
                prev_sib.appendChild(child)
            remove_node(node)
675240
def merge_text_nodes_on(self, node):
        """"""

        if not isinstance(node, ContainerNode) or not node.children:
            return

        new_children = []
        text_run = []
        for i in node.children:
            if isinstance(i, Text) and not i.translatable:
                text_run.append(i.escaped())
            else:
                if text_run:
                    new_children.append(EscapedText(''.join(text_run)))
                    text_run = []

                new_children.append(i)

        if text_run:
            new_children.append(EscapedText(''.join(text_run)))

        node.children = new_children
        for i in node.children:
            self.merge_text_nodes_on(i)
834109
def arrow(self, JOIN, _id):
        """"""
        r = JOIN
        for node in self.lattice.get_elements(JOIN):
            if node.left_hand_side == _id:
                r = r ^ self.lattice.el2bv[node]
        return r
614054
private Node<K, V> combine(Node<K, V> l) {
        if (l == null) {
            return null;
        }

        assert l.o_s == null;

        // left-right pass
        Node<K, V> pairs = null;
        Node<K, V> it = l, p_it;
        if (comparator == null) { // no comparator
            while (it != null) {
                p_it = it;
                it = it.y_s;

                if (it == null) {
                    // append last node to pair list
                    p_it.y_s = pairs;
                    p_it.o_s = null;
                    pairs = p_it;
                } else {
                    Node<K, V> n_it = it.y_s;

                    // disconnect both
                    p_it.y_s = null;
                    p_it.o_s = null;
                    it.y_s = null;
                    it.o_s = null;

                    // link trees
                    p_it = link(p_it, it);

                    // append to pair list
                    p_it.y_s = pairs;
                    pairs = p_it;

                    // advance
                    it = n_it;
                }
            }
        } else {
            while (it != null) {
                p_it = it;
                it = it.y_s;

                if (it == null) {
                    // append last node to pair list
                    p_it.y_s = pairs;
                    p_it.o_s = null;
                    pairs = p_it;
                } else {
                    Node<K, V> n_it = it.y_s;

                    // disconnect both
                    p_it.y_s = null;
                    p_it.o_s = null;
                    it.y_s = null;
                    it.o_s = null;

                    // link trees
                    p_it = linkWithComparator(p_it, it);

                    // append to pair list
                    p_it.y_s = pairs;
                    pairs = p_it;

                    // advance
                    it = n_it;
                }
            }
        }

        // second pass (reverse order - due to add first)
        it = pairs;
        Node<K, V> f = null;
        if (comparator == null) {
            while (it != null) {
                Node<K, V> nextIt = it.y_s;
                it.y_s = null;
                f = link(f, it);
                it = nextIt;
            }
        } else {
            while (it != null) {
                Node<K, V> nextIt = it.y_s;
                it.y_s = null;
                f = linkWithComparator(f, it);
                it = nextIt;
            }
        }

        return f;
    }