id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
229,200
sentinel-hub/sentinelhub-py
sentinelhub/data_request.py
get_safe_format
def get_safe_format(product_id=None, tile=None, entire_product=False, bands=None, data_source=DataSource.SENTINEL2_L1C): """ Returns .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified. :param product_id: original ESA product identification string. Default is ``None`` :type product_id: str :param tile: tuple containing tile name and sensing time/date. Default is ``None`` :type tile: (str, str) :param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure of the product. Default is ``False`` :type entire_product: bool :param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None`` :type bands: list(str) or None :param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2 L1C data. :type data_source: constants.DataSource :return: Nested dictionaries representing .SAFE structure. :rtype: dict """ entire_product = entire_product and product_id is None if tile is not None: safe_tile = SafeTile(tile_name=tile[0], time=tile[1], bands=bands, data_source=data_source) if not entire_product: return safe_tile.get_safe_struct() product_id = safe_tile.get_product_id() if product_id is None: raise ValueError('Either product_id or tile must be specified') safe_product = SafeProduct(product_id, tile_list=[tile[0]], bands=bands) if entire_product else \ SafeProduct(product_id, bands=bands) return safe_product.get_safe_struct()
python
def get_safe_format(product_id=None, tile=None, entire_product=False, bands=None, data_source=DataSource.SENTINEL2_L1C): """ Returns .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified. :param product_id: original ESA product identification string. Default is ``None`` :type product_id: str :param tile: tuple containing tile name and sensing time/date. Default is ``None`` :type tile: (str, str) :param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure of the product. Default is ``False`` :type entire_product: bool :param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None`` :type bands: list(str) or None :param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2 L1C data. :type data_source: constants.DataSource :return: Nested dictionaries representing .SAFE structure. :rtype: dict """ entire_product = entire_product and product_id is None if tile is not None: safe_tile = SafeTile(tile_name=tile[0], time=tile[1], bands=bands, data_source=data_source) if not entire_product: return safe_tile.get_safe_struct() product_id = safe_tile.get_product_id() if product_id is None: raise ValueError('Either product_id or tile must be specified') safe_product = SafeProduct(product_id, tile_list=[tile[0]], bands=bands) if entire_product else \ SafeProduct(product_id, bands=bands) return safe_product.get_safe_struct()
[ "def", "get_safe_format", "(", "product_id", "=", "None", ",", "tile", "=", "None", ",", "entire_product", "=", "False", ",", "bands", "=", "None", ",", "data_source", "=", "DataSource", ".", "SENTINEL2_L1C", ")", ":", "entire_product", "=", "entire_product", "and", "product_id", "is", "None", "if", "tile", "is", "not", "None", ":", "safe_tile", "=", "SafeTile", "(", "tile_name", "=", "tile", "[", "0", "]", ",", "time", "=", "tile", "[", "1", "]", ",", "bands", "=", "bands", ",", "data_source", "=", "data_source", ")", "if", "not", "entire_product", ":", "return", "safe_tile", ".", "get_safe_struct", "(", ")", "product_id", "=", "safe_tile", ".", "get_product_id", "(", ")", "if", "product_id", "is", "None", ":", "raise", "ValueError", "(", "'Either product_id or tile must be specified'", ")", "safe_product", "=", "SafeProduct", "(", "product_id", ",", "tile_list", "=", "[", "tile", "[", "0", "]", "]", ",", "bands", "=", "bands", ")", "if", "entire_product", "else", "SafeProduct", "(", "product_id", ",", "bands", "=", "bands", ")", "return", "safe_product", ".", "get_safe_struct", "(", ")" ]
Returns .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified. :param product_id: original ESA product identification string. Default is ``None`` :type product_id: str :param tile: tuple containing tile name and sensing time/date. Default is ``None`` :type tile: (str, str) :param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure of the product. Default is ``False`` :type entire_product: bool :param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None`` :type bands: list(str) or None :param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2 L1C data. :type data_source: constants.DataSource :return: Nested dictionaries representing .SAFE structure. :rtype: dict
[ "Returns", ".", "SAFE", "format", "structure", "in", "form", "of", "nested", "dictionaries", ".", "Either", "product_id", "or", "tile", "must", "be", "specified", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L862-L891
229,201
sentinel-hub/sentinelhub-py
sentinelhub/data_request.py
download_safe_format
def download_safe_format(product_id=None, tile=None, folder='.', redownload=False, entire_product=False, bands=None, data_source=DataSource.SENTINEL2_L1C): """ Downloads .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified. :param product_id: original ESA product identification string. Default is ``None`` :type product_id: str :param tile: tuple containing tile name and sensing time/date. Default is ``None`` :type tile: (str, str) :param folder: location of the directory where the fetched data will be saved. Default is ``'.'`` :type folder: str :param redownload: if ``True``, download again the requested data even though it's already saved to disk. If ``False``, do not download if data is already available on disk. Default is ``False`` :type redownload: bool :param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure of the product. Default is ``False`` :type entire_product: bool :param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None`` :type bands: list(str) or None :param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2 L1C data. :type data_source: constants.DataSource :return: Nested dictionaries representing .SAFE structure. :rtype: dict """ entire_product = entire_product and product_id is None if tile is not None: safe_request = AwsTileRequest(tile=tile[0], time=tile[1], data_folder=folder, bands=bands, safe_format=True, data_source=data_source) if entire_product: safe_tile = safe_request.get_aws_service() product_id = safe_tile.get_product_id() if product_id is not None: safe_request = AwsProductRequest(product_id, tile_list=[tile[0]], data_folder=folder, bands=bands, safe_format=True) if entire_product else \ AwsProductRequest(product_id, data_folder=folder, bands=bands, safe_format=True) safe_request.save_data(redownload=redownload)
python
def download_safe_format(product_id=None, tile=None, folder='.', redownload=False, entire_product=False, bands=None, data_source=DataSource.SENTINEL2_L1C): """ Downloads .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified. :param product_id: original ESA product identification string. Default is ``None`` :type product_id: str :param tile: tuple containing tile name and sensing time/date. Default is ``None`` :type tile: (str, str) :param folder: location of the directory where the fetched data will be saved. Default is ``'.'`` :type folder: str :param redownload: if ``True``, download again the requested data even though it's already saved to disk. If ``False``, do not download if data is already available on disk. Default is ``False`` :type redownload: bool :param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure of the product. Default is ``False`` :type entire_product: bool :param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None`` :type bands: list(str) or None :param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2 L1C data. :type data_source: constants.DataSource :return: Nested dictionaries representing .SAFE structure. :rtype: dict """ entire_product = entire_product and product_id is None if tile is not None: safe_request = AwsTileRequest(tile=tile[0], time=tile[1], data_folder=folder, bands=bands, safe_format=True, data_source=data_source) if entire_product: safe_tile = safe_request.get_aws_service() product_id = safe_tile.get_product_id() if product_id is not None: safe_request = AwsProductRequest(product_id, tile_list=[tile[0]], data_folder=folder, bands=bands, safe_format=True) if entire_product else \ AwsProductRequest(product_id, data_folder=folder, bands=bands, safe_format=True) safe_request.save_data(redownload=redownload)
[ "def", "download_safe_format", "(", "product_id", "=", "None", ",", "tile", "=", "None", ",", "folder", "=", "'.'", ",", "redownload", "=", "False", ",", "entire_product", "=", "False", ",", "bands", "=", "None", ",", "data_source", "=", "DataSource", ".", "SENTINEL2_L1C", ")", ":", "entire_product", "=", "entire_product", "and", "product_id", "is", "None", "if", "tile", "is", "not", "None", ":", "safe_request", "=", "AwsTileRequest", "(", "tile", "=", "tile", "[", "0", "]", ",", "time", "=", "tile", "[", "1", "]", ",", "data_folder", "=", "folder", ",", "bands", "=", "bands", ",", "safe_format", "=", "True", ",", "data_source", "=", "data_source", ")", "if", "entire_product", ":", "safe_tile", "=", "safe_request", ".", "get_aws_service", "(", ")", "product_id", "=", "safe_tile", ".", "get_product_id", "(", ")", "if", "product_id", "is", "not", "None", ":", "safe_request", "=", "AwsProductRequest", "(", "product_id", ",", "tile_list", "=", "[", "tile", "[", "0", "]", "]", ",", "data_folder", "=", "folder", ",", "bands", "=", "bands", ",", "safe_format", "=", "True", ")", "if", "entire_product", "else", "AwsProductRequest", "(", "product_id", ",", "data_folder", "=", "folder", ",", "bands", "=", "bands", ",", "safe_format", "=", "True", ")", "safe_request", ".", "save_data", "(", "redownload", "=", "redownload", ")" ]
Downloads .SAFE format structure in form of nested dictionaries. Either ``product_id`` or ``tile`` must be specified. :param product_id: original ESA product identification string. Default is ``None`` :type product_id: str :param tile: tuple containing tile name and sensing time/date. Default is ``None`` :type tile: (str, str) :param folder: location of the directory where the fetched data will be saved. Default is ``'.'`` :type folder: str :param redownload: if ``True``, download again the requested data even though it's already saved to disk. If ``False``, do not download if data is already available on disk. Default is ``False`` :type redownload: bool :param entire_product: in case tile is specified this flag determines if it will be place inside a .SAFE structure of the product. Default is ``False`` :type entire_product: bool :param bands: list of bands to download. If ``None`` all bands will be downloaded. Default is ``None`` :type bands: list(str) or None :param data_source: In case of tile request the source of satellite data has to be specified. Default is Sentinel-2 L1C data. :type data_source: constants.DataSource :return: Nested dictionaries representing .SAFE structure. :rtype: dict
[ "Downloads", ".", "SAFE", "format", "structure", "in", "form", "of", "nested", "dictionaries", ".", "Either", "product_id", "or", "tile", "must", "be", "specified", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L894-L932
229,202
sentinel-hub/sentinelhub-py
sentinelhub/data_request.py
DataRequest.save_data
def save_data(self, *, data_filter=None, redownload=False, max_threads=None, raise_download_errors=False): """ Saves data to disk. If ``redownload=True`` then the data is redownloaded using ``max_threads`` workers. :param data_filter: Used to specify which items will be returned by the method and in which order. E.g. with `data_filter=[0, 2, -1]` the method will return only 1st, 3rd and last item. Default filter is ``None``. :type data_filter: list(int) or None :param redownload: data is redownloaded if ``redownload=True``. Default is ``False`` :type redownload: bool :param max_threads: number of threads to use when downloading data; default is ``max_threads=None`` which by default uses the number of processors on the system :type max_threads: int :param raise_download_errors: If ``True`` any error in download process should be raised as ``DownloadFailedException``. If ``False`` failed downloads will only raise warnings. :type raise_download_errors: bool """ self._preprocess_request(True, False) self._execute_data_download(data_filter, redownload, max_threads, raise_download_errors)
python
def save_data(self, *, data_filter=None, redownload=False, max_threads=None, raise_download_errors=False): """ Saves data to disk. If ``redownload=True`` then the data is redownloaded using ``max_threads`` workers. :param data_filter: Used to specify which items will be returned by the method and in which order. E.g. with `data_filter=[0, 2, -1]` the method will return only 1st, 3rd and last item. Default filter is ``None``. :type data_filter: list(int) or None :param redownload: data is redownloaded if ``redownload=True``. Default is ``False`` :type redownload: bool :param max_threads: number of threads to use when downloading data; default is ``max_threads=None`` which by default uses the number of processors on the system :type max_threads: int :param raise_download_errors: If ``True`` any error in download process should be raised as ``DownloadFailedException``. If ``False`` failed downloads will only raise warnings. :type raise_download_errors: bool """ self._preprocess_request(True, False) self._execute_data_download(data_filter, redownload, max_threads, raise_download_errors)
[ "def", "save_data", "(", "self", ",", "*", ",", "data_filter", "=", "None", ",", "redownload", "=", "False", ",", "max_threads", "=", "None", ",", "raise_download_errors", "=", "False", ")", ":", "self", ".", "_preprocess_request", "(", "True", ",", "False", ")", "self", ".", "_execute_data_download", "(", "data_filter", ",", "redownload", ",", "max_threads", ",", "raise_download_errors", ")" ]
Saves data to disk. If ``redownload=True`` then the data is redownloaded using ``max_threads`` workers. :param data_filter: Used to specify which items will be returned by the method and in which order. E.g. with `data_filter=[0, 2, -1]` the method will return only 1st, 3rd and last item. Default filter is ``None``. :type data_filter: list(int) or None :param redownload: data is redownloaded if ``redownload=True``. Default is ``False`` :type redownload: bool :param max_threads: number of threads to use when downloading data; default is ``max_threads=None`` which by default uses the number of processors on the system :type max_threads: int :param raise_download_errors: If ``True`` any error in download process should be raised as ``DownloadFailedException``. If ``False`` failed downloads will only raise warnings. :type raise_download_errors: bool
[ "Saves", "data", "to", "disk", ".", "If", "redownload", "=", "True", "then", "the", "data", "is", "redownloaded", "using", "max_threads", "workers", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L113-L130
229,203
sentinel-hub/sentinelhub-py
sentinelhub/data_request.py
DataRequest._execute_data_download
def _execute_data_download(self, data_filter, redownload, max_threads, raise_download_errors): """Calls download module and executes the download process :param data_filter: Used to specify which items will be returned by the method and in which order. E.g. with `data_filter=[0, 2, -1]` the method will return only 1st, 3rd and last item. Default filter is ``None``. :type data_filter: list(int) or None :param redownload: data is redownloaded if ``redownload=True``. Default is ``False`` :type redownload: bool :param max_threads: the number of workers to use when downloading, default ``max_threads=None`` :type max_threads: int :param raise_download_errors: If ``True`` any error in download process should be raised as ``DownloadFailedException``. If ``False`` failed downloads will only raise warnings. :type raise_download_errors: bool :return: List of data obtained from download :rtype: list """ is_repeating_filter = False if data_filter is None: filtered_download_list = self.download_list elif isinstance(data_filter, (list, tuple)): try: filtered_download_list = [self.download_list[index] for index in data_filter] except IndexError: raise IndexError('Indices of data_filter are out of range') filtered_download_list, mapping_list = self._filter_repeating_items(filtered_download_list) is_repeating_filter = len(filtered_download_list) < len(mapping_list) else: raise ValueError('data_filter parameter must be a list of indices') data_list = [] for future in download_data(filtered_download_list, redownload=redownload, max_threads=max_threads): try: data_list.append(future.result(timeout=SHConfig().download_timeout_seconds)) except ImageDecodingError as err: data_list.append(None) LOGGER.debug('%s while downloading data; will try to load it from disk if it was saved', err) except DownloadFailedException as download_exception: if raise_download_errors: raise download_exception warnings.warn(str(download_exception)) data_list.append(None) if is_repeating_filter: data_list = [copy.deepcopy(data_list[index]) for index in mapping_list] return data_list
python
def _execute_data_download(self, data_filter, redownload, max_threads, raise_download_errors): """Calls download module and executes the download process :param data_filter: Used to specify which items will be returned by the method and in which order. E.g. with `data_filter=[0, 2, -1]` the method will return only 1st, 3rd and last item. Default filter is ``None``. :type data_filter: list(int) or None :param redownload: data is redownloaded if ``redownload=True``. Default is ``False`` :type redownload: bool :param max_threads: the number of workers to use when downloading, default ``max_threads=None`` :type max_threads: int :param raise_download_errors: If ``True`` any error in download process should be raised as ``DownloadFailedException``. If ``False`` failed downloads will only raise warnings. :type raise_download_errors: bool :return: List of data obtained from download :rtype: list """ is_repeating_filter = False if data_filter is None: filtered_download_list = self.download_list elif isinstance(data_filter, (list, tuple)): try: filtered_download_list = [self.download_list[index] for index in data_filter] except IndexError: raise IndexError('Indices of data_filter are out of range') filtered_download_list, mapping_list = self._filter_repeating_items(filtered_download_list) is_repeating_filter = len(filtered_download_list) < len(mapping_list) else: raise ValueError('data_filter parameter must be a list of indices') data_list = [] for future in download_data(filtered_download_list, redownload=redownload, max_threads=max_threads): try: data_list.append(future.result(timeout=SHConfig().download_timeout_seconds)) except ImageDecodingError as err: data_list.append(None) LOGGER.debug('%s while downloading data; will try to load it from disk if it was saved', err) except DownloadFailedException as download_exception: if raise_download_errors: raise download_exception warnings.warn(str(download_exception)) data_list.append(None) if is_repeating_filter: data_list = [copy.deepcopy(data_list[index]) for index in mapping_list] return data_list
[ "def", "_execute_data_download", "(", "self", ",", "data_filter", ",", "redownload", ",", "max_threads", ",", "raise_download_errors", ")", ":", "is_repeating_filter", "=", "False", "if", "data_filter", "is", "None", ":", "filtered_download_list", "=", "self", ".", "download_list", "elif", "isinstance", "(", "data_filter", ",", "(", "list", ",", "tuple", ")", ")", ":", "try", ":", "filtered_download_list", "=", "[", "self", ".", "download_list", "[", "index", "]", "for", "index", "in", "data_filter", "]", "except", "IndexError", ":", "raise", "IndexError", "(", "'Indices of data_filter are out of range'", ")", "filtered_download_list", ",", "mapping_list", "=", "self", ".", "_filter_repeating_items", "(", "filtered_download_list", ")", "is_repeating_filter", "=", "len", "(", "filtered_download_list", ")", "<", "len", "(", "mapping_list", ")", "else", ":", "raise", "ValueError", "(", "'data_filter parameter must be a list of indices'", ")", "data_list", "=", "[", "]", "for", "future", "in", "download_data", "(", "filtered_download_list", ",", "redownload", "=", "redownload", ",", "max_threads", "=", "max_threads", ")", ":", "try", ":", "data_list", ".", "append", "(", "future", ".", "result", "(", "timeout", "=", "SHConfig", "(", ")", ".", "download_timeout_seconds", ")", ")", "except", "ImageDecodingError", "as", "err", ":", "data_list", ".", "append", "(", "None", ")", "LOGGER", ".", "debug", "(", "'%s while downloading data; will try to load it from disk if it was saved'", ",", "err", ")", "except", "DownloadFailedException", "as", "download_exception", ":", "if", "raise_download_errors", ":", "raise", "download_exception", "warnings", ".", "warn", "(", "str", "(", "download_exception", ")", ")", "data_list", ".", "append", "(", "None", ")", "if", "is_repeating_filter", ":", "data_list", "=", "[", "copy", ".", "deepcopy", "(", "data_list", "[", "index", "]", ")", "for", "index", "in", "mapping_list", "]", "return", "data_list" ]
Calls download module and executes the download process :param data_filter: Used to specify which items will be returned by the method and in which order. E.g. with `data_filter=[0, 2, -1]` the method will return only 1st, 3rd and last item. Default filter is ``None``. :type data_filter: list(int) or None :param redownload: data is redownloaded if ``redownload=True``. Default is ``False`` :type redownload: bool :param max_threads: the number of workers to use when downloading, default ``max_threads=None`` :type max_threads: int :param raise_download_errors: If ``True`` any error in download process should be raised as ``DownloadFailedException``. If ``False`` failed downloads will only raise warnings. :type raise_download_errors: bool :return: List of data obtained from download :rtype: list
[ "Calls", "download", "module", "and", "executes", "the", "download", "process" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L132-L178
229,204
sentinel-hub/sentinelhub-py
sentinelhub/data_request.py
DataRequest._filter_repeating_items
def _filter_repeating_items(download_list): """ Because of data_filter some requests in download list might be the same. In order not to download them again this method will reduce the list of requests. It will also return a mapping list which can be used to reconstruct the previous list of download requests. :param download_list: List of download requests :type download_list: list(sentinelhub.DownloadRequest) :return: reduced download list with unique requests and mapping list :rtype: (list(sentinelhub.DownloadRequest), list(int)) """ unique_requests_map = {} mapping_list = [] unique_download_list = [] for download_request in download_list: if download_request not in unique_requests_map: unique_requests_map[download_request] = len(unique_download_list) unique_download_list.append(download_request) mapping_list.append(unique_requests_map[download_request]) return unique_download_list, mapping_list
python
def _filter_repeating_items(download_list): """ Because of data_filter some requests in download list might be the same. In order not to download them again this method will reduce the list of requests. It will also return a mapping list which can be used to reconstruct the previous list of download requests. :param download_list: List of download requests :type download_list: list(sentinelhub.DownloadRequest) :return: reduced download list with unique requests and mapping list :rtype: (list(sentinelhub.DownloadRequest), list(int)) """ unique_requests_map = {} mapping_list = [] unique_download_list = [] for download_request in download_list: if download_request not in unique_requests_map: unique_requests_map[download_request] = len(unique_download_list) unique_download_list.append(download_request) mapping_list.append(unique_requests_map[download_request]) return unique_download_list, mapping_list
[ "def", "_filter_repeating_items", "(", "download_list", ")", ":", "unique_requests_map", "=", "{", "}", "mapping_list", "=", "[", "]", "unique_download_list", "=", "[", "]", "for", "download_request", "in", "download_list", ":", "if", "download_request", "not", "in", "unique_requests_map", ":", "unique_requests_map", "[", "download_request", "]", "=", "len", "(", "unique_download_list", ")", "unique_download_list", ".", "append", "(", "download_request", ")", "mapping_list", ".", "append", "(", "unique_requests_map", "[", "download_request", "]", ")", "return", "unique_download_list", ",", "mapping_list" ]
Because of data_filter some requests in download list might be the same. In order not to download them again this method will reduce the list of requests. It will also return a mapping list which can be used to reconstruct the previous list of download requests. :param download_list: List of download requests :type download_list: list(sentinelhub.DownloadRequest) :return: reduced download list with unique requests and mapping list :rtype: (list(sentinelhub.DownloadRequest), list(int))
[ "Because", "of", "data_filter", "some", "requests", "in", "download", "list", "might", "be", "the", "same", ".", "In", "order", "not", "to", "download", "them", "again", "this", "method", "will", "reduce", "the", "list", "of", "requests", ".", "It", "will", "also", "return", "a", "mapping", "list", "which", "can", "be", "used", "to", "reconstruct", "the", "previous", "list", "of", "download", "requests", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L181-L199
229,205
sentinel-hub/sentinelhub-py
sentinelhub/data_request.py
DataRequest._preprocess_request
def _preprocess_request(self, save_data, return_data): """ Prepares requests for download and creates empty folders :param save_data: Tells whether to save data or not :type: bool :param return_data: Tells whether to return data or not :type: bool """ if not self.is_valid_request(): raise ValueError('Cannot obtain data because request is invalid') if save_data and self.data_folder is None: raise ValueError('Request parameter `data_folder` is not specified. ' 'In order to save data please set `data_folder` to location on your disk.') for download_request in self.download_list: download_request.set_save_response(save_data) download_request.set_return_data(return_data) download_request.set_data_folder(self.data_folder) if save_data: for folder in self.folder_list: make_folder(os.path.join(self.data_folder, folder))
python
def _preprocess_request(self, save_data, return_data): """ Prepares requests for download and creates empty folders :param save_data: Tells whether to save data or not :type: bool :param return_data: Tells whether to return data or not :type: bool """ if not self.is_valid_request(): raise ValueError('Cannot obtain data because request is invalid') if save_data and self.data_folder is None: raise ValueError('Request parameter `data_folder` is not specified. ' 'In order to save data please set `data_folder` to location on your disk.') for download_request in self.download_list: download_request.set_save_response(save_data) download_request.set_return_data(return_data) download_request.set_data_folder(self.data_folder) if save_data: for folder in self.folder_list: make_folder(os.path.join(self.data_folder, folder))
[ "def", "_preprocess_request", "(", "self", ",", "save_data", ",", "return_data", ")", ":", "if", "not", "self", ".", "is_valid_request", "(", ")", ":", "raise", "ValueError", "(", "'Cannot obtain data because request is invalid'", ")", "if", "save_data", "and", "self", ".", "data_folder", "is", "None", ":", "raise", "ValueError", "(", "'Request parameter `data_folder` is not specified. '", "'In order to save data please set `data_folder` to location on your disk.'", ")", "for", "download_request", "in", "self", ".", "download_list", ":", "download_request", ".", "set_save_response", "(", "save_data", ")", "download_request", ".", "set_return_data", "(", "return_data", ")", "download_request", ".", "set_data_folder", "(", "self", ".", "data_folder", ")", "if", "save_data", ":", "for", "folder", "in", "self", ".", "folder_list", ":", "make_folder", "(", "os", ".", "path", ".", "join", "(", "self", ".", "data_folder", ",", "folder", ")", ")" ]
Prepares requests for download and creates empty folders :param save_data: Tells whether to save data or not :type: bool :param return_data: Tells whether to return data or not :type: bool
[ "Prepares", "requests", "for", "download", "and", "creates", "empty", "folders" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L201-L224
229,206
sentinel-hub/sentinelhub-py
sentinelhub/data_request.py
DataRequest._add_saved_data
def _add_saved_data(self, data_list, data_filter, raise_download_errors): """ Adds already saved data that was not redownloaded to the requested data list. """ filtered_download_list = self.download_list if data_filter is None else \ [self.download_list[index] for index in data_filter] for i, request in enumerate(filtered_download_list): if request.return_data and data_list[i] is None: if os.path.exists(request.get_file_path()): data_list[i] = read_data(request.get_file_path()) elif raise_download_errors: raise DownloadFailedException('Failed to download data from {}.\n No previously downloaded data ' 'exists in file {}.'.format(request.url, request.get_file_path())) return data_list
python
def _add_saved_data(self, data_list, data_filter, raise_download_errors): """ Adds already saved data that was not redownloaded to the requested data list. """ filtered_download_list = self.download_list if data_filter is None else \ [self.download_list[index] for index in data_filter] for i, request in enumerate(filtered_download_list): if request.return_data and data_list[i] is None: if os.path.exists(request.get_file_path()): data_list[i] = read_data(request.get_file_path()) elif raise_download_errors: raise DownloadFailedException('Failed to download data from {}.\n No previously downloaded data ' 'exists in file {}.'.format(request.url, request.get_file_path())) return data_list
[ "def", "_add_saved_data", "(", "self", ",", "data_list", ",", "data_filter", ",", "raise_download_errors", ")", ":", "filtered_download_list", "=", "self", ".", "download_list", "if", "data_filter", "is", "None", "else", "[", "self", ".", "download_list", "[", "index", "]", "for", "index", "in", "data_filter", "]", "for", "i", ",", "request", "in", "enumerate", "(", "filtered_download_list", ")", ":", "if", "request", ".", "return_data", "and", "data_list", "[", "i", "]", "is", "None", ":", "if", "os", ".", "path", ".", "exists", "(", "request", ".", "get_file_path", "(", ")", ")", ":", "data_list", "[", "i", "]", "=", "read_data", "(", "request", ".", "get_file_path", "(", ")", ")", "elif", "raise_download_errors", ":", "raise", "DownloadFailedException", "(", "'Failed to download data from {}.\\n No previously downloaded data '", "'exists in file {}.'", ".", "format", "(", "request", ".", "url", ",", "request", ".", "get_file_path", "(", ")", ")", ")", "return", "data_list" ]
Adds already saved data that was not redownloaded to the requested data list.
[ "Adds", "already", "saved", "data", "that", "was", "not", "redownloaded", "to", "the", "requested", "data", "list", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L226-L239
229,207
sentinel-hub/sentinelhub-py
sentinelhub/data_request.py
GeopediaImageRequest.create_request
def create_request(self, reset_gpd_iterator=False): """Set a list of download requests Set a list of DownloadRequests for all images that are under the given property of the Geopedia's Vector layer. :param reset_gpd_iterator: When re-running the method this flag is used to reset/keep existing ``gpd_iterator`` (i.e. instance of ``GeopediaFeatureIterator`` class). If the iterator is not reset you don't have to repeat a service call but tiles and dates will stay the same. :type reset_gpd_iterator: bool """ if reset_gpd_iterator: self.gpd_iterator = None gpd_service = GeopediaImageService() self.download_list = gpd_service.get_request(self) self.gpd_iterator = gpd_service.get_gpd_iterator()
python
def create_request(self, reset_gpd_iterator=False): """Set a list of download requests Set a list of DownloadRequests for all images that are under the given property of the Geopedia's Vector layer. :param reset_gpd_iterator: When re-running the method this flag is used to reset/keep existing ``gpd_iterator`` (i.e. instance of ``GeopediaFeatureIterator`` class). If the iterator is not reset you don't have to repeat a service call but tiles and dates will stay the same. :type reset_gpd_iterator: bool """ if reset_gpd_iterator: self.gpd_iterator = None gpd_service = GeopediaImageService() self.download_list = gpd_service.get_request(self) self.gpd_iterator = gpd_service.get_gpd_iterator()
[ "def", "create_request", "(", "self", ",", "reset_gpd_iterator", "=", "False", ")", ":", "if", "reset_gpd_iterator", ":", "self", ".", "gpd_iterator", "=", "None", "gpd_service", "=", "GeopediaImageService", "(", ")", "self", ".", "download_list", "=", "gpd_service", ".", "get_request", "(", "self", ")", "self", ".", "gpd_iterator", "=", "gpd_service", ".", "get_gpd_iterator", "(", ")" ]
Set a list of download requests Set a list of DownloadRequests for all images that are under the given property of the Geopedia's Vector layer. :param reset_gpd_iterator: When re-running the method this flag is used to reset/keep existing ``gpd_iterator`` (i.e. instance of ``GeopediaFeatureIterator`` class). If the iterator is not reset you don't have to repeat a service call but tiles and dates will stay the same. :type reset_gpd_iterator: bool
[ "Set", "a", "list", "of", "download", "requests" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/data_request.py#L707-L723
229,208
sentinel-hub/sentinelhub-py
sentinelhub/geopedia.py
GeopediaSession.provide_session
def provide_session(self, start_new=False): """ Makes sure that session is still valid and provides session info :param start_new: If `True` it will always create a new session. Otherwise it will create a new session only if no session exists or the previous session timed out. :type start_new: bool :return: Current session info :rtype: dict """ if self.is_global: self._session_info = self._global_session_info self._session_start = self._global_session_start if self._session_info is None or start_new or \ datetime.datetime.now() > self._session_start + self.SESSION_DURATION: self._start_new_session() return self._session_info
python
def provide_session(self, start_new=False): """ Makes sure that session is still valid and provides session info :param start_new: If `True` it will always create a new session. Otherwise it will create a new session only if no session exists or the previous session timed out. :type start_new: bool :return: Current session info :rtype: dict """ if self.is_global: self._session_info = self._global_session_info self._session_start = self._global_session_start if self._session_info is None or start_new or \ datetime.datetime.now() > self._session_start + self.SESSION_DURATION: self._start_new_session() return self._session_info
[ "def", "provide_session", "(", "self", ",", "start_new", "=", "False", ")", ":", "if", "self", ".", "is_global", ":", "self", ".", "_session_info", "=", "self", ".", "_global_session_info", "self", ".", "_session_start", "=", "self", ".", "_global_session_start", "if", "self", ".", "_session_info", "is", "None", "or", "start_new", "or", "datetime", ".", "datetime", ".", "now", "(", ")", ">", "self", ".", "_session_start", "+", "self", ".", "SESSION_DURATION", ":", "self", ".", "_start_new_session", "(", ")", "return", "self", ".", "_session_info" ]
Makes sure that session is still valid and provides session info :param start_new: If `True` it will always create a new session. Otherwise it will create a new session only if no session exists or the previous session timed out. :type start_new: bool :return: Current session info :rtype: dict
[ "Makes", "sure", "that", "session", "is", "still", "valid", "and", "provides", "session", "info" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L153-L170
229,209
sentinel-hub/sentinelhub-py
sentinelhub/geopedia.py
GeopediaSession._start_new_session
def _start_new_session(self): """ Starts a new session and calculates when the new session will end. If username and password are provided it will also make login. """ self._session_start = datetime.datetime.now() session_id = self._parse_session_id(self._session_info) if self._session_info else '' session_url = '{}data/v1/session/create?locale=en&sid={}'.format(self.base_url, session_id) self._session_info = get_json(session_url) if self.username and self.password and self._parse_user_id(self._session_info) == self.UNAUTHENTICATED_USER_ID: self._make_login() if self.is_global: GeopediaSession._global_session_info = self._session_info GeopediaSession._global_session_start = self._session_start
python
def _start_new_session(self): """ Starts a new session and calculates when the new session will end. If username and password are provided it will also make login. """ self._session_start = datetime.datetime.now() session_id = self._parse_session_id(self._session_info) if self._session_info else '' session_url = '{}data/v1/session/create?locale=en&sid={}'.format(self.base_url, session_id) self._session_info = get_json(session_url) if self.username and self.password and self._parse_user_id(self._session_info) == self.UNAUTHENTICATED_USER_ID: self._make_login() if self.is_global: GeopediaSession._global_session_info = self._session_info GeopediaSession._global_session_start = self._session_start
[ "def", "_start_new_session", "(", "self", ")", ":", "self", ".", "_session_start", "=", "datetime", ".", "datetime", ".", "now", "(", ")", "session_id", "=", "self", ".", "_parse_session_id", "(", "self", ".", "_session_info", ")", "if", "self", ".", "_session_info", "else", "''", "session_url", "=", "'{}data/v1/session/create?locale=en&sid={}'", ".", "format", "(", "self", ".", "base_url", ",", "session_id", ")", "self", ".", "_session_info", "=", "get_json", "(", "session_url", ")", "if", "self", ".", "username", "and", "self", ".", "password", "and", "self", ".", "_parse_user_id", "(", "self", ".", "_session_info", ")", "==", "self", ".", "UNAUTHENTICATED_USER_ID", ":", "self", ".", "_make_login", "(", ")", "if", "self", ".", "is_global", ":", "GeopediaSession", ".", "_global_session_info", "=", "self", ".", "_session_info", "GeopediaSession", ".", "_global_session_start", "=", "self", ".", "_session_start" ]
Starts a new session and calculates when the new session will end. If username and password are provided it will also make login.
[ "Starts", "a", "new", "session", "and", "calculates", "when", "the", "new", "session", "will", "end", ".", "If", "username", "and", "password", "are", "provided", "it", "will", "also", "make", "login", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L172-L187
229,210
sentinel-hub/sentinelhub-py
sentinelhub/geopedia.py
GeopediaSession._make_login
def _make_login(self): """ Private method that makes login """ login_url = '{}data/v1/session/login?user={}&pass={}&sid={}'.format(self.base_url, self.username, self.password, self._parse_session_id(self._session_info)) self._session_info = get_json(login_url)
python
def _make_login(self): """ Private method that makes login """ login_url = '{}data/v1/session/login?user={}&pass={}&sid={}'.format(self.base_url, self.username, self.password, self._parse_session_id(self._session_info)) self._session_info = get_json(login_url)
[ "def", "_make_login", "(", "self", ")", ":", "login_url", "=", "'{}data/v1/session/login?user={}&pass={}&sid={}'", ".", "format", "(", "self", ".", "base_url", ",", "self", ".", "username", ",", "self", ".", "password", ",", "self", ".", "_parse_session_id", "(", "self", ".", "_session_info", ")", ")", "self", ".", "_session_info", "=", "get_json", "(", "login_url", ")" ]
Private method that makes login
[ "Private", "method", "that", "makes", "login" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L189-L194
229,211
sentinel-hub/sentinelhub-py
sentinelhub/geopedia.py
GeopediaImageService._get_items
def _get_items(self, request): """ Collects data from Geopedia layer and returns list of features """ if request.gpd_iterator is None: self.gpd_iterator = GeopediaFeatureIterator(request.layer, bbox=request.bbox, base_url=self.base_url, gpd_session=request.gpd_session) else: self.gpd_iterator = request.gpd_iterator field_iter = self.gpd_iterator.get_field_iterator(request.image_field_name) items = [] for field_items in field_iter: # an image field can have multiple images for item in field_items: if not item['mimeType'].startswith('image/'): continue mime_type = MimeType.from_string(item['mimeType'][6:]) if mime_type is request.image_format: items.append(item) return items
python
def _get_items(self, request): """ Collects data from Geopedia layer and returns list of features """ if request.gpd_iterator is None: self.gpd_iterator = GeopediaFeatureIterator(request.layer, bbox=request.bbox, base_url=self.base_url, gpd_session=request.gpd_session) else: self.gpd_iterator = request.gpd_iterator field_iter = self.gpd_iterator.get_field_iterator(request.image_field_name) items = [] for field_items in field_iter: # an image field can have multiple images for item in field_items: if not item['mimeType'].startswith('image/'): continue mime_type = MimeType.from_string(item['mimeType'][6:]) if mime_type is request.image_format: items.append(item) return items
[ "def", "_get_items", "(", "self", ",", "request", ")", ":", "if", "request", ".", "gpd_iterator", "is", "None", ":", "self", ".", "gpd_iterator", "=", "GeopediaFeatureIterator", "(", "request", ".", "layer", ",", "bbox", "=", "request", ".", "bbox", ",", "base_url", "=", "self", ".", "base_url", ",", "gpd_session", "=", "request", ".", "gpd_session", ")", "else", ":", "self", ".", "gpd_iterator", "=", "request", ".", "gpd_iterator", "field_iter", "=", "self", ".", "gpd_iterator", ".", "get_field_iterator", "(", "request", ".", "image_field_name", ")", "items", "=", "[", "]", "for", "field_items", "in", "field_iter", ":", "# an image field can have multiple images", "for", "item", "in", "field_items", ":", "if", "not", "item", "[", "'mimeType'", "]", ".", "startswith", "(", "'image/'", ")", ":", "continue", "mime_type", "=", "MimeType", ".", "from_string", "(", "item", "[", "'mimeType'", "]", "[", "6", ":", "]", ")", "if", "mime_type", "is", "request", ".", "image_format", ":", "items", ".", "append", "(", "item", ")", "return", "items" ]
Collects data from Geopedia layer and returns list of features
[ "Collects", "data", "from", "Geopedia", "layer", "and", "returns", "list", "of", "features" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L269-L292
229,212
sentinel-hub/sentinelhub-py
sentinelhub/geopedia.py
GeopediaImageService._get_filename
def _get_filename(request, item): """ Creates a filename """ if request.keep_image_names: filename = OgcImageService.finalize_filename(item['niceName'].replace(' ', '_')) else: filename = OgcImageService.finalize_filename( '_'.join([str(GeopediaService._parse_layer(request.layer)), item['objectPath'].rsplit('/', 1)[-1]]), request.image_format ) LOGGER.debug("filename=%s", filename) return filename
python
def _get_filename(request, item): """ Creates a filename """ if request.keep_image_names: filename = OgcImageService.finalize_filename(item['niceName'].replace(' ', '_')) else: filename = OgcImageService.finalize_filename( '_'.join([str(GeopediaService._parse_layer(request.layer)), item['objectPath'].rsplit('/', 1)[-1]]), request.image_format ) LOGGER.debug("filename=%s", filename) return filename
[ "def", "_get_filename", "(", "request", ",", "item", ")", ":", "if", "request", ".", "keep_image_names", ":", "filename", "=", "OgcImageService", ".", "finalize_filename", "(", "item", "[", "'niceName'", "]", ".", "replace", "(", "' '", ",", "'_'", ")", ")", "else", ":", "filename", "=", "OgcImageService", ".", "finalize_filename", "(", "'_'", ".", "join", "(", "[", "str", "(", "GeopediaService", ".", "_parse_layer", "(", "request", ".", "layer", ")", ")", ",", "item", "[", "'objectPath'", "]", ".", "rsplit", "(", "'/'", ",", "1", ")", "[", "-", "1", "]", "]", ")", ",", "request", ".", "image_format", ")", "LOGGER", ".", "debug", "(", "\"filename=%s\"", ",", "filename", ")", "return", "filename" ]
Creates a filename
[ "Creates", "a", "filename" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L299-L311
229,213
sentinel-hub/sentinelhub-py
sentinelhub/geopedia.py
GeopediaFeatureIterator._fetch_features
def _fetch_features(self): """ Retrieves a new page of features from Geopedia """ if self.next_page_url is None: return response = get_json(self.next_page_url, post_values=self.query, headers=self.gpd_session.session_headers) self.features.extend(response['features']) self.next_page_url = response['pagination']['next'] self.layer_size = response['pagination']['total']
python
def _fetch_features(self): """ Retrieves a new page of features from Geopedia """ if self.next_page_url is None: return response = get_json(self.next_page_url, post_values=self.query, headers=self.gpd_session.session_headers) self.features.extend(response['features']) self.next_page_url = response['pagination']['next'] self.layer_size = response['pagination']['total']
[ "def", "_fetch_features", "(", "self", ")", ":", "if", "self", ".", "next_page_url", "is", "None", ":", "return", "response", "=", "get_json", "(", "self", ".", "next_page_url", ",", "post_values", "=", "self", ".", "query", ",", "headers", "=", "self", ".", "gpd_session", ".", "session_headers", ")", "self", ".", "features", ".", "extend", "(", "response", "[", "'features'", "]", ")", "self", ".", "next_page_url", "=", "response", "[", "'pagination'", "]", "[", "'next'", "]", "self", ".", "layer_size", "=", "response", "[", "'pagination'", "]", "[", "'total'", "]" ]
Retrieves a new page of features from Geopedia
[ "Retrieves", "a", "new", "page", "of", "features", "from", "Geopedia" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geopedia.py#L388-L398
229,214
sentinel-hub/sentinelhub-py
sentinelhub/os_utils.py
get_folder_list
def get_folder_list(folder='.'): """ Get list of sub-folders contained in input folder :param folder: input folder to list sub-folders. Default is ``'.'`` :type folder: str :return: list of sub-folders :rtype: list(str) """ dir_list = get_content_list(folder) return [f for f in dir_list if not os.path.isfile(os.path.join(folder, f))]
python
def get_folder_list(folder='.'): """ Get list of sub-folders contained in input folder :param folder: input folder to list sub-folders. Default is ``'.'`` :type folder: str :return: list of sub-folders :rtype: list(str) """ dir_list = get_content_list(folder) return [f for f in dir_list if not os.path.isfile(os.path.join(folder, f))]
[ "def", "get_folder_list", "(", "folder", "=", "'.'", ")", ":", "dir_list", "=", "get_content_list", "(", "folder", ")", "return", "[", "f", "for", "f", "in", "dir_list", "if", "not", "os", ".", "path", ".", "isfile", "(", "os", ".", "path", ".", "join", "(", "folder", ",", "f", ")", ")", "]" ]
Get list of sub-folders contained in input folder :param folder: input folder to list sub-folders. Default is ``'.'`` :type folder: str :return: list of sub-folders :rtype: list(str)
[ "Get", "list", "of", "sub", "-", "folders", "contained", "in", "input", "folder" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/os_utils.py#L21-L30
229,215
sentinel-hub/sentinelhub-py
sentinelhub/os_utils.py
create_parent_folder
def create_parent_folder(filename): """ Create parent folder for input filename recursively :param filename: input filename :type filename: str :raises: error if folder cannot be created """ path = os.path.dirname(filename) if path != '': make_folder(path)
python
def create_parent_folder(filename): """ Create parent folder for input filename recursively :param filename: input filename :type filename: str :raises: error if folder cannot be created """ path = os.path.dirname(filename) if path != '': make_folder(path)
[ "def", "create_parent_folder", "(", "filename", ")", ":", "path", "=", "os", ".", "path", ".", "dirname", "(", "filename", ")", "if", "path", "!=", "''", ":", "make_folder", "(", "path", ")" ]
Create parent folder for input filename recursively :param filename: input filename :type filename: str :raises: error if folder cannot be created
[ "Create", "parent", "folder", "for", "input", "filename", "recursively" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/os_utils.py#L45-L54
229,216
sentinel-hub/sentinelhub-py
sentinelhub/os_utils.py
make_folder
def make_folder(path): """ Create folder at input path recursively Create a folder specified by input path if one does not exist already :param path: input path to folder to be created :type path: str :raises: os.error if folder cannot be created """ if not os.path.exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise ValueError('Specified folder is not writable: %s' '\nPlease check permissions or set a new valid folder.' % path)
python
def make_folder(path): """ Create folder at input path recursively Create a folder specified by input path if one does not exist already :param path: input path to folder to be created :type path: str :raises: os.error if folder cannot be created """ if not os.path.exists(path): try: os.makedirs(path) except OSError as exception: if exception.errno != errno.EEXIST: raise ValueError('Specified folder is not writable: %s' '\nPlease check permissions or set a new valid folder.' % path)
[ "def", "make_folder", "(", "path", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "path", ")", ":", "try", ":", "os", ".", "makedirs", "(", "path", ")", "except", "OSError", "as", "exception", ":", "if", "exception", ".", "errno", "!=", "errno", ".", "EEXIST", ":", "raise", "ValueError", "(", "'Specified folder is not writable: %s'", "'\\nPlease check permissions or set a new valid folder.'", "%", "path", ")" ]
Create folder at input path recursively Create a folder specified by input path if one does not exist already :param path: input path to folder to be created :type path: str :raises: os.error if folder cannot be created
[ "Create", "folder", "at", "input", "path", "recursively" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/os_utils.py#L57-L73
229,217
sentinel-hub/sentinelhub-py
sentinelhub/os_utils.py
rename
def rename(old_path, new_path, edit_folders=True): """ Rename files or folders :param old_path: name of file or folder to rename :param new_path: name of new file or folder :param edit_folders: flag to allow recursive renaming of folders. Default is ``True`` :type old_path: str :type new_path: str :type edit_folders: bool """ if edit_folders: os.renames(old_path, new_path) else: os.rename(old_path, new_path)
python
def rename(old_path, new_path, edit_folders=True): """ Rename files or folders :param old_path: name of file or folder to rename :param new_path: name of new file or folder :param edit_folders: flag to allow recursive renaming of folders. Default is ``True`` :type old_path: str :type new_path: str :type edit_folders: bool """ if edit_folders: os.renames(old_path, new_path) else: os.rename(old_path, new_path)
[ "def", "rename", "(", "old_path", ",", "new_path", ",", "edit_folders", "=", "True", ")", ":", "if", "edit_folders", ":", "os", ".", "renames", "(", "old_path", ",", "new_path", ")", "else", ":", "os", ".", "rename", "(", "old_path", ",", "new_path", ")" ]
Rename files or folders :param old_path: name of file or folder to rename :param new_path: name of new file or folder :param edit_folders: flag to allow recursive renaming of folders. Default is ``True`` :type old_path: str :type new_path: str :type edit_folders: bool
[ "Rename", "files", "or", "folders" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/os_utils.py#L76-L89
229,218
sentinel-hub/sentinelhub-py
sentinelhub/os_utils.py
size
def size(pathname): """ Returns size of a file or folder in Bytes :param pathname: path to file or folder to be sized :type pathname: str :return: size of file or folder in Bytes :rtype: int :raises: os.error if file is not accessible """ if os.path.isfile(pathname): return os.path.getsize(pathname) return sum([size('{}/{}'.format(pathname, name)) for name in get_content_list(pathname)])
python
def size(pathname): """ Returns size of a file or folder in Bytes :param pathname: path to file or folder to be sized :type pathname: str :return: size of file or folder in Bytes :rtype: int :raises: os.error if file is not accessible """ if os.path.isfile(pathname): return os.path.getsize(pathname) return sum([size('{}/{}'.format(pathname, name)) for name in get_content_list(pathname)])
[ "def", "size", "(", "pathname", ")", ":", "if", "os", ".", "path", ".", "isfile", "(", "pathname", ")", ":", "return", "os", ".", "path", ".", "getsize", "(", "pathname", ")", "return", "sum", "(", "[", "size", "(", "'{}/{}'", ".", "format", "(", "pathname", ",", "name", ")", ")", "for", "name", "in", "get_content_list", "(", "pathname", ")", "]", ")" ]
Returns size of a file or folder in Bytes :param pathname: path to file or folder to be sized :type pathname: str :return: size of file or folder in Bytes :rtype: int :raises: os.error if file is not accessible
[ "Returns", "size", "of", "a", "file", "or", "folder", "in", "Bytes" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/os_utils.py#L92-L103
229,219
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBox.middle
def middle(self): """ Returns the middle point of the bounding box :return: middle point :rtype: (float, float) """ return (self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2
python
def middle(self): """ Returns the middle point of the bounding box :return: middle point :rtype: (float, float) """ return (self.min_x + self.max_x) / 2, (self.min_y + self.max_y) / 2
[ "def", "middle", "(", "self", ")", ":", "return", "(", "self", ".", "min_x", "+", "self", ".", "max_x", ")", "/", "2", ",", "(", "self", ".", "min_y", "+", "self", ".", "max_y", ")", "/", "2" ]
Returns the middle point of the bounding box :return: middle point :rtype: (float, float)
[ "Returns", "the", "middle", "point", "of", "the", "bounding", "box" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L206-L212
229,220
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBox.reverse
def reverse(self): """ Returns a new BBox object where x and y coordinates are switched :return: New BBox object with switched coordinates :rtype: BBox """ return BBox((self.min_y, self.min_x, self.max_y, self.max_x), crs=self.crs)
python
def reverse(self): """ Returns a new BBox object where x and y coordinates are switched :return: New BBox object with switched coordinates :rtype: BBox """ return BBox((self.min_y, self.min_x, self.max_y, self.max_x), crs=self.crs)
[ "def", "reverse", "(", "self", ")", ":", "return", "BBox", "(", "(", "self", ".", "min_y", ",", "self", ".", "min_x", ",", "self", ".", "max_y", ",", "self", ".", "max_x", ")", ",", "crs", "=", "self", ".", "crs", ")" ]
Returns a new BBox object where x and y coordinates are switched :return: New BBox object with switched coordinates :rtype: BBox
[ "Returns", "a", "new", "BBox", "object", "where", "x", "and", "y", "coordinates", "are", "switched" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L222-L228
229,221
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBox.transform
def transform(self, crs): """ Transforms BBox from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Bounding box in target CRS :rtype: BBox """ new_crs = CRS(crs) return BBox((transform_point(self.lower_left, self.crs, new_crs), transform_point(self.upper_right, self.crs, new_crs)), crs=new_crs)
python
def transform(self, crs): """ Transforms BBox from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Bounding box in target CRS :rtype: BBox """ new_crs = CRS(crs) return BBox((transform_point(self.lower_left, self.crs, new_crs), transform_point(self.upper_right, self.crs, new_crs)), crs=new_crs)
[ "def", "transform", "(", "self", ",", "crs", ")", ":", "new_crs", "=", "CRS", "(", "crs", ")", "return", "BBox", "(", "(", "transform_point", "(", "self", ".", "lower_left", ",", "self", ".", "crs", ",", "new_crs", ")", ",", "transform_point", "(", "self", ".", "upper_right", ",", "self", ".", "crs", ",", "new_crs", ")", ")", ",", "crs", "=", "new_crs", ")" ]
Transforms BBox from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Bounding box in target CRS :rtype: BBox
[ "Transforms", "BBox", "from", "current", "CRS", "to", "target", "CRS" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L230-L240
229,222
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBox.get_polygon
def get_polygon(self, reverse=False): """ Returns a tuple of coordinates of 5 points describing a polygon. Points are listed in clockwise order, first point is the same as the last. :param reverse: `True` if x and y coordinates should be switched and `False` otherwise :type reverse: bool :return: `((x_1, y_1), ... , (x_5, y_5))` :rtype: tuple(tuple(float)) """ bbox = self.reverse() if reverse else self polygon = ((bbox.min_x, bbox.min_y), (bbox.min_x, bbox.max_y), (bbox.max_x, bbox.max_y), (bbox.max_x, bbox.min_y), (bbox.min_x, bbox.min_y)) return polygon
python
def get_polygon(self, reverse=False): """ Returns a tuple of coordinates of 5 points describing a polygon. Points are listed in clockwise order, first point is the same as the last. :param reverse: `True` if x and y coordinates should be switched and `False` otherwise :type reverse: bool :return: `((x_1, y_1), ... , (x_5, y_5))` :rtype: tuple(tuple(float)) """ bbox = self.reverse() if reverse else self polygon = ((bbox.min_x, bbox.min_y), (bbox.min_x, bbox.max_y), (bbox.max_x, bbox.max_y), (bbox.max_x, bbox.min_y), (bbox.min_x, bbox.min_y)) return polygon
[ "def", "get_polygon", "(", "self", ",", "reverse", "=", "False", ")", ":", "bbox", "=", "self", ".", "reverse", "(", ")", "if", "reverse", "else", "self", "polygon", "=", "(", "(", "bbox", ".", "min_x", ",", "bbox", ".", "min_y", ")", ",", "(", "bbox", ".", "min_x", ",", "bbox", ".", "max_y", ")", ",", "(", "bbox", ".", "max_x", ",", "bbox", ".", "max_y", ")", ",", "(", "bbox", ".", "max_x", ",", "bbox", ".", "min_y", ")", ",", "(", "bbox", ".", "min_x", ",", "bbox", ".", "min_y", ")", ")", "return", "polygon" ]
Returns a tuple of coordinates of 5 points describing a polygon. Points are listed in clockwise order, first point is the same as the last. :param reverse: `True` if x and y coordinates should be switched and `False` otherwise :type reverse: bool :return: `((x_1, y_1), ... , (x_5, y_5))` :rtype: tuple(tuple(float))
[ "Returns", "a", "tuple", "of", "coordinates", "of", "5", "points", "describing", "a", "polygon", ".", "Points", "are", "listed", "in", "clockwise", "order", "first", "point", "is", "the", "same", "as", "the", "last", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L258-L273
229,223
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBox.get_partition
def get_partition(self, num_x=1, num_y=1): """ Partitions bounding box into smaller bounding boxes of the same size. :param num_x: Number of parts BBox will be horizontally divided into. :type num_x: int :param num_y: Number of parts BBox will be vertically divided into. :type num_y: int or None :return: Two-dimensional list of smaller bounding boxes. Their location is :rtype: list(list(BBox)) """ size_x, size_y = (self.max_x - self.min_x) / num_x, (self.max_y - self.min_y) / num_y return [[BBox([self.min_x + i * size_x, self.min_y + j * size_y, self.min_x + (i + 1) * size_x, self.min_y + (j + 1) * size_y], crs=self.crs) for j in range(num_y)] for i in range(num_x)]
python
def get_partition(self, num_x=1, num_y=1): """ Partitions bounding box into smaller bounding boxes of the same size. :param num_x: Number of parts BBox will be horizontally divided into. :type num_x: int :param num_y: Number of parts BBox will be vertically divided into. :type num_y: int or None :return: Two-dimensional list of smaller bounding boxes. Their location is :rtype: list(list(BBox)) """ size_x, size_y = (self.max_x - self.min_x) / num_x, (self.max_y - self.min_y) / num_y return [[BBox([self.min_x + i * size_x, self.min_y + j * size_y, self.min_x + (i + 1) * size_x, self.min_y + (j + 1) * size_y], crs=self.crs) for j in range(num_y)] for i in range(num_x)]
[ "def", "get_partition", "(", "self", ",", "num_x", "=", "1", ",", "num_y", "=", "1", ")", ":", "size_x", ",", "size_y", "=", "(", "self", ".", "max_x", "-", "self", ".", "min_x", ")", "/", "num_x", ",", "(", "self", ".", "max_y", "-", "self", ".", "min_y", ")", "/", "num_y", "return", "[", "[", "BBox", "(", "[", "self", ".", "min_x", "+", "i", "*", "size_x", ",", "self", ".", "min_y", "+", "j", "*", "size_y", ",", "self", ".", "min_x", "+", "(", "i", "+", "1", ")", "*", "size_x", ",", "self", ".", "min_y", "+", "(", "j", "+", "1", ")", "*", "size_y", "]", ",", "crs", "=", "self", ".", "crs", ")", "for", "j", "in", "range", "(", "num_y", ")", "]", "for", "i", "in", "range", "(", "num_x", ")", "]" ]
Partitions bounding box into smaller bounding boxes of the same size. :param num_x: Number of parts BBox will be horizontally divided into. :type num_x: int :param num_y: Number of parts BBox will be vertically divided into. :type num_y: int or None :return: Two-dimensional list of smaller bounding boxes. Their location is :rtype: list(list(BBox))
[ "Partitions", "bounding", "box", "into", "smaller", "bounding", "boxes", "of", "the", "same", "size", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L284-L297
229,224
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBox.get_transform_vector
def get_transform_vector(self, resx, resy): """ Given resolution it returns a transformation vector :param resx: Resolution in x direction :type resx: float or int :param resy: Resolution in y direction :type resy: float or int :return: A tuple with 6 numbers representing transformation vector :rtype: tuple(float) """ return self.x_min, self._parse_resolution(resx), 0, self.y_max, 0, -self._parse_resolution(resy)
python
def get_transform_vector(self, resx, resy): """ Given resolution it returns a transformation vector :param resx: Resolution in x direction :type resx: float or int :param resy: Resolution in y direction :type resy: float or int :return: A tuple with 6 numbers representing transformation vector :rtype: tuple(float) """ return self.x_min, self._parse_resolution(resx), 0, self.y_max, 0, -self._parse_resolution(resy)
[ "def", "get_transform_vector", "(", "self", ",", "resx", ",", "resy", ")", ":", "return", "self", ".", "x_min", ",", "self", ".", "_parse_resolution", "(", "resx", ")", ",", "0", ",", "self", ".", "y_max", ",", "0", ",", "-", "self", ".", "_parse_resolution", "(", "resy", ")" ]
Given resolution it returns a transformation vector :param resx: Resolution in x direction :type resx: float or int :param resy: Resolution in y direction :type resy: float or int :return: A tuple with 6 numbers representing transformation vector :rtype: tuple(float)
[ "Given", "resolution", "it", "returns", "a", "transformation", "vector" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L299-L309
229,225
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBox._parse_resolution
def _parse_resolution(res): """ Helper method for parsing given resolution. It will also try to parse a string into float :return: A float value of resolution :rtype: float """ if isinstance(res, str): return float(res.strip('m')) if isinstance(res, (int, float)): return float(res) raise TypeError('Resolution should be a float, got resolution of type {}'.format(type(res)))
python
def _parse_resolution(res): """ Helper method for parsing given resolution. It will also try to parse a string into float :return: A float value of resolution :rtype: float """ if isinstance(res, str): return float(res.strip('m')) if isinstance(res, (int, float)): return float(res) raise TypeError('Resolution should be a float, got resolution of type {}'.format(type(res)))
[ "def", "_parse_resolution", "(", "res", ")", ":", "if", "isinstance", "(", "res", ",", "str", ")", ":", "return", "float", "(", "res", ".", "strip", "(", "'m'", ")", ")", "if", "isinstance", "(", "res", ",", "(", "int", ",", "float", ")", ")", ":", "return", "float", "(", "res", ")", "raise", "TypeError", "(", "'Resolution should be a float, got resolution of type {}'", ".", "format", "(", "type", "(", "res", ")", ")", ")" ]
Helper method for parsing given resolution. It will also try to parse a string into float :return: A float value of resolution :rtype: float
[ "Helper", "method", "for", "parsing", "given", "resolution", ".", "It", "will", "also", "try", "to", "parse", "a", "string", "into", "float" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L312-L323
229,226
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBox._tuple_from_list_or_tuple
def _tuple_from_list_or_tuple(bbox): """ Converts a list or tuple representation of a bbox into a flat tuple representation. :param bbox: a list or tuple with 4 coordinates that is either flat or nested :return: tuple (min_x,min_y,max_x,max_y) :raises: TypeError """ if len(bbox) == 4: return tuple(map(float, bbox)) if len(bbox) == 2 and all([isinstance(point, (list, tuple)) for point in bbox]): return BBox._tuple_from_list_or_tuple(bbox[0] + bbox[1]) raise TypeError('Expected a valid list or tuple representation of a bbox')
python
def _tuple_from_list_or_tuple(bbox): """ Converts a list or tuple representation of a bbox into a flat tuple representation. :param bbox: a list or tuple with 4 coordinates that is either flat or nested :return: tuple (min_x,min_y,max_x,max_y) :raises: TypeError """ if len(bbox) == 4: return tuple(map(float, bbox)) if len(bbox) == 2 and all([isinstance(point, (list, tuple)) for point in bbox]): return BBox._tuple_from_list_or_tuple(bbox[0] + bbox[1]) raise TypeError('Expected a valid list or tuple representation of a bbox')
[ "def", "_tuple_from_list_or_tuple", "(", "bbox", ")", ":", "if", "len", "(", "bbox", ")", "==", "4", ":", "return", "tuple", "(", "map", "(", "float", ",", "bbox", ")", ")", "if", "len", "(", "bbox", ")", "==", "2", "and", "all", "(", "[", "isinstance", "(", "point", ",", "(", "list", ",", "tuple", ")", ")", "for", "point", "in", "bbox", "]", ")", ":", "return", "BBox", ".", "_tuple_from_list_or_tuple", "(", "bbox", "[", "0", "]", "+", "bbox", "[", "1", "]", ")", "raise", "TypeError", "(", "'Expected a valid list or tuple representation of a bbox'", ")" ]
Converts a list or tuple representation of a bbox into a flat tuple representation. :param bbox: a list or tuple with 4 coordinates that is either flat or nested :return: tuple (min_x,min_y,max_x,max_y) :raises: TypeError
[ "Converts", "a", "list", "or", "tuple", "representation", "of", "a", "bbox", "into", "a", "flat", "tuple", "representation", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L347-L358
229,227
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBox._tuple_from_str
def _tuple_from_str(bbox): """ Parses a string of numbers separated by any combination of commas and spaces :param bbox: e.g. str of the form `min_x ,min_y max_x, max_y` :return: tuple (min_x,min_y,max_x,max_y) """ return tuple([float(s) for s in bbox.replace(',', ' ').split() if s])
python
def _tuple_from_str(bbox): """ Parses a string of numbers separated by any combination of commas and spaces :param bbox: e.g. str of the form `min_x ,min_y max_x, max_y` :return: tuple (min_x,min_y,max_x,max_y) """ return tuple([float(s) for s in bbox.replace(',', ' ').split() if s])
[ "def", "_tuple_from_str", "(", "bbox", ")", ":", "return", "tuple", "(", "[", "float", "(", "s", ")", "for", "s", "in", "bbox", ".", "replace", "(", "','", ",", "' '", ")", ".", "split", "(", ")", "if", "s", "]", ")" ]
Parses a string of numbers separated by any combination of commas and spaces :param bbox: e.g. str of the form `min_x ,min_y max_x, max_y` :return: tuple (min_x,min_y,max_x,max_y)
[ "Parses", "a", "string", "of", "numbers", "separated", "by", "any", "combination", "of", "commas", "and", "spaces" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L361-L367
229,228
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
Geometry.reverse
def reverse(self): """ Returns a new Geometry object where x and y coordinates are switched :return: New Geometry object with switched coordinates :rtype: Geometry """ return Geometry(shapely.ops.transform(lambda x, y: (y, x), self.geometry), crs=self.crs)
python
def reverse(self): """ Returns a new Geometry object where x and y coordinates are switched :return: New Geometry object with switched coordinates :rtype: Geometry """ return Geometry(shapely.ops.transform(lambda x, y: (y, x), self.geometry), crs=self.crs)
[ "def", "reverse", "(", "self", ")", ":", "return", "Geometry", "(", "shapely", ".", "ops", ".", "transform", "(", "lambda", "x", ",", "y", ":", "(", "y", ",", "x", ")", ",", "self", ".", "geometry", ")", ",", "crs", "=", "self", ".", "crs", ")" ]
Returns a new Geometry object where x and y coordinates are switched :return: New Geometry object with switched coordinates :rtype: Geometry
[ "Returns", "a", "new", "Geometry", "object", "where", "x", "and", "y", "coordinates", "are", "switched" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L423-L429
229,229
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
Geometry.transform
def transform(self, crs): """ Transforms Geometry from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Geometry in target CRS :rtype: Geometry """ new_crs = CRS(crs) geometry = self.geometry if new_crs is not self.crs: project = functools.partial(pyproj.transform, self.crs.projection(), new_crs.projection()) geometry = shapely.ops.transform(project, geometry) return Geometry(geometry, crs=new_crs)
python
def transform(self, crs): """ Transforms Geometry from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Geometry in target CRS :rtype: Geometry """ new_crs = CRS(crs) geometry = self.geometry if new_crs is not self.crs: project = functools.partial(pyproj.transform, self.crs.projection(), new_crs.projection()) geometry = shapely.ops.transform(project, geometry) return Geometry(geometry, crs=new_crs)
[ "def", "transform", "(", "self", ",", "crs", ")", ":", "new_crs", "=", "CRS", "(", "crs", ")", "geometry", "=", "self", ".", "geometry", "if", "new_crs", "is", "not", "self", ".", "crs", ":", "project", "=", "functools", ".", "partial", "(", "pyproj", ".", "transform", ",", "self", ".", "crs", ".", "projection", "(", ")", ",", "new_crs", ".", "projection", "(", ")", ")", "geometry", "=", "shapely", ".", "ops", ".", "transform", "(", "project", ",", "geometry", ")", "return", "Geometry", "(", "geometry", ",", "crs", "=", "new_crs", ")" ]
Transforms Geometry from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: Geometry in target CRS :rtype: Geometry
[ "Transforms", "Geometry", "from", "current", "CRS", "to", "target", "CRS" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L431-L446
229,230
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
Geometry._parse_geometry
def _parse_geometry(geometry): """ Parses given geometry into shapely object :param geometry: :return: Shapely polygon or multipolygon :rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon :raises TypeError """ if isinstance(geometry, str): geometry = shapely.wkt.loads(geometry) elif isinstance(geometry, dict): geometry = shapely.geometry.shape(geometry) elif not isinstance(geometry, shapely.geometry.base.BaseGeometry): raise TypeError('Unsupported geometry representation') if not isinstance(geometry, (shapely.geometry.Polygon, shapely.geometry.MultiPolygon)): raise ValueError('Supported geometry types are polygon and multipolygon, got {}'.format(type(geometry))) return geometry
python
def _parse_geometry(geometry): """ Parses given geometry into shapely object :param geometry: :return: Shapely polygon or multipolygon :rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon :raises TypeError """ if isinstance(geometry, str): geometry = shapely.wkt.loads(geometry) elif isinstance(geometry, dict): geometry = shapely.geometry.shape(geometry) elif not isinstance(geometry, shapely.geometry.base.BaseGeometry): raise TypeError('Unsupported geometry representation') if not isinstance(geometry, (shapely.geometry.Polygon, shapely.geometry.MultiPolygon)): raise ValueError('Supported geometry types are polygon and multipolygon, got {}'.format(type(geometry))) return geometry
[ "def", "_parse_geometry", "(", "geometry", ")", ":", "if", "isinstance", "(", "geometry", ",", "str", ")", ":", "geometry", "=", "shapely", ".", "wkt", ".", "loads", "(", "geometry", ")", "elif", "isinstance", "(", "geometry", ",", "dict", ")", ":", "geometry", "=", "shapely", ".", "geometry", ".", "shape", "(", "geometry", ")", "elif", "not", "isinstance", "(", "geometry", ",", "shapely", ".", "geometry", ".", "base", ".", "BaseGeometry", ")", ":", "raise", "TypeError", "(", "'Unsupported geometry representation'", ")", "if", "not", "isinstance", "(", "geometry", ",", "(", "shapely", ".", "geometry", ".", "Polygon", ",", "shapely", ".", "geometry", ".", "MultiPolygon", ")", ")", ":", "raise", "ValueError", "(", "'Supported geometry types are polygon and multipolygon, got {}'", ".", "format", "(", "type", "(", "geometry", ")", ")", ")", "return", "geometry" ]
Parses given geometry into shapely object :param geometry: :return: Shapely polygon or multipolygon :rtype: shapely.geometry.Polygon or shapely.geometry.MultiPolygon :raises TypeError
[ "Parses", "given", "geometry", "into", "shapely", "object" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L467-L485
229,231
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBoxCollection.transform
def transform(self, crs): """ Transforms BBoxCollection from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: BBoxCollection in target CRS :rtype: BBoxCollection """ return BBoxCollection([bbox.transform(crs) for bbox in self.bbox_list])
python
def transform(self, crs): """ Transforms BBoxCollection from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: BBoxCollection in target CRS :rtype: BBoxCollection """ return BBoxCollection([bbox.transform(crs) for bbox in self.bbox_list])
[ "def", "transform", "(", "self", ",", "crs", ")", ":", "return", "BBoxCollection", "(", "[", "bbox", ".", "transform", "(", "crs", ")", "for", "bbox", "in", "self", ".", "bbox_list", "]", ")" ]
Transforms BBoxCollection from current CRS to target CRS :param crs: target CRS :type crs: constants.CRS :return: BBoxCollection in target CRS :rtype: BBoxCollection
[ "Transforms", "BBoxCollection", "from", "current", "CRS", "to", "target", "CRS" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L551-L559
229,232
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBoxCollection._get_geometry
def _get_geometry(self): """ Creates a multipolygon of bounding box polygons """ return shapely.geometry.MultiPolygon([bbox.geometry for bbox in self.bbox_list])
python
def _get_geometry(self): """ Creates a multipolygon of bounding box polygons """ return shapely.geometry.MultiPolygon([bbox.geometry for bbox in self.bbox_list])
[ "def", "_get_geometry", "(", "self", ")", ":", "return", "shapely", ".", "geometry", ".", "MultiPolygon", "(", "[", "bbox", ".", "geometry", "for", "bbox", "in", "self", ".", "bbox_list", "]", ")" ]
Creates a multipolygon of bounding box polygons
[ "Creates", "a", "multipolygon", "of", "bounding", "box", "polygons" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L561-L564
229,233
sentinel-hub/sentinelhub-py
sentinelhub/geometry.py
BBoxCollection._parse_bbox_list
def _parse_bbox_list(bbox_list): """ Helper method for parsing a list of bounding boxes """ if isinstance(bbox_list, BBoxCollection): return bbox_list.bbox_list, bbox_list.crs if not isinstance(bbox_list, list) or not bbox_list: raise ValueError('Expected non-empty list of BBox objects') for bbox in bbox_list: if not isinstance(bbox, BBox): raise ValueError('Elements in the list should be of type {}, got {}'.format(BBox.__name__, type(bbox))) crs = bbox_list[0].crs for bbox in bbox_list: if bbox.crs is not crs: raise ValueError('All bounding boxes should have the same CRS') return bbox_list, crs
python
def _parse_bbox_list(bbox_list): """ Helper method for parsing a list of bounding boxes """ if isinstance(bbox_list, BBoxCollection): return bbox_list.bbox_list, bbox_list.crs if not isinstance(bbox_list, list) or not bbox_list: raise ValueError('Expected non-empty list of BBox objects') for bbox in bbox_list: if not isinstance(bbox, BBox): raise ValueError('Elements in the list should be of type {}, got {}'.format(BBox.__name__, type(bbox))) crs = bbox_list[0].crs for bbox in bbox_list: if bbox.crs is not crs: raise ValueError('All bounding boxes should have the same CRS') return bbox_list, crs
[ "def", "_parse_bbox_list", "(", "bbox_list", ")", ":", "if", "isinstance", "(", "bbox_list", ",", "BBoxCollection", ")", ":", "return", "bbox_list", ".", "bbox_list", ",", "bbox_list", ".", "crs", "if", "not", "isinstance", "(", "bbox_list", ",", "list", ")", "or", "not", "bbox_list", ":", "raise", "ValueError", "(", "'Expected non-empty list of BBox objects'", ")", "for", "bbox", "in", "bbox_list", ":", "if", "not", "isinstance", "(", "bbox", ",", "BBox", ")", ":", "raise", "ValueError", "(", "'Elements in the list should be of type {}, got {}'", ".", "format", "(", "BBox", ".", "__name__", ",", "type", "(", "bbox", ")", ")", ")", "crs", "=", "bbox_list", "[", "0", "]", ".", "crs", "for", "bbox", "in", "bbox_list", ":", "if", "bbox", ".", "crs", "is", "not", "crs", ":", "raise", "ValueError", "(", "'All bounding boxes should have the same CRS'", ")", "return", "bbox_list", ",", "crs" ]
Helper method for parsing a list of bounding boxes
[ "Helper", "method", "for", "parsing", "a", "list", "of", "bounding", "boxes" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/geometry.py#L567-L585
229,234
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
read_data
def read_data(filename, data_format=None): """ Read image data from file This function reads input data from file. The format of the file can be specified in ``data_format``. If not specified, the format is guessed from the extension of the filename. :param filename: filename to read data from :type filename: str :param data_format: format of filename. Default is ``None`` :type data_format: MimeType :return: data read from filename :raises: exception if filename does not exist """ if not os.path.exists(filename): raise ValueError('Filename {} does not exist'.format(filename)) if not isinstance(data_format, MimeType): data_format = get_data_format(filename) if data_format.is_tiff_format(): return read_tiff_image(filename) if data_format is MimeType.JP2: return read_jp2_image(filename) if data_format.is_image_format(): return read_image(filename) try: return { MimeType.TXT: read_text, MimeType.CSV: read_csv, MimeType.JSON: read_json, MimeType.XML: read_xml, MimeType.GML: read_xml, MimeType.SAFE: read_xml }[data_format](filename) except KeyError: raise ValueError('Reading data format .{} is not supported'.format(data_format.value))
python
def read_data(filename, data_format=None): """ Read image data from file This function reads input data from file. The format of the file can be specified in ``data_format``. If not specified, the format is guessed from the extension of the filename. :param filename: filename to read data from :type filename: str :param data_format: format of filename. Default is ``None`` :type data_format: MimeType :return: data read from filename :raises: exception if filename does not exist """ if not os.path.exists(filename): raise ValueError('Filename {} does not exist'.format(filename)) if not isinstance(data_format, MimeType): data_format = get_data_format(filename) if data_format.is_tiff_format(): return read_tiff_image(filename) if data_format is MimeType.JP2: return read_jp2_image(filename) if data_format.is_image_format(): return read_image(filename) try: return { MimeType.TXT: read_text, MimeType.CSV: read_csv, MimeType.JSON: read_json, MimeType.XML: read_xml, MimeType.GML: read_xml, MimeType.SAFE: read_xml }[data_format](filename) except KeyError: raise ValueError('Reading data format .{} is not supported'.format(data_format.value))
[ "def", "read_data", "(", "filename", ",", "data_format", "=", "None", ")", ":", "if", "not", "os", ".", "path", ".", "exists", "(", "filename", ")", ":", "raise", "ValueError", "(", "'Filename {} does not exist'", ".", "format", "(", "filename", ")", ")", "if", "not", "isinstance", "(", "data_format", ",", "MimeType", ")", ":", "data_format", "=", "get_data_format", "(", "filename", ")", "if", "data_format", ".", "is_tiff_format", "(", ")", ":", "return", "read_tiff_image", "(", "filename", ")", "if", "data_format", "is", "MimeType", ".", "JP2", ":", "return", "read_jp2_image", "(", "filename", ")", "if", "data_format", ".", "is_image_format", "(", ")", ":", "return", "read_image", "(", "filename", ")", "try", ":", "return", "{", "MimeType", ".", "TXT", ":", "read_text", ",", "MimeType", ".", "CSV", ":", "read_csv", ",", "MimeType", ".", "JSON", ":", "read_json", ",", "MimeType", ".", "XML", ":", "read_xml", ",", "MimeType", ".", "GML", ":", "read_xml", ",", "MimeType", ".", "SAFE", ":", "read_xml", "}", "[", "data_format", "]", "(", "filename", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "'Reading data format .{} is not supported'", ".", "format", "(", "data_format", ".", "value", ")", ")" ]
Read image data from file This function reads input data from file. The format of the file can be specified in ``data_format``. If not specified, the format is guessed from the extension of the filename. :param filename: filename to read data from :type filename: str :param data_format: format of filename. Default is ``None`` :type data_format: MimeType :return: data read from filename :raises: exception if filename does not exist
[ "Read", "image", "data", "from", "file" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L26-L62
229,235
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
read_jp2_image
def read_jp2_image(filename): """ Read data from JPEG2000 file :param filename: name of JPEG2000 file to be read :type filename: str :return: data stored in JPEG2000 file """ # Other option: # return glymur.Jp2k(filename)[:] image = read_image(filename) with open(filename, 'rb') as file: bit_depth = get_jp2_bit_depth(file) return fix_jp2_image(image, bit_depth)
python
def read_jp2_image(filename): """ Read data from JPEG2000 file :param filename: name of JPEG2000 file to be read :type filename: str :return: data stored in JPEG2000 file """ # Other option: # return glymur.Jp2k(filename)[:] image = read_image(filename) with open(filename, 'rb') as file: bit_depth = get_jp2_bit_depth(file) return fix_jp2_image(image, bit_depth)
[ "def", "read_jp2_image", "(", "filename", ")", ":", "# Other option:", "# return glymur.Jp2k(filename)[:]", "image", "=", "read_image", "(", "filename", ")", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "file", ":", "bit_depth", "=", "get_jp2_bit_depth", "(", "file", ")", "return", "fix_jp2_image", "(", "image", ",", "bit_depth", ")" ]
Read data from JPEG2000 file :param filename: name of JPEG2000 file to be read :type filename: str :return: data stored in JPEG2000 file
[ "Read", "data", "from", "JPEG2000", "file" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L75-L89
229,236
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
read_csv
def read_csv(filename, delimiter=CSV_DELIMITER): """ Read data from CSV file :param filename: name of CSV file to be read :type filename: str :param delimiter: type of CSV delimiter. Default is ``;`` :type delimiter: str :return: data stored in CSV file as list """ with open(filename, 'r') as file: return list(csv.reader(file, delimiter=delimiter))
python
def read_csv(filename, delimiter=CSV_DELIMITER): """ Read data from CSV file :param filename: name of CSV file to be read :type filename: str :param delimiter: type of CSV delimiter. Default is ``;`` :type delimiter: str :return: data stored in CSV file as list """ with open(filename, 'r') as file: return list(csv.reader(file, delimiter=delimiter))
[ "def", "read_csv", "(", "filename", ",", "delimiter", "=", "CSV_DELIMITER", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "file", ":", "return", "list", "(", "csv", ".", "reader", "(", "file", ",", "delimiter", "=", "delimiter", ")", ")" ]
Read data from CSV file :param filename: name of CSV file to be read :type filename: str :param delimiter: type of CSV delimiter. Default is ``;`` :type delimiter: str :return: data stored in CSV file as list
[ "Read", "data", "from", "CSV", "file" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L113-L123
229,237
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
write_data
def write_data(filename, data, data_format=None, compress=False, add=False): """ Write image data to file Function to write image data to specified file. If file format is not provided explicitly, it is guessed from the filename extension. If format is TIFF, geo information and compression can be optionally added. :param filename: name of file to write data to :type filename: str :param data: image data to write to file :type data: numpy array :param data_format: format of output file. Default is ``None`` :type data_format: MimeType :param compress: whether to compress data or not. Default is ``False`` :type compress: bool :param add: whether to append to existing text file or not. Default is ``False`` :type add: bool :raises: exception if numpy format is not supported or file cannot be written """ create_parent_folder(filename) if not isinstance(data_format, MimeType): data_format = get_data_format(filename) if data_format.is_tiff_format(): return write_tiff_image(filename, data, compress) if data_format.is_image_format(): return write_image(filename, data) if data_format is MimeType.TXT: return write_text(filename, data, add=add) try: return { MimeType.CSV: write_csv, MimeType.JSON: write_json, MimeType.XML: write_xml, MimeType.GML: write_xml }[data_format](filename, data) except KeyError: raise ValueError('Writing data format .{} is not supported'.format(data_format.value))
python
def write_data(filename, data, data_format=None, compress=False, add=False): """ Write image data to file Function to write image data to specified file. If file format is not provided explicitly, it is guessed from the filename extension. If format is TIFF, geo information and compression can be optionally added. :param filename: name of file to write data to :type filename: str :param data: image data to write to file :type data: numpy array :param data_format: format of output file. Default is ``None`` :type data_format: MimeType :param compress: whether to compress data or not. Default is ``False`` :type compress: bool :param add: whether to append to existing text file or not. Default is ``False`` :type add: bool :raises: exception if numpy format is not supported or file cannot be written """ create_parent_folder(filename) if not isinstance(data_format, MimeType): data_format = get_data_format(filename) if data_format.is_tiff_format(): return write_tiff_image(filename, data, compress) if data_format.is_image_format(): return write_image(filename, data) if data_format is MimeType.TXT: return write_text(filename, data, add=add) try: return { MimeType.CSV: write_csv, MimeType.JSON: write_json, MimeType.XML: write_xml, MimeType.GML: write_xml }[data_format](filename, data) except KeyError: raise ValueError('Writing data format .{} is not supported'.format(data_format.value))
[ "def", "write_data", "(", "filename", ",", "data", ",", "data_format", "=", "None", ",", "compress", "=", "False", ",", "add", "=", "False", ")", ":", "create_parent_folder", "(", "filename", ")", "if", "not", "isinstance", "(", "data_format", ",", "MimeType", ")", ":", "data_format", "=", "get_data_format", "(", "filename", ")", "if", "data_format", ".", "is_tiff_format", "(", ")", ":", "return", "write_tiff_image", "(", "filename", ",", "data", ",", "compress", ")", "if", "data_format", ".", "is_image_format", "(", ")", ":", "return", "write_image", "(", "filename", ",", "data", ")", "if", "data_format", "is", "MimeType", ".", "TXT", ":", "return", "write_text", "(", "filename", ",", "data", ",", "add", "=", "add", ")", "try", ":", "return", "{", "MimeType", ".", "CSV", ":", "write_csv", ",", "MimeType", ".", "JSON", ":", "write_json", ",", "MimeType", ".", "XML", ":", "write_xml", ",", "MimeType", ".", "GML", ":", "write_xml", "}", "[", "data_format", "]", "(", "filename", ",", "data", ")", "except", "KeyError", ":", "raise", "ValueError", "(", "'Writing data format .{} is not supported'", ".", "format", "(", "data_format", ".", "value", ")", ")" ]
Write image data to file Function to write image data to specified file. If file format is not provided explicitly, it is guessed from the filename extension. If format is TIFF, geo information and compression can be optionally added. :param filename: name of file to write data to :type filename: str :param data: image data to write to file :type data: numpy array :param data_format: format of output file. Default is ``None`` :type data_format: MimeType :param compress: whether to compress data or not. Default is ``False`` :type compress: bool :param add: whether to append to existing text file or not. Default is ``False`` :type add: bool :raises: exception if numpy format is not supported or file cannot be written
[ "Write", "image", "data", "to", "file" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L157-L196
229,238
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
write_tiff_image
def write_tiff_image(filename, image, compress=False): """ Write image data to TIFF file :param filename: name of file to write data to :type filename: str :param image: image data to write to file :type image: numpy array :param compress: whether to compress data. If ``True``, lzma compression is used. Default is ``False`` :type compress: bool """ if compress: return tiff.imsave(filename, image, compress='lzma') # loseless compression, works very well on masks return tiff.imsave(filename, image)
python
def write_tiff_image(filename, image, compress=False): """ Write image data to TIFF file :param filename: name of file to write data to :type filename: str :param image: image data to write to file :type image: numpy array :param compress: whether to compress data. If ``True``, lzma compression is used. Default is ``False`` :type compress: bool """ if compress: return tiff.imsave(filename, image, compress='lzma') # loseless compression, works very well on masks return tiff.imsave(filename, image)
[ "def", "write_tiff_image", "(", "filename", ",", "image", ",", "compress", "=", "False", ")", ":", "if", "compress", ":", "return", "tiff", ".", "imsave", "(", "filename", ",", "image", ",", "compress", "=", "'lzma'", ")", "# loseless compression, works very well on masks", "return", "tiff", ".", "imsave", "(", "filename", ",", "image", ")" ]
Write image data to TIFF file :param filename: name of file to write data to :type filename: str :param image: image data to write to file :type image: numpy array :param compress: whether to compress data. If ``True``, lzma compression is used. Default is ``False`` :type compress: bool
[ "Write", "image", "data", "to", "TIFF", "file" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L199-L211
229,239
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
write_image
def write_image(filename, image): """ Write image data to PNG, JPG file :param filename: name of PNG or JPG file to write data to :type filename: str :param image: image data to write to file :type image: numpy array """ data_format = get_data_format(filename) if data_format is MimeType.JPG: LOGGER.warning('Warning: jpeg is a lossy format therefore saved data will be modified.') return Image.fromarray(image).save(filename)
python
def write_image(filename, image): """ Write image data to PNG, JPG file :param filename: name of PNG or JPG file to write data to :type filename: str :param image: image data to write to file :type image: numpy array """ data_format = get_data_format(filename) if data_format is MimeType.JPG: LOGGER.warning('Warning: jpeg is a lossy format therefore saved data will be modified.') return Image.fromarray(image).save(filename)
[ "def", "write_image", "(", "filename", ",", "image", ")", ":", "data_format", "=", "get_data_format", "(", "filename", ")", "if", "data_format", "is", "MimeType", ".", "JPG", ":", "LOGGER", ".", "warning", "(", "'Warning: jpeg is a lossy format therefore saved data will be modified.'", ")", "return", "Image", ".", "fromarray", "(", "image", ")", ".", "save", "(", "filename", ")" ]
Write image data to PNG, JPG file :param filename: name of PNG or JPG file to write data to :type filename: str :param image: image data to write to file :type image: numpy array
[ "Write", "image", "data", "to", "PNG", "JPG", "file" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L229-L240
229,240
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
write_text
def write_text(filename, data, add=False): """ Write image data to text file :param filename: name of text file to write data to :type filename: str :param data: image data to write to text file :type data: numpy array :param add: whether to append to existing file or not. Default is ``False`` :type add: bool """ write_type = 'a' if add else 'w' with open(filename, write_type) as file: print(data, end='', file=file)
python
def write_text(filename, data, add=False): """ Write image data to text file :param filename: name of text file to write data to :type filename: str :param data: image data to write to text file :type data: numpy array :param add: whether to append to existing file or not. Default is ``False`` :type add: bool """ write_type = 'a' if add else 'w' with open(filename, write_type) as file: print(data, end='', file=file)
[ "def", "write_text", "(", "filename", ",", "data", ",", "add", "=", "False", ")", ":", "write_type", "=", "'a'", "if", "add", "else", "'w'", "with", "open", "(", "filename", ",", "write_type", ")", "as", "file", ":", "print", "(", "data", ",", "end", "=", "''", ",", "file", "=", "file", ")" ]
Write image data to text file :param filename: name of text file to write data to :type filename: str :param data: image data to write to text file :type data: numpy array :param add: whether to append to existing file or not. Default is ``False`` :type add: bool
[ "Write", "image", "data", "to", "text", "file" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L243-L255
229,241
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
write_csv
def write_csv(filename, data, delimiter=CSV_DELIMITER): """ Write image data to CSV file :param filename: name of CSV file to write data to :type filename: str :param data: image data to write to CSV file :type data: numpy array :param delimiter: delimiter used in CSV file. Default is ``;`` :type delimiter: str """ with open(filename, 'w') as file: csv_writer = csv.writer(file, delimiter=delimiter) for line in data: csv_writer.writerow(line)
python
def write_csv(filename, data, delimiter=CSV_DELIMITER): """ Write image data to CSV file :param filename: name of CSV file to write data to :type filename: str :param data: image data to write to CSV file :type data: numpy array :param delimiter: delimiter used in CSV file. Default is ``;`` :type delimiter: str """ with open(filename, 'w') as file: csv_writer = csv.writer(file, delimiter=delimiter) for line in data: csv_writer.writerow(line)
[ "def", "write_csv", "(", "filename", ",", "data", ",", "delimiter", "=", "CSV_DELIMITER", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "file", ":", "csv_writer", "=", "csv", ".", "writer", "(", "file", ",", "delimiter", "=", "delimiter", ")", "for", "line", "in", "data", ":", "csv_writer", ".", "writerow", "(", "line", ")" ]
Write image data to CSV file :param filename: name of CSV file to write data to :type filename: str :param data: image data to write to CSV file :type data: numpy array :param delimiter: delimiter used in CSV file. Default is ``;`` :type delimiter: str
[ "Write", "image", "data", "to", "CSV", "file" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L258-L271
229,242
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
write_json
def write_json(filename, data): """ Write data to JSON file :param filename: name of JSON file to write data to :type filename: str :param data: data to write to JSON file :type data: list, tuple """ with open(filename, 'w') as file: json.dump(data, file, indent=4, sort_keys=True)
python
def write_json(filename, data): """ Write data to JSON file :param filename: name of JSON file to write data to :type filename: str :param data: data to write to JSON file :type data: list, tuple """ with open(filename, 'w') as file: json.dump(data, file, indent=4, sort_keys=True)
[ "def", "write_json", "(", "filename", ",", "data", ")", ":", "with", "open", "(", "filename", ",", "'w'", ")", "as", "file", ":", "json", ".", "dump", "(", "data", ",", "file", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ")" ]
Write data to JSON file :param filename: name of JSON file to write data to :type filename: str :param data: data to write to JSON file :type data: list, tuple
[ "Write", "data", "to", "JSON", "file" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L274-L283
229,243
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
get_jp2_bit_depth
def get_jp2_bit_depth(stream): """Reads bit encoding depth of jpeg2000 file in binary stream format :param stream: binary stream format :type stream: Binary I/O (e.g. io.BytesIO, io.BufferedReader, ...) :return: bit depth :rtype: int """ stream.seek(0) while True: read_buffer = stream.read(8) if len(read_buffer) < 8: raise ValueError('Image Header Box not found in Jpeg2000 file') _, box_id = struct.unpack('>I4s', read_buffer) if box_id == b'ihdr': read_buffer = stream.read(14) params = struct.unpack('>IIHBBBB', read_buffer) return (params[3] & 0x7f) + 1
python
def get_jp2_bit_depth(stream): """Reads bit encoding depth of jpeg2000 file in binary stream format :param stream: binary stream format :type stream: Binary I/O (e.g. io.BytesIO, io.BufferedReader, ...) :return: bit depth :rtype: int """ stream.seek(0) while True: read_buffer = stream.read(8) if len(read_buffer) < 8: raise ValueError('Image Header Box not found in Jpeg2000 file') _, box_id = struct.unpack('>I4s', read_buffer) if box_id == b'ihdr': read_buffer = stream.read(14) params = struct.unpack('>IIHBBBB', read_buffer) return (params[3] & 0x7f) + 1
[ "def", "get_jp2_bit_depth", "(", "stream", ")", ":", "stream", ".", "seek", "(", "0", ")", "while", "True", ":", "read_buffer", "=", "stream", ".", "read", "(", "8", ")", "if", "len", "(", "read_buffer", ")", "<", "8", ":", "raise", "ValueError", "(", "'Image Header Box not found in Jpeg2000 file'", ")", "_", ",", "box_id", "=", "struct", ".", "unpack", "(", "'>I4s'", ",", "read_buffer", ")", "if", "box_id", "==", "b'ihdr'", ":", "read_buffer", "=", "stream", ".", "read", "(", "14", ")", "params", "=", "struct", ".", "unpack", "(", "'>IIHBBBB'", ",", "read_buffer", ")", "return", "(", "params", "[", "3", "]", "&", "0x7f", ")", "+", "1" ]
Reads bit encoding depth of jpeg2000 file in binary stream format :param stream: binary stream format :type stream: Binary I/O (e.g. io.BytesIO, io.BufferedReader, ...) :return: bit depth :rtype: int
[ "Reads", "bit", "encoding", "depth", "of", "jpeg2000", "file", "in", "binary", "stream", "format" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L322-L341
229,244
sentinel-hub/sentinelhub-py
sentinelhub/io_utils.py
fix_jp2_image
def fix_jp2_image(image, bit_depth): """Because Pillow library incorrectly reads JPEG 2000 images with 15-bit encoding this function corrects the values in image. :param image: image read by opencv library :type image: numpy array :param bit_depth: bit depth of jp2 image encoding :type bit_depth: int :return: corrected image :rtype: numpy array """ if bit_depth in [8, 16]: return image if bit_depth == 15: try: return image >> 1 except TypeError: raise IOError('Failed to read JPEG 2000 image correctly. Most likely reason is that Pillow did not ' 'install OpenJPEG library correctly. Try reinstalling Pillow from a wheel') raise ValueError('Bit depth {} of jp2 image is currently not supported. ' 'Please raise an issue on package Github page'.format(bit_depth))
python
def fix_jp2_image(image, bit_depth): """Because Pillow library incorrectly reads JPEG 2000 images with 15-bit encoding this function corrects the values in image. :param image: image read by opencv library :type image: numpy array :param bit_depth: bit depth of jp2 image encoding :type bit_depth: int :return: corrected image :rtype: numpy array """ if bit_depth in [8, 16]: return image if bit_depth == 15: try: return image >> 1 except TypeError: raise IOError('Failed to read JPEG 2000 image correctly. Most likely reason is that Pillow did not ' 'install OpenJPEG library correctly. Try reinstalling Pillow from a wheel') raise ValueError('Bit depth {} of jp2 image is currently not supported. ' 'Please raise an issue on package Github page'.format(bit_depth))
[ "def", "fix_jp2_image", "(", "image", ",", "bit_depth", ")", ":", "if", "bit_depth", "in", "[", "8", ",", "16", "]", ":", "return", "image", "if", "bit_depth", "==", "15", ":", "try", ":", "return", "image", ">>", "1", "except", "TypeError", ":", "raise", "IOError", "(", "'Failed to read JPEG 2000 image correctly. Most likely reason is that Pillow did not '", "'install OpenJPEG library correctly. Try reinstalling Pillow from a wheel'", ")", "raise", "ValueError", "(", "'Bit depth {} of jp2 image is currently not supported. '", "'Please raise an issue on package Github page'", ".", "format", "(", "bit_depth", ")", ")" ]
Because Pillow library incorrectly reads JPEG 2000 images with 15-bit encoding this function corrects the values in image. :param image: image read by opencv library :type image: numpy array :param bit_depth: bit depth of jp2 image encoding :type bit_depth: int :return: corrected image :rtype: numpy array
[ "Because", "Pillow", "library", "incorrectly", "reads", "JPEG", "2000", "images", "with", "15", "-", "bit", "encoding", "this", "function", "corrects", "the", "values", "in", "image", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/io_utils.py#L344-L365
229,245
sentinel-hub/sentinelhub-py
sentinelhub/download.py
download_data
def download_data(request_list, redownload=False, max_threads=None): """ Download all requested data or read data from disk, if already downloaded and available and redownload is not required. :param request_list: list of DownloadRequests :type request_list: list of DownloadRequests :param redownload: if ``True``, download again the data, although it was already downloaded and is available on the disk. Default is ``False``. :type redownload: bool :param max_threads: number of threads to use when downloading data; default is ``max_threads=None`` which by default uses the number of processors on the system :type max_threads: int :return: list of Futures holding downloaded data, where each element in the list corresponds to an element in the download request list. :rtype: list[concurrent.futures.Future] """ _check_if_must_download(request_list, redownload) LOGGER.debug("Using max_threads=%s for %s requests", max_threads, len(request_list)) with concurrent.futures.ThreadPoolExecutor(max_workers=max_threads) as executor: return [executor.submit(execute_download_request, request) for request in request_list]
python
def download_data(request_list, redownload=False, max_threads=None): """ Download all requested data or read data from disk, if already downloaded and available and redownload is not required. :param request_list: list of DownloadRequests :type request_list: list of DownloadRequests :param redownload: if ``True``, download again the data, although it was already downloaded and is available on the disk. Default is ``False``. :type redownload: bool :param max_threads: number of threads to use when downloading data; default is ``max_threads=None`` which by default uses the number of processors on the system :type max_threads: int :return: list of Futures holding downloaded data, where each element in the list corresponds to an element in the download request list. :rtype: list[concurrent.futures.Future] """ _check_if_must_download(request_list, redownload) LOGGER.debug("Using max_threads=%s for %s requests", max_threads, len(request_list)) with concurrent.futures.ThreadPoolExecutor(max_workers=max_threads) as executor: return [executor.submit(execute_download_request, request) for request in request_list]
[ "def", "download_data", "(", "request_list", ",", "redownload", "=", "False", ",", "max_threads", "=", "None", ")", ":", "_check_if_must_download", "(", "request_list", ",", "redownload", ")", "LOGGER", ".", "debug", "(", "\"Using max_threads=%s for %s requests\"", ",", "max_threads", ",", "len", "(", "request_list", ")", ")", "with", "concurrent", ".", "futures", ".", "ThreadPoolExecutor", "(", "max_workers", "=", "max_threads", ")", "as", "executor", ":", "return", "[", "executor", ".", "submit", "(", "execute_download_request", ",", "request", ")", "for", "request", "in", "request_list", "]" ]
Download all requested data or read data from disk, if already downloaded and available and redownload is not required. :param request_list: list of DownloadRequests :type request_list: list of DownloadRequests :param redownload: if ``True``, download again the data, although it was already downloaded and is available on the disk. Default is ``False``. :type redownload: bool :param max_threads: number of threads to use when downloading data; default is ``max_threads=None`` which by default uses the number of processors on the system :type max_threads: int :return: list of Futures holding downloaded data, where each element in the list corresponds to an element in the download request list. :rtype: list[concurrent.futures.Future]
[ "Download", "all", "requested", "data", "or", "read", "data", "from", "disk", "if", "already", "downloaded", "and", "available", "and", "redownload", "is", "not", "required", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L178-L199
229,246
sentinel-hub/sentinelhub-py
sentinelhub/download.py
_check_if_must_download
def _check_if_must_download(request_list, redownload): """ Updates request.will_download attribute of each request in request_list. **Note:** the function mutates the elements of the list! :param request_list: a list of ``DownloadRequest`` instances :type: list[DownloadRequest] :param redownload: tells whether to download the data again or not :type: bool """ for request in request_list: request.will_download = (request.save_response or request.return_data) \ and (not request.is_downloaded() or redownload)
python
def _check_if_must_download(request_list, redownload): """ Updates request.will_download attribute of each request in request_list. **Note:** the function mutates the elements of the list! :param request_list: a list of ``DownloadRequest`` instances :type: list[DownloadRequest] :param redownload: tells whether to download the data again or not :type: bool """ for request in request_list: request.will_download = (request.save_response or request.return_data) \ and (not request.is_downloaded() or redownload)
[ "def", "_check_if_must_download", "(", "request_list", ",", "redownload", ")", ":", "for", "request", "in", "request_list", ":", "request", ".", "will_download", "=", "(", "request", ".", "save_response", "or", "request", ".", "return_data", ")", "and", "(", "not", "request", ".", "is_downloaded", "(", ")", "or", "redownload", ")" ]
Updates request.will_download attribute of each request in request_list. **Note:** the function mutates the elements of the list! :param request_list: a list of ``DownloadRequest`` instances :type: list[DownloadRequest] :param redownload: tells whether to download the data again or not :type: bool
[ "Updates", "request", ".", "will_download", "attribute", "of", "each", "request", "in", "request_list", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L202-L215
229,247
sentinel-hub/sentinelhub-py
sentinelhub/download.py
execute_download_request
def execute_download_request(request): """ Executes download request. :param request: DownloadRequest to be executed :type request: DownloadRequest :return: downloaded data or None :rtype: numpy array, other possible data type or None :raises: DownloadFailedException """ if request.save_response and request.data_folder is None: raise ValueError('Data folder is not specified. ' 'Please give a data folder name in the initialization of your request.') if not request.will_download: return None try_num = SHConfig().max_download_attempts response = None while try_num > 0: try: if request.is_aws_s3(): response = _do_aws_request(request) response_content = response['Body'].read() else: response = _do_request(request) response.raise_for_status() response_content = response.content LOGGER.debug('Successful download from %s', request.url) break except requests.RequestException as exception: try_num -= 1 if try_num > 0 and (_is_temporal_problem(exception) or (isinstance(exception, requests.HTTPError) and exception.response.status_code >= requests.status_codes.codes.INTERNAL_SERVER_ERROR) or _request_limit_reached(exception)): LOGGER.debug('Download attempt failed: %s\n%d attempts left, will retry in %ds', exception, try_num, SHConfig().download_sleep_time) sleep_time = SHConfig().download_sleep_time if _request_limit_reached(exception): sleep_time = max(sleep_time, 60) time.sleep(sleep_time) else: if request.url.startswith(SHConfig().aws_metadata_url) and \ isinstance(exception, requests.HTTPError) and \ exception.response.status_code == requests.status_codes.codes.NOT_FOUND: raise AwsDownloadFailedException('File in location %s is missing' % request.url) raise DownloadFailedException(_create_download_failed_message(exception, request.url)) _save_if_needed(request, response_content) if request.return_data: return decode_data(response_content, request.data_type, entire_response=response) return None
python
def execute_download_request(request): """ Executes download request. :param request: DownloadRequest to be executed :type request: DownloadRequest :return: downloaded data or None :rtype: numpy array, other possible data type or None :raises: DownloadFailedException """ if request.save_response and request.data_folder is None: raise ValueError('Data folder is not specified. ' 'Please give a data folder name in the initialization of your request.') if not request.will_download: return None try_num = SHConfig().max_download_attempts response = None while try_num > 0: try: if request.is_aws_s3(): response = _do_aws_request(request) response_content = response['Body'].read() else: response = _do_request(request) response.raise_for_status() response_content = response.content LOGGER.debug('Successful download from %s', request.url) break except requests.RequestException as exception: try_num -= 1 if try_num > 0 and (_is_temporal_problem(exception) or (isinstance(exception, requests.HTTPError) and exception.response.status_code >= requests.status_codes.codes.INTERNAL_SERVER_ERROR) or _request_limit_reached(exception)): LOGGER.debug('Download attempt failed: %s\n%d attempts left, will retry in %ds', exception, try_num, SHConfig().download_sleep_time) sleep_time = SHConfig().download_sleep_time if _request_limit_reached(exception): sleep_time = max(sleep_time, 60) time.sleep(sleep_time) else: if request.url.startswith(SHConfig().aws_metadata_url) and \ isinstance(exception, requests.HTTPError) and \ exception.response.status_code == requests.status_codes.codes.NOT_FOUND: raise AwsDownloadFailedException('File in location %s is missing' % request.url) raise DownloadFailedException(_create_download_failed_message(exception, request.url)) _save_if_needed(request, response_content) if request.return_data: return decode_data(response_content, request.data_type, entire_response=response) return None
[ "def", "execute_download_request", "(", "request", ")", ":", "if", "request", ".", "save_response", "and", "request", ".", "data_folder", "is", "None", ":", "raise", "ValueError", "(", "'Data folder is not specified. '", "'Please give a data folder name in the initialization of your request.'", ")", "if", "not", "request", ".", "will_download", ":", "return", "None", "try_num", "=", "SHConfig", "(", ")", ".", "max_download_attempts", "response", "=", "None", "while", "try_num", ">", "0", ":", "try", ":", "if", "request", ".", "is_aws_s3", "(", ")", ":", "response", "=", "_do_aws_request", "(", "request", ")", "response_content", "=", "response", "[", "'Body'", "]", ".", "read", "(", ")", "else", ":", "response", "=", "_do_request", "(", "request", ")", "response", ".", "raise_for_status", "(", ")", "response_content", "=", "response", ".", "content", "LOGGER", ".", "debug", "(", "'Successful download from %s'", ",", "request", ".", "url", ")", "break", "except", "requests", ".", "RequestException", "as", "exception", ":", "try_num", "-=", "1", "if", "try_num", ">", "0", "and", "(", "_is_temporal_problem", "(", "exception", ")", "or", "(", "isinstance", "(", "exception", ",", "requests", ".", "HTTPError", ")", "and", "exception", ".", "response", ".", "status_code", ">=", "requests", ".", "status_codes", ".", "codes", ".", "INTERNAL_SERVER_ERROR", ")", "or", "_request_limit_reached", "(", "exception", ")", ")", ":", "LOGGER", ".", "debug", "(", "'Download attempt failed: %s\\n%d attempts left, will retry in %ds'", ",", "exception", ",", "try_num", ",", "SHConfig", "(", ")", ".", "download_sleep_time", ")", "sleep_time", "=", "SHConfig", "(", ")", ".", "download_sleep_time", "if", "_request_limit_reached", "(", "exception", ")", ":", "sleep_time", "=", "max", "(", "sleep_time", ",", "60", ")", "time", ".", "sleep", "(", "sleep_time", ")", "else", ":", "if", "request", ".", "url", ".", "startswith", "(", "SHConfig", "(", ")", ".", "aws_metadata_url", ")", "and", "isinstance", "(", "exception", ",", "requests", ".", "HTTPError", ")", "and", "exception", ".", "response", ".", "status_code", "==", "requests", ".", "status_codes", ".", "codes", ".", "NOT_FOUND", ":", "raise", "AwsDownloadFailedException", "(", "'File in location %s is missing'", "%", "request", ".", "url", ")", "raise", "DownloadFailedException", "(", "_create_download_failed_message", "(", "exception", ",", "request", ".", "url", ")", ")", "_save_if_needed", "(", "request", ",", "response_content", ")", "if", "request", ".", "return_data", ":", "return", "decode_data", "(", "response_content", ",", "request", ".", "data_type", ",", "entire_response", "=", "response", ")", "return", "None" ]
Executes download request. :param request: DownloadRequest to be executed :type request: DownloadRequest :return: downloaded data or None :rtype: numpy array, other possible data type or None :raises: DownloadFailedException
[ "Executes", "download", "request", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L218-L270
229,248
sentinel-hub/sentinelhub-py
sentinelhub/download.py
_is_temporal_problem
def _is_temporal_problem(exception): """ Checks if the obtained exception is temporal and if download attempt should be repeated :param exception: Exception raised during download :type exception: Exception :return: True if exception is temporal and False otherwise :rtype: bool """ try: return isinstance(exception, (requests.ConnectionError, requests.Timeout)) except AttributeError: # Earlier requests versions might not have requests.Timeout return isinstance(exception, requests.ConnectionError)
python
def _is_temporal_problem(exception): """ Checks if the obtained exception is temporal and if download attempt should be repeated :param exception: Exception raised during download :type exception: Exception :return: True if exception is temporal and False otherwise :rtype: bool """ try: return isinstance(exception, (requests.ConnectionError, requests.Timeout)) except AttributeError: # Earlier requests versions might not have requests.Timeout return isinstance(exception, requests.ConnectionError)
[ "def", "_is_temporal_problem", "(", "exception", ")", ":", "try", ":", "return", "isinstance", "(", "exception", ",", "(", "requests", ".", "ConnectionError", ",", "requests", ".", "Timeout", ")", ")", "except", "AttributeError", ":", "# Earlier requests versions might not have requests.Timeout", "return", "isinstance", "(", "exception", ",", "requests", ".", "ConnectionError", ")" ]
Checks if the obtained exception is temporal and if download attempt should be repeated :param exception: Exception raised during download :type exception: Exception :return: True if exception is temporal and False otherwise :rtype: bool
[ "Checks", "if", "the", "obtained", "exception", "is", "temporal", "and", "if", "download", "attempt", "should", "be", "repeated" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L325-L336
229,249
sentinel-hub/sentinelhub-py
sentinelhub/download.py
_create_download_failed_message
def _create_download_failed_message(exception, url): """ Creates message describing why download has failed :param exception: Exception raised during download :type exception: Exception :param url: An URL from where download was attempted :type url: str :return: Error message :rtype: str """ message = 'Failed to download from:\n{}\nwith {}:\n{}'.format(url, exception.__class__.__name__, exception) if _is_temporal_problem(exception): if isinstance(exception, requests.ConnectionError): message += '\nPlease check your internet connection and try again.' else: message += '\nThere might be a problem in connection or the server failed to process ' \ 'your request. Please try again.' elif isinstance(exception, requests.HTTPError): try: server_message = '' for elem in decode_data(exception.response.content, MimeType.XML): if 'ServiceException' in elem.tag or 'Message' in elem.tag: server_message += elem.text.strip('\n\t ') except ElementTree.ParseError: server_message = exception.response.text message += '\nServer response: "{}"'.format(server_message) return message
python
def _create_download_failed_message(exception, url): """ Creates message describing why download has failed :param exception: Exception raised during download :type exception: Exception :param url: An URL from where download was attempted :type url: str :return: Error message :rtype: str """ message = 'Failed to download from:\n{}\nwith {}:\n{}'.format(url, exception.__class__.__name__, exception) if _is_temporal_problem(exception): if isinstance(exception, requests.ConnectionError): message += '\nPlease check your internet connection and try again.' else: message += '\nThere might be a problem in connection or the server failed to process ' \ 'your request. Please try again.' elif isinstance(exception, requests.HTTPError): try: server_message = '' for elem in decode_data(exception.response.content, MimeType.XML): if 'ServiceException' in elem.tag or 'Message' in elem.tag: server_message += elem.text.strip('\n\t ') except ElementTree.ParseError: server_message = exception.response.text message += '\nServer response: "{}"'.format(server_message) return message
[ "def", "_create_download_failed_message", "(", "exception", ",", "url", ")", ":", "message", "=", "'Failed to download from:\\n{}\\nwith {}:\\n{}'", ".", "format", "(", "url", ",", "exception", ".", "__class__", ".", "__name__", ",", "exception", ")", "if", "_is_temporal_problem", "(", "exception", ")", ":", "if", "isinstance", "(", "exception", ",", "requests", ".", "ConnectionError", ")", ":", "message", "+=", "'\\nPlease check your internet connection and try again.'", "else", ":", "message", "+=", "'\\nThere might be a problem in connection or the server failed to process '", "'your request. Please try again.'", "elif", "isinstance", "(", "exception", ",", "requests", ".", "HTTPError", ")", ":", "try", ":", "server_message", "=", "''", "for", "elem", "in", "decode_data", "(", "exception", ".", "response", ".", "content", ",", "MimeType", ".", "XML", ")", ":", "if", "'ServiceException'", "in", "elem", ".", "tag", "or", "'Message'", "in", "elem", ".", "tag", ":", "server_message", "+=", "elem", ".", "text", ".", "strip", "(", "'\\n\\t '", ")", "except", "ElementTree", ".", "ParseError", ":", "server_message", "=", "exception", ".", "response", ".", "text", "message", "+=", "'\\nServer response: \"{}\"'", ".", "format", "(", "server_message", ")", "return", "message" ]
Creates message describing why download has failed :param exception: Exception raised during download :type exception: Exception :param url: An URL from where download was attempted :type url: str :return: Error message :rtype: str
[ "Creates", "message", "describing", "why", "download", "has", "failed" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L352-L380
229,250
sentinel-hub/sentinelhub-py
sentinelhub/download.py
decode_data
def decode_data(response_content, data_type, entire_response=None): """ Interprets downloaded data and returns it. :param response_content: downloaded data (i.e. json, png, tiff, xml, zip, ... file) :type response_content: bytes :param data_type: expected downloaded data type :type data_type: constants.MimeType :param entire_response: A response obtained from execution of download request :type entire_response: requests.Response or dict or None :return: downloaded data :rtype: numpy array in case of image data type, or other possible data type :raises: ValueError """ LOGGER.debug('data_type=%s', data_type) if data_type is MimeType.JSON: if isinstance(entire_response, requests.Response): return entire_response.json() return json.loads(response_content.decode('utf-8')) if MimeType.is_image_format(data_type): return decode_image(response_content, data_type) if data_type is MimeType.XML or data_type is MimeType.GML or data_type is MimeType.SAFE: return ElementTree.fromstring(response_content) try: return { MimeType.RAW: response_content, MimeType.TXT: response_content, MimeType.REQUESTS_RESPONSE: entire_response, MimeType.ZIP: BytesIO(response_content) }[data_type] except KeyError: raise ValueError('Unknown response data type {}'.format(data_type))
python
def decode_data(response_content, data_type, entire_response=None): """ Interprets downloaded data and returns it. :param response_content: downloaded data (i.e. json, png, tiff, xml, zip, ... file) :type response_content: bytes :param data_type: expected downloaded data type :type data_type: constants.MimeType :param entire_response: A response obtained from execution of download request :type entire_response: requests.Response or dict or None :return: downloaded data :rtype: numpy array in case of image data type, or other possible data type :raises: ValueError """ LOGGER.debug('data_type=%s', data_type) if data_type is MimeType.JSON: if isinstance(entire_response, requests.Response): return entire_response.json() return json.loads(response_content.decode('utf-8')) if MimeType.is_image_format(data_type): return decode_image(response_content, data_type) if data_type is MimeType.XML or data_type is MimeType.GML or data_type is MimeType.SAFE: return ElementTree.fromstring(response_content) try: return { MimeType.RAW: response_content, MimeType.TXT: response_content, MimeType.REQUESTS_RESPONSE: entire_response, MimeType.ZIP: BytesIO(response_content) }[data_type] except KeyError: raise ValueError('Unknown response data type {}'.format(data_type))
[ "def", "decode_data", "(", "response_content", ",", "data_type", ",", "entire_response", "=", "None", ")", ":", "LOGGER", ".", "debug", "(", "'data_type=%s'", ",", "data_type", ")", "if", "data_type", "is", "MimeType", ".", "JSON", ":", "if", "isinstance", "(", "entire_response", ",", "requests", ".", "Response", ")", ":", "return", "entire_response", ".", "json", "(", ")", "return", "json", ".", "loads", "(", "response_content", ".", "decode", "(", "'utf-8'", ")", ")", "if", "MimeType", ".", "is_image_format", "(", "data_type", ")", ":", "return", "decode_image", "(", "response_content", ",", "data_type", ")", "if", "data_type", "is", "MimeType", ".", "XML", "or", "data_type", "is", "MimeType", ".", "GML", "or", "data_type", "is", "MimeType", ".", "SAFE", ":", "return", "ElementTree", ".", "fromstring", "(", "response_content", ")", "try", ":", "return", "{", "MimeType", ".", "RAW", ":", "response_content", ",", "MimeType", ".", "TXT", ":", "response_content", ",", "MimeType", ".", "REQUESTS_RESPONSE", ":", "entire_response", ",", "MimeType", ".", "ZIP", ":", "BytesIO", "(", "response_content", ")", "}", "[", "data_type", "]", "except", "KeyError", ":", "raise", "ValueError", "(", "'Unknown response data type {}'", ".", "format", "(", "data_type", ")", ")" ]
Interprets downloaded data and returns it. :param response_content: downloaded data (i.e. json, png, tiff, xml, zip, ... file) :type response_content: bytes :param data_type: expected downloaded data type :type data_type: constants.MimeType :param entire_response: A response obtained from execution of download request :type entire_response: requests.Response or dict or None :return: downloaded data :rtype: numpy array in case of image data type, or other possible data type :raises: ValueError
[ "Interprets", "downloaded", "data", "and", "returns", "it", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L398-L430
229,251
sentinel-hub/sentinelhub-py
sentinelhub/download.py
decode_image
def decode_image(data, image_type): """ Decodes the image provided in various formats, i.e. png, 16-bit float tiff, 32-bit float tiff, jp2 and returns it as an numpy array :param data: image in its original format :type data: any of possible image types :param image_type: expected image format :type image_type: constants.MimeType :return: image as numpy array :rtype: numpy array :raises: ImageDecodingError """ bytes_data = BytesIO(data) if image_type.is_tiff_format(): image = tiff.imread(bytes_data) else: image = np.array(Image.open(bytes_data)) if image_type is MimeType.JP2: try: bit_depth = get_jp2_bit_depth(bytes_data) image = fix_jp2_image(image, bit_depth) except ValueError: pass if image is None: raise ImageDecodingError('Unable to decode image') return image
python
def decode_image(data, image_type): """ Decodes the image provided in various formats, i.e. png, 16-bit float tiff, 32-bit float tiff, jp2 and returns it as an numpy array :param data: image in its original format :type data: any of possible image types :param image_type: expected image format :type image_type: constants.MimeType :return: image as numpy array :rtype: numpy array :raises: ImageDecodingError """ bytes_data = BytesIO(data) if image_type.is_tiff_format(): image = tiff.imread(bytes_data) else: image = np.array(Image.open(bytes_data)) if image_type is MimeType.JP2: try: bit_depth = get_jp2_bit_depth(bytes_data) image = fix_jp2_image(image, bit_depth) except ValueError: pass if image is None: raise ImageDecodingError('Unable to decode image') return image
[ "def", "decode_image", "(", "data", ",", "image_type", ")", ":", "bytes_data", "=", "BytesIO", "(", "data", ")", "if", "image_type", ".", "is_tiff_format", "(", ")", ":", "image", "=", "tiff", ".", "imread", "(", "bytes_data", ")", "else", ":", "image", "=", "np", ".", "array", "(", "Image", ".", "open", "(", "bytes_data", ")", ")", "if", "image_type", "is", "MimeType", ".", "JP2", ":", "try", ":", "bit_depth", "=", "get_jp2_bit_depth", "(", "bytes_data", ")", "image", "=", "fix_jp2_image", "(", "image", ",", "bit_depth", ")", "except", "ValueError", ":", "pass", "if", "image", "is", "None", ":", "raise", "ImageDecodingError", "(", "'Unable to decode image'", ")", "return", "image" ]
Decodes the image provided in various formats, i.e. png, 16-bit float tiff, 32-bit float tiff, jp2 and returns it as an numpy array :param data: image in its original format :type data: any of possible image types :param image_type: expected image format :type image_type: constants.MimeType :return: image as numpy array :rtype: numpy array :raises: ImageDecodingError
[ "Decodes", "the", "image", "provided", "in", "various", "formats", "i", ".", "e", ".", "png", "16", "-", "bit", "float", "tiff", "32", "-", "bit", "float", "tiff", "jp2", "and", "returns", "it", "as", "an", "numpy", "array" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L433-L460
229,252
sentinel-hub/sentinelhub-py
sentinelhub/download.py
get_json
def get_json(url, post_values=None, headers=None): """ Download request as JSON data type :param url: url to Sentinel Hub's services or other sources from where the data is downloaded :type url: str :param post_values: form encoded data to send in POST request. Default is ``None`` :type post_values: dict :param headers: add HTTP headers to request. Default is ``None`` :type headers: dict :return: request response as JSON instance :rtype: JSON instance or None :raises: RunTimeError """ json_headers = {} if headers is None else headers.copy() if post_values is None: request_type = RequestType.GET else: request_type = RequestType.POST json_headers = {**json_headers, **{'Content-Type': MimeType.get_string(MimeType.JSON)}} request = DownloadRequest(url=url, headers=json_headers, request_type=request_type, post_values=post_values, save_response=False, return_data=True, data_type=MimeType.JSON) return execute_download_request(request)
python
def get_json(url, post_values=None, headers=None): """ Download request as JSON data type :param url: url to Sentinel Hub's services or other sources from where the data is downloaded :type url: str :param post_values: form encoded data to send in POST request. Default is ``None`` :type post_values: dict :param headers: add HTTP headers to request. Default is ``None`` :type headers: dict :return: request response as JSON instance :rtype: JSON instance or None :raises: RunTimeError """ json_headers = {} if headers is None else headers.copy() if post_values is None: request_type = RequestType.GET else: request_type = RequestType.POST json_headers = {**json_headers, **{'Content-Type': MimeType.get_string(MimeType.JSON)}} request = DownloadRequest(url=url, headers=json_headers, request_type=request_type, post_values=post_values, save_response=False, return_data=True, data_type=MimeType.JSON) return execute_download_request(request)
[ "def", "get_json", "(", "url", ",", "post_values", "=", "None", ",", "headers", "=", "None", ")", ":", "json_headers", "=", "{", "}", "if", "headers", "is", "None", "else", "headers", ".", "copy", "(", ")", "if", "post_values", "is", "None", ":", "request_type", "=", "RequestType", ".", "GET", "else", ":", "request_type", "=", "RequestType", ".", "POST", "json_headers", "=", "{", "*", "*", "json_headers", ",", "*", "*", "{", "'Content-Type'", ":", "MimeType", ".", "get_string", "(", "MimeType", ".", "JSON", ")", "}", "}", "request", "=", "DownloadRequest", "(", "url", "=", "url", ",", "headers", "=", "json_headers", ",", "request_type", "=", "request_type", ",", "post_values", "=", "post_values", ",", "save_response", "=", "False", ",", "return_data", "=", "True", ",", "data_type", "=", "MimeType", ".", "JSON", ")", "return", "execute_download_request", "(", "request", ")" ]
Download request as JSON data type :param url: url to Sentinel Hub's services or other sources from where the data is downloaded :type url: str :param post_values: form encoded data to send in POST request. Default is ``None`` :type post_values: dict :param headers: add HTTP headers to request. Default is ``None`` :type headers: dict :return: request response as JSON instance :rtype: JSON instance or None :raises: RunTimeError
[ "Download", "request", "as", "JSON", "data", "type" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L463-L488
229,253
sentinel-hub/sentinelhub-py
sentinelhub/download.py
get_xml
def get_xml(url): """ Download request as XML data type :param url: url to Sentinel Hub's services or other sources from where the data is downloaded :type url: str :return: request response as XML instance :rtype: XML instance or None :raises: RunTimeError """ request = DownloadRequest(url=url, request_type=RequestType.GET, save_response=False, return_data=True, data_type=MimeType.XML) return execute_download_request(request)
python
def get_xml(url): """ Download request as XML data type :param url: url to Sentinel Hub's services or other sources from where the data is downloaded :type url: str :return: request response as XML instance :rtype: XML instance or None :raises: RunTimeError """ request = DownloadRequest(url=url, request_type=RequestType.GET, save_response=False, return_data=True, data_type=MimeType.XML) return execute_download_request(request)
[ "def", "get_xml", "(", "url", ")", ":", "request", "=", "DownloadRequest", "(", "url", "=", "url", ",", "request_type", "=", "RequestType", ".", "GET", ",", "save_response", "=", "False", ",", "return_data", "=", "True", ",", "data_type", "=", "MimeType", ".", "XML", ")", "return", "execute_download_request", "(", "request", ")" ]
Download request as XML data type :param url: url to Sentinel Hub's services or other sources from where the data is downloaded :type url: str :return: request response as XML instance :rtype: XML instance or None :raises: RunTimeError
[ "Download", "request", "as", "XML", "data", "type" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L491-L503
229,254
sentinel-hub/sentinelhub-py
sentinelhub/download.py
DownloadRequest.is_downloaded
def is_downloaded(self): """ Checks if data for this request has already been downloaded and is saved to disk. :return: returns ``True`` if data for this request has already been downloaded and is saved to disk. :rtype: bool """ if self.file_path is None: return False return os.path.exists(self.file_path)
python
def is_downloaded(self): """ Checks if data for this request has already been downloaded and is saved to disk. :return: returns ``True`` if data for this request has already been downloaded and is saved to disk. :rtype: bool """ if self.file_path is None: return False return os.path.exists(self.file_path)
[ "def", "is_downloaded", "(", "self", ")", ":", "if", "self", ".", "file_path", "is", "None", ":", "return", "False", "return", "os", ".", "path", ".", "exists", "(", "self", ".", "file_path", ")" ]
Checks if data for this request has already been downloaded and is saved to disk. :return: returns ``True`` if data for this request has already been downloaded and is saved to disk. :rtype: bool
[ "Checks", "if", "data", "for", "this", "request", "has", "already", "been", "downloaded", "and", "is", "saved", "to", "disk", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/download.py#L159-L167
229,255
sentinel-hub/sentinelhub-py
sentinelhub/opensearch.py
get_area_info
def get_area_info(bbox, date_interval, maxcc=None): """ Get information about all images from specified area and time range :param bbox: bounding box of requested area :type bbox: geometry.BBox :param date_interval: a pair of time strings in ISO8601 format :type date_interval: tuple(str) :param maxcc: filter images by maximum percentage of cloud coverage :type maxcc: float in range [0, 1] or None :return: list of dictionaries containing info provided by Opensearch REST service :rtype: list(dict) """ result_list = search_iter(bbox=bbox, start_date=date_interval[0], end_date=date_interval[1]) if maxcc: return reduce_by_maxcc(result_list, maxcc) return result_list
python
def get_area_info(bbox, date_interval, maxcc=None): """ Get information about all images from specified area and time range :param bbox: bounding box of requested area :type bbox: geometry.BBox :param date_interval: a pair of time strings in ISO8601 format :type date_interval: tuple(str) :param maxcc: filter images by maximum percentage of cloud coverage :type maxcc: float in range [0, 1] or None :return: list of dictionaries containing info provided by Opensearch REST service :rtype: list(dict) """ result_list = search_iter(bbox=bbox, start_date=date_interval[0], end_date=date_interval[1]) if maxcc: return reduce_by_maxcc(result_list, maxcc) return result_list
[ "def", "get_area_info", "(", "bbox", ",", "date_interval", ",", "maxcc", "=", "None", ")", ":", "result_list", "=", "search_iter", "(", "bbox", "=", "bbox", ",", "start_date", "=", "date_interval", "[", "0", "]", ",", "end_date", "=", "date_interval", "[", "1", "]", ")", "if", "maxcc", ":", "return", "reduce_by_maxcc", "(", "result_list", ",", "maxcc", ")", "return", "result_list" ]
Get information about all images from specified area and time range :param bbox: bounding box of requested area :type bbox: geometry.BBox :param date_interval: a pair of time strings in ISO8601 format :type date_interval: tuple(str) :param maxcc: filter images by maximum percentage of cloud coverage :type maxcc: float in range [0, 1] or None :return: list of dictionaries containing info provided by Opensearch REST service :rtype: list(dict)
[ "Get", "information", "about", "all", "images", "from", "specified", "area", "and", "time", "range" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/opensearch.py#L79-L94
229,256
sentinel-hub/sentinelhub-py
sentinelhub/opensearch.py
get_area_dates
def get_area_dates(bbox, date_interval, maxcc=None): """ Get list of times of existing images from specified area and time range :param bbox: bounding box of requested area :type bbox: geometry.BBox :param date_interval: a pair of time strings in ISO8601 format :type date_interval: tuple(str) :param maxcc: filter images by maximum percentage of cloud coverage :type maxcc: float in range [0, 1] or None :return: list of time strings in ISO8601 format :rtype: list[datetime.datetime] """ area_info = get_area_info(bbox, date_interval, maxcc=maxcc) return sorted({datetime.datetime.strptime(tile_info['properties']['startDate'].strip('Z'), '%Y-%m-%dT%H:%M:%S') for tile_info in area_info})
python
def get_area_dates(bbox, date_interval, maxcc=None): """ Get list of times of existing images from specified area and time range :param bbox: bounding box of requested area :type bbox: geometry.BBox :param date_interval: a pair of time strings in ISO8601 format :type date_interval: tuple(str) :param maxcc: filter images by maximum percentage of cloud coverage :type maxcc: float in range [0, 1] or None :return: list of time strings in ISO8601 format :rtype: list[datetime.datetime] """ area_info = get_area_info(bbox, date_interval, maxcc=maxcc) return sorted({datetime.datetime.strptime(tile_info['properties']['startDate'].strip('Z'), '%Y-%m-%dT%H:%M:%S') for tile_info in area_info})
[ "def", "get_area_dates", "(", "bbox", ",", "date_interval", ",", "maxcc", "=", "None", ")", ":", "area_info", "=", "get_area_info", "(", "bbox", ",", "date_interval", ",", "maxcc", "=", "maxcc", ")", "return", "sorted", "(", "{", "datetime", ".", "datetime", ".", "strptime", "(", "tile_info", "[", "'properties'", "]", "[", "'startDate'", "]", ".", "strip", "(", "'Z'", ")", ",", "'%Y-%m-%dT%H:%M:%S'", ")", "for", "tile_info", "in", "area_info", "}", ")" ]
Get list of times of existing images from specified area and time range :param bbox: bounding box of requested area :type bbox: geometry.BBox :param date_interval: a pair of time strings in ISO8601 format :type date_interval: tuple(str) :param maxcc: filter images by maximum percentage of cloud coverage :type maxcc: float in range [0, 1] or None :return: list of time strings in ISO8601 format :rtype: list[datetime.datetime]
[ "Get", "list", "of", "times", "of", "existing", "images", "from", "specified", "area", "and", "time", "range" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/opensearch.py#L97-L113
229,257
sentinel-hub/sentinelhub-py
sentinelhub/opensearch.py
search_iter
def search_iter(tile_id=None, bbox=None, start_date=None, end_date=None, absolute_orbit=None): """ A generator function that implements OpenSearch search queries and returns results All parameters for search are optional. :param tile_id: original tile identification string provided by ESA (e.g. 'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01') :type tile_id: str :param bbox: bounding box of requested area :type bbox: geometry.BBox :param start_date: beginning of time range in ISO8601 format :type start_date: str :param end_date: end of time range in ISO8601 format :type end_date: str :param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA :type absolute_orbit: int :return: An iterator returning dictionaries with info provided by Sentinel Hub OpenSearch REST service :rtype: Iterator[dict] """ if bbox and bbox.crs is not CRS.WGS84: bbox = bbox.transform(CRS.WGS84) url_params = _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit) url_params['maxRecords'] = SHConfig().max_opensearch_records_per_query start_index = 1 while True: url_params['index'] = start_index url = '{}search.json?{}'.format(SHConfig().opensearch_url, urlencode(url_params)) LOGGER.debug("URL=%s", url) response = get_json(url) for tile_info in response["features"]: yield tile_info if len(response["features"]) < SHConfig().max_opensearch_records_per_query: break start_index += SHConfig().max_opensearch_records_per_query
python
def search_iter(tile_id=None, bbox=None, start_date=None, end_date=None, absolute_orbit=None): """ A generator function that implements OpenSearch search queries and returns results All parameters for search are optional. :param tile_id: original tile identification string provided by ESA (e.g. 'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01') :type tile_id: str :param bbox: bounding box of requested area :type bbox: geometry.BBox :param start_date: beginning of time range in ISO8601 format :type start_date: str :param end_date: end of time range in ISO8601 format :type end_date: str :param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA :type absolute_orbit: int :return: An iterator returning dictionaries with info provided by Sentinel Hub OpenSearch REST service :rtype: Iterator[dict] """ if bbox and bbox.crs is not CRS.WGS84: bbox = bbox.transform(CRS.WGS84) url_params = _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit) url_params['maxRecords'] = SHConfig().max_opensearch_records_per_query start_index = 1 while True: url_params['index'] = start_index url = '{}search.json?{}'.format(SHConfig().opensearch_url, urlencode(url_params)) LOGGER.debug("URL=%s", url) response = get_json(url) for tile_info in response["features"]: yield tile_info if len(response["features"]) < SHConfig().max_opensearch_records_per_query: break start_index += SHConfig().max_opensearch_records_per_query
[ "def", "search_iter", "(", "tile_id", "=", "None", ",", "bbox", "=", "None", ",", "start_date", "=", "None", ",", "end_date", "=", "None", ",", "absolute_orbit", "=", "None", ")", ":", "if", "bbox", "and", "bbox", ".", "crs", "is", "not", "CRS", ".", "WGS84", ":", "bbox", "=", "bbox", ".", "transform", "(", "CRS", ".", "WGS84", ")", "url_params", "=", "_prepare_url_params", "(", "tile_id", ",", "bbox", ",", "end_date", ",", "start_date", ",", "absolute_orbit", ")", "url_params", "[", "'maxRecords'", "]", "=", "SHConfig", "(", ")", ".", "max_opensearch_records_per_query", "start_index", "=", "1", "while", "True", ":", "url_params", "[", "'index'", "]", "=", "start_index", "url", "=", "'{}search.json?{}'", ".", "format", "(", "SHConfig", "(", ")", ".", "opensearch_url", ",", "urlencode", "(", "url_params", ")", ")", "LOGGER", ".", "debug", "(", "\"URL=%s\"", ",", "url", ")", "response", "=", "get_json", "(", "url", ")", "for", "tile_info", "in", "response", "[", "\"features\"", "]", ":", "yield", "tile_info", "if", "len", "(", "response", "[", "\"features\"", "]", ")", "<", "SHConfig", "(", ")", ".", "max_opensearch_records_per_query", ":", "break", "start_index", "+=", "SHConfig", "(", ")", ".", "max_opensearch_records_per_query" ]
A generator function that implements OpenSearch search queries and returns results All parameters for search are optional. :param tile_id: original tile identification string provided by ESA (e.g. 'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01') :type tile_id: str :param bbox: bounding box of requested area :type bbox: geometry.BBox :param start_date: beginning of time range in ISO8601 format :type start_date: str :param end_date: end of time range in ISO8601 format :type end_date: str :param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA :type absolute_orbit: int :return: An iterator returning dictionaries with info provided by Sentinel Hub OpenSearch REST service :rtype: Iterator[dict]
[ "A", "generator", "function", "that", "implements", "OpenSearch", "search", "queries", "and", "returns", "results" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/opensearch.py#L129-L168
229,258
sentinel-hub/sentinelhub-py
sentinelhub/opensearch.py
_prepare_url_params
def _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit): """ Constructs dict with URL params :param tile_id: original tile identification string provided by ESA (e.g. 'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01') :type tile_id: str :param bbox: bounding box of requested area in WGS84 CRS :type bbox: geometry.BBox :param start_date: beginning of time range in ISO8601 format :type start_date: str :param end_date: end of time range in ISO8601 format :type end_date: str :param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA :type absolute_orbit: int :return: dictionary with parameters as properties when arguments not None :rtype: dict """ url_params = { 'identifier': tile_id, 'startDate': start_date, 'completionDate': end_date, 'orbitNumber': absolute_orbit, 'box': bbox } return {key: str(value) for key, value in url_params.items() if value}
python
def _prepare_url_params(tile_id, bbox, end_date, start_date, absolute_orbit): """ Constructs dict with URL params :param tile_id: original tile identification string provided by ESA (e.g. 'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01') :type tile_id: str :param bbox: bounding box of requested area in WGS84 CRS :type bbox: geometry.BBox :param start_date: beginning of time range in ISO8601 format :type start_date: str :param end_date: end of time range in ISO8601 format :type end_date: str :param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA :type absolute_orbit: int :return: dictionary with parameters as properties when arguments not None :rtype: dict """ url_params = { 'identifier': tile_id, 'startDate': start_date, 'completionDate': end_date, 'orbitNumber': absolute_orbit, 'box': bbox } return {key: str(value) for key, value in url_params.items() if value}
[ "def", "_prepare_url_params", "(", "tile_id", ",", "bbox", ",", "end_date", ",", "start_date", ",", "absolute_orbit", ")", ":", "url_params", "=", "{", "'identifier'", ":", "tile_id", ",", "'startDate'", ":", "start_date", ",", "'completionDate'", ":", "end_date", ",", "'orbitNumber'", ":", "absolute_orbit", ",", "'box'", ":", "bbox", "}", "return", "{", "key", ":", "str", "(", "value", ")", "for", "key", ",", "value", "in", "url_params", ".", "items", "(", ")", "if", "value", "}" ]
Constructs dict with URL params :param tile_id: original tile identification string provided by ESA (e.g. 'S2A_OPER_MSI_L1C_TL_SGS__20160109T230542_A002870_T10UEV_N02.01') :type tile_id: str :param bbox: bounding box of requested area in WGS84 CRS :type bbox: geometry.BBox :param start_date: beginning of time range in ISO8601 format :type start_date: str :param end_date: end of time range in ISO8601 format :type end_date: str :param absolute_orbit: An absolute orbit number of Sentinel-2 L1C products as defined by ESA :type absolute_orbit: int :return: dictionary with parameters as properties when arguments not None :rtype: dict
[ "Constructs", "dict", "with", "URL", "params" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/opensearch.py#L171-L195
229,259
sentinel-hub/sentinelhub-py
sentinelhub/aws_safe.py
_edit_name
def _edit_name(name, code, add_code=None, delete_end=False): """ Helping function for creating file names in .SAFE format :param name: initial string :type name: str :param code: :type code: str :param add_code: :type add_code: str or None :param delete_end: :type delete_end: bool :return: edited string :rtype: str """ info = name.split('_') info[2] = code if add_code is not None: info[3] = add_code if delete_end: info.pop() return '_'.join(info)
python
def _edit_name(name, code, add_code=None, delete_end=False): """ Helping function for creating file names in .SAFE format :param name: initial string :type name: str :param code: :type code: str :param add_code: :type add_code: str or None :param delete_end: :type delete_end: bool :return: edited string :rtype: str """ info = name.split('_') info[2] = code if add_code is not None: info[3] = add_code if delete_end: info.pop() return '_'.join(info)
[ "def", "_edit_name", "(", "name", ",", "code", ",", "add_code", "=", "None", ",", "delete_end", "=", "False", ")", ":", "info", "=", "name", ".", "split", "(", "'_'", ")", "info", "[", "2", "]", "=", "code", "if", "add_code", "is", "not", "None", ":", "info", "[", "3", "]", "=", "add_code", "if", "delete_end", ":", "info", ".", "pop", "(", ")", "return", "'_'", ".", "join", "(", "info", ")" ]
Helping function for creating file names in .SAFE format :param name: initial string :type name: str :param code: :type code: str :param add_code: :type add_code: str or None :param delete_end: :type delete_end: bool :return: edited string :rtype: str
[ "Helping", "function", "for", "creating", "file", "names", "in", ".", "SAFE", "format" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws_safe.py#L362-L383
229,260
sentinel-hub/sentinelhub-py
sentinelhub/aws_safe.py
SafeProduct.get_requests
def get_requests(self): """ Creates product structure and returns list of files for download :return: list of download requests :rtype: list(download.DownloadRequest) """ safe = self.get_safe_struct() self.download_list = [] self.structure_recursion(safe, self.parent_folder) self.sort_download_list() return self.download_list, self.folder_list
python
def get_requests(self): """ Creates product structure and returns list of files for download :return: list of download requests :rtype: list(download.DownloadRequest) """ safe = self.get_safe_struct() self.download_list = [] self.structure_recursion(safe, self.parent_folder) self.sort_download_list() return self.download_list, self.folder_list
[ "def", "get_requests", "(", "self", ")", ":", "safe", "=", "self", ".", "get_safe_struct", "(", ")", "self", ".", "download_list", "=", "[", "]", "self", ".", "structure_recursion", "(", "safe", ",", "self", ".", "parent_folder", ")", "self", ".", "sort_download_list", "(", ")", "return", "self", ".", "download_list", ",", "self", ".", "folder_list" ]
Creates product structure and returns list of files for download :return: list of download requests :rtype: list(download.DownloadRequest)
[ "Creates", "product", "structure", "and", "returns", "list", "of", "files", "for", "download" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws_safe.py#L14-L26
229,261
sentinel-hub/sentinelhub-py
sentinelhub/aws_safe.py
SafeProduct.get_safe_struct
def get_safe_struct(self): """ Describes a structure inside tile folder of ESA product .SAFE structure :return: nested dictionaries representing .SAFE structure :rtype: dict """ safe = {} main_folder = self.get_main_folder() safe[main_folder] = {} safe[main_folder][AwsConstants.AUX_DATA] = {} safe[main_folder][AwsConstants.DATASTRIP] = {} datastrip_list = self.get_datastrip_list() for datastrip_folder, datastrip_url in datastrip_list: safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder] = {} safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][AwsConstants.QI_DATA] = {} # S-2 L1C reports are on AWS only stored with tiles and without RADIOMETRIC_QUALITY if self.has_reports() and self.data_source is DataSource.SENTINEL2_L2A: for metafile in AwsConstants.QUALITY_REPORTS: metafile_name = self.add_file_extension(metafile) safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][AwsConstants.QI_DATA][ metafile_name] = '{}/qi/{}'.format(datastrip_url, metafile_name) safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][ self.get_datastrip_metadata_name(datastrip_folder)] = '{}/{}'.format( datastrip_url, self.add_file_extension(AwsConstants.METADATA)) safe[main_folder][AwsConstants.GRANULE] = {} for tile_info in self.product_info['tiles']: tile_name, date, aws_index = self.url_to_tile(self.get_tile_url(tile_info)) if self.tile_list is None or AwsTile.parse_tile_name(tile_name) in self.tile_list: tile_struct = SafeTile(tile_name, date, aws_index, parent_folder=None, bands=self.bands, metafiles=self.metafiles, data_source=self.data_source).get_safe_struct() for tile_name, safe_struct in tile_struct.items(): safe[main_folder][AwsConstants.GRANULE][tile_name] = safe_struct safe[main_folder][AwsConstants.HTML] = {} # AWS doesn't have this data safe[main_folder][AwsConstants.INFO] = {} # AWS doesn't have this data safe[main_folder][self.get_product_metadata_name()] = self.get_url(AwsConstants.METADATA) safe[main_folder]['INSPIRE.xml'] = self.get_url(AwsConstants.INSPIRE) safe[main_folder][self.add_file_extension(AwsConstants.MANIFEST)] = self.get_url(AwsConstants.MANIFEST) if self.is_early_compact_l2a(): safe[main_folder]['L2A_Manifest.xml'] = self.get_url(AwsConstants.L2A_MANIFEST) safe[main_folder][self.get_report_name()] = self.get_url(AwsConstants.REPORT) if self.safe_type == EsaSafeType.OLD_TYPE and self.baseline != '02.02': safe[main_folder][_edit_name(self.product_id, 'BWI') + '.png'] = self.get_url(AwsConstants.PREVIEW, MimeType.PNG) return safe
python
def get_safe_struct(self): """ Describes a structure inside tile folder of ESA product .SAFE structure :return: nested dictionaries representing .SAFE structure :rtype: dict """ safe = {} main_folder = self.get_main_folder() safe[main_folder] = {} safe[main_folder][AwsConstants.AUX_DATA] = {} safe[main_folder][AwsConstants.DATASTRIP] = {} datastrip_list = self.get_datastrip_list() for datastrip_folder, datastrip_url in datastrip_list: safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder] = {} safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][AwsConstants.QI_DATA] = {} # S-2 L1C reports are on AWS only stored with tiles and without RADIOMETRIC_QUALITY if self.has_reports() and self.data_source is DataSource.SENTINEL2_L2A: for metafile in AwsConstants.QUALITY_REPORTS: metafile_name = self.add_file_extension(metafile) safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][AwsConstants.QI_DATA][ metafile_name] = '{}/qi/{}'.format(datastrip_url, metafile_name) safe[main_folder][AwsConstants.DATASTRIP][datastrip_folder][ self.get_datastrip_metadata_name(datastrip_folder)] = '{}/{}'.format( datastrip_url, self.add_file_extension(AwsConstants.METADATA)) safe[main_folder][AwsConstants.GRANULE] = {} for tile_info in self.product_info['tiles']: tile_name, date, aws_index = self.url_to_tile(self.get_tile_url(tile_info)) if self.tile_list is None or AwsTile.parse_tile_name(tile_name) in self.tile_list: tile_struct = SafeTile(tile_name, date, aws_index, parent_folder=None, bands=self.bands, metafiles=self.metafiles, data_source=self.data_source).get_safe_struct() for tile_name, safe_struct in tile_struct.items(): safe[main_folder][AwsConstants.GRANULE][tile_name] = safe_struct safe[main_folder][AwsConstants.HTML] = {} # AWS doesn't have this data safe[main_folder][AwsConstants.INFO] = {} # AWS doesn't have this data safe[main_folder][self.get_product_metadata_name()] = self.get_url(AwsConstants.METADATA) safe[main_folder]['INSPIRE.xml'] = self.get_url(AwsConstants.INSPIRE) safe[main_folder][self.add_file_extension(AwsConstants.MANIFEST)] = self.get_url(AwsConstants.MANIFEST) if self.is_early_compact_l2a(): safe[main_folder]['L2A_Manifest.xml'] = self.get_url(AwsConstants.L2A_MANIFEST) safe[main_folder][self.get_report_name()] = self.get_url(AwsConstants.REPORT) if self.safe_type == EsaSafeType.OLD_TYPE and self.baseline != '02.02': safe[main_folder][_edit_name(self.product_id, 'BWI') + '.png'] = self.get_url(AwsConstants.PREVIEW, MimeType.PNG) return safe
[ "def", "get_safe_struct", "(", "self", ")", ":", "safe", "=", "{", "}", "main_folder", "=", "self", ".", "get_main_folder", "(", ")", "safe", "[", "main_folder", "]", "=", "{", "}", "safe", "[", "main_folder", "]", "[", "AwsConstants", ".", "AUX_DATA", "]", "=", "{", "}", "safe", "[", "main_folder", "]", "[", "AwsConstants", ".", "DATASTRIP", "]", "=", "{", "}", "datastrip_list", "=", "self", ".", "get_datastrip_list", "(", ")", "for", "datastrip_folder", ",", "datastrip_url", "in", "datastrip_list", ":", "safe", "[", "main_folder", "]", "[", "AwsConstants", ".", "DATASTRIP", "]", "[", "datastrip_folder", "]", "=", "{", "}", "safe", "[", "main_folder", "]", "[", "AwsConstants", ".", "DATASTRIP", "]", "[", "datastrip_folder", "]", "[", "AwsConstants", ".", "QI_DATA", "]", "=", "{", "}", "# S-2 L1C reports are on AWS only stored with tiles and without RADIOMETRIC_QUALITY", "if", "self", ".", "has_reports", "(", ")", "and", "self", ".", "data_source", "is", "DataSource", ".", "SENTINEL2_L2A", ":", "for", "metafile", "in", "AwsConstants", ".", "QUALITY_REPORTS", ":", "metafile_name", "=", "self", ".", "add_file_extension", "(", "metafile", ")", "safe", "[", "main_folder", "]", "[", "AwsConstants", ".", "DATASTRIP", "]", "[", "datastrip_folder", "]", "[", "AwsConstants", ".", "QI_DATA", "]", "[", "metafile_name", "]", "=", "'{}/qi/{}'", ".", "format", "(", "datastrip_url", ",", "metafile_name", ")", "safe", "[", "main_folder", "]", "[", "AwsConstants", ".", "DATASTRIP", "]", "[", "datastrip_folder", "]", "[", "self", ".", "get_datastrip_metadata_name", "(", "datastrip_folder", ")", "]", "=", "'{}/{}'", ".", "format", "(", "datastrip_url", ",", "self", ".", "add_file_extension", "(", "AwsConstants", ".", "METADATA", ")", ")", "safe", "[", "main_folder", "]", "[", "AwsConstants", ".", "GRANULE", "]", "=", "{", "}", "for", "tile_info", "in", "self", ".", "product_info", "[", "'tiles'", "]", ":", "tile_name", ",", "date", ",", "aws_index", "=", "self", ".", "url_to_tile", "(", "self", ".", "get_tile_url", "(", "tile_info", ")", ")", "if", "self", ".", "tile_list", "is", "None", "or", "AwsTile", ".", "parse_tile_name", "(", "tile_name", ")", "in", "self", ".", "tile_list", ":", "tile_struct", "=", "SafeTile", "(", "tile_name", ",", "date", ",", "aws_index", ",", "parent_folder", "=", "None", ",", "bands", "=", "self", ".", "bands", ",", "metafiles", "=", "self", ".", "metafiles", ",", "data_source", "=", "self", ".", "data_source", ")", ".", "get_safe_struct", "(", ")", "for", "tile_name", ",", "safe_struct", "in", "tile_struct", ".", "items", "(", ")", ":", "safe", "[", "main_folder", "]", "[", "AwsConstants", ".", "GRANULE", "]", "[", "tile_name", "]", "=", "safe_struct", "safe", "[", "main_folder", "]", "[", "AwsConstants", ".", "HTML", "]", "=", "{", "}", "# AWS doesn't have this data", "safe", "[", "main_folder", "]", "[", "AwsConstants", ".", "INFO", "]", "=", "{", "}", "# AWS doesn't have this data", "safe", "[", "main_folder", "]", "[", "self", ".", "get_product_metadata_name", "(", ")", "]", "=", "self", ".", "get_url", "(", "AwsConstants", ".", "METADATA", ")", "safe", "[", "main_folder", "]", "[", "'INSPIRE.xml'", "]", "=", "self", ".", "get_url", "(", "AwsConstants", ".", "INSPIRE", ")", "safe", "[", "main_folder", "]", "[", "self", ".", "add_file_extension", "(", "AwsConstants", ".", "MANIFEST", ")", "]", "=", "self", ".", "get_url", "(", "AwsConstants", ".", "MANIFEST", ")", "if", "self", ".", "is_early_compact_l2a", "(", ")", ":", "safe", "[", "main_folder", "]", "[", "'L2A_Manifest.xml'", "]", "=", "self", ".", "get_url", "(", "AwsConstants", ".", "L2A_MANIFEST", ")", "safe", "[", "main_folder", "]", "[", "self", ".", "get_report_name", "(", ")", "]", "=", "self", ".", "get_url", "(", "AwsConstants", ".", "REPORT", ")", "if", "self", ".", "safe_type", "==", "EsaSafeType", ".", "OLD_TYPE", "and", "self", ".", "baseline", "!=", "'02.02'", ":", "safe", "[", "main_folder", "]", "[", "_edit_name", "(", "self", ".", "product_id", ",", "'BWI'", ")", "+", "'.png'", "]", "=", "self", ".", "get_url", "(", "AwsConstants", ".", "PREVIEW", ",", "MimeType", ".", "PNG", ")", "return", "safe" ]
Describes a structure inside tile folder of ESA product .SAFE structure :return: nested dictionaries representing .SAFE structure :rtype: dict
[ "Describes", "a", "structure", "inside", "tile", "folder", "of", "ESA", "product", ".", "SAFE", "structure" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws_safe.py#L28-L81
229,262
sentinel-hub/sentinelhub-py
sentinelhub/aws_safe.py
SafeTile.get_tile_id
def get_tile_id(self): """Creates ESA tile ID :return: ESA tile ID :rtype: str """ tree = get_xml(self.get_url(AwsConstants.METADATA)) tile_id_tag = 'TILE_ID_2A' if self.data_source is DataSource.SENTINEL2_L2A and self.baseline <= '02.06' else\ 'TILE_ID' tile_id = tree[0].find(tile_id_tag).text if self.safe_type is not EsaSafeType.OLD_TYPE: info = tile_id.split('_') tile_id = '_'.join([info[3], info[-2], info[-3], self.get_sensing_time()]) return tile_id
python
def get_tile_id(self): """Creates ESA tile ID :return: ESA tile ID :rtype: str """ tree = get_xml(self.get_url(AwsConstants.METADATA)) tile_id_tag = 'TILE_ID_2A' if self.data_source is DataSource.SENTINEL2_L2A and self.baseline <= '02.06' else\ 'TILE_ID' tile_id = tree[0].find(tile_id_tag).text if self.safe_type is not EsaSafeType.OLD_TYPE: info = tile_id.split('_') tile_id = '_'.join([info[3], info[-2], info[-3], self.get_sensing_time()]) return tile_id
[ "def", "get_tile_id", "(", "self", ")", ":", "tree", "=", "get_xml", "(", "self", ".", "get_url", "(", "AwsConstants", ".", "METADATA", ")", ")", "tile_id_tag", "=", "'TILE_ID_2A'", "if", "self", ".", "data_source", "is", "DataSource", ".", "SENTINEL2_L2A", "and", "self", ".", "baseline", "<=", "'02.06'", "else", "'TILE_ID'", "tile_id", "=", "tree", "[", "0", "]", ".", "find", "(", "tile_id_tag", ")", ".", "text", "if", "self", ".", "safe_type", "is", "not", "EsaSafeType", ".", "OLD_TYPE", ":", "info", "=", "tile_id", ".", "split", "(", "'_'", ")", "tile_id", "=", "'_'", ".", "join", "(", "[", "info", "[", "3", "]", ",", "info", "[", "-", "2", "]", ",", "info", "[", "-", "3", "]", ",", "self", ".", "get_sensing_time", "(", ")", "]", ")", "return", "tile_id" ]
Creates ESA tile ID :return: ESA tile ID :rtype: str
[ "Creates", "ESA", "tile", "ID" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws_safe.py#L250-L264
229,263
sentinel-hub/sentinelhub-py
sentinelhub/areas.py
AreaSplitter._parse_shape_list
def _parse_shape_list(shape_list, crs): """ Checks if the given list of shapes is in correct format and parses geometry objects :param shape_list: The parameter `shape_list` from class initialization :type shape_list: list(shapely.geometry.multipolygon.MultiPolygon or shapely.geometry.polygon.Polygon) :raises: ValueError """ if not isinstance(shape_list, list): raise ValueError('Splitter must be initialized with a list of shapes') return [AreaSplitter._parse_shape(shape, crs) for shape in shape_list]
python
def _parse_shape_list(shape_list, crs): """ Checks if the given list of shapes is in correct format and parses geometry objects :param shape_list: The parameter `shape_list` from class initialization :type shape_list: list(shapely.geometry.multipolygon.MultiPolygon or shapely.geometry.polygon.Polygon) :raises: ValueError """ if not isinstance(shape_list, list): raise ValueError('Splitter must be initialized with a list of shapes') return [AreaSplitter._parse_shape(shape, crs) for shape in shape_list]
[ "def", "_parse_shape_list", "(", "shape_list", ",", "crs", ")", ":", "if", "not", "isinstance", "(", "shape_list", ",", "list", ")", ":", "raise", "ValueError", "(", "'Splitter must be initialized with a list of shapes'", ")", "return", "[", "AreaSplitter", ".", "_parse_shape", "(", "shape", ",", "crs", ")", "for", "shape", "in", "shape_list", "]" ]
Checks if the given list of shapes is in correct format and parses geometry objects :param shape_list: The parameter `shape_list` from class initialization :type shape_list: list(shapely.geometry.multipolygon.MultiPolygon or shapely.geometry.polygon.Polygon) :raises: ValueError
[ "Checks", "if", "the", "given", "list", "of", "shapes", "is", "in", "correct", "format", "and", "parses", "geometry", "objects" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L40-L50
229,264
sentinel-hub/sentinelhub-py
sentinelhub/areas.py
AreaSplitter.get_bbox_list
def get_bbox_list(self, crs=None, buffer=None, reduce_bbox_sizes=None): """Returns a list of bounding boxes that are the result of the split :param crs: Coordinate reference system in which the bounding boxes should be returned. If None the CRS will be the default CRS of the splitter. :type crs: CRS or None :param buffer: A percentage of each BBox size increase. This will cause neighbouring bounding boxes to overlap. :type buffer: float or None :param reduce_bbox_sizes: If `True` it will reduce the sizes of bounding boxes so that they will tightly fit the given geometry in `shape_list`. This overrides the same parameter from constructor :type reduce_bbox_sizes: bool :return: List of bounding boxes :rtype: list(BBox) """ bbox_list = self.bbox_list if buffer: bbox_list = [bbox.buffer(buffer) for bbox in bbox_list] if reduce_bbox_sizes is None: reduce_bbox_sizes = self.reduce_bbox_sizes if reduce_bbox_sizes: bbox_list = self._reduce_sizes(bbox_list) if crs: return [bbox.transform(crs) for bbox in bbox_list] return bbox_list
python
def get_bbox_list(self, crs=None, buffer=None, reduce_bbox_sizes=None): """Returns a list of bounding boxes that are the result of the split :param crs: Coordinate reference system in which the bounding boxes should be returned. If None the CRS will be the default CRS of the splitter. :type crs: CRS or None :param buffer: A percentage of each BBox size increase. This will cause neighbouring bounding boxes to overlap. :type buffer: float or None :param reduce_bbox_sizes: If `True` it will reduce the sizes of bounding boxes so that they will tightly fit the given geometry in `shape_list`. This overrides the same parameter from constructor :type reduce_bbox_sizes: bool :return: List of bounding boxes :rtype: list(BBox) """ bbox_list = self.bbox_list if buffer: bbox_list = [bbox.buffer(buffer) for bbox in bbox_list] if reduce_bbox_sizes is None: reduce_bbox_sizes = self.reduce_bbox_sizes if reduce_bbox_sizes: bbox_list = self._reduce_sizes(bbox_list) if crs: return [bbox.transform(crs) for bbox in bbox_list] return bbox_list
[ "def", "get_bbox_list", "(", "self", ",", "crs", "=", "None", ",", "buffer", "=", "None", ",", "reduce_bbox_sizes", "=", "None", ")", ":", "bbox_list", "=", "self", ".", "bbox_list", "if", "buffer", ":", "bbox_list", "=", "[", "bbox", ".", "buffer", "(", "buffer", ")", "for", "bbox", "in", "bbox_list", "]", "if", "reduce_bbox_sizes", "is", "None", ":", "reduce_bbox_sizes", "=", "self", ".", "reduce_bbox_sizes", "if", "reduce_bbox_sizes", ":", "bbox_list", "=", "self", ".", "_reduce_sizes", "(", "bbox_list", ")", "if", "crs", ":", "return", "[", "bbox", ".", "transform", "(", "crs", ")", "for", "bbox", "in", "bbox_list", "]", "return", "bbox_list" ]
Returns a list of bounding boxes that are the result of the split :param crs: Coordinate reference system in which the bounding boxes should be returned. If None the CRS will be the default CRS of the splitter. :type crs: CRS or None :param buffer: A percentage of each BBox size increase. This will cause neighbouring bounding boxes to overlap. :type buffer: float or None :param reduce_bbox_sizes: If `True` it will reduce the sizes of bounding boxes so that they will tightly fit the given geometry in `shape_list`. This overrides the same parameter from constructor :type reduce_bbox_sizes: bool :return: List of bounding boxes :rtype: list(BBox)
[ "Returns", "a", "list", "of", "bounding", "boxes", "that", "are", "the", "result", "of", "the", "split" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L78-L103
229,265
sentinel-hub/sentinelhub-py
sentinelhub/areas.py
AreaSplitter.get_area_bbox
def get_area_bbox(self, crs=None): """Returns a bounding box of the entire area :param crs: Coordinate reference system in which the bounding box should be returned. If None the CRS will be the default CRS of the splitter. :type crs: CRS or None :return: A bounding box of the area defined by the `shape_list` :rtype: BBox """ bbox_list = [BBox(shape.bounds, crs=self.crs) for shape in self.shape_list] area_minx = min([bbox.lower_left[0] for bbox in bbox_list]) area_miny = min([bbox.lower_left[1] for bbox in bbox_list]) area_maxx = max([bbox.upper_right[0] for bbox in bbox_list]) area_maxy = max([bbox.upper_right[1] for bbox in bbox_list]) bbox = BBox([area_minx, area_miny, area_maxx, area_maxy], crs=self.crs) if crs is None: return bbox return bbox.transform(crs)
python
def get_area_bbox(self, crs=None): """Returns a bounding box of the entire area :param crs: Coordinate reference system in which the bounding box should be returned. If None the CRS will be the default CRS of the splitter. :type crs: CRS or None :return: A bounding box of the area defined by the `shape_list` :rtype: BBox """ bbox_list = [BBox(shape.bounds, crs=self.crs) for shape in self.shape_list] area_minx = min([bbox.lower_left[0] for bbox in bbox_list]) area_miny = min([bbox.lower_left[1] for bbox in bbox_list]) area_maxx = max([bbox.upper_right[0] for bbox in bbox_list]) area_maxy = max([bbox.upper_right[1] for bbox in bbox_list]) bbox = BBox([area_minx, area_miny, area_maxx, area_maxy], crs=self.crs) if crs is None: return bbox return bbox.transform(crs)
[ "def", "get_area_bbox", "(", "self", ",", "crs", "=", "None", ")", ":", "bbox_list", "=", "[", "BBox", "(", "shape", ".", "bounds", ",", "crs", "=", "self", ".", "crs", ")", "for", "shape", "in", "self", ".", "shape_list", "]", "area_minx", "=", "min", "(", "[", "bbox", ".", "lower_left", "[", "0", "]", "for", "bbox", "in", "bbox_list", "]", ")", "area_miny", "=", "min", "(", "[", "bbox", ".", "lower_left", "[", "1", "]", "for", "bbox", "in", "bbox_list", "]", ")", "area_maxx", "=", "max", "(", "[", "bbox", ".", "upper_right", "[", "0", "]", "for", "bbox", "in", "bbox_list", "]", ")", "area_maxy", "=", "max", "(", "[", "bbox", ".", "upper_right", "[", "1", "]", "for", "bbox", "in", "bbox_list", "]", ")", "bbox", "=", "BBox", "(", "[", "area_minx", ",", "area_miny", ",", "area_maxx", ",", "area_maxy", "]", ",", "crs", "=", "self", ".", "crs", ")", "if", "crs", "is", "None", ":", "return", "bbox", "return", "bbox", ".", "transform", "(", "crs", ")" ]
Returns a bounding box of the entire area :param crs: Coordinate reference system in which the bounding box should be returned. If None the CRS will be the default CRS of the splitter. :type crs: CRS or None :return: A bounding box of the area defined by the `shape_list` :rtype: BBox
[ "Returns", "a", "bounding", "box", "of", "the", "entire", "area" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L131-L148
229,266
sentinel-hub/sentinelhub-py
sentinelhub/areas.py
AreaSplitter._bbox_to_area_polygon
def _bbox_to_area_polygon(self, bbox): """Transforms bounding box into a polygon object in the area CRS. :param bbox: A bounding box :type bbox: BBox :return: A polygon :rtype: shapely.geometry.polygon.Polygon """ projected_bbox = bbox.transform(self.crs) return projected_bbox.geometry
python
def _bbox_to_area_polygon(self, bbox): """Transforms bounding box into a polygon object in the area CRS. :param bbox: A bounding box :type bbox: BBox :return: A polygon :rtype: shapely.geometry.polygon.Polygon """ projected_bbox = bbox.transform(self.crs) return projected_bbox.geometry
[ "def", "_bbox_to_area_polygon", "(", "self", ",", "bbox", ")", ":", "projected_bbox", "=", "bbox", ".", "transform", "(", "self", ".", "crs", ")", "return", "projected_bbox", ".", "geometry" ]
Transforms bounding box into a polygon object in the area CRS. :param bbox: A bounding box :type bbox: BBox :return: A polygon :rtype: shapely.geometry.polygon.Polygon
[ "Transforms", "bounding", "box", "into", "a", "polygon", "object", "in", "the", "area", "CRS", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L170-L179
229,267
sentinel-hub/sentinelhub-py
sentinelhub/areas.py
AreaSplitter._reduce_sizes
def _reduce_sizes(self, bbox_list): """Reduces sizes of bounding boxes """ return [BBox(self._intersection_area(bbox).bounds, self.crs).transform(bbox.crs) for bbox in bbox_list]
python
def _reduce_sizes(self, bbox_list): """Reduces sizes of bounding boxes """ return [BBox(self._intersection_area(bbox).bounds, self.crs).transform(bbox.crs) for bbox in bbox_list]
[ "def", "_reduce_sizes", "(", "self", ",", "bbox_list", ")", ":", "return", "[", "BBox", "(", "self", ".", "_intersection_area", "(", "bbox", ")", ".", "bounds", ",", "self", ".", "crs", ")", ".", "transform", "(", "bbox", ".", "crs", ")", "for", "bbox", "in", "bbox_list", "]" ]
Reduces sizes of bounding boxes
[ "Reduces", "sizes", "of", "bounding", "boxes" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L181-L184
229,268
sentinel-hub/sentinelhub-py
sentinelhub/areas.py
BBoxSplitter._parse_split_shape
def _parse_split_shape(split_shape): """Parses the parameter `split_shape` :param split_shape: The parameter `split_shape` from class initialization :type split_shape: int or (int, int) :return: A tuple of n :rtype: (int, int) :raises: ValueError """ if isinstance(split_shape, int): return split_shape, split_shape if isinstance(split_shape, (tuple, list)): if len(split_shape) == 2 and isinstance(split_shape[0], int) and isinstance(split_shape[1], int): return split_shape[0], split_shape[1] raise ValueError("Content of split_shape {} must be 2 integers.".format(split_shape)) raise ValueError("Split shape must be an int or a tuple of 2 integers.")
python
def _parse_split_shape(split_shape): """Parses the parameter `split_shape` :param split_shape: The parameter `split_shape` from class initialization :type split_shape: int or (int, int) :return: A tuple of n :rtype: (int, int) :raises: ValueError """ if isinstance(split_shape, int): return split_shape, split_shape if isinstance(split_shape, (tuple, list)): if len(split_shape) == 2 and isinstance(split_shape[0], int) and isinstance(split_shape[1], int): return split_shape[0], split_shape[1] raise ValueError("Content of split_shape {} must be 2 integers.".format(split_shape)) raise ValueError("Split shape must be an int or a tuple of 2 integers.")
[ "def", "_parse_split_shape", "(", "split_shape", ")", ":", "if", "isinstance", "(", "split_shape", ",", "int", ")", ":", "return", "split_shape", ",", "split_shape", "if", "isinstance", "(", "split_shape", ",", "(", "tuple", ",", "list", ")", ")", ":", "if", "len", "(", "split_shape", ")", "==", "2", "and", "isinstance", "(", "split_shape", "[", "0", "]", ",", "int", ")", "and", "isinstance", "(", "split_shape", "[", "1", "]", ",", "int", ")", ":", "return", "split_shape", "[", "0", "]", ",", "split_shape", "[", "1", "]", "raise", "ValueError", "(", "\"Content of split_shape {} must be 2 integers.\"", ".", "format", "(", "split_shape", ")", ")", "raise", "ValueError", "(", "\"Split shape must be an int or a tuple of 2 integers.\"", ")" ]
Parses the parameter `split_shape` :param split_shape: The parameter `split_shape` from class initialization :type split_shape: int or (int, int) :return: A tuple of n :rtype: (int, int) :raises: ValueError
[ "Parses", "the", "parameter", "split_shape" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L212-L227
229,269
sentinel-hub/sentinelhub-py
sentinelhub/areas.py
OsmSplitter._recursive_split
def _recursive_split(self, bbox, zoom_level, column, row): """Method that recursively creates bounding boxes of OSM grid that intersect the area. :param bbox: Bounding box :type bbox: BBox :param zoom_level: OSM zoom level :type zoom_level: int :param column: Column in the OSM grid :type column: int :param row: Row in the OSM grid :type row: int """ if zoom_level == self.zoom_level: self.bbox_list.append(bbox) self.info_list.append({'zoom_level': zoom_level, 'index_x': column, 'index_y': row}) return bbox_partition = bbox.get_partition(2, 2) for i, j in itertools.product(range(2), range(2)): if self._intersects_area(bbox_partition[i][j]): self._recursive_split(bbox_partition[i][j], zoom_level + 1, 2 * column + i, 2 * row + 1 - j)
python
def _recursive_split(self, bbox, zoom_level, column, row): """Method that recursively creates bounding boxes of OSM grid that intersect the area. :param bbox: Bounding box :type bbox: BBox :param zoom_level: OSM zoom level :type zoom_level: int :param column: Column in the OSM grid :type column: int :param row: Row in the OSM grid :type row: int """ if zoom_level == self.zoom_level: self.bbox_list.append(bbox) self.info_list.append({'zoom_level': zoom_level, 'index_x': column, 'index_y': row}) return bbox_partition = bbox.get_partition(2, 2) for i, j in itertools.product(range(2), range(2)): if self._intersects_area(bbox_partition[i][j]): self._recursive_split(bbox_partition[i][j], zoom_level + 1, 2 * column + i, 2 * row + 1 - j)
[ "def", "_recursive_split", "(", "self", ",", "bbox", ",", "zoom_level", ",", "column", ",", "row", ")", ":", "if", "zoom_level", "==", "self", ".", "zoom_level", ":", "self", ".", "bbox_list", ".", "append", "(", "bbox", ")", "self", ".", "info_list", ".", "append", "(", "{", "'zoom_level'", ":", "zoom_level", ",", "'index_x'", ":", "column", ",", "'index_y'", ":", "row", "}", ")", "return", "bbox_partition", "=", "bbox", ".", "get_partition", "(", "2", ",", "2", ")", "for", "i", ",", "j", "in", "itertools", ".", "product", "(", "range", "(", "2", ")", ",", "range", "(", "2", ")", ")", ":", "if", "self", ".", "_intersects_area", "(", "bbox_partition", "[", "i", "]", "[", "j", "]", ")", ":", "self", ".", "_recursive_split", "(", "bbox_partition", "[", "i", "]", "[", "j", "]", ",", "zoom_level", "+", "1", ",", "2", "*", "column", "+", "i", ",", "2", "*", "row", "+", "1", "-", "j", ")" ]
Method that recursively creates bounding boxes of OSM grid that intersect the area. :param bbox: Bounding box :type bbox: BBox :param zoom_level: OSM zoom level :type zoom_level: int :param column: Column in the OSM grid :type column: int :param row: Row in the OSM grid :type row: int
[ "Method", "that", "recursively", "creates", "bounding", "boxes", "of", "OSM", "grid", "that", "intersect", "the", "area", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L303-L325
229,270
sentinel-hub/sentinelhub-py
sentinelhub/areas.py
CustomGridSplitter._parse_bbox_grid
def _parse_bbox_grid(bbox_grid): """ Helper method for parsing bounding box grid. It will try to parse it into `BBoxCollection` """ if isinstance(bbox_grid, BBoxCollection): return bbox_grid if isinstance(bbox_grid, list): return BBoxCollection(bbox_grid) raise ValueError("Parameter 'bbox_grid' should be an instance of {}".format(BBoxCollection.__name__))
python
def _parse_bbox_grid(bbox_grid): """ Helper method for parsing bounding box grid. It will try to parse it into `BBoxCollection` """ if isinstance(bbox_grid, BBoxCollection): return bbox_grid if isinstance(bbox_grid, list): return BBoxCollection(bbox_grid) raise ValueError("Parameter 'bbox_grid' should be an instance of {}".format(BBoxCollection.__name__))
[ "def", "_parse_bbox_grid", "(", "bbox_grid", ")", ":", "if", "isinstance", "(", "bbox_grid", ",", "BBoxCollection", ")", ":", "return", "bbox_grid", "if", "isinstance", "(", "bbox_grid", ",", "list", ")", ":", "return", "BBoxCollection", "(", "bbox_grid", ")", "raise", "ValueError", "(", "\"Parameter 'bbox_grid' should be an instance of {}\"", ".", "format", "(", "BBoxCollection", ".", "__name__", ")", ")" ]
Helper method for parsing bounding box grid. It will try to parse it into `BBoxCollection`
[ "Helper", "method", "for", "parsing", "bounding", "box", "grid", ".", "It", "will", "try", "to", "parse", "it", "into", "BBoxCollection" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/areas.py#L446-L455
229,271
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsService._parse_metafiles
def _parse_metafiles(self, metafile_input): """ Parses class input and verifies metadata file names. :param metafile_input: class input parameter `metafiles` :type metafile_input: str or list(str) or None :return: verified list of metadata files :rtype: list(str) """ all_metafiles = AwsConstants.S2_L1C_METAFILES if self.data_source is DataSource.SENTINEL2_L1C else \ AwsConstants.S2_L2A_METAFILES if metafile_input is None: if self.__class__.__name__ == 'SafeProduct': return all_metafiles if self.__class__.__name__ == 'SafeTile': return [metafile for metafile in all_metafiles if metafile in AwsConstants.TILE_FILES] return [] if isinstance(metafile_input, str): metafile_list = metafile_input.split(',') elif isinstance(metafile_input, list): metafile_list = metafile_input.copy() else: raise ValueError('metafiles parameter must be a list or a string') metafile_list = [metafile.strip().split('.')[0] for metafile in metafile_list] metafile_list = [metafile for metafile in metafile_list if metafile != ''] if not set(metafile_list) <= set(all_metafiles): raise ValueError('metadata files {} must be a subset of {}'.format(metafile_list, all_metafiles)) return metafile_list
python
def _parse_metafiles(self, metafile_input): """ Parses class input and verifies metadata file names. :param metafile_input: class input parameter `metafiles` :type metafile_input: str or list(str) or None :return: verified list of metadata files :rtype: list(str) """ all_metafiles = AwsConstants.S2_L1C_METAFILES if self.data_source is DataSource.SENTINEL2_L1C else \ AwsConstants.S2_L2A_METAFILES if metafile_input is None: if self.__class__.__name__ == 'SafeProduct': return all_metafiles if self.__class__.__name__ == 'SafeTile': return [metafile for metafile in all_metafiles if metafile in AwsConstants.TILE_FILES] return [] if isinstance(metafile_input, str): metafile_list = metafile_input.split(',') elif isinstance(metafile_input, list): metafile_list = metafile_input.copy() else: raise ValueError('metafiles parameter must be a list or a string') metafile_list = [metafile.strip().split('.')[0] for metafile in metafile_list] metafile_list = [metafile for metafile in metafile_list if metafile != ''] if not set(metafile_list) <= set(all_metafiles): raise ValueError('metadata files {} must be a subset of {}'.format(metafile_list, all_metafiles)) return metafile_list
[ "def", "_parse_metafiles", "(", "self", ",", "metafile_input", ")", ":", "all_metafiles", "=", "AwsConstants", ".", "S2_L1C_METAFILES", "if", "self", ".", "data_source", "is", "DataSource", ".", "SENTINEL2_L1C", "else", "AwsConstants", ".", "S2_L2A_METAFILES", "if", "metafile_input", "is", "None", ":", "if", "self", ".", "__class__", ".", "__name__", "==", "'SafeProduct'", ":", "return", "all_metafiles", "if", "self", ".", "__class__", ".", "__name__", "==", "'SafeTile'", ":", "return", "[", "metafile", "for", "metafile", "in", "all_metafiles", "if", "metafile", "in", "AwsConstants", ".", "TILE_FILES", "]", "return", "[", "]", "if", "isinstance", "(", "metafile_input", ",", "str", ")", ":", "metafile_list", "=", "metafile_input", ".", "split", "(", "','", ")", "elif", "isinstance", "(", "metafile_input", ",", "list", ")", ":", "metafile_list", "=", "metafile_input", ".", "copy", "(", ")", "else", ":", "raise", "ValueError", "(", "'metafiles parameter must be a list or a string'", ")", "metafile_list", "=", "[", "metafile", ".", "strip", "(", ")", ".", "split", "(", "'.'", ")", "[", "0", "]", "for", "metafile", "in", "metafile_list", "]", "metafile_list", "=", "[", "metafile", "for", "metafile", "in", "metafile_list", "if", "metafile", "!=", "''", "]", "if", "not", "set", "(", "metafile_list", ")", "<=", "set", "(", "all_metafiles", ")", ":", "raise", "ValueError", "(", "'metadata files {} must be a subset of {}'", ".", "format", "(", "metafile_list", ",", "all_metafiles", ")", ")", "return", "metafile_list" ]
Parses class input and verifies metadata file names. :param metafile_input: class input parameter `metafiles` :type metafile_input: str or list(str) or None :return: verified list of metadata files :rtype: list(str)
[ "Parses", "class", "input", "and", "verifies", "metadata", "file", "names", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L74-L102
229,272
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsService.get_base_url
def get_base_url(self, force_http=False): """ Creates base URL path :param force_http: `True` if HTTP base URL should be used and `False` otherwise :type force_http: str :return: base url string :rtype: str """ base_url = SHConfig().aws_metadata_url.rstrip('/') if force_http else 's3:/' aws_bucket = SHConfig().aws_s3_l1c_bucket if self.data_source is DataSource.SENTINEL2_L1C else \ SHConfig().aws_s3_l2a_bucket return '{}/{}/'.format(base_url, aws_bucket)
python
def get_base_url(self, force_http=False): """ Creates base URL path :param force_http: `True` if HTTP base URL should be used and `False` otherwise :type force_http: str :return: base url string :rtype: str """ base_url = SHConfig().aws_metadata_url.rstrip('/') if force_http else 's3:/' aws_bucket = SHConfig().aws_s3_l1c_bucket if self.data_source is DataSource.SENTINEL2_L1C else \ SHConfig().aws_s3_l2a_bucket return '{}/{}/'.format(base_url, aws_bucket)
[ "def", "get_base_url", "(", "self", ",", "force_http", "=", "False", ")", ":", "base_url", "=", "SHConfig", "(", ")", ".", "aws_metadata_url", ".", "rstrip", "(", "'/'", ")", "if", "force_http", "else", "'s3:/'", "aws_bucket", "=", "SHConfig", "(", ")", ".", "aws_s3_l1c_bucket", "if", "self", ".", "data_source", "is", "DataSource", ".", "SENTINEL2_L1C", "else", "SHConfig", "(", ")", ".", "aws_s3_l2a_bucket", "return", "'{}/{}/'", ".", "format", "(", "base_url", ",", "aws_bucket", ")" ]
Creates base URL path :param force_http: `True` if HTTP base URL should be used and `False` otherwise :type force_http: str :return: base url string :rtype: str
[ "Creates", "base", "URL", "path" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L104-L116
229,273
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsService.get_safe_type
def get_safe_type(self): """Determines the type of ESA product. In 2016 ESA changed structure and naming of data. Therefore the class must distinguish between old product type and compact (new) product type. :return: type of ESA product :rtype: constants.EsaSafeType :raises: ValueError """ product_type = self.product_id.split('_')[1] if product_type.startswith('MSI'): return EsaSafeType.COMPACT_TYPE if product_type in ['OPER', 'USER']: return EsaSafeType.OLD_TYPE raise ValueError('Unrecognized product type of product id {}'.format(self.product_id))
python
def get_safe_type(self): """Determines the type of ESA product. In 2016 ESA changed structure and naming of data. Therefore the class must distinguish between old product type and compact (new) product type. :return: type of ESA product :rtype: constants.EsaSafeType :raises: ValueError """ product_type = self.product_id.split('_')[1] if product_type.startswith('MSI'): return EsaSafeType.COMPACT_TYPE if product_type in ['OPER', 'USER']: return EsaSafeType.OLD_TYPE raise ValueError('Unrecognized product type of product id {}'.format(self.product_id))
[ "def", "get_safe_type", "(", "self", ")", ":", "product_type", "=", "self", ".", "product_id", ".", "split", "(", "'_'", ")", "[", "1", "]", "if", "product_type", ".", "startswith", "(", "'MSI'", ")", ":", "return", "EsaSafeType", ".", "COMPACT_TYPE", "if", "product_type", "in", "[", "'OPER'", ",", "'USER'", "]", ":", "return", "EsaSafeType", ".", "OLD_TYPE", "raise", "ValueError", "(", "'Unrecognized product type of product id {}'", ".", "format", "(", "self", ".", "product_id", ")", ")" ]
Determines the type of ESA product. In 2016 ESA changed structure and naming of data. Therefore the class must distinguish between old product type and compact (new) product type. :return: type of ESA product :rtype: constants.EsaSafeType :raises: ValueError
[ "Determines", "the", "type", "of", "ESA", "product", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L118-L133
229,274
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsService._read_baseline_from_info
def _read_baseline_from_info(self): """Tries to find and return baseline number from either tileInfo or productInfo file. :return: Baseline ID :rtype: str :raises: ValueError """ if hasattr(self, 'tile_info'): return self.tile_info['datastrip']['id'][-5:] if hasattr(self, 'product_info'): return self.product_info['datastrips'][0]['id'][-5:] raise ValueError('No info file has been obtained yet.')
python
def _read_baseline_from_info(self): """Tries to find and return baseline number from either tileInfo or productInfo file. :return: Baseline ID :rtype: str :raises: ValueError """ if hasattr(self, 'tile_info'): return self.tile_info['datastrip']['id'][-5:] if hasattr(self, 'product_info'): return self.product_info['datastrips'][0]['id'][-5:] raise ValueError('No info file has been obtained yet.')
[ "def", "_read_baseline_from_info", "(", "self", ")", ":", "if", "hasattr", "(", "self", ",", "'tile_info'", ")", ":", "return", "self", ".", "tile_info", "[", "'datastrip'", "]", "[", "'id'", "]", "[", "-", "5", ":", "]", "if", "hasattr", "(", "self", ",", "'product_info'", ")", ":", "return", "self", ".", "product_info", "[", "'datastrips'", "]", "[", "0", "]", "[", "'id'", "]", "[", "-", "5", ":", "]", "raise", "ValueError", "(", "'No info file has been obtained yet.'", ")" ]
Tries to find and return baseline number from either tileInfo or productInfo file. :return: Baseline ID :rtype: str :raises: ValueError
[ "Tries", "to", "find", "and", "return", "baseline", "number", "from", "either", "tileInfo", "or", "productInfo", "file", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L149-L160
229,275
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsService.url_to_tile
def url_to_tile(url): """ Extracts tile name, date and AWS index from tile url on AWS. :param url: class input parameter 'metafiles' :type url: str :return: Name of tile, date and AWS index which uniquely identifies tile on AWS :rtype: (str, str, int) """ info = url.strip('/').split('/') name = ''.join(info[-7: -4]) date = '-'.join(info[-4: -1]) return name, date, int(info[-1])
python
def url_to_tile(url): """ Extracts tile name, date and AWS index from tile url on AWS. :param url: class input parameter 'metafiles' :type url: str :return: Name of tile, date and AWS index which uniquely identifies tile on AWS :rtype: (str, str, int) """ info = url.strip('/').split('/') name = ''.join(info[-7: -4]) date = '-'.join(info[-4: -1]) return name, date, int(info[-1])
[ "def", "url_to_tile", "(", "url", ")", ":", "info", "=", "url", ".", "strip", "(", "'/'", ")", ".", "split", "(", "'/'", ")", "name", "=", "''", ".", "join", "(", "info", "[", "-", "7", ":", "-", "4", "]", ")", "date", "=", "'-'", ".", "join", "(", "info", "[", "-", "4", ":", "-", "1", "]", ")", "return", "name", ",", "date", ",", "int", "(", "info", "[", "-", "1", "]", ")" ]
Extracts tile name, date and AWS index from tile url on AWS. :param url: class input parameter 'metafiles' :type url: str :return: Name of tile, date and AWS index which uniquely identifies tile on AWS :rtype: (str, str, int)
[ "Extracts", "tile", "name", "date", "and", "AWS", "index", "from", "tile", "url", "on", "AWS", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L163-L175
229,276
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsService.structure_recursion
def structure_recursion(self, struct, folder): """ From nested dictionaries representing .SAFE structure it recursively extracts all the files that need to be downloaded and stores them into class attribute `download_list`. :param struct: nested dictionaries representing a part of .SAFE structure :type struct: dict :param folder: name of folder where this structure will be saved :type folder: str """ has_subfolder = False for name, substruct in struct.items(): subfolder = os.path.join(folder, name) if not isinstance(substruct, dict): product_name, data_name = self._url_to_props(substruct) if '.' in data_name: data_type = MimeType(data_name.split('.')[-1]) data_name = data_name.rsplit('.', 1)[0] else: data_type = MimeType.RAW if data_name in self.bands + self.metafiles: self.download_list.append(DownloadRequest(url=substruct, filename=subfolder, data_type=data_type, data_name=data_name, product_name=product_name)) else: has_subfolder = True self.structure_recursion(substruct, subfolder) if not has_subfolder: self.folder_list.append(folder)
python
def structure_recursion(self, struct, folder): """ From nested dictionaries representing .SAFE structure it recursively extracts all the files that need to be downloaded and stores them into class attribute `download_list`. :param struct: nested dictionaries representing a part of .SAFE structure :type struct: dict :param folder: name of folder where this structure will be saved :type folder: str """ has_subfolder = False for name, substruct in struct.items(): subfolder = os.path.join(folder, name) if not isinstance(substruct, dict): product_name, data_name = self._url_to_props(substruct) if '.' in data_name: data_type = MimeType(data_name.split('.')[-1]) data_name = data_name.rsplit('.', 1)[0] else: data_type = MimeType.RAW if data_name in self.bands + self.metafiles: self.download_list.append(DownloadRequest(url=substruct, filename=subfolder, data_type=data_type, data_name=data_name, product_name=product_name)) else: has_subfolder = True self.structure_recursion(substruct, subfolder) if not has_subfolder: self.folder_list.append(folder)
[ "def", "structure_recursion", "(", "self", ",", "struct", ",", "folder", ")", ":", "has_subfolder", "=", "False", "for", "name", ",", "substruct", "in", "struct", ".", "items", "(", ")", ":", "subfolder", "=", "os", ".", "path", ".", "join", "(", "folder", ",", "name", ")", "if", "not", "isinstance", "(", "substruct", ",", "dict", ")", ":", "product_name", ",", "data_name", "=", "self", ".", "_url_to_props", "(", "substruct", ")", "if", "'.'", "in", "data_name", ":", "data_type", "=", "MimeType", "(", "data_name", ".", "split", "(", "'.'", ")", "[", "-", "1", "]", ")", "data_name", "=", "data_name", ".", "rsplit", "(", "'.'", ",", "1", ")", "[", "0", "]", "else", ":", "data_type", "=", "MimeType", ".", "RAW", "if", "data_name", "in", "self", ".", "bands", "+", "self", ".", "metafiles", ":", "self", ".", "download_list", ".", "append", "(", "DownloadRequest", "(", "url", "=", "substruct", ",", "filename", "=", "subfolder", ",", "data_type", "=", "data_type", ",", "data_name", "=", "data_name", ",", "product_name", "=", "product_name", ")", ")", "else", ":", "has_subfolder", "=", "True", "self", ".", "structure_recursion", "(", "substruct", ",", "subfolder", ")", "if", "not", "has_subfolder", ":", "self", ".", "folder_list", ".", "append", "(", "folder", ")" ]
From nested dictionaries representing .SAFE structure it recursively extracts all the files that need to be downloaded and stores them into class attribute `download_list`. :param struct: nested dictionaries representing a part of .SAFE structure :type struct: dict :param folder: name of folder where this structure will be saved :type folder: str
[ "From", "nested", "dictionaries", "representing", ".", "SAFE", "structure", "it", "recursively", "extracts", "all", "the", "files", "that", "need", "to", "be", "downloaded", "and", "stores", "them", "into", "class", "attribute", "download_list", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L194-L221
229,277
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsService.add_file_extension
def add_file_extension(filename, data_format=None, remove_path=False): """Joins filename and corresponding file extension if it has one. :param filename: Name of the file without extension :type filename: str :param data_format: format of file, if None it will be set automatically :type data_format: constants.MimeType or None :param remove_path: True if the path in filename string should be removed :type remove_path: bool :return: Name of the file with extension :rtype: str """ if data_format is None: data_format = AwsConstants.AWS_FILES[filename] if remove_path: filename = filename.split('/')[-1] if filename.startswith('datastrip'): filename = filename.replace('*', '0') if data_format is MimeType.RAW: return filename return '{}.{}'.format(filename.replace('*', ''), data_format.value)
python
def add_file_extension(filename, data_format=None, remove_path=False): """Joins filename and corresponding file extension if it has one. :param filename: Name of the file without extension :type filename: str :param data_format: format of file, if None it will be set automatically :type data_format: constants.MimeType or None :param remove_path: True if the path in filename string should be removed :type remove_path: bool :return: Name of the file with extension :rtype: str """ if data_format is None: data_format = AwsConstants.AWS_FILES[filename] if remove_path: filename = filename.split('/')[-1] if filename.startswith('datastrip'): filename = filename.replace('*', '0') if data_format is MimeType.RAW: return filename return '{}.{}'.format(filename.replace('*', ''), data_format.value)
[ "def", "add_file_extension", "(", "filename", ",", "data_format", "=", "None", ",", "remove_path", "=", "False", ")", ":", "if", "data_format", "is", "None", ":", "data_format", "=", "AwsConstants", ".", "AWS_FILES", "[", "filename", "]", "if", "remove_path", ":", "filename", "=", "filename", ".", "split", "(", "'/'", ")", "[", "-", "1", "]", "if", "filename", ".", "startswith", "(", "'datastrip'", ")", ":", "filename", "=", "filename", ".", "replace", "(", "'*'", ",", "'0'", ")", "if", "data_format", "is", "MimeType", ".", "RAW", ":", "return", "filename", "return", "'{}.{}'", ".", "format", "(", "filename", ".", "replace", "(", "'*'", ",", "''", ")", ",", "data_format", ".", "value", ")" ]
Joins filename and corresponding file extension if it has one. :param filename: Name of the file without extension :type filename: str :param data_format: format of file, if None it will be set automatically :type data_format: constants.MimeType or None :param remove_path: True if the path in filename string should be removed :type remove_path: bool :return: Name of the file with extension :rtype: str
[ "Joins", "filename", "and", "corresponding", "file", "extension", "if", "it", "has", "one", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L244-L264
229,278
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsService.is_early_compact_l2a
def is_early_compact_l2a(self): """Check if product is early version of compact L2A product :return: True if product is early version of compact L2A product and False otherwise :rtype: bool """ return self.data_source is DataSource.SENTINEL2_L2A and self.safe_type is EsaSafeType.COMPACT_TYPE and \ self.baseline <= '02.06'
python
def is_early_compact_l2a(self): """Check if product is early version of compact L2A product :return: True if product is early version of compact L2A product and False otherwise :rtype: bool """ return self.data_source is DataSource.SENTINEL2_L2A and self.safe_type is EsaSafeType.COMPACT_TYPE and \ self.baseline <= '02.06'
[ "def", "is_early_compact_l2a", "(", "self", ")", ":", "return", "self", ".", "data_source", "is", "DataSource", ".", "SENTINEL2_L2A", "and", "self", ".", "safe_type", "is", "EsaSafeType", ".", "COMPACT_TYPE", "and", "self", ".", "baseline", "<=", "'02.06'" ]
Check if product is early version of compact L2A product :return: True if product is early version of compact L2A product and False otherwise :rtype: bool
[ "Check", "if", "product", "is", "early", "version", "of", "compact", "L2A", "product" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L275-L282
229,279
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsProduct.get_requests
def get_requests(self): """ Creates product structure and returns list of files for download. :return: List of download requests and list of empty folders that need to be created :rtype: (list(download.DownloadRequest), list(str)) """ self.download_list = [DownloadRequest(url=self.get_url(metafile), filename=self.get_filepath(metafile), data_type=AwsConstants.AWS_FILES[metafile], data_name=metafile) for metafile in self.metafiles if metafile in AwsConstants.PRODUCT_FILES] tile_parent_folder = os.path.join(self.parent_folder, self.product_id) for tile_info in self.product_info['tiles']: tile_name, date, aws_index = self.url_to_tile(self.get_tile_url(tile_info)) if self.tile_list is None or AwsTile.parse_tile_name(tile_name) in self.tile_list: tile_downloads, tile_folders = AwsTile(tile_name, date, aws_index, parent_folder=tile_parent_folder, bands=self.bands, metafiles=self.metafiles, data_source=self.data_source).get_requests() self.download_list.extend(tile_downloads) self.folder_list.extend(tile_folders) self.sort_download_list() return self.download_list, self.folder_list
python
def get_requests(self): """ Creates product structure and returns list of files for download. :return: List of download requests and list of empty folders that need to be created :rtype: (list(download.DownloadRequest), list(str)) """ self.download_list = [DownloadRequest(url=self.get_url(metafile), filename=self.get_filepath(metafile), data_type=AwsConstants.AWS_FILES[metafile], data_name=metafile) for metafile in self.metafiles if metafile in AwsConstants.PRODUCT_FILES] tile_parent_folder = os.path.join(self.parent_folder, self.product_id) for tile_info in self.product_info['tiles']: tile_name, date, aws_index = self.url_to_tile(self.get_tile_url(tile_info)) if self.tile_list is None or AwsTile.parse_tile_name(tile_name) in self.tile_list: tile_downloads, tile_folders = AwsTile(tile_name, date, aws_index, parent_folder=tile_parent_folder, bands=self.bands, metafiles=self.metafiles, data_source=self.data_source).get_requests() self.download_list.extend(tile_downloads) self.folder_list.extend(tile_folders) self.sort_download_list() return self.download_list, self.folder_list
[ "def", "get_requests", "(", "self", ")", ":", "self", ".", "download_list", "=", "[", "DownloadRequest", "(", "url", "=", "self", ".", "get_url", "(", "metafile", ")", ",", "filename", "=", "self", ".", "get_filepath", "(", "metafile", ")", ",", "data_type", "=", "AwsConstants", ".", "AWS_FILES", "[", "metafile", "]", ",", "data_name", "=", "metafile", ")", "for", "metafile", "in", "self", ".", "metafiles", "if", "metafile", "in", "AwsConstants", ".", "PRODUCT_FILES", "]", "tile_parent_folder", "=", "os", ".", "path", ".", "join", "(", "self", ".", "parent_folder", ",", "self", ".", "product_id", ")", "for", "tile_info", "in", "self", ".", "product_info", "[", "'tiles'", "]", ":", "tile_name", ",", "date", ",", "aws_index", "=", "self", ".", "url_to_tile", "(", "self", ".", "get_tile_url", "(", "tile_info", ")", ")", "if", "self", ".", "tile_list", "is", "None", "or", "AwsTile", ".", "parse_tile_name", "(", "tile_name", ")", "in", "self", ".", "tile_list", ":", "tile_downloads", ",", "tile_folders", "=", "AwsTile", "(", "tile_name", ",", "date", ",", "aws_index", ",", "parent_folder", "=", "tile_parent_folder", ",", "bands", "=", "self", ".", "bands", ",", "metafiles", "=", "self", ".", "metafiles", ",", "data_source", "=", "self", ".", "data_source", ")", ".", "get_requests", "(", ")", "self", ".", "download_list", ".", "extend", "(", "tile_downloads", ")", "self", ".", "folder_list", ".", "extend", "(", "tile_folders", ")", "self", ".", "sort_download_list", "(", ")", "return", "self", ".", "download_list", ",", "self", ".", "folder_list" ]
Creates product structure and returns list of files for download. :return: List of download requests and list of empty folders that need to be created :rtype: (list(download.DownloadRequest), list(str))
[ "Creates", "product", "structure", "and", "returns", "list", "of", "files", "for", "download", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L337-L358
229,280
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsProduct.get_data_source
def get_data_source(self): """The method determines data source from product ID. :return: Data source of the product :rtype: DataSource :raises: ValueError """ product_type = self.product_id.split('_')[1] if product_type.endswith('L1C') or product_type == 'OPER': return DataSource.SENTINEL2_L1C if product_type.endswith('L2A') or product_type == 'USER': return DataSource.SENTINEL2_L2A raise ValueError('Unknown data source of product {}'.format(self.product_id))
python
def get_data_source(self): """The method determines data source from product ID. :return: Data source of the product :rtype: DataSource :raises: ValueError """ product_type = self.product_id.split('_')[1] if product_type.endswith('L1C') or product_type == 'OPER': return DataSource.SENTINEL2_L1C if product_type.endswith('L2A') or product_type == 'USER': return DataSource.SENTINEL2_L2A raise ValueError('Unknown data source of product {}'.format(self.product_id))
[ "def", "get_data_source", "(", "self", ")", ":", "product_type", "=", "self", ".", "product_id", ".", "split", "(", "'_'", ")", "[", "1", "]", "if", "product_type", ".", "endswith", "(", "'L1C'", ")", "or", "product_type", "==", "'OPER'", ":", "return", "DataSource", ".", "SENTINEL2_L1C", "if", "product_type", ".", "endswith", "(", "'L2A'", ")", "or", "product_type", "==", "'USER'", ":", "return", "DataSource", ".", "SENTINEL2_L2A", "raise", "ValueError", "(", "'Unknown data source of product {}'", ".", "format", "(", "self", ".", "product_id", ")", ")" ]
The method determines data source from product ID. :return: Data source of the product :rtype: DataSource :raises: ValueError
[ "The", "method", "determines", "data", "source", "from", "product", "ID", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L360-L372
229,281
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsProduct.get_date
def get_date(self): """ Collects sensing date of the product. :return: Sensing date :rtype: str """ if self.safe_type == EsaSafeType.OLD_TYPE: name = self.product_id.split('_')[-2] date = [name[1:5], name[5:7], name[7:9]] else: name = self.product_id.split('_')[2] date = [name[:4], name[4:6], name[6:8]] return '-'.join(date_part.lstrip('0') for date_part in date)
python
def get_date(self): """ Collects sensing date of the product. :return: Sensing date :rtype: str """ if self.safe_type == EsaSafeType.OLD_TYPE: name = self.product_id.split('_')[-2] date = [name[1:5], name[5:7], name[7:9]] else: name = self.product_id.split('_')[2] date = [name[:4], name[4:6], name[6:8]] return '-'.join(date_part.lstrip('0') for date_part in date)
[ "def", "get_date", "(", "self", ")", ":", "if", "self", ".", "safe_type", "==", "EsaSafeType", ".", "OLD_TYPE", ":", "name", "=", "self", ".", "product_id", ".", "split", "(", "'_'", ")", "[", "-", "2", "]", "date", "=", "[", "name", "[", "1", ":", "5", "]", ",", "name", "[", "5", ":", "7", "]", ",", "name", "[", "7", ":", "9", "]", "]", "else", ":", "name", "=", "self", ".", "product_id", ".", "split", "(", "'_'", ")", "[", "2", "]", "date", "=", "[", "name", "[", ":", "4", "]", ",", "name", "[", "4", ":", "6", "]", ",", "name", "[", "6", ":", "8", "]", "]", "return", "'-'", ".", "join", "(", "date_part", ".", "lstrip", "(", "'0'", ")", "for", "date_part", "in", "date", ")" ]
Collects sensing date of the product. :return: Sensing date :rtype: str
[ "Collects", "sensing", "date", "of", "the", "product", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L374-L386
229,282
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsProduct.get_product_url
def get_product_url(self, force_http=False): """ Creates base url of product location on AWS. :param force_http: True if HTTP base URL should be used and False otherwise :type force_http: str :return: url of product location :rtype: str """ base_url = self.base_http_url if force_http else self.base_url return '{}products/{}/{}'.format(base_url, self.date.replace('-', '/'), self.product_id)
python
def get_product_url(self, force_http=False): """ Creates base url of product location on AWS. :param force_http: True if HTTP base URL should be used and False otherwise :type force_http: str :return: url of product location :rtype: str """ base_url = self.base_http_url if force_http else self.base_url return '{}products/{}/{}'.format(base_url, self.date.replace('-', '/'), self.product_id)
[ "def", "get_product_url", "(", "self", ",", "force_http", "=", "False", ")", ":", "base_url", "=", "self", ".", "base_http_url", "if", "force_http", "else", "self", ".", "base_url", "return", "'{}products/{}/{}'", ".", "format", "(", "base_url", ",", "self", ".", "date", ".", "replace", "(", "'-'", ",", "'/'", ")", ",", "self", ".", "product_id", ")" ]
Creates base url of product location on AWS. :param force_http: True if HTTP base URL should be used and False otherwise :type force_http: str :return: url of product location :rtype: str
[ "Creates", "base", "url", "of", "product", "location", "on", "AWS", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L405-L415
229,283
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsTile.parse_tile_name
def parse_tile_name(name): """ Parses and verifies tile name. :param name: class input parameter `tile_name` :type name: str :return: parsed tile name :rtype: str """ tile_name = name.lstrip('T0') if len(tile_name) == 4: tile_name = '0' + tile_name if len(tile_name) != 5: raise ValueError('Invalid tile name {}'.format(name)) return tile_name
python
def parse_tile_name(name): """ Parses and verifies tile name. :param name: class input parameter `tile_name` :type name: str :return: parsed tile name :rtype: str """ tile_name = name.lstrip('T0') if len(tile_name) == 4: tile_name = '0' + tile_name if len(tile_name) != 5: raise ValueError('Invalid tile name {}'.format(name)) return tile_name
[ "def", "parse_tile_name", "(", "name", ")", ":", "tile_name", "=", "name", ".", "lstrip", "(", "'T0'", ")", "if", "len", "(", "tile_name", ")", "==", "4", ":", "tile_name", "=", "'0'", "+", "tile_name", "if", "len", "(", "tile_name", ")", "!=", "5", ":", "raise", "ValueError", "(", "'Invalid tile name {}'", ".", "format", "(", "name", ")", ")", "return", "tile_name" ]
Parses and verifies tile name. :param name: class input parameter `tile_name` :type name: str :return: parsed tile name :rtype: str
[ "Parses", "and", "verifies", "tile", "name", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L485-L499
229,284
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsTile.get_requests
def get_requests(self): """ Creates tile structure and returns list of files for download. :return: List of download requests and list of empty folders that need to be created :rtype: (list(download.DownloadRequest), list(str)) """ self.download_list = [] for data_name in [band for band in self.bands if self._band_exists(band)] + self.metafiles: if data_name in AwsConstants.TILE_FILES: url = self.get_url(data_name) filename = self.get_filepath(data_name) self.download_list.append(DownloadRequest(url=url, filename=filename, data_type=AwsConstants.AWS_FILES[data_name], data_name=data_name)) self.sort_download_list() return self.download_list, self.folder_list
python
def get_requests(self): """ Creates tile structure and returns list of files for download. :return: List of download requests and list of empty folders that need to be created :rtype: (list(download.DownloadRequest), list(str)) """ self.download_list = [] for data_name in [band for band in self.bands if self._band_exists(band)] + self.metafiles: if data_name in AwsConstants.TILE_FILES: url = self.get_url(data_name) filename = self.get_filepath(data_name) self.download_list.append(DownloadRequest(url=url, filename=filename, data_type=AwsConstants.AWS_FILES[data_name], data_name=data_name)) self.sort_download_list() return self.download_list, self.folder_list
[ "def", "get_requests", "(", "self", ")", ":", "self", ".", "download_list", "=", "[", "]", "for", "data_name", "in", "[", "band", "for", "band", "in", "self", ".", "bands", "if", "self", ".", "_band_exists", "(", "band", ")", "]", "+", "self", ".", "metafiles", ":", "if", "data_name", "in", "AwsConstants", ".", "TILE_FILES", ":", "url", "=", "self", ".", "get_url", "(", "data_name", ")", "filename", "=", "self", ".", "get_filepath", "(", "data_name", ")", "self", ".", "download_list", ".", "append", "(", "DownloadRequest", "(", "url", "=", "url", ",", "filename", "=", "filename", ",", "data_type", "=", "AwsConstants", ".", "AWS_FILES", "[", "data_name", "]", ",", "data_name", "=", "data_name", ")", ")", "self", ".", "sort_download_list", "(", ")", "return", "self", ".", "download_list", ",", "self", ".", "folder_list" ]
Creates tile structure and returns list of files for download. :return: List of download requests and list of empty folders that need to be created :rtype: (list(download.DownloadRequest), list(str))
[ "Creates", "tile", "structure", "and", "returns", "list", "of", "files", "for", "download", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L516-L532
229,285
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsTile.get_aws_index
def get_aws_index(self): """ Returns tile index on AWS. If `tile_index` was not set during class initialization it will be determined according to existing tiles on AWS. :return: Index of tile on AWS :rtype: int """ if self.aws_index is not None: return self.aws_index tile_info_list = get_tile_info(self.tile_name, self.datetime, all_tiles=True) if not tile_info_list: raise ValueError('Cannot find aws_index for specified tile and time') if self.data_source is DataSource.SENTINEL2_L2A: for tile_info in sorted(tile_info_list, key=self._parse_aws_index): try: self.aws_index = self._parse_aws_index(tile_info) self.get_tile_info() return self.aws_index except AwsDownloadFailedException: pass return self._parse_aws_index(tile_info_list[0])
python
def get_aws_index(self): """ Returns tile index on AWS. If `tile_index` was not set during class initialization it will be determined according to existing tiles on AWS. :return: Index of tile on AWS :rtype: int """ if self.aws_index is not None: return self.aws_index tile_info_list = get_tile_info(self.tile_name, self.datetime, all_tiles=True) if not tile_info_list: raise ValueError('Cannot find aws_index for specified tile and time') if self.data_source is DataSource.SENTINEL2_L2A: for tile_info in sorted(tile_info_list, key=self._parse_aws_index): try: self.aws_index = self._parse_aws_index(tile_info) self.get_tile_info() return self.aws_index except AwsDownloadFailedException: pass return self._parse_aws_index(tile_info_list[0])
[ "def", "get_aws_index", "(", "self", ")", ":", "if", "self", ".", "aws_index", "is", "not", "None", ":", "return", "self", ".", "aws_index", "tile_info_list", "=", "get_tile_info", "(", "self", ".", "tile_name", ",", "self", ".", "datetime", ",", "all_tiles", "=", "True", ")", "if", "not", "tile_info_list", ":", "raise", "ValueError", "(", "'Cannot find aws_index for specified tile and time'", ")", "if", "self", ".", "data_source", "is", "DataSource", ".", "SENTINEL2_L2A", ":", "for", "tile_info", "in", "sorted", "(", "tile_info_list", ",", "key", "=", "self", ".", "_parse_aws_index", ")", ":", "try", ":", "self", ".", "aws_index", "=", "self", ".", "_parse_aws_index", "(", "tile_info", ")", "self", ".", "get_tile_info", "(", ")", "return", "self", ".", "aws_index", "except", "AwsDownloadFailedException", ":", "pass", "return", "self", ".", "_parse_aws_index", "(", "tile_info_list", "[", "0", "]", ")" ]
Returns tile index on AWS. If `tile_index` was not set during class initialization it will be determined according to existing tiles on AWS. :return: Index of tile on AWS :rtype: int
[ "Returns", "tile", "index", "on", "AWS", ".", "If", "tile_index", "was", "not", "set", "during", "class", "initialization", "it", "will", "be", "determined", "according", "to", "existing", "tiles", "on", "AWS", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L534-L557
229,286
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsTile.tile_is_valid
def tile_is_valid(self): """ Checks if tile has tile info and valid timestamp :return: `True` if tile is valid and `False` otherwise :rtype: bool """ return self.tile_info is not None \ and (self.datetime == self.date or self.datetime == self.parse_datetime(self.tile_info['timestamp']))
python
def tile_is_valid(self): """ Checks if tile has tile info and valid timestamp :return: `True` if tile is valid and `False` otherwise :rtype: bool """ return self.tile_info is not None \ and (self.datetime == self.date or self.datetime == self.parse_datetime(self.tile_info['timestamp']))
[ "def", "tile_is_valid", "(", "self", ")", ":", "return", "self", ".", "tile_info", "is", "not", "None", "and", "(", "self", ".", "datetime", "==", "self", ".", "date", "or", "self", ".", "datetime", "==", "self", ".", "parse_datetime", "(", "self", ".", "tile_info", "[", "'timestamp'", "]", ")", ")" ]
Checks if tile has tile info and valid timestamp :return: `True` if tile is valid and `False` otherwise :rtype: bool
[ "Checks", "if", "tile", "has", "tile", "info", "and", "valid", "timestamp" ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L570-L577
229,287
sentinel-hub/sentinelhub-py
sentinelhub/aws.py
AwsTile.get_tile_url
def get_tile_url(self, force_http=False): """ Creates base url of tile location on AWS. :param force_http: True if HTTP base URL should be used and False otherwise :type force_http: str :return: url of tile location :rtype: str """ base_url = self.base_http_url if force_http else self.base_url url = '{}tiles/{}/{}/{}/'.format(base_url, self.tile_name[0:2].lstrip('0'), self.tile_name[2], self.tile_name[3:5]) date_params = self.date.split('-') for param in date_params: url += param.lstrip('0') + '/' return url + str(self.aws_index)
python
def get_tile_url(self, force_http=False): """ Creates base url of tile location on AWS. :param force_http: True if HTTP base URL should be used and False otherwise :type force_http: str :return: url of tile location :rtype: str """ base_url = self.base_http_url if force_http else self.base_url url = '{}tiles/{}/{}/{}/'.format(base_url, self.tile_name[0:2].lstrip('0'), self.tile_name[2], self.tile_name[3:5]) date_params = self.date.split('-') for param in date_params: url += param.lstrip('0') + '/' return url + str(self.aws_index)
[ "def", "get_tile_url", "(", "self", ",", "force_http", "=", "False", ")", ":", "base_url", "=", "self", ".", "base_http_url", "if", "force_http", "else", "self", ".", "base_url", "url", "=", "'{}tiles/{}/{}/{}/'", ".", "format", "(", "base_url", ",", "self", ".", "tile_name", "[", "0", ":", "2", "]", ".", "lstrip", "(", "'0'", ")", ",", "self", ".", "tile_name", "[", "2", "]", ",", "self", ".", "tile_name", "[", "3", ":", "5", "]", ")", "date_params", "=", "self", ".", "date", ".", "split", "(", "'-'", ")", "for", "param", "in", "date_params", ":", "url", "+=", "param", ".", "lstrip", "(", "'0'", ")", "+", "'/'", "return", "url", "+", "str", "(", "self", ".", "aws_index", ")" ]
Creates base url of tile location on AWS. :param force_http: True if HTTP base URL should be used and False otherwise :type force_http: str :return: url of tile location :rtype: str
[ "Creates", "base", "url", "of", "tile", "location", "on", "AWS", "." ]
08a83b7f1e289187159a643336995d8369860fea
https://github.com/sentinel-hub/sentinelhub-py/blob/08a83b7f1e289187159a643336995d8369860fea/sentinelhub/aws.py#L603-L618
229,288
ethereum/pyethereum
ethereum/abi.py
split32
def split32(data): """ Split data into pieces of 32 bytes. """ all_pieces = [] for position in range(0, len(data), 32): piece = data[position:position + 32] all_pieces.append(piece) return all_pieces
python
def split32(data): """ Split data into pieces of 32 bytes. """ all_pieces = [] for position in range(0, len(data), 32): piece = data[position:position + 32] all_pieces.append(piece) return all_pieces
[ "def", "split32", "(", "data", ")", ":", "all_pieces", "=", "[", "]", "for", "position", "in", "range", "(", "0", ",", "len", "(", "data", ")", ",", "32", ")", ":", "piece", "=", "data", "[", "position", ":", "position", "+", "32", "]", "all_pieces", ".", "append", "(", "piece", ")", "return", "all_pieces" ]
Split data into pieces of 32 bytes.
[ "Split", "data", "into", "pieces", "of", "32", "bytes", "." ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/abi.py#L38-L46
229,289
ethereum/pyethereum
ethereum/abi.py
_canonical_type
def _canonical_type(name): # pylint: disable=too-many-return-statements """ Replace aliases to the corresponding type to compute the ids. """ if name == 'int': return 'int256' if name == 'uint': return 'uint256' if name == 'fixed': return 'fixed128x128' if name == 'ufixed': return 'ufixed128x128' if name.startswith('int['): return 'int256' + name[3:] if name.startswith('uint['): return 'uint256' + name[4:] if name.startswith('fixed['): return 'fixed128x128' + name[5:] if name.startswith('ufixed['): return 'ufixed128x128' + name[6:] return name
python
def _canonical_type(name): # pylint: disable=too-many-return-statements """ Replace aliases to the corresponding type to compute the ids. """ if name == 'int': return 'int256' if name == 'uint': return 'uint256' if name == 'fixed': return 'fixed128x128' if name == 'ufixed': return 'ufixed128x128' if name.startswith('int['): return 'int256' + name[3:] if name.startswith('uint['): return 'uint256' + name[4:] if name.startswith('fixed['): return 'fixed128x128' + name[5:] if name.startswith('ufixed['): return 'ufixed128x128' + name[6:] return name
[ "def", "_canonical_type", "(", "name", ")", ":", "# pylint: disable=too-many-return-statements", "if", "name", "==", "'int'", ":", "return", "'int256'", "if", "name", "==", "'uint'", ":", "return", "'uint256'", "if", "name", "==", "'fixed'", ":", "return", "'fixed128x128'", "if", "name", "==", "'ufixed'", ":", "return", "'ufixed128x128'", "if", "name", ".", "startswith", "(", "'int['", ")", ":", "return", "'int256'", "+", "name", "[", "3", ":", "]", "if", "name", ".", "startswith", "(", "'uint['", ")", ":", "return", "'uint256'", "+", "name", "[", "4", ":", "]", "if", "name", ".", "startswith", "(", "'fixed['", ")", ":", "return", "'fixed128x128'", "+", "name", "[", "5", ":", "]", "if", "name", ".", "startswith", "(", "'ufixed['", ")", ":", "return", "'ufixed128x128'", "+", "name", "[", "6", ":", "]", "return", "name" ]
Replace aliases to the corresponding type to compute the ids.
[ "Replace", "aliases", "to", "the", "corresponding", "type", "to", "compute", "the", "ids", "." ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/abi.py#L49-L76
229,290
ethereum/pyethereum
ethereum/abi.py
method_id
def method_id(name, encode_types): """ Return the unique method id. The signature is defined as the canonical expression of the basic prototype, i.e. the function name with the parenthesised list of parameter types. Parameter types are split by a single comma - no spaces are used. The method id is defined as the first four bytes (left, high-order in big-endian) of the Keccak (SHA-3) hash of the signature of the function. """ function_types = [ _canonical_type(type_) for type_ in encode_types ] function_signature = '{function_name}({canonical_types})'.format( function_name=name, canonical_types=','.join(function_types), ) function_keccak = utils.sha3(function_signature) first_bytes = function_keccak[:4] return big_endian_to_int(first_bytes)
python
def method_id(name, encode_types): """ Return the unique method id. The signature is defined as the canonical expression of the basic prototype, i.e. the function name with the parenthesised list of parameter types. Parameter types are split by a single comma - no spaces are used. The method id is defined as the first four bytes (left, high-order in big-endian) of the Keccak (SHA-3) hash of the signature of the function. """ function_types = [ _canonical_type(type_) for type_ in encode_types ] function_signature = '{function_name}({canonical_types})'.format( function_name=name, canonical_types=','.join(function_types), ) function_keccak = utils.sha3(function_signature) first_bytes = function_keccak[:4] return big_endian_to_int(first_bytes)
[ "def", "method_id", "(", "name", ",", "encode_types", ")", ":", "function_types", "=", "[", "_canonical_type", "(", "type_", ")", "for", "type_", "in", "encode_types", "]", "function_signature", "=", "'{function_name}({canonical_types})'", ".", "format", "(", "function_name", "=", "name", ",", "canonical_types", "=", "','", ".", "join", "(", "function_types", ")", ",", ")", "function_keccak", "=", "utils", ".", "sha3", "(", "function_signature", ")", "first_bytes", "=", "function_keccak", "[", ":", "4", "]", "return", "big_endian_to_int", "(", "first_bytes", ")" ]
Return the unique method id. The signature is defined as the canonical expression of the basic prototype, i.e. the function name with the parenthesised list of parameter types. Parameter types are split by a single comma - no spaces are used. The method id is defined as the first four bytes (left, high-order in big-endian) of the Keccak (SHA-3) hash of the signature of the function.
[ "Return", "the", "unique", "method", "id", "." ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/abi.py#L87-L110
229,291
ethereum/pyethereum
ethereum/abi.py
event_id
def event_id(name, encode_types): """ Return the event id. Defined as: `keccak(EVENT_NAME+"("+EVENT_ARGS.map(canonical_type_of).join(",")+")")` Where `canonical_type_of` is a function that simply returns the canonical type of a given argument, e.g. for uint indexed foo, it would return uint256). Note the lack of spaces. """ event_types = [ _canonical_type(type_) for type_ in encode_types ] event_signature = '{event_name}({canonical_types})'.format( event_name=name, canonical_types=','.join(event_types), ) return big_endian_to_int(utils.sha3(event_signature))
python
def event_id(name, encode_types): """ Return the event id. Defined as: `keccak(EVENT_NAME+"("+EVENT_ARGS.map(canonical_type_of).join(",")+")")` Where `canonical_type_of` is a function that simply returns the canonical type of a given argument, e.g. for uint indexed foo, it would return uint256). Note the lack of spaces. """ event_types = [ _canonical_type(type_) for type_ in encode_types ] event_signature = '{event_name}({canonical_types})'.format( event_name=name, canonical_types=','.join(event_types), ) return big_endian_to_int(utils.sha3(event_signature))
[ "def", "event_id", "(", "name", ",", "encode_types", ")", ":", "event_types", "=", "[", "_canonical_type", "(", "type_", ")", "for", "type_", "in", "encode_types", "]", "event_signature", "=", "'{event_name}({canonical_types})'", ".", "format", "(", "event_name", "=", "name", ",", "canonical_types", "=", "','", ".", "join", "(", "event_types", ")", ",", ")", "return", "big_endian_to_int", "(", "utils", ".", "sha3", "(", "event_signature", ")", ")" ]
Return the event id. Defined as: `keccak(EVENT_NAME+"("+EVENT_ARGS.map(canonical_type_of).join(",")+")")` Where `canonical_type_of` is a function that simply returns the canonical type of a given argument, e.g. for uint indexed foo, it would return uint256). Note the lack of spaces.
[ "Return", "the", "event", "id", "." ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/abi.py#L113-L135
229,292
ethereum/pyethereum
ethereum/abi.py
ContractTranslator.encode_function_call
def encode_function_call(self, function_name, args): """ Return the encoded function call. Args: function_name (str): One of the existing functions described in the contract interface. args (List[object]): The function arguments that wll be encoded and used in the contract execution in the vm. Return: bin: The encoded function name and arguments so that it can be used with the evm to execute a funcion call, the binary string follows the Ethereum Contract ABI. """ if function_name not in self.function_data: raise ValueError('Unkown function {}'.format(function_name)) description = self.function_data[function_name] function_selector = zpad(encode_int(description['prefix']), 4) arguments = encode_abi(description['encode_types'], args) return function_selector + arguments
python
def encode_function_call(self, function_name, args): """ Return the encoded function call. Args: function_name (str): One of the existing functions described in the contract interface. args (List[object]): The function arguments that wll be encoded and used in the contract execution in the vm. Return: bin: The encoded function name and arguments so that it can be used with the evm to execute a funcion call, the binary string follows the Ethereum Contract ABI. """ if function_name not in self.function_data: raise ValueError('Unkown function {}'.format(function_name)) description = self.function_data[function_name] function_selector = zpad(encode_int(description['prefix']), 4) arguments = encode_abi(description['encode_types'], args) return function_selector + arguments
[ "def", "encode_function_call", "(", "self", ",", "function_name", ",", "args", ")", ":", "if", "function_name", "not", "in", "self", ".", "function_data", ":", "raise", "ValueError", "(", "'Unkown function {}'", ".", "format", "(", "function_name", ")", ")", "description", "=", "self", ".", "function_data", "[", "function_name", "]", "function_selector", "=", "zpad", "(", "encode_int", "(", "description", "[", "'prefix'", "]", ")", ",", "4", ")", "arguments", "=", "encode_abi", "(", "description", "[", "'encode_types'", "]", ",", "args", ")", "return", "function_selector", "+", "arguments" ]
Return the encoded function call. Args: function_name (str): One of the existing functions described in the contract interface. args (List[object]): The function arguments that wll be encoded and used in the contract execution in the vm. Return: bin: The encoded function name and arguments so that it can be used with the evm to execute a funcion call, the binary string follows the Ethereum Contract ABI.
[ "Return", "the", "encoded", "function", "call", "." ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/abi.py#L502-L524
229,293
ethereum/pyethereum
ethereum/abi.py
ContractTranslator.decode_function_result
def decode_function_result(self, function_name, data): """ Return the function call result decoded. Args: function_name (str): One of the existing functions described in the contract interface. data (bin): The encoded result from calling `function_name`. Return: List[object]: The values returned by the call to `function_name`. """ description = self.function_data[function_name] arguments = decode_abi(description['decode_types'], data) return arguments
python
def decode_function_result(self, function_name, data): """ Return the function call result decoded. Args: function_name (str): One of the existing functions described in the contract interface. data (bin): The encoded result from calling `function_name`. Return: List[object]: The values returned by the call to `function_name`. """ description = self.function_data[function_name] arguments = decode_abi(description['decode_types'], data) return arguments
[ "def", "decode_function_result", "(", "self", ",", "function_name", ",", "data", ")", ":", "description", "=", "self", ".", "function_data", "[", "function_name", "]", "arguments", "=", "decode_abi", "(", "description", "[", "'decode_types'", "]", ",", "data", ")", "return", "arguments" ]
Return the function call result decoded. Args: function_name (str): One of the existing functions described in the contract interface. data (bin): The encoded result from calling `function_name`. Return: List[object]: The values returned by the call to `function_name`.
[ "Return", "the", "function", "call", "result", "decoded", "." ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/abi.py#L526-L539
229,294
ethereum/pyethereum
ethereum/abi.py
ContractTranslator.encode_constructor_arguments
def encode_constructor_arguments(self, args): """ Return the encoded constructor call. """ if self.constructor_data is None: raise ValueError( "The contract interface didn't have a constructor") return encode_abi(self.constructor_data['encode_types'], args)
python
def encode_constructor_arguments(self, args): """ Return the encoded constructor call. """ if self.constructor_data is None: raise ValueError( "The contract interface didn't have a constructor") return encode_abi(self.constructor_data['encode_types'], args)
[ "def", "encode_constructor_arguments", "(", "self", ",", "args", ")", ":", "if", "self", ".", "constructor_data", "is", "None", ":", "raise", "ValueError", "(", "\"The contract interface didn't have a constructor\"", ")", "return", "encode_abi", "(", "self", ".", "constructor_data", "[", "'encode_types'", "]", ",", "args", ")" ]
Return the encoded constructor call.
[ "Return", "the", "encoded", "constructor", "call", "." ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/abi.py#L541-L547
229,295
ethereum/pyethereum
ethereum/abi.py
ContractTranslator.decode_event
def decode_event(self, log_topics, log_data): """ Return a dictionary representation the log. Note: This function won't work with anonymous events. Args: log_topics (List[bin]): The log's indexed arguments. log_data (bin): The encoded non-indexed arguments. """ # https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#function-selector-and-argument-encoding # topics[0]: keccak(EVENT_NAME+"("+EVENT_ARGS.map(canonical_type_of).join(",")+")") # If the event is declared as anonymous the topics[0] is not generated; if not len(log_topics) or log_topics[0] not in self.event_data: raise ValueError('Unknown log type') event_id_ = log_topics[0] event = self.event_data[event_id_] # data: abi_serialise(EVENT_NON_INDEXED_ARGS) # EVENT_NON_INDEXED_ARGS is the series of EVENT_ARGS that are not # indexed, abi_serialise is the ABI serialisation function used for # returning a series of typed values from a function. unindexed_types = [ type_ for type_, indexed in zip(event['types'], event['indexed']) if not indexed ] unindexed_args = decode_abi(unindexed_types, log_data) # topics[n]: EVENT_INDEXED_ARGS[n - 1] # EVENT_INDEXED_ARGS is the series of EVENT_ARGS that are indexed indexed_count = 1 # skip topics[0] result = {} for name, type_, indexed in zip( event['names'], event['types'], event['indexed']): if indexed: topic_bytes = utils.zpad( utils.encode_int(log_topics[indexed_count]), 32, ) indexed_count += 1 value = decode_single(process_type(type_), topic_bytes) else: value = unindexed_args.pop(0) result[name] = value result['_event_type'] = utils.to_string(event['name']) return result
python
def decode_event(self, log_topics, log_data): """ Return a dictionary representation the log. Note: This function won't work with anonymous events. Args: log_topics (List[bin]): The log's indexed arguments. log_data (bin): The encoded non-indexed arguments. """ # https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#function-selector-and-argument-encoding # topics[0]: keccak(EVENT_NAME+"("+EVENT_ARGS.map(canonical_type_of).join(",")+")") # If the event is declared as anonymous the topics[0] is not generated; if not len(log_topics) or log_topics[0] not in self.event_data: raise ValueError('Unknown log type') event_id_ = log_topics[0] event = self.event_data[event_id_] # data: abi_serialise(EVENT_NON_INDEXED_ARGS) # EVENT_NON_INDEXED_ARGS is the series of EVENT_ARGS that are not # indexed, abi_serialise is the ABI serialisation function used for # returning a series of typed values from a function. unindexed_types = [ type_ for type_, indexed in zip(event['types'], event['indexed']) if not indexed ] unindexed_args = decode_abi(unindexed_types, log_data) # topics[n]: EVENT_INDEXED_ARGS[n - 1] # EVENT_INDEXED_ARGS is the series of EVENT_ARGS that are indexed indexed_count = 1 # skip topics[0] result = {} for name, type_, indexed in zip( event['names'], event['types'], event['indexed']): if indexed: topic_bytes = utils.zpad( utils.encode_int(log_topics[indexed_count]), 32, ) indexed_count += 1 value = decode_single(process_type(type_), topic_bytes) else: value = unindexed_args.pop(0) result[name] = value result['_event_type'] = utils.to_string(event['name']) return result
[ "def", "decode_event", "(", "self", ",", "log_topics", ",", "log_data", ")", ":", "# https://github.com/ethereum/wiki/wiki/Ethereum-Contract-ABI#function-selector-and-argument-encoding", "# topics[0]: keccak(EVENT_NAME+\"(\"+EVENT_ARGS.map(canonical_type_of).join(\",\")+\")\")", "# If the event is declared as anonymous the topics[0] is not generated;", "if", "not", "len", "(", "log_topics", ")", "or", "log_topics", "[", "0", "]", "not", "in", "self", ".", "event_data", ":", "raise", "ValueError", "(", "'Unknown log type'", ")", "event_id_", "=", "log_topics", "[", "0", "]", "event", "=", "self", ".", "event_data", "[", "event_id_", "]", "# data: abi_serialise(EVENT_NON_INDEXED_ARGS)", "# EVENT_NON_INDEXED_ARGS is the series of EVENT_ARGS that are not", "# indexed, abi_serialise is the ABI serialisation function used for", "# returning a series of typed values from a function.", "unindexed_types", "=", "[", "type_", "for", "type_", ",", "indexed", "in", "zip", "(", "event", "[", "'types'", "]", ",", "event", "[", "'indexed'", "]", ")", "if", "not", "indexed", "]", "unindexed_args", "=", "decode_abi", "(", "unindexed_types", ",", "log_data", ")", "# topics[n]: EVENT_INDEXED_ARGS[n - 1]", "# EVENT_INDEXED_ARGS is the series of EVENT_ARGS that are indexed", "indexed_count", "=", "1", "# skip topics[0]", "result", "=", "{", "}", "for", "name", ",", "type_", ",", "indexed", "in", "zip", "(", "event", "[", "'names'", "]", ",", "event", "[", "'types'", "]", ",", "event", "[", "'indexed'", "]", ")", ":", "if", "indexed", ":", "topic_bytes", "=", "utils", ".", "zpad", "(", "utils", ".", "encode_int", "(", "log_topics", "[", "indexed_count", "]", ")", ",", "32", ",", ")", "indexed_count", "+=", "1", "value", "=", "decode_single", "(", "process_type", "(", "type_", ")", ",", "topic_bytes", ")", "else", ":", "value", "=", "unindexed_args", ".", "pop", "(", "0", ")", "result", "[", "name", "]", "=", "value", "result", "[", "'_event_type'", "]", "=", "utils", ".", "to_string", "(", "event", "[", "'name'", "]", ")", "return", "result" ]
Return a dictionary representation the log. Note: This function won't work with anonymous events. Args: log_topics (List[bin]): The log's indexed arguments. log_data (bin): The encoded non-indexed arguments.
[ "Return", "a", "dictionary", "representation", "the", "log", "." ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/abi.py#L549-L601
229,296
ethereum/pyethereum
ethereum/abi.py
ContractTranslator.listen
def listen(self, log, noprint=True): """ Return a dictionary representation of the Log instance. Note: This function won't work with anonymous events. Args: log (processblock.Log): The Log instance that needs to be parsed. noprint (bool): Flag to turn off priting of the decoded log instance. """ try: result = self.decode_event(log.topics, log.data) except ValueError: return # api compatibility if not noprint: print(result) return result
python
def listen(self, log, noprint=True): """ Return a dictionary representation of the Log instance. Note: This function won't work with anonymous events. Args: log (processblock.Log): The Log instance that needs to be parsed. noprint (bool): Flag to turn off priting of the decoded log instance. """ try: result = self.decode_event(log.topics, log.data) except ValueError: return # api compatibility if not noprint: print(result) return result
[ "def", "listen", "(", "self", ",", "log", ",", "noprint", "=", "True", ")", ":", "try", ":", "result", "=", "self", ".", "decode_event", "(", "log", ".", "topics", ",", "log", ".", "data", ")", "except", "ValueError", ":", "return", "# api compatibility", "if", "not", "noprint", ":", "print", "(", "result", ")", "return", "result" ]
Return a dictionary representation of the Log instance. Note: This function won't work with anonymous events. Args: log (processblock.Log): The Log instance that needs to be parsed. noprint (bool): Flag to turn off priting of the decoded log instance.
[ "Return", "a", "dictionary", "representation", "of", "the", "Log", "instance", "." ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/abi.py#L603-L622
229,297
ethereum/pyethereum
ethereum/experimental/pruning_trie.py
unpack_to_nibbles
def unpack_to_nibbles(bindata): """unpack packed binary data to nibbles :param bindata: binary packed from nibbles :return: nibbles sequence, may have a terminator """ o = bin_to_nibbles(bindata) flags = o[0] if flags & 2: o.append(NIBBLE_TERMINATOR) if flags & 1 == 1: o = o[1:] else: o = o[2:] return o
python
def unpack_to_nibbles(bindata): """unpack packed binary data to nibbles :param bindata: binary packed from nibbles :return: nibbles sequence, may have a terminator """ o = bin_to_nibbles(bindata) flags = o[0] if flags & 2: o.append(NIBBLE_TERMINATOR) if flags & 1 == 1: o = o[1:] else: o = o[2:] return o
[ "def", "unpack_to_nibbles", "(", "bindata", ")", ":", "o", "=", "bin_to_nibbles", "(", "bindata", ")", "flags", "=", "o", "[", "0", "]", "if", "flags", "&", "2", ":", "o", ".", "append", "(", "NIBBLE_TERMINATOR", ")", "if", "flags", "&", "1", "==", "1", ":", "o", "=", "o", "[", "1", ":", "]", "else", ":", "o", "=", "o", "[", "2", ":", "]", "return", "o" ]
unpack packed binary data to nibbles :param bindata: binary packed from nibbles :return: nibbles sequence, may have a terminator
[ "unpack", "packed", "binary", "data", "to", "nibbles" ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/experimental/pruning_trie.py#L154-L168
229,298
ethereum/pyethereum
ethereum/experimental/pruning_trie.py
starts_with
def starts_with(full, part): """ test whether the items in the part is the leading items of the full """ if len(full) < len(part): return False return full[:len(part)] == part
python
def starts_with(full, part): """ test whether the items in the part is the leading items of the full """ if len(full) < len(part): return False return full[:len(part)] == part
[ "def", "starts_with", "(", "full", ",", "part", ")", ":", "if", "len", "(", "full", ")", "<", "len", "(", "part", ")", ":", "return", "False", "return", "full", "[", ":", "len", "(", "part", ")", "]", "==", "part" ]
test whether the items in the part is the leading items of the full
[ "test", "whether", "the", "items", "in", "the", "part", "is", "the", "leading", "items", "of", "the", "full" ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/experimental/pruning_trie.py#L171-L177
229,299
ethereum/pyethereum
ethereum/experimental/pruning_trie.py
Trie._get_node_type
def _get_node_type(self, node): """ get node type and content :param node: node in form of list, or BLANK_NODE :return: node type """ if node == BLANK_NODE: return NODE_TYPE_BLANK if len(node) == 2: nibbles = unpack_to_nibbles(node[0]) has_terminator = (nibbles and nibbles[-1] == NIBBLE_TERMINATOR) return NODE_TYPE_LEAF if has_terminator\ else NODE_TYPE_EXTENSION if len(node) == 17: return NODE_TYPE_BRANCH
python
def _get_node_type(self, node): """ get node type and content :param node: node in form of list, or BLANK_NODE :return: node type """ if node == BLANK_NODE: return NODE_TYPE_BLANK if len(node) == 2: nibbles = unpack_to_nibbles(node[0]) has_terminator = (nibbles and nibbles[-1] == NIBBLE_TERMINATOR) return NODE_TYPE_LEAF if has_terminator\ else NODE_TYPE_EXTENSION if len(node) == 17: return NODE_TYPE_BRANCH
[ "def", "_get_node_type", "(", "self", ",", "node", ")", ":", "if", "node", "==", "BLANK_NODE", ":", "return", "NODE_TYPE_BLANK", "if", "len", "(", "node", ")", "==", "2", ":", "nibbles", "=", "unpack_to_nibbles", "(", "node", "[", "0", "]", ")", "has_terminator", "=", "(", "nibbles", "and", "nibbles", "[", "-", "1", "]", "==", "NIBBLE_TERMINATOR", ")", "return", "NODE_TYPE_LEAF", "if", "has_terminator", "else", "NODE_TYPE_EXTENSION", "if", "len", "(", "node", ")", "==", "17", ":", "return", "NODE_TYPE_BRANCH" ]
get node type and content :param node: node in form of list, or BLANK_NODE :return: node type
[ "get", "node", "type", "and", "content" ]
b704a5c6577863edc539a1ec3d2620a443b950fb
https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/experimental/pruning_trie.py#L353-L368