method that extracts the logic for Document creation.  `hierarchy` is optional
327281
function setupDocument(record, hierarchy) {
  var wofDoc = new Document( 'whosonfirst', record.place_type, record.id );

  if (record.name) {
    wofDoc.setName('default', record.name);

    // index a version of postcode which doesn't contain whitespace
    if (record.place_type === 'postalcode' && typeof record.name === 'string') {
      var sans_whitespace = record.name.replace(/\s/g, '');
      if (sans_whitespace !== record.name) {
        wofDoc.setNameAlias('default', sans_whitespace);
      }
    }

    // index name aliases for all other records (where available)
    else if (record.name_aliases.length) {
      record.name_aliases.forEach(alias => {
        wofDoc.setNameAlias('default', alias);
      });
    }
  }
  wofDoc.setCentroid({ lat: record.lat, lon: record.lon });

  // only set population if available
  if (record.population) {
    wofDoc.setPopulation(record.population);
  }

  // only set popularity if available
  if (record.popularity) {
    wofDoc.setPopularity(record.popularity);
  }

  // WOF bbox is defined as:
  // lowerLeft.lon, lowerLeft.lat, upperRight.lon, upperRight.lat
  // so convert to what ES understands
  if (!_.isUndefined(record.bounding_box)) {
    var parsedBoundingBox = record.bounding_box.split(',').map(parseFloat);
    var marshaledBoundingBoxBox = {
      upperLeft: {
        lat: parsedBoundingBox[3],
        lon: parsedBoundingBox[0]
      },
      lowerRight: {
        lat: parsedBoundingBox[1],
        lon: parsedBoundingBox[2]
      }

    };
    wofDoc.setBoundingBox(marshaledBoundingBoxBox);
  }

  // a `hierarchy` is composed of potentially multiple WOF records, so iterate
  // and assign fields
  if (!_.isUndefined(hierarchy)) {
    hierarchy.forEach(function(hierarchyElement) {
      assignField(hierarchyElement, wofDoc);
    });
  }

  // add self to parent hierarchy for postalcodes only
  if (record.place_type === 'postalcode') {
    assignField(record, wofDoc);
  }

  return wofDoc;

}
312413
function initDocument (docName) {
  return db.getDocument(dbName, docName)
    .then(response => response.data._rev) // document already exists
    .catch(response => {
      if (response.status === 404) {
        // create new document
        return db.createDocument(dbName, {foo: 'bar'}, docName)
          .then(response => response.data.rev)
      } else {
        // real error
        return Promise.reject(response)
      }
    })
}
59474
function() {
      var frag = doc.createDocumentFragment();
      var root = doc.firstChild;
      while(root.hasChildNodes()) {
        frag.appendChild(root.firstChild);
      }
      return frag;
    }
1132802
def document_created_message(self, request, document):
        
        messages.success(request, _("Document {} was created".format(document)))
330637
function createDOM (rootDoc, id, option) {
  var el = rootDoc.getElementById(id);
  var head = rootDoc.getElementsByTagName('head')[0];
  if(el) {
    if(option.append) return el
    el.parentNode && el.parentNode.removeChild(el);
  }
  el = rootDoc.createElement('style');
  head.appendChild(el);
  el.setAttribute('id', id);
  if (option.attrs)
    for (var i in option.attrs) {
      el.setAttribute(i, option.attrs[i]);
    }
  return el
}
838837
function FinderBuilder(newDocument) {
// private
    var doc = newDocument;

    function buildIdFinder(e) {
        if (e.id) {
            var id = e.id;

            return (function(targetDoc) {
                return targetDoc.getElementById(id);
            });
        }

        return null;
    }

    function buildTagNameFinder(e) {
        var elements = doc.getElementsByTagName(e.tagName);

        for (var i = 0, n = elements.length; i < n; ++i) {
            if (elements[i] === e) {
                // both the descendant axis and getElementsByTagName() should
                // return elements in document order; hence the following index
                // operation is possible
                return (function(targetDoc) {
                    return targetDoc.getElementsByTagName(e.tagName)[i];
                });
            }
        }

        return null;
    }

// public
    this.setDocument = function(newDocument) {
        doc = newDocument;
        return this;
    };

    this.build = function(e) {
        return (
            buildIdFinder(e) ||
            buildTagNameFinder(e)
        );
    };
}
709286
function findRootNode(document)
{
	var i;
	var rootNodes = document.childNodes;
	
	for (i=0; i<rootNodes.length; i++)
	{
		// Doctypes have no `childNodes` property
		if (rootNodes[i].childNodes != null)
		{
			return rootNodes[i];
		}
	}
}
631038
function createDocumentFragment(ownerDocument, data){
    if (!ownerDocument) {
        ownerDocument = document;
    }
    if(supportsUnknownElements){
        return ownerDocument.createDocumentFragment();
    }
    data = data || getExpandoData(ownerDocument);
    var clone = data.frag.cloneNode(),
        i = 0,
        elems = getElements(),
        l = elems.length;
    for(;i<l;i++){
        clone.createElement(elems[i]);
    }
    return clone;
  }
893094
function(parent, field, options) {  
  options = options || {};
  // Unique id for this node's generated method
  this.id = utils.generateId();
  // Link to parent node
  this.parent = parent;
  // The field related to this node
  this.field = field;
  // Perform type check or not on generation
  this.typeCheck = typeof options.typeCheck == 'boolean' ? options.typeCheck : false;
  // Validation language
  this.validation = options.validation ? options.validation : null;
  // Any options
  this.options = options;
  // All children attached to this node
  this.children = [];
  // Just some metadata
  this.type = 'enum';
}
516744
def _from_dict(cls, _dict):
        """"""
        args = {}
        if 'document_id' in _dict:
            args['document_id'] = _dict.get('document_id')
        if 'field' in _dict:
            args['field'] = _dict.get('field')
        if 'start_offset' in _dict:
            args['start_offset'] = _dict.get('start_offset')
        if 'end_offset' in _dict:
            args['end_offset'] = _dict.get('end_offset')
        if 'entities' in _dict:
            args['entities'] = [
                QueryEvidenceEntity._from_dict(x)
                for x in (_dict.get('entities'))
            ]
        return cls(**args)
1007171
def getMappingById(self, document, depth=None, element=None,
                       mapping=None, level=1):
        """"""
        if document is not None:
            element = document.documentElement
            mapping = {}
        attr = element._attrs.get('id', None)
        if attr is not None:
            mapping[attr.value] = element
        if depth is None or depth > level:
            level = level + 1
            ELEMENT_NODE = element.ELEMENT_NODE
            for child in element.childNodes:
                if child.nodeType == ELEMENT_NODE:
                    self.getMappingById(None, depth, child, mapping, level)
        return mapping
560299
def documento(self, *args, **kwargs):
        
        forcar_unicode = kwargs.pop('forcar_unicode', False)
        incluir_xml_decl = kwargs.pop('incluir_xml_decl', True)
        doc = ET.tostring(self._xml(*args, **kwargs),
                encoding='utf-8').decode('utf-8')
        if forcar_unicode:
            if incluir_xml_decl:
                doc = u'{}\n{}'.format(constantes.XML_DECL_UNICODE, doc)
        else:
            if incluir_xml_decl:
                doc = '{}\n{}'.format(constantes.XML_DECL, unidecode(doc))
            else:
                doc = unidecode(doc)
        return doc
716976
private void addRootElement() {
        if (root instanceof Document) {
            // Get the single element child of the document node.
            // There could be a doctype node and comment nodes that we must skip.
            Element element = DOMHelper.getFirstChildElement(root);
            Assert.notNull(element, "there should be a root element!");
            result.add(element);
        } else {
            Assert.isTrue(root instanceof Element, "root must be a document or element node!");
            result.add(root);
        }
    }
500992
private DocumentPath getDocumentPath(List<PathSegment> params) {
    if (params.isEmpty()) {
      return DocumentPath.ROOT;
    } else {
      return DocumentPath.from(params.stream().map(PathSegment::getPath).collect(Collectors.toList()));
    }
  }
853975
function _doc_to_tree_node(doc, parent_id){

    var retnode = {};

    // ID.
    var raw_id = doc['id'];
    var safe_id = raw_id; // need to process?
    retnode['attr'] = { "id" : safe_id }; 

    // Label (with fallback).
    var label = doc['label'];
    if( ! label || label == '' ){
	label = raw_id;
    }else{
	label = label + ' (' + raw_id + ')';
    }

    // Set anchor title and href.
    var detlink = linker.url(raw_id, 'term');
    retnode['data'] = {"title" : label,
		       "attr": {"href": detlink}};

    // Turn to graph, get kids.
    var graph = new bbop.model.graph();
    graph.load_json(jQuery.parseJSON(doc['topology_graph']));
    var kids = graph.get_child_nodes(doc['id']);

    // Add state and kid_query.
    if( ! kids || kids.length == 0 ){
	// No kids...
    }else{
	// No kids, make sure the node is closed.
    	retnode['state'] = 'closed';

	// Collect kid info for the query to get them later.
	var qbuff = [];
	bbop.core.each(kids,
		       function(kid){
			   qbuff.push('id:"' + kid.id() + '"');
		       });
	retnode['attr']['kid_query'] = qbuff.join(' OR ');
    }

    // If the parent_id is defined, use that to pull the relationship
    // out of the graph and get a more appropriate icon.
    if( parent_id ){

	// Try and dig out the rel to display.
	var edges = graph.get_edges(raw_id, parent_id);
	if( edges && edges.length ){
	    var weight = {
		'is_a': 3,
		'part_of': 2
	    };
	    var unknown_rel_weight = 1;
	    edges.sort(
		function(a, b){
		    var aw = weight[a.predicate_id()];
		    if( ! aw ){ aw = unknown_rel_weight; }
		    var bw = weight[b.predicate_id()];
		    if( ! bw ){ bw = unknown_rel_weight; }
		    return bw - aw;
		});

	    // Add it in a brittle way.
	    var prime_rel = edges[0].predicate_id();
	    retnode['data']['icon'] = 
	    	server_meta.image_base() + '/' + prime_rel + '.gif';
	}
    }

    return retnode;
}
359247
public static Document createDOMDocument()
    {
        try {
            return DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
        } catch (ParserConfigurationException ex) {
            LOGGER.error("Cannot create DOM Documents", ex);
            return null;
        }
    }
1085327
@Override
	public List<Object> listDocumentsInHierarchy() throws Exception 
	{
		Vector<Object> hierarchy = toHierarchyNodeVector(root);
		hierarchy.setElementAt(root.getName(), 0);
		hierarchy.setElementAt(false, 1);
		hierarchy.setElementAt(false, 2);
		return hierarchy;
	}