### `_newGraphSONMapper()` Create a GraphSONMapper (promise) that preserves types.
17627
function _newGraphSONMapper() {
        return Tinkerpop.GraphSONMapper.buildP()
            .then(function (builder) {
            return builder.embedTypesP(true);
        })
            .then(function (builder) {
            return builder.createP();
        });
    }
891624
function stringToGraphQLType(type) {
  switch (type) {
    case 'String':
      return GraphQLString;
    case 'Number':
      return GraphQLFloat;
    case 'Date':
      return GraphQLDate;
    case 'Buffer':
      return GraphQLBuffer;
    case 'Boolean':
      return GraphQLBoolean;
    case 'ObjectID':
      return GraphQLID;
    default:
      return GraphQLGeneric;
  }
}
267579
private ErrorDetectingWrapper createUnmappedChain() {
		int nextIndex = this.graphRequests.size();

		return
			new ErrorDetectingWrapper(
				new GraphNodeExtractor(nextIndex, this.mapper,
					new ErrorDetectingWrapper(this)));
	}
16979
function factoryObjectGraph(ParentClassGraph) {
  /**
   * Inherited class. Class with methods for control links in graph.
   * Adapted for array collection.
   * 
   * @class
   * @description `import { ObjectGraph as Graph } from 'ancient-graph';`
   */
  class ObjectGraph extends ParentClassGraph {
    
    /**
     * Construct new graph and checks for required adaptation methods.
     * @param {Array[]} collection
     * @param {Object.<string, string>} fields - matching of fields in the link with fields in document
     * @param {Object} [config] - Additional config.
     * @param {Object} [config.aliases]
     * @param {String} [config.aliases.$]
     * @throws {Error} if the adapter methods is not complete
     */
    constructor(collection, fields, config) {
      super(...arguments);
      this.emitter = new EventEmitter();
    }
    
    /**
     * Specifies the id field on insert
     * 
     * @param {number} index
     * @param {Link} link
     * @return {number|string} id;
     */
    _idGenerator(index, link) {
      return ""+index;
    };
    
    /**
     * Generate insert modifier.
     * 
     * @param {number} index
     * @param {Link} link
     * @return {number|string} id;
     */
    _insertModifier(link) {
      var _modifier = {};
      for (var f in link) {
        if (this.fields[f]) {
          _modifier[this.fields[f]] = link[this.config.aliases[f]];
        }
      }
      return _modifier;
    };
    
    /**
     * Should insert new link into graph.
     * Return a synchronous result. This can be useful in your application. But for writing generic code, it is recommended to only use the callback result.
     * 
     * @param {Link} link
     * @param {Graph~insertCallback} [callback]
     * @param {Object} [context]
     * @return {number|string} [id]
     */
    insert(link, callback, context) {
      this.callback
      var _modifier = this._insertModifier(link);
      var index, error, id;
      try {
        index = this.collection.push(_modifier) - 1;
        if (!this.collection[index].hasOwnProperty(this.fields[this.config.aliases['id']])) {
          id = this.collection[index][this.fields[this.config.aliases['id']]] = this._idGenerator(index, this.collection[index]);
        }
        this.emitter.emit('insert', this.collection[index]);
      } catch(_error) {
        error = _error;
      }
      if (callback) {
        callback(error, id)
      }
      return id;
    }
    
    /**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the unique id of inserted link as the second.
     *
     * @callback Graph~insertCallback
     * @param {Error} [error]
     * @param {number|string} [id]
     */
    
    /**
     * Push into link value some item/items.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */
    _updateModifierPush(data, item) {
      data.push(item);
    }
    
    /**
     * Push into link value some item/items if not already exists.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */
    _updateModifierAdd(data, item) {
      if (lodash.isArray(item)) {
        for (var i in item) {
          this._updateModifierAdd(data, item[i]);
        }
      } else {
        var index = lodash.indexOf(data, item);
        if (index < 0) {
          this._updateModifierPush(data, item);
        }
      }
    }
     
    /**
     * Remove from link value some item/items.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */
    _updateModifierRemove(data, item) {
      if (lodash.isArray(item)) {
        for (var i in item) {
          this._updateModifierRemove(data, item[i]);
        }
      } else {
        lodash.remove(data, function(value) {
          return value == item;
        });
      }
    }
  
    /**
     * Generate update modifier.
     * 
     * @param {LinkModifier} modifier 
     * @param {Object} result
     * @return {number|string} id;
     */
    _updateModifier(modifier, result) {
      for (var m in modifier) {
        if (this.fields[m]) {
          if (typeof(modifier[m]) == 'undefined') {
            delete result[this.fields[m]];
          } else {
            if (typeof(modifier[m]) == 'object') {
              if (lodash.isArray(modifier[m])) {
                result[this.fields[m]] = modifier[m];
              } else {
                if (!lodash.isArray(result[this.fields[m]])) {
                  result[this.fields[m]] = result[this.fields[m]]?[result[this.fields[m]]]:[];
                }
                for (var key in modifier[m]) {
                  if (key == 'add') {
                    this._updateModifierAdd(result[this.fields[m]], modifier[m][key]);
                  }
                  if (key == 'push') {
                    this._updateModifierPush(result[this.fields[m]], modifier[m][key]);
                  }
                  if (key == 'remove') {
                    this._updateModifierRemove(result[this.fields[m]], modifier[m][key]);
                  }
                }
              }
            } else {
              result[this.fields[m]] = modifier[m];
            }
          }
        }
      }
    };
    
    /**
     * Should update to new state of modifier object link by unique id or by link query object.
     * If the database allows, it is recommended to return a synchronous result. This can be useful in your application. But for writing generic code, it is recommended to only use the callback result.
     * 
     * @param {string|LinkSelector} selector
     * @param {LinkModifier} modifier
     * @param {Graph~updateCallback} [callback]
     * @param {Object} [context]
     * @return {number} [count]
     */
    update(selector, modifier, callback, context) {
      var results = this._fetch(selector);
      for (var r in results) {
        var oldResult = lodash.cloneDeep(results[r]);
        this._updateModifier(modifier, results[r]);
        this.emitter.emit('update', results[r], oldResult);
      }
      if (callback) callback(undefined, results.length);
      return results.length;
    }
    
    /**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.
     *
     * @callback Graph~updateCallback
     * @param {Error} [error]
     * @param {number} [count]
     */
    
    /**
     * Should remove link by unique id or by link query object.
     * 
     * @param {string|LinkSelector} selector
     * @param {Graph~removeCallback} [callback]
     * @param {Object} [context]
     */
    remove(selector, callback, context) {
      var oldLength = this.collection.length;
      var removed = [];
      lodash.remove(this.collection, (result) => {
        var _query = this.query(selector)(result);
        if (_query) removed.push(result)
        return _query;
      });
      for (var r in removed) {
        this.emitter.emit('remove', removed[r]);
      }
      var newLength = this.collection.length;
      if (callback) callback(undefined, oldLength - newLength);
    }
    
    /**
     * Optional callback. If present, called with an error object as the first argument.
     *
     * @callback Graph~removeCallback
     * @param {Error} [error]
     * @param {number} [count]
     */
    
    /**
     * Generate adapter for database query for links search by unique id or by link query object.
     * 
     * @param {string|LinkSelector} selector
     * @return {*} query
     */
    query(selector) {
      var type = typeof(selector);
      if (type == 'string' || type == 'number') {
        return (doc) => { return doc[this.fields[this.config.aliases['id']]] == selector };
      } else if (type == 'object') {
        return (doc) => {
          if (typeof(doc) != 'object') return false;
          for (var m in selector) {
            if (this.fields[m]) {
              if (typeof(selector[m]) == 'undefined') {
                if (doc.hasOwnProperty(this.fields[m])) return false;
              } else {
                if (lodash.isArray(doc[this.fields[m]])) {
                  if (lodash.isArray(selector[m])) {
                    for (var s in selector[m]) {
                      if (!lodash.includes(doc[this.fields[m]], selector[m][s])) {
                        return false;
                      }
                    }
                  } else {
                    if (!lodash.includes(doc[this.fields[m]], selector[m])) {
                      return false;
                    }
                  }
                } else {
                  if (doc[this.fields[m]] != selector[m]) return false;
                }
              }
            }
          }
          return true;
        }
      }
    }
    
    /**
     * Generate adapted for database options object.
     * 
     * @param {Object} [options]
     * @return {*} options - a options suitable for the database
     */
    options(options) {
      var _options = {};
      if (options) {
        if (options.sort) {
          _options.sort = { keys: [], orders: [] };
          for (var s in options.sort) {
            if (this.fields[s]) {
              _options.sort.keys.push(this.fields[s]);
              _options.sort.orders.push(options.sort[s]?'asc':'desc');
            }
          }
        }
        if (typeof(options.skip) == 'number') {
          _options.skip = options.skip;
        }
        if (typeof(options.limit) == 'number') {
          _options.limit = options.limit;
        }
      }
      return _options;
    }
    
    /**
     * Generate Link from document by fields.
     * 
     * @param {Object} document
     * @return {Link} link
     */
    _generateLink(document) {
      var link = {};
      for (var f in this.fields) {
        if (document.hasOwnProperty(this.fields[f])) {
          link[f] = document[this.fields[f]];
        }
      }
      return link;
    }
    
    /**
     * Get one first matching link.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~getCallback} [callback]
     * @return {Link} link - result link object
     */
    get(selector, options, callback) {
      var results = this.fetch(selector, options, (error, results) => {
        if (callback) callback(error, results?results[0]:undefined);
      });
      if (results) return results[0];
    }
    
    /**
     * Fetch native database documents.
     * 
     * @param {string|linkSelector} selector
     * @param {SelectOptions} [options]
     * @return {Object[]} documents - result documents
     */
    _fetch(selector, options) {
      var query = this.query(selector);
      var documents = lodash.filter(this.collection, query); 
      var _options = this.options(options);
      if (_options.sort) documents = lodash.orderBy(documents, _options.sort.keys, _options.orders);
      var skip = _options.skip?_options.skip:0;
      var limit = _options.limit?skip+_options.limit:_options.limit;
      documents = documents.slice(skip, limit);
      return documents;
    }
    
    /**
     * Find and all matching links as an Array.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~fetchCallback} [callback]
     * @return {Link[]} links - result links objects in array
     */
    fetch(selector, options, callback) {
      var documents = this._fetch(selector, options);
      var links = [];
      for (var d in documents) {
        links.push(this._generateLink(documents[d]));
      }
      if (callback) callback(undefined, links);
      return links;
    }
    
    /**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the result links objects in array.
     *
     * @callback Graph~fetchCallback
     * @param {Error} [error]
     * @param {Link[]} [links]
     */
    
    /**
     * Should call callback once for each matching document, sequentially and synchronously.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~eachCallback} [callback]
     */
    each(selector, options, callback) {
      var links = this.fetch(selector, options);
      for (var l in links) {
        callback(links[l]);
      }
    }
    
    /**
     * @callback Graph~eachCallback
     * @param {Link} [link]
     */
    
    /**
     * Map callback over all matching documents. Returns an Array.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~mapCallback} [callback]
     * @return {Array} results
     */
    map(selector, options, callback) {
      var links = this.fetch(selector, options);
      return links.map(callback);
    }
    
    /**
     * @callback Graph~mapCallback
     * @param {Link} [link]
     * @return {*} result
     */
    
    /**
     * Count all matching documents.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~countCallback} [callback]
     * @return {number} [count]
     */
    count(selector, options, callback) {
      var links = this.fetch(selector, options);
      if (callback) callback(undefined, links.length);
      return links.length;
    }
    
    /**
     * @callback Graph~countCallback
     * @param {Error} [error]
     * @param {number} [count]
     */
    
    /**
     * Should subscribe to the events: link, unlink, insert, update, remove.
     * 
     * @param {string} event - One event name
     * @param {Graph~onCallback} callback
     * @returns {Function} Stops event subscription.
     * @example
     * var counter = 0;
     * var stop = graph.on('update', (oldData, newData) => {
     *   if (oldData.id == '1') console.log(oldData.id, 'is changed');
     *   counter++;
     *   if (counter == 3) stop();
     * });
     */
    on(event, callback) {
      var subscriptions = [];
      
      if (event == 'insert') {
        subscriptions.push(this.emitter.addListener('insert', (document) => {
          callback(undefined, this._generateLink(document));
        }));
      }
      if (event == 'update') {
        subscriptions.push(this.emitter.addListener('update', (newDocument, oldDocument) => {
          callback(this._generateLink(oldDocument), this._generateLink(newDocument));
        }));
      }
      if (event == 'remove') {
        subscriptions.push(this.emitter.addListener('remove', (document) => {
          callback(this._generateLink(document), undefined);
        }));
      }
      if (event == 'link') {
        subscriptions.push(this.emitter.addListener('insert', (document) => {
          callback(undefined, this._generateLink(document));
        }));
        subscriptions.push(this.emitter.addListener('update', (newDocument, oldDocument) => {
          callback(this._generateLink(oldDocument), this._generateLink(newDocument));
        }));
      }
      if (event == 'unlink') {
        subscriptions.push(this.emitter.addListener('update', (newDocument, oldDocument) => {
          callback(this._generateLink(oldDocument), this._generateLink(newDocument));
        }));
        subscriptions.push(this.emitter.addListener('remove', (document) => {
          callback(this._generateLink(document), undefined);
        }));
      }
      
      return () => {
        for (var subscription of subscriptions) {
          subscription.remove();
        }
      };
    }
    
    /**
     * @callback Graph~onCallback
     * @param {Link} [oldLink] - can be undefined on link and insert events
     * @param {Link} [newLink] - can be undefined on unlink and remove events
     * @param {Object} [context] - additional app information, such as context.userId
     */
  }
  
  return ObjectGraph;
}
836822
public <NV> Graph<K, NV, EV> mapVertices(final MapFunction<Vertex<K, VV>, NV> mapper, TypeInformation<Vertex<K, NV>> returnType) {
		DataSet<Vertex<K, NV>> mappedVertices = vertices.map(
				new MapFunction<Vertex<K, VV>, Vertex<K, NV>>() {
					private Vertex<K, NV> output = new Vertex<>();

					public Vertex<K, NV> map(Vertex<K, VV> value) throws Exception {
						output.f0 = value.f0;
						output.f1 = mapper.map(value);
						return output;
					}
				})
				.returns(returnType)
				.withForwardedFields("f0")
					.name("Map vertices");

		return new Graph<>(mappedVertices, this.edges, this.context);
	}
179169
function createGraph(options) {
  // Graph structure is maintained as dictionary of nodes
  // and array of links. Each node has 'links' property which
  // hold all links related to that node. And general links
  // array is used to speed up all links enumeration. This is inefficient
  // in terms of memory, but simplifies coding.
  options = options || {};
  if ('uniqueLinkId' in options) {
    console.warn(
      'ngraph.graph: Starting from version 0.14 `uniqueLinkId` is deprecated.\n' +
      'Use `multigraph` option instead\n',
      '\n',
      'Note: there is also change in default behavior: From now on each graph\n'+
      'is considered to be not a multigraph by default (each edge is unique).'
    );

    options.multigraph = options.uniqueLinkId;
  }

  // Dear reader, the non-multigraphs do not guarantee that there is only
  // one link for a given pair of node. When this option is set to false
  // we can save some memory and CPU (18% faster for non-multigraph);
  if (options.multigraph === undefined) options.multigraph = false;

  var nodes = typeof Object.create === 'function' ? Object.create(null) : {},
    links = [],
    // Hash of multi-edges. Used to track ids of edges between same nodes
    multiEdges = {},
    nodesCount = 0,
    suspendEvents = 0,

    forEachNode = createNodeIterator(),
    createLink = options.multigraph ? createUniqueLink : createSingleLink,

    // Our graph API provides means to listen to graph changes. Users can subscribe
    // to be notified about changes in the graph by using `on` method. However
    // in some cases they don't use it. To avoid unnecessary memory consumption
    // we will not record graph changes until we have at least one subscriber.
    // Code below supports this optimization.
    //
    // Accumulates all changes made during graph updates.
    // Each change element contains:
    //  changeType - one of the strings: 'add', 'remove' or 'update';
    //  node - if change is related to node this property is set to changed graph's node;
    //  link - if change is related to link this property is set to changed graph's link;
    changes = [],
    recordLinkChange = noop,
    recordNodeChange = noop,
    enterModification = noop,
    exitModification = noop;

  // this is our public API:
  var graphPart = {
    /**
     * Adds node to the graph. If node with given id already exists in the graph
     * its data is extended with whatever comes in 'data' argument.
     *
     * @param nodeId the node's identifier. A string or number is preferred.
     * @param [data] additional data for the node being added. If node already
     *   exists its data object is augmented with the new one.
     *
     * @return {node} The newly added node or node with given id if it already exists.
     */
    addNode: addNode,

    /**
     * Adds a link to the graph. The function always create a new
     * link between two nodes. If one of the nodes does not exists
     * a new node is created.
     *
     * @param fromId link start node id;
     * @param toId link end node id;
     * @param [data] additional data to be set on the new link;
     *
     * @return {link} The newly created link
     */
    addLink: addLink,

    /**
     * Removes link from the graph. If link does not exist does nothing.
     *
     * @param link - object returned by addLink() or getLinks() methods.
     *
     * @returns true if link was removed; false otherwise.
     */
    removeLink: removeLink,

    /**
     * Removes node with given id from the graph. If node does not exist in the graph
     * does nothing.
     *
     * @param nodeId node's identifier passed to addNode() function.
     *
     * @returns true if node was removed; false otherwise.
     */
    removeNode: removeNode,

    /**
     * Gets node with given identifier. If node does not exist undefined value is returned.
     *
     * @param nodeId requested node identifier;
     *
     * @return {node} in with requested identifier or undefined if no such node exists.
     */
    getNode: getNode,

    /**
     * Gets number of nodes in this graph.
     *
     * @return number of nodes in the graph.
     */
    getNodesCount: function () {
      return nodesCount;
    },

    /**
     * Gets total number of links in the graph.
     */
    getLinksCount: function () {
      return links.length;
    },

    /**
     * Gets all links (inbound and outbound) from the node with given id.
     * If node with given id is not found null is returned.
     *
     * @param nodeId requested node identifier.
     *
     * @return Array of links from and to requested node if such node exists;
     *   otherwise null is returned.
     */
    getLinks: getLinks,

    /**
     * Invokes callback on each node of the graph.
     *
     * @param {Function(node)} callback Function to be invoked. The function
     *   is passed one argument: visited node.
     */
    forEachNode: forEachNode,

    /**
     * Invokes callback on every linked (adjacent) node to the given one.
     *
     * @param nodeId Identifier of the requested node.
     * @param {Function(node, link)} callback Function to be called on all linked nodes.
     *   The function is passed two parameters: adjacent node and link object itself.
     * @param oriented if true graph treated as oriented.
     */
    forEachLinkedNode: forEachLinkedNode,

    /**
     * Enumerates all links in the graph
     *
     * @param {Function(link)} callback Function to be called on all links in the graph.
     *   The function is passed one parameter: graph's link object.
     *
     * Link object contains at least the following fields:
     *  fromId - node id where link starts;
     *  toId - node id where link ends,
     *  data - additional data passed to graph.addLink() method.
     */
    forEachLink: forEachLink,

    /**
     * Suspend all notifications about graph changes until
     * endUpdate is called.
     */
    beginUpdate: enterModification,

    /**
     * Resumes all notifications about graph changes and fires
     * graph 'changed' event in case there are any pending changes.
     */
    endUpdate: exitModification,

    /**
     * Removes all nodes and links from the graph.
     */
    clear: clear,

    /**
     * Detects whether there is a link between two nodes.
     * Operation complexity is O(n) where n - number of links of a node.
     * NOTE: this function is synonim for getLink()
     *
     * @returns link if there is one. null otherwise.
     */
    hasLink: getLink,

    /**
     * Detects whether there is a node with given id
     * 
     * Operation complexity is O(1)
     * NOTE: this function is synonim for getNode()
     *
     * @returns node if there is one; Falsy value otherwise.
     */
    hasNode: getNode,

    /**
     * Gets an edge between two nodes.
     * Operation complexity is O(n) where n - number of links of a node.
     *
     * @param {string} fromId link start identifier
     * @param {string} toId link end identifier
     *
     * @returns link if there is one. null otherwise.
     */
    getLink: getLink
  };

  // this will add `on()` and `fire()` methods.
  eventify(graphPart);

  monitorSubscribers();

  return graphPart;

  function monitorSubscribers() {
    var realOn = graphPart.on;

    // replace real `on` with our temporary on, which will trigger change
    // modification monitoring:
    graphPart.on = on;

    function on() {
      // now it's time to start tracking stuff:
      graphPart.beginUpdate = enterModification = enterModificationReal;
      graphPart.endUpdate = exitModification = exitModificationReal;
      recordLinkChange = recordLinkChangeReal;
      recordNodeChange = recordNodeChangeReal;

      // this will replace current `on` method with real pub/sub from `eventify`.
      graphPart.on = realOn;
      // delegate to real `on` handler:
      return realOn.apply(graphPart, arguments);
    }
  }

  function recordLinkChangeReal(link, changeType) {
    changes.push({
      link: link,
      changeType: changeType
    });
  }

  function recordNodeChangeReal(node, changeType) {
    changes.push({
      node: node,
      changeType: changeType
    });
  }

  function addNode(nodeId, data) {
    if (nodeId === undefined) {
      throw new Error('Invalid node identifier');
    }

    enterModification();

    var node = getNode(nodeId);
    if (!node) {
      node = new Node(nodeId, data);
      nodesCount++;
      recordNodeChange(node, 'add');
    } else {
      node.data = data;
      recordNodeChange(node, 'update');
    }

    nodes[nodeId] = node;

    exitModification();
    return node;
  }

  function getNode(nodeId) {
    return nodes[nodeId];
  }

  function removeNode(nodeId) {
    var node = getNode(nodeId);
    if (!node) {
      return false;
    }

    enterModification();

    var prevLinks = node.links;
    if (prevLinks) {
      node.links = null;
      for(var i = 0; i < prevLinks.length; ++i) {
        removeLink(prevLinks[i]);
      }
    }

    delete nodes[nodeId];
    nodesCount--;

    recordNodeChange(node, 'remove');

    exitModification();

    return true;
  }


  function addLink(fromId, toId, data) {
    enterModification();

    var fromNode = getNode(fromId) || addNode(fromId);
    var toNode = getNode(toId) || addNode(toId);

    var link = createLink(fromId, toId, data);

    links.push(link);

    // TODO: this is not cool. On large graphs potentially would consume more memory.
    addLinkToNode(fromNode, link);
    if (fromId !== toId) {
      // make sure we are not duplicating links for self-loops
      addLinkToNode(toNode, link);
    }

    recordLinkChange(link, 'add');

    exitModification();

    return link;
  }

  function createSingleLink(fromId, toId, data) {
    var linkId = makeLinkId(fromId, toId);
    return new Link(fromId, toId, data, linkId);
  }

  function createUniqueLink(fromId, toId, data) {
    // TODO: Get rid of this method.
    var linkId = makeLinkId(fromId, toId);
    var isMultiEdge = multiEdges.hasOwnProperty(linkId);
    if (isMultiEdge || getLink(fromId, toId)) {
      if (!isMultiEdge) {
        multiEdges[linkId] = 0;
      }
      var suffix = '@' + (++multiEdges[linkId]);
      linkId = makeLinkId(fromId + suffix, toId + suffix);
    }

    return new Link(fromId, toId, data, linkId);
  }

  function getLinks(nodeId) {
    var node = getNode(nodeId);
    return node ? node.links : null;
  }

  function removeLink(link) {
    if (!link) {
      return false;
    }
    var idx = indexOfElementInArray(link, links);
    if (idx < 0) {
      return false;
    }

    enterModification();

    links.splice(idx, 1);

    var fromNode = getNode(link.fromId);
    var toNode = getNode(link.toId);

    if (fromNode) {
      idx = indexOfElementInArray(link, fromNode.links);
      if (idx >= 0) {
        fromNode.links.splice(idx, 1);
      }
    }

    if (toNode) {
      idx = indexOfElementInArray(link, toNode.links);
      if (idx >= 0) {
        toNode.links.splice(idx, 1);
      }
    }

    recordLinkChange(link, 'remove');

    exitModification();

    return true;
  }

  function getLink(fromNodeId, toNodeId) {
    // TODO: Use sorted links to speed this up
    var node = getNode(fromNodeId),
      i;
    if (!node || !node.links) {
      return null;
    }

    for (i = 0; i < node.links.length; ++i) {
      var link = node.links[i];
      if (link.fromId === fromNodeId && link.toId === toNodeId) {
        return link;
      }
    }

    return null; // no link.
  }

  function clear() {
    enterModification();
    forEachNode(function(node) {
      removeNode(node.id);
    });
    exitModification();
  }

  function forEachLink(callback) {
    var i, length;
    if (typeof callback === 'function') {
      for (i = 0, length = links.length; i < length; ++i) {
        callback(links[i]);
      }
    }
  }

  function forEachLinkedNode(nodeId, callback, oriented) {
    var node = getNode(nodeId);

    if (node && node.links && typeof callback === 'function') {
      if (oriented) {
        return forEachOrientedLink(node.links, nodeId, callback);
      } else {
        return forEachNonOrientedLink(node.links, nodeId, callback);
      }
    }
  }

  function forEachNonOrientedLink(links, nodeId, callback) {
    var quitFast;
    for (var i = 0; i < links.length; ++i) {
      var link = links[i];
      var linkedNodeId = link.fromId === nodeId ? link.toId : link.fromId;

      quitFast = callback(nodes[linkedNodeId], link);
      if (quitFast) {
        return true; // Client does not need more iterations. Break now.
      }
    }
  }

  function forEachOrientedLink(links, nodeId, callback) {
    var quitFast;
    for (var i = 0; i < links.length; ++i) {
      var link = links[i];
      if (link.fromId === nodeId) {
        quitFast = callback(nodes[link.toId], link);
        if (quitFast) {
          return true; // Client does not need more iterations. Break now.
        }
      }
    }
  }

  // we will not fire anything until users of this library explicitly call `on()`
  // method.
  function noop() {}

  // Enter, Exit modification allows bulk graph updates without firing events.
  function enterModificationReal() {
    suspendEvents += 1;
  }

  function exitModificationReal() {
    suspendEvents -= 1;
    if (suspendEvents === 0 && changes.length > 0) {
      graphPart.fire('changed', changes);
      changes.length = 0;
    }
  }

  function createNodeIterator() {
    // Object.keys iterator is 1.3x faster than `for in` loop.
    // See `https://github.com/anvaka/ngraph.graph/tree/bench-for-in-vs-obj-keys`
    // branch for perf test
    return Object.keys ? objectKeysIterator : forInIterator;
  }

  function objectKeysIterator(callback) {
    if (typeof callback !== 'function') {
      return;
    }

    var keys = Object.keys(nodes);
    for (var i = 0; i < keys.length; ++i) {
      if (callback(nodes[keys[i]])) {
        return true; // client doesn't want to proceed. Return.
      }
    }
  }

  function forInIterator(callback) {
    if (typeof callback !== 'function') {
      return;
    }
    var node;

    for (node in nodes) {
      if (callback(nodes[node])) {
        return true; // client doesn't want to proceed. Return.
      }
    }
  }
}
1260955
private <T> GraphRequest<T> graph(String object, JavaType type, Param... params) {
		this.checkForBatchExecution();
		
		// The data is transformed through a chain of wrappers
		GraphRequest<T> req =
			new GraphRequest<T>(object, params, this.mapper, this.<T>createMappingChain(type));
		
		this.graphRequests.add(req);
		return req;
	}
1179095
function it_leavesNewEdgeWithNewValue() {
			it("leaves a new edge in the graph with a new value", function () {
				callItWith('k1', 'k2', 'newValue');
				expect(graph.hasEdge('k1', 'k2')).toBeTruthy();
				expect(graph.edgeValue('k1', 'k2')).toBe('newValue');
				expect(graph.edgeCount()).toBe(originalEdgeCount + 1);
			});
		}
1291351
function create(type, constructor) {
  return function scale() {
    var s = constructor();

    if (!s.invertRange) {
      s.invertRange = s.invert ? invertRange(s)
        : s.invertExtent ? invertRangeExtent(s)
        : undefined;
    }

    s.type = type;
    return s;
  };
}
639217
function createEdgeIteratorForNode(type, direction, nodeData) {
  let iterator = Iterator.empty();

  if (type !== 'undirected') {
    if (direction !== 'out' && typeof nodeData.in !== 'undefined')
      iterator = chain(iterator, createIterator(nodeData.in));
    if (direction !== 'in' && typeof nodeData.out !== 'undefined')
      iterator = chain(iterator, createIterator(nodeData.out));
  }

  if (type !== 'directed' && typeof nodeData.undirected !== 'undefined') {
    iterator = chain(iterator, createIterator(nodeData.undirected));
  }

  return iterator;
}
970100
function newInstance(extend) {
  return (initialValues = {}) => {
    const model = {};
    const publicAPI = {};
    extend(publicAPI, model, initialValues);
    return Object.freeze(publicAPI);
  };
}
566888
function(posType) {
    posType = posType || "current";

    var root = this.graph.getNode(this.root),
        config = this.config,
        size = this.canvas.getSize(),
        width = size.width,
        height = size.height,
        offset = config.offset,
        levelsToShow = config.constrained ? config.levelsToShow : Number.MAX_VALUE;

    this.controller.onBeforeCompute(root);

    Graph.Util.computeLevels(this.graph, root.id, 0, "ignore");

    var treeDepth = 0;

    Graph.Util.eachLevel(root, 0, false, function (n, d) { if(d > treeDepth) treeDepth = d; });

    var startNode = this.graph.getNode(this.clickedNode && this.clickedNode.id || root.id);
    var maxDepth = Math.min(treeDepth, levelsToShow-1);
    var initialDepth = startNode._depth;
    if(this.layout.horizontal()) {
      this.computeSubtree(startNode, -width/2, -height/2, width/(maxDepth+1), height, initialDepth, maxDepth, posType);
    } else {
      this.computeSubtree(startNode, -width/2, -height/2, width, height/(maxDepth+1), initialDepth, maxDepth, posType);
    }
  }
528927
@SuppressWarnings("unchecked")
  public static <T extends Map<?, ?>> T newMap(Type type)
  {
    Class<?> implementation = MAPS.get(type);
    if(implementation == null) {
      throw new BugError("No registered implementation for map |%s|.", type);
    }
    return (T)newInstance(implementation);
  }
841709
function factoryObjectGraph(ParentClassGraph){/**
   * Inherited class. Class with methods for control links in graph.
   * Adapted for array collection.
   * 
   * @class
   * @description `import { ObjectGraph as Graph } from 'ancient-graph';`
   */var ObjectGraph=function(_ParentClassGraph){_inherits(ObjectGraph,_ParentClassGraph);/**
     * Construct new graph and checks for required adaptation methods.
     * @param {Array[]} collection
     * @param {Object.<string, string>} fields - matching of fields in the link with fields in document
     * @param {Object} [config] - Additional config.
     * @param {Object} [config.aliases]
     * @param {String} [config.aliases.$]
     * @throws {Error} if the adapter methods is not complete
     */function ObjectGraph(collection,fields,config){_classCallCheck(this,ObjectGraph);var _this=_possibleConstructorReturn(this,(ObjectGraph.__proto__||Object.getPrototypeOf(ObjectGraph)).apply(this,arguments));_this.emitter=new _fbemitter.EventEmitter;return _this}/**
     * Specifies the id field on insert
     * 
     * @param {number} index
     * @param {Link} link
     * @return {number|string} id;
     */_createClass(ObjectGraph,[{key:'_idGenerator',value:function _idGenerator(index,link){return''+index}},{key:'_insertModifier',/**
     * Generate insert modifier.
     * 
     * @param {number} index
     * @param {Link} link
     * @return {number|string} id;
     */value:function _insertModifier(link){var _modifier={};for(var f in link){if(this.fields[f]){_modifier[this.fields[f]]=link[this.config.aliases[f]]}}return _modifier}},{key:'insert',/**
     * Should insert new link into graph.
     * Return a synchronous result. This can be useful in your application. But for writing generic code, it is recommended to only use the callback result.
     * 
     * @param {Link} link
     * @param {Graph~insertCallback} [callback]
     * @param {Object} [context]
     * @return {number|string} [id]
     */value:function insert(link,callback,context){this.callback;var _modifier=this._insertModifier(link);var index,error,id;try{index=this.collection.push(_modifier)-1;if(!this.collection[index].hasOwnProperty(this.fields[this.config.aliases['id']])){id=this.collection[index][this.fields[this.config.aliases['id']]]=this._idGenerator(index,this.collection[index])}this.emitter.emit('insert',this.collection[index])}catch(_error){error=_error}if(callback){callback(error,id)}return id}/**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the unique id of inserted link as the second.
     *
     * @callback Graph~insertCallback
     * @param {Error} [error]
     * @param {number|string} [id]
     *//**
     * Push into link value some item/items.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */},{key:'_updateModifierPush',value:function _updateModifierPush(data,item){data.push(item)}/**
     * Push into link value some item/items if not already exists.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */},{key:'_updateModifierAdd',value:function _updateModifierAdd(data,item){if(_lodash2.default.isArray(item)){for(var i in item){this._updateModifierAdd(data,item[i])}}else{var index=_lodash2.default.indexOf(data,item);if(index<0){this._updateModifierPush(data,item)}}}/**
     * Remove from link value some item/items.
     * 
     * @param {Array} data
     * @param {string|number|string[]|number[]} item
     */},{key:'_updateModifierRemove',value:function _updateModifierRemove(data,item){if(_lodash2.default.isArray(item)){for(var i in item){this._updateModifierRemove(data,item[i])}}else{_lodash2.default.remove(data,function(value){return value==item})}}/**
     * Generate update modifier.
     * 
     * @param {LinkModifier} modifier 
     * @param {Object} result
     * @return {number|string} id;
     */},{key:'_updateModifier',value:function _updateModifier(modifier,result){for(var m in modifier){if(this.fields[m]){if(typeof modifier[m]=='undefined'){delete result[this.fields[m]]}else{if(_typeof(modifier[m])=='object'){if(_lodash2.default.isArray(modifier[m])){result[this.fields[m]]=modifier[m]}else{if(!_lodash2.default.isArray(result[this.fields[m]])){result[this.fields[m]]=result[this.fields[m]]?[result[this.fields[m]]]:[]}for(var key in modifier[m]){if(key=='add'){this._updateModifierAdd(result[this.fields[m]],modifier[m][key])}if(key=='push'){this._updateModifierPush(result[this.fields[m]],modifier[m][key])}if(key=='remove'){this._updateModifierRemove(result[this.fields[m]],modifier[m][key])}}}}else{result[this.fields[m]]=modifier[m]}}}}}},{key:'update',/**
     * Should update to new state of modifier object link by unique id or by link query object.
     * If the database allows, it is recommended to return a synchronous result. This can be useful in your application. But for writing generic code, it is recommended to only use the callback result.
     * 
     * @param {string|LinkSelector} selector
     * @param {LinkModifier} modifier
     * @param {Graph~updateCallback} [callback]
     * @param {Object} [context]
     * @return {number} [count]
     */value:function update(selector,modifier,callback,context){var results=this._fetch(selector);for(var r in results){var oldResult=_lodash2.default.cloneDeep(results[r]);this._updateModifier(modifier,results[r]);this.emitter.emit('update',results[r],oldResult)}if(callback)callback(undefined,results.length);return results.length}/**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the number of affected documents as the second.
     *
     * @callback Graph~updateCallback
     * @param {Error} [error]
     * @param {number} [count]
     *//**
     * Should remove link by unique id or by link query object.
     * 
     * @param {string|LinkSelector} selector
     * @param {Graph~removeCallback} [callback]
     * @param {Object} [context]
     */},{key:'remove',value:function remove(selector,callback,context){var _this2=this;var oldLength=this.collection.length;var removed=[];_lodash2.default.remove(this.collection,function(result){var _query=_this2.query(selector)(result);if(_query)removed.push(result);return _query});for(var r in removed){this.emitter.emit('remove',removed[r])}var newLength=this.collection.length;if(callback)callback(undefined,oldLength-newLength)}/**
     * Optional callback. If present, called with an error object as the first argument.
     *
     * @callback Graph~removeCallback
     * @param {Error} [error]
     * @param {number} [count]
     *//**
     * Generate adapter for database query for links search by unique id or by link query object.
     * 
     * @param {string|LinkSelector} selector
     * @return {*} query
     */},{key:'query',value:function query(selector){var _this3=this;var type=typeof selector==='undefined'?'undefined':_typeof(selector);if(type=='string'||type=='number'){return function(doc){return doc[_this3.fields[_this3.config.aliases['id']]]==selector}}else if(type=='object'){return function(doc){if((typeof doc==='undefined'?'undefined':_typeof(doc))!='object')return false;for(var m in selector){if(_this3.fields[m]){if(typeof selector[m]=='undefined'){if(doc.hasOwnProperty(_this3.fields[m]))return false}else{if(_lodash2.default.isArray(doc[_this3.fields[m]])){if(_lodash2.default.isArray(selector[m])){for(var s in selector[m]){if(!_lodash2.default.includes(doc[_this3.fields[m]],selector[m][s])){return false}}}else{if(!_lodash2.default.includes(doc[_this3.fields[m]],selector[m])){return false}}}else{if(doc[_this3.fields[m]]!=selector[m])return false}}}}return true}}}/**
     * Generate adapted for database options object.
     * 
     * @param {Object} [options]
     * @return {*} options - a options suitable for the database
     */},{key:'options',value:function options(_options2){var _options={};if(_options2){if(_options2.sort){_options.sort={keys:[],orders:[]};for(var s in _options2.sort){if(this.fields[s]){_options.sort.keys.push(this.fields[s]);_options.sort.orders.push(_options2.sort[s]?'asc':'desc')}}}if(typeof _options2.skip=='number'){_options.skip=_options2.skip}if(typeof _options2.limit=='number'){_options.limit=_options2.limit}}return _options}/**
     * Generate Link from document by fields.
     * 
     * @param {Object} document
     * @return {Link} link
     */},{key:'_generateLink',value:function _generateLink(document){var link={};for(var f in this.fields){if(document.hasOwnProperty(this.fields[f])){link[f]=document[this.fields[f]]}}return link}/**
     * Get one first matching link.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~getCallback} [callback]
     * @return {Link} link - result link object
     */},{key:'get',value:function get(selector,options,callback){var results=this.fetch(selector,options,function(error,results){if(callback)callback(error,results?results[0]:undefined)});if(results)return results[0]}/**
     * Fetch native database documents.
     * 
     * @param {string|linkSelector} selector
     * @param {SelectOptions} [options]
     * @return {Object[]} documents - result documents
     */},{key:'_fetch',value:function _fetch(selector,options){var query=this.query(selector);var documents=_lodash2.default.filter(this.collection,query);var _options=this.options(options);if(_options.sort)documents=_lodash2.default.orderBy(documents,_options.sort.keys,_options.orders);var skip=_options.skip?_options.skip:0;var limit=_options.limit?skip+_options.limit:_options.limit;documents=documents.slice(skip,limit);return documents}/**
     * Find and all matching links as an Array.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~fetchCallback} [callback]
     * @return {Link[]} links - result links objects in array
     */},{key:'fetch',value:function fetch(selector,options,callback){var documents=this._fetch(selector,options);var links=[];for(var d in documents){links.push(this._generateLink(documents[d]))}if(callback)callback(undefined,links);return links}/**
     * Optional callback. If present, called with an error object as the first argument and, if no error, the result links objects in array.
     *
     * @callback Graph~fetchCallback
     * @param {Error} [error]
     * @param {Link[]} [links]
     *//**
     * Should call callback once for each matching document, sequentially and synchronously.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~eachCallback} [callback]
     */},{key:'each',value:function each(selector,options,callback){var links=this.fetch(selector,options);for(var l in links){callback(links[l])}}/**
     * @callback Graph~eachCallback
     * @param {Link} [link]
     *//**
     * Map callback over all matching documents. Returns an Array.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~mapCallback} [callback]
     * @return {Array} results
     */},{key:'map',value:function map(selector,options,callback){var links=this.fetch(selector,options);return links.map(callback)}/**
     * @callback Graph~mapCallback
     * @param {Link} [link]
     * @return {*} result
     *//**
     * Count all matching documents.
     * 
     * @param {string|LinkSelector} selector
     * @param {SelectOptions} [options]
     * @param {Graph~countCallback} [callback]
     * @return {number} [count]
     */},{key:'count',value:function count(selector,options,callback){var links=this.fetch(selector,options);if(callback)callback(undefined,links.length);return links.length}/**
     * @callback Graph~countCallback
     * @param {Error} [error]
     * @param {number} [count]
     *//**
     * Should subscribe to the events: link, unlink, insert, update, remove.
     * 
     * @param {string} event - One event name
     * @param {Graph~onCallback} callback
     * @returns {Function} Stops event subscription.
     * @example
     * var counter = 0;
     * var stop = graph.on('update', (oldData, newData) => {
     *   if (oldData.id == '1') console.log(oldData.id, 'is changed');
     *   counter++;
     *   if (counter == 3) stop();
     * });
     */},{key:'on',value:function on(event,callback){var _this4=this;var subscriptions=[];if(event=='insert'){subscriptions.push(this.emitter.addListener('insert',function(document){callback(undefined,_this4._generateLink(document))}))}if(event=='update'){subscriptions.push(this.emitter.addListener('update',function(newDocument,oldDocument){callback(_this4._generateLink(oldDocument),_this4._generateLink(newDocument))}))}if(event=='remove'){subscriptions.push(this.emitter.addListener('remove',function(document){callback(_this4._generateLink(document),undefined)}))}if(event=='link'){subscriptions.push(this.emitter.addListener('insert',function(document){callback(undefined,_this4._generateLink(document))}));subscriptions.push(this.emitter.addListener('update',function(newDocument,oldDocument){callback(_this4._generateLink(oldDocument),_this4._generateLink(newDocument))}))}if(event=='unlink'){subscriptions.push(this.emitter.addListener('update',function(newDocument,oldDocument){callback(_this4._generateLink(oldDocument),_this4._generateLink(newDocument))}));subscriptions.push(this.emitter.addListener('remove',function(document){callback(_this4._generateLink(document),undefined)}))}return function(){var _iteratorNormalCompletion=true;var _didIteratorError=false;var _iteratorError=undefined;try{for(var _iterator=subscriptions[Symbol.iterator](),_step;!(_iteratorNormalCompletion=(_step=_iterator.next()).done);_iteratorNormalCompletion=true){var subscription=_step.value;subscription.remove()}}catch(err){_didIteratorError=true;_iteratorError=err}finally{try{if(!_iteratorNormalCompletion&&_iterator.return){_iterator.return()}}finally{if(_didIteratorError){throw _iteratorError}}}}}/**
     * @callback Graph~onCallback
     * @param {Link} [oldLink] - can be undefined on link and insert events
     * @param {Link} [newLink] - can be undefined on unlink and remove events
     * @param {Object} [context] - additional app information, such as context.userId
     */}]);return ObjectGraph}(ParentClassGraph);return ObjectGraph}
1352979
private void mapMapCollectionToVertex(ITypedInstance typedInstance, AtlasVertex instanceVertex,
                                          AttributeInfo attributeInfo, Operation operation) throws AtlasException {
        if (LOG.isDebugEnabled()) {
            LOG.debug("Mapping instance {} to vertex {} for attribute {}", typedInstance.toShortString(), string(instanceVertex),
                    attributeInfo.name);
        }

        @SuppressWarnings("unchecked") Map<Object, Object> newAttribute =
                (Map<Object, Object>) typedInstance.get(attributeInfo.name);

        boolean newAttributeEmpty = (newAttribute == null || newAttribute.isEmpty());

        IDataType elementType = ((DataTypes.MapType) attributeInfo.dataType()).getValueType();
        String propertyName = GraphHelper.getQualifiedFieldName(typedInstance, attributeInfo);

        Map<String, Object> currentMap = new HashMap<>();
        Map<String, Object> newMap = new HashMap<>();

        List<String> currentKeys = GraphHelper.getListProperty(instanceVertex, propertyName);
        if (currentKeys != null && !currentKeys.isEmpty()) {
            for (String key : currentKeys) {
                String propertyNameForKey = GraphHelper.getQualifiedNameForMapKey(propertyName, key);
                Object propertyValueForKey = GraphHelper.getMapValueProperty(elementType, instanceVertex, propertyNameForKey);
                currentMap.put(key, propertyValueForKey);
            }
        }

        if (!newAttributeEmpty) {
            for (Map.Entry<Object,Object> entry : newAttribute.entrySet()) {
                String keyStr = entry.getKey().toString();
                String propertyNameForKey = GraphHelper.getQualifiedNameForMapKey(propertyName, keyStr);

                Object newEntry = addOrUpdateCollectionEntry(instanceVertex, attributeInfo, elementType,
                        entry.getValue(), currentMap.get(keyStr), propertyNameForKey, operation);

                //Add/Update/Remove property value
                GraphHelper.setMapValueProperty(elementType, instanceVertex, propertyNameForKey, newEntry);
                newMap.put(keyStr, newEntry);
            }
        }

        Map<String, Object> additionalMap =
                removeUnusedMapEntries(instanceVertex, propertyName, currentMap, newMap, elementType, attributeInfo);

        Set<String> newKeys = new HashSet<>(newMap.keySet());
        newKeys.addAll(additionalMap.keySet());


        // for dereference on way out
        GraphHelper.setListProperty(instanceVertex, propertyName, new ArrayList<>(newKeys));
    }
490621
private void ensureTyped(Node n, JSType type) {
    // Make sure FUNCTION nodes always get function type.
    checkState(!n.isFunction() || type.isFunctionType() || type.isUnknownType());
    if (n.getJSType() == null) {
      n.setJSType(type);
    }
  }
452541
function(graph, opt) {

        opt = opt || {};

        var glGraphType = joint.util.pick(opt, 'directed', 'compound', 'multigraph');
        var glGraph = new graphlib.Graph(glGraphType);
        var setNodeLabel = opt.setNodeLabel || joint.util.noop;
        var setEdgeLabel = opt.setEdgeLabel || joint.util.noop;
        var setEdgeName = opt.setEdgeName || joint.util.noop;
        var collection = graph.get('cells');

        for (var i = 0, n = collection.length; i < n; i++) {

            var cell = collection.at(i);
            if (cell.isLink()) {

                var source = cell.get('source');
                var target = cell.get('target');

                // Links that end at a point are ignored.
                if (!source.id || !target.id) break;

                // Note that if we are creating a multigraph we can name the edges. If
                // we try to name edges on a non-multigraph an exception is thrown.
                glGraph.setEdge(source.id, target.id, setEdgeLabel(cell), setEdgeName(cell));

            } else {

                glGraph.setNode(cell.id, setNodeLabel(cell));

                // For the compound graphs we have to take embeds into account.
                if (glGraph.isCompound() && cell.has('parent')) {
                    var parentId = cell.get('parent');
                    if (collection.has(parentId)) {
                        // Make sure the parent cell is included in the graph (this can
                        // happen when the layout is run on part of the graph only).
                        glGraph.setParent(cell.id, parentId);
                    }
                }
            }
        }

        return glGraph;
    }