
[c           @` s#  d  Z  d d l m Z m Z m Z m Z d d l m Z d d l m	 Z	 m
 Z
 d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l Z d d l m Z m Z d d l m Z d d	 l m Z d d
 l m Z d d l m  Z  m! Z! y d d l" Z" Wn e# k
 rKe$ Z% n Xe& Z% d d d d d d d d d d d d d d d d d d g Z' i  Z( d e j) f d     YZ* e*   Z+ d  e f d!     YZ, d"   Z- d#   Z. e j/ d e$ e& d d$   Z1 d%   Z2 e j/ d d e& d&   Z3 d e& d d'  Z4 d d e& d(  Z5 d d) d*  Z6 d d) d d+  Z7 d,   Z8 d d-  Z9 d.   Z: d/   Z; d0   Z< e$ e& d d1  Z= d2   Z> d3   Z? e$ e& d d4  Z@ g  aA e jB d5    ZC d d6  ZD d7   ZE e$ d8  ZF d9   ZG d:   ZH d;   ZI d S(<   u[    This module contains helper functions for accessing, downloading, and
caching data files.
i    (   t   absolute_importt   divisiont   print_functiont   unicode_literalsi   (   t   six(   t   urllibt   rangeN(   t   NamedTemporaryFilet
   gettempdir(   t   warn(   t   config(   t   AstropyWarning(   t   find_current_modulet   resolve_nameu   Confu   confu   get_readable_fileobju   get_file_contentsu   get_pkg_data_fileobju   get_pkg_data_filenameu   get_pkg_data_contentsu   get_pkg_data_fileobjsu   get_pkg_data_filenamesu   compute_hashu   clear_download_cacheu   CacheMissingWarningu   get_free_space_in_diru   check_free_space_in_diru   download_fileu   download_files_in_parallelu   is_url_in_cacheu   get_cached_urlst   Confc           B` s   e  Z d  Z e j d d  Z e j d d  Z e j d d d d g Z e j d d  Z e j d d  Z	 e j d d d  Z
 e j e d  Z RS(   u<   
    Configuration parameters for `astropy.utils.data`.
    u   http://data.astropy.org/u)   Primary URL for astropy remote data site.u$   http://www.astropy.org/astropy-data/u(   Mirror URL for astropy remote data site.g      $@u2   Time to wait for remote data queries (in seconds).t   aliasesu5   astropy.coordinates.name_resolve.name_resolve_timeouti   i   u)   Block size for computing MD5 file hashes.u4   Number of bytes of remote data to download per step.i   u'   Number of times to try to get the lock u0   while accessing the data cache before giving up.uz   If True, temporary download files created when the cache is inaccessible will be deleted at the end of the python session.i   i   (   t   __name__t
   __module__t   __doc__t   _configt
   ConfigItemt   dataurlt   dataurl_mirrort   remote_timeoutt   compute_hash_block_sizet   download_block_sizet   download_cache_lock_attemptst   Truet"   delete_temporary_downloads_at_exit(    (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyR   2   s0   				
t   CacheMissingWarningc           B` s   e  Z d  Z RS(   u1  
    This warning indicates the standard cache directory is not accessible, with
    the first argument providing the warning message. If args[1] is present, it
    is a filename indicating the path to a temporary file that was created to
    store a remote data download in the absence of the cache.
    (   R   R   R   (    (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyR   T   s   c         C` s%   t  j j |   } | j j   d k S(   uy   
    Test whether a string is a valid URL

    Parameters
    ----------
    string : str
        The string to test
    u   httpu   httpsu   ftpu   sftpu   sshu   file(   u   httpu   httpsu   ftpu   sftpu   sshu   file(   R   t   parset   urlparset   schemet   lower(   t   stringt   url(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   _is_url]   s    	c         C` sL   t  j j |   j t  j j |   pK t  j j |   j t  j j |   S(   N(   t   ost   patht   abspatht
   startswitht   realpath(   R&   t   parent_path(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt
   _is_insidem   s    'c         c` s  t  j } t r" | t j f 7} n  g  } g  } | d k rF t j } n  t |  |  r t rj t	 |   }  n  t
 |   } | r t |  d | d | d | }  n  t  j r t |  d  }	 n t j |  d  }	 | r | r | j |	  n  | j |	  n |  }	 t |	 d  s$t j |	 j    }	 n  |	 j d  }
 |	 j d  |
 d	  d
 k rd d l } y5 d d l } | j d |	 d d  } | j d  WnX t t f k
 r|	 j d  | j   qM| j k
 r|	 j d  | j   qMX| j d  | }	 nK|
 d	  d k ry d d l } Wn8 t k
 r\x | D] } | j   q9Wt d   n Xya t d d t  < } | j! |	 j    | j   | j" | j# d d } Wd QX| j d  Wn( t k
 r|	 j d  | j   qMX| j d  | j |  | }	 nA|
 d	  d k rMy t$ j% d k rRd d l& } | j' |	 d d } nm d d l( m& } d d l) m' } t d d t  9 } | j! |	 j    | j   | | j# d d } Wd QX| j d  Wng t k
 rx | D] } | j   qWt d   qMt t f k
 r6} |	 j d  | j   qMX| j d  | }	 n  t  j rq| d k ok| d k	 } n | d k } | ry d d l } Wn t k
 rn Xt |	 | j"  r>t d d t  } |	 j   } | j! |  | j   | j |  t  j rt | j# d  }	 n t j | j# d  }	 | j |	  n  t  j rnt |	 t*  rnt j |	 j+    }	 n  t j, |	  }	 t j- |	 d | }	 |	 j d  n  z	 |	 VWd x | D] } | j   qWx | D] } t. j/ | j#  qWXd S(   u  
    Given a filename, pathlib.Path object or a readable file-like object, return a context
    manager that yields a readable file-like object.

    This supports passing filenames, URLs, and readable file-like objects,
    any of which can be compressed in gzip, bzip2 or lzma (xz) if the
    appropriate compression libraries are provided by the Python installation.

    Notes
    -----

    This function is a context manager, and should be used for example
    as::

        with get_readable_fileobj('file.dat') as f:
            contents = f.read()

    Parameters
    ----------
    name_or_obj : str or file-like object
        The filename of the file to access (if given as a string), or
        the file-like object to access.

        If a file-like object, it must be opened in binary mode.

    encoding : str, optional
        When `None` (default), returns a file-like object with a
        ``read`` method that on Python 2.x returns `bytes` objects and
        on Python 3.x returns `str` (``unicode``) objects, using
        `locale.getpreferredencoding` as an encoding.  This matches
        the default behavior of the built-in `open` when no ``mode``
        argument is provided.

        When ``'binary'``, returns a file-like object where its ``read``
        method returns `bytes` objects.

        When another string, it is the name of an encoding, and the
        file-like object's ``read`` method will return `str` (``unicode``)
        objects, decoded from binary using the given encoding.

    cache : bool, optional
        Whether to cache the contents of remote URLs.

    show_progress : bool, optional
        Whether to display a progress bar if the file is downloaded
        from a remote server.  Default is `True`.

    remote_timeout : float
        Timeout for remote requests in seconds (default is the configurable
        `astropy.utils.data.Conf.remote_timeout`, which is 3s by default)

    Returns
    -------
    file : readable file-like object
    t   cachet   show_progresst   timeoutu   rbu   ru   seeki   i    i   s   Nt   fileobjt   modei   t   BZhu`   .bz2 format files are not supported since the Python interpreter does not include the bz2 moduleu   wbt   deletes   7z(   t   lzma(   t   LZMAFileu   .xz format files are not supported since the Python interpreter does not include the lzma module. On Python versions < 3.3 consider installing backports.lzmau   binaryt   encoding(   i   i   i    (0   R   t   string_typest   HAS_PATHLIBt   pathlibt   Patht   Nonet   confR   t
   isinstancet   strR$   t   download_filet   PY2t   opent   iot   FileIOt   appendt   hasattrt   BytesIOt   readt   seekt   structt   gzipt   GzipFilet   IOErrort   EOFErrort   closet   errort   bz2t   ImportErrort
   ValueErrorR   t   Falset   writet   BZ2Filet   namet   syst   version_infoR3   R4   t	   backportst   backports.lzmat   filet   filenot   BufferedReadert   TextIOWrapperR%   t   remove(   t   name_or_objR5   R,   R-   R   t
   PATH_TYPESt	   close_fdst
   delete_fdst   is_urlR/   t	   signatureRH   RI   t   fileobj_newRO   t   fdt   tmpR3   R4   t   et   needs_textio_wrappert   data(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   get_readable_fileobjv   s    A			
	
		
		c          O` s&   t  |  |    } | j   SWd QXd S(   u   
    Retrieves the contents of a filename or file-like object.

    See  the `get_readable_fileobj` docstring for details on parameters.

    Returns
    -------
    content
        The content of the file (as requested by ``encoding``).

    N(   Rk   RF   (   t   argst   kwargst   f(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   get_file_contentso  s    c   	      c` s)  t  |  d | } t j j |  r3 t d   n t j j |  rh t | d |  } | VWd QXn t j t j	 f } x | D]i } yI t | |  d | d | ' } | j
 d  | j d  | VPWd QXWq t j j k
 r q Xq Wd j d	   | D  } t j j d
 j |  |    d S(   uJ  
    Retrieves a data file from the standard locations for the package and
    provides the file as a file-like object that reads bytes.

    Parameters
    ----------
    data_name : str
        Name/location of the desired data file.  One of the following:

            * The name of a data file included in the source
              distribution.  The path is relative to the module
              calling this function.  For example, if calling from
              ``astropy.pkname``, use ``'data/file.dat'`` to get the
              file in ``astropy/pkgname/data/file.dat``.  Double-dots
              can be used to go up a level.  In the same example, use
              ``'../data/file.dat'`` to get ``astropy/data/file.dat``.
            * If a matching local file does not exist, the Astropy
              data server will be queried for the file.
            * A hash like that produced by `compute_hash` can be
              requested, prefixed by 'hash/'
              e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'.  The hash
              will first be searched for locally, and if not found,
              the Astropy data server will be queried.

    package : str, optional
        If specified, look for a file relative to the given package, rather
        than the default of looking relative to the calling module's package.

    encoding : str, optional
        When `None` (default), returns a file-like object with a
        ``read`` method that on Python 2.x returns `bytes` objects and
        on Python 3.x returns `str` (``unicode``) objects, using
        `locale.getpreferredencoding` as an encoding.  This matches
        the default behavior of the built-in `open` when no ``mode``
        argument is provided.

        When ``'binary'``, returns a file-like object where its ``read``
        method returns `bytes` objects.

        When another string, it is the name of an encoding, and the
        file-like object's ``read`` method will return `str` (``unicode``)
        objects, decoded from binary using the given encoding.

    cache : bool
        If True, the file will be downloaded and saved locally or the
        already-cached local copy will be accessed. If False, the
        file-like object will directly access the resource (e.g. if a
        remote URL is accessed, an object like that from
        `urllib2.urlopen` on Python 2 or `urllib.request.urlopen` on
        Python 3 is returned).

    Returns
    -------
    fileobj : file-like
        An object with the contents of the data file available via
        ``read`` function.  Can be used as part of a ``with`` statement,
        automatically closing itself after the ``with`` block.

    Raises
    ------
    urllib2.URLError, urllib.error.URLError
        If a remote file cannot be found.
    IOError
        If problems occur writing or reading a local file.

    Examples
    --------

    This will retrieve a data file and its contents for the `astropy.wcs`
    tests::

        >>> from astropy.utils.data import get_pkg_data_fileobj
        >>> with get_pkg_data_fileobj('data/3d_cd.hdr',
        ...                           package='astropy.wcs.tests') as fobj:
        ...     fcontents = fobj.read()
        ...

    This next example would download a data file from the astropy data server
    because the ``allsky/allsky_rosat.fits`` file is not present in the
    source distribution.  It will also save the file locally so the
    next time it is accessed it won't need to be downloaded.::

        >>> from astropy.utils.data import get_pkg_data_fileobj
        >>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits',
        ...                           encoding='binary') as fobj:  # doctest: +REMOTE_DATA
        ...     fcontents = fobj.read()
        ...
        Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done]

    This does the same thing but does *not* cache it locally::

        >>> with get_pkg_data_fileobj('allsky/allsky_rosat.fits',
        ...                           encoding='binary', cache=False) as fobj:  # doctest: +REMOTE_DATA
        ...     fcontents = fobj.read()
        ...
        Downloading http://data.astropy.org/allsky/allsky_rosat.fits [Done]

    See Also
    --------
    get_pkg_data_contents : returns the contents of a file or url as a bytes object
    get_pkg_data_filename : returns a local name for a file containing the data
    t   packageuD   Tried to access a data file that's actually a package data directoryR5   NR,   i   i    u   
c         s` s   |  ] } d  j  |  Vq d S(   u     - {0}N(   t   format(   t   .0R#   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pys	   <genexpr>  s    u<   Failed to download {0} from the following repositories:

{1}(   t   _find_pkg_data_pathR%   R&   t   isdirRK   t   isfileRk   R;   R   R   RF   RG   R   RN   t   URLErrort   joinRq   (	   t	   data_nameRp   R5   R,   t   datafnR/   t   all_urlsR#   t   urls(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   get_pkg_data_fileobj  s(    ic   
   	   C` s  | d k r t j } n  |  j d  r t |  d  } | d k r t j t j f } xL | D]D } y$ t | |  d t d | d | SWq\ t	 j
 j k
 r q\ Xq\ Wd j d   | D  } t	 j
 j d j |  |    q| Sn t j j |   } t | d	 | }	 t j j |	  r*t d
   n t j j |	  r@|	 St j t j f } xL | D]D } y$ t | |  d t d | d | SWqYt	 j
 j k
 rqYXqYWd j d   | D  } t	 j
 j d j |  |    d S(   uA  
    Retrieves a data file from the standard locations for the package and
    provides a local filename for the data.

    This function is similar to `get_pkg_data_fileobj` but returns the
    file *name* instead of a readable file-like object.  This means
    that this function must always cache remote files locally, unlike
    `get_pkg_data_fileobj`.

    Parameters
    ----------
    data_name : str
        Name/location of the desired data file.  One of the following:

            * The name of a data file included in the source
              distribution.  The path is relative to the module
              calling this function.  For example, if calling from
              ``astropy.pkname``, use ``'data/file.dat'`` to get the
              file in ``astropy/pkgname/data/file.dat``.  Double-dots
              can be used to go up a level.  In the same example, use
              ``'../data/file.dat'`` to get ``astropy/data/file.dat``.
            * If a matching local file does not exist, the Astropy
              data server will be queried for the file.
            * A hash like that produced by `compute_hash` can be
              requested, prefixed by 'hash/'
              e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'.  The hash
              will first be searched for locally, and if not found,
              the Astropy data server will be queried.

    package : str, optional
        If specified, look for a file relative to the given package, rather
        than the default of looking relative to the calling module's package.

    show_progress : bool, optional
        Whether to display a progress bar if the file is downloaded
        from a remote server.  Default is `True`.

    remote_timeout : float
        Timeout for the requests in seconds (default is the
        configurable `astropy.utils.data.Conf.remote_timeout`, which
        is 3s by default)

    Raises
    ------
    urllib2.URLError, urllib.error.URLError
        If a remote file cannot be found.
    IOError
        If problems occur writing or reading a local file.

    Returns
    -------
    filename : str
        A file path on the local file system corresponding to the data
        requested in ``data_name``.

    Examples
    --------

    This will retrieve the contents of the data file for the `astropy.wcs`
    tests::

        >>> from astropy.utils.data import get_pkg_data_filename
        >>> fn = get_pkg_data_filename('data/3d_cd.hdr',
        ...                            package='astropy.wcs.tests')
        >>> with open(fn) as f:
        ...     fcontents = f.read()
        ...

    This retrieves a data file by hash either locally or from the astropy data
    server::

        >>> from astropy.utils.data import get_pkg_data_filename
        >>> fn = get_pkg_data_filename('hash/34c33b3eb0d56eb9462003af249eff28')  # doctest: +SKIP
        >>> with open(fn) as f:
        ...     fcontents = f.read()
        ...

    See Also
    --------
    get_pkg_data_contents : returns the contents of a file or url as a bytes object
    get_pkg_data_fileobj : returns a file-like object with the data
    u   hash/i   R,   R-   R.   u   
c         s` s   |  ] } d  j  |  Vq d S(   u     - {0}N(   Rq   (   Rr   R#   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pys	   <genexpr>h  s    u>   Failed to download {0} from the following repositories:

{1}

Rp   uD   Tried to access a data file that's actually a package data directoryc         s` s   |  ] } d  j  |  Vq d S(   u     - {0}N(   Rq   (   Rr   R#   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pys	   <genexpr>  s    u<   Failed to download {0} from the following repositories:

{1}N(   R:   R;   R   R(   t   _find_hash_fnR   R   R>   R   R   RN   Rv   Rw   Rq   R%   R&   t   normpathRs   Rt   RK   Ru   (
   Rx   Rp   R-   R   t   hashfnRz   R#   R{   t   fs_pathRy   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   get_pkg_data_filename  sD    Uc         C` s7   t  |  d | d | d |  } | j   } Wd QX| S(   ub  
    Retrieves a data file from the standard locations and returns its
    contents as a bytes object.

    Parameters
    ----------
    data_name : str
        Name/location of the desired data file.  One of the following:

            * The name of a data file included in the source
              distribution.  The path is relative to the module
              calling this function.  For example, if calling from
              ``astropy.pkname``, use ``'data/file.dat'`` to get the
              file in ``astropy/pkgname/data/file.dat``.  Double-dots
              can be used to go up a level.  In the same example, use
              ``'../data/file.dat'`` to get ``astropy/data/file.dat``.
            * If a matching local file does not exist, the Astropy
              data server will be queried for the file.
            * A hash like that produced by `compute_hash` can be
              requested, prefixed by 'hash/'
              e.g. 'hash/34c33b3eb0d56eb9462003af249eff28'.  The hash
              will first be searched for locally, and if not found,
              the Astropy data server will be queried.
            * A URL to some other file.

    package : str, optional
        If specified, look for a file relative to the given package, rather
        than the default of looking relative to the calling module's package.


    encoding : str, optional
        When `None` (default), returns a file-like object with a
        ``read`` method that on Python 2.x returns `bytes` objects and
        on Python 3.x returns `str` (``unicode``) objects, using
        `locale.getpreferredencoding` as an encoding.  This matches
        the default behavior of the built-in `open` when no ``mode``
        argument is provided.

        When ``'binary'``, returns a file-like object where its ``read``
        method returns `bytes` objects.

        When another string, it is the name of an encoding, and the
        file-like object's ``read`` method will return `str` (``unicode``)
        objects, decoded from binary using the given encoding.

    cache : bool
        If True, the file will be downloaded and saved locally or the
        already-cached local copy will be accessed. If False, the
        file-like object will directly access the resource (e.g. if a
        remote URL is accessed, an object like that from
        `urllib2.urlopen` on Python 2 or `urllib.request.urlopen` on
        Python 3 is returned).

    Returns
    -------
    contents : bytes
        The complete contents of the file as a bytes object.

    Raises
    ------
    urllib2.URLError, urllib.error.URLError
        If a remote file cannot be found.
    IOError
        If problems occur writing or reading a local file.

    See Also
    --------
    get_pkg_data_fileobj : returns a file-like object with the data
    get_pkg_data_filename : returns a local name for a file containing the data
    Rp   R5   R,   N(   R|   RF   (   Rx   Rp   R5   R,   Rf   t   contents(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   get_pkg_data_contents  s    Hu   *c         c` s   t  |  d | } t j j |  r3 t d   nd t j j |  r xO t j |  D]/ } t j | |  rU t j j | |  VqU qU Wn t d   d S(   u  
    Returns the path of all of the data files in a given directory
    that match a given glob pattern.

    Parameters
    ----------
    datadir : str
        Name/location of the desired data files.  One of the following:

            * The name of a directory included in the source
              distribution.  The path is relative to the module
              calling this function.  For example, if calling from
              ``astropy.pkname``, use ``'data'`` to get the
              files in ``astropy/pkgname/data``.
            * Remote URLs are not currently supported.

    package : str, optional
        If specified, look for a file relative to the given package, rather
        than the default of looking relative to the calling module's package.

    pattern : str, optional
        A UNIX-style filename glob pattern to match files.  See the
        `glob` module in the standard library for more information.
        By default, matches all files.

    Returns
    -------
    filenames : iterator of str
        Paths on the local filesystem in *datadir* matching *pattern*.

    Examples
    --------
    This will retrieve the contents of the data file for the `astropy.wcs`
    tests::

        >>> from astropy.utils.data import get_pkg_data_filenames
        >>> for fn in get_pkg_data_filenames('maps', 'astropy.wcs.tests',
        ...                                  '*.hdr'):
        ...     with open(fn) as f:
        ...         fcontents = f.read()
        ...
    Rp   uD   Tried to access a data directory that's actually a package data fileu   Path not foundN(	   Rs   R%   R&   Ru   RK   Rt   t   listdirt   fnmatchRw   (   t   datadirRp   t   patternR&   t   filename(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   get_pkg_data_filenames  s    ,c         c` sG   x@ t  |  d | d | D]& } t | d |  } | VWd QXq Wd S(   u  
    Returns readable file objects for all of the data files in a given
    directory that match a given glob pattern.

    Parameters
    ----------
    datadir : str
        Name/location of the desired data files.  One of the following:

            * The name of a directory included in the source
              distribution.  The path is relative to the module
              calling this function.  For example, if calling from
              ``astropy.pkname``, use ``'data'`` to get the
              files in ``astropy/pkgname/data``
            * Remote URLs are not currently supported

    package : str, optional
        If specified, look for a file relative to the given package, rather
        than the default of looking relative to the calling module's package.

    pattern : str, optional
        A UNIX-style filename glob pattern to match files.  See the
        `glob` module in the standard library for more information.
        By default, matches all files.

    encoding : str, optional
        When `None` (default), returns a file-like object with a
        ``read`` method that on Python 2.x returns `bytes` objects and
        on Python 3.x returns `str` (``unicode``) objects, using
        `locale.getpreferredencoding` as an encoding.  This matches
        the default behavior of the built-in `open` when no ``mode``
        argument is provided.

        When ``'binary'``, returns a file-like object where its ``read``
        method returns `bytes` objects.

        When another string, it is the name of an encoding, and the
        file-like object's ``read`` method will return `str` (``unicode``)
        objects, decoded from binary using the given encoding.

    Returns
    -------
    fileobjs : iterator of file objects
        File objects for each of the files on the local filesystem in
        *datadir* matching *pattern*.

    Examples
    --------
    This will retrieve the contents of the data file for the `astropy.wcs`
    tests::

        >>> from astropy.utils.data import get_pkg_data_filenames
        >>> for fd in get_pkg_data_fileobjs('maps', 'astropy.wcs.tests',
        ...                                 '*.hdr'):
        ...     fcontents = fd.read()
        ...
    Rp   R   R5   N(   R   Rk   (   R   Rp   R   R5   t   fnRf   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   get_pkg_data_fileobjs  s    ;c         C` sl   t  |  d  Q } t j   } | j t j  } x) | r[ | j |  | j t j  } q3 WWd QX| j   S(   ug   Computes the MD5 hash for a file.

    The hash for a data file is used for looking up data files in a unique
    fashion. This is of particular use for tests; a test may require a
    particular version of a particular file, in which case it can be accessed
    via hash to get the appropriate version.

    Typically, if you wish to write a test that requires a particular data
    file, you will want to submit that file to the astropy data servers, and
    use
    e.g. ``get_pkg_data_filename('hash/34c33b3eb0d56eb9462003af249eff28')``,
    but with the hash for your file in place of the hash in the example.

    Parameters
    ----------
    localfn : str
        The path to the file for which the hash should be generated.

    Returns
    -------
    md5hash : str
        The hex digest of the MD5 hash for the contents of the ``localfn``
        file.

    u   rbN(   R@   t   hashlibt   md5RF   R;   R   t   updatet	   hexdigest(   t   localfnRn   t   ht   block(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   compute_hashL  s    	c         C` s#  | d	 k r t d d d d g } | d	 k r4 |  St | d  sN | j r d | j k rv | j j d  d } q | j } q | j } n t |  } | j d  d } t |  } t j	 j
 | j  } t j	 j | |   } t j	 j
 | j  } t | |  st d j |    n  | S(
   uX   
    Look for data in the source-included data directories and return the
    path.
    i   t   finddiffu   astropy.utils.datau
   contextlibu   __package__u   .i    u:   attempted to get a local data file outside of the {} tree.N(   R:   R   RD   t   __package__R   t
   rpartitionR   t	   partitionR%   R&   t   dirnamet   __file__Rw   R+   t   RuntimeErrorRq   (   Rx   Rp   t   modulet   rootpkgnamet   rootpkgt   module_pathR&   t   root_dir(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyRs   q  s&    	c         C` s   y t    \ } } Wn: t t f k
 rO } d } t t | t |    d SXt j j	 | |   } t j j
 |  r{ | Sd Sd S(   us   
    Looks for a local file by hash - returns file name if found and a valid
    file, otherwise returns None.
    u:   Could not access cache directory to search for data file: N(   t   _get_download_cache_locsRK   t   OSErrorR	   R   R=   R:   R%   R&   Rw   Ru   (   t   hasht   dldirt   urlmapfnRh   t   msgR   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyR}     s    c         C` s   t  j j d  r d d l } | j d  } | j j j | j |   d d | j
 |   } | d k r t d j |     n  | j St j |   } | j | j Sd S(   u5  
    Given a path to a directory, returns the amount of free space (in
    bytes) on that filesystem.

    Parameters
    ----------
    path : str
        The path to a directory

    Returns
    -------
    bytes : int
        The amount of free space on the partition that the directory
        is on.
    u   wini    Nu0   Checking free space on {!r} failed unexpectedly.(   RV   t   platformR(   t   ctypest   c_ulonglongt   windllt   kernel32t   GetDiskFreeSpaceExWt	   c_wchar_pR:   t   pointerRK   Rq   t   valueR%   t   statvfst   f_bavailt   f_frsize(   R&   R   t
   free_bytest   retvalt   stat(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   get_free_space_in_dir  s    $	c         C` sM   d d l  m } t |   } | | k  rI t d j |  | |     n  d S(   ug  
    Determines if a given directory has enough space to hold a file of
    a given size.  Raises an IOError if the file would be too large.

    Parameters
    ----------
    path : str
        The path to a directory

    size : int
        A proposed filesize (in bytes)

    Raises
    -------
    IOError : There is not enough room on the filesystem
    i   (   t   human_file_sizeu5   Not enough free space in '{0}' to download a {1} fileN(   t   utils.consoleR   R   RK   Rq   (   R&   t   sizeR   t   space(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   check_free_space_in_dir  s    c         C` sr  d d l  m } | d	 k r( t j } n  t } | r y t   \ } } Wq t t f k
 r } d }	 t	 | j
  d k  r d n d t |  }
 t t |	 | j j |
   t } t } q Xn  t j r t |  t j  r |  j d  } n |  } | j t j  rat j t k rat j t j j t j d |  # } t j | j   g t t j <Wd	 QXn  yV| r!t | t   } | | k r| | Sx t j  t j g   D]n } | j |  r| j! | t j"  } t j rt | t j  r| j d  } n  | | k r| | SqqWWd	 QXn  t j t j j |  d |  } t# j$   } | j%   } d
 | k ry t& | d
  } Wqt' k
 rd	 } qXn d	 } | d	 k	 rt( t)   |  | rt( | |  qn  | rt* j+ } n t, j-   } d j. |   } | | | d |  } t/ d t   } yr d } | j0 t j1  } xS | r| j2 |  | j3 |  | t	 |  7} | j3 |  | j0 t j1  } qJWWn< t4 k
 rt5 j6 j7 | j8  rt5 j9 | j8  n    n XWd	 QXWd	 QXWd	 QX| rrt:   zh t | t  S } | | k r%| | St5 j6 j; | | j<    } t= j> | j8 |  | | | <Wd	 QXWd	 t?   XnD | j8 } | rd }	 t t |	 |   n  t j@ rtA jB |  n  Wn t jC jD k
 rF} tE | d  r=tE | jF d  r=| jF jG d k r=| jF jH d |  | jF _H | jF jG | jF jH f | jF _
 n  |  n( tI jJ k
 rm} t jC jD |   n X| S(   um  
    Accepts a URL, downloads and optionally caches the result
    returning the filename, with a name determined by the file's MD5
    hash. If ``cache=True`` and the file is present in the cache, just
    returns the filename.

    Parameters
    ----------
    remote_url : str
        The URL of the file to download

    cache : bool, optional
        Whether to use the cache

    show_progress : bool, optional
        Whether to display a progress bar during the download (default
        is `True`)

    timeout : float, optional
        The timeout, in seconds.  Otherwise, use
        `astropy.utils.data.Conf.remote_timeout`.

    Returns
    -------
    local_path : str
        Returns the local path that the file was download to.

    Raises
    ------
    urllib2.URLError, urllib.error.URLError
        Whenever there's a problem getting the remote file.
    i   (   t   ProgressBarOrSpinneru/   Remote data cache could not be accessed due to i   u    u   : u   utf-8R.   Nu   Content-Lengthu   Downloading {0}RZ   R2   i    ua   File downloaded to temporary location due to problem with cache directory and will not be cached.u   reasonu   errnoi   u   . requested URL: (K   R   R   R:   R;   R   RR   R   RK   R   t   lenRl   R=   R	   R   t	   __class__R   R   R   R?   R<   t	   text_typet   encodeR(   R   t   _dataurls_to_aliast
   contextlibt   closingR   t   requestt   urlopent   geturlt   _open_shelvet   gett   replaceR   R   R   t   infot   intRQ   R   R   RV   t   stdoutRA   t   StringIORq   R   RF   R   RS   R   t   BaseExceptionR%   R&   t   existsRU   R^   t   _acquire_download_cache_lockRw   R   t   shutilt   movet   _release_download_cache_lockR   t   _tempfilestodelRC   RN   Rv   RD   t   reasont   errnot   strerrort   socketR.   (   t
   remote_urlR,   R-   R.   R   t   missing_cacheR   R   Rh   R   t   estrt   url_keyt   remotet   url2hasht   cur_urlt
   url_mirrorR   R   R   t   progress_streamt   dlmsgt   pRn   t
   bytes_readR   t
   local_path(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyR>     s    "+%				3!	c         C` s   y t    \ } } Wni t t f k
 r~ } d } t | j  d k  rL d n d t |  } t t | | j j	 |   t
 SXt j r t |  t j  r |  j d  }  n  t | t   } |  | k r t SWd QXt
 S(   u   
    Check if a download from ``url_key`` is in the cache.

    Parameters
    ----------
    url_key : string
        The URL retrieved

    Returns
    -------
    in_cache : bool
        `True` if a download from ``url_key`` is in the cache
    u/   Remote data cache could not be accessed due to i   u    u   : u   utf-8N(   R   RK   R   R   Rl   R=   R	   R   R   R   RR   R   R?   R<   R   R   R   R   (   R   R   R   Rh   R   R   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   is_url_in_cache  s    +
c         C` s
   t  |    S(   N(   R>   (   Rl   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   _do_download_files_in_parallel  s    c         C` s   d d l  m } | d k r( t j } n  | r: t j } n t j   } t	 t
 |    } | j t g  | D] } | | t | f ^ qh d | d t } g  }	 x( |  D]  }
 |	 j | | j |
   q W|	 S(   u  
    Downloads multiple files in parallel from the given URLs.  Blocks until
    all files have downloaded.  The result is a list of local file paths
    corresponding to the given urls.

    Parameters
    ----------
    urls : list of str
        The URLs to retrieve.

    cache : bool, optional
        Whether to use the cache

    show_progress : bool, optional
        Whether to display a progress bar during the download (default
        is `True`)

    timeout : float, optional
        Timeout for each individual requests in seconds (default is the
        configurable `astropy.utils.data.Conf.remote_timeout`).

    Returns
    -------
    paths : list of str
        The local file paths corresponding to the downloaded URLs.
    i   (   t   ProgressBarRZ   t   multiprocessN(   t   consoleR   R:   R;   R   RV   R   RA   RE   t   listt   sett   mapR   RR   R   RC   t   index(   R{   R,   R-   R.   R   t   progresst   combined_urlst   xt   combined_pathst   pathsR#   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   download_files_in_parallel  s     %	c          C` sZ   t  d  k	 rV xG t t   d k rR t  j   }  t j j |   r t j |   q q Wn  d  S(   Ni    (   R   R:   R   t   popR%   R&   Ru   R^   (   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt	   _deltemps  s
    c         C` s  y t    \ } } Wni t t f k
 r~ } d } t | j  d k  rL d n d t |  } t t | | j j	 |   d SXt
   zM|  d k r t j j |  rt j |  qnt | t  } t j j | |   } t | |  s t d   n  t j r,t |  t j  r,|  j d  } n |  } t j j |  rx3 t j |  D]" \ }	 }
 |
 | k rT| |	 =qTqTWt j |  nB | | k r| | } | | =t j j |  rt j |  qn  Wd QXWd t j j t j j | d   rt   n  Xd S(	   uJ   Clears the data file cache by deleting the local file(s).

    Parameters
    ----------
    hashorurl : str or None
        If None, the whole cache is cleared.  Otherwise, either specifies a
        hash for the cached file that is supposed to be deleted, or a URL that
        should be removed from the cache if present.
    u3   Not clearing data cache - cache inacessable due to i   u    u   : NuP   attempted to use clear_download_cache on a path outside the data cache directoryu   utf-8u   lock(   R   RK   R   R   Rl   R=   R	   R   R   R   R   R:   R%   R&   R   R   t   rmtreeR   R   Rw   R+   R   R   R?   R<   R   R   t	   iteritemst   unlinkR   (   t	   hashorurlR   R   Rh   R   R   R   t   filepatht   hash_keyt   kt   v(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   clear_download_cache  s>    +
!c          C` s  d d l  m }  d t t j j  } t j j |    d |  } t j j | d  } t j j	 |  s y t j
 |  Wq t k
 r } t j j	 |  s   q q Xn0 t j j |  s d } t | j |    n  t j j |  r
d } t | j |    n  | | f S(   u   Finds the path to the data cache directory and makes them if
    they don't exist.

    Returns
    -------
    datadir : str
        The path to the data cache directory.
    shelveloc : str
        The path to the shelve object that stores the cache info.
    i   (   t   get_cache_diru   pyu   downloadu   urlmapu+   Data cache directory {0} is not a directoryu4   Data cache shelve object location {0} is a directory(   t   config.pathsR   R=   RV   RW   t   majorR%   R&   Rw   R   t   makedirsR   Rt   RK   Rq   (   R   t
   py_versionR   t	   shelvelocRh   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyR   -  s"    c         C` s<   d d l  } | j |  d d } | r4 t j |  S| Sd S(   u   
    Opens a shelf file.  If `withclosing` is  True, it will be opened with closing,
    allowing use like:

        with _open_shelve('somefile',True) as s:
            ...
    i    Nt   protocoli   (   t   shelveR@   R   R   (   t   shelffnt   withclosingR  t   shelf(    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyR   T  s
    c          C` s   t  j j t   d d  }  x t t j  D]| } yQ t  j |   t t  j j |  d  d    } | j	 t
 t  j     Wd QXWn t k
 r t j d  q, Xd Sq, Wd } t | j |     d S(   u   
    Uses the lock directory method.  This is good because `mkdir` is
    atomic at the system call level, so it's thread-safe.
    i    u   locku   pidu   wNi   u   Unable to acquire lock for cache directory ({0} exists). You may need to delete the lock if the python interpreter wasn't shut down properly.(   R%   R&   Rw   R   R   R;   R   t   mkdirR@   RS   R=   t   getpidR   t   timet   sleepR   Rq   (   t   lockdirt   iRn   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyR   h  s    !#c          C` s   t  j j t   d d  }  t  j j |   ru t  j j |  d  } t  j j |  re t  j |  n  t  j |   n d d } t | j	 |     d  S(   Ni    u   locku   pidu<   Error releasing lock. "{0}" either does not exist or is not u   a directory.(
   R%   R&   Rw   R   Rt   R   R^   t   rmdirR   Rq   (   R  t   pidfnR   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyR     s    c          C` s   y t    \ }  } Wni t t f k
 r~ } d } t | j  d k  rL d n d t |  } t t | | j j	 |   t
 SXt | t   } t | j    SWd QXd S(   u   
    Get the list of URLs in the cache. Especially useful for looking up what
    files are stored in your cache when you don't have internet access.

    Returns
    -------
    cached_urls : list
        List of cached URLs.
    u/   Remote data cache could not be accessed due to i   u    u   : N(   R   RK   R   R   Rl   R=   R	   R   R   R   RR   R   R   R   t   keys(   R   R   Rh   R   R   R   (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   get_cached_urls  s    +(J   R   t
   __future__R    R   R   R   t   externR   t   extern.six.movesR   R   t   atexitR   R   R   R%   RA   R   R   RV   R  t   tempfileR   R   t   warningsR	   t    R
   R   t   utils.exceptionsR   t   utils.introspectionR   R   R8   RP   RR   R7   R   t   __all__R   t   ConfigNamespaceR   R;   R   R$   R+   t   contextmanagerR:   Rk   Ro   R|   R   R   R   R   R   Rs   R}   R   R   R>   R   R   R   R   t   registerR   R   R   R   R   R   R  (    (    (    s1   lib/python2.7/site-packages/astropy/utils/data.pyt   <module>   s   "
							N9A	%(				!	4=	'		