idx
int64
0
63k
question
stringlengths
61
4.03k
target
stringlengths
6
1.23k
36,000
def plot_silhouette ( clf , X , title = 'Silhouette Analysis' , metric = 'euclidean' , copy = True , ax = None , figsize = None , cmap = 'nipy_spectral' , title_fontsize = "large" , text_fontsize = "medium" ) : if copy : clf = clone ( clf ) cluster_labels = clf . fit_predict ( X ) n_clusters = len ( set ( cluster_label...
Plots silhouette analysis of clusters using fit_predict .
36,001
def _clone_and_score_clusterer ( clf , X , n_clusters ) : start = time . time ( ) clf = clone ( clf ) setattr ( clf , 'n_clusters' , n_clusters ) return clf . fit ( X ) . score ( X ) , time . time ( ) - start
Clones and scores clusterer instance .
36,002
def plot_learning_curve ( clf , X , y , title = 'Learning Curve' , cv = None , shuffle = False , random_state = None , train_sizes = None , n_jobs = 1 , scoring = None , ax = None , figsize = None , title_fontsize = "large" , text_fontsize = "medium" ) : if ax is None : fig , ax = plt . subplots ( 1 , 1 , figsize = fig...
Generates a plot of the train and test learning curves for a classifier .
36,003
def plot_calibration_curve ( y_true , probas_list , clf_names = None , n_bins = 10 , title = 'Calibration plots (Reliability Curves)' , ax = None , figsize = None , cmap = 'nipy_spectral' , title_fontsize = "large" , text_fontsize = "medium" ) : y_true = np . asarray ( y_true ) if not isinstance ( probas_list , list ) ...
Plots calibration curves for a set of classifier probability estimates .
36,004
def clustering_factory ( clf ) : required_methods = [ 'fit' , 'fit_predict' ] for method in required_methods : if not hasattr ( clf , method ) : raise TypeError ( '"{}" is not in clf. Did you ' 'pass a clusterer instance?' . format ( method ) ) additional_methods = { 'plot_silhouette' : plot_silhouette , 'plot_elbow_cu...
Embeds scikit - plot plotting methods in an sklearn clusterer instance .
36,005
def validate_labels ( known_classes , passed_labels , argument_name ) : known_classes = np . array ( known_classes ) passed_labels = np . array ( passed_labels ) unique_labels , unique_indexes = np . unique ( passed_labels , return_index = True ) if len ( passed_labels ) != len ( unique_labels ) : indexes = np . arange...
Validates the labels passed into the true_labels or pred_labels arguments in the plot_confusion_matrix function .
36,006
def cumulative_gain_curve ( y_true , y_score , pos_label = None ) : y_true , y_score = np . asarray ( y_true ) , np . asarray ( y_score ) classes = np . unique ( y_true ) if ( pos_label is None and not ( np . array_equal ( classes , [ 0 , 1 ] ) or np . array_equal ( classes , [ - 1 , 1 ] ) or np . array_equal ( classes...
This function generates the points necessary to plot the Cumulative Gain
36,007
def getargspec ( func ) : if inspect . ismethod ( func ) : func = func . __func__ parts = 0 , ( ) if type ( func ) is partial : keywords = func . keywords if keywords is None : keywords = { } parts = len ( func . args ) , keywords . keys ( ) func = func . func if not inspect . isfunction ( func ) : raise TypeError ( '%...
Used because getargspec for python 2 . 7 does not accept functools . partial which is the type for pytest fixtures .
36,008
def querystring ( self ) : return { key : value for ( key , value ) in self . qs . items ( ) if key . startswith ( self . MANAGED_KEYS ) or self . _get_key_values ( 'filter[' ) }
Return original querystring but containing only managed keys
36,009
def filters ( self ) : results = [ ] filters = self . qs . get ( 'filter' ) if filters is not None : try : results . extend ( json . loads ( filters ) ) except ( ValueError , TypeError ) : raise InvalidFilters ( "Parse error" ) if self . _get_key_values ( 'filter[' ) : results . extend ( self . _simple_filters ( self ....
Return filters from query string .
36,010
def pagination ( self ) : result = self . _get_key_values ( 'page' ) for key , value in result . items ( ) : if key not in ( 'number' , 'size' ) : raise BadRequest ( "{} is not a valid parameter of pagination" . format ( key ) , source = { 'parameter' : 'page' } ) try : int ( value ) except ValueError : raise BadReques...
Return all page parameters as a dict .
36,011
def fields ( self ) : result = self . _get_key_values ( 'fields' ) for key , value in result . items ( ) : if not isinstance ( value , list ) : result [ key ] = [ value ] for key , value in result . items ( ) : schema = get_schema_from_type ( key ) for obj in value : if obj not in schema . _declared_fields : raise Inva...
Return fields wanted by client .
36,012
def sorting ( self ) : if self . qs . get ( 'sort' ) : sorting_results = [ ] for sort_field in self . qs [ 'sort' ] . split ( ',' ) : field = sort_field . replace ( '-' , '' ) if field not in self . schema . _declared_fields : raise InvalidSort ( "{} has no attribute {}" . format ( self . schema . __name__ , field ) ) ...
Return fields to sort by including sort name for SQLAlchemy and row sort parameter for other ORMs
36,013
def include ( self ) : include_param = self . qs . get ( 'include' , [ ] ) if current_app . config . get ( 'MAX_INCLUDE_DEPTH' ) is not None : for include_path in include_param : if len ( include_path . split ( '.' ) ) > current_app . config [ 'MAX_INCLUDE_DEPTH' ] : raise InvalidInclude ( "You can't use include throug...
Return fields to include
36,014
def to_dict ( self ) : error_dict = { } for field in ( 'status' , 'source' , 'title' , 'detail' , 'id' , 'code' , 'links' , 'meta' ) : if getattr ( self , field , None ) : error_dict . update ( { field : getattr ( self , field ) } ) return error_dict
Return values of each fields of an jsonapi error
36,015
def dispatch_request ( self , * args , ** kwargs ) : method = getattr ( self , request . method . lower ( ) , None ) if method is None and request . method == 'HEAD' : method = getattr ( self , 'get' , None ) assert method is not None , 'Unimplemented method {}' . format ( request . method ) headers = { 'Content-Type' ...
Logic of how to handle a request
36,016
def get ( self , * args , ** kwargs ) : self . before_get ( args , kwargs ) qs = QSManager ( request . args , self . schema ) objects_count , objects = self . get_collection ( qs , kwargs ) schema_kwargs = getattr ( self , 'get_schema_kwargs' , dict ( ) ) schema_kwargs . update ( { 'many' : True } ) self . before_marsh...
Retrieve a collection of objects
36,017
def post ( self , * args , ** kwargs ) : json_data = request . get_json ( ) or { } qs = QSManager ( request . args , self . schema ) schema = compute_schema ( self . schema , getattr ( self , 'post_schema_kwargs' , dict ( ) ) , qs , qs . include ) try : data , errors = schema . load ( json_data ) except IncorrectTypeEr...
Create an object
36,018
def get ( self , * args , ** kwargs ) : self . before_get ( args , kwargs ) qs = QSManager ( request . args , self . schema ) obj = self . get_object ( kwargs , qs ) self . before_marshmallow ( args , kwargs ) schema = compute_schema ( self . schema , getattr ( self , 'get_schema_kwargs' , dict ( ) ) , qs , qs . includ...
Get object details
36,019
def patch ( self , * args , ** kwargs ) : json_data = request . get_json ( ) or { } qs = QSManager ( request . args , self . schema ) schema_kwargs = getattr ( self , 'patch_schema_kwargs' , dict ( ) ) schema_kwargs . update ( { 'partial' : True } ) self . before_marshmallow ( args , kwargs ) schema = compute_schema ( ...
Update an object
36,020
def delete ( self , * args , ** kwargs ) : self . before_delete ( args , kwargs ) self . delete_object ( kwargs ) result = { 'meta' : { 'message' : 'Object successfully deleted' } } final_result = self . after_delete ( result ) return final_result
Delete an object
36,021
def get ( self , * args , ** kwargs ) : self . before_get ( args , kwargs ) relationship_field , model_relationship_field , related_type_ , related_id_field = self . _get_relationship_data ( ) obj , data = self . _data_layer . get_relationship ( model_relationship_field , related_type_ , related_id_field , kwargs ) res...
Get a relationship details
36,022
def patch ( self , * args , ** kwargs ) : json_data = request . get_json ( ) or { } relationship_field , model_relationship_field , related_type_ , related_id_field = self . _get_relationship_data ( ) if 'data' not in json_data : raise BadRequest ( 'You must provide data with a "data" route node' , source = { 'pointer'...
Update a relationship
36,023
def _get_relationship_data ( self ) : relationship_field = request . path . split ( '/' ) [ - 1 ] . replace ( '-' , '_' ) if relationship_field not in get_relationships ( self . schema ) : raise RelationNotFound ( "{} has no attribute {}" . format ( self . schema . __name__ , relationship_field ) ) related_type_ = self...
Get useful data for relationship management
36,024
def compute_schema ( schema_cls , default_kwargs , qs , include ) : schema_kwargs = default_kwargs schema_kwargs [ 'include_data' ] = tuple ( ) related_includes = { } if include : for include_path in include : field = include_path . split ( '.' ) [ 0 ] if field not in schema_cls . _declared_fields : raise InvalidInclud...
Compute a schema around compound documents and sparse fieldsets
36,025
def get_model_field ( schema , field ) : if schema . _declared_fields . get ( field ) is None : raise Exception ( "{} has no attribute {}" . format ( schema . __name__ , field ) ) if schema . _declared_fields [ field ] . attribute is not None : return schema . _declared_fields [ field ] . attribute return field
Get the model field of a schema field
36,026
def get_nested_fields ( schema , model_field = False ) : nested_fields = [ ] for ( key , value ) in schema . _declared_fields . items ( ) : if isinstance ( value , List ) and isinstance ( value . container , Nested ) : nested_fields . append ( key ) elif isinstance ( value , Nested ) : nested_fields . append ( key ) if...
Return nested fields of a schema to support a join
36,027
def get_relationships ( schema , model_field = False ) : relationships = [ key for ( key , value ) in schema . _declared_fields . items ( ) if isinstance ( value , Relationship ) ] if model_field is True : relationships = [ get_model_field ( schema , key ) for key in relationships ] return relationships
Return relationship fields of a schema
36,028
def get_schema_from_type ( resource_type ) : for cls_name , cls in class_registry . _registry . items ( ) : try : if cls [ 0 ] . opts . type_ == resource_type : return cls [ 0 ] except Exception : pass raise Exception ( "Couldn't find schema for type: {}" . format ( resource_type ) )
Retrieve a schema from the registry by his type
36,029
def get_schema_field ( schema , field ) : schema_fields_to_model = { key : get_model_field ( schema , key ) for ( key , value ) in schema . _declared_fields . items ( ) } for key , value in schema_fields_to_model . items ( ) : if value == field : return key raise Exception ( "Couldn't find schema field from {}" . forma...
Get the schema field of a model field
36,030
def bound_rewritable_methods ( self , methods ) : for key , value in methods . items ( ) : if key in self . REWRITABLE_METHODS : setattr ( self , key , types . MethodType ( value , self ) )
Bound additional methods to current instance
36,031
def create_filters ( model , filter_info , resource ) : filters = [ ] for filter_ in filter_info : filters . append ( Node ( model , filter_ , resource , resource . schema ) . resolve ( ) ) return filters
Apply filters from filters information to base query
36,032
def resolve ( self ) : if 'or' not in self . filter_ and 'and' not in self . filter_ and 'not' not in self . filter_ : value = self . value if isinstance ( value , dict ) : value = Node ( self . related_model , value , self . resource , self . related_schema ) . resolve ( ) if '__' in self . filter_ . get ( 'name' , ''...
Create filter for a particular node of the filter tree
36,033
def name ( self ) : name = self . filter_ . get ( 'name' ) if name is None : raise InvalidFilters ( "Can't find name of a filter" ) if '__' in name : name = name . split ( '__' ) [ 0 ] if name not in self . schema . _declared_fields : raise InvalidFilters ( "{} has no attribute {}" . format ( self . schema . __name__ ,...
Return the name of the node or raise a BadRequest exception
36,034
def column ( self ) : field = self . name model_field = get_model_field ( self . schema , field ) try : return getattr ( self . model , model_field ) except AttributeError : raise InvalidFilters ( "{} has no attribute {}" . format ( self . model . __name__ , model_field ) )
Get the column object
36,035
def operator ( self ) : operators = ( self . op , self . op + '_' , '__' + self . op + '__' ) for op in operators : if hasattr ( self . column , op ) : return op raise InvalidFilters ( "{} has no operator {}" . format ( self . column . key , self . op ) )
Get the function operator from his name
36,036
def value ( self ) : if self . filter_ . get ( 'field' ) is not None : try : result = getattr ( self . model , self . filter_ [ 'field' ] ) except AttributeError : raise InvalidFilters ( "{} has no attribute {}" . format ( self . model . __name__ , self . filter_ [ 'field' ] ) ) else : return result else : if 'val' not...
Get the value to filter on
36,037
def related_model ( self ) : relationship_field = self . name if relationship_field not in get_relationships ( self . schema ) : raise InvalidFilters ( "{} has no relationship attribute {}" . format ( self . schema . __name__ , relationship_field ) ) return getattr ( self . model , get_model_field ( self . schema , rel...
Get the related model of a relationship field
36,038
def related_schema ( self ) : relationship_field = self . name if relationship_field not in get_relationships ( self . schema ) : raise InvalidFilters ( "{} has no relationship attribute {}" . format ( self . schema . __name__ , relationship_field ) ) return self . schema . _declared_fields [ relationship_field ] . sch...
Get the related schema of a relationship field
36,039
def init_app ( self , app = None , blueprint = None , additional_blueprints = None ) : if app is not None : self . app = app if blueprint is not None : self . blueprint = blueprint for resource in self . resources : self . route ( resource [ 'resource' ] , resource [ 'view' ] , * resource [ 'urls' ] , url_rule_options ...
Update flask application with our api
36,040
def route ( self , resource , view , * urls , ** kwargs ) : resource . view = view url_rule_options = kwargs . get ( 'url_rule_options' ) or dict ( ) view_func = resource . as_view ( view ) if 'blueprint' in kwargs : resource . view = '.' . join ( [ kwargs [ 'blueprint' ] . name , resource . view ] ) for url in urls : ...
Create an api view .
36,041
def oauth_manager ( self , oauth_manager ) : @ self . app . before_request def before_request ( ) : endpoint = request . endpoint resource = self . app . view_functions [ endpoint ] . view_class if not getattr ( resource , 'disable_oauth' ) : scopes = request . args . get ( 'scopes' ) if getattr ( resource , 'schema' )...
Use the oauth manager to enable oauth for API
36,042
def build_scope ( resource , method ) : if ResourceList in inspect . getmro ( resource ) and method == 'GET' : prefix = 'list' else : method_to_prefix = { 'GET' : 'get' , 'POST' : 'create' , 'PATCH' : 'update' , 'DELETE' : 'delete' } prefix = method_to_prefix [ method ] if ResourceRelationship in inspect . getmro ( res...
Compute the name of the scope for oauth
36,043
def permission_manager ( self , permission_manager ) : self . check_permissions = permission_manager for resource in self . resource_registry : if getattr ( resource , 'disable_permission' , None ) is not True : for method in getattr ( resource , 'methods' , ( 'GET' , 'POST' , 'PATCH' , 'DELETE' ) ) : setattr ( resourc...
Use permission manager to enable permission for API
36,044
def has_permission ( self , * args , ** kwargs ) : def wrapper ( view ) : if getattr ( view , '_has_permissions_decorator' , False ) is True : return view @ wraps ( view ) @ jsonapi_exception_formatter def decorated ( * view_args , ** view_kwargs ) : self . check_permissions ( view , view_args , view_kwargs , * args , ...
Decorator used to check permissions before to call resource manager method
36,045
def check_headers ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : if request . method in ( 'POST' , 'PATCH' ) : if 'Content-Type' in request . headers and 'application/vnd.api+json' in request . headers [ 'Content-Type' ] and request . headers [ 'Content-Type' ] != 'application/vnd.api+json' : error = ...
Check headers according to jsonapi reference
36,046
def check_method_requirements ( func ) : @ wraps ( func ) def wrapper ( * args , ** kwargs ) : error_message = "You must provide {error_field} in {cls} to get access to the default {method} method" error_data = { 'cls' : args [ 0 ] . __class__ . __name__ , 'method' : request . method . lower ( ) } if request . method !...
Check methods requirements
36,047
def create_object ( self , data , view_kwargs ) : self . before_create_object ( data , view_kwargs ) relationship_fields = get_relationships ( self . resource . schema , model_field = True ) nested_fields = get_nested_fields ( self . resource . schema , model_field = True ) join_fields = relationship_fields + nested_fi...
Create an object through sqlalchemy
36,048
def get_object ( self , view_kwargs , qs = None ) : self . before_get_object ( view_kwargs ) id_field = getattr ( self , 'id_field' , inspect ( self . model ) . primary_key [ 0 ] . key ) try : filter_field = getattr ( self . model , id_field ) except Exception : raise Exception ( "{} has no attribute {}" . format ( sel...
Retrieve an object through sqlalchemy
36,049
def get_collection ( self , qs , view_kwargs ) : self . before_get_collection ( qs , view_kwargs ) query = self . query ( view_kwargs ) if qs . filters : query = self . filter_query ( query , qs . filters , self . model ) if qs . sorting : query = self . sort_query ( query , qs . sorting ) object_count = query . count ...
Retrieve a collection of objects through sqlalchemy
36,050
def update_object ( self , obj , data , view_kwargs ) : if obj is None : url_field = getattr ( self , 'url_field' , 'id' ) filter_value = view_kwargs [ url_field ] raise ObjectNotFound ( '{}: {} not found' . format ( self . model . __name__ , filter_value ) , source = { 'parameter' : url_field } ) self . before_update_...
Update an object through sqlalchemy
36,051
def delete_object ( self , obj , view_kwargs ) : if obj is None : url_field = getattr ( self , 'url_field' , 'id' ) filter_value = view_kwargs [ url_field ] raise ObjectNotFound ( '{}: {} not found' . format ( self . model . __name__ , filter_value ) , source = { 'parameter' : url_field } ) self . before_delete_object ...
Delete an object through sqlalchemy
36,052
def create_relationship ( self , json_data , relationship_field , related_id_field , view_kwargs ) : self . before_create_relationship ( json_data , relationship_field , related_id_field , view_kwargs ) obj = self . get_object ( view_kwargs ) if obj is None : url_field = getattr ( self , 'url_field' , 'id' ) filter_val...
Create a relationship
36,053
def get_relationship ( self , relationship_field , related_type_ , related_id_field , view_kwargs ) : self . before_get_relationship ( relationship_field , related_type_ , related_id_field , view_kwargs ) obj = self . get_object ( view_kwargs ) if obj is None : url_field = getattr ( self , 'url_field' , 'id' ) filter_v...
Get a relationship
36,054
def delete_relationship ( self , json_data , relationship_field , related_id_field , view_kwargs ) : self . before_delete_relationship ( json_data , relationship_field , related_id_field , view_kwargs ) obj = self . get_object ( view_kwargs ) if obj is None : url_field = getattr ( self , 'url_field' , 'id' ) filter_val...
Delete a relationship
36,055
def get_related_object ( self , related_model , related_id_field , obj ) : try : related_object = self . session . query ( related_model ) . filter ( getattr ( related_model , related_id_field ) == obj [ 'id' ] ) . one ( ) except NoResultFound : raise RelatedObjectNotFound ( "{}.{}: {} not found" . format ( related_mod...
Get a related object
36,056
def apply_relationships ( self , data , obj ) : relationships_to_apply = [ ] relationship_fields = get_relationships ( self . resource . schema , model_field = True ) for key , value in data . items ( ) : if key in relationship_fields : related_model = getattr ( obj . __class__ , key ) . property . mapper . class_ sche...
Apply relationship provided by data to obj
36,057
def filter_query ( self , query , filter_info , model ) : if filter_info : filters = create_filters ( model , filter_info , self . resource ) query = query . filter ( * filters ) return query
Filter query according to jsonapi 1 . 0
36,058
def sort_query ( self , query , sort_info ) : for sort_opt in sort_info : field = sort_opt [ 'field' ] if not hasattr ( self . model , field ) : raise InvalidSort ( "{} has no attribute {}" . format ( self . model . __name__ , field ) ) query = query . order_by ( getattr ( getattr ( self . model , field ) , sort_opt [ ...
Sort query according to jsonapi 1 . 0
36,059
def paginate_query ( self , query , paginate_info ) : if int ( paginate_info . get ( 'size' , 1 ) ) == 0 : return query page_size = int ( paginate_info . get ( 'size' , 0 ) ) or current_app . config [ 'PAGE_SIZE' ] query = query . limit ( page_size ) if paginate_info . get ( 'number' ) : query = query . offset ( ( int ...
Paginate query according to jsonapi 1 . 0
36,060
def eagerload_includes ( self , query , qs ) : for include in qs . include : joinload_object = None if '.' in include : current_schema = self . resource . schema for obj in include . split ( '.' ) : try : field = get_model_field ( current_schema , obj ) except Exception as e : raise InvalidInclude ( str ( e ) ) if join...
Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter
36,061
def retrieve_object_query ( self , view_kwargs , filter_field , filter_value ) : return self . session . query ( self . model ) . filter ( filter_field == filter_value )
Build query to retrieve object
36,062
def add_pagination_links ( data , object_count , querystring , base_url ) : links = { } all_qs_args = copy ( querystring . querystring ) links [ 'self' ] = base_url if all_qs_args : links [ 'self' ] += '?' + urlencode ( all_qs_args ) if querystring . pagination . get ( 'size' ) != '0' and object_count > 1 : page_size =...
Add pagination links to result
36,063
def idfn ( fixture_params : Iterable [ Any ] ) -> str : return ":" . join ( ( str ( item ) for item in fixture_params ) )
Function for pytest to produce uniform names for fixtures .
36,064
def get_fixtures_file_hash ( all_fixture_paths : Iterable [ str ] ) -> str : hasher = hashlib . md5 ( ) for fixture_path in sorted ( all_fixture_paths ) : with open ( fixture_path , 'rb' ) as fixture_file : hasher . update ( fixture_file . read ( ) ) return hasher . hexdigest ( )
Returns the MD5 hash of the fixture files . Used for cache busting .
36,065
def create_unsigned_transaction ( cls , * , nonce : int , gas_price : int , gas : int , to : Address , value : int , data : bytes ) -> 'BaseUnsignedTransaction' : raise NotImplementedError ( "Must be implemented by subclasses" )
Create an unsigned transaction .
36,066
def import_header ( self , header : BlockHeader ) -> Tuple [ Tuple [ BlockHeader , ... ] , Tuple [ BlockHeader , ... ] ] : new_canonical_headers = self . headerdb . persist_header ( header ) self . header = self . get_canonical_head ( ) return new_canonical_headers
Direct passthrough to headerdb
36,067
def from_parent ( cls , parent : 'BlockHeader' , gas_limit : int , difficulty : int , timestamp : int , coinbase : Address = ZERO_ADDRESS , nonce : bytes = None , extra_data : bytes = None , transaction_root : bytes = None , receipt_root : bytes = None ) -> 'BlockHeader' : header_kwargs = { 'parent_hash' : parent . has...
Initialize a new block header with the parent header as the block s parent hash .
36,068
def get_block_uncles ( self , uncles_hash : Hash32 ) -> List [ BlockHeader ] : validate_word ( uncles_hash , title = "Uncles Hash" ) if uncles_hash == EMPTY_UNCLE_HASH : return [ ] try : encoded_uncles = self . db [ uncles_hash ] except KeyError : raise HeaderNotFound ( "No uncles found for hash {0}" . format ( uncles_...
Returns an iterable of uncle headers specified by the given uncles_hash
36,069
def persist_block ( self , block : 'BaseBlock' ) -> Tuple [ Tuple [ Hash32 , ... ] , Tuple [ Hash32 , ... ] ] : with self . db . atomic_batch ( ) as db : return self . _persist_block ( db , block )
Persist the given block s header and uncles .
36,070
def persist_uncles ( self , uncles : Tuple [ BlockHeader ] ) -> Hash32 : return self . _persist_uncles ( self . db , uncles )
Persists the list of uncles to the database .
36,071
def add_receipt ( self , block_header : BlockHeader , index_key : int , receipt : Receipt ) -> Hash32 : receipt_db = HexaryTrie ( db = self . db , root_hash = block_header . receipt_root ) receipt_db [ index_key ] = rlp . encode ( receipt ) return receipt_db . root_hash
Adds the given receipt to the provided block header .
36,072
def add_transaction ( self , block_header : BlockHeader , index_key : int , transaction : 'BaseTransaction' ) -> Hash32 : transaction_db = HexaryTrie ( self . db , root_hash = block_header . transaction_root ) transaction_db [ index_key ] = rlp . encode ( transaction ) return transaction_db . root_hash
Adds the given transaction to the provided block header .
36,073
def get_block_transactions ( self , header : BlockHeader , transaction_class : Type [ 'BaseTransaction' ] ) -> Iterable [ 'BaseTransaction' ] : return self . _get_block_transactions ( header . transaction_root , transaction_class )
Returns an iterable of transactions for the block speficied by the given block header .
36,074
def get_block_transaction_hashes ( self , block_header : BlockHeader ) -> Iterable [ Hash32 ] : return self . _get_block_transaction_hashes ( self . db , block_header )
Returns an iterable of the transaction hashes from the block specified by the given block header .
36,075
def get_receipts ( self , header : BlockHeader , receipt_class : Type [ Receipt ] ) -> Iterable [ Receipt ] : receipt_db = HexaryTrie ( db = self . db , root_hash = header . receipt_root ) for receipt_idx in itertools . count ( ) : receipt_key = rlp . encode ( receipt_idx ) if receipt_key in receipt_db : receipt_data =...
Returns an iterable of receipts for the block specified by the given block header .
36,076
def get_transaction_by_index ( self , block_number : BlockNumber , transaction_index : int , transaction_class : Type [ 'BaseTransaction' ] ) -> 'BaseTransaction' : try : block_header = self . get_canonical_block_header_by_number ( block_number ) except HeaderNotFound : raise TransactionNotFound ( "Block {} is not in t...
Returns the transaction at the specified transaction_index from the block specified by block_number from the canonical chain .
36,077
def get_receipt_by_index ( self , block_number : BlockNumber , receipt_index : int ) -> Receipt : try : block_header = self . get_canonical_block_header_by_number ( block_number ) except HeaderNotFound : raise ReceiptNotFound ( "Block {} is not in the canonical chain" . format ( block_number ) ) receipt_db = HexaryTrie...
Returns the Receipt of the transaction at specified index for the block header obtained by the specified block number
36,078
def _get_block_transaction_data ( db : BaseDB , transaction_root : Hash32 ) -> Iterable [ Hash32 ] : transaction_db = HexaryTrie ( db , root_hash = transaction_root ) for transaction_idx in itertools . count ( ) : transaction_key = rlp . encode ( transaction_idx ) if transaction_key in transaction_db : yield transactio...
Returns iterable of the encoded transactions for the given block header
36,079
def _get_block_transactions ( self , transaction_root : Hash32 , transaction_class : Type [ 'BaseTransaction' ] ) -> Iterable [ 'BaseTransaction' ] : for encoded_transaction in self . _get_block_transaction_data ( self . db , transaction_root ) : yield rlp . decode ( encoded_transaction , sedes = transaction_class )
Memoizable version of get_block_transactions
36,080
def _remove_transaction_from_canonical_chain ( db : BaseDB , transaction_hash : Hash32 ) -> None : db . delete ( SchemaV1 . make_transaction_hash_to_block_lookup_key ( transaction_hash ) )
Removes the transaction specified by the given hash from the canonical chain .
36,081
def persist_trie_data_dict ( self , trie_data_dict : Dict [ Hash32 , bytes ] ) -> None : with self . db . atomic_batch ( ) as db : for key , value in trie_data_dict . items ( ) : db [ key ] = value
Store raw trie data to db from a dict
36,082
def from_header ( cls , header : BlockHeader , chaindb : BaseChainDB ) -> BaseBlock : if header . uncles_hash == EMPTY_UNCLE_HASH : uncles = [ ] else : uncles = chaindb . get_block_uncles ( header . uncles_hash ) transactions = chaindb . get_block_transactions ( header , cls . get_transaction_class ( ) ) return cls ( h...
Returns the block denoted by the given block header .
36,083
def shl ( computation : BaseComputation ) -> None : shift_length , value = computation . stack_pop ( num_items = 2 , type_hint = constants . UINT256 ) if shift_length >= 256 : result = 0 else : result = ( value << shift_length ) & constants . UINT_256_MAX computation . stack_push ( result )
Bitwise left shift
36,084
def sar ( computation : BaseComputation ) -> None : shift_length , value = computation . stack_pop ( num_items = 2 , type_hint = constants . UINT256 ) value = unsigned_to_signed ( value ) if shift_length >= 256 : result = 0 if value >= 0 else constants . UINT_255_NEGATIVE_ONE else : result = ( value >> shift_length ) &...
Arithmetic bitwise right shift
36,085
def compute_frontier_difficulty ( parent_header : BlockHeader , timestamp : int ) -> int : validate_gt ( timestamp , parent_header . timestamp , title = "Header timestamp" ) offset = parent_header . difficulty // DIFFICULTY_ADJUSTMENT_DENOMINATOR difficulty_minimum = min ( parent_header . difficulty , DIFFICULTY_MINIMU...
Computes the difficulty for a frontier block based on the parent block .
36,086
def build_computation ( self , message : Message , transaction : BaseOrSpoofTransaction ) -> BaseComputation : transaction_context = self . vm_state . get_transaction_context ( transaction ) if message . is_create : is_collision = self . vm_state . has_code_or_nonce ( message . storage_address ) if is_collision : compu...
Apply the message to the VM .
36,087
def push ( self , value : Union [ int , bytes ] ) -> None : if len ( self . values ) > 1023 : raise FullStack ( 'Stack limit reached' ) validate_stack_item ( value ) self . values . append ( value )
Push an item onto the stack .
36,088
def pop ( self , num_items : int , type_hint : str ) -> Union [ int , bytes , Tuple [ Union [ int , bytes ] , ... ] ] : try : if num_items == 1 : return next ( self . _pop ( num_items , type_hint ) ) else : return tuple ( self . _pop ( num_items , type_hint ) ) except IndexError : raise InsufficientStack ( "No stack it...
Pop an item off the stack .
36,089
def swap ( self , position : int ) -> None : idx = - 1 * position - 1 try : self . values [ - 1 ] , self . values [ idx ] = self . values [ idx ] , self . values [ - 1 ] except IndexError : raise InsufficientStack ( "Insufficient stack items for SWAP{0}" . format ( position ) )
Perform a SWAP operation on the stack .
36,090
def dup ( self , position : int ) -> None : idx = - 1 * position try : self . push ( self . values [ idx ] ) except IndexError : raise InsufficientStack ( "Insufficient stack items for DUP{0}" . format ( position ) )
Perform a DUP operation on the stack .
36,091
def get_canonical_block_hash ( self , block_number : BlockNumber ) -> Hash32 : return self . _get_canonical_block_hash ( self . db , block_number )
Returns the block hash for the canonical block at the given number .
36,092
def get_canonical_block_header_by_number ( self , block_number : BlockNumber ) -> BlockHeader : return self . _get_canonical_block_header_by_number ( self . db , block_number )
Returns the block header with the given number in the canonical chain .
36,093
def persist_header_chain ( self , headers : Iterable [ BlockHeader ] ) -> Tuple [ Tuple [ BlockHeader , ... ] , Tuple [ BlockHeader , ... ] ] : with self . db . atomic_batch ( ) as db : return self . _persist_header_chain ( db , headers )
Return two iterable of headers the first containing the new canonical headers the second containing the old canonical headers
36,094
def _set_as_canonical_chain_head ( cls , db : BaseDB , block_hash : Hash32 ) -> Tuple [ Tuple [ BlockHeader , ... ] , Tuple [ BlockHeader , ... ] ] : try : header = cls . _get_block_header_by_hash ( db , block_hash ) except HeaderNotFound : raise ValueError ( "Cannot use unknown block hash as canonical head: {}" . form...
Sets the canonical chain HEAD to the block header as specified by the given block hash .
36,095
def _add_block_number_to_hash_lookup ( db : BaseDB , header : BlockHeader ) -> None : block_number_to_hash_key = SchemaV1 . make_block_number_to_hash_lookup_key ( header . block_number ) db . set ( block_number_to_hash_key , rlp . encode ( header . hash , sedes = rlp . sedes . binary ) , )
Sets a record in the database to allow looking up this header by its block number .
36,096
def compute_gas_limit_bounds ( parent : BlockHeader ) -> Tuple [ int , int ] : boundary_range = parent . gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR upper_bound = parent . gas_limit + boundary_range lower_bound = max ( GAS_LIMIT_MINIMUM , parent . gas_limit - boundary_range ) return lower_bound , upper_bound
Compute the boundaries for the block gas limit based on the parent block .
36,097
def compute_gas_limit ( parent_header : BlockHeader , gas_limit_floor : int ) -> int : if gas_limit_floor < GAS_LIMIT_MINIMUM : raise ValueError ( "The `gas_limit_floor` value must be greater than the " "GAS_LIMIT_MINIMUM. Got {0}. Must be greater than " "{1}" . format ( gas_limit_floor , GAS_LIMIT_MINIMUM ) ) decay ...
A simple strategy for adjusting the gas limit .
36,098
def generate_header_from_parent_header ( compute_difficulty_fn : Callable [ [ BlockHeader , int ] , int ] , parent_header : BlockHeader , coinbase : Address , timestamp : Optional [ int ] = None , extra_data : bytes = b'' ) -> BlockHeader : if timestamp is None : timestamp = max ( int ( time . time ( ) ) , parent_heade...
Generate BlockHeader from state_root and parent_header
36,099
def state_definition_to_dict ( state_definition : GeneralState ) -> AccountState : if isinstance ( state_definition , Mapping ) : state_dict = state_definition elif isinstance ( state_definition , Iterable ) : state_dicts = [ assoc_in ( { } , state_item [ : - 1 ] , state_item [ - 1 ] ) if not isinstance ( state_item , ...
Convert a state definition to the canonical dict form .