Parse a TRANSFAC record out of `lines` and return a motif.
433644
def parse_record( self, lines ):
        
        # Break lines up
        temp_lines = []
        for line in lines:
            fields = line.rstrip( "\r\n" ).split( None, 1 )
            if len( fields ) == 1:
                fields.append( "" )
            temp_lines.append( fields )
        lines = temp_lines
        # Fill in motif from lines
        motif = TransfacMotif()
        current_line = 0
        while 1:
            # Done parsing if no more lines to consume
            if current_line >= len( lines ):
                break
            # Remove prefix and first separator from line
            prefix, rest = lines[ current_line ]
            # No action for this prefix, just ignore the line
            if prefix not in self.parse_actions:
                current_line += 1
                continue
            # Get action for line
            action = self.parse_actions[ prefix ]
            # Store a single line value
            if action[0] == "store_single":
                key = action[1]
                setattr( motif, key, rest )
                current_line += 1
            # Add a single line value to a list
            if action[0] == "store_single_list":
                key = action[1]
                if not getattr( motif, key ):
                    setattr( motif, key, [] )
                getattr( motif, key ).append( rest )
                current_line += 1
            # Add a single line value to a dictionary
            if action[0] == "store_single_key_value":
                key = action[1]
                k, v = rest.strip().split( '=', 1 )
                if not getattr( motif, key ):
                    setattr( motif, key, {} )
                getattr( motif, key )[k] = v
                current_line += 1
            # Store a block of text
            if action[0] == "store_block":
                key = action[1]
                value = []
                while current_line < len( lines ) and lines[ current_line ][0] == prefix:
                    value.append( lines[current_line][1] )
                    current_line += 1
                setattr( motif, key, str.join( "\n", value ) )
            # Store a matrix
            if action[0] == "store_matrix":
                # First line is alphabet
                alphabet = rest.split()
                alphabet_size = len( alphabet )
                rows = []
                pattern = ""
                current_line += 1
                # Next lines are the rows of the matrix (we allow 0 rows)
                while current_line < len( lines ):
                    prefix, rest = lines[ current_line ]
                    # Prefix should be a two digit 0 padded row number
                    if not prefix.isdigit():
                        break
                    # The first `alphabet_size` fields are the row values
                    values = rest.split()
                    rows.append( [ float(_) for _ in values[:alphabet_size] ] )
                    # TRANSFAC includes an extra column with the IUPAC code
                    if len( values ) > alphabet_size:
                        pattern += values[alphabet_size]
                    current_line += 1
                # Only store the pattern if it is the correct length (meaning
                # that every row had an extra field)
                if len( pattern ) != len( rows ):
                    pattern = None
                matrix = FrequencyMatrix.from_rows( alphabet, rows )
                setattr( motif, action[1], matrix )
        # Only return a motif if we saw at least ID or AC or NA
        if motif.id or motif.accession or motif.name:
            return motif
1190776
def parse_record(header, record):
    """"""
    major_version = header[1]

    try:
        return RECORD_PARSER[major_version](header, record)
    except (KeyError, struct.error) as error:
        raise RuntimeError("Corrupted USN Record") from error
547732
def _DoParse(self):
    
    get4 = lambda x: struct.unpack("<L", self.input_dat[x:x + 4])[0]
    filesize = get4(0x1c)
    offset = get4(0x20)
    coffset = offset
    while coffset < filesize:
      etype = struct.unpack("4s", self.input_dat[coffset:coffset + 4])[0]
      if etype == b"REDR":
        pass
      elif etype in [b"URL "]:
        # Found a valid record
        reclen = get4(coffset + 4) * self.BLOCK_SIZE
        yield self._GetRecord(coffset, reclen)
      coffset += self.BLOCK_SIZE
220690
def _decode_record(self, s, line=0):
        '''
        '''
        s = s.rstrip('\r\n')
        if not s:
            return          # empty line

        if s[0] == ':':
            try:
                bin = array('B', unhexlify(asbytes(s[1:])))
            except (TypeError, ValueError):
                # this might be raised by unhexlify when odd hexascii digits
                raise HexRecordError(line=line)
            length = len(bin)
            if length < 5:
                raise HexRecordError(line=line)
        else:
            raise HexRecordError(line=line)

        record_length = bin[0]
        if length != (5 + record_length):
            raise RecordLengthError(line=line)

        addr = bin[1]*256 + bin[2]

        record_type = bin[3]
        if not (0 <= record_type <= 5):
            raise RecordTypeError(line=line)

        crc = sum(bin)
        crc &= 0x0FF
        if crc != 0:
            raise RecordChecksumError(line=line)

        if record_type == 0:
            # data record
            addr += self._offset
            for i in range_g(4, 4+record_length):
                if not self._buf.get(addr, None) is None:
                    raise AddressOverlapError(address=addr, line=line)
                self._buf[addr] = bin[i]
                addr += 1   # FIXME: addr should be wrapped
                            # BUT after 02 record (at 64K boundary)
                            # and after 04 record (at 4G boundary)

        elif record_type == 1:
            # end of file record
            if record_length != 0:
                raise EOFRecordError(line=line)
            raise _EndOfFile

        elif record_type == 2:
            # Extended 8086 Segment Record
            if record_length != 2 or addr != 0:
                raise ExtendedSegmentAddressRecordError(line=line)
            self._offset = (bin[4]*256 + bin[5]) * 16

        elif record_type == 4:
            # Extended Linear Address Record
            if record_length != 2 or addr != 0:
                raise ExtendedLinearAddressRecordError(line=line)
            self._offset = (bin[4]*256 + bin[5]) * 65536

        elif record_type == 3:
            # Start Segment Address Record
            if record_length != 4 or addr != 0:
                raise StartSegmentAddressRecordError(line=line)
            if self.start_addr:
                raise DuplicateStartAddressRecordError(line=line)
            self.start_addr = {'CS': bin[4]*256 + bin[5],
                               'IP': bin[6]*256 + bin[7],
                              }

        elif record_type == 5:
            # Start Linear Address Record
            if record_length != 4 or addr != 0:
                raise StartLinearAddressRecordError(line=line)
            if self.start_addr:
                raise DuplicateStartAddressRecordError(line=line)
            self.start_addr = {'EIP': (bin[4]*16777216 +
                                       bin[5]*65536 +
                                       bin[6]*256 +
                                       bin[7]),
                              }
341772
def _line_parse(line):
    
    if line[-2:] in ["\r\n", b"\r\n"]:
        return line[:-2], True
    elif line[-1:] in ["\r", "\n", b"\r", b"\n"]:
        return line[:-1], True
    return line, False
912095
def _parseline(self, line):
        
        sline = line.split(SEPARATOR)
        segment = sline[0]
        handlers = {
            SEGMENT_HEADER: self._handle_header,
            SEGMENT_EOF: self._handle_eof,
            SEGMENT_RESULT: self._handle_result_line,
            SEGMENT_OBSERVATION_ORDER: self._handle_new_record
        }
        handler = handlers.get(segment)
        if handler:
            return handler(sline)
        return 0
476582
def extract_from_plain(msg_body):
    """"""
    stripped_text = msg_body

    delimiter = get_delimiter(msg_body)
    msg_body = preprocess(msg_body, delimiter)
    # don't process too long messages
    lines = msg_body.splitlines()[:MAX_LINES_COUNT]
    markers = mark_message_lines(lines)
    lines = process_marked_lines(lines, markers)

    # concatenate lines, change links back, strip and return
    msg_body = delimiter.join(lines)
    msg_body = postprocess(msg_body)
    return msg_body
552942
def get_lines(data_nts, prtfmt=None, nt_fields=None, **kws):
    """"""
    lines = []
    # optional keyword args: prt_if sort_by
    if prtfmt is None:
        prtfmt = mk_fmtfld(data_nts[0], kws.get('joinchr', ' '), kws.get('eol', '\n'))
    # if nt_fields arg is None, use fields from prtfmt string.
    if nt_fields is not None:
        _chk_flds_fmt(nt_fields, prtfmt)
    if 'sort_by' in kws:
        data_nts = sorted(data_nts, key=kws['sort_by'])
    prt_if = kws.get('prt_if', None)
    for data_nt in data_nts:
        if prt_if is None or prt_if(data_nt):
            lines.append(prtfmt.format(**data_nt._asdict()))
    return lines
1307976
def _get_line_type(line):
    '''  '''
    stripped = line.strip()
    if not stripped:
        return 'empty'
    remainder = re.sub(r"\s+", " ", re.sub(CHORD_RE, "", stripped))
    if len(remainder) * 2 < len(re.sub(r"\s+", " ", stripped)):
        return 'chord'
    return 'lyric'
545661
def from_lines(lines: Iterable[str], **kwargs) -> BELGraph:
    
    graph = BELGraph()
    parse_lines(graph=graph, lines=lines, **kwargs)
    return graph
1309328
def parse(cls, line, ns={}):
        
        definitions = []
        parses  = [p for p in cls.compositor_spec.scanString(line)]
        if len(parses) != 1:
            raise SyntaxError("Invalid specification syntax.")
        else:
            e = parses[0][2]
            processed = line[:e]
            if (processed.strip() != line.strip()):
                raise SyntaxError("Failed to parse remainder of string: %r" % line[e:])

        opmap = {op.__name__:op for op in Compositor.operations}
        for group in cls.compositor_spec.parseString(line):

            if ('mode' not in group) or group['mode'] not in ['data', 'display']:
                raise SyntaxError("Either data or display mode must be specified.")
            mode = group['mode']

            kwargs = {}
            operation = opmap[group['op']]
            spec = ' '.join(group['spec'].asList()[0])

            if  group['op'] not in opmap:
                raise SyntaxError("Operation %s not available for use with compositors."
                                  % group['op'])
            if  'op_settings' in group:
                kwargs = cls.todict(group['op_settings'][0], 'brackets', ns=ns)

            definition = Compositor(str(spec), operation, str(group['value']), mode, **kwargs)
            definitions.append(definition)
        return definitions
1369724
def parse(self, lines):
        ''''''
        if self.type == 'msdos':
            return self.parse_msdos(lines)
        elif self.type == 'unix':
            return self.parse_unix(lines)
        elif self.type == 'nlst':
            return self.parse_nlst(lines)
        else:
            raise UnknownListingError('Unsupported listing type.')
332862
def parse_line(line):
    '''  '''
    line = line.rstrip()
    line_type = _get_line_type(line)
    return TabLine(
        type=line_type,
        data=_DATA_PARSERS[line_type](line),
        original=line,
    )
121504
def convert(self, line=None, is_end=True):
        
        if line is not None:
            self.line = line
        if not self.line:
            raise TomlDecodeError(self.parser.lineno,
                                  'EOF is hit!')
        token = None
        self.line = self.line.lstrip()
        for key, pattern in self.patterns:
            m = pattern.match(self.line)
            if m:
                self.line = self.line[m.end():]
                handler = getattr(self, 'convert_%s' % key)
                token = handler(m)
                break
        else:
            raise TomlDecodeError(self.parser.lineno,
                                  'Parsing error: %r' % self.line)
        if is_end and not BLANK_RE.match(self.line):
            raise TomlDecodeError(self.parser.lineno,
                                  'Something is remained: %r' % self.line)
        return token
678964
def parse (cls, line, lineno, log, cmddict=None):
    
    start  = line.find('%')
    pos    = SeqPos(line, lineno, start + 1, len(line))
    result = None

    if start >= 0:
      result = cls(line[start:], pos)

    return result
452826
def from_statement(cls, statement, filename='<expr>'):
    
    lines = textwrap.dedent(statement).split('\n')
    if lines and not lines[0]:  # Remove the initial empty line, which is an artifact of dedent.
      lines = lines[1:]

    blob = '\n'.join(lines).encode('utf-8')
    tree = cls._parse(blob, filename)
    return cls(blob=blob, tree=tree, root=None, filename=filename)
290885
def parse(self, fo):
        
        motifs = []
        m = [[float(x) for x in fo.readline().strip().split(" ")] for i in range(4)]
        matrix = [[m[0][i], m[1][i],m[2][i],m[3][i]] for i in range(len(m[0]))]
        motifs = [Motif(matrix)]
        motifs[-1].id = self.name
        
        return motifs