Consumes input extracting definitions.

    Args:
      a_file: The file like stream to parse.

    Raises:
      PDDMError if there are any issues.
761906
def ParseInput(self, a_file):
    
    input_lines = a_file.read().splitlines()
    self.ParseLines(input_lines)
1255054
def load_from_file(self, fname):
        '''
        
        '''
        try:
            # Process each line from the extract file, ignoring comments
            with open(fname, 'r') as f:
                for rule in f.readlines():
                    self.add_rule(rule.split(self.COMMENT_DELIM, 1)[0])
        except KeyboardInterrupt as e:
            raise e
        except Exception as e:
            raise Exception("Extractor.load_from_file failed to load file '%s': %s" % (fname, str(e)))
736413
def parse_from_file(file_object):
    

    logger.info('Parsing %s file.', file_object.file_name)

    # Read the files
    doc_content = file_object.read_file('document.xml')

    # Parse the document
    document = parse_document(doc_content)

    try:
        style_content = file_object.read_file('styles.xml')
        parse_style(document, style_content)
    except KeyError:
        logger.warning('Could not read styles.')

    try:
        doc_rel_content = file_object.read_file('_rels/document.xml.rels')
        parse_relationship(document, doc_rel_content, 'document')
    except KeyError:
        logger.warning('Could not read document relationships.')

    try:
        doc_rel_content = file_object.read_file('_rels/endnotes.xml.rels')
        parse_relationship(document, doc_rel_content, 'endnotes')
    except KeyError:
        logger.warning('Could not read endnotes relationships.')

    try:
        doc_rel_content = file_object.read_file('_rels/footnotes.xml.rels')
        parse_relationship(document, doc_rel_content, 'footnotes')
    except KeyError:
        logger.warning('Could not read footnotes relationships.')

    try:
        comments_content = file_object.read_file('comments.xml')
        parse_comments(document, comments_content)
    except KeyError:
        logger.warning('Could not read comments.')

    try:
        footnotes_content = file_object.read_file('footnotes.xml')
        parse_footnotes(document, footnotes_content)
    except KeyError:
        logger.warning('Could not read footnotes.')

    try:
        endnotes_content = file_object.read_file('endnotes.xml')
        parse_endnotes(document, endnotes_content)
    except KeyError:
        logger.warning('Could not read endnotes.')

    try:
        numbering_content = file_object.read_file('numbering.xml')
        parse_numbering(document, numbering_content)
    except KeyError:
        logger.warning('Could not read numbering.')

    return document
532053
def parse_raw_file(file)
      data = {}
      File.readlines(file).each do |line|
        line = str_clean line, false
        next if line.empty? || line[0] == '#'
        prefix, line_data = line.split('|')
        data[prefix] = line_data && line_data.strip.split('&')
      end
      data
    end
1119635
def read_input_file(filename, sep='\t', noquote=False):
    
    output = []
    stream = None
    try:
        stream = open(filename, 'r')
        for row in stream:
            row = row.strip()
            if noquote:
                row = row.replace('"', '')
            output.append(row.split(sep))
    except IOError as err:  # pragma: no cover
        LOG.info("Something wrong happend while reading the file %s "
                 % filename)
        LOG.debug("ERROR: %s" % err)
    finally:
        if stream:
            stream.close()
    return output
927332
def parse(self, file):
        '''
        
        '''
        parser = make_parser()
        self.clear()

        class Extractor(xml.sax.ContentHandler):

            def __init__(self, parent):
                self.parent = parent

            def startElement(self, name, attrs):
                attribs = {}
                for attrname in attrs.getNames():
                    attrvalue = attrs.get(attrname)
                    attribs[attrname] = attrvalue
                self.parent.StartTag(name, attribs)

            def characters(self, text):
                self.parent.NewData(text)

            def endElement(self, name):
                self.parent.EndTag(name)
        parser.setContentHandler(Extractor(self))
        # OFFLINE MODE
        parser.setFeature(handler.feature_external_ges, False)
        fob = open(file, 'r')
        parser.parse(fob)
        return self.piece
434528
def parse_file(defn, preprocess=True):
    
    if pycparser is None:
        raise ImportError("Please install pycparser in order to parse C definitions")

    defn = '\n'.join(x for x in defn.split('\n') if _include_re.match(x) is None)

    if preprocess:
        defn = do_preprocess(defn)

    preamble, ignoreme = make_preamble()
    node = pycparser.c_parser.CParser().parse(preamble + defn)
    if not isinstance(node, pycparser.c_ast.FileAST):
        raise ValueError("Something went horribly wrong using pycparser")
    out = {}
    extra_types = {}
    for piece in node.ext:
        if isinstance(piece, pycparser.c_ast.FuncDef):
            out[piece.decl.name] = _decl_to_type(piece.decl.type, extra_types)
        elif isinstance(piece, pycparser.c_ast.Decl):
            ty = _decl_to_type(piece.type, extra_types)
            if piece.name is not None:
                out[piece.name] = ty
        elif isinstance(piece, pycparser.c_ast.Typedef):
            extra_types[piece.name] = _decl_to_type(piece.type, extra_types)

    for ty in ignoreme:
        del extra_types[ty]
    return out, extra_types
1136170
def read_file(self, path, **kwargs):
        
        # TODO support JSON here
        # TODO sphinx way of reporting errors in logs?

        parser_command = ["godocjson"]

        _ignore = kwargs.get("ignore")
        if _ignore:
            parser_command.extend(["-e", "{0}".format("|".join(_ignore))])

        parser_command.append(path)

        try:
            parsed_data = json.loads(subprocess.check_output(parser_command))
            return parsed_data
        except IOError:
            LOGGER.warning("Error reading file: {0}".format(path))
        except TypeError:
            LOGGER.warning("Error reading file: {0}".format(path))
        return None
360065
def read_stream(self, file: IO, data_stream: DataStream) -> Reply:
        '''
        '''

        yield from data_stream.read_file(file=file)

        reply = yield from self._control_stream.read_reply()

        self.raise_if_not_match(
            'End stream',
            ReplyCodes.closing_data_connection,
            reply
        )

        data_stream.close()

        return reply
884667
def _ParseFile(self, file_obj, line_parser):
    
    lines = [
        l.strip() for l in utils.ReadFileBytesAsUnicode(file_obj).splitlines()
    ]
    try:
      for index, line in enumerate(lines):
        if line:
          line_parser(line)
    except (IndexError, KeyError) as e:
      raise parser.ParseError("Invalid file at line %d: %s" % (index + 1, e))
956803
def load_from_file!(file)
      data = Psych.safe_load(File.read(file)) if File.file? file
      data = {} unless data.is_a? Hash
      conf = {}
      conf[:networks]     = Network.deserialize_all data['networks'], conf
      conf[:integrations] = Integration.deserialize_all data['integrations'],
                                                        conf
      conf
    end
1213704
def _parse_file(self, file):
        
        case = Case()
        file.seek(0)

        line = file.readline().split()
        if line[0] != "function":
            logger.error("Invalid data file header.")
            return case
        if line[1] != "mpc":
            self._is_struct = False
            base = ""
        else:
            base = "mpc."
        case.name = line[-1]

        for line in file:
            if line.startswith("%sbaseMVA" % base):
                case_data = line.rstrip(";\n").split()
                case.base_mva = float(case_data[-1])
            elif line.startswith("%sbus" % base):
                self._parse_buses(case, file)
            elif line.startswith("%sgencost" % base):
                self._parse_gencost(case, file)
            elif line.startswith("%sgen" % base):
                self._parse_generators(case, file)
            elif line.startswith("%sbranch" % base):
                self._parse_branches(case, file)

        return case
956520
def _read_from_file(self):
        
        # test if we can read the given file
        if not gf.file_can_be_read(self.file_path):
            self.log_exc(u"File '%s' cannot be read" % (self.file_path), None, True, OSError)

        if self.file_format not in TextFileFormat.ALLOWED_VALUES:
            self.log_exc(u"Text file format '%s' is not supported." % (self.file_format), None, True, ValueError)

        # read the contents of the file
        self.log([u"Reading contents of file '%s'", self.file_path])
        with io.open(self.file_path, "r", encoding="utf-8") as text_file:
            lines = text_file.readlines()

        # clear text fragments
        self.clear()

        # parse the contents
        map_read_function = {
            TextFileFormat.MPLAIN: self._read_mplain,
            TextFileFormat.MUNPARSED: self._read_munparsed,
            TextFileFormat.PARSED: self._read_parsed,
            TextFileFormat.PLAIN: self._read_plain,
            TextFileFormat.SUBTITLES: self._read_subtitles,
            TextFileFormat.UNPARSED: self._read_unparsed
        }
        map_read_function[self.file_format](lines)

        # log the number of fragments
        self.log([u"Parsed %d fragments", len(self.fragments)])
600775
def from_files(cls, ID, datafiles, parser, readdata_kwargs={}, readmeta_kwargs={}, **ID_kwargs):
        
        d = _assign_IDS_to_datafiles(datafiles, parser, cls._measurement_class, **ID_kwargs)
        measurements = []
        for sID, dfile in d.items():
            try:
                measurements.append(cls._measurement_class(sID, datafile=dfile,
                                                           readdata_kwargs=readdata_kwargs,
                                                           readmeta_kwargs=readmeta_kwargs))
            except:
                msg = 'Error occurred while trying to parse file: %s' % dfile
                raise IOError(msg)
        return cls(ID, measurements)
843264
function parse(context, file) {
  var message

  if (stats(file).fatal) {
    return
  }

  if (context.treeIn) {
    debug('Not parsing already parsed document')

    try {
      context.tree = json(file.toString())
    } catch (error) {
      message = file.message(
        new Error('Cannot read file as JSON\n' + error.message)
      )
      message.fatal = true
    }

    /* Add the preferred extension to ensure the file, when compiled, is
     * correctly recognized. Only add it if there’s a path — not if the
     * file is for example stdin. */
    if (file.path) {
      file.extname = context.extensions[0]
    }

    file.contents = ''

    return
  }

  debug('Parsing `%s`', file.path)

  context.tree = context.processor.parse(file)

  debug('Parsed document')
}
527483
def _parse_singlefile(self, desired_type: Type[T], file_path: str, encoding: str, logger: Logger,
                          options: Dict[str, Dict[str, Any]]) -> T:
        
        raise Exception('Not implemented since this is a MultiFileParser')
1057137
def _load_yaml_file(self, file):
        
        try:
            res = load_yaml_file(file)
        except:
            self.exception("Failed to load from {}".format(file))
            raise IOError("Loading file failed")
        return res