Parse footnotes document.

    Footnotes are defined in file 'footnotes.xml'
356777
def parse_footnotes(document, xmlcontent):
    

    footnotes = etree.fromstring(xmlcontent)
    document.footnotes = {}

    for footnote in footnotes.xpath('.//w:footnote', namespaces=NAMESPACES):
        _type = footnote.attrib.get(_name('{{{w}}}type'), None)

        # don't know what to do with these now
        if _type in ['separator', 'continuationSeparator', 'continuationNotice']:
            continue

        paragraphs = [parse_paragraph(document, para) for para in footnote.xpath('.//w:p', namespaces=NAMESPACES)]

        document.footnotes[footnote.attrib[_name('{{{w}}}id')]] = paragraphs
1150248
def _read_provenance_from_xml(self, root):
        
        path = self._special_properties['provenance']
        provenance = root.find(path, XML_NS)
        for step in provenance.iter('provenance_step'):
            title = step.find('title').text
            description = step.find('description').text
            timestamp = step.get('timestamp')

            if 'IF Provenance' in title:
                data = {}
                from safe.metadata35.provenance import IFProvenanceStep
                keys = IFProvenanceStep.impact_functions_fields
                for key in keys:
                    value = step.find(key)
                    if value is not None:
                        data[key] = value.text
                    else:
                        data[key] = ''
                self.append_if_provenance_step(
                    title, description, timestamp, data)
            else:
                self.append_provenance_step(title, description, timestamp)
519151
def parse_endnote(document, container, elem):
    ""

    _rid = elem.attrib[_name('{{{w}}}id')]
    note = doc.Endnote(_rid)
    container.elements.append(note)
395305
def _parse_references(xml):
    """"""
    references = []
    ref_finder = HTMLReferenceFinder(xml)
    for elm, uri_attr in ref_finder:
        type_ = _discover_uri_type(elm.get(uri_attr))
        references.append(Reference(elm, type_, uri_attr))
    return references
16301
static function convertWordFootnotes() {

		if ( ! current_user_can( 'edit_posts' ) || ! check_ajax_referer( 'pb-footnote-convert', false, false ) ) {
			static::ajaxFailure( __( 'Invalid permissions.', 'pressbooks' ) );
			return;
		}

		$html = urldecode( stripslashes( $_POST['content'] ) );

		/**
		 * Regular expression tip:
		 * (?: ), in contrast to ( ), is used to avoid capturing text.
		 *
		 * A $pattern must capture:
		 *  [0] => ... full capture ...
		 *  [1] => #_ftnref130
		 *  [2] => 130
		 *  [3] => ... the text we want to move ...
		 *
		 * Known MS Word variations:
		 *  href="#_ftn123" (-> #_ftnref123)
		 *  href="#_edn123" (-> #_ednref123)
		 *  href="/Users/foo/Documents/bar/9781426766497.doc#_ftn123" (-> .doc#_ftnref123)
		 *  href="/Users/foo/Documents/bar/9781426766497.docx#_edn123" (-> .docx#_ednref123)
		 *
		 * Known Libre Office variations:
		 *  href="#sdfootnote123sym" (-> #sdfootnote123anc)
		 */
		$patterns = [
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(#_ftnref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](#_ftnref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(#_ednref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](#_ednref([0-9]+))["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(#sdfootnote([0-9]+)anc)["\']+.*?>(?:[^<]+|.*?)?</a>(.*?)</div>~si', // Libre Office
		];

		/**
		 * A $replacer must be in the same position as a corresponding $pattern above,
		 * use __REPLACE_ME__ to substitute for what we don't know yet.
		 */
		$replacers = [
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(?:#_ftn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](?:#_ftn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(?:#_edn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+.*?[\.doc|\.docx](?:#_edn__REPLACE_ME__)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // MS Word
			'~<a[\s]+[^>]*?href[\s]?=[\s"\']+(?:#sdfootnote__REPLACE_ME__sym)["\']+.*?>(?:[^<]+|.*?)?</a>~si', // Libre Office
		];

		$footnotes = [];
		$find = [];
		$replace = [];

		foreach ( $patterns as $i => $pattern ) {

			preg_match_all( $pattern, $html, $footnotes, PREG_SET_ORDER );

			foreach ( $footnotes as $footnote ) {

				$tmp = wp_kses(
					$footnote[3], [
						'b' => [],
						'em' => [],
						'i' => [],
						'strong' => [],
					]
				);
				$tmp = \Pressbooks\Sanitize\remove_control_characters( $tmp );
				$tmp = trim( preg_replace( '/\s+/', ' ', $tmp ) ); // Normalize white spaces

				$find[] = str_replace( '__REPLACE_ME__', preg_quote( $footnote[2] ), $replacers[ $i ] );
				$replace[] = '[footnote]' . $tmp . '[/footnote]';
			}

			// Remove originals when done
			$find[] = $pattern;
			$replace[] = '&hellip;</div>';
		}

		// Twerk it
		$html = preg_replace( $find, $replace, $html );

		// Important, complex regular expressions have been known to, literally, crash PHP.
		// When testing, make sure this function exits as expected.

		// Send back JSON
		header( 'Content-Type: application/json' );
		$json = wp_json_encode(
			[
				'content' => $html,
			]
		);
		echo $json;

		wp_die();
	}
572782
function parseXmlFromFile(fileName) {
  try {
    var xmlFile = fs.readFileSync(fileName, "utf8");
    var xmlDoc = new xmldoc.XmlDocument(xmlFile);

    // Single testsuite, not wrapped in a testsuites
    if (xmlDoc.name === "testsuite") {
      module.exports.testsuites = xmlDoc;
      module.exports.testsuiteCount = 1;
    } else {
      // Multiple testsuites, wrapped in a parent
      module.exports.testsuites = xmlDoc.childrenNamed("testsuite");
      module.exports.testsuiteCount = module.exports.testsuites.length;
    }

    return xmlDoc;
  } catch (e) {
    if (e.code === "ENOENT") {
      // Bad directory
      return "File not found";
    }
    // Unknown error
    return e;
  }
}
237229
def parseFile(filename):
    
    ret = libxml2mod.xmlParseFile(filename)
    if ret is None:raise parserError('xmlParseFile() failed')
    return xmlDoc(_obj=ret)
515751
def _footer(trigger, data, content):
        
        # footer of the note
        footer = EvernoteMgr.set_note_footer(data, trigger)
        content += footer
        return content
224057
def parse_text(document, container, element):
    ""

    txt = None

    alternate = element.find(_name('{{{mc}}}AlternateContent'))

    if alternate is not None:
        parse_alternate(document, container, alternate)

    br = element.find(_name('{{{w}}}br'))

    if br is not None:
        if _name('{{{w}}}type') in br.attrib:
            _type = br.attrib[_name('{{{w}}}type')]
            brk = doc.Break(_type)
        else:
            brk = doc.Break()

        container.elements.append(brk)

    t = element.find(_name('{{{w}}}t'))

    if t is not None:
        txt = doc.Text(t.text)
        txt.parent = container

        container.elements.append(txt)

    rpr = element.find(_name('{{{w}}}rPr'))

    if rpr is not None:
        # Notice it is using txt as container
        parse_previous_properties(document, txt, rpr)

    for r in element.findall(_name('{{{w}}}r')):
        parse_text(document, container, r)

    foot = element.find(_name('{{{w}}}footnoteReference'))

    if foot is not None:
        parse_footnote(document, container, foot)

    end = element.find(_name('{{{w}}}endnoteReference'))

    if end is not None:
        parse_endnote(document, container, end)

    sym = element.find(_name('{{{w}}}sym'))

    if sym is not None:
        _font = sym.attrib[_name('{{{w}}}font')]
        _char = sym.attrib[_name('{{{w}}}char')]

        container.elements.append(doc.Symbol(font=_font, character=_char))

    image = element.find(_name('{{{w}}}drawing'))

    if image is not None:
        parse_drawing(document, container, image)

    refe = element.find(_name('{{{w}}}commentReference'))

    if refe is not None:
        _m = doc.Comment(refe.attrib[_name('{{{w}}}id')], 'reference')
        container.elements.append(_m)

    return
471581
function parse_javascript(file, options, callback) { 
  fs.readFile(file, 'utf8', function (err, source) {
    if (err) {
      callback(err);
      return;
    }
    process_jsd(source, file, options, callback);
  });
}
759985
function parseEndpoints(document) {
  const defaultParent = WORKSPACE_ID;

  const paths = Object.keys(document.paths);
  const endpointsSchemas = paths
    .map(path => {
      const schemasPerMethod = document.paths[path];
      const methods = Object.keys(schemasPerMethod);

      return methods
        .filter(method => method !== 'parameters')
        .map(method => Object.assign({}, schemasPerMethod[method], { path, method }));
    })
    .reduce((flat, arr) => flat.concat(arr), []); //flat single array

  const tags = document.tags || [];
  const folders = tags.map(tag => {
    return importFolderItem(tag, defaultParent);
  });
  const folderLookup = {};
  folders.forEach(folder => (folderLookup[folder.name] = folder._id));

  const requests = [];
  endpointsSchemas.map(endpointSchema => {
    let { tags } = endpointSchema;
    if (!tags || tags.length == 0) tags = [''];
    tags.forEach((tag, index) => {
      let id = endpointSchema.operationId
        ? `${endpointSchema.operationId}${index > 0 ? index : ''}`
        : `__REQUEST_${requestCount++}__`;
      let parentId = folderLookup[tag] || defaultParent;
      requests.push(importRequest(endpointSchema, id, parentId));
    });
  });

  return [...folders, ...requests];
}
671256
function parseJsDoc(filePath, jsdoc) {
  return jsdoc.explain({files:[filePath]}).then(items=>{
    const data = {};
    items.forEach(item=>{
      if (!item.undocumented && !data.hasOwnProperty(item.longname)) {
        data[item.longname] =  {
          name: item.name,
          description: item.classdesc || item.description
        };
      }
    });

    return data;
  });
}
480752
def _parse_xml(self):
        
        import xml.etree.ElementTree as ET
        from os import path
        #This dict has the keys of XML tags that are required in order for the
        #CI server to run the repo. When each one is parsed, we change its value
        #to True and then check that they are all true at the end.
        required = {"testing": False, "wiki": False}
        #Make sure the file exists and then import it as XML and read the values out.
        if path.isfile(self.filepath):
            tree = ET.parse(self.filepath)
            vms("Parsing XML tree from {}.".format(self.filepath), 2)
            root = tree.getroot()
            if root.tag != "cirepo":
                raise ValueError("The root tag in a continuous integration settings XML "
                                 "file should be a <cirepo> tag.")

            self._parse_repo(root)
            for child in root:
                if child.tag == "cron":
                    if self.server is not None:
                        self.server.cron.settings[self.name] = CronSettings(child)
                if child.tag == "testing":
                    self.testing = TestingSettings(child)
                if child.tag == "static":
                    self.static = StaticSettings(child)
                if child.tag == "wiki":
                    self.wiki["user"] = get_attrib(child, "user", "wiki")
                    self.wiki["password"] = get_attrib(child, "password", "wiki")
                    self.wiki["basepage"] = get_attrib(child, "basepage", "wiki")
                if child.tag in required:
                    required[child.tag] = True

            if not all(required.values()):
                tags = ', '.join(["<{}>".format(t) for t in required])
                raise ValueError("{} are required tags in the repo's XML settings file.".format(tags))
49814
function getSupportedElementsAsFootnote(elements) {
				const notes = [];

				const supportedElements = elements.map(element => {
					if (typeof element === 'string') {
						return `\`<${element}>\``;
					}

					/**
					 * if element is not a string it will be an object with structure:
							{
								nodeName: string,
								properties: {
									type: {string|string[]}
								}
							}
					*/
					return Object.keys(element.properties).map(prop => {
						const value = element.properties[prop];

						// the 'type' property can be a string or an array
						if (typeof value === 'string') {
							return `\`<${element.nodeName} ${prop}="${value}">\``;
						}

						// output format for an array of types:
						// <input type="button" | "checkbox">
						const values = value.map(v => `"${v}"`).join(' | ');
						return `\`<${element.nodeName} ${prop}=${values}>\``;
					});
				});

				notes.push('Supported on elements: ' + supportedElements.join(', '));

				return notes;
			}
46721
def parse(self, filename):
        
        with io.open(filename, 'r', encoding='utf-8') as _:
            lines = _.readlines()

        all_source_files = set()
        source_map = {}

        lineno = 0
        root = None
        index = None
        cur_level = -1
        parent_queue = []

        for line in lines:
            try:
                level, line = dedent(line)
                if line.startswith('#'):
                    lineno += 1
                    continue
                elif line.startswith('\\#'):
                    line = line[1:]
            except IndentError as exc:
                error('bad-indent', 'Invalid indentation', filename=filename,
                      lineno=lineno, column=exc.column)

            if not line:
                lineno += 1
                continue

            source_file = dequote(line)

            if not source_file:
                lineno += 1
                continue

            if source_file in all_source_files:
                error('sitemap-duplicate', 'Filename listed twice',
                      filename=filename, lineno=lineno, column=level * 8 + 1)

            all_source_files.add(source_file)
            source_map[source_file] = (lineno, level * 8 + 1)

            page = OrderedDict()

            if root is not None and level == 0:
                error('sitemap-error', 'Sitemaps only support one root',
                      filename=filename, lineno=lineno, column=0)

            if root is None:
                root = page
                index = source_file
            else:
                lvl_diff = cur_level - level
                while lvl_diff >= 0:
                    parent_queue.pop()
                    lvl_diff -= 1

                parent_queue[-1][source_file] = page

            parent_queue.append(page)

            cur_level = level

            lineno += 1

        return Sitemap(root, filename, index, source_map)
251975
function parse(doc,context){
	var vs;
	var cmds=[];
	var pats;
	var exprs;
	var subpats;
	var mode=context.mode;

	var vs=splitLine_(doc);
	for(var i=0;i<vs.length;i++){
		if(pats=vs[i].match(macroRegex)){
			if(mode=='tcmd'){
				console.log(pats[1]+','+pats[2]);
			}
			exprs=null;
			switch(pats[1]){
			case 'define':
				if(subpats=pats[2].match(defineRegex)){
					exprs=[subpats[1],subpats[2]];
				}else{
					console.log("error: invalid format in define statement "+pats[1]+" in line "+(i+1));
				}
				break;
			case 'include':
			case 'include_once':
			case 'include_code':
			case 'include_code_once':
				exprs=toExpr(pats[2],i+1);
				break;
			case 'if':
			case 'elseif':
			case 'elif':
				exprs=toExpr(pats[2],i+1);
				break;
			case 'else':
			case 'endif':
				break;
			case 'namespace':
				if(subpats=pats[2].match(nsRegex)){
					setNamespace_(subpats[1]);
				}else{
					console.log("error: invalid format in namespace statement "+pats[1]+" in line "+(i+1));
				}
				break;
			default:
				if(pats[1].charAt(0)!='@'){
					console.log("error: unknown statement "+pats[1]+" in line "+(i+1));
				}
				break;
			}
			cmds.push({type:pats[1], exprs:exprs});
		}else{
			cmds.push({type:'text', value:vs[i]});
		}
	}
	if(mode=='cmd'){
		for(var i=0;i<cmds.length;i++){
			console.log(JSON.stringify(cmds[i]));
		}
	}
	return cmds;
}
249019
def _parse_docstrings(self, filepath):
        """"""        
        xmlpath = self.get_xmldoc_path(filepath)
        if self.tramp.exists(xmlpath):
            xmlstring = self.tramp.read(xmlpath)
            self.modulep.docparser.parsexml(xmlstring, self.modules, xmlpath)