Merges all arrays extracted from the graphml file (workflow, nodes, edges) to create and
return a single array descrbing a workflow.

@param [] $w
workflow attributes
@param [] $n
nodes attributes
@param [] $e
edges attributes
321840
private function createWorkflowDefinition($w, $n, $e)
	{
		$nodes = [];

		foreach ($n as $key => $node) {
			$newNode = [];
			if (isset($node['label'])) {
				$newNode['label'] = $node['label'];
			}
			$newNode['metadata'] = [
				'background-color' => $node['background-color'],
				'color' => $node['color']
			];
			$newNode['transition'] = [];
			if (isset($e[$key])) {
				foreach ($e[$key] as $trgKey => $edge) {
					$newNode['transition'][] = $n[$trgKey]['id']; // $edge;
				}
			}
			$nodes[$node['id']] = $newNode;
		}
		return [
			'initialStatusId' => $w['initial'],
			'status' => $nodes
		];
	}
1241004
protected function buildNestedArray(array $nodes = [], $parentId = 0)
    {
        $branch = [];

        if (empty($nodes)) {
            $nodes = $this->allNodes();
        }

        foreach ($nodes as $node) {
            if ($node[$this->parentColumn] === $parentId) {
                $children = $this->buildNestedArray($nodes, $node[$this->getKeyName()]);

                if ($children) {
                    $node['children'] = $children;
                }

                $branch[] = $node;
            }
        }

        return $branch;
    }
786806
public function writeXML( \XMLWriter $w, string $elementName = 'ImageSizeReducer' )
   {

      $w->startElement( $elementName );
      $this->writeXMLAttributes( $w );
      $w->endElement();

   }
929897
private function transferChildren(
        NodeInterface $node,
        array &$node_map = [],
        array &$lazy_links = [],
        int $path_size = 0
    ): array {
        $children = [];
        $suffix_min = -1;
        $suffix_max = $suffix_min;
        foreach ($node->children as $edge => $child_node) {
            if ($child_node instanceof LeafNode) {
                $new_node = new Leaf(
                    $child_node->start,
                    $child_node->end,
                    $this->length - ($path_size + $child_node->getEdgeSize()) + 1
                );
                if ($suffix_min === -1) {
                    $suffix_min = $new_node->getSuffixIdx();
                    $suffix_max = $suffix_min;
                } else {
                    $suffix_min = min($suffix_min, $new_node->getSuffixIdx());
                    $suffix_max = max($suffix_max, $new_node->getSuffixIdx());
                }
            } else {
                list($grand_children, $smin, $smax) = $this->transferChildren(
                    $child_node,
                    $node_map,
                    $lazy_links,
                    $path_size + $child_node->getEdgeSize()
                );
                $suffix_node = null;
                if ($child_node->suffix_link !== null) {
                    $suffix_hash = (string)$child_node->suffix_link;
                    $suffix_node = isset($node_map[$suffix_hash]) ? $node_map[$suffix_hash] : null;
                }
                $new_node = new Internal(
                    $child_node->start,
                    $child_node->end,
                    $smin,
                    $smax,
                    $grand_children,
                    $suffix_node
                );
                if ($suffix_node === null && $child_node->suffix_link !== null) {
                    $lazy_links[$suffix_hash] = $new_node;
                }
                $child_hash = (string)$child_node;
                if (isset($lazy_links[$child_hash])) {
                    // todo: find out way to prevent mutating node state here, need to get the new node ref
                    // into the proper place within the new tree
                    $lazy_links[$child_hash]->withSuffixLink($new_node);
                }
                if ($suffix_min === -1) {
                    $suffix_min = $new_node->getMinSuffixIdx();
                    $suffix_max = $new_node->getMaxSuffixIdx();
                } else {
                    $suffix_min = min($suffix_min, $new_node->getMinSuffixIdx());
                    $suffix_max = max($suffix_max, $new_node->getMaxSuffixIdx());
                }
                $node_map[$child_hash] = $new_node;
            }
            $children[$edge] = $new_node;
        }

        return [ $children, $suffix_min, $suffix_max ];
    }
1193269
public function renderPresentationNetwork( $network, $elr, $instance, $formulas, $observer, $evaluationResults, $echo = true )
	{
		$entities = $instance->getContexts()->AllEntities();

		// Add a depth to each node
		$addDepth = function( &$nodes, $depth = 0 ) use( &$addDepth )
		{
			foreach ( $nodes as $label => &$node )
			{
				$node['depth'] = $depth;
				if ( ! isset( $node['children'] ) ) continue;
				$addDepth( $node['children'], $depth + 1 );
			}
			unset( $node );
		};

		$addDepth( $network['hierarchy'] );

		$result = array();

		foreach ( $entities as $entity )
		{
			$entityQName = qname( $entity );

			// Find periods
			$names = array_map( function( $conceptQName )
			{
				return $conceptQName->localName;
			}, $network['concepts'] );

			$elements = $instance->getElements()->ElementsByName( $names )->getElements();

			$contextRefs = array_reduce( $elements, function( $carry, $element ) use ( $instance )
			{
				$result = array_unique( array_map( function( $fact ) { return $fact['contextRef']; }, array_values( $element ) ) );
				return array_unique( array_merge( $carry, $result ) );
			}, array() );

			$rawContexts = array_intersect_key( $instance->getContexts()->getContexts(), array_flip( $contextRefs ) );

			// Filter contexts to just those used by an axis or default members
			$cf = new ContextsFilter( $instance, $rawContexts );
			// Context without a segment are always allowed because they will be used by default members
			$contexts = $cf->NoSegmentContexts()->getContexts();
			// Select dimension specific contexts
			foreach ( $network['axes'] as $axisLabel => $axis )
			{
				if ( ! isset( $axis['dimension'] ) ) continue;
				$dimTaxonomy = $instance->getInstanceTaxonomy()->getTaxonomyForXSD( $axisLabel );
				$contexts = array_merge( $contexts, $cf->SegmentContexts( strstr( $axisLabel, '#' ), $dimTaxonomy->getNamespace() )->getContexts() );
			}

			$years = array();
			foreach ( $contexts as $contextRef => $context )
			{
				$year = substr( $context['period']['endDate'], 0, 4 );
				if ( ! isset( $years[ $year ] ) ) $years[ $year ] = array(
					'text' => $context['period']['is_instant']
									? $context['period']['endDate']
									: "{$context['period']['startDate']} - {$context['period']['endDate']}",
					'contextRefs' => array(),
					// 'year' => $year
				);
				$years[ $year ]['contextRefs'][] = $contextRef;
			}

			// Present years in a consistent order - most recent first
			krsort( $years );

			$result[ $entity ] = $this->renderNetworkReport( $network, $elr, $instance, $entityQName, $formulas, $observer, $evaluationResults, $contexts, $years, $echo );
		}

		return $result;
	}
434319
public void addEdge(Edge e) {

		if (!containsNode(e.getFromNodeId())) {
			throw new NodeNotFoundException(e.getFromNodeId());
		}
		
		if (!containsNode(e.getToNodeId())) {
			throw new NodeNotFoundException(e.getToNodeId());
		}

		if (this.containsEdge(e.getId()))
			throw new DuplicatedEdgeException(e.getId());

		int eIndex = nextEdgeId++;

		edgeIdMapping.put(e.getId(), eIndex);

		int aliveIndex = eIndex >> 5;
		int aliveSubIndex = eIndex & 31;

		if (aliveIndex >= aliveEdges.size())
			aliveEdges.add(0);

		aliveEdges.set(aliveIndex, aliveEdges.get(aliveIndex) | (1 << aliveSubIndex));

		updateAdjacency(e, eIndex);
		
		edges.add(e);
		numberOfEdges++;
	}
834148
private Node tryFoldArrayJoin(Node n) {
    checkState(n.isCall(), n);
    Node callTarget = n.getFirstChild();

    if (callTarget == null || !callTarget.isGetProp()) {
      return n;
    }

    Node right = callTarget.getNext();
    if (right != null) {
      if (right.getNext() != null || !NodeUtil.isImmutableValue(right)) {
        return n;
      }
    }

    Node arrayNode = callTarget.getFirstChild();
    Node functionName = arrayNode.getNext();

    if (!arrayNode.isArrayLit() || !functionName.getString().equals("join")) {
      return n;
    }

    if (right != null && right.isString() && ",".equals(right.getString())) {
      // "," is the default, it doesn't need to be explicit
      n.removeChild(right);
      reportChangeToEnclosingScope(n);
    }

    String joinString = (right == null) ? "," : NodeUtil.getStringValue(right);
    List<Node> arrayFoldedChildren = new ArrayList<>();
    StringBuilder sb = null;
    int foldedSize = 0;
    Node prev = null;
    Node elem = arrayNode.getFirstChild();
    // Merges adjacent String nodes.
    while (elem != null) {
      if (NodeUtil.isImmutableValue(elem) || elem.isEmpty()) {
        if (sb == null) {
          sb = new StringBuilder();
        } else {
          sb.append(joinString);
        }
        sb.append(NodeUtil.getArrayElementStringValue(elem));
      } else {
        if (sb != null) {
          checkNotNull(prev);
          // + 2 for the quotes.
          foldedSize += sb.length() + 2;
          arrayFoldedChildren.add(
              IR.string(sb.toString()).useSourceInfoIfMissingFrom(prev));
          sb = null;
        }
        foldedSize += InlineCostEstimator.getCost(elem);
        arrayFoldedChildren.add(elem);
      }
      prev = elem;
      elem = elem.getNext();
    }

    if (sb != null) {
      checkNotNull(prev);
      // + 2 for the quotes.
      foldedSize += sb.length() + 2;
      arrayFoldedChildren.add(
          IR.string(sb.toString()).useSourceInfoIfMissingFrom(prev));
    }
    // one for each comma.
    foldedSize += arrayFoldedChildren.size() - 1;

    int originalSize = InlineCostEstimator.getCost(n);
    switch (arrayFoldedChildren.size()) {
      case 0:
        Node emptyStringNode = IR.string("");
        n.getParent().replaceChild(n, emptyStringNode);
        reportChangeToEnclosingScope(emptyStringNode);
        return emptyStringNode;
      case 1:
        Node foldedStringNode = arrayFoldedChildren.remove(0);
        // The spread isn't valid outside any array literal (or would change meaning)
        // so don't try to fold it.
        if (foldedStringNode.isSpread() || foldedSize > originalSize) {
          return n;
        }
        if (foldedStringNode.isString()) {
          arrayNode.detachChildren();
          n.replaceWith(foldedStringNode);
          reportChangeToEnclosingScope(foldedStringNode);
          return foldedStringNode;
        } else {
          // Because of special case behavior for `null` and `undefined` values, there's no safe way
          // to convert `[someNonStringValue].join()` to something shorter.
          // e.g. String(someNonStringValue) would turn `null` into `"null"`, which isn't right.
          return n;
        }
      default:
        if (arrayNode.hasXChildren(arrayFoldedChildren.size())) {
          // No folding could actually be performed.
          return n;
        }
        int kJoinOverhead = "[].join()".length();
        foldedSize += kJoinOverhead;
        foldedSize += (right != null) ? InlineCostEstimator.getCost(right) : 0;
        if (foldedSize > originalSize) {
          return n;
        }
        arrayNode.detachChildren();
        for (Node node : arrayFoldedChildren) {
          arrayNode.addChildToBack(node);
        }
        reportChangeToEnclosingScope(arrayNode);
        break;
    }

    return n;
  }
590513
public static <N, E> void write(Graph<N, E> graph, Appendable a) throws IOException {
        writeRaw(graph, a, toDOTVisualizationHelper(graph.getVisualizationHelper()));
    }
1287177
function addArray($arr, &$n, $name=""){
		foreach ($arr as $key => $val){
			if (is_int($key)){
				if (strlen($name)>1){
					$newKey = blib_grammar::singular($name); //substr($name, 0, strlen($name)-1);
				}else{
					$newKey="item";
				}
			}else{
				$newKey = $key;
			}

			$node = $this->doc->createElement($newKey);
			if (is_array($val)){
				$this->addArray($arr[$key], $node, $key);
			}else{
				$nodeText = $this->doc->createTextNode($val);
				$node->appendChild($nodeText);
			}
			$n->appendChild($node);
		}
	}
204527
public function addEdge(&$nodeA, &$nodeB, $name = NULL, $directed = TRUE, $data = array(), $weight = 0)
    {

        $edge = new Graph\Edge($nodeA, $name, $nodeB, $data, $directed, $weight); //Will need to decide whether to use nodeAId-nodeBId as edgeId
        $edgeId = $edge->getId();

        //Directed edges have their Id's referenced in arcSet
        if ($directed && !in_array($edgeId, $this->arcSet))
            $this->arcSet[] = $edgeId;

        //@TODO This is not the ideal way to set parrallel edges, Parralel edges connect the same pair of nodes
        //If edge already exists, increment the weight;
        if (isset($this->edgeSet[$edgeId])) {
            $this->edgeSet[$edgeId]->weight++;
            $edgeData = $this->edgeSet[$edgeId]->getData();
            $data = array_merge($edgeData, $data);
            //Makeing a directed array undirected
            if (!$directed && in_array($edgeId, $this->arcSet))
                $this->arcSet = array_diff($this->arcSet, array($edgeId));
            return true;
        }
        //array_merge edge data
        if (!isset($this->edgeSet[$edgeId]))
            $this->edgeSet[$edgeId] = &$edge;

        //If directed, use edgeIsArc to indicate;
        return true;
    }
782034
def merge_workitems(workitems, merge_type)

      workitems.inject(nil) do |t, wi|
        Ruote.merge_workitem(workitem_index(wi), t, wi, merge_type)
      end
    end
157469
def final_merge

      wi = if h.workitem

        h.workitem

      elsif h.cmerge_type == 'ignore' || h.workitems.nil? || h.workitems.empty?

        h.applied_workitem

      else

        wis = h.workitems

        if %w[ highest lowest ].include?(h.cmerge)
          wis = h.workitems.sort_by { |wi| wi['fei']['expid'] }
        end

        if
          %w[ first highest ].include?(h.cmerge) &&
          ! %w[ stack union concat deep ].include?(h.cmerge_type)
        then
          wis = wis.reverse
        end

        as, bs = wis.partition { |wi| wi.delete('winner') }
        wis = bs + as
          #
          # the 'winner' is the workitem that triggered successfully the
          # :over_if or :over_unless, let's take him precedence in the merge...

        merge_workitems(wis, h.cmerge_type)
      end

      if h.cmerge_type == 'stack'
        wi['fields']['stack_attributes'] = compile_atts
      end

      wi
    end
726394
public void mergeXfaData(Node n) throws IOException, DocumentException {
        XfaForm.Xml2SomDatasets data = new XfaForm.Xml2SomDatasets(n);
        for (Iterator it = data.getOrder().iterator(); it.hasNext();) {
            String name = (String)it.next();
            String text = XfaForm.getNodeText((Node)data.getName2Node().get(name));
            setField(name, text);
        }
    }
1165416
public function assertWorkflows(TableNode $expected) {
    $workflow_info = [];
    foreach ($this->getWorkflows() as $workflow) {
      $workflow_info[] = [
        $workflow->label(),
        $workflow->id(),
        (string) $workflow->getTypePlugin()->label(),
      ];
    }
    $actual = new TableNode($workflow_info);

    (new TableEqualityAssertion($expected, $actual))
      ->expectHeader([
        'Label',
        'Machine name',
        'Type',
      ])
      ->ignoreRowOrder()
      ->setMissingRowsLabel(self::missingRowsLabelFor('workflow'))
      ->setUnexpectedRowsLabel(self::unexpectedRowsLabelFor('workflow'))
      ->assert();
  }
1222702
protected static function mergeNodes(\SimpleXMLElement $source, \SimpleXMLElement $new)
	{
		// The assumption is that the inputs are at the same relative level.
		// So we just have to scan the children and deal with them.

		// Update the attributes of the child node.
		foreach ($new->attributes() as $name => $value)
		{
			if (isset($source[$name]))
			{
				$source[$name] = (string) $value;
			}
			else
			{
				$source->addAttribute($name, $value);
			}
		}

		foreach ($new->children() as $child)
		{
			$type = $child->getName();
			$name = $child['name'];

			// Does this node exist?
			$fields = $source->xpath($type . '[@name="' . $name . '"]');

			if (empty($fields))
			{
				// This node does not exist, so add it.
				self::addNode($source, $child);
			}
			else
			{
				// This node does exist.
				switch ($type)
				{
					case 'field':
						self::mergeNode($fields[0], $child);
						break;

					default:
						self::mergeNodes($fields[0], $child);
						break;
				}
			}
		}
	}
560988
public function merge($elements = []): NodeList {
        if (!is_array($elements)) {
            $elements = $elements->toArray();
        }

        return $this->newNodeList(array_merge($this->toArray(), $elements));
    }
13236
public void addEdge(DiEdge e, double w) {
        if (!getEdges().contains(e)) { 
            super.addEdge(e);
            weights.put(e, w);
        }
    }