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 listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
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",
"(",
"... | 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 | train | 224,100 |
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 initializatio... | 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 | train | 224,101 |
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 ... | 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 | train | 224,102 |
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_tem... | 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 | train | 224,103 |
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",
"... | 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 | train | 224,104 |
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",
... | 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 | train | 224,105 |
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",
":",
"re... | 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 | train | 224,106 |
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",
... | 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 | train | 224,107 |
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 | train | 224,108 |
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",
"[",... | 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 | train | 224,109 |
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... | 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 | train | 224,110 |
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",
".",... | 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 | train | 224,111 |
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... | 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 | train | 224,112 |
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",
... | 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 | train | 224,113 |
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_... | 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 | train | 224,114 |
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",
... | 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 | train | 224,115 |
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",
... | 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 | train | 224,116 |
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",
".",
"... | 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 | train | 224,117 |
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",
"(... | 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 | train | 224,118 |
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",
"=",
"m... | 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 | train | 224,119 |
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 | train | 224,120 |
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",
"bbo... | 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 | train | 224,121 |
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... | 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 | train | 224,122 |
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",
... | 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 | train | 224,123 |
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",
")",... | 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 | train | 224,124 |
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",... | 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 | train | 224,125 |
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",
"(",
")",
... | 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 | train | 224,126 |
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",
"i... | 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 | train | 224,127 |
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",
... | 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 | train | 224,128 |
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",
"=",
"'-'",
".",
"joi... | 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 | train | 224,129 |
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",
"(",
"fold... | 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 | train | 224,130 |
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",
... | 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 | train | 224,131 |
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 | train | 224,132 |
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_ty... | 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 | train | 224,133 |
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",
... | 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 | train | 224,134 |
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",
":... | 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 | train | 224,135 |
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",
... | 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 | train | 224,136 |
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",
... | 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 | train | 224,137 |
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",
".",
... | 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 | train | 224,138 |
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_tile... | 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 | train | 224,139 |
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",
"."... | 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 | train | 224,140 |
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",... | 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 | train | 224,141 |
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_piec... | 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 | train | 224,142 |
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",
"'fix... | 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 | train | 224,143 |
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",
"(",
"fun... | 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 | train | 224,144 |
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",
... | 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 | train | 224,145 |
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",
")",
")",
"... | 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 | train | 224,146 |
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 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 | train | 224,147 |
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",
".",
"c... | Return the encoded constructor call. | [
"Return",
"the",
"encoded",
"constructor",
"call",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/abi.py#L541-L547 | train | 224,148 |
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 ev... | 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 | train | 224,149 |
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 compatibilit... | 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 | train | 224,150 |
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",
"==",
... | 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 | train | 224,151 |
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 | train | 224,152 |
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_t... | 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 | train | 224,153 |
ethereum/pyethereum | ethereum/experimental/pruning_trie.py | Trie._get | def _get(self, node, key):
""" get value inside a node
:param node: node in form of list, or BLANK_NODE
:param key: nibble list without terminator
:return:
BLANK_NODE if does not exist, otherwise value or hash
"""
node_type = self._get_node_type(node)
if node_type == NODE_TYPE_BLANK:
return BLANK_NODE
if node_type == NODE_TYPE_BRANCH:
# already reach the expected node
if not key:
return node[-1]
sub_node = self._decode_to_node(node[key[0]])
return self._get(sub_node, key[1:])
# key value node
curr_key = without_terminator(unpack_to_nibbles(node[0]))
if node_type == NODE_TYPE_LEAF:
return node[1] if key == curr_key else BLANK_NODE
if node_type == NODE_TYPE_EXTENSION:
# traverse child nodes
if starts_with(key, curr_key):
sub_node = self._decode_to_node(node[1])
return self._get(sub_node, key[len(curr_key):])
else:
return BLANK_NODE | python | def _get(self, node, key):
""" get value inside a node
:param node: node in form of list, or BLANK_NODE
:param key: nibble list without terminator
:return:
BLANK_NODE if does not exist, otherwise value or hash
"""
node_type = self._get_node_type(node)
if node_type == NODE_TYPE_BLANK:
return BLANK_NODE
if node_type == NODE_TYPE_BRANCH:
# already reach the expected node
if not key:
return node[-1]
sub_node = self._decode_to_node(node[key[0]])
return self._get(sub_node, key[1:])
# key value node
curr_key = without_terminator(unpack_to_nibbles(node[0]))
if node_type == NODE_TYPE_LEAF:
return node[1] if key == curr_key else BLANK_NODE
if node_type == NODE_TYPE_EXTENSION:
# traverse child nodes
if starts_with(key, curr_key):
sub_node = self._decode_to_node(node[1])
return self._get(sub_node, key[len(curr_key):])
else:
return BLANK_NODE | [
"def",
"_get",
"(",
"self",
",",
"node",
",",
"key",
")",
":",
"node_type",
"=",
"self",
".",
"_get_node_type",
"(",
"node",
")",
"if",
"node_type",
"==",
"NODE_TYPE_BLANK",
":",
"return",
"BLANK_NODE",
"if",
"node_type",
"==",
"NODE_TYPE_BRANCH",
":",
"# ... | get value inside a node
:param node: node in form of list, or BLANK_NODE
:param key: nibble list without terminator
:return:
BLANK_NODE if does not exist, otherwise value or hash | [
"get",
"value",
"inside",
"a",
"node"
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/experimental/pruning_trie.py#L370-L401 | train | 224,154 |
ethereum/pyethereum | ethereum/experimental/pruning_trie.py | Trie._normalize_branch_node | def _normalize_branch_node(self, node):
# sys.stderr.write('nbn\n')
"""node should have only one item changed
"""
not_blank_items_count = sum(1 for x in range(17) if node[x])
assert not_blank_items_count >= 1
if not_blank_items_count > 1:
self._encode_node(node)
return node
# now only one item is not blank
not_blank_index = [i for i, item in enumerate(node) if item][0]
# the value item is not blank
if not_blank_index == 16:
o = [pack_nibbles(with_terminator([])), node[16]]
self._encode_node(o)
return o
# normal item is not blank
sub_node = self._decode_to_node(node[not_blank_index])
sub_node_type = self._get_node_type(sub_node)
if is_key_value_type(sub_node_type):
# collape subnode to this node, not this node will have same
# terminator with the new sub node, and value does not change
self._delete_node_storage(sub_node)
new_key = [not_blank_index] + \
unpack_to_nibbles(sub_node[0])
o = [pack_nibbles(new_key), sub_node[1]]
self._encode_node(o)
return o
if sub_node_type == NODE_TYPE_BRANCH:
o = [pack_nibbles([not_blank_index]),
node[not_blank_index]]
self._encode_node(o)
return o
assert False | python | def _normalize_branch_node(self, node):
# sys.stderr.write('nbn\n')
"""node should have only one item changed
"""
not_blank_items_count = sum(1 for x in range(17) if node[x])
assert not_blank_items_count >= 1
if not_blank_items_count > 1:
self._encode_node(node)
return node
# now only one item is not blank
not_blank_index = [i for i, item in enumerate(node) if item][0]
# the value item is not blank
if not_blank_index == 16:
o = [pack_nibbles(with_terminator([])), node[16]]
self._encode_node(o)
return o
# normal item is not blank
sub_node = self._decode_to_node(node[not_blank_index])
sub_node_type = self._get_node_type(sub_node)
if is_key_value_type(sub_node_type):
# collape subnode to this node, not this node will have same
# terminator with the new sub node, and value does not change
self._delete_node_storage(sub_node)
new_key = [not_blank_index] + \
unpack_to_nibbles(sub_node[0])
o = [pack_nibbles(new_key), sub_node[1]]
self._encode_node(o)
return o
if sub_node_type == NODE_TYPE_BRANCH:
o = [pack_nibbles([not_blank_index]),
node[not_blank_index]]
self._encode_node(o)
return o
assert False | [
"def",
"_normalize_branch_node",
"(",
"self",
",",
"node",
")",
":",
"# sys.stderr.write('nbn\\n')",
"not_blank_items_count",
"=",
"sum",
"(",
"1",
"for",
"x",
"in",
"range",
"(",
"17",
")",
"if",
"node",
"[",
"x",
"]",
")",
"assert",
"not_blank_items_count",
... | node should have only one item changed | [
"node",
"should",
"have",
"only",
"one",
"item",
"changed"
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/experimental/pruning_trie.py#L650-L688 | train | 224,155 |
ethereum/pyethereum | ethereum/slogging.py | DEBUG | def DEBUG(msg, *args, **kwargs):
"""temporary logger during development that is always on"""
logger = getLogger("DEBUG")
if len(logger.handlers) == 0:
logger.addHandler(StreamHandler())
logger.propagate = False
logger.setLevel(logging.DEBUG)
logger.DEV(msg, *args, **kwargs) | python | def DEBUG(msg, *args, **kwargs):
"""temporary logger during development that is always on"""
logger = getLogger("DEBUG")
if len(logger.handlers) == 0:
logger.addHandler(StreamHandler())
logger.propagate = False
logger.setLevel(logging.DEBUG)
logger.DEV(msg, *args, **kwargs) | [
"def",
"DEBUG",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"logger",
"=",
"getLogger",
"(",
"\"DEBUG\"",
")",
"if",
"len",
"(",
"logger",
".",
"handlers",
")",
"==",
"0",
":",
"logger",
".",
"addHandler",
"(",
"StreamHandler",
... | temporary logger during development that is always on | [
"temporary",
"logger",
"during",
"development",
"that",
"is",
"always",
"on"
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/slogging.py#L349-L356 | train | 224,156 |
ethereum/pyethereum | ethereum/vm.py | vm_trace | def vm_trace(ext, msg, compustate, opcode, pushcache, tracer=log_vm_op):
"""
This diverges from normal logging, as we use the logging namespace
only to decide which features get logged in 'eth.vm.op'
i.e. tracing can not be activated by activating a sub
like 'eth.vm.op.stack'
"""
op, in_args, out_args, fee = opcodes.opcodes[opcode]
trace_data = {}
trace_data['stack'] = list(map(to_string, list(compustate.prev_stack)))
if compustate.prev_prev_op in ('MLOAD', 'MSTORE', 'MSTORE8', 'SHA3', 'CALL',
'CALLCODE', 'CREATE', 'CALLDATACOPY', 'CODECOPY',
'EXTCODECOPY'):
if len(compustate.prev_memory) < 4096:
trace_data['memory'] = \
''.join([encode_hex(ascii_chr(x)) for x
in compustate.prev_memory])
else:
trace_data['sha3memory'] = \
encode_hex(utils.sha3(b''.join([ascii_chr(x) for
x in compustate.prev_memory])))
if compustate.prev_prev_op in ('SSTORE',) or compustate.steps == 0:
trace_data['storage'] = ext.log_storage(msg.to)
trace_data['gas'] = to_string(compustate.prev_gas)
trace_data['gas_cost'] = to_string(compustate.prev_gas - compustate.gas)
trace_data['fee'] = fee
trace_data['inst'] = opcode
trace_data['pc'] = to_string(compustate.prev_pc)
if compustate.steps == 0:
trace_data['depth'] = msg.depth
trace_data['address'] = msg.to
trace_data['steps'] = compustate.steps
trace_data['depth'] = msg.depth
if op[:4] == 'PUSH':
print(repr(pushcache))
trace_data['pushvalue'] = pushcache[compustate.prev_pc]
tracer.trace('vm', op=op, **trace_data)
compustate.steps += 1
compustate.prev_prev_op = op | python | def vm_trace(ext, msg, compustate, opcode, pushcache, tracer=log_vm_op):
"""
This diverges from normal logging, as we use the logging namespace
only to decide which features get logged in 'eth.vm.op'
i.e. tracing can not be activated by activating a sub
like 'eth.vm.op.stack'
"""
op, in_args, out_args, fee = opcodes.opcodes[opcode]
trace_data = {}
trace_data['stack'] = list(map(to_string, list(compustate.prev_stack)))
if compustate.prev_prev_op in ('MLOAD', 'MSTORE', 'MSTORE8', 'SHA3', 'CALL',
'CALLCODE', 'CREATE', 'CALLDATACOPY', 'CODECOPY',
'EXTCODECOPY'):
if len(compustate.prev_memory) < 4096:
trace_data['memory'] = \
''.join([encode_hex(ascii_chr(x)) for x
in compustate.prev_memory])
else:
trace_data['sha3memory'] = \
encode_hex(utils.sha3(b''.join([ascii_chr(x) for
x in compustate.prev_memory])))
if compustate.prev_prev_op in ('SSTORE',) or compustate.steps == 0:
trace_data['storage'] = ext.log_storage(msg.to)
trace_data['gas'] = to_string(compustate.prev_gas)
trace_data['gas_cost'] = to_string(compustate.prev_gas - compustate.gas)
trace_data['fee'] = fee
trace_data['inst'] = opcode
trace_data['pc'] = to_string(compustate.prev_pc)
if compustate.steps == 0:
trace_data['depth'] = msg.depth
trace_data['address'] = msg.to
trace_data['steps'] = compustate.steps
trace_data['depth'] = msg.depth
if op[:4] == 'PUSH':
print(repr(pushcache))
trace_data['pushvalue'] = pushcache[compustate.prev_pc]
tracer.trace('vm', op=op, **trace_data)
compustate.steps += 1
compustate.prev_prev_op = op | [
"def",
"vm_trace",
"(",
"ext",
",",
"msg",
",",
"compustate",
",",
"opcode",
",",
"pushcache",
",",
"tracer",
"=",
"log_vm_op",
")",
":",
"op",
",",
"in_args",
",",
"out_args",
",",
"fee",
"=",
"opcodes",
".",
"opcodes",
"[",
"opcode",
"]",
"trace_data... | This diverges from normal logging, as we use the logging namespace
only to decide which features get logged in 'eth.vm.op'
i.e. tracing can not be activated by activating a sub
like 'eth.vm.op.stack' | [
"This",
"diverges",
"from",
"normal",
"logging",
"as",
"we",
"use",
"the",
"logging",
"namespace",
"only",
"to",
"decide",
"which",
"features",
"get",
"logged",
"in",
"eth",
".",
"vm",
".",
"op",
"i",
".",
"e",
".",
"tracing",
"can",
"not",
"be",
"acti... | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/vm.py#L202-L242 | train | 224,157 |
ethereum/pyethereum | ethereum/transactions.py | Transaction.sign | def sign(self, key, network_id=None):
"""Sign this transaction with a private key.
A potentially already existing signature would be overridden.
"""
if network_id is None:
rawhash = utils.sha3(rlp.encode(unsigned_tx_from_tx(self), UnsignedTransaction))
else:
assert 1 <= network_id < 2**63 - 18
rlpdata = rlp.encode(rlp.infer_sedes(self).serialize(self)[
:-3] + [network_id, b'', b''])
rawhash = utils.sha3(rlpdata)
key = normalize_key(key)
v, r, s = ecsign(rawhash, key)
if network_id is not None:
v += 8 + network_id * 2
ret = self.copy(
v=v, r=r, s=s
)
ret._sender = utils.privtoaddr(key)
return ret | python | def sign(self, key, network_id=None):
"""Sign this transaction with a private key.
A potentially already existing signature would be overridden.
"""
if network_id is None:
rawhash = utils.sha3(rlp.encode(unsigned_tx_from_tx(self), UnsignedTransaction))
else:
assert 1 <= network_id < 2**63 - 18
rlpdata = rlp.encode(rlp.infer_sedes(self).serialize(self)[
:-3] + [network_id, b'', b''])
rawhash = utils.sha3(rlpdata)
key = normalize_key(key)
v, r, s = ecsign(rawhash, key)
if network_id is not None:
v += 8 + network_id * 2
ret = self.copy(
v=v, r=r, s=s
)
ret._sender = utils.privtoaddr(key)
return ret | [
"def",
"sign",
"(",
"self",
",",
"key",
",",
"network_id",
"=",
"None",
")",
":",
"if",
"network_id",
"is",
"None",
":",
"rawhash",
"=",
"utils",
".",
"sha3",
"(",
"rlp",
".",
"encode",
"(",
"unsigned_tx_from_tx",
"(",
"self",
")",
",",
"UnsignedTransa... | Sign this transaction with a private key.
A potentially already existing signature would be overridden. | [
"Sign",
"this",
"transaction",
"with",
"a",
"private",
"key",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/transactions.py#L118-L141 | train | 224,158 |
ethereum/pyethereum | ethereum/transactions.py | Transaction.creates | def creates(self):
"returns the address of a contract created by this tx"
if self.to in (b'', '\0' * 20):
return mk_contract_address(self.sender, self.nonce) | python | def creates(self):
"returns the address of a contract created by this tx"
if self.to in (b'', '\0' * 20):
return mk_contract_address(self.sender, self.nonce) | [
"def",
"creates",
"(",
"self",
")",
":",
"if",
"self",
".",
"to",
"in",
"(",
"b''",
",",
"'\\0'",
"*",
"20",
")",
":",
"return",
"mk_contract_address",
"(",
"self",
".",
"sender",
",",
"self",
".",
"nonce",
")"
] | returns the address of a contract created by this tx | [
"returns",
"the",
"address",
"of",
"a",
"contract",
"created",
"by",
"this",
"tx"
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/transactions.py#L167-L170 | train | 224,159 |
ethereum/pyethereum | ethereum/pow/ethpow.py | check_pow | def check_pow(block_number, header_hash, mixhash, nonce, difficulty):
"""Check if the proof-of-work of the block is valid.
:param nonce: if given the proof of work function will be evaluated
with this nonce instead of the one already present in
the header
:returns: `True` or `False`
"""
log.debug('checking pow', block_number=block_number)
if len(mixhash) != 32 or len(header_hash) != 32 or len(nonce) != 8:
return False
# Grab current cache
cache = get_cache(block_number)
mining_output = hashimoto_light(block_number, cache, header_hash, nonce)
if mining_output[b'mix digest'] != mixhash:
return False
return utils.big_endian_to_int(
mining_output[b'result']) <= 2**256 // (difficulty or 1) | python | def check_pow(block_number, header_hash, mixhash, nonce, difficulty):
"""Check if the proof-of-work of the block is valid.
:param nonce: if given the proof of work function will be evaluated
with this nonce instead of the one already present in
the header
:returns: `True` or `False`
"""
log.debug('checking pow', block_number=block_number)
if len(mixhash) != 32 or len(header_hash) != 32 or len(nonce) != 8:
return False
# Grab current cache
cache = get_cache(block_number)
mining_output = hashimoto_light(block_number, cache, header_hash, nonce)
if mining_output[b'mix digest'] != mixhash:
return False
return utils.big_endian_to_int(
mining_output[b'result']) <= 2**256 // (difficulty or 1) | [
"def",
"check_pow",
"(",
"block_number",
",",
"header_hash",
",",
"mixhash",
",",
"nonce",
",",
"difficulty",
")",
":",
"log",
".",
"debug",
"(",
"'checking pow'",
",",
"block_number",
"=",
"block_number",
")",
"if",
"len",
"(",
"mixhash",
")",
"!=",
"32",... | Check if the proof-of-work of the block is valid.
:param nonce: if given the proof of work function will be evaluated
with this nonce instead of the one already present in
the header
:returns: `True` or `False` | [
"Check",
"if",
"the",
"proof",
"-",
"of",
"-",
"work",
"of",
"the",
"block",
"is",
"valid",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/pow/ethpow.py#L62-L80 | train | 224,160 |
ethereum/pyethereum | ethereum/block.py | BlockHeader.to_dict | def to_dict(self):
"""Serialize the header to a readable dictionary."""
d = {}
for field in ('prevhash', 'uncles_hash', 'extra_data', 'nonce',
'mixhash'):
d[field] = '0x' + encode_hex(getattr(self, field))
for field in ('state_root', 'tx_list_root', 'receipts_root',
'coinbase'):
d[field] = encode_hex(getattr(self, field))
for field in ('number', 'difficulty', 'gas_limit', 'gas_used',
'timestamp'):
d[field] = utils.to_string(getattr(self, field))
d['bloom'] = encode_hex(int256.serialize(self.bloom))
assert len(d) == len(BlockHeader.fields)
return d | python | def to_dict(self):
"""Serialize the header to a readable dictionary."""
d = {}
for field in ('prevhash', 'uncles_hash', 'extra_data', 'nonce',
'mixhash'):
d[field] = '0x' + encode_hex(getattr(self, field))
for field in ('state_root', 'tx_list_root', 'receipts_root',
'coinbase'):
d[field] = encode_hex(getattr(self, field))
for field in ('number', 'difficulty', 'gas_limit', 'gas_used',
'timestamp'):
d[field] = utils.to_string(getattr(self, field))
d['bloom'] = encode_hex(int256.serialize(self.bloom))
assert len(d) == len(BlockHeader.fields)
return d | [
"def",
"to_dict",
"(",
"self",
")",
":",
"d",
"=",
"{",
"}",
"for",
"field",
"in",
"(",
"'prevhash'",
",",
"'uncles_hash'",
",",
"'extra_data'",
",",
"'nonce'",
",",
"'mixhash'",
")",
":",
"d",
"[",
"field",
"]",
"=",
"'0x'",
"+",
"encode_hex",
"(",
... | Serialize the header to a readable dictionary. | [
"Serialize",
"the",
"header",
"to",
"a",
"readable",
"dictionary",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/block.py#L137-L151 | train | 224,161 |
ethereum/pyethereum | ethereum/utils.py | decode_int | def decode_int(v):
"""decodes and integer from serialization"""
if len(v) > 0 and (v[0] == b'\x00' or v[0] == 0):
raise Exception("No leading zero bytes allowed for integers")
return big_endian_to_int(v) | python | def decode_int(v):
"""decodes and integer from serialization"""
if len(v) > 0 and (v[0] == b'\x00' or v[0] == 0):
raise Exception("No leading zero bytes allowed for integers")
return big_endian_to_int(v) | [
"def",
"decode_int",
"(",
"v",
")",
":",
"if",
"len",
"(",
"v",
")",
">",
"0",
"and",
"(",
"v",
"[",
"0",
"]",
"==",
"b'\\x00'",
"or",
"v",
"[",
"0",
"]",
"==",
"0",
")",
":",
"raise",
"Exception",
"(",
"\"No leading zero bytes allowed for integers\"... | decodes and integer from serialization | [
"decodes",
"and",
"integer",
"from",
"serialization"
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/utils.py#L350-L354 | train | 224,162 |
ethereum/pyethereum | ethereum/utils.py | encode_int | def encode_int(v):
"""encodes an integer into serialization"""
if not is_numeric(v) or v < 0 or v >= TT256:
raise Exception("Integer invalid or out of range: %r" % v)
return int_to_big_endian(v) | python | def encode_int(v):
"""encodes an integer into serialization"""
if not is_numeric(v) or v < 0 or v >= TT256:
raise Exception("Integer invalid or out of range: %r" % v)
return int_to_big_endian(v) | [
"def",
"encode_int",
"(",
"v",
")",
":",
"if",
"not",
"is_numeric",
"(",
"v",
")",
"or",
"v",
"<",
"0",
"or",
"v",
">=",
"TT256",
":",
"raise",
"Exception",
"(",
"\"Integer invalid or out of range: %r\"",
"%",
"v",
")",
"return",
"int_to_big_endian",
"(",
... | encodes an integer into serialization | [
"encodes",
"an",
"integer",
"into",
"serialization"
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/utils.py#L371-L375 | train | 224,163 |
ethereum/pyethereum | ethereum/utils.py | print_func_call | def print_func_call(ignore_first_arg=False, max_call_number=100):
""" utility function to facilitate debug, it will print input args before
function call, and print return value after function call
usage:
@print_func_call
def some_func_to_be_debu():
pass
:param ignore_first_arg: whether print the first arg or not.
useful when ignore the `self` parameter of an object method call
"""
from functools import wraps
def display(x):
x = to_string(x)
try:
x.decode('ascii')
except BaseException:
return 'NON_PRINTABLE'
return x
local = {'call_number': 0}
def inner(f):
@wraps(f)
def wrapper(*args, **kwargs):
local['call_number'] += 1
tmp_args = args[1:] if ignore_first_arg and len(args) else args
this_call_number = local['call_number']
print(('{0}#{1} args: {2}, {3}'.format(
f.__name__,
this_call_number,
', '.join([display(x) for x in tmp_args]),
', '.join(display(key) + '=' + to_string(value)
for key, value in kwargs.items())
)))
res = f(*args, **kwargs)
print(('{0}#{1} return: {2}'.format(
f.__name__,
this_call_number,
display(res))))
if local['call_number'] > 100:
raise Exception("Touch max call number!")
return res
return wrapper
return inner | python | def print_func_call(ignore_first_arg=False, max_call_number=100):
""" utility function to facilitate debug, it will print input args before
function call, and print return value after function call
usage:
@print_func_call
def some_func_to_be_debu():
pass
:param ignore_first_arg: whether print the first arg or not.
useful when ignore the `self` parameter of an object method call
"""
from functools import wraps
def display(x):
x = to_string(x)
try:
x.decode('ascii')
except BaseException:
return 'NON_PRINTABLE'
return x
local = {'call_number': 0}
def inner(f):
@wraps(f)
def wrapper(*args, **kwargs):
local['call_number'] += 1
tmp_args = args[1:] if ignore_first_arg and len(args) else args
this_call_number = local['call_number']
print(('{0}#{1} args: {2}, {3}'.format(
f.__name__,
this_call_number,
', '.join([display(x) for x in tmp_args]),
', '.join(display(key) + '=' + to_string(value)
for key, value in kwargs.items())
)))
res = f(*args, **kwargs)
print(('{0}#{1} return: {2}'.format(
f.__name__,
this_call_number,
display(res))))
if local['call_number'] > 100:
raise Exception("Touch max call number!")
return res
return wrapper
return inner | [
"def",
"print_func_call",
"(",
"ignore_first_arg",
"=",
"False",
",",
"max_call_number",
"=",
"100",
")",
":",
"from",
"functools",
"import",
"wraps",
"def",
"display",
"(",
"x",
")",
":",
"x",
"=",
"to_string",
"(",
"x",
")",
"try",
":",
"x",
".",
"de... | utility function to facilitate debug, it will print input args before
function call, and print return value after function call
usage:
@print_func_call
def some_func_to_be_debu():
pass
:param ignore_first_arg: whether print the first arg or not.
useful when ignore the `self` parameter of an object method call | [
"utility",
"function",
"to",
"facilitate",
"debug",
"it",
"will",
"print",
"input",
"args",
"before",
"function",
"call",
"and",
"print",
"return",
"value",
"after",
"function",
"call"
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/utils.py#L449-L498 | train | 224,164 |
ethereum/pyethereum | ethereum/tools/_solidity.py | get_compiler_path | def get_compiler_path():
""" Return the path to the solc compiler.
This funtion will search for the solc binary in the $PATH and return the
path of the first executable occurence.
"""
# If the user provides a specific solc binary let's use that
given_binary = os.environ.get('SOLC_BINARY')
if given_binary:
return given_binary
for path in os.getenv('PATH', '').split(os.pathsep):
path = path.strip('"')
executable_path = os.path.join(path, BINARY)
if os.path.isfile(executable_path) and os.access(
executable_path, os.X_OK):
return executable_path
return None | python | def get_compiler_path():
""" Return the path to the solc compiler.
This funtion will search for the solc binary in the $PATH and return the
path of the first executable occurence.
"""
# If the user provides a specific solc binary let's use that
given_binary = os.environ.get('SOLC_BINARY')
if given_binary:
return given_binary
for path in os.getenv('PATH', '').split(os.pathsep):
path = path.strip('"')
executable_path = os.path.join(path, BINARY)
if os.path.isfile(executable_path) and os.access(
executable_path, os.X_OK):
return executable_path
return None | [
"def",
"get_compiler_path",
"(",
")",
":",
"# If the user provides a specific solc binary let's use that",
"given_binary",
"=",
"os",
".",
"environ",
".",
"get",
"(",
"'SOLC_BINARY'",
")",
"if",
"given_binary",
":",
"return",
"given_binary",
"for",
"path",
"in",
"os",... | Return the path to the solc compiler.
This funtion will search for the solc binary in the $PATH and return the
path of the first executable occurence. | [
"Return",
"the",
"path",
"to",
"the",
"solc",
"compiler",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L24-L43 | train | 224,165 |
ethereum/pyethereum | ethereum/tools/_solidity.py | solc_arguments | def solc_arguments(libraries=None, combined='bin,abi',
optimize=True, extra_args=None):
""" Build the arguments to call the solc binary. """
args = [
'--combined-json', combined,
]
def str_of(address):
"""cast address to string. py2/3 compatability. """
try:
return address.decode('utf8')
except AttributeError:
return address
if optimize:
args.append('--optimize')
if extra_args:
try:
args.extend(shlex.split(extra_args))
except BaseException: # if not a parseable string then treat it as a list
args.extend(extra_args)
if libraries is not None and len(libraries):
addresses = [
'{name}:{address}'.format(
name=name, address=str_of(address))
for name, address in libraries.items()
]
args.extend([
'--libraries',
','.join(addresses),
])
return args | python | def solc_arguments(libraries=None, combined='bin,abi',
optimize=True, extra_args=None):
""" Build the arguments to call the solc binary. """
args = [
'--combined-json', combined,
]
def str_of(address):
"""cast address to string. py2/3 compatability. """
try:
return address.decode('utf8')
except AttributeError:
return address
if optimize:
args.append('--optimize')
if extra_args:
try:
args.extend(shlex.split(extra_args))
except BaseException: # if not a parseable string then treat it as a list
args.extend(extra_args)
if libraries is not None and len(libraries):
addresses = [
'{name}:{address}'.format(
name=name, address=str_of(address))
for name, address in libraries.items()
]
args.extend([
'--libraries',
','.join(addresses),
])
return args | [
"def",
"solc_arguments",
"(",
"libraries",
"=",
"None",
",",
"combined",
"=",
"'bin,abi'",
",",
"optimize",
"=",
"True",
",",
"extra_args",
"=",
"None",
")",
":",
"args",
"=",
"[",
"'--combined-json'",
",",
"combined",
",",
"]",
"def",
"str_of",
"(",
"ad... | Build the arguments to call the solc binary. | [
"Build",
"the",
"arguments",
"to",
"call",
"the",
"solc",
"binary",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L54-L89 | train | 224,166 |
ethereum/pyethereum | ethereum/tools/_solidity.py | solc_parse_output | def solc_parse_output(compiler_output):
""" Parses the compiler output. """
# At the moment some solc output like --hashes or -- gas will not output
# json at all so if used with those arguments the logic here will break.
# Perhaps solidity will slowly switch to a json only output and this comment
# can eventually go away and we will not need to add more logic here at
# all.
result = yaml.safe_load(compiler_output)['contracts']
if 'bin' in tuple(result.values())[0]:
for value in result.values():
value['bin_hex'] = value['bin']
# decoding can fail if the compiled contract has unresolved symbols
try:
value['bin'] = decode_hex(value['bin_hex'])
except (TypeError, ValueError):
pass
for json_data in ('abi', 'devdoc', 'userdoc'):
# the values in the output can be configured through the
# --combined-json flag, check that it's present in the first value and
# assume all values are consistent
if json_data not in tuple(result.values())[0]:
continue
for value in result.values():
value[json_data] = yaml.safe_load(value[json_data])
return result | python | def solc_parse_output(compiler_output):
""" Parses the compiler output. """
# At the moment some solc output like --hashes or -- gas will not output
# json at all so if used with those arguments the logic here will break.
# Perhaps solidity will slowly switch to a json only output and this comment
# can eventually go away and we will not need to add more logic here at
# all.
result = yaml.safe_load(compiler_output)['contracts']
if 'bin' in tuple(result.values())[0]:
for value in result.values():
value['bin_hex'] = value['bin']
# decoding can fail if the compiled contract has unresolved symbols
try:
value['bin'] = decode_hex(value['bin_hex'])
except (TypeError, ValueError):
pass
for json_data in ('abi', 'devdoc', 'userdoc'):
# the values in the output can be configured through the
# --combined-json flag, check that it's present in the first value and
# assume all values are consistent
if json_data not in tuple(result.values())[0]:
continue
for value in result.values():
value[json_data] = yaml.safe_load(value[json_data])
return result | [
"def",
"solc_parse_output",
"(",
"compiler_output",
")",
":",
"# At the moment some solc output like --hashes or -- gas will not output",
"# json at all so if used with those arguments the logic here will break.",
"# Perhaps solidity will slowly switch to a json only output and this comment",
"# c... | Parses the compiler output. | [
"Parses",
"the",
"compiler",
"output",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L92-L121 | train | 224,167 |
ethereum/pyethereum | ethereum/tools/_solidity.py | compiler_version | def compiler_version():
""" Return the version of the installed solc. """
version_info = subprocess.check_output(['solc', '--version'])
match = re.search(b'^Version: ([0-9a-z.-]+)/', version_info, re.MULTILINE)
if match:
return match.group(1) | python | def compiler_version():
""" Return the version of the installed solc. """
version_info = subprocess.check_output(['solc', '--version'])
match = re.search(b'^Version: ([0-9a-z.-]+)/', version_info, re.MULTILINE)
if match:
return match.group(1) | [
"def",
"compiler_version",
"(",
")",
":",
"version_info",
"=",
"subprocess",
".",
"check_output",
"(",
"[",
"'solc'",
",",
"'--version'",
"]",
")",
"match",
"=",
"re",
".",
"search",
"(",
"b'^Version: ([0-9a-z.-]+)/'",
",",
"version_info",
",",
"re",
".",
"M... | Return the version of the installed solc. | [
"Return",
"the",
"version",
"of",
"the",
"installed",
"solc",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L124-L130 | train | 224,168 |
ethereum/pyethereum | ethereum/tools/_solidity.py | solidity_names | def solidity_names(code): # pylint: disable=too-many-branches
""" Return the library and contract names in order of appearence. """
names = []
in_string = None
backslash = False
comment = None
# "parse" the code by hand to handle the corner cases:
# - the contract or library can be inside a comment or string
# - multiline comments
# - the contract and library keywords could not be at the start of the line
for pos, char in enumerate(code):
if in_string:
if not backslash and in_string == char:
in_string = None
backslash = False
if char == '\\': # pylint: disable=simplifiable-if-statement
backslash = True
else:
backslash = False
elif comment == '//':
if char in ('\n', '\r'):
comment = None
elif comment == '/*':
if char == '*' and code[pos + 1] == '/':
comment = None
else:
if char == '"' or char == "'":
in_string = char
if char == '/':
if code[pos + 1] == '/':
comment = '//'
if code[pos + 1] == '*':
comment = '/*'
if char == 'c' and code[pos: pos + 8] == 'contract':
result = re.match(
'^contract[^_$a-zA-Z]+([_$a-zA-Z][_$a-zA-Z0-9]*)', code[pos:])
if result:
names.append(('contract', result.groups()[0]))
if char == 'i' and code[pos: pos + 9] == 'interface':
result = re.match(
'^interface[^_$a-zA-Z]+([_$a-zA-Z][_$a-zA-Z0-9]*)', code[pos:])
if result:
names.append(('contract', result.groups()[0]))
if char == 'l' and code[pos: pos + 7] == 'library':
result = re.match(
'^library[^_$a-zA-Z]+([_$a-zA-Z][_$a-zA-Z0-9]*)', code[pos:])
if result:
names.append(('library', result.groups()[0]))
return names | python | def solidity_names(code): # pylint: disable=too-many-branches
""" Return the library and contract names in order of appearence. """
names = []
in_string = None
backslash = False
comment = None
# "parse" the code by hand to handle the corner cases:
# - the contract or library can be inside a comment or string
# - multiline comments
# - the contract and library keywords could not be at the start of the line
for pos, char in enumerate(code):
if in_string:
if not backslash and in_string == char:
in_string = None
backslash = False
if char == '\\': # pylint: disable=simplifiable-if-statement
backslash = True
else:
backslash = False
elif comment == '//':
if char in ('\n', '\r'):
comment = None
elif comment == '/*':
if char == '*' and code[pos + 1] == '/':
comment = None
else:
if char == '"' or char == "'":
in_string = char
if char == '/':
if code[pos + 1] == '/':
comment = '//'
if code[pos + 1] == '*':
comment = '/*'
if char == 'c' and code[pos: pos + 8] == 'contract':
result = re.match(
'^contract[^_$a-zA-Z]+([_$a-zA-Z][_$a-zA-Z0-9]*)', code[pos:])
if result:
names.append(('contract', result.groups()[0]))
if char == 'i' and code[pos: pos + 9] == 'interface':
result = re.match(
'^interface[^_$a-zA-Z]+([_$a-zA-Z][_$a-zA-Z0-9]*)', code[pos:])
if result:
names.append(('contract', result.groups()[0]))
if char == 'l' and code[pos: pos + 7] == 'library':
result = re.match(
'^library[^_$a-zA-Z]+([_$a-zA-Z][_$a-zA-Z0-9]*)', code[pos:])
if result:
names.append(('library', result.groups()[0]))
return names | [
"def",
"solidity_names",
"(",
"code",
")",
":",
"# pylint: disable=too-many-branches",
"names",
"=",
"[",
"]",
"in_string",
"=",
"None",
"backslash",
"=",
"False",
"comment",
"=",
"None",
"# \"parse\" the code by hand to handle the corner cases:",
"# - the contract or libr... | Return the library and contract names in order of appearence. | [
"Return",
"the",
"library",
"and",
"contract",
"names",
"in",
"order",
"of",
"appearence",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L133-L194 | train | 224,169 |
ethereum/pyethereum | ethereum/tools/_solidity.py | compile_file | def compile_file(filepath, libraries=None, combined='bin,abi',
optimize=True, extra_args=None):
""" Return the compile contract code.
Args:
filepath (str): The path to the contract source code.
libraries (dict): A dictionary mapping library name to it's address.
combined (str): The argument for solc's --combined-json.
optimize (bool): Enable/disables compiler optimization.
Returns:
dict: A mapping from the contract name to it's binary.
"""
workdir, filename = os.path.split(filepath)
args = solc_arguments(
libraries=libraries,
combined=combined,
optimize=optimize,
extra_args=extra_args)
args.insert(0, get_compiler_path())
args.append(filename)
output = subprocess.check_output(args, cwd=workdir)
return solc_parse_output(output) | python | def compile_file(filepath, libraries=None, combined='bin,abi',
optimize=True, extra_args=None):
""" Return the compile contract code.
Args:
filepath (str): The path to the contract source code.
libraries (dict): A dictionary mapping library name to it's address.
combined (str): The argument for solc's --combined-json.
optimize (bool): Enable/disables compiler optimization.
Returns:
dict: A mapping from the contract name to it's binary.
"""
workdir, filename = os.path.split(filepath)
args = solc_arguments(
libraries=libraries,
combined=combined,
optimize=optimize,
extra_args=extra_args)
args.insert(0, get_compiler_path())
args.append(filename)
output = subprocess.check_output(args, cwd=workdir)
return solc_parse_output(output) | [
"def",
"compile_file",
"(",
"filepath",
",",
"libraries",
"=",
"None",
",",
"combined",
"=",
"'bin,abi'",
",",
"optimize",
"=",
"True",
",",
"extra_args",
"=",
"None",
")",
":",
"workdir",
",",
"filename",
"=",
"os",
".",
"path",
".",
"split",
"(",
"fi... | Return the compile contract code.
Args:
filepath (str): The path to the contract source code.
libraries (dict): A dictionary mapping library name to it's address.
combined (str): The argument for solc's --combined-json.
optimize (bool): Enable/disables compiler optimization.
Returns:
dict: A mapping from the contract name to it's binary. | [
"Return",
"the",
"compile",
"contract",
"code",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L265-L291 | train | 224,170 |
ethereum/pyethereum | ethereum/tools/_solidity.py | solidity_get_contract_key | def solidity_get_contract_key(all_contracts, filepath, contract_name):
""" A backwards compatible method of getting the key to the all_contracts
dictionary for a particular contract"""
if contract_name in all_contracts:
return contract_name
else:
if filepath is None:
filename = '<stdin>'
else:
_, filename = os.path.split(filepath)
contract_key = filename + ":" + contract_name
return contract_key if contract_key in all_contracts else None | python | def solidity_get_contract_key(all_contracts, filepath, contract_name):
""" A backwards compatible method of getting the key to the all_contracts
dictionary for a particular contract"""
if contract_name in all_contracts:
return contract_name
else:
if filepath is None:
filename = '<stdin>'
else:
_, filename = os.path.split(filepath)
contract_key = filename + ":" + contract_name
return contract_key if contract_key in all_contracts else None | [
"def",
"solidity_get_contract_key",
"(",
"all_contracts",
",",
"filepath",
",",
"contract_name",
")",
":",
"if",
"contract_name",
"in",
"all_contracts",
":",
"return",
"contract_name",
"else",
":",
"if",
"filepath",
"is",
"None",
":",
"filename",
"=",
"'<stdin>'",... | A backwards compatible method of getting the key to the all_contracts
dictionary for a particular contract | [
"A",
"backwards",
"compatible",
"method",
"of",
"getting",
"the",
"key",
"to",
"the",
"all_contracts",
"dictionary",
"for",
"a",
"particular",
"contract"
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L308-L319 | train | 224,171 |
ethereum/pyethereum | ethereum/tools/_solidity.py | Solc.compile | def compile(cls, code, path=None, libraries=None,
contract_name='', extra_args=None):
""" Return the binary of last contract in code. """
result = cls._code_or_path(
code,
path,
contract_name,
libraries,
'bin',
extra_args)
return result['bin'] | python | def compile(cls, code, path=None, libraries=None,
contract_name='', extra_args=None):
""" Return the binary of last contract in code. """
result = cls._code_or_path(
code,
path,
contract_name,
libraries,
'bin',
extra_args)
return result['bin'] | [
"def",
"compile",
"(",
"cls",
",",
"code",
",",
"path",
"=",
"None",
",",
"libraries",
"=",
"None",
",",
"contract_name",
"=",
"''",
",",
"extra_args",
"=",
"None",
")",
":",
"result",
"=",
"cls",
".",
"_code_or_path",
"(",
"code",
",",
"path",
",",
... | Return the binary of last contract in code. | [
"Return",
"the",
"binary",
"of",
"last",
"contract",
"in",
"code",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L420-L430 | train | 224,172 |
ethereum/pyethereum | ethereum/tools/_solidity.py | Solc.combined | def combined(cls, code, path=None, extra_args=None):
""" Compile combined-json with abi,bin,devdoc,userdoc.
@param code: literal solidity code as a string.
@param path: absolute path to solidity-file. Note: code & path are
mutually exclusive!
@param extra_args: Either a space separated string or a list of extra
arguments to be passed to the solidity compiler.
"""
if code and path:
raise ValueError('sourcecode and path are mutually exclusive.')
if path:
contracts = compile_file(path, extra_args=extra_args)
with open(path) as handler:
code = handler.read()
elif code:
contracts = compile_code(code, extra_args=extra_args)
else:
raise ValueError('either code or path needs to be supplied.')
sorted_contracts = []
for name in solidity_names(code):
sorted_contracts.append(
(
name[1],
solidity_get_contract_data(contracts, path, name[1])
)
)
return sorted_contracts | python | def combined(cls, code, path=None, extra_args=None):
""" Compile combined-json with abi,bin,devdoc,userdoc.
@param code: literal solidity code as a string.
@param path: absolute path to solidity-file. Note: code & path are
mutually exclusive!
@param extra_args: Either a space separated string or a list of extra
arguments to be passed to the solidity compiler.
"""
if code and path:
raise ValueError('sourcecode and path are mutually exclusive.')
if path:
contracts = compile_file(path, extra_args=extra_args)
with open(path) as handler:
code = handler.read()
elif code:
contracts = compile_code(code, extra_args=extra_args)
else:
raise ValueError('either code or path needs to be supplied.')
sorted_contracts = []
for name in solidity_names(code):
sorted_contracts.append(
(
name[1],
solidity_get_contract_data(contracts, path, name[1])
)
)
return sorted_contracts | [
"def",
"combined",
"(",
"cls",
",",
"code",
",",
"path",
"=",
"None",
",",
"extra_args",
"=",
"None",
")",
":",
"if",
"code",
"and",
"path",
":",
"raise",
"ValueError",
"(",
"'sourcecode and path are mutually exclusive.'",
")",
"if",
"path",
":",
"contracts"... | Compile combined-json with abi,bin,devdoc,userdoc.
@param code: literal solidity code as a string.
@param path: absolute path to solidity-file. Note: code & path are
mutually exclusive!
@param extra_args: Either a space separated string or a list of extra
arguments to be passed to the solidity compiler. | [
"Compile",
"combined",
"-",
"json",
"with",
"abi",
"bin",
"devdoc",
"userdoc",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L447-L480 | train | 224,173 |
ethereum/pyethereum | ethereum/tools/_solidity.py | Solc.compile_rich | def compile_rich(cls, code, path=None, extra_args=None):
"""full format as returned by jsonrpc"""
return {
contract_name: {
'code': '0x' + contract.get('bin_hex'),
'info': {
'abiDefinition': contract.get('abi'),
'compilerVersion': cls.compiler_version(),
'developerDoc': contract.get('devdoc'),
'language': 'Solidity',
'languageVersion': '0',
'source': code,
'userDoc': contract.get('userdoc')
},
}
for contract_name, contract
in cls.combined(code, path=path, extra_args=extra_args)
} | python | def compile_rich(cls, code, path=None, extra_args=None):
"""full format as returned by jsonrpc"""
return {
contract_name: {
'code': '0x' + contract.get('bin_hex'),
'info': {
'abiDefinition': contract.get('abi'),
'compilerVersion': cls.compiler_version(),
'developerDoc': contract.get('devdoc'),
'language': 'Solidity',
'languageVersion': '0',
'source': code,
'userDoc': contract.get('userdoc')
},
}
for contract_name, contract
in cls.combined(code, path=path, extra_args=extra_args)
} | [
"def",
"compile_rich",
"(",
"cls",
",",
"code",
",",
"path",
"=",
"None",
",",
"extra_args",
"=",
"None",
")",
":",
"return",
"{",
"contract_name",
":",
"{",
"'code'",
":",
"'0x'",
"+",
"contract",
".",
"get",
"(",
"'bin_hex'",
")",
",",
"'info'",
":... | full format as returned by jsonrpc | [
"full",
"format",
"as",
"returned",
"by",
"jsonrpc"
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/tools/_solidity.py#L483-L501 | train | 224,174 |
ethereum/pyethereum | ethereum/pow/consensus.py | validate_uncles | def validate_uncles(state, block):
"""Validate the uncles of this block."""
# Make sure hash matches up
if utils.sha3(rlp.encode(block.uncles)) != block.header.uncles_hash:
raise VerificationFailed("Uncle hash mismatch")
# Enforce maximum number of uncles
if len(block.uncles) > state.config['MAX_UNCLES']:
raise VerificationFailed("Too many uncles")
# Uncle must have lower block number than blockj
for uncle in block.uncles:
if uncle.number >= block.header.number:
raise VerificationFailed("Uncle number too high")
# Check uncle validity
MAX_UNCLE_DEPTH = state.config['MAX_UNCLE_DEPTH']
ancestor_chain = [block.header] + \
[a for a in state.prev_headers[:MAX_UNCLE_DEPTH + 1] if a]
# Uncles of this block cannot be direct ancestors and cannot also
# be uncles included 1-6 blocks ago
ineligible = [b.hash for b in ancestor_chain]
for blknum, uncles in state.recent_uncles.items():
if state.block_number > int(
blknum) >= state.block_number - MAX_UNCLE_DEPTH:
ineligible.extend([u for u in uncles])
eligible_ancestor_hashes = [x.hash for x in ancestor_chain[2:]]
for uncle in block.uncles:
if uncle.prevhash not in eligible_ancestor_hashes:
raise VerificationFailed("Uncle does not have a valid ancestor")
parent = [x for x in ancestor_chain if x.hash == uncle.prevhash][0]
if uncle.difficulty != calc_difficulty(
parent, uncle.timestamp, config=state.config):
raise VerificationFailed("Difficulty mismatch")
if uncle.number != parent.number + 1:
raise VerificationFailed("Number mismatch")
if uncle.timestamp < parent.timestamp:
raise VerificationFailed("Timestamp mismatch")
if uncle.hash in ineligible:
raise VerificationFailed("Duplicate uncle")
if uncle.gas_used > uncle.gas_limit:
raise VerificationFailed("Uncle used too much gas")
if not check_pow(state, uncle):
raise VerificationFailed('uncle pow mismatch')
ineligible.append(uncle.hash)
return True | python | def validate_uncles(state, block):
"""Validate the uncles of this block."""
# Make sure hash matches up
if utils.sha3(rlp.encode(block.uncles)) != block.header.uncles_hash:
raise VerificationFailed("Uncle hash mismatch")
# Enforce maximum number of uncles
if len(block.uncles) > state.config['MAX_UNCLES']:
raise VerificationFailed("Too many uncles")
# Uncle must have lower block number than blockj
for uncle in block.uncles:
if uncle.number >= block.header.number:
raise VerificationFailed("Uncle number too high")
# Check uncle validity
MAX_UNCLE_DEPTH = state.config['MAX_UNCLE_DEPTH']
ancestor_chain = [block.header] + \
[a for a in state.prev_headers[:MAX_UNCLE_DEPTH + 1] if a]
# Uncles of this block cannot be direct ancestors and cannot also
# be uncles included 1-6 blocks ago
ineligible = [b.hash for b in ancestor_chain]
for blknum, uncles in state.recent_uncles.items():
if state.block_number > int(
blknum) >= state.block_number - MAX_UNCLE_DEPTH:
ineligible.extend([u for u in uncles])
eligible_ancestor_hashes = [x.hash for x in ancestor_chain[2:]]
for uncle in block.uncles:
if uncle.prevhash not in eligible_ancestor_hashes:
raise VerificationFailed("Uncle does not have a valid ancestor")
parent = [x for x in ancestor_chain if x.hash == uncle.prevhash][0]
if uncle.difficulty != calc_difficulty(
parent, uncle.timestamp, config=state.config):
raise VerificationFailed("Difficulty mismatch")
if uncle.number != parent.number + 1:
raise VerificationFailed("Number mismatch")
if uncle.timestamp < parent.timestamp:
raise VerificationFailed("Timestamp mismatch")
if uncle.hash in ineligible:
raise VerificationFailed("Duplicate uncle")
if uncle.gas_used > uncle.gas_limit:
raise VerificationFailed("Uncle used too much gas")
if not check_pow(state, uncle):
raise VerificationFailed('uncle pow mismatch')
ineligible.append(uncle.hash)
return True | [
"def",
"validate_uncles",
"(",
"state",
",",
"block",
")",
":",
"# Make sure hash matches up",
"if",
"utils",
".",
"sha3",
"(",
"rlp",
".",
"encode",
"(",
"block",
".",
"uncles",
")",
")",
"!=",
"block",
".",
"header",
".",
"uncles_hash",
":",
"raise",
"... | Validate the uncles of this block. | [
"Validate",
"the",
"uncles",
"of",
"this",
"block",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/pow/consensus.py#L63-L106 | train | 224,175 |
ethereum/pyethereum | ethereum/pow/consensus.py | finalize | def finalize(state, block):
"""Apply rewards and commit."""
if state.is_METROPOLIS():
br = state.config['BYZANTIUM_BLOCK_REWARD']
nr = state.config['BYZANTIUM_NEPHEW_REWARD']
else:
br = state.config['BLOCK_REWARD']
nr = state.config['NEPHEW_REWARD']
delta = int(br + nr * len(block.uncles))
state.delta_balance(state.block_coinbase, delta)
udpf = state.config['UNCLE_DEPTH_PENALTY_FACTOR']
for uncle in block.uncles:
r = int(br * (udpf + uncle.number - state.block_number) // udpf)
state.delta_balance(uncle.coinbase, r)
if state.block_number - \
state.config['MAX_UNCLE_DEPTH'] in state.recent_uncles:
del state.recent_uncles[state.block_number -
state.config['MAX_UNCLE_DEPTH']] | python | def finalize(state, block):
"""Apply rewards and commit."""
if state.is_METROPOLIS():
br = state.config['BYZANTIUM_BLOCK_REWARD']
nr = state.config['BYZANTIUM_NEPHEW_REWARD']
else:
br = state.config['BLOCK_REWARD']
nr = state.config['NEPHEW_REWARD']
delta = int(br + nr * len(block.uncles))
state.delta_balance(state.block_coinbase, delta)
udpf = state.config['UNCLE_DEPTH_PENALTY_FACTOR']
for uncle in block.uncles:
r = int(br * (udpf + uncle.number - state.block_number) // udpf)
state.delta_balance(uncle.coinbase, r)
if state.block_number - \
state.config['MAX_UNCLE_DEPTH'] in state.recent_uncles:
del state.recent_uncles[state.block_number -
state.config['MAX_UNCLE_DEPTH']] | [
"def",
"finalize",
"(",
"state",
",",
"block",
")",
":",
"if",
"state",
".",
"is_METROPOLIS",
"(",
")",
":",
"br",
"=",
"state",
".",
"config",
"[",
"'BYZANTIUM_BLOCK_REWARD'",
"]",
"nr",
"=",
"state",
".",
"config",
"[",
"'BYZANTIUM_NEPHEW_REWARD'",
"]",
... | Apply rewards and commit. | [
"Apply",
"rewards",
"and",
"commit",
"."
] | b704a5c6577863edc539a1ec3d2620a443b950fb | https://github.com/ethereum/pyethereum/blob/b704a5c6577863edc539a1ec3d2620a443b950fb/ethereum/pow/consensus.py#L110-L132 | train | 224,176 |
Microsoft/knack | knack/deprecation.py | Deprecated.ensure_new_style_deprecation | def ensure_new_style_deprecation(cli_ctx, kwargs, object_type):
""" Helper method to make the previous string-based deprecate_info kwarg
work with the new style. """
deprecate_info = kwargs.get('deprecate_info', None)
if isinstance(deprecate_info, Deprecated):
deprecate_info.object_type = object_type
elif isinstance(deprecate_info, STRING_TYPES):
deprecate_info = Deprecated(cli_ctx, redirect=deprecate_info, object_type=object_type)
kwargs['deprecate_info'] = deprecate_info
return deprecate_info | python | def ensure_new_style_deprecation(cli_ctx, kwargs, object_type):
""" Helper method to make the previous string-based deprecate_info kwarg
work with the new style. """
deprecate_info = kwargs.get('deprecate_info', None)
if isinstance(deprecate_info, Deprecated):
deprecate_info.object_type = object_type
elif isinstance(deprecate_info, STRING_TYPES):
deprecate_info = Deprecated(cli_ctx, redirect=deprecate_info, object_type=object_type)
kwargs['deprecate_info'] = deprecate_info
return deprecate_info | [
"def",
"ensure_new_style_deprecation",
"(",
"cli_ctx",
",",
"kwargs",
",",
"object_type",
")",
":",
"deprecate_info",
"=",
"kwargs",
".",
"get",
"(",
"'deprecate_info'",
",",
"None",
")",
"if",
"isinstance",
"(",
"deprecate_info",
",",
"Deprecated",
")",
":",
... | Helper method to make the previous string-based deprecate_info kwarg
work with the new style. | [
"Helper",
"method",
"to",
"make",
"the",
"previous",
"string",
"-",
"based",
"deprecate_info",
"kwarg",
"work",
"with",
"the",
"new",
"style",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/deprecation.py#L53-L62 | train | 224,177 |
Microsoft/knack | knack/deprecation.py | Deprecated._version_less_than_or_equal_to | def _version_less_than_or_equal_to(self, v1, v2):
""" Returns true if v1 <= v2. """
# pylint: disable=no-name-in-module, import-error
from distutils.version import LooseVersion
return LooseVersion(v1) <= LooseVersion(v2) | python | def _version_less_than_or_equal_to(self, v1, v2):
""" Returns true if v1 <= v2. """
# pylint: disable=no-name-in-module, import-error
from distutils.version import LooseVersion
return LooseVersion(v1) <= LooseVersion(v2) | [
"def",
"_version_less_than_or_equal_to",
"(",
"self",
",",
"v1",
",",
"v2",
")",
":",
"# pylint: disable=no-name-in-module, import-error",
"from",
"distutils",
".",
"version",
"import",
"LooseVersion",
"return",
"LooseVersion",
"(",
"v1",
")",
"<=",
"LooseVersion",
"(... | Returns true if v1 <= v2. | [
"Returns",
"true",
"if",
"v1",
"<",
"=",
"v2",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/deprecation.py#L127-L131 | train | 224,178 |
Microsoft/knack | knack/prompting.py | prompt_choice_list | def prompt_choice_list(msg, a_list, default=1, help_string=None):
"""Prompt user to select from a list of possible choices.
:param msg:A message displayed to the user before the choice list
:type msg: str
:param a_list:The list of choices (list of strings or list of dicts with 'name' & 'desc')
"type a_list: list
:param default:The default option that should be chosen if user doesn't enter a choice
:type default: int
:returns: The list index of the item chosen.
"""
verify_is_a_tty()
options = '\n'.join([' [{}] {}{}'
.format(i + 1,
x['name'] if isinstance(x, dict) and 'name' in x else x,
' - ' + x['desc'] if isinstance(x, dict) and 'desc' in x else '')
for i, x in enumerate(a_list)])
allowed_vals = list(range(1, len(a_list) + 1))
while True:
val = _input('{}\n{}\nPlease enter a choice [Default choice({})]: '.format(msg, options, default))
if val == '?' and help_string is not None:
print(help_string)
continue
if not val:
val = '{}'.format(default)
try:
ans = int(val)
if ans in allowed_vals:
# array index is 0-based, user input is 1-based
return ans - 1
raise ValueError
except ValueError:
logger.warning('Valid values are %s', allowed_vals) | python | def prompt_choice_list(msg, a_list, default=1, help_string=None):
"""Prompt user to select from a list of possible choices.
:param msg:A message displayed to the user before the choice list
:type msg: str
:param a_list:The list of choices (list of strings or list of dicts with 'name' & 'desc')
"type a_list: list
:param default:The default option that should be chosen if user doesn't enter a choice
:type default: int
:returns: The list index of the item chosen.
"""
verify_is_a_tty()
options = '\n'.join([' [{}] {}{}'
.format(i + 1,
x['name'] if isinstance(x, dict) and 'name' in x else x,
' - ' + x['desc'] if isinstance(x, dict) and 'desc' in x else '')
for i, x in enumerate(a_list)])
allowed_vals = list(range(1, len(a_list) + 1))
while True:
val = _input('{}\n{}\nPlease enter a choice [Default choice({})]: '.format(msg, options, default))
if val == '?' and help_string is not None:
print(help_string)
continue
if not val:
val = '{}'.format(default)
try:
ans = int(val)
if ans in allowed_vals:
# array index is 0-based, user input is 1-based
return ans - 1
raise ValueError
except ValueError:
logger.warning('Valid values are %s', allowed_vals) | [
"def",
"prompt_choice_list",
"(",
"msg",
",",
"a_list",
",",
"default",
"=",
"1",
",",
"help_string",
"=",
"None",
")",
":",
"verify_is_a_tty",
"(",
")",
"options",
"=",
"'\\n'",
".",
"join",
"(",
"[",
"' [{}] {}{}'",
".",
"format",
"(",
"i",
"+",
"1",... | Prompt user to select from a list of possible choices.
:param msg:A message displayed to the user before the choice list
:type msg: str
:param a_list:The list of choices (list of strings or list of dicts with 'name' & 'desc')
"type a_list: list
:param default:The default option that should be chosen if user doesn't enter a choice
:type default: int
:returns: The list index of the item chosen. | [
"Prompt",
"user",
"to",
"select",
"from",
"a",
"list",
"of",
"possible",
"choices",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/prompting.py#L99-L131 | train | 224,179 |
Microsoft/knack | knack/parser.py | CLICommandParser._add_argument | def _add_argument(obj, arg):
""" Only pass valid argparse kwargs to argparse.ArgumentParser.add_argument """
argparse_options = {name: value for name, value in arg.options.items() if name in ARGPARSE_SUPPORTED_KWARGS}
if arg.options_list:
scrubbed_options_list = []
for item in arg.options_list:
if isinstance(item, Deprecated):
# don't add expired options to the parser
if item.expired():
continue
class _DeprecatedOption(str):
def __new__(cls, *args, **kwargs):
instance = str.__new__(cls, *args, **kwargs)
return instance
option = _DeprecatedOption(item.target)
setattr(option, 'deprecate_info', item)
item = option
scrubbed_options_list.append(item)
return obj.add_argument(*scrubbed_options_list, **argparse_options)
if 'required' in argparse_options:
del argparse_options['required']
if 'metavar' not in argparse_options:
argparse_options['metavar'] = '<{}>'.format(argparse_options['dest'].upper())
return obj.add_argument(**argparse_options) | python | def _add_argument(obj, arg):
""" Only pass valid argparse kwargs to argparse.ArgumentParser.add_argument """
argparse_options = {name: value for name, value in arg.options.items() if name in ARGPARSE_SUPPORTED_KWARGS}
if arg.options_list:
scrubbed_options_list = []
for item in arg.options_list:
if isinstance(item, Deprecated):
# don't add expired options to the parser
if item.expired():
continue
class _DeprecatedOption(str):
def __new__(cls, *args, **kwargs):
instance = str.__new__(cls, *args, **kwargs)
return instance
option = _DeprecatedOption(item.target)
setattr(option, 'deprecate_info', item)
item = option
scrubbed_options_list.append(item)
return obj.add_argument(*scrubbed_options_list, **argparse_options)
if 'required' in argparse_options:
del argparse_options['required']
if 'metavar' not in argparse_options:
argparse_options['metavar'] = '<{}>'.format(argparse_options['dest'].upper())
return obj.add_argument(**argparse_options) | [
"def",
"_add_argument",
"(",
"obj",
",",
"arg",
")",
":",
"argparse_options",
"=",
"{",
"name",
":",
"value",
"for",
"name",
",",
"value",
"in",
"arg",
".",
"options",
".",
"items",
"(",
")",
"if",
"name",
"in",
"ARGPARSE_SUPPORTED_KWARGS",
"}",
"if",
... | Only pass valid argparse kwargs to argparse.ArgumentParser.add_argument | [
"Only",
"pass",
"valid",
"argparse",
"kwargs",
"to",
"argparse",
".",
"ArgumentParser",
".",
"add_argument"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/parser.py#L42-L69 | train | 224,180 |
Microsoft/knack | knack/parser.py | CLICommandParser.load_command_table | def load_command_table(self, command_loader):
""" Process the command table and load it into the parser
:param cmd_tbl: A dictionary containing the commands
:type cmd_tbl: dict
"""
cmd_tbl = command_loader.command_table
grp_tbl = command_loader.command_group_table
if not cmd_tbl:
raise ValueError('The command table is empty. At least one command is required.')
# If we haven't already added a subparser, we
# better do it.
if not self.subparsers:
sp = self.add_subparsers(dest='_command')
sp.required = True
self.subparsers = {(): sp}
for command_name, metadata in cmd_tbl.items():
subparser = self._get_subparser(command_name.split(), grp_tbl)
command_verb = command_name.split()[-1]
# To work around http://bugs.python.org/issue9253, we artificially add any new
# parsers we add to the "choices" section of the subparser.
subparser = self._get_subparser(command_name.split(), grp_tbl)
deprecate_info = metadata.deprecate_info
if not subparser or (deprecate_info and deprecate_info.expired()):
continue
# inject command_module designer's help formatter -- default is HelpFormatter
fc = metadata.formatter_class or argparse.HelpFormatter
command_parser = subparser.add_parser(command_verb,
description=metadata.description,
parents=self.parents,
conflict_handler='error',
help_file=metadata.help,
formatter_class=fc,
cli_help=self.cli_help)
command_parser.cli_ctx = self.cli_ctx
command_validator = metadata.validator
argument_validators = []
argument_groups = {}
for arg in metadata.arguments.values():
# don't add deprecated arguments to the parser
deprecate_info = arg.type.settings.get('deprecate_info', None)
if deprecate_info and deprecate_info.expired():
continue
if arg.validator:
argument_validators.append(arg.validator)
if arg.arg_group:
try:
group = argument_groups[arg.arg_group]
except KeyError:
# group not found so create
group_name = '{} Arguments'.format(arg.arg_group)
group = command_parser.add_argument_group(arg.arg_group, group_name)
argument_groups[arg.arg_group] = group
param = CLICommandParser._add_argument(group, arg)
else:
param = CLICommandParser._add_argument(command_parser, arg)
param.completer = arg.completer
param.deprecate_info = arg.deprecate_info
command_parser.set_defaults(
func=metadata,
command=command_name,
_command_validator=command_validator,
_argument_validators=argument_validators,
_parser=command_parser) | python | def load_command_table(self, command_loader):
""" Process the command table and load it into the parser
:param cmd_tbl: A dictionary containing the commands
:type cmd_tbl: dict
"""
cmd_tbl = command_loader.command_table
grp_tbl = command_loader.command_group_table
if not cmd_tbl:
raise ValueError('The command table is empty. At least one command is required.')
# If we haven't already added a subparser, we
# better do it.
if not self.subparsers:
sp = self.add_subparsers(dest='_command')
sp.required = True
self.subparsers = {(): sp}
for command_name, metadata in cmd_tbl.items():
subparser = self._get_subparser(command_name.split(), grp_tbl)
command_verb = command_name.split()[-1]
# To work around http://bugs.python.org/issue9253, we artificially add any new
# parsers we add to the "choices" section of the subparser.
subparser = self._get_subparser(command_name.split(), grp_tbl)
deprecate_info = metadata.deprecate_info
if not subparser or (deprecate_info and deprecate_info.expired()):
continue
# inject command_module designer's help formatter -- default is HelpFormatter
fc = metadata.formatter_class or argparse.HelpFormatter
command_parser = subparser.add_parser(command_verb,
description=metadata.description,
parents=self.parents,
conflict_handler='error',
help_file=metadata.help,
formatter_class=fc,
cli_help=self.cli_help)
command_parser.cli_ctx = self.cli_ctx
command_validator = metadata.validator
argument_validators = []
argument_groups = {}
for arg in metadata.arguments.values():
# don't add deprecated arguments to the parser
deprecate_info = arg.type.settings.get('deprecate_info', None)
if deprecate_info and deprecate_info.expired():
continue
if arg.validator:
argument_validators.append(arg.validator)
if arg.arg_group:
try:
group = argument_groups[arg.arg_group]
except KeyError:
# group not found so create
group_name = '{} Arguments'.format(arg.arg_group)
group = command_parser.add_argument_group(arg.arg_group, group_name)
argument_groups[arg.arg_group] = group
param = CLICommandParser._add_argument(group, arg)
else:
param = CLICommandParser._add_argument(command_parser, arg)
param.completer = arg.completer
param.deprecate_info = arg.deprecate_info
command_parser.set_defaults(
func=metadata,
command=command_name,
_command_validator=command_validator,
_argument_validators=argument_validators,
_parser=command_parser) | [
"def",
"load_command_table",
"(",
"self",
",",
"command_loader",
")",
":",
"cmd_tbl",
"=",
"command_loader",
".",
"command_table",
"grp_tbl",
"=",
"command_loader",
".",
"command_group_table",
"if",
"not",
"cmd_tbl",
":",
"raise",
"ValueError",
"(",
"'The command ta... | Process the command table and load it into the parser
:param cmd_tbl: A dictionary containing the commands
:type cmd_tbl: dict | [
"Process",
"the",
"command",
"table",
"and",
"load",
"it",
"into",
"the",
"parser"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/parser.py#L111-L178 | train | 224,181 |
Microsoft/knack | knack/parser.py | CLICommandParser._get_subparser | def _get_subparser(self, path, group_table=None):
"""For each part of the path, walk down the tree of
subparsers, creating new ones if one doesn't already exist.
"""
group_table = group_table or {}
for length in range(0, len(path)):
parent_path = path[:length]
parent_subparser = self.subparsers.get(tuple(parent_path), None)
if not parent_subparser:
# No subparser exists for the given subpath - create and register
# a new subparser.
# Since we know that we always have a root subparser (we created)
# one when we started loading the command table, and we walk the
# path from left to right (i.e. for "cmd subcmd1 subcmd2", we start
# with ensuring that a subparser for cmd exists, then for subcmd1,
# subcmd2 and so on), we know we can always back up one step and
# add a subparser if one doesn't exist
command_group = group_table.get(' '.join(parent_path))
if command_group:
deprecate_info = command_group.group_kwargs.get('deprecate_info', None)
if deprecate_info and deprecate_info.expired():
continue
grandparent_path = path[:length - 1]
grandparent_subparser = self.subparsers[tuple(grandparent_path)]
new_path = path[length - 1]
new_parser = grandparent_subparser.add_parser(new_path, cli_help=self.cli_help)
# Due to http://bugs.python.org/issue9253, we have to give the subparser
# a destination and set it to required in order to get a meaningful error
parent_subparser = new_parser.add_subparsers(dest='_subcommand')
command_group = group_table.get(' '.join(parent_path), None)
deprecate_info = None
if command_group:
deprecate_info = command_group.group_kwargs.get('deprecate_info', None)
parent_subparser.required = True
parent_subparser.deprecate_info = deprecate_info
self.subparsers[tuple(path[0:length])] = parent_subparser
return parent_subparser | python | def _get_subparser(self, path, group_table=None):
"""For each part of the path, walk down the tree of
subparsers, creating new ones if one doesn't already exist.
"""
group_table = group_table or {}
for length in range(0, len(path)):
parent_path = path[:length]
parent_subparser = self.subparsers.get(tuple(parent_path), None)
if not parent_subparser:
# No subparser exists for the given subpath - create and register
# a new subparser.
# Since we know that we always have a root subparser (we created)
# one when we started loading the command table, and we walk the
# path from left to right (i.e. for "cmd subcmd1 subcmd2", we start
# with ensuring that a subparser for cmd exists, then for subcmd1,
# subcmd2 and so on), we know we can always back up one step and
# add a subparser if one doesn't exist
command_group = group_table.get(' '.join(parent_path))
if command_group:
deprecate_info = command_group.group_kwargs.get('deprecate_info', None)
if deprecate_info and deprecate_info.expired():
continue
grandparent_path = path[:length - 1]
grandparent_subparser = self.subparsers[tuple(grandparent_path)]
new_path = path[length - 1]
new_parser = grandparent_subparser.add_parser(new_path, cli_help=self.cli_help)
# Due to http://bugs.python.org/issue9253, we have to give the subparser
# a destination and set it to required in order to get a meaningful error
parent_subparser = new_parser.add_subparsers(dest='_subcommand')
command_group = group_table.get(' '.join(parent_path), None)
deprecate_info = None
if command_group:
deprecate_info = command_group.group_kwargs.get('deprecate_info', None)
parent_subparser.required = True
parent_subparser.deprecate_info = deprecate_info
self.subparsers[tuple(path[0:length])] = parent_subparser
return parent_subparser | [
"def",
"_get_subparser",
"(",
"self",
",",
"path",
",",
"group_table",
"=",
"None",
")",
":",
"group_table",
"=",
"group_table",
"or",
"{",
"}",
"for",
"length",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"path",
")",
")",
":",
"parent_path",
"=",
"pa... | For each part of the path, walk down the tree of
subparsers, creating new ones if one doesn't already exist. | [
"For",
"each",
"part",
"of",
"the",
"path",
"walk",
"down",
"the",
"tree",
"of",
"subparsers",
"creating",
"new",
"ones",
"if",
"one",
"doesn",
"t",
"already",
"exist",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/parser.py#L180-L217 | train | 224,182 |
Microsoft/knack | knack/parser.py | CLICommandParser.parse_args | def parse_args(self, args=None, namespace=None):
""" Overrides argparse.ArgumentParser.parse_args
Enables '@'-prefixed files to be expanded before arguments are processed
by ArgumentParser.parse_args as usual
"""
self._expand_prefixed_files(args)
return super(CLICommandParser, self).parse_args(args) | python | def parse_args(self, args=None, namespace=None):
""" Overrides argparse.ArgumentParser.parse_args
Enables '@'-prefixed files to be expanded before arguments are processed
by ArgumentParser.parse_args as usual
"""
self._expand_prefixed_files(args)
return super(CLICommandParser, self).parse_args(args) | [
"def",
"parse_args",
"(",
"self",
",",
"args",
"=",
"None",
",",
"namespace",
"=",
"None",
")",
":",
"self",
".",
"_expand_prefixed_files",
"(",
"args",
")",
"return",
"super",
"(",
"CLICommandParser",
",",
"self",
")",
".",
"parse_args",
"(",
"args",
")... | Overrides argparse.ArgumentParser.parse_args
Enables '@'-prefixed files to be expanded before arguments are processed
by ArgumentParser.parse_args as usual | [
"Overrides",
"argparse",
".",
"ArgumentParser",
".",
"parse_args"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/parser.py#L249-L256 | train | 224,183 |
Microsoft/knack | knack/introspection.py | extract_full_summary_from_signature | def extract_full_summary_from_signature(operation):
""" Extract the summary from the docstring of the command. """
lines = inspect.getdoc(operation)
regex = r'\s*(:param)\s+(.+?)\s*:(.*)'
summary = ''
if lines:
match = re.search(regex, lines)
summary = lines[:match.regs[0][0]] if match else lines
summary = summary.replace('\n', ' ').replace('\r', '')
return summary | python | def extract_full_summary_from_signature(operation):
""" Extract the summary from the docstring of the command. """
lines = inspect.getdoc(operation)
regex = r'\s*(:param)\s+(.+?)\s*:(.*)'
summary = ''
if lines:
match = re.search(regex, lines)
summary = lines[:match.regs[0][0]] if match else lines
summary = summary.replace('\n', ' ').replace('\r', '')
return summary | [
"def",
"extract_full_summary_from_signature",
"(",
"operation",
")",
":",
"lines",
"=",
"inspect",
".",
"getdoc",
"(",
"operation",
")",
"regex",
"=",
"r'\\s*(:param)\\s+(.+?)\\s*:(.*)'",
"summary",
"=",
"''",
"if",
"lines",
":",
"match",
"=",
"re",
".",
"search... | Extract the summary from the docstring of the command. | [
"Extract",
"the",
"summary",
"from",
"the",
"docstring",
"of",
"the",
"command",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/introspection.py#L15-L25 | train | 224,184 |
Microsoft/knack | knack/cli.py | CLI.get_runtime_version | def get_runtime_version(self): # pylint: disable=no-self-use
""" Get the runtime information.
:return: Runtime information
:rtype: str
"""
import platform
version_info = '\n\n'
version_info += 'Python ({}) {}'.format(platform.system(), sys.version)
version_info += '\n\n'
version_info += 'Python location \'{}\''.format(sys.executable)
version_info += '\n'
return version_info | python | def get_runtime_version(self): # pylint: disable=no-self-use
""" Get the runtime information.
:return: Runtime information
:rtype: str
"""
import platform
version_info = '\n\n'
version_info += 'Python ({}) {}'.format(platform.system(), sys.version)
version_info += '\n\n'
version_info += 'Python location \'{}\''.format(sys.executable)
version_info += '\n'
return version_info | [
"def",
"get_runtime_version",
"(",
"self",
")",
":",
"# pylint: disable=no-self-use",
"import",
"platform",
"version_info",
"=",
"'\\n\\n'",
"version_info",
"+=",
"'Python ({}) {}'",
".",
"format",
"(",
"platform",
".",
"system",
"(",
")",
",",
"sys",
".",
"versio... | Get the runtime information.
:return: Runtime information
:rtype: str | [
"Get",
"the",
"runtime",
"information",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/cli.py#L107-L120 | train | 224,185 |
Microsoft/knack | knack/cli.py | CLI.show_version | def show_version(self):
""" Print version information to the out file. """
version_info = self.get_cli_version()
version_info += self.get_runtime_version()
print(version_info, file=self.out_file) | python | def show_version(self):
""" Print version information to the out file. """
version_info = self.get_cli_version()
version_info += self.get_runtime_version()
print(version_info, file=self.out_file) | [
"def",
"show_version",
"(",
"self",
")",
":",
"version_info",
"=",
"self",
".",
"get_cli_version",
"(",
")",
"version_info",
"+=",
"self",
".",
"get_runtime_version",
"(",
")",
"print",
"(",
"version_info",
",",
"file",
"=",
"self",
".",
"out_file",
")"
] | Print version information to the out file. | [
"Print",
"version",
"information",
"to",
"the",
"out",
"file",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/cli.py#L122-L126 | train | 224,186 |
Microsoft/knack | knack/cli.py | CLI.unregister_event | def unregister_event(self, event_name, handler):
""" Unregister a callable that will be called when event is raised.
:param event_name: The name of the event (see knack.events for in-built events)
:type event_name: str
:param handler: The callback that was used to register the event
:type handler: function
"""
try:
self._event_handlers[event_name].remove(handler)
except ValueError:
pass | python | def unregister_event(self, event_name, handler):
""" Unregister a callable that will be called when event is raised.
:param event_name: The name of the event (see knack.events for in-built events)
:type event_name: str
:param handler: The callback that was used to register the event
:type handler: function
"""
try:
self._event_handlers[event_name].remove(handler)
except ValueError:
pass | [
"def",
"unregister_event",
"(",
"self",
",",
"event_name",
",",
"handler",
")",
":",
"try",
":",
"self",
".",
"_event_handlers",
"[",
"event_name",
"]",
".",
"remove",
"(",
"handler",
")",
"except",
"ValueError",
":",
"pass"
] | Unregister a callable that will be called when event is raised.
:param event_name: The name of the event (see knack.events for in-built events)
:type event_name: str
:param handler: The callback that was used to register the event
:type handler: function | [
"Unregister",
"a",
"callable",
"that",
"will",
"be",
"called",
"when",
"event",
"is",
"raised",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/cli.py#L139-L150 | train | 224,187 |
Microsoft/knack | knack/cli.py | CLI.raise_event | def raise_event(self, event_name, **kwargs):
""" Raise an event. Calls each handler in turn with kwargs
:param event_name: The name of the event to raise
:type event_name: str
:param kwargs: Kwargs to be passed to all event handlers
"""
handlers = list(self._event_handlers[event_name])
logger.debug('Event: %s %s', event_name, handlers)
for func in handlers:
func(self, **kwargs) | python | def raise_event(self, event_name, **kwargs):
""" Raise an event. Calls each handler in turn with kwargs
:param event_name: The name of the event to raise
:type event_name: str
:param kwargs: Kwargs to be passed to all event handlers
"""
handlers = list(self._event_handlers[event_name])
logger.debug('Event: %s %s', event_name, handlers)
for func in handlers:
func(self, **kwargs) | [
"def",
"raise_event",
"(",
"self",
",",
"event_name",
",",
"*",
"*",
"kwargs",
")",
":",
"handlers",
"=",
"list",
"(",
"self",
".",
"_event_handlers",
"[",
"event_name",
"]",
")",
"logger",
".",
"debug",
"(",
"'Event: %s %s'",
",",
"event_name",
",",
"ha... | Raise an event. Calls each handler in turn with kwargs
:param event_name: The name of the event to raise
:type event_name: str
:param kwargs: Kwargs to be passed to all event handlers | [
"Raise",
"an",
"event",
".",
"Calls",
"each",
"handler",
"in",
"turn",
"with",
"kwargs"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/cli.py#L152-L162 | train | 224,188 |
Microsoft/knack | knack/cli.py | CLI.exception_handler | def exception_handler(self, ex): # pylint: disable=no-self-use
""" The default exception handler """
if isinstance(ex, CLIError):
logger.error(ex)
else:
logger.exception(ex)
return 1 | python | def exception_handler(self, ex): # pylint: disable=no-self-use
""" The default exception handler """
if isinstance(ex, CLIError):
logger.error(ex)
else:
logger.exception(ex)
return 1 | [
"def",
"exception_handler",
"(",
"self",
",",
"ex",
")",
":",
"# pylint: disable=no-self-use",
"if",
"isinstance",
"(",
"ex",
",",
"CLIError",
")",
":",
"logger",
".",
"error",
"(",
"ex",
")",
"else",
":",
"logger",
".",
"exception",
"(",
"ex",
")",
"ret... | The default exception handler | [
"The",
"default",
"exception",
"handler"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/cli.py#L164-L170 | train | 224,189 |
Microsoft/knack | knack/cli.py | CLI.invoke | def invoke(self, args, initial_invocation_data=None, out_file=None):
""" Invoke a command.
:param args: The arguments that represent the command
:type args: list, tuple
:param initial_invocation_data: Prime the in memory collection of key-value data for this invocation.
:type initial_invocation_data: dict
:param out_file: The file to send output to. If not used, we use out_file for knack.cli.CLI instance
:type out_file: file-like object
:return: The exit code of the invocation
:rtype: int
"""
from .util import CommandResultItem
if not isinstance(args, (list, tuple)):
raise TypeError('args should be a list or tuple.')
exit_code = 0
try:
args = self.completion.get_completion_args() or args
out_file = out_file or self.out_file
self.logging.configure(args)
logger.debug('Command arguments: %s', args)
self.raise_event(EVENT_CLI_PRE_EXECUTE)
if CLI._should_show_version(args):
self.show_version()
self.result = CommandResultItem(None)
else:
self.invocation = self.invocation_cls(cli_ctx=self,
parser_cls=self.parser_cls,
commands_loader_cls=self.commands_loader_cls,
help_cls=self.help_cls,
initial_data=initial_invocation_data)
cmd_result = self.invocation.execute(args)
self.result = cmd_result
exit_code = self.result.exit_code
output_type = self.invocation.data['output']
if cmd_result and cmd_result.result is not None:
formatter = self.output.get_formatter(output_type)
self.output.out(cmd_result, formatter=formatter, out_file=out_file)
self.raise_event(EVENT_CLI_POST_EXECUTE)
except KeyboardInterrupt as ex:
self.result = CommandResultItem(None, error=ex)
exit_code = 1
except Exception as ex: # pylint: disable=broad-except
exit_code = self.exception_handler(ex)
self.result = CommandResultItem(None, error=ex)
finally:
pass
self.result.exit_code = exit_code
return exit_code | python | def invoke(self, args, initial_invocation_data=None, out_file=None):
""" Invoke a command.
:param args: The arguments that represent the command
:type args: list, tuple
:param initial_invocation_data: Prime the in memory collection of key-value data for this invocation.
:type initial_invocation_data: dict
:param out_file: The file to send output to. If not used, we use out_file for knack.cli.CLI instance
:type out_file: file-like object
:return: The exit code of the invocation
:rtype: int
"""
from .util import CommandResultItem
if not isinstance(args, (list, tuple)):
raise TypeError('args should be a list or tuple.')
exit_code = 0
try:
args = self.completion.get_completion_args() or args
out_file = out_file or self.out_file
self.logging.configure(args)
logger.debug('Command arguments: %s', args)
self.raise_event(EVENT_CLI_PRE_EXECUTE)
if CLI._should_show_version(args):
self.show_version()
self.result = CommandResultItem(None)
else:
self.invocation = self.invocation_cls(cli_ctx=self,
parser_cls=self.parser_cls,
commands_loader_cls=self.commands_loader_cls,
help_cls=self.help_cls,
initial_data=initial_invocation_data)
cmd_result = self.invocation.execute(args)
self.result = cmd_result
exit_code = self.result.exit_code
output_type = self.invocation.data['output']
if cmd_result and cmd_result.result is not None:
formatter = self.output.get_formatter(output_type)
self.output.out(cmd_result, formatter=formatter, out_file=out_file)
self.raise_event(EVENT_CLI_POST_EXECUTE)
except KeyboardInterrupt as ex:
self.result = CommandResultItem(None, error=ex)
exit_code = 1
except Exception as ex: # pylint: disable=broad-except
exit_code = self.exception_handler(ex)
self.result = CommandResultItem(None, error=ex)
finally:
pass
self.result.exit_code = exit_code
return exit_code | [
"def",
"invoke",
"(",
"self",
",",
"args",
",",
"initial_invocation_data",
"=",
"None",
",",
"out_file",
"=",
"None",
")",
":",
"from",
".",
"util",
"import",
"CommandResultItem",
"if",
"not",
"isinstance",
"(",
"args",
",",
"(",
"list",
",",
"tuple",
")... | Invoke a command.
:param args: The arguments that represent the command
:type args: list, tuple
:param initial_invocation_data: Prime the in memory collection of key-value data for this invocation.
:type initial_invocation_data: dict
:param out_file: The file to send output to. If not used, we use out_file for knack.cli.CLI instance
:type out_file: file-like object
:return: The exit code of the invocation
:rtype: int | [
"Invoke",
"a",
"command",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/cli.py#L172-L223 | train | 224,190 |
Microsoft/knack | knack/log.py | get_logger | def get_logger(module_name=None):
""" Get the logger for a module. If no module name is given, the current CLI logger is returned.
Example:
get_logger(__name__)
:param module_name: The module to get the logger for
:type module_name: str
:return: The logger
:rtype: logger
"""
if module_name:
logger_name = '{}.{}'.format(CLI_LOGGER_NAME, module_name)
else:
logger_name = CLI_LOGGER_NAME
return logging.getLogger(logger_name) | python | def get_logger(module_name=None):
""" Get the logger for a module. If no module name is given, the current CLI logger is returned.
Example:
get_logger(__name__)
:param module_name: The module to get the logger for
:type module_name: str
:return: The logger
:rtype: logger
"""
if module_name:
logger_name = '{}.{}'.format(CLI_LOGGER_NAME, module_name)
else:
logger_name = CLI_LOGGER_NAME
return logging.getLogger(logger_name) | [
"def",
"get_logger",
"(",
"module_name",
"=",
"None",
")",
":",
"if",
"module_name",
":",
"logger_name",
"=",
"'{}.{}'",
".",
"format",
"(",
"CLI_LOGGER_NAME",
",",
"module_name",
")",
"else",
":",
"logger_name",
"=",
"CLI_LOGGER_NAME",
"return",
"logging",
".... | Get the logger for a module. If no module name is given, the current CLI logger is returned.
Example:
get_logger(__name__)
:param module_name: The module to get the logger for
:type module_name: str
:return: The logger
:rtype: logger | [
"Get",
"the",
"logger",
"for",
"a",
"module",
".",
"If",
"no",
"module",
"name",
"is",
"given",
"the",
"current",
"CLI",
"logger",
"is",
"returned",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/log.py#L16-L31 | train | 224,191 |
Microsoft/knack | knack/log.py | CLILogging.configure | def configure(self, args):
""" Configure the loggers with the appropriate log level etc.
:param args: The arguments from the command line
:type args: list
"""
verbose_level = self._determine_verbose_level(args)
log_level_config = self.console_log_configs[verbose_level]
root_logger = logging.getLogger()
cli_logger = logging.getLogger(CLI_LOGGER_NAME)
# Set the levels of the loggers to lowest level.
# Handlers can override by choosing a higher level.
root_logger.setLevel(logging.DEBUG)
cli_logger.setLevel(logging.DEBUG)
cli_logger.propagate = False
if root_logger.handlers and cli_logger.handlers:
# loggers already configured
return
self._init_console_handlers(root_logger, cli_logger, log_level_config)
if self.file_log_enabled:
self._init_logfile_handlers(root_logger, cli_logger)
get_logger(__name__).debug("File logging enabled - writing logs to '%s'.", self.log_dir) | python | def configure(self, args):
""" Configure the loggers with the appropriate log level etc.
:param args: The arguments from the command line
:type args: list
"""
verbose_level = self._determine_verbose_level(args)
log_level_config = self.console_log_configs[verbose_level]
root_logger = logging.getLogger()
cli_logger = logging.getLogger(CLI_LOGGER_NAME)
# Set the levels of the loggers to lowest level.
# Handlers can override by choosing a higher level.
root_logger.setLevel(logging.DEBUG)
cli_logger.setLevel(logging.DEBUG)
cli_logger.propagate = False
if root_logger.handlers and cli_logger.handlers:
# loggers already configured
return
self._init_console_handlers(root_logger, cli_logger, log_level_config)
if self.file_log_enabled:
self._init_logfile_handlers(root_logger, cli_logger)
get_logger(__name__).debug("File logging enabled - writing logs to '%s'.", self.log_dir) | [
"def",
"configure",
"(",
"self",
",",
"args",
")",
":",
"verbose_level",
"=",
"self",
".",
"_determine_verbose_level",
"(",
"args",
")",
"log_level_config",
"=",
"self",
".",
"console_log_configs",
"[",
"verbose_level",
"]",
"root_logger",
"=",
"logging",
".",
... | Configure the loggers with the appropriate log level etc.
:param args: The arguments from the command line
:type args: list | [
"Configure",
"the",
"loggers",
"with",
"the",
"appropriate",
"log",
"level",
"etc",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/log.py#L120-L141 | train | 224,192 |
Microsoft/knack | knack/log.py | CLILogging._determine_verbose_level | def _determine_verbose_level(self, args):
""" Get verbose level by reading the arguments. """
verbose_level = 0
for arg in args:
if arg == CLILogging.VERBOSE_FLAG:
verbose_level += 1
elif arg == CLILogging.DEBUG_FLAG:
verbose_level += 2
# Use max verbose level if too much verbosity specified.
return min(verbose_level, len(self.console_log_configs) - 1) | python | def _determine_verbose_level(self, args):
""" Get verbose level by reading the arguments. """
verbose_level = 0
for arg in args:
if arg == CLILogging.VERBOSE_FLAG:
verbose_level += 1
elif arg == CLILogging.DEBUG_FLAG:
verbose_level += 2
# Use max verbose level if too much verbosity specified.
return min(verbose_level, len(self.console_log_configs) - 1) | [
"def",
"_determine_verbose_level",
"(",
"self",
",",
"args",
")",
":",
"verbose_level",
"=",
"0",
"for",
"arg",
"in",
"args",
":",
"if",
"arg",
"==",
"CLILogging",
".",
"VERBOSE_FLAG",
":",
"verbose_level",
"+=",
"1",
"elif",
"arg",
"==",
"CLILogging",
"."... | Get verbose level by reading the arguments. | [
"Get",
"verbose",
"level",
"by",
"reading",
"the",
"arguments",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/log.py#L143-L152 | train | 224,193 |
Microsoft/knack | knack/arguments.py | enum_choice_list | def enum_choice_list(data):
""" Creates the argparse choices and type kwargs for a supplied enum type or list of strings """
# transform enum types, otherwise assume list of string choices
if not data:
return {}
try:
choices = [x.value for x in data]
except AttributeError:
choices = data
def _type(value):
return next((x for x in choices if x.lower() == value.lower()), value) if value else value
params = {
'choices': CaseInsensitiveList(choices),
'type': _type
}
return params | python | def enum_choice_list(data):
""" Creates the argparse choices and type kwargs for a supplied enum type or list of strings """
# transform enum types, otherwise assume list of string choices
if not data:
return {}
try:
choices = [x.value for x in data]
except AttributeError:
choices = data
def _type(value):
return next((x for x in choices if x.lower() == value.lower()), value) if value else value
params = {
'choices': CaseInsensitiveList(choices),
'type': _type
}
return params | [
"def",
"enum_choice_list",
"(",
"data",
")",
":",
"# transform enum types, otherwise assume list of string choices",
"if",
"not",
"data",
":",
"return",
"{",
"}",
"try",
":",
"choices",
"=",
"[",
"x",
".",
"value",
"for",
"x",
"in",
"data",
"]",
"except",
"Att... | Creates the argparse choices and type kwargs for a supplied enum type or list of strings | [
"Creates",
"the",
"argparse",
"choices",
"and",
"type",
"kwargs",
"for",
"a",
"supplied",
"enum",
"type",
"or",
"list",
"of",
"strings"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/arguments.py#L359-L376 | train | 224,194 |
Microsoft/knack | knack/arguments.py | ArgumentRegistry.register_cli_argument | def register_cli_argument(self, scope, dest, argtype, **kwargs):
""" Add an argument to the argument registry
:param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand')
:type scope: str
:param dest: The parameter/destination that this argument is for
:type dest: str
:param argtype: The argument type for this command argument
:type argtype: knack.arguments.CLIArgumentType
:param kwargs: see knack.arguments.CLIArgumentType
"""
argument = CLIArgumentType(overrides=argtype, **kwargs)
self.arguments[scope][dest] = argument | python | def register_cli_argument(self, scope, dest, argtype, **kwargs):
""" Add an argument to the argument registry
:param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand')
:type scope: str
:param dest: The parameter/destination that this argument is for
:type dest: str
:param argtype: The argument type for this command argument
:type argtype: knack.arguments.CLIArgumentType
:param kwargs: see knack.arguments.CLIArgumentType
"""
argument = CLIArgumentType(overrides=argtype, **kwargs)
self.arguments[scope][dest] = argument | [
"def",
"register_cli_argument",
"(",
"self",
",",
"scope",
",",
"dest",
",",
"argtype",
",",
"*",
"*",
"kwargs",
")",
":",
"argument",
"=",
"CLIArgumentType",
"(",
"overrides",
"=",
"argtype",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"arguments",
"[",
... | Add an argument to the argument registry
:param scope: The command level to apply the argument registration (e.g. 'mygroup mycommand')
:type scope: str
:param dest: The parameter/destination that this argument is for
:type dest: str
:param argtype: The argument type for this command argument
:type argtype: knack.arguments.CLIArgumentType
:param kwargs: see knack.arguments.CLIArgumentType | [
"Add",
"an",
"argument",
"to",
"the",
"argument",
"registry"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/arguments.py#L93-L105 | train | 224,195 |
Microsoft/knack | knack/arguments.py | ArgumentRegistry.get_cli_argument | def get_cli_argument(self, command, name):
""" Get the argument for the command after applying the scope hierarchy
:param command: The command that we want the argument for
:type command: str
:param name: The name of the argument
:type name: str
:return: The CLI command after all overrides in the scope hierarchy have been applied
:rtype: knack.arguments.CLIArgumentType
"""
parts = command.split()
result = CLIArgumentType()
for index in range(0, len(parts) + 1):
probe = ' '.join(parts[0:index])
override = self.arguments.get(probe, {}).get(name, None)
if override:
result.update(override)
return result | python | def get_cli_argument(self, command, name):
""" Get the argument for the command after applying the scope hierarchy
:param command: The command that we want the argument for
:type command: str
:param name: The name of the argument
:type name: str
:return: The CLI command after all overrides in the scope hierarchy have been applied
:rtype: knack.arguments.CLIArgumentType
"""
parts = command.split()
result = CLIArgumentType()
for index in range(0, len(parts) + 1):
probe = ' '.join(parts[0:index])
override = self.arguments.get(probe, {}).get(name, None)
if override:
result.update(override)
return result | [
"def",
"get_cli_argument",
"(",
"self",
",",
"command",
",",
"name",
")",
":",
"parts",
"=",
"command",
".",
"split",
"(",
")",
"result",
"=",
"CLIArgumentType",
"(",
")",
"for",
"index",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"parts",
")",
"+",
... | Get the argument for the command after applying the scope hierarchy
:param command: The command that we want the argument for
:type command: str
:param name: The name of the argument
:type name: str
:return: The CLI command after all overrides in the scope hierarchy have been applied
:rtype: knack.arguments.CLIArgumentType | [
"Get",
"the",
"argument",
"for",
"the",
"command",
"after",
"applying",
"the",
"scope",
"hierarchy"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/arguments.py#L107-L124 | train | 224,196 |
Microsoft/knack | knack/arguments.py | ArgumentsContext.argument | def argument(self, argument_dest, arg_type=None, **kwargs):
""" Register an argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided kwargs.
:type arg_type: knack.arguments.CLIArgumentType
:param kwargs: Possible values: `options_list`, `validator`, `completer`, `nargs`, `action`, `const`, `default`,
`type`, `choices`, `required`, `help`, `metavar`. See /docs/arguments.md.
"""
self._check_stale()
if not self._applicable():
return
deprecate_action = self._handle_deprecations(argument_dest, **kwargs)
if deprecate_action:
kwargs['action'] = deprecate_action
self.command_loader.argument_registry.register_cli_argument(self.command_scope,
argument_dest,
arg_type,
**kwargs) | python | def argument(self, argument_dest, arg_type=None, **kwargs):
""" Register an argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided kwargs.
:type arg_type: knack.arguments.CLIArgumentType
:param kwargs: Possible values: `options_list`, `validator`, `completer`, `nargs`, `action`, `const`, `default`,
`type`, `choices`, `required`, `help`, `metavar`. See /docs/arguments.md.
"""
self._check_stale()
if not self._applicable():
return
deprecate_action = self._handle_deprecations(argument_dest, **kwargs)
if deprecate_action:
kwargs['action'] = deprecate_action
self.command_loader.argument_registry.register_cli_argument(self.command_scope,
argument_dest,
arg_type,
**kwargs) | [
"def",
"argument",
"(",
"self",
",",
"argument_dest",
",",
"arg_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_stale",
"(",
")",
"if",
"not",
"self",
".",
"_applicable",
"(",
")",
":",
"return",
"deprecate_action",
"=",
"se... | Register an argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided kwargs.
:type arg_type: knack.arguments.CLIArgumentType
:param kwargs: Possible values: `options_list`, `validator`, `completer`, `nargs`, `action`, `const`, `default`,
`type`, `choices`, `required`, `help`, `metavar`. See /docs/arguments.md. | [
"Register",
"an",
"argument",
"for",
"the",
"given",
"command",
"scope",
"using",
"a",
"knack",
".",
"arguments",
".",
"CLIArgumentType"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/arguments.py#L247-L267 | train | 224,197 |
Microsoft/knack | knack/arguments.py | ArgumentsContext.positional | def positional(self, argument_dest, arg_type=None, **kwargs):
""" Register a positional argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided kwargs.
:type arg_type: knack.arguments.CLIArgumentType
:param kwargs: Possible values: `validator`, `completer`, `nargs`, `action`, `const`, `default`,
`type`, `choices`, `required`, `help`, `metavar`. See /docs/arguments.md.
"""
self._check_stale()
if not self._applicable():
return
if self.command_scope not in self.command_loader.command_table:
raise ValueError("command authoring error: positional argument '{}' cannot be registered to a group-level "
"scope '{}'. It must be registered to a specific command.".format(
argument_dest, self.command_scope))
# Before adding the new positional arg, ensure that there are no existing positional arguments
# registered for this command.
command_args = self.command_loader.argument_registry.arguments[self.command_scope]
positional_args = {k: v for k, v in command_args.items() if v.settings.get('options_list') == []}
if positional_args and argument_dest not in positional_args:
raise CLIError("command authoring error: commands may have, at most, one positional argument. '{}' already "
"has positional argument: {}.".format(self.command_scope, ' '.join(positional_args.keys())))
deprecate_action = self._handle_deprecations(argument_dest, **kwargs)
if deprecate_action:
kwargs['action'] = deprecate_action
kwargs['options_list'] = []
self.command_loader.argument_registry.register_cli_argument(self.command_scope,
argument_dest,
arg_type,
**kwargs) | python | def positional(self, argument_dest, arg_type=None, **kwargs):
""" Register a positional argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided kwargs.
:type arg_type: knack.arguments.CLIArgumentType
:param kwargs: Possible values: `validator`, `completer`, `nargs`, `action`, `const`, `default`,
`type`, `choices`, `required`, `help`, `metavar`. See /docs/arguments.md.
"""
self._check_stale()
if not self._applicable():
return
if self.command_scope not in self.command_loader.command_table:
raise ValueError("command authoring error: positional argument '{}' cannot be registered to a group-level "
"scope '{}'. It must be registered to a specific command.".format(
argument_dest, self.command_scope))
# Before adding the new positional arg, ensure that there are no existing positional arguments
# registered for this command.
command_args = self.command_loader.argument_registry.arguments[self.command_scope]
positional_args = {k: v for k, v in command_args.items() if v.settings.get('options_list') == []}
if positional_args and argument_dest not in positional_args:
raise CLIError("command authoring error: commands may have, at most, one positional argument. '{}' already "
"has positional argument: {}.".format(self.command_scope, ' '.join(positional_args.keys())))
deprecate_action = self._handle_deprecations(argument_dest, **kwargs)
if deprecate_action:
kwargs['action'] = deprecate_action
kwargs['options_list'] = []
self.command_loader.argument_registry.register_cli_argument(self.command_scope,
argument_dest,
arg_type,
**kwargs) | [
"def",
"positional",
"(",
"self",
",",
"argument_dest",
",",
"arg_type",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_stale",
"(",
")",
"if",
"not",
"self",
".",
"_applicable",
"(",
")",
":",
"return",
"if",
"self",
".",
"comm... | Register a positional argument for the given command scope using a knack.arguments.CLIArgumentType
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param arg_type: Predefined CLIArgumentType definition to register, as modified by any provided kwargs.
:type arg_type: knack.arguments.CLIArgumentType
:param kwargs: Possible values: `validator`, `completer`, `nargs`, `action`, `const`, `default`,
`type`, `choices`, `required`, `help`, `metavar`. See /docs/arguments.md. | [
"Register",
"a",
"positional",
"argument",
"for",
"the",
"given",
"command",
"scope",
"using",
"a",
"knack",
".",
"arguments",
".",
"CLIArgumentType"
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/arguments.py#L269-L304 | train | 224,198 |
Microsoft/knack | knack/arguments.py | ArgumentsContext.extra | def extra(self, argument_dest, **kwargs):
"""Register extra parameters for the given command. Typically used to augment auto-command built
commands to add more parameters than the specific SDK method introspected.
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param kwargs: Possible values: `options_list`, `validator`, `completer`, `nargs`, `action`, `const`, `default`,
`type`, `choices`, `required`, `help`, `metavar`. See /docs/arguments.md.
"""
self._check_stale()
if not self._applicable():
return
if self.command_scope in self.command_loader.command_group_table:
raise ValueError("command authoring error: extra argument '{}' cannot be registered to a group-level "
"scope '{}'. It must be registered to a specific command.".format(
argument_dest, self.command_scope))
deprecate_action = self._handle_deprecations(argument_dest, **kwargs)
if deprecate_action:
kwargs['action'] = deprecate_action
self.command_loader.extra_argument_registry[self.command_scope][argument_dest] = CLICommandArgument(
argument_dest, **kwargs) | python | def extra(self, argument_dest, **kwargs):
"""Register extra parameters for the given command. Typically used to augment auto-command built
commands to add more parameters than the specific SDK method introspected.
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param kwargs: Possible values: `options_list`, `validator`, `completer`, `nargs`, `action`, `const`, `default`,
`type`, `choices`, `required`, `help`, `metavar`. See /docs/arguments.md.
"""
self._check_stale()
if not self._applicable():
return
if self.command_scope in self.command_loader.command_group_table:
raise ValueError("command authoring error: extra argument '{}' cannot be registered to a group-level "
"scope '{}'. It must be registered to a specific command.".format(
argument_dest, self.command_scope))
deprecate_action = self._handle_deprecations(argument_dest, **kwargs)
if deprecate_action:
kwargs['action'] = deprecate_action
self.command_loader.extra_argument_registry[self.command_scope][argument_dest] = CLICommandArgument(
argument_dest, **kwargs) | [
"def",
"extra",
"(",
"self",
",",
"argument_dest",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"_check_stale",
"(",
")",
"if",
"not",
"self",
".",
"_applicable",
"(",
")",
":",
"return",
"if",
"self",
".",
"command_scope",
"in",
"self",
".",
"com... | Register extra parameters for the given command. Typically used to augment auto-command built
commands to add more parameters than the specific SDK method introspected.
:param argument_dest: The destination argument to add this argument type to
:type argument_dest: str
:param kwargs: Possible values: `options_list`, `validator`, `completer`, `nargs`, `action`, `const`, `default`,
`type`, `choices`, `required`, `help`, `metavar`. See /docs/arguments.md. | [
"Register",
"extra",
"parameters",
"for",
"the",
"given",
"command",
".",
"Typically",
"used",
"to",
"augment",
"auto",
"-",
"command",
"built",
"commands",
"to",
"add",
"more",
"parameters",
"than",
"the",
"specific",
"SDK",
"method",
"introspected",
"."
] | 5f1a480a33f103e2688c46eef59fb2d9eaf2baad | https://github.com/Microsoft/knack/blob/5f1a480a33f103e2688c46eef59fb2d9eaf2baad/knack/arguments.py#L319-L341 | train | 224,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.