Return the contents of a real file or a zip file.
771721
def get_package_data(filename, mode='rb'):
    ''''''
    if os.path.exists(filename):
        with open(filename, mode=mode) as in_file:
            return in_file.read()
    else:
        parts = os.path.normpath(filename).split(os.sep)

        for part, index in zip(parts, range(len(parts))):
            if part.endswith('.zip'):
                zip_path = os.sep.join(parts[:index + 1])
                member_path = os.sep.join(parts[index + 1:])
                break

        if platform.system() == 'Windows':
            member_path = member_path.replace('\\', '/')

        with zipfile.ZipFile(zip_path) as zip_file:
            return zip_file.read(member_path)
356216
def read_bytes(self, path):
        """"""
        file = staticfiles_storage.open(path)
        content = file.read()
        file.close()
        return content
154992
def parse_files(self, req, name, field):
        """"""
        return get_value(req.files, name, field)
443872
def url_or_file_open(uri):
    """"""
    if (not re.match(r'''\w+:''', uri)):
        uri = 'file:' + uri
    return(urlopen(uri))
932838
def read(*paths):
    """"""
    basedir = os.path.dirname(__file__)
    fullpath = os.path.join(basedir, *paths)
    contents = io.open(fullpath, encoding='utf-8').read().strip()
    return contents
1290538
def load_zip_data(zipname, f_sino_real, f_sino_imag,
                  f_angles=None, f_phantom=None, f_info=None):
    """"""
    ret = []
    with zipfile.ZipFile(str(zipname)) as arc:
        sino_real = np.loadtxt(arc.open(f_sino_real))
        sino_imag = np.loadtxt(arc.open(f_sino_imag))
        sino = sino_real + 1j * sino_imag
        ret.append(sino)
        if f_angles:
            angles = np.loadtxt(arc.open(f_angles))
            ret.append(angles)
        if f_phantom:
            phantom = np.loadtxt(arc.open(f_phantom))
            ret.append(phantom)
        if f_info:
            with arc.open(f_info) as info:
                cfg = {}
                for li in info.readlines():
                    li = li.decode()
                    if li.count("=") == 1:
                        key, val = li.split("=")
                        cfg[key.strip()] = float(val.strip())
            ret.append(cfg)
    return ret
1357239
def get_gzipped_contents(input_file):
    
    zbuf = StringIO()
    zfile = GzipFile(mode="wb", compresslevel=6, fileobj=zbuf)
    zfile.write(input_file.read())
    zfile.close()
    return ContentFile(zbuf.getvalue())
743494
def get_file_contents(self, file_key):
		'''
		'''
		#does not work
		self._raise_unimplemented_error()
		
		uri = '/'.join([self.api_uri,
						self.files_suffix,
						file_key,
						self.file_contents_suffix,
						])
		return self._req('get', uri)
907892
def data_file(self):
        """"""

        if self._data_file is None:
            fileobj = _SubFile(self._fileobj, self.data_offset)

            if self.headers["archive_compression"] == b"xz":
                if not getattr(sys.modules[__name__], 'lzma', False):
                    raise NoLZMAModuleError('lzma module not present')
                self._data_file = lzma.LZMAFile(fileobj)
            else:
                self._data_file = gzip.GzipFile(fileobj=fileobj)

        return self._data_file
21764
def get(tzid):
    """"""
    ns = {}
    path = os.path.join(DATA_DIR, tzid)
    with open(path) as f:
        raw_data = f.read()
    exec(raw_data, ns, ns)
    z = ZoneData()
    z.types = [(delta(offset), delta(save), abbr)
               for offset, save, abbr in ns['types']]
    z.times = [(datetime(*time), i)
               for time, i in ns['times']]
    z.rules = ns['posix']
    return z
440599
def _contents(self):
        """"""
        if self.__urldata__ is Ellipsis or self.__cache_request__ is False:
            if self._file_data:
                # Special-case: do a multipart upload if there's file data
                self.__post__ = True
                boundary = "-"*12+str(uuid.uuid4())+"$"
                multipart_data = ''
                for k, v in cgi.parse_qs(self.query).items():
                    if not isinstance(v, list):
                        v = [v]
                    for val in v:
                        multipart_data += boundary + "\r\n"
                        multipart_data += ('Content-Disposition: form-data; '
                                           'name="%s"\r\n\r\n' % k)
                        multipart_data += val + "\r\n"
                for k, v in self._file_data.items():
                    fn = os.path.basename(getattr(v, 'name', 'file'))
                    ct = (mimetypes.guess_type(fn) 
                            or ("application/octet-stream",))[0]
                    multipart_data += boundary + "\r\n"
                    multipart_data += ('Content-Disposition: form-data; '
                                       'name="%s"; filename="%s"\r\n'
                                       'Content-Type:%s\r\n\r\n' % 
                                            (k, fn, ct))
                    multipart_data += v.read() + "\r\n"
                multipart_data += boundary + "--\r\n\r\n"
                req_dict = {'User-Agent' : USER_AGENT,
                            'Content-Type': 
                                'multipart/form-data; boundary='+boundary[2:],
                            'Content-Length': str(len(multipart_data))
                            }
                if self._referer:
                    req_dict['Referer'] = self._referer
                request = compat.urllib2.Request(self.url,
                                          multipart_data,
                                          req_dict)
            else:
                req_dict = {'User-Agent' : USER_AGENT}
                if self._referer:
                    req_dict['Referer'] = self._referer
                request = compat.urllib2.Request(self.url, self.query 
                                                        if self.__post__
                                                        else None,
                                           req_dict)
            handle = compat.urllib2.urlopen(request)
            # Handle the special case of a redirect (only follow once) --
            # Note that only the first 3 components (protocol, hostname, path)
            # are altered as component 4 is the query string, which can get
            # clobbered by the server.
            fetched_url = list(compat.urlsplit(handle.url)[:3])
            if fetched_url != list(self._url[:3]):
                self._url[:3] = fetched_url
                return self._contents
            # No redirect, proceed as usual.
            self.__headers__ = compat.get_headers(handle)
            self.__urldata__ = handle.read()
        data = self.__urldata__
        if self.__cache_request__ is False:
            self.__urldata__ = Ellipsis
        return data
1177062
def from_file(cls, file_path, compressed=False, encoded=False):
        """"""
        file_id = '.'.join(path.basename(file_path).split('.')[:-1])
        file_format = file_path.split('.')[-1]
        content = cls(file_id, file_format, compressed, encoded)
        content.file_exists = True
        content._location = path.dirname(file_path)
        return content
822199
def from_zipfile(cls, path, filename, encoding, dialect, fields, converters):
        """"""

        stream = ZipReader(path, filename).readlines(encoding)
        return cls(stream, dialect, fields, converters)
727580
def read(afile):
    """"""
    the_relative_file = os.path.join(HERE, afile)
    with codecs.open(the_relative_file, 'r', 'utf-8') as opened_file:
        content = filter_out_test_code(opened_file)
        content = "".join(list(content))
        return content
1308052
def _RealGetContents(self):
        """"""
        fp = self.fp
        try:
            endrec = _EndRecData(fp)
        except OSError:
            raise BadZipFile("File is not a zip file")
        if not endrec:
            raise BadZipFile("File is not a zip file")
        if self.debug > 1:
            print(endrec)
        size_cd = endrec[_ECD_SIZE]             # bytes in central directory
        offset_cd = endrec[_ECD_OFFSET]         # offset of central directory
        self._comment = endrec[_ECD_COMMENT]    # archive comment

        # ---> APK文件只有一个，不可能存在额外数据。
        # "concat" is zero, unless zip was concatenated to another file
        # concat = endrec[_ECD_LOCATION] - size_cd - offset_cd
        # if endrec[_ECD_SIGNATURE] == stringEndArchive64:
        #     # If Zip64 extension structures are present, account for them
        #     concat -= (sizeEndCentDir64 + sizeEndCentDir64Locator)
        concat = 0

        if self.debug > 2:
            inferred = concat + offset_cd
            print("given, inferred, offset", offset_cd, inferred, concat)
        # self.start_dir:  Position of start of central directory
        self.start_dir = offset_cd + concat
        fp.seek(self.start_dir, 0)
        data = fp.read(size_cd)
        fp = io.BytesIO(data)
        total = 0
        while total < size_cd:
            centdir = fp.read(sizeCentralDir)
            if len(centdir) != sizeCentralDir:
                raise BadZipFile("Truncated central directory")
            centdir = struct.unpack(structCentralDir, centdir)
            if centdir[_CD_SIGNATURE] != stringCentralDir:
                raise BadZipFile("Bad magic number for central directory")
            if self.debug > 2:
                print(centdir)
            filename = fp.read(centdir[_CD_FILENAME_LENGTH])
            flags = centdir[5]
            if flags & 0x800:
                # UTF-8 file names extension
                filename = filename.decode('utf-8')
            else:
                # Historical ZIP filename encoding
                filename = filename.decode('cp437')
            # Create ZipInfo instance to store file information
            x = ZipInfo(filename)
            x.extra = fp.read(centdir[_CD_EXTRA_FIELD_LENGTH])
            x.comment = fp.read(centdir[_CD_COMMENT_LENGTH])
            x.header_offset = centdir[_CD_LOCAL_HEADER_OFFSET]
            (x.create_version, x.create_system, x.extract_version, x.reserved,
             x.flag_bits, x.compress_type, t, d,
             x.CRC, x.compress_size, x.file_size) = centdir[1:12]
            if x.extract_version > MAX_EXTRACT_VERSION:
                raise NotImplementedError("zip file version %.1f" %
                                          (x.extract_version / 10))
            x.volume, x.internal_attr, x.external_attr = centdir[15:18]
            # Convert date/time code to (year, month, day, hour, min, sec)
            x._raw_time = t
            x.date_time = ((d >> 9) + 1980, (d >> 5) & 0xF, d & 0x1F,
                           t >> 11, (t >> 5) & 0x3F, (t & 0x1F) * 2)

            x._decodeExtra()
            # x.header_offset = x.header_offset + concat
            self.filelist.append(x)
            self.NameToInfo[x.filename] = x

            # update total bytes read from central directory
            total = total + sizeCentralDir + \
                centdir[_CD_FILENAME_LENGTH] + \
                centdir[_CD_EXTRA_FIELD_LENGTH] + centdir[_CD_COMMENT_LENGTH]
187216
def getsourcefile(object):
    """"""
    filename = getfile(object)
    if string.lower(filename[-4:]) in ['.pyc', '.pyo']:
        filename = filename[:-4] + '.py'
    for suffix, mode, kind in imp.get_suffixes():
        if 'b' in mode and string.lower(filename[-len(suffix):]) == suffix:
            # Looks like a binary file.  We want to only return a text file.
            return None
    if os.path.exists(filename):
        return filename
798310
def get_file_contents(self, pointer=False):
        '''
        
        '''
        if self.pointer:
            if pointer:
                return self.old_pointed
            else:
                return self.old_data
        else:
            return self.old_data