Read MM_UIC2 tag from file and return as dictionary.
517526
def read_mm_uic2(fd, byte_order, dtype, count):
    """"""
    result = {'number_planes': count}
    values = numpy.fromfile(fd, byte_order+'I', 6*count)
    result['z_distance'] = values[0::6] // values[1::6]
    #result['date_created'] = tuple(values[2::6])
    #result['time_created'] = tuple(values[3::6])
    #result['date_modified'] = tuple(values[4::6])
    #result['time_modified'] = tuple(values[5::6])
    return result
362957
def readmodule(module, path=None):
    ''''''

    res = {}
    for key, value in _readmodule(module, path or []).items():
        if isinstance(value, Class):
            res[key] = value
    return res
101844
def read(self):
        """"""
        self.convertRSTmetaToMD()
        self._md = Markdown(extensions=['meta', 'codehilite(linenums=True)'])
        content = self._md.convert(self.source)
        metadata = self._parse_metadata(self._md.Meta)
        return content, metadata
567732
def _read_tags(self):
        
        tags = self._config.get('tags', {})
        logging.info('Tags:')
        for tag_name in tags.keys():
            tag = {}
            tag['Key'] = tag_name
            tag['Value'] = tags[tag_name]
            self._tags.append(tag)
            logging.info('{} = {}'.format(tag_name, tags[tag_name]))

        logging.debug(json.dumps(
            self._tags,
            indent=2,
            sort_keys=True
        ))
        return True
600280
def parse_readme():
    
    name = None
    re_mod = re.compile(r'^\#\#\# <a name="(?P<name>[a-z_0-9]+)"></a>')
    readme_file = os.path.join(modules_directory(), "README.md")
    modules_dict = {}
    with open(readme_file) as f:
        for row in f.readlines():
            match = re_mod.match(row)
            if match:
                name = match.group("name")
                modules_dict[name] = []
                continue
            if row.startswith("---"):
                name = None
                continue
            if name:
                modules_dict[name].append(row)
    return modules_dict
278643
def _parse(self, text, i):
        """"""

        m = self.start_dict_re.match(text, i)
        if m:
            parsed = m.group(0)
            i += len(parsed)
            return self._parse_dict(text, i)

        m = self.start_list_re.match(text, i)
        if m:
            parsed = m.group(0)
            i += len(parsed)
            return self._parse_list(text, i)

        m = self.value_re.match(text, i)
        if m:
            parsed = m.group(0)
            i += len(parsed)
            if hasattr(self.current_type, "read"):
                reader = self.current_type()
                # Give the escaped value to `read` to be symetrical with
                # `plistValue` which handles the escaping itself.
                value = reader.read(m.group(1))
                return value, i

            value = self._trim_value(m.group(1))

            if self.current_type in (None, dict, OrderedDict):
                self.current_type = self._guess_current_type(parsed, value)

            if self.current_type == bool:
                value = bool(int(value))  # bool(u'0') returns True
                return value, i

            value = self.current_type(value)

            return value, i

        m = self.hex_re.match(text, i)
        if m:
            from glyphsLib.types import BinaryData

            parsed, value = m.group(0), m.group(1)
            decoded = BinaryData.fromHex(value)
            i += len(parsed)
            return decoded, i
        else:
            self._fail("Unexpected content", text, i)
293407
def get_metadata():
    
    misc_path = pkg_resources.resource_filename('hwrt', 'misc/')
    wm_symbols = os.path.join(misc_path, 'wm_symbols.csv')
    wm_tags = os.path.join(misc_path, 'wm_tags.csv')
    wm_tags2symbols = os.path.join(misc_path, 'wm_tags2symbols.csv')
    return {'symbols': read_csv(wm_symbols),
            'tags': read_csv(wm_tags),
            'tags2symbols': read_csv(wm_tags2symbols)}
257951
def read_bytes(fd, byte_order, dtype, count):
    """"""
    return numpy.fromfile(fd, byte_order+dtype[-1], count).tostring()
357269
def read_uic_tag(fh, tagid, planecount, offset):
    
    def read_int(count=1):
        value = struct.unpack('<%iI' % count, fh.read(4*count))
        return value[0] if count == 1 else value

    try:
        name, dtype = TIFF.UIC_TAGS[tagid]
    except IndexError:
        # unknown tag
        return '_TagId%i' % tagid, read_int()

    Fraction = TIFF.UIC_TAGS[4][1]

    if offset:
        pos = fh.tell()
        if dtype not in (int, None):
            off = read_int()
            if off < 8:
                if dtype is str:
                    return name, ''
                log.warning("read_uic_tag: invalid offset for tag '%s' (%i)",
                            name, off)
                return name, off
            fh.seek(off)

    if dtype is None:
        # skip
        name = '_' + name
        value = read_int()
    elif dtype is int:
        # int
        value = read_int()
    elif dtype is Fraction:
        # fraction
        value = read_int(2)
        value = value[0] / value[1]
    elif dtype is julian_datetime:
        # datetime
        value = julian_datetime(*read_int(2))
    elif dtype is read_uic_image_property:
        # ImagePropertyEx
        value = read_uic_image_property(fh)
    elif dtype is str:
        # pascal string
        size = read_int()
        if 0 <= size < 2**10:
            value = struct.unpack('%is' % size, fh.read(size))[0][:-1]
            value = bytes2str(stripnull(value))
        elif offset:
            value = ''
            log.warning("read_uic_tag: corrupt string in tag '%s'", name)
        else:
            raise ValueError('read_uic_tag: invalid string size %i' % size)
    elif dtype == '%ip':
        # sequence of pascal strings
        value = []
        for _ in range(planecount):
            size = read_int()
            if 0 <= size < 2**10:
                string = struct.unpack('%is' % size, fh.read(size))[0][:-1]
                string = bytes2str(stripnull(string))
                value.append(string)
            elif offset:
                log.warning("read_uic_tag: corrupt string in tag '%s'", name)
            else:
                raise ValueError('read_uic_tag: invalid string size: %i' %
                                 size)
    else:
        # struct or numpy type
        dtype = '<' + dtype
        if '%i' in dtype:
            dtype = dtype % planecount
        if '(' in dtype:
            # numpy type
            value = fh.read_array(dtype, 1)[0]
            if value.shape[-1] == 2:
                # assume fractions
                value = value[..., 0] / value[..., 1]
        else:
            # struct format
            value = struct.unpack(dtype, fh.read(struct.calcsize(dtype)))
            if len(value) == 1:
                value = value[0]

    if offset:
        fh.seek(pos + 4)

    return name, value
1011844
def parse_uniprot_txt_file(infile):
    
    uniprot_metadata_dict = {}

    metadata = old_parse_uniprot_txt_file(infile)
    metadata_keys = list(metadata.keys())

    if metadata_keys:
        metadata_key = metadata_keys[0]
    else:
        return uniprot_metadata_dict

    uniprot_metadata_dict['seq_len'] = len(str(metadata[metadata_key]['sequence']))
    uniprot_metadata_dict['reviewed'] = metadata[metadata_key]['is_reviewed']
    uniprot_metadata_dict['seq_version'] = metadata[metadata_key]['sequence_version']
    uniprot_metadata_dict['entry_version'] = metadata[metadata_key]['entry_version']
    if 'gene' in metadata[metadata_key]:
        uniprot_metadata_dict['gene_name'] = metadata[metadata_key]['gene']
    if 'description' in metadata[metadata_key]:
        uniprot_metadata_dict['description'] = metadata[metadata_key]['description']
    if 'refseq' in metadata[metadata_key]:
        uniprot_metadata_dict['refseq'] = metadata[metadata_key]['refseq']
    if 'kegg' in metadata[metadata_key]:
        uniprot_metadata_dict['kegg'] = metadata[metadata_key]['kegg']
    if 'ec' in metadata[metadata_key]:
        uniprot_metadata_dict['ec_number'] = metadata[metadata_key]['ec']
    if 'pfam' in metadata[metadata_key]:
        uniprot_metadata_dict['pfam'] = metadata[metadata_key]['pfam']
    if 'pdbs' in metadata[metadata_key]:
        uniprot_metadata_dict['pdbs'] = list(set(metadata[metadata_key]['pdbs']))
    return uniprot_metadata_dict
582616
def to_dict(self, instance, d):
        

        value = self.__get__(instance, type(instance))
        if value == self.default:
            return

        d[self.tag] = self.type_.format(value)
1266483
def parse_tag_info(self, f):
        
        # General Stats Table
        tag_info = dict()
        for l in f['f']:
            s = l.split("=")
            if len(s) > 1:
                if s[0].strip() == 'genome':
                    ss = s[1].split("\t")
                    if len(ss) > 2:
                        tag_info['genome'] = ss[0].strip()
                        try:
                            tag_info['UniqPositions'] = float(ss[1].strip())
                            tag_info['TotalPositions'] = float(ss[2].strip())
                        except:
                            tag_info['UniqPositions'] = ss[1].strip()
                            tag_info['TotalPositions'] = ss[2].strip()
                try:
                    tag_info[s[0].strip()] = float(s[1].strip())
                except ValueError:
                    tag_info[s[0].strip()] = s[1].strip()
        return tag_info
799862
def from_file(cls, f):
        
        word2index = {}
        counts = Counter()
        for i, line in enumerate(f):
            word, count_str = line.split('\t')
            word = word.decode('utf-8')
            word2index[word] = i
            counts[word] = float(count_str)
            if i == 0:
                unk = word
        return cls.from_dict(word2index, unk, counts)
1309483
def parse_MML(self, mml):
        '''  '''
        hashes_c = []
        mentions_c = []
        soup = BeautifulSoup(mml, "lxml")
        hashes = soup.find_all('hash', {"tag": True})
        for hashe in hashes:
            hashes_c.append(hashe['tag'])
        mentions = soup.find_all('mention', {"uid": True})
        for mention in mentions:
            mentions_c.append(mention['uid'])
        msg_string = soup.messageml.text.strip()
        self.logger.debug('%s : %s : %s' % (hashes_c, mentions_c, msg_string))
        return hashes_c, mentions_c, msg_string
728922
def _parse(fileobj):
    """"""
    fileobj.seek(0)
    try:
        part = fileobj.read(2)
    except UnicodeDecodeError:
        part = ""

    if part == "#!":
        shebang = shlex.split(fileobj.readline().strip())
        if (platform.system() == "Windows" and
                len(shebang) and
                os.path.basename(shebang[0]) == "env"):
            return shebang[1:]

        return shebang

    return []
1356898
def read_uic_image_property(fh):
    """"""
    # TODO: test this
    size = struct.unpack('B', fh.read(1))[0]
    name = struct.unpack('%is' % size, fh.read(size))[0][:-1]
    flags, prop = struct.unpack('<IB', fh.read(5))
    if prop == 1:
        value = struct.unpack('II', fh.read(8))
        value = value[0] / value[1]
    else:
        size = struct.unpack('B', fh.read(1))[0]
        value = struct.unpack('%is' % size, fh.read(size))[0]
    return dict(name=name, flags=flags, value=value)
135376
def imread(filename):
    ''' 
     
    '''
    im = cv2.imread(filename)
    if im is None:
        raise RuntimeError("file: '%s' not exists" % filename)
    return im