/* eslint-disable 

@param {Graph} graph
@returns {Array}
488642
function topologicalSort(graph) {
    var processed = [],
        unprocessed = [],
        queue = [];

    /**
     *
     * @param arr
     * @param callback
     * @this {Object}
     */
    function each(arr, callback) {
        var i = void 0;

        // if Array, then process as array
        if (arr instanceof Array) {
            for (i = 0; i < arr.length; i++) {
                callback.call(arr[i], i);
            }
        }

        // if object, iterate over property/keys
        else {
                for (i in arr) {
                    if (arr.hasOwnProperty(i)) {
                        callback.call(arr[i], i);
                    }
                }
            }
    }

    function processStartingPoint(node) {
        if (node === undefined) {
            throw 'You have a cycle!!';
        }
        each(node.edges, function () {
            node.sortImportance--;
        });
        processed.push(node);
    }

    var populateIndegreesAndUnprocessed = function populateIndegreesAndUnprocessed() {
        each(graph.nodes, function () {
            var self = this;
            unprocessed.push(this);
            if (!Object.prototype.hasOwnProperty.call(self, 'sortImportance')) {
                self.sortImportance = 0;
            }

            each(self.edges, function () {
                self.sortImportance++;
            });
        });
    };

    populateIndegreesAndUnprocessed();

    while (unprocessed.length > 0) {
        for (var i = 0; i < unprocessed.length; i++) {
            var node = unprocessed[i];
            if (node.sortImportance === 0) {
                queue.push(node);
                unprocessed.splice(i, 1); // Remove this node, its all done.
                i--; // decrement i since we just removed that index from the iterated list;
            } else {
                node.sortImportance--;
            }
        }

        if (queue.length > 0) {
            processStartingPoint(queue.shift());
        }
    }

    return processed;
}
570980
function (graph, opts, params) {
    if (graph.children.length == 0) return '';

    function getRels(node) {
      var rels = [];
      node.children.forEach(function(childNode) {
        rels.push('(' + node.name + ')-[__rel_' + childNode.name + ':' + childNode.comp.rel + ']->(' + childNode.name + ')');
        rels.push.apply(rels, getRels(childNode));
      });
      return rels;
    }
    
    return 'CREATE UNIQUE ' + getRels(graph).join(',');
  }
571874
function savePrettyGraphSON(graph, filename, callback) {
        var ByteArrayOutputStream = Tinkerpop.autoImport('ByteArrayOutputStream');
        var stream = new ByteArrayOutputStream();
        return Tinkerpop.GraphSONWriter.buildP()
            .then(function (builder) {
            return _newGraphSONMapper()
                .then(function (mapper) { return builder.mapperP(mapper); });
        })
            .then(function (builder) { return builder.createP(); })
            .then(function (writer) { return writer.writeGraphP(stream, graph); })
            .then(function () { return stream.toStringP(); })
            .then(function (ugly) {
            var prettyString = _prettyGraphSONString(ugly);
            var writeFileP = BluePromise.promisify(fs.writeFile);
            return writeFileP(filename, prettyString);
        })
            .then(function () { return graph; })
            .nodeify(callback);
    }
799662
function nodeExtent(graph, attribute) {
  if (!isGraph(graph))
    throw new Error('graphology-metrics/extent: the given graph is not a valid graphology instance.');

  var attributes = [].concat(attribute);

  var nodes = graph.nodes(),
      node,
      data,
      value,
      key,
      a,
      i,
      l;

  var results = {};

  for (a = 0; a < attributes.length; a++) {
    key = attributes[a];

    results[key] = [Infinity, -Infinity];
  }

  for (i = 0, l = nodes.length; i < l; i++) {
    node = nodes[i];
    data = graph.getNodeAttributes(node);

    for (a = 0; a < attributes.length; a++) {
      key = attributes[a];
      value = data[key];

      if (value < results[key][0])
        results[key][0] = value;

      if (value > results[key][1])
        results[key][1] = value;
    }
  }

  return typeof attribute === 'string' ? results[attribute] : results;
}
262101
function simplify(g) {
  var simplified = new Graph().setGraph(g.graph());
  _.forEach(g.nodes(), function(v) { simplified.setNode(v, g.node(v)); });
  _.forEach(g.edges(), function(e) {
    var simpleLabel = simplified.edge(e.v, e.w) || { weight: 0, minlen: 1 };
    var label = g.edge(e);
    simplified.setEdge(e.v, e.w, {
      weight: simpleLabel.weight + label.weight,
      minlen: Math.max(simpleLabel.minlen, label.minlen)
    });
  });
  return simplified;
}
868905
function sortNodesByDepth (graph) {
      // Build the map of nodes to their levels
      let nodesSortedByDepth = [];
      let index;
      for (index in graph.nodes) {
        if ({}.hasOwnProperty.call(graph.nodes, index)) {
          const node = graph.nodes[index];
          nodesSortedByDepth[node.rank] = nodesSortedByDepth[node.rank] || [];
          nodesSortedByDepth[node.rank].push(node);
        }
      }

      // Remove empty ranks (and normalize to base 0)
      nodesSortedByDepth = nodesSortedByDepth.reduce((a, n) => { a.push(n); return a; }, []);

      const maxNodesPerDepth = 30;
      for (let i = 0; i < nodesSortedByDepth.length; i++) {
        const nodesInDepth = nodesSortedByDepth[i];
        if (nodesInDepth.length > maxNodesPerDepth) {
          const nodesToKeep = Math.min((nodesInDepth.length / 2) - 1, maxNodesPerDepth);
          const newNodeDepth = nodesInDepth.splice(nodesToKeep);
          nodesSortedByDepth.splice(i + 1, 0, newNodeDepth);
        }
      }

      return nodesSortedByDepth;
    }
581166
function resolveNodeSkel(index, nodeName) {
    var idx = +graph.nameToIndex[nodeName];
    argh = [idx, +index]
    if(Number.isNaN(idx)) {
      throw "Unable to get index for node '" + nodeName + "'. (Is the node name misspelled?)";
    }
    if(index !== undefined && idx > +index) {
      throw "Unable to get index for node '" + nodeName + "'. (Are the nodes out of order?)";
    }
    if(index !== undefined && idx == +index) {
      throw "Unable to get index for node '" + nodeName + "'. (Is the node trying to reference itself?)";
    }
    return (dataContext) => dataContext.values[idx];
  }
1160085
def graph(graph_def, max_const_size=32):
    
    if hasattr(graph_def, 'as_graph_def'):
        graph_def = graph_def.as_graph_def()
    strip_def = _strip_consts(graph_def, max_const_size=max_const_size)
    code = """
        <script>
          function load() {{
            document.getElementById("{id}").pbtxt = {data};
          }}
        </script>
        <link rel="import" href="https://tensorboard.appspot.com/tf-graph-basic.build.html" onload=load()>
        <div style="height:600px">
          <tf-graph-basic id="{id}"></tf-graph-basic>
        </div>
    """.format(data=repr(str(strip_def)), id='graph'+str(np.random.rand()))

    iframe = """
        <iframe seamless style="width:100%; height:620px; border: none;" srcdoc="{}"></iframe>
    """.format(code.replace('"', '&quot;'))
    _display_html(iframe)
647685
function removeEdge(u, v){
    if(edges[u]){
      edges[u] = adjacent(u).filter(function (_v){
        return _v !== v;
      });
    }
    return graph;
  }
357621
function makeAcyclic(g) {
    var onStack = {};
    var visited = {};

    function dfs(u) {
      if (u in visited) {
        return;
      }
      visited[u] = true;
      onStack[u] = true;
      g.successors(u).forEach(function(v) {
        if (v in onStack) {
          g.addEdge(v, u);
          g.removeEdge(u, v);
        } else {
          dfs(v);
        }
      });
      delete onStack[u];
    }

    g.nodes().forEach(function(u) {
      dfs(u);
    });
  }
1153717
function Graph(directed) {
  this.directed = (directed === undefined ? true : !!directed);
  this.adjList = Object.create(null);
  this.vertices = new HashSet();
}
795
function createEdgeIterator(graph, type) {
  if (graph.size === 0)
    return Iterator.empty();

  let iterator;

  if (type === 'mixed') {
    iterator = graph._edges.values();

    return new Iterator(function next() {
      const step = iterator.next();

      if (step.done)
        return step;

      const data = step.value;

      const value = [
        data.key,
        data.attributes,
        data.source.key,
        data.target.key,
        data.source.attributes,
        data.target.attributes
      ];

      return {value, done: false};
    });
  }

  iterator = graph._edges.values();

  return new Iterator(function next() {
    const step = iterator.next();

    if (step.done)
      return step;

    const data = step.value;

    if ((data instanceof UndirectedEdgeData) === (type === 'undirected')) {
      const value = [
        data.key,
        data.attributes,
        data.source.key,
        data.target.key,
        data.source.attributes,
        data.target.attributes
      ];

      return {value, done: false};
    }

    return next();
  });
}
167258
function getGraphQLValue(value) {
      if ("string" === typeof value) {
        value = JSON.stringify(value);
      } else if (Array.isArray(value)) {
        value = value.map(item => {
            return getGraphQLValue(item);
            }).join();
        value = `[${value}]`;
      } else if ("object" === typeof value) {
      /*if (value.toSource)
            value = value.toSource().slice(2,-2);
        else*/
            value = objectToString(value);
            //console.error("No toSource!!",value);
      }
      return value;
}
494235
function flagCircularDependencies(graph) {
	var includes = require("lodash/includes");
	var nodes = Array.isArray(graph) ? graph : require("lodash/values")(graph);

	for (var i = 0; i < nodes.length; i += 1) {
		var curr = nodes[i];

		for (var j = i + 1; j < nodes.length; j += 1) {
			var next = nodes[j];

			if (
				includes(curr.dependencies, next.load.name) &&
				includes(next.dependencies, curr.load.name)
			) {
				curr.load.circular = true;
				next.load.circular = true;
			}
		}
	}

	return graph;
}
388086
function loadGraphSONSync(graph, filename) {
        var FileInputStream = Tinkerpop.autoImport('FileInputStream');
        var stream = new FileInputStream(filename);
        var builder = Tinkerpop.GraphSONReader.build();
        var mapper = _newGraphSONMapperSync();
        builder.mapper(mapper);
        var reader = builder.create();
        reader.readGraph(stream, graph);
        return graph;
    }
238434
function validate (graph, additionalFunctions) {
  // Required properties.
  var pipe = graph.pipe
  var task = graph.task

  // Optional properties.
  var data = graph.data || {}
  var func = graph.func || {}
  var info = graph.info || {}

  var seenPipe = {}

  // Validate addition functions, if any.
  // Check there are no reserved keys.

  function throwIfEquals (taskName, reservedKey) {
    if (taskName === reservedKey) {
      throw new TypeError('Reserved function name: ' + taskName)
    }
  }

  if (typeof additionalFunctions === 'object') {
    for (var taskName in additionalFunctions) {
      var throwIfEqualsTaskName = throwIfEquals.bind(null, taskName)

      reservedKeys.forEach(throwIfEqualsTaskName)

      if (regexArgument.test(taskName)) {
        throw new TypeError('Reserved function name: ' + taskName)
      }

      if (regexAccessor.test(taskName)) {
        throw new TypeError('Function name cannot start with "@": ' + taskName)
      }

      if (regexDotOperator.attrRead.test(taskName)) {
        throw new TypeError('Function name cannot start with ".":' + taskName)
      }

      if (regexDotOperator.attrWrite.test(taskName)) {
        throw new TypeError('Function name cannot start with "." and end with "=":' + taskName)
      }

      if (regexDotOperator.func.test(taskName)) {
        throw new TypeError('Function name cannot start with "." and end with "()":' + taskName)
      }

      if (regexReference.test(taskName)) {
        throw new TypeError('Function name cannot start with "&": ' + taskName)
      }
    }
  }

  // Check pipe and task are objects.

  if (typeof pipe !== 'object') {
    throw new TypeError('Not an object: pipe ' + pipe)
  }

  if (typeof task !== 'object') {
    throw new TypeError('Not an object: task ' + task)
  }

  // Check optional data, func, info and view are objects.

  if (typeof data !== 'object') {
    throw new TypeError('Not an object: data ' + data)
  }

  if (typeof func !== 'object') {
    throw new TypeError('Not an object: func ' + func)
  }

  if (typeof info !== 'object') {
    throw new TypeError('Not an object: info ' + info)
  }

  function checkPipe (key) {
    var arg = pipe[key][2] || 0
    var from = pipe[key][0]
    var to = pipe[key][1]

    // Check types.

    if (typeof arg !== 'number') {
      throw new TypeError('Invalid pipe: ' + pipe[key])
    }

    if (typeof from !== 'string') {
      throw new TypeError('Invalid pipe: ' + pipe[key])
    }

    if (typeof to !== 'string') {
      throw new TypeError('Invalid pipe: ' + pipe[key])
    }

    // Check for orphan pipes.

    if (no(task[from])) throw new Error('Orphan pipe: ' + pipe[key])

    if (no(task[to])) throw new Error('Orphan pipe: ' + pipe[key])

    // Remember pipes, avoid duplicates.

    if (no(seenPipe[from])) seenPipe[from] = {}

    if (no(seenPipe[from][to])) seenPipe[from][to] = []

    if (no(seenPipe[from][to][arg])) seenPipe[from][to][arg] = true
    else throw new Error('Duplicated pipe: ' + pipe[key])
  }

  Object.keys(pipe)
    .forEach(checkPipe)

  // Check that every subgraph referenced are defined.

  function onlySubgraphs (key) {
    var taskName = task[key]

    return regexSubgraph.test(taskName)
  }

  function checkSubgraph (key) {
    var taskName = task[key]

    var funcName = taskName.substring(1)

    if (no(func[funcName])) throw new Error('Undefined subgraph: ' + funcName)
  }

  Object.keys(task)
    .filter(onlySubgraphs)
    .forEach(checkSubgraph)

  // Recursively check subgraphs in func property.

  function checkFunc (key) {
    validate(func[key], additionalFunctions)
  }

  if (typeof func === 'object') {
    Object.keys(func)
      .forEach(checkFunc)
  }

  return true
}
820045
function BoundJSONGraphModelError() {
    var instance = new Error("It is not legal to use the JSON Graph " +
    "format from a bound Model. JSON Graph format" +
    " can only be used from a root model.");

    instance.name = "BoundJSONGraphModelError";

    if (Object.setPrototypeOf) {
        Object.setPrototypeOf(instance, Object.getPrototypeOf(this));
    }

    if (Error.captureStackTrace) {
        Error.captureStackTrace(instance, BoundJSONGraphModelError);
    }

    return instance;
}