<commit_before>import os
import uuid
import json
from hashlib import sha256
from itertools import chain
from collections import OrderedDict, defaultdict
import threading
from tempfile import NamedTemporaryFile
try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

try:
    from functools import lru_cache # python 3
except ImportError:
    from cachtools.func import lru_cache

import rasterio
import pycurl
import numpy as np

import gbdxtools as gbdx
from gbdxtools.ipe.util import IPE_TO_DTYPE
from gbdxtools.ipe.graph import VIRTUAL_IPE_URL, register_ipe_graph, get_ipe_metadata
from gbdxtools.images.meta import DaskMeta
from gbdxtools.auth import Auth

import warnings
warnings.filterwarnings('ignore')

_curl_pool = defaultdict(pycurl.Curl)
MAX_RETRIES = 5
try:
    basestring
except NameError:
    basestring = str

try:
    xrange
except NameError:
    xrange = range

NAMESPACE_UUID = uuid.NAMESPACE_DNS


@lru_cache(maxsize=128)
def load_url(url, token, shape=(8, 256, 256)):
    """ Loads a geotiff url inside a thread and returns as an ndarray """
    # print("calling load_url ({})".format(url))
    _, ext = os.path.splitext(urlparse(url).path)
    success = False
    for i in xrange(MAX_RETRIES):
        thread_id = threading.current_thread().ident
        _curl = _curl_pool[thread_id]
        _curl.setopt(_curl.URL, url)
        _curl.setopt(pycurl.NOSIGNAL, 1)
        _curl.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer {}'.format(token)])
        with NamedTemporaryFile(prefix="gbdxtools", suffix=ext, delete=False) as temp: # TODO: apply correct file extension
            _curl.setopt(_curl.WRITEDATA, temp.file)
            _curl.perform()
            code = _curl.getinfo(pycurl.HTTP_CODE)
            try:
                if(code != 200):
                    raise TypeError("Request for {} returned unexpected error code: {}".format(url, code))
                temp.file.flush()
                temp.close()
                with rasterio.open(temp.name) as dataset:
                    arr = dataset.read()
                success = True
                return arr
            except (TypeError, rasterio.RasterioIOError) as e:
                print(e)
                temp.seek(0)
                _curl.close()
                del _curl_pool[thread_id]
            finally:
                temp.close()
                os.remove(temp.name)

    if success is False:
        arr = np.zeros(shape, dtype=np.float32)
    return arr<commit_msg>seek to 0 not needed if the data is not printed<commit_after>import os
import uuid
import json
from hashlib import sha256
from itertools import chain
from collections import OrderedDict, defaultdict
import threading
from tempfile import NamedTemporaryFile
try:
    from urlparse import urlparse
except ImportError:
    from urllib.parse import urlparse

try:
    from functools import lru_cache # python 3
except ImportError:
    from cachtools.func import lru_cache

import rasterio
import pycurl
import numpy as np

import gbdxtools as gbdx
from gbdxtools.ipe.util import IPE_TO_DTYPE
from gbdxtools.ipe.graph import VIRTUAL_IPE_URL, register_ipe_graph, get_ipe_metadata
from gbdxtools.images.meta import DaskMeta
from gbdxtools.auth import Auth

import warnings
warnings.filterwarnings('ignore')

_curl_pool = defaultdict(pycurl.Curl)
MAX_RETRIES = 5
try:
    basestring
except NameError:
    basestring = str

try:
    xrange
except NameError:
    xrange = range

NAMESPACE_UUID = uuid.NAMESPACE_DNS


@lru_cache(maxsize=128)
def load_url(url, token, shape=(8, 256, 256)):
    """ Loads a geotiff url inside a thread and returns as an ndarray """
    # print("calling load_url ({})".format(url))
    _, ext = os.path.splitext(urlparse(url).path)
    success = False
    for i in xrange(MAX_RETRIES):
        thread_id = threading.current_thread().ident
        _curl = _curl_pool[thread_id]
        _curl.setopt(_curl.URL, url)
        _curl.setopt(pycurl.NOSIGNAL, 1)
        _curl.setopt(pycurl.HTTPHEADER, ['Authorization: Bearer {}'.format(token)])
        with NamedTemporaryFile(prefix="gbdxtools", suffix=ext, delete=False) as temp: # TODO: apply correct file extension
            _curl.setopt(_curl.WRITEDATA, temp.file)
            _curl.perform()
            code = _curl.getinfo(pycurl.HTTP_CODE)
            try:
                if(code != 200):
                    raise TypeError("Request for {} returned unexpected error code: {}".format(url, code))
                temp.file.flush()
                temp.close()
                with rasterio.open(temp.name) as dataset:
                    arr = dataset.read()
                success = True
                return arr
            except (TypeError, rasterio.RasterioIOError) as e:
                print(e)
                _curl.close()
                del _curl_pool[thread_id]
            finally:
                temp.close()
                os.remove(temp.name)

    if success is False:
        arr = np.zeros(shape, dtype=np.float32)
    return arr
{'fraction_non_alphanumeric': 0.08225966303270565, 'fraction_numerical': 0.008721506442021803, 'mean_word_length': 2.622397702799713, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 3, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2236008', 'n_tokens_mistral': 1625, 'n_tokens_neox': 1530, 'n_words': 416}