Init a new object from a file-like object.
        Not for Outlook msg.

        Args:
            fp (file-like object): file-like object of raw email

        Returns:
            Instance of MailParser
761986
def from_file_obj(cls, fp):
        
        log.debug("Parsing email from file object")
        try:
            fp.seek(0)
        except IOError:
            # When stdout is a TTY it's a character device
            # and it's not seekable, you cannot seek in a TTY.
            pass
        finally:
            s = fp.read()

        return cls.from_string(s)
507563
def ParseFileObject(self, parser_mediator, file_object):
    
    evt_file = pyevt.file()
    evt_file.set_ascii_codepage(parser_mediator.codepage)

    try:
      evt_file.open_file_object(file_object)
    except IOError as exception:
      parser_mediator.ProduceExtractionWarning(
          'unable to open file with error: {0!s}'.format(exception))
      return

    try:
      self._ParseRecords(parser_mediator, evt_file)
    finally:
      evt_file.close()
24162
def load(fp, model=None, parser=None):
    """"""
    if not model:
        model = 'simple'
    if not parser:
        parser = 'quick'

    if model not in ['simple']:
        raise ValueError
    if parser not in ['quick']:
        raise ValueError

    if model == 'simple' and parser == 'quick':
        return ARPAParserQuick(ARPAModelSimple).parse(fp)
    else:
        raise ValueError
514802
def from_yaml_file(f):
    
    return from_json(to_json(yaml.load(f, Loader=yaml.Loader)))
1190412
def from_EmailMessage(cls, message):
        
        mail = cls(
            from_email=Email(message.get('From')),
            subject=message.get('Subject'),
            to_emails=Email(message.get('To')),
        )
        try:
            body = message.get_content()
        except AttributeError:
            # Python2
            body = message.get_payload()
        mail.add_content(Content(
            message.get_content_type(),
            body.strip()
        ))
        for k, v in message.items():
            mail.add_header(Header(k, v))
        return mail
807320
def _structure(msg, fp=None, level=0, include_default=False):
    """"""
    if fp is None:
        fp = sys.stdout
    tab = ' ' * (level * 4)
    print(tab + msg.get_content_type(), end='', file=fp)
    if include_default:
        print(' [%s]' % msg.get_default_type(), file=fp)
    else:
        print(file=fp)
    if msg.is_multipart():
        for subpart in msg.get_payload():
            _structure(subpart, fp, level+1, include_default)
934625
def from_file(cls, filename):
        
        with open(filename) as infp:
            if filename.endswith('.yaml') or filename.endswith('.yml'):
                import yaml
                data = yaml.safe_load(infp)
            else:
                import json
                data = json.load(infp)
        return cls.from_data(data)
186555
def from_file(fn, **options):
        
        if hasattr(fn, 'read'):
            return TableFu(fn, **options)
        with open(fn) as f:
            return TableFu(f, **options)
135277
def _get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any],
                                                 logger: Logger) -> Dict[str, Any]:
        
        raise Exception('This should never happen, since this parser relies on underlying parsers')
415331
def create(parser: Parser, obj: PersistedObject = None):
        
        if obj is not None:
            return _InvalidParserException('Error ' + str(obj) + ' cannot be parsed using ' + str(parser) + ' since '
                                           + ' this parser does not support ' + obj.get_pretty_file_mode())
        else:
            return _InvalidParserException('Error this parser is neither SingleFile nor MultiFile !')
784534
def _build_parser_for_fileobject_and_desiredtype(self, obj_on_filesystem: PersistedObject, object_typ: Type[T],
                                                     logger: Logger = None) -> Dict[Type, Parser]:
        

        parsers = OrderedDict()
        errors = OrderedDict()
        try:
            p = self.__build_parser_for_fileobject_and_desiredtype(obj_on_filesystem,
                                                                   object_typ=object_typ,
                                                                   logger=logger)
            parsers[object_typ] = p
        except NoParserFoundForObjectExt as e:
            logger.warning("{} - {}".format(type(e).__name__, e))
            errors[e] = e
        except NoParserFoundForObjectType as f:
            logger.warning("{} - {}".format(type(f).__name__, f))
            errors[f] = f

        # do not explore subclasses for collections
        if is_collection(object_typ, strict=True):
            if len(errors) > 0:
                raise next(iter(errors.values()))
            else:
                return parsers

        # Finally create one such parser for each subclass
        subclasses = get_all_subclasses(object_typ)

        # Then for each subclass also try (with a configurable limit in nb of subclasses)
        for subclass in subclasses[0:GLOBAL_CONFIG.dict_to_object_subclass_limit]:
            try:
                parsers[subclass] = self.__build_parser_for_fileobject_and_desiredtype(obj_on_filesystem,
                                                                                       object_typ=subclass,
                                                                                       logger=logger)
            except NoParserFoundForObjectExt as e:
                logger.warning("{} - {}".format(type(e).__name__, e))
                errors[e] = e
            except NoParserFoundForObjectType as f:
                logger.warning("{} - {}".format(type(f).__name__, f))
                errors[f] = f

        if len(subclasses) > GLOBAL_CONFIG.dict_to_object_subclass_limit:
            warn('Type {} has more than {} subclasses, only {} were tried to convert it, with no success. You '
                 'can raise this limit by setting the appropriate option with `parsyfiles_global_config()`'
                 ''.format(object_typ, len(subclasses), GLOBAL_CONFIG.dict_to_object_subclass_limit))

        return parsers
373832
def dump(obj, fp, pretty=False, escaped=True):
    
    if not isinstance(obj, dict):
        raise TypeError("Expected data to be an instance of``dict``")
    if not hasattr(fp, 'write'):
        raise TypeError("Expected fp to have write() method")
    if not isinstance(pretty, bool):
        raise TypeError("Expected pretty to be of type bool")
    if not isinstance(escaped, bool):
        raise TypeError("Expected escaped to be of type bool")

    for chunk in _dump_gen(obj, pretty, escaped):
        fp.write(chunk)
68831
def _get_parsing_plan_for_multifile_children(self, obj_on_fs: PersistedObject, desired_type: Type[Any],
                                                 logger: Logger) -> Dict[str, Any]:
        
        return self._base_parser._get_parsing_plan_for_multifile_children(obj_on_fs, self._converter.from_type, logger)
1210595
def init_parser():
    """"""

    usage = "Usage: %(prog)s <option(s)> <file(s)>"
    description = " Display information from object <file(s)>.\n"
    description += " At least one of the following switches must be given:"

    #
    # Create an argument parser and an exclusive group.
    #
    parser = ArgumentParser(
        usage=usage, description=description, add_help=False)

    group = parser.add_mutually_exclusive_group()

    #
    # Add objdump parameters.
    #
    group.add_argument("-a", "--archive-headers",
        action=DumpArchieveHeadersAction,
        type=FileType("r"), nargs="+",
        help="Display archive header information")

    group.add_argument("-f", "--file-headers",
        action=DumpFileHeadersAction,
        type=FileType("r"), nargs="+",
        help="Display the contents of the overall file header")

    #group.add_argument("-p", "--private-headers",    action="store", type=FileType("r"), nargs="+", help="Display object format specific file header contents")
    #group.add_argument("-P", "--private=OPT,OPT...", action="store", type=FileType("r"), nargs="+", help="Display object format specific contents")

    group.add_argument("-h", "--section-headers",
        action=DumpSectionHeadersAction,
        type=FileType("r"), nargs="+",
        help="Display the contents of the section headers")

    #group.add_argument("-x", "--all-headers",        action="store", type=FileType("r"), nargs="+", help="Display the contents of all headers")

    group.add_argument("-d", "--disassemble",
        action=DisassembleSectionAction,
        type=FileType("r"), nargs="+",
        help="Display assembler contents of executable sections")


    group.add_argument("-D", "--disassemble-all",
        action=DisassembleSectionsAction,
        type=FileType("r"), nargs="+",
        help="Display assembler contents of executable sections")

    #group.add_argument("-S", "--source",             action="store", type=FileType("r"), nargs="+", help="Intermix source code with disassembly")

    group.add_argument("-s", "--full-contents",
        action=DumpSectionContentAction,
        type=FileType("r"), nargs="+",
        help="Display the full contents of all sections requested")

    #group.add_argument("-g", "--debugging",          action="store", type=FileType("r"), nargs="+", help="Display debug information in object file")
    #group.add_argument("-e", "--debugging-tags",     action="store", type=FileType("r"), nargs="+", help="Display debug information using ctags style")
    #group.add_argument("-G", "--stabs",              action="store", type=FileType("r"), nargs="+", help="Display (in raw form) any STABS info in the file")

    #-W[lLiaprmfFsoRt] or")
    #--dwarf[=rawline,=decodedline,=info,=abbrev,=pubnames,=aranges,=macro,=frames,")
    #      =frames-interp,=str,=loc,=Ranges,=pubtypes,")
    #      =gdb_index,=trace_info,=trace_abbrev,=trace_aranges]")
    #                       Display DWARF info in the file")

    group.add_argument("-t", "--syms",
        action=DumpFileSymbols,
        type=FileType("r"), nargs="+",
        help="Display the contents of the symbol table(s)")

    #-T, --dynamic-syms       Display the contents of the dynamic symbol table")
    #-r, --reloc              Display the relocation entries in the file")
    #-R, --dynamic-reloc      Display the dynamic relocation entries in the file")

    group.add_argument("-v", "--version", action="version",
        version="%%(prog)s %s (%s)" % (__version__, __description__),
        help="Display this program's version number")

    group.add_argument("-i", "--info",
        action=ListFormatAndArchitecturesInformationAction,
        nargs=REMAINDER,
        help="List object formats and architectures supported")

    group.add_argument("-H", "--help", action="store_true", default=False,
        help="Display this information")

    return parser
573615
def load(fp):
    '''
    
    '''
    reader = reading.Reader(fp)
    keys = reader.fields
    columns = {k: [] for k in keys}
    for row in reader:
        for key, value in zip(keys, row):
            columns[key].append(value)
    return columns
1087923
def create_from_file(cls, filename):
        """"""
        obj = cls()
        obj.object_file = filename
        obj.load()
        return obj
616871
def parse(self, fp, headersonly=True):
        """"""
        feedparser = FeedParser(self._class)
        feedparser._set_headersonly()

        try:
            mp = mmap.mmap(fp.fileno(), 0, access=mmap.ACCESS_READ)
        except:
            mp = fp

        data = ""

        # While parsing the header we can convert to us-ascii?
        while True:
            line = mp.readline()
            data = data + line.decode("us-ascii")
            if line == b"\n":
                break
        feedparser.feed(data) # mp[0:5000])
        return feedparser.close()