idx int64 0 63k | question stringlengths 61 4.03k | target stringlengths 6 1.23k |
|---|---|---|
35,200 | def _get_items ( self , request ) : if request . gpd_iterator is None : self . gpd_iterator = GeopediaFeatureIterator ( request . layer , bbox = request . bbox , base_url = self . base_url , gpd_session = request . gpd_session ) else : self . gpd_iterator = request . gpd_iterator field_iter = self . gpd_iterator . get_... | Collects data from Geopedia layer and returns list of features |
35,201 | def _get_filename ( request , item ) : if request . keep_image_names : filename = OgcImageService . finalize_filename ( item [ 'niceName' ] . replace ( ' ' , '_' ) ) else : filename = OgcImageService . finalize_filename ( '_' . join ( [ str ( GeopediaService . _parse_layer ( request . layer ) ) , item [ 'objectPath' ] ... | Creates a filename |
35,202 | def _fetch_features ( self ) : if self . next_page_url is None : return response = get_json ( self . next_page_url , post_values = self . query , headers = self . gpd_session . session_headers ) self . features . extend ( response [ 'features' ] ) self . next_page_url = response [ 'pagination' ] [ 'next' ] self . layer... | Retrieves a new page of features from Geopedia |
35,203 | def get_folder_list ( folder = '.' ) : dir_list = get_content_list ( folder ) return [ f for f in dir_list if not os . path . isfile ( os . path . join ( folder , f ) ) ] | Get list of sub - folders contained in input folder |
35,204 | def create_parent_folder ( filename ) : path = os . path . dirname ( filename ) if path != '' : make_folder ( path ) | Create parent folder for input filename recursively |
35,205 | def make_folder ( path ) : if not os . path . exists ( path ) : try : os . makedirs ( path ) except OSError as exception : if exception . errno != errno . EEXIST : raise ValueError ( 'Specified folder is not writable: %s' '\nPlease check permissions or set a new valid folder.' % path ) | Create folder at input path recursively |
35,206 | def rename ( old_path , new_path , edit_folders = True ) : if edit_folders : os . renames ( old_path , new_path ) else : os . rename ( old_path , new_path ) | Rename files or folders |
35,207 | def size ( pathname ) : if os . path . isfile ( pathname ) : return os . path . getsize ( pathname ) return sum ( [ size ( '{}/{}' . format ( pathname , name ) ) for name in get_content_list ( pathname ) ] ) | Returns size of a file or folder in Bytes |
35,208 | def middle ( self ) : return ( self . min_x + self . max_x ) / 2 , ( self . min_y + self . max_y ) / 2 | Returns the middle point of the bounding box |
35,209 | def reverse ( self ) : return BBox ( ( self . min_y , self . min_x , self . max_y , self . max_x ) , crs = self . crs ) | Returns a new BBox object where x and y coordinates are switched |
35,210 | def transform ( self , crs ) : new_crs = CRS ( crs ) return BBox ( ( transform_point ( self . lower_left , self . crs , new_crs ) , transform_point ( self . upper_right , self . crs , new_crs ) ) , crs = new_crs ) | Transforms BBox from current CRS to target CRS |
35,211 | def get_polygon ( self , reverse = False ) : bbox = self . reverse ( ) if reverse else self polygon = ( ( bbox . min_x , bbox . min_y ) , ( bbox . min_x , bbox . max_y ) , ( bbox . max_x , bbox . max_y ) , ( bbox . max_x , bbox . min_y ) , ( bbox . min_x , bbox . min_y ) ) return polygon | Returns a tuple of coordinates of 5 points describing a polygon . Points are listed in clockwise order first point is the same as the last . |
35,212 | def get_partition ( self , num_x = 1 , num_y = 1 ) : size_x , size_y = ( self . max_x - self . min_x ) / num_x , ( self . max_y - self . min_y ) / num_y return [ [ BBox ( [ self . min_x + i * size_x , self . min_y + j * size_y , self . min_x + ( i + 1 ) * size_x , self . min_y + ( j + 1 ) * size_y ] , crs = self . crs ... | Partitions bounding box into smaller bounding boxes of the same size . |
35,213 | def get_transform_vector ( self , resx , resy ) : return self . x_min , self . _parse_resolution ( resx ) , 0 , self . y_max , 0 , - self . _parse_resolution ( resy ) | Given resolution it returns a transformation vector |
35,214 | def _parse_resolution ( res ) : if isinstance ( res , str ) : return float ( res . strip ( 'm' ) ) if isinstance ( res , ( int , float ) ) : return float ( res ) raise TypeError ( 'Resolution should be a float, got resolution of type {}' . format ( type ( res ) ) ) | Helper method for parsing given resolution . It will also try to parse a string into float |
35,215 | def _tuple_from_list_or_tuple ( bbox ) : if len ( bbox ) == 4 : return tuple ( map ( float , bbox ) ) if len ( bbox ) == 2 and all ( [ isinstance ( point , ( list , tuple ) ) for point in bbox ] ) : return BBox . _tuple_from_list_or_tuple ( bbox [ 0 ] + bbox [ 1 ] ) raise TypeError ( 'Expected a valid list or tuple rep... | Converts a list or tuple representation of a bbox into a flat tuple representation . |
35,216 | def _tuple_from_str ( bbox ) : return tuple ( [ float ( s ) for s in bbox . replace ( ',' , ' ' ) . split ( ) if s ] ) | Parses a string of numbers separated by any combination of commas and spaces |
35,217 | def reverse ( self ) : return Geometry ( shapely . ops . transform ( lambda x , y : ( y , x ) , self . geometry ) , crs = self . crs ) | Returns a new Geometry object where x and y coordinates are switched |
35,218 | def transform ( self , crs ) : new_crs = CRS ( crs ) geometry = self . geometry if new_crs is not self . crs : project = functools . partial ( pyproj . transform , self . crs . projection ( ) , new_crs . projection ( ) ) geometry = shapely . ops . transform ( project , geometry ) return Geometry ( geometry , crs = new_... | Transforms Geometry from current CRS to target CRS |
35,219 | def _parse_geometry ( geometry ) : if isinstance ( geometry , str ) : geometry = shapely . wkt . loads ( geometry ) elif isinstance ( geometry , dict ) : geometry = shapely . geometry . shape ( geometry ) elif not isinstance ( geometry , shapely . geometry . base . BaseGeometry ) : raise TypeError ( 'Unsupported geomet... | Parses given geometry into shapely object |
35,220 | def transform ( self , crs ) : return BBoxCollection ( [ bbox . transform ( crs ) for bbox in self . bbox_list ] ) | Transforms BBoxCollection from current CRS to target CRS |
35,221 | def _get_geometry ( self ) : return shapely . geometry . MultiPolygon ( [ bbox . geometry for bbox in self . bbox_list ] ) | Creates a multipolygon of bounding box polygons |
35,222 | def _parse_bbox_list ( bbox_list ) : if isinstance ( bbox_list , BBoxCollection ) : return bbox_list . bbox_list , bbox_list . crs if not isinstance ( bbox_list , list ) or not bbox_list : raise ValueError ( 'Expected non-empty list of BBox objects' ) for bbox in bbox_list : if not isinstance ( bbox , BBox ) : raise Va... | Helper method for parsing a list of bounding boxes |
35,223 | def read_data ( filename , data_format = None ) : if not os . path . exists ( filename ) : raise ValueError ( 'Filename {} does not exist' . format ( filename ) ) if not isinstance ( data_format , MimeType ) : data_format = get_data_format ( filename ) if data_format . is_tiff_format ( ) : return read_tiff_image ( file... | Read image data from file |
35,224 | def read_jp2_image ( filename ) : image = read_image ( filename ) with open ( filename , 'rb' ) as file : bit_depth = get_jp2_bit_depth ( file ) return fix_jp2_image ( image , bit_depth ) | Read data from JPEG2000 file |
35,225 | def read_csv ( filename , delimiter = CSV_DELIMITER ) : with open ( filename , 'r' ) as file : return list ( csv . reader ( file , delimiter = delimiter ) ) | Read data from CSV file |
35,226 | def write_data ( filename , data , data_format = None , compress = False , add = False ) : create_parent_folder ( filename ) if not isinstance ( data_format , MimeType ) : data_format = get_data_format ( filename ) if data_format . is_tiff_format ( ) : return write_tiff_image ( filename , data , compress ) if data_form... | Write image data to file |
35,227 | def write_tiff_image ( filename , image , compress = False ) : if compress : return tiff . imsave ( filename , image , compress = 'lzma' ) return tiff . imsave ( filename , image ) | Write image data to TIFF file |
35,228 | def write_image ( filename , image ) : data_format = get_data_format ( filename ) if data_format is MimeType . JPG : LOGGER . warning ( 'Warning: jpeg is a lossy format therefore saved data will be modified.' ) return Image . fromarray ( image ) . save ( filename ) | Write image data to PNG JPG file |
35,229 | def write_text ( filename , data , add = False ) : write_type = 'a' if add else 'w' with open ( filename , write_type ) as file : print ( data , end = '' , file = file ) | Write image data to text file |
35,230 | def write_csv ( filename , data , delimiter = CSV_DELIMITER ) : with open ( filename , 'w' ) as file : csv_writer = csv . writer ( file , delimiter = delimiter ) for line in data : csv_writer . writerow ( line ) | Write image data to CSV file |
35,231 | def write_json ( filename , data ) : with open ( filename , 'w' ) as file : json . dump ( data , file , indent = 4 , sort_keys = True ) | Write data to JSON file |
35,232 | def get_jp2_bit_depth ( stream ) : stream . seek ( 0 ) while True : read_buffer = stream . read ( 8 ) if len ( read_buffer ) < 8 : raise ValueError ( 'Image Header Box not found in Jpeg2000 file' ) _ , box_id = struct . unpack ( '>I4s' , read_buffer ) if box_id == b'ihdr' : read_buffer = stream . read ( 14 ) params = s... | Reads bit encoding depth of jpeg2000 file in binary stream format |
35,233 | def fix_jp2_image ( image , bit_depth ) : if bit_depth in [ 8 , 16 ] : return image if bit_depth == 15 : try : return image >> 1 except TypeError : raise IOError ( 'Failed to read JPEG 2000 image correctly. Most likely reason is that Pillow did not ' 'install OpenJPEG library correctly. Try reinstalling Pillow from a w... | Because Pillow library incorrectly reads JPEG 2000 images with 15 - bit encoding this function corrects the values in image . |
35,234 | def download_data ( request_list , redownload = False , max_threads = None ) : _check_if_must_download ( request_list , redownload ) LOGGER . debug ( "Using max_threads=%s for %s requests" , max_threads , len ( request_list ) ) with concurrent . futures . ThreadPoolExecutor ( max_workers = max_threads ) as executor : r... | Download all requested data or read data from disk if already downloaded and available and redownload is not required . |
35,235 | def _check_if_must_download ( request_list , redownload ) : for request in request_list : request . will_download = ( request . save_response or request . return_data ) and ( not request . is_downloaded ( ) or redownload ) | Updates request . will_download attribute of each request in request_list . |
35,236 | def execute_download_request ( request ) : if request . save_response and request . data_folder is None : raise ValueError ( 'Data folder is not specified. ' 'Please give a data folder name in the initialization of your request.' ) if not request . will_download : return None try_num = SHConfig ( ) . max_download_attem... | Executes download request . |
35,237 | def _is_temporal_problem ( exception ) : try : return isinstance ( exception , ( requests . ConnectionError , requests . Timeout ) ) except AttributeError : return isinstance ( exception , requests . ConnectionError ) | Checks if the obtained exception is temporal and if download attempt should be repeated |
35,238 | def _create_download_failed_message ( exception , url ) : message = 'Failed to download from:\n{}\nwith {}:\n{}' . format ( url , exception . __class__ . __name__ , exception ) if _is_temporal_problem ( exception ) : if isinstance ( exception , requests . ConnectionError ) : message += '\nPlease check your internet con... | Creates message describing why download has failed |
35,239 | def decode_data ( response_content , data_type , entire_response = None ) : LOGGER . debug ( 'data_type=%s' , data_type ) if data_type is MimeType . JSON : if isinstance ( entire_response , requests . Response ) : return entire_response . json ( ) return json . loads ( response_content . decode ( 'utf-8' ) ) if MimeTyp... | Interprets downloaded data and returns it . |
35,240 | def decode_image ( data , image_type ) : bytes_data = BytesIO ( data ) if image_type . is_tiff_format ( ) : image = tiff . imread ( bytes_data ) else : image = np . array ( Image . open ( bytes_data ) ) if image_type is MimeType . JP2 : try : bit_depth = get_jp2_bit_depth ( bytes_data ) image = fix_jp2_image ( image , ... | 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 |
35,241 | def get_json ( url , post_values = None , headers = None ) : json_headers = { } if headers is None else headers . copy ( ) if post_values is None : request_type = RequestType . GET else : request_type = RequestType . POST json_headers = { ** json_headers , ** { 'Content-Type' : MimeType . get_string ( MimeType . JSON )... | Download request as JSON data type |
35,242 | def get_xml ( url ) : request = DownloadRequest ( url = url , request_type = RequestType . GET , save_response = False , return_data = True , data_type = MimeType . XML ) return execute_download_request ( request ) | Download request as XML data type |
35,243 | 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 . |
35,244 | def get_area_info ( bbox , date_interval , maxcc = None ) : result_list = search_iter ( bbox = bbox , start_date = date_interval [ 0 ] , end_date = date_interval [ 1 ] ) if maxcc : return reduce_by_maxcc ( result_list , maxcc ) return result_list | Get information about all images from specified area and time range |
35,245 | def get_area_dates ( bbox , date_interval , maxcc = None ) : area_info = get_area_info ( bbox , date_interval , maxcc = maxcc ) return sorted ( { datetime . datetime . strptime ( tile_info [ 'properties' ] [ 'startDate' ] . strip ( 'Z' ) , '%Y-%m-%dT%H:%M:%S' ) for tile_info in area_info } ) | Get list of times of existing images from specified area and time range |
35,246 | def search_iter ( tile_id = None , bbox = None , start_date = None , end_date = None , absolute_orbit = None ) : if bbox and bbox . crs is not CRS . WGS84 : bbox = bbox . transform ( CRS . WGS84 ) url_params = _prepare_url_params ( tile_id , bbox , end_date , start_date , absolute_orbit ) url_params [ 'maxRecords' ] = ... | A generator function that implements OpenSearch search queries and returns results |
35,247 | def _prepare_url_params ( tile_id , bbox , end_date , start_date , absolute_orbit ) : url_params = { 'identifier' : tile_id , 'startDate' : start_date , 'completionDate' : end_date , 'orbitNumber' : absolute_orbit , 'box' : bbox } return { key : str ( value ) for key , value in url_params . items ( ) if value } | Constructs dict with URL params |
35,248 | def _edit_name ( name , code , add_code = None , delete_end = False ) : info = name . split ( '_' ) info [ 2 ] = code if add_code is not None : info [ 3 ] = add_code if delete_end : info . pop ( ) return '_' . join ( info ) | Helping function for creating file names in . SAFE format |
35,249 | def get_requests ( self ) : safe = self . get_safe_struct ( ) self . download_list = [ ] self . structure_recursion ( safe , self . parent_folder ) self . sort_download_list ( ) return self . download_list , self . folder_list | Creates product structure and returns list of files for download |
35,250 | def get_safe_struct ( self ) : safe = { } main_folder = self . get_main_folder ( ) safe [ main_folder ] = { } safe [ main_folder ] [ AwsConstants . AUX_DATA ] = { } safe [ main_folder ] [ AwsConstants . DATASTRIP ] = { } datastrip_list = self . get_datastrip_list ( ) for datastrip_folder , datastrip_url in datastrip_li... | Describes a structure inside tile folder of ESA product . SAFE structure |
35,251 | def get_tile_id ( self ) : tree = get_xml ( self . get_url ( AwsConstants . METADATA ) ) tile_id_tag = 'TILE_ID_2A' if self . data_source is DataSource . SENTINEL2_L2A and self . baseline <= '02.06' else 'TILE_ID' tile_id = tree [ 0 ] . find ( tile_id_tag ) . text if self . safe_type is not EsaSafeType . OLD_TYPE : inf... | Creates ESA tile ID |
35,252 | def _parse_shape_list ( shape_list , crs ) : if not isinstance ( shape_list , list ) : raise ValueError ( 'Splitter must be initialized with a list of shapes' ) return [ AreaSplitter . _parse_shape ( shape , crs ) for shape in shape_list ] | Checks if the given list of shapes is in correct format and parses geometry objects |
35,253 | def get_bbox_list ( self , crs = None , buffer = None , reduce_bbox_sizes = None ) : bbox_list = self . bbox_list if buffer : bbox_list = [ bbox . buffer ( buffer ) for bbox in bbox_list ] if reduce_bbox_sizes is None : reduce_bbox_sizes = self . reduce_bbox_sizes if reduce_bbox_sizes : bbox_list = self . _reduce_sizes... | Returns a list of bounding boxes that are the result of the split |
35,254 | def get_area_bbox ( self , crs = None ) : bbox_list = [ BBox ( shape . bounds , crs = self . crs ) for shape in self . shape_list ] area_minx = min ( [ bbox . lower_left [ 0 ] for bbox in bbox_list ] ) area_miny = min ( [ bbox . lower_left [ 1 ] for bbox in bbox_list ] ) area_maxx = max ( [ bbox . upper_right [ 0 ] for... | Returns a bounding box of the entire area |
35,255 | 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 . |
35,256 | def _reduce_sizes ( self , bbox_list ) : return [ BBox ( self . _intersection_area ( bbox ) . bounds , self . crs ) . transform ( bbox . crs ) for bbox in bbox_list ] | Reduces sizes of bounding boxes |
35,257 | def _parse_split_shape ( split_shape ) : if isinstance ( split_shape , int ) : return split_shape , split_shape if isinstance ( split_shape , ( tuple , list ) ) : if len ( split_shape ) == 2 and isinstance ( split_shape [ 0 ] , int ) and isinstance ( split_shape [ 1 ] , int ) : return split_shape [ 0 ] , split_shape [ ... | Parses the parameter split_shape |
35,258 | def _recursive_split ( self , bbox , zoom_level , column , row ) : if zoom_level == self . zoom_level : self . bbox_list . append ( bbox ) self . info_list . append ( { 'zoom_level' : zoom_level , 'index_x' : column , 'index_y' : row } ) return bbox_partition = bbox . get_partition ( 2 , 2 ) for i , j in itertools . pr... | Method that recursively creates bounding boxes of OSM grid that intersect the area . |
35,259 | def _parse_bbox_grid ( bbox_grid ) : if isinstance ( bbox_grid , BBoxCollection ) : return bbox_grid if isinstance ( bbox_grid , list ) : return BBoxCollection ( bbox_grid ) raise ValueError ( "Parameter 'bbox_grid' should be an instance of {}" . format ( BBoxCollection . __name__ ) ) | Helper method for parsing bounding box grid . It will try to parse it into BBoxCollection |
35,260 | def _parse_metafiles ( self , metafile_input ) : all_metafiles = AwsConstants . S2_L1C_METAFILES if self . data_source is DataSource . SENTINEL2_L1C else AwsConstants . S2_L2A_METAFILES if metafile_input is None : if self . __class__ . __name__ == 'SafeProduct' : return all_metafiles if self . __class__ . __name__ == '... | Parses class input and verifies metadata file names . |
35,261 | def get_base_url ( self , force_http = False ) : base_url = SHConfig ( ) . aws_metadata_url . rstrip ( '/' ) if force_http else 's3:/' aws_bucket = SHConfig ( ) . aws_s3_l1c_bucket if self . data_source is DataSource . SENTINEL2_L1C else SHConfig ( ) . aws_s3_l2a_bucket return '{}/{}/' . format ( base_url , aws_bucket ... | Creates base URL path |
35,262 | def get_safe_type ( self ) : product_type = self . product_id . split ( '_' ) [ 1 ] if product_type . startswith ( 'MSI' ) : return EsaSafeType . COMPACT_TYPE if product_type in [ 'OPER' , 'USER' ] : return EsaSafeType . OLD_TYPE raise ValueError ( 'Unrecognized product type of product id {}' . format ( self . product_... | Determines the type of ESA product . |
35,263 | def _read_baseline_from_info ( self ) : if hasattr ( self , 'tile_info' ) : return self . tile_info [ 'datastrip' ] [ 'id' ] [ - 5 : ] if hasattr ( self , 'product_info' ) : return self . product_info [ 'datastrips' ] [ 0 ] [ 'id' ] [ - 5 : ] raise ValueError ( 'No info file has been obtained yet.' ) | Tries to find and return baseline number from either tileInfo or productInfo file . |
35,264 | def url_to_tile ( url ) : info = url . strip ( '/' ) . split ( '/' ) name = '' . join ( info [ - 7 : - 4 ] ) date = '-' . join ( info [ - 4 : - 1 ] ) return name , date , int ( info [ - 1 ] ) | Extracts tile name date and AWS index from tile url on AWS . |
35,265 | def structure_recursion ( self , struct , folder ) : has_subfolder = False for name , substruct in struct . items ( ) : subfolder = os . path . join ( folder , name ) if not isinstance ( substruct , dict ) : product_name , data_name = self . _url_to_props ( substruct ) if '.' in data_name : data_type = MimeType ( data_... | 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 . |
35,266 | def add_file_extension ( filename , data_format = None , remove_path = False ) : if data_format is None : data_format = AwsConstants . AWS_FILES [ filename ] if remove_path : filename = filename . split ( '/' ) [ - 1 ] if filename . startswith ( 'datastrip' ) : filename = filename . replace ( '*' , '0' ) if data_format... | Joins filename and corresponding file extension if it has one . |
35,267 | 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 |
35,268 | def get_requests ( self ) : self . download_list = [ DownloadRequest ( url = self . get_url ( metafile ) , filename = self . get_filepath ( metafile ) , data_type = AwsConstants . AWS_FILES [ metafile ] , data_name = metafile ) for metafile in self . metafiles if metafile in AwsConstants . PRODUCT_FILES ] tile_parent_f... | Creates product structure and returns list of files for download . |
35,269 | def get_data_source ( self ) : product_type = self . product_id . split ( '_' ) [ 1 ] if product_type . endswith ( 'L1C' ) or product_type == 'OPER' : return DataSource . SENTINEL2_L1C if product_type . endswith ( 'L2A' ) or product_type == 'USER' : return DataSource . SENTINEL2_L2A raise ValueError ( 'Unknown data sou... | The method determines data source from product ID . |
35,270 | def get_date ( self ) : if self . safe_type == EsaSafeType . OLD_TYPE : name = self . product_id . split ( '_' ) [ - 2 ] date = [ name [ 1 : 5 ] , name [ 5 : 7 ] , name [ 7 : 9 ] ] else : name = self . product_id . split ( '_' ) [ 2 ] date = [ name [ : 4 ] , name [ 4 : 6 ] , name [ 6 : 8 ] ] return '-' . join ( date_pa... | Collects sensing date of the product . |
35,271 | def get_product_url ( self , force_http = False ) : base_url = self . base_http_url if force_http else self . base_url return '{}products/{}/{}' . format ( base_url , self . date . replace ( '-' , '/' ) , self . product_id ) | Creates base url of product location on AWS . |
35,272 | def parse_tile_name ( name ) : tile_name = name . lstrip ( 'T0' ) if len ( tile_name ) == 4 : tile_name = '0' + tile_name if len ( tile_name ) != 5 : raise ValueError ( 'Invalid tile name {}' . format ( name ) ) return tile_name | Parses and verifies tile name . |
35,273 | def get_requests ( self ) : self . download_list = [ ] for data_name in [ band for band in self . bands if self . _band_exists ( band ) ] + self . metafiles : if data_name in AwsConstants . TILE_FILES : url = self . get_url ( data_name ) filename = self . get_filepath ( data_name ) self . download_list . append ( Downl... | Creates tile structure and returns list of files for download . |
35,274 | def get_aws_index ( self ) : if self . aws_index is not None : return self . aws_index tile_info_list = get_tile_info ( self . tile_name , self . datetime , all_tiles = True ) if not tile_info_list : raise ValueError ( 'Cannot find aws_index for specified tile and time' ) if self . data_source is DataSource . SENTINEL2... | Returns tile index on AWS . If tile_index was not set during class initialization it will be determined according to existing tiles on AWS . |
35,275 | def tile_is_valid ( self ) : return self . tile_info is not None and ( self . datetime == self . date or self . datetime == self . parse_datetime ( self . tile_info [ 'timestamp' ] ) ) | Checks if tile has tile info and valid timestamp |
35,276 | def get_tile_url ( self , force_http = False ) : base_url = self . base_http_url if force_http else self . base_url url = '{}tiles/{}/{}/{}/' . format ( base_url , self . tile_name [ 0 : 2 ] . lstrip ( '0' ) , self . tile_name [ 2 ] , self . tile_name [ 3 : 5 ] ) date_params = self . date . split ( '-' ) for param in d... | Creates base url of tile location on AWS . |
35,277 | def split32 ( data ) : all_pieces = [ ] for position in range ( 0 , len ( data ) , 32 ) : piece = data [ position : position + 32 ] all_pieces . append ( piece ) return all_pieces | Split data into pieces of 32 bytes . |
35,278 | def _canonical_type ( name ) : 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 :... | Replace aliases to the corresponding type to compute the ids . |
35,279 | def method_id ( name , encode_types ) : function_types = [ _canonical_type ( type_ ) for type_ in encode_types ] function_signature = '{function_name}({canonical_types})' . format ( function_name = name , canonical_types = ',' . join ( function_types ) , ) function_keccak = utils . sha3 ( function_signature ) first_byt... | Return the unique method id . |
35,280 | def event_id ( name , encode_types ) : event_types = [ _canonical_type ( type_ ) for type_ in encode_types ] event_signature = '{event_name}({canonical_types})' . format ( event_name = name , canonical_types = ',' . join ( event_types ) , ) return big_endian_to_int ( utils . sha3 ( event_signature ) ) | Return the event id . |
35,281 | def encode_function_call ( self , function_name , args ) : if function_name not in self . function_data : raise ValueError ( 'Unkown function {}' . format ( function_name ) ) description = self . function_data [ function_name ] function_selector = zpad ( encode_int ( description [ 'prefix' ] ) , 4 ) arguments = encode_... | Return the encoded function call . |
35,282 | def decode_function_result ( self , function_name , data ) : description = self . function_data [ function_name ] arguments = decode_abi ( description [ 'decode_types' ] , data ) return arguments | Return the function call result decoded . |
35,283 | def encode_constructor_arguments ( self , args ) : if self . constructor_data is None : raise ValueError ( "The contract interface didn't have a constructor" ) return encode_abi ( self . constructor_data [ 'encode_types' ] , args ) | Return the encoded constructor call . |
35,284 | def decode_event ( self , log_topics , log_data ) : 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_ ] unindexed_types = [ type_ for type_ , indexed in zip ( event [ 'types' ] , event [ 'in... | Return a dictionary representation the log . |
35,285 | def listen ( self , log , noprint = True ) : try : result = self . decode_event ( log . topics , log . data ) except ValueError : return if not noprint : print ( result ) return result | Return a dictionary representation of the Log instance . |
35,286 | def unpack_to_nibbles ( bindata ) : o = bin_to_nibbles ( bindata ) flags = o [ 0 ] if flags & 2 : o . append ( NIBBLE_TERMINATOR ) if flags & 1 == 1 : o = o [ 1 : ] else : o = o [ 2 : ] return o | unpack packed binary data to nibbles |
35,287 | 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 |
35,288 | def _get_node_type ( self , node ) : if node == BLANK_NODE : return NODE_TYPE_BLANK if len ( node ) == 2 : nibbles = unpack_to_nibbles ( node [ 0 ] ) has_terminator = ( nibbles and nibbles [ - 1 ] == NIBBLE_TERMINATOR ) return NODE_TYPE_LEAF if has_terminator else NODE_TYPE_EXTENSION if len ( node ) == 17 : return NODE... | get node type and content |
35,289 | 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 : if not key : return node [ - 1 ] sub_node = self . _decode_to_node ( node [ key [ 0 ] ] ) return self . _get ( sub_node , key [ 1 : ] ) curr_key = without_te... | get value inside a node |
35,290 | def _normalize_branch_node ( self , node ) : 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 not_blank_index = [ i for i , item in enumerate ( node ) if item ] [ 0 ] if not_blank_index == 16 :... | node should have only one item changed |
35,291 | def DEBUG ( msg , * args , ** kwargs ) : logger = getLogger ( "DEBUG" ) if len ( logger . handlers ) == 0 : logger . addHandler ( StreamHandler ( ) ) logger . propagate = False logger . setLevel ( logging . DEBUG ) logger . DEV ( msg , * args , ** kwargs ) | temporary logger during development that is always on |
35,292 | def vm_trace ( ext , msg , compustate , opcode , pushcache , tracer = log_vm_op ) : 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' , 'SHA... | 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 |
35,293 | def sign ( self , key , network_id = None ) : 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'' ... | Sign this transaction with a private key . |
35,294 | 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 ) | returns the address of a contract created by this tx |
35,295 | def check_pow ( block_number , header_hash , mixhash , nonce , difficulty ) : log . debug ( 'checking pow' , block_number = block_number ) if len ( mixhash ) != 32 or len ( header_hash ) != 32 or len ( nonce ) != 8 : return False cache = get_cache ( block_number ) mining_output = hashimoto_light ( block_number , cache ... | Check if the proof - of - work of the block is valid . |
35,296 | def to_dict ( self ) : 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 i... | Serialize the header to a readable dictionary . |
35,297 | 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" ) return big_endian_to_int ( v ) | decodes and integer from serialization |
35,298 | 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 ( v ) | encodes an integer into serialization |
35,299 | 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 . decode ( 'ascii' ) except BaseException : return 'NON_PRINTABLE' return x local = { 'call_number' : 0 } def inner ( f ) : @ wraps ( f ) def wrapper ( * args , ** kwarg... | utility function to facilitate debug it will print input args before function call and print return value after function call |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.