Read MetaMorph STK UIC2Tag from file and return as dict.
176099
def read_uic2tag(fh, byteorder, dtype, planecount, offsetsize):
    """"""
    assert dtype == '2I' and byteorder == '<'
    values = fh.read_array('<u4', 6*planecount).reshape(planecount, 6)
    return {
        'ZDistance': values[:, 0] / values[:, 1],
        'DateCreated': values[:, 2],  # julian days
        'TimeCreated': values[:, 3],  # milliseconds
        'DateModified': values[:, 4],  # julian days
        'TimeModified': values[:, 5]}
291412
def _ParseTokenType(self, file_object, file_offset):
    
    token_type_map = self._GetDataTypeMap('uint8')

    token_type, _ = self._ReadStructureFromFileObject(
        file_object, file_offset, token_type_map)

    return token_type
323776
def stk_metadata(self):
        """"""
        if not self.is_stk:
            return None
        page = self.pages[0]
        tags = page.tags
        result = {}
        result['NumberPlanes'] = tags['UIC2tag'].count
        if page.description:
            result['PlaneDescriptions'] = page.description.split('\0')
            # result['plane_descriptions'] = stk_description_metadata(
            #    page.image_description)
        if 'UIC1tag' in tags:
            result.update(tags['UIC1tag'].value)
        if 'UIC3tag' in tags:
            result.update(tags['UIC3tag'].value)  # wavelengths
        if 'UIC4tag' in tags:
            result.update(tags['UIC4tag'].value)  # override uic1 tags
        uic2tag = tags['UIC2tag'].value
        result['ZDistance'] = uic2tag['ZDistance']
        result['TimeCreated'] = uic2tag['TimeCreated']
        result['TimeModified'] = uic2tag['TimeModified']
        try:
            result['DatetimeCreated'] = numpy.array(
                [julian_datetime(*dt) for dt in
                 zip(uic2tag['DateCreated'], uic2tag['TimeCreated'])],
                dtype='datetime64[ns]')
            result['DatetimeModified'] = numpy.array(
                [julian_datetime(*dt) for dt in
                 zip(uic2tag['DateModified'], uic2tag['TimeModified'])],
                dtype='datetime64[ns]')
        except ValueError as exc:
            log.warning('STK metadata: %s: %s', exc.__class__.__name__, exc)
        return result
1220884
def to_yaml(cls, dumper, vividict):
        
        dictionary = cls.vividict_to_dict(vividict)
        node = dumper.represent_mapping(cls.yaml_tag, dictionary)
        return node
1179903
def load_metadata(fileobj):
        
        with gzip.GzipFile(fileobj=fileobj, mode='r') as z:
            return json.loads(z.readline())
252519
def read(cls, iprot):
        '''
        
        '''

        init_kwds = {}

        iprot.read_struct_begin()
        while True:
            ifield_name, ifield_type, _ifield_id = iprot.read_field_begin()
            if ifield_type == 0:  # STOP
                break
            elif ifield_name == 'full_size_url':
                init_kwds['full_size_url'] = iprot.read_string()
            elif ifield_name == 'mediaid':
                init_kwds['mediaid'] = iprot.read_string()
            elif ifield_name == 'objectid':
                init_kwds['objectid'] = iprot.read_string()
            elif ifield_name == 'src':
                init_kwds['src'] = iprot.read_string()
            elif ifield_name == 'thumbnail_url':
                init_kwds['thumbnail_url'] = iprot.read_string()
            elif ifield_name == 'title':
                init_kwds['title'] = iprot.read_string()
            elif ifield_name == 'type':
                init_kwds['type'] = pastpy.gen.database.impl.online.online_database_object_detail_image_type.OnlineDatabaseObjectDetailImageType.value_of(iprot.read_string().strip().upper())
            iprot.read_field_end()
        iprot.read_struct_end()

        return cls(**init_kwds)
1313511
def parse_kegg_gene_metadata(infile):
    
    metadata = defaultdict(str)

    with open(infile) as mf:
        kegg_parsed = bs_kegg.parse(mf.read())

    # TODO: additional fields can be parsed

    if 'DBLINKS' in kegg_parsed.keys():
        if 'UniProt' in kegg_parsed['DBLINKS']:
            unis = str(kegg_parsed['DBLINKS']['UniProt']).split(' ')
            # TODO: losing other uniprot ids by doing this
            if isinstance(unis, list):
                metadata['uniprot'] = unis[0]
            else:
                metadata['uniprot'] = unis
        if 'NCBI-ProteinID' in kegg_parsed['DBLINKS']:
            metadata['refseq'] = str(kegg_parsed['DBLINKS']['NCBI-ProteinID'])
    if 'STRUCTURE' in kegg_parsed.keys():
        metadata['pdbs'] = str(kegg_parsed['STRUCTURE']['PDB']).split(' ')
    else:
        metadata['pdbs'] = None
    if 'ORGANISM' in kegg_parsed.keys():
        metadata['taxonomy'] = str(kegg_parsed['ORGANISM'])

    return metadata
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)
369878
def raw(self, tag, raw, metadata):
        
        raw = base64.b64encode(raw)
        return {
            'type': 'raw',
            'tag': tag,
            'raw': raw,
            'metadata': metadata
        }
174395
def _handle_tag_definemorphshape2(self):
        """"""
        obj = _make_object("DefineMorphShape2")
        obj.CharacterId = unpack_ui16(self._src)
        obj.StartBounds = self._get_struct_rect()
        obj.EndBounds = self._get_struct_rect()
        obj.StartEdgeBounds = self._get_struct_rect()
        obj.EndEdgeBounds = self._get_struct_rect()

        bc = BitConsumer(self._src)
        bc.u_get(6)  # reserved
        obj.UsesNonScalingStrokes = bc.u_get(1)
        obj.UsesScalingStrokes = bc.u_get(1)

        obj.Offset = unpack_ui32(self._src)

        # FIXME: this tag needs more work; I'm skipping some attributes here
        self._src.read(obj.Offset)

        obj.EndEdges = self._get_struct_shape()
        return obj
334393
def metafetcher(bamfile, metacontig2contig, metatag):
    ''' '''
    for metacontig in metacontig2contig:
        for contig in metacontig2contig[metacontig]:
            for read in bamfile.fetch(contig):
                read.set_tag(metatag, metacontig)
                yield read
408436
def _fromfile(self):
        
        fd = self.parent._fd
        byte_order = self.parent.byte_order
        offset_size = self.parent.offset_size

        fmt = {4: 'I', 8: 'Q'}[offset_size]
        offset = struct.unpack(byte_order + fmt, fd.read(offset_size))[0]
        if not offset:
            raise StopIteration()

        # read standard tags
        tags = self.tags
        fd.seek(offset)
        fmt, size = {4: ('H', 2), 8: ('Q', 8)}[offset_size]
        try:
            numtags = struct.unpack(byte_order + fmt, fd.read(size))[0]
        except Exception:
            warnings.warn("corrupted page list")
            raise StopIteration()

        for _ in range(numtags):
            tag = TIFFtag(self.parent)
            tags[tag.name] = tag

        # read LSM info subrecords
        if self.is_lsm:
            pos = fd.tell()
            for name, reader in CZ_LSM_INFO_READERS.items():
                try:
                    offset = self.cz_lsm_info["offset_"+name]
                except KeyError:
                    continue
                if not offset:
                    continue
                fd.seek(offset)
                try:
                    setattr(self, "cz_lsm_"+name, reader(fd, byte_order))
                except ValueError:
                    pass
            fd.seek(pos)
601400
def load_metadata_from_file(filename):
    
    try:
        extension = os.path.splitext(filename)[1]
        return _metadata_loader[extension](filename)
    except KeyError:
        raise TypeError('Cannot read metadata from file %s, extension %s not '
                        'supported at this time' % (filename, extension))
1237483
def read_dict_from_properties(desired_type: Type[dict], file_object: TextIOBase,
                              logger: Logger, conversion_finder: ConversionFinder, **kwargs) -> Dict[str, Any]:
    

    # right now jprops relies on a byte stream. So we convert back our nicely decoded Text stream to a unicode
    # byte stream ! (urgh)
    class Unicoder:
        def __init__(self, file_object):
            self.f = file_object

        def __iter__(self):
            return self

        def __next__(self):
            line = self.f.__next__()
            return line.encode(encoding='utf-8')

    res = jprops.load_properties(Unicoder(file_object))

    # first automatic conversion of strings > numbers
    res = {key: try_parse_num_and_booleans(val) for key, val in res.items()}

    # further convert if required
    return ConversionFinder.convert_collection_values_according_to_pep(res, desired_type, conversion_finder, logger, 
                                                                       **kwargs)
1138219
def get_metadata(self, filename):
        ''''''
        dest = self.path(filename)
        with open(dest, 'rb', buffering=0) as f:
            checksum = 'sha1:{0}'.format(sha1(f))
        return {
            'checksum': checksum,
            'size': os.path.getsize(dest),
            'mime': files.mime(filename),
            'modified': datetime.fromtimestamp(os.path.getmtime(dest)),
        }
228921
def parse_tag (self, tag, attr, value, name, base):
        """"""
        assert isinstance(tag, unicode), repr(tag)
        assert isinstance(attr, unicode), repr(attr)
        assert isinstance(name, unicode), repr(name)
        assert isinstance(base, unicode), repr(base)
        assert isinstance(value, unicode) or value is None, repr(value)
        # look for meta refresh
        if tag == u'meta' and value:
            mo = refresh_re.match(value)
            if mo:
                self.found_url(mo.group("url"), name, base)
            elif attr != 'content':
                self.found_url(value, name, base)
        elif attr == u'style' and value:
            for mo in css_url_re.finditer(value):
                url = unquote(mo.group("url"), matching=True)
                self.found_url(url, name, base)
        elif attr == u'archive':
            for url in value.split(u','):
                self.found_url(url, name, base)
        elif attr == u'srcset':
            for img_candidate in value.split(u','):
                url = img_candidate.split()[0]
                self.found_url(url, name, base)
        else:
            self.found_url(value, name, base)
502526
def from_tag(cls, tag, schemas, ext='.rnc'):
        """"""
        return cls(fn=cls.filename(tag, schemas, ext=ext))