INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Generates the Cumulative Gains Plot from labels and scores/probabilities The cumulative gains chart is used to determine the effectiveness of a binary classifier. A detailed explanation can be found at http://mlwiki.org/index.php/Cumulative_Gain_Chart. The implementation here works only for binary clas...
def plot_cumulative_gain(y_true, y_probas, title='Cumulative Gains Curve', ax=None, figsize=None, title_fontsize="large", text_fontsize="medium"): """Generates the Cumulative Gains Plot from labels and scores/probabilities The cumulative gains chart is used to ...
Embeds scikit-plot plotting methods in an sklearn clusterer instance. Args: clf: Scikit-learn clusterer instance Returns: The same scikit-learn clusterer instance passed in **clf** with embedded scikit-plot instance methods. Raises: ValueError: If **clf** does not contain ...
def clustering_factory(clf): """Embeds scikit-plot plotting methods in an sklearn clusterer instance. Args: clf: Scikit-learn clusterer instance Returns: The same scikit-learn clusterer instance passed in **clf** with embedded scikit-plot instance methods. Raises: Valu...
This function generates the points necessary to calculate the KS Statistic curve. Args: y_true (array-like, shape (n_samples)): True labels of the data. y_probas (array-like, shape (n_samples)): Probability predictions of the positive class. Returns: thresholds (numpy....
def binary_ks_curve(y_true, y_probas): """This function generates the points necessary to calculate the KS Statistic curve. Args: y_true (array-like, shape (n_samples)): True labels of the data. y_probas (array-like, shape (n_samples)): Probability predictions of the positive c...
Validates the labels passed into the true_labels or pred_labels arguments in the plot_confusion_matrix function. Raises a ValueError exception if any of the passed labels are not in the set of known classes or if there are duplicate labels. Otherwise returns None. Args: known_classes (arra...
def validate_labels(known_classes, passed_labels, argument_name): """Validates the labels passed into the true_labels or pred_labels arguments in the plot_confusion_matrix function. Raises a ValueError exception if any of the passed labels are not in the set of known classes or if there are duplicate l...
This function generates the points necessary to plot the Cumulative Gain Note: This implementation is restricted to the binary classification task. Args: y_true (array-like, shape (n_samples)): True labels of the data. y_score (array-like, shape (n_samples)): Target scores, can either be ...
def cumulative_gain_curve(y_true, y_score, pos_label=None): """This function generates the points necessary to plot the Cumulative Gain Note: This implementation is restricted to the binary classification task. Args: y_true (array-like, shape (n_samples)): True labels of the data. y_score...
>>> get_allure_suites('Suite1.Test') [Label(name='suite', value='Suite1')] >>> get_allure_suites('Suite1.Suite2.Test') # doctest: +NORMALIZE_WHITESPACE [Label(name='suite', value='Suite1'), Label(name='subSuite', value='Suite2')] >>> get_allure_suites('Suite1.Suite2.Suite3.Test') # doctest: +NORMALIZE_W...
def get_allure_suites(longname): """ >>> get_allure_suites('Suite1.Test') [Label(name='suite', value='Suite1')] >>> get_allure_suites('Suite1.Suite2.Test') # doctest: +NORMALIZE_WHITESPACE [Label(name='suite', value='Suite1'), Label(name='subSuite', value='Suite2')] >>> get_allure_suites('Suite1...
Used because getargspec for python 2.7 does not accept functools.partial which is the type for pytest fixtures. getargspec excerpted from: sphinx.util.inspect ~~~~~~~~~~~~~~~~~~~ Helpers for inspecting Python modules. :copyright: Copyright 2007-2018 by the Sphinx team, see AUTHORS. :licens...
def getargspec(func): """ Used because getargspec for python 2.7 does not accept functools.partial which is the type for pytest fixtures. getargspec excerpted from: sphinx.util.inspect ~~~~~~~~~~~~~~~~~~~ Helpers for inspecting Python modules. :copyright: Copyright 2007-2018 by the Sph...
>>> represent(None) 'None' >>> represent(123) '123' >>> import six >>> expected = u"'hi'" if six.PY2 else "'hi'" >>> represent('hi') == expected True >>> expected = u"'привет'" if six.PY2 else "'привет'" >>> represent(u'привет') == expected True >>> represent(bytearray([0...
def represent(item): """ >>> represent(None) 'None' >>> represent(123) '123' >>> import six >>> expected = u"'hi'" if six.PY2 else "'hi'" >>> represent('hi') == expected True >>> expected = u"'привет'" if six.PY2 else "'привет'" >>> represent(u'привет') == expected Tru...
>>> def helper(func): ... def wrapper(*args, **kwargs): ... params = func_parameters(func, *args, **kwargs) ... print(list(params.items())) ... return func(*args, **kwargs) ... return wrapper >>> @helper ... def args(a, b): ... pass >>> args(1, 2...
def func_parameters(func, *args, **kwargs): """ >>> def helper(func): ... def wrapper(*args, **kwargs): ... params = func_parameters(func, *args, **kwargs) ... print(list(params.items())) ... return func(*args, **kwargs) ... return wrapper >>> @helper ...
Return a dict containing key / values items for a given key, used for items like filters, page, etc. :param str name: name of the querystring parameter :return dict: a dict of key / values items
def _get_key_values(self, name): """Return a dict containing key / values items for a given key, used for items like filters, page, etc. :param str name: name of the querystring parameter :return dict: a dict of key / values items """ results = {} for key, value in self...
Return filters from query string. :return list: filter information
def filters(self): """Return filters from query string. :return list: filter information """ results = [] filters = self.qs.get('filter') if filters is not None: try: results.extend(json.loads(filters)) except (ValueError, TypeErro...
Return original querystring but containing only managed keys :return dict: dict of managed querystring parameter
def querystring(self): """Return original querystring but containing only managed keys :return dict: dict of managed querystring parameter """ return {key: value for (key, value) in self.qs.items() if key.startswith(self.MANAGED_KEYS) or self._get_key_values('filter[')}
Return all page parameters as a dict. :return dict: a dict of pagination information To allow multiples strategies, all parameters starting with `page` will be included. e.g:: { "number": '25', "size": '150', } Example with number strat...
def pagination(self): """Return all page parameters as a dict. :return dict: a dict of pagination information To allow multiples strategies, all parameters starting with `page` will be included. e.g:: { "number": '25', "size": '150', } ...
Return fields wanted by client. :return dict: a dict of sparse fieldsets information Return value will be a dict containing all fields by resource, for example:: { "user": ['name', 'email'], }
def fields(self): """Return fields wanted by client. :return dict: a dict of sparse fieldsets information Return value will be a dict containing all fields by resource, for example:: { "user": ['name', 'email'], } """ result = self._get...
Return fields to sort by including sort name for SQLAlchemy and row sort parameter for other ORMs :return list: a list of sorting information Example of return value:: [ {'field': 'created_at', 'order': 'desc'}, ]
def sorting(self): """Return fields to sort by including sort name for SQLAlchemy and row sort parameter for other ORMs :return list: a list of sorting information Example of return value:: [ {'field': 'created_at', 'order': 'desc'}, ] ...
Return fields to include :return list: a list of include information
def include(self): """Return fields to include :return list: a list of include information """ 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_pa...
Return values of each fields of an jsonapi error
def to_dict(self): """Return values of each fields of an jsonapi error""" 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)}) retu...
Logic of how to handle a request
def dispatch_request(self, *args, **kwargs): """Logic of how to handle a request""" 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 {}'.fo...
Retrieve a collection of objects
def get(self, *args, **kwargs): """Retrieve a collection of objects""" 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_kwa...
Create an object
def post(self, *args, **kwargs): """Create an object""" json_data = request.get_json() or {} qs = QSManager(request.args, self.schema) schema = compute_schema(self.schema, getattr(self, 'post_schema_kwargs', dict()), qs, ...
Get object details
def get(self, *args, **kwargs): """Get object details""" 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, ...
Update an object
def patch(self, *args, **kwargs): """Update an object""" 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, kwa...
Delete an object
def delete(self, *args, **kwargs): """Delete an object""" self.before_delete(args, kwargs) self.delete_object(kwargs) result = {'meta': {'message': 'Object successfully deleted'}} final_result = self.after_delete(result) return final_result
Get a relationship details
def get(self, *args, **kwargs): """Get a relationship details""" 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, ...
Add / create relationship(s)
def post(self, *args, **kwargs): """Add / create relationship(s)""" 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 prov...
Update a relationship
def patch(self, *args, **kwargs): """Update a relationship""" 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 da...
Delete relationship(s)
def delete(self, *args, **kwargs): """Delete relationship(s)""" 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 ...
Get useful data for relationship management
def _get_relationship_data(self): """Get useful data for relationship management""" relationship_field = request.path.split('/')[-1].replace('-', '_') if relationship_field not in get_relationships(self.schema): raise RelationNotFound("{} has no attribute {}".format(self.schema.__na...
Compute a schema around compound documents and sparse fieldsets :param Schema schema_cls: the schema class :param dict default_kwargs: the schema default kwargs :param QueryStringManager qs: qs :param list include: the relation field to include data from :return Schema schema: the schema computed
def compute_schema(schema_cls, default_kwargs, qs, include): """Compute a schema around compound documents and sparse fieldsets :param Schema schema_cls: the schema class :param dict default_kwargs: the schema default kwargs :param QueryStringManager qs: qs :param list include: the relation field t...
Get the model field of a schema field :param Schema schema: a marshmallow schema :param str field: the name of the schema field :return str: the name of the field in the model
def get_model_field(schema, field): """Get the model field of a schema field :param Schema schema: a marshmallow schema :param str field: the name of the schema field :return str: the name of the field in the model """ if schema._declared_fields.get(field) is None: raise Exception("{} h...
Return nested fields of a schema to support a join :param Schema schema: a marshmallow schema :param boolean model_field: whether to extract the model field for the nested fields :return list: list of nested fields of the schema
def get_nested_fields(schema, model_field=False): """Return nested fields of a schema to support a join :param Schema schema: a marshmallow schema :param boolean model_field: whether to extract the model field for the nested fields :return list: list of nested fields of the schema """ nested_f...
Return relationship fields of a schema :param Schema schema: a marshmallow schema :param list: list of relationship fields of a schema
def get_relationships(schema, model_field=False): """Return relationship fields of a schema :param Schema schema: a marshmallow schema :param list: list of relationship fields of a schema """ relationships = [key for (key, value) in schema._declared_fields.items() if isinstance(value, Relationship)...
Retrieve a schema from the registry by his type :param str type_: the type of the resource :return Schema: the schema class
def get_schema_from_type(resource_type): """Retrieve a schema from the registry by his type :param str type_: the type of the resource :return Schema: the schema class """ for cls_name, cls in class_registry._registry.items(): try: if cls[0].opts.type_ == resource_type: ...
Get the schema field of a model field :param Schema schema: a marshmallow schema :param str field: the name of the model field :return str: the name of the field in the schema
def get_schema_field(schema, field): """Get the schema field of a model field :param Schema schema: a marshmallow schema :param str field: the name of the model field :return str: the name of the field in the schema """ schema_fields_to_model = {key: get_model_field(schema, key) for (key, value...
Bound additional methods to current instance :param class meta: information from Meta class used to configure the data layer instance
def bound_rewritable_methods(self, methods): """Bound additional methods to current instance :param class meta: information from Meta class used to configure the data layer instance """ for key, value in methods.items(): if key in self.REWRITABLE_METHODS: set...
Apply filters from filters information to base query :param DeclarativeMeta model: the model of the node :param dict filter_info: current node filter information :param Resource resource: the resource
def create_filters(model, filter_info, resource): """Apply filters from filters information to base query :param DeclarativeMeta model: the model of the node :param dict filter_info: current node filter information :param Resource resource: the resource """ filters = [] for filter_ in filte...
Create filter for a particular node of the filter tree
def resolve(self): """Create filter for a particular node of the filter tree""" 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.re...
Return the name of the node or raise a BadRequest exception :return str: the name of the field to filter on
def name(self): """Return the name of the node or raise a BadRequest exception :return str: the name of the field to filter on """ name = self.filter_.get('name') if name is None: raise InvalidFilters("Can't find name of a filter") if '__' in name: ...
Get the column object :param DeclarativeMeta model: the model :param str field: the field :return InstrumentedAttribute: the column to filter on
def column(self): """Get the column object :param DeclarativeMeta model: the model :param str field: the field :return InstrumentedAttribute: the column to filter on """ field = self.name model_field = get_model_field(self.schema, field) try: ...
Get the function operator from his name :return callable: a callable to make operation on a column
def operator(self): """Get the function operator from his name :return callable: a callable to make operation on a column """ operators = (self.op, self.op + '_', '__' + self.op + '__') for op in operators: if hasattr(self.column, op): return op ...
Get the value to filter on :return: the value to filter on
def value(self): """Get the value to filter on :return: the value to filter on """ if self.filter_.get('field') is not None: try: result = getattr(self.model, self.filter_['field']) except AttributeError: raise InvalidFilters("{} h...
Get the related model of a relationship field :return DeclarativeMeta: the related model
def related_model(self): """Get the related model of a relationship field :return DeclarativeMeta: the related model """ relationship_field = self.name if relationship_field not in get_relationships(self.schema): raise InvalidFilters("{} has no relationship attribut...
Get the related schema of a relationship field :return Schema: the related schema
def related_schema(self): """Get the related schema of a relationship field :return Schema: the related schema """ relationship_field = self.name if relationship_field not in get_relationships(self.schema): raise InvalidFilters("{} has no relationship attribute {}"....
Update flask application with our api :param Application app: a flask application
def init_app(self, app=None, blueprint=None, additional_blueprints=None): """Update flask application with our api :param Application app: a flask application """ if app is not None: self.app = app if blueprint is not None: self.blueprint = blueprint ...
Create an api view. :param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource :param str view: the view name :param list urls: the urls of the view :param dict kwargs: additional options of the route
def route(self, resource, view, *urls, **kwargs): """Create an api view. :param Resource resource: a resource class inherited from flask_rest_jsonapi.resource.Resource :param str view: the view name :param list urls: the urls of the view :param dict kwargs: additional options of...
Use the oauth manager to enable oauth for API :param oauth_manager: the oauth manager
def oauth_manager(self, oauth_manager): """Use the oauth manager to enable oauth for API :param oauth_manager: the oauth manager """ @self.app.before_request def before_request(): endpoint = request.endpoint resource = self.app.view_functions[endpoint].vi...
Compute the name of the scope for oauth :param Resource resource: the resource manager :param str method: an http method :return str: the name of the scope
def build_scope(resource, method): """Compute the name of the scope for oauth :param Resource resource: the resource manager :param str method: an http method :return str: the name of the scope """ if ResourceList in inspect.getmro(resource) and method == 'GET': ...
Use permission manager to enable permission for API :param callable permission_manager: the permission manager
def permission_manager(self, permission_manager): """Use permission manager to enable permission for API :param callable permission_manager: the permission manager """ self.check_permissions = permission_manager for resource in self.resource_registry: if getattr(res...
Decorator used to check permissions before to call resource manager method
def has_permission(self, *args, **kwargs): """Decorator used to check permissions before to call resource manager method""" def wrapper(view): if getattr(view, '_has_permissions_decorator', False) is True: return view @wraps(view) @jsonapi_exception_f...
Check headers according to jsonapi reference :param callable func: the function to decorate :return callable: the wrapped function
def check_headers(func): """Check headers according to jsonapi reference :param callable func: the function to decorate :return callable: the wrapped function """ @wraps(func) def wrapper(*args, **kwargs): if request.method in ('POST', 'PATCH'): if 'Content-Type' in request....
Check methods requirements :param callable func: the function to decorate :return callable: the wrapped function
def check_method_requirements(func): """Check methods requirements :param callable func: the function to decorate :return callable: the wrapped function """ @wraps(func) def wrapper(*args, **kwargs): error_message = "You must provide {error_field} in {cls} to get access to the default {...
Retrieve an object through sqlalchemy :params dict view_kwargs: kwargs from the resource view :return DeclarativeMeta: an object from sqlalchemy
def get_object(self, view_kwargs, qs=None): """Retrieve an object through sqlalchemy :params dict view_kwargs: kwargs from the resource view :return DeclarativeMeta: an object from sqlalchemy """ self.before_get_object(view_kwargs) id_field = getattr(self, 'id_field', i...
Create an object through sqlalchemy :param dict data: the data validated by marshmallow :param dict view_kwargs: kwargs from the resource view :return DeclarativeMeta: an object from sqlalchemy
def create_object(self, data, view_kwargs): """Create an object through sqlalchemy :param dict data: the data validated by marshmallow :param dict view_kwargs: kwargs from the resource view :return DeclarativeMeta: an object from sqlalchemy """ self.before_create_object(...
Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a querystring manager to retrieve information from url :param dict view_kwargs: kwargs from the resource view :return tuple: the number of object and the list of objects
def get_collection(self, qs, view_kwargs): """Retrieve a collection of objects through sqlalchemy :param QueryStringManager qs: a querystring manager to retrieve information from url :param dict view_kwargs: kwargs from the resource view :return tuple: the number of object and the list ...
Update an object through sqlalchemy :param DeclarativeMeta obj: an object from sqlalchemy :param dict data: the data validated by marshmallow :param dict view_kwargs: kwargs from the resource view :return boolean: True if object have changed else False
def update_object(self, obj, data, view_kwargs): """Update an object through sqlalchemy :param DeclarativeMeta obj: an object from sqlalchemy :param dict data: the data validated by marshmallow :param dict view_kwargs: kwargs from the resource view :return boolean: True if objec...
Delete an object through sqlalchemy :param DeclarativeMeta item: an item from sqlalchemy :param dict view_kwargs: kwargs from the resource view
def delete_object(self, obj, view_kwargs): """Delete an object through sqlalchemy :param DeclarativeMeta item: an item from sqlalchemy :param dict view_kwargs: kwargs from the resource view """ if obj is None: url_field = getattr(self, 'url_field', 'id') ...
Create a relationship :param dict json_data: the request params :param str relationship_field: the model attribute used for relationship :param str related_id_field: the identifier field of the related model :param dict view_kwargs: kwargs from the resource view :return boolean:...
def create_relationship(self, json_data, relationship_field, related_id_field, view_kwargs): """Create a relationship :param dict json_data: the request params :param str relationship_field: the model attribute used for relationship :param str related_id_field: the identifier field of t...
Get a relationship :param str relationship_field: the model attribute used for relationship :param str related_type_: the related resource type :param str related_id_field: the identifier field of the related model :param dict view_kwargs: kwargs from the resource view :return t...
def get_relationship(self, relationship_field, related_type_, related_id_field, view_kwargs): """Get a relationship :param str relationship_field: the model attribute used for relationship :param str related_type_: the related resource type :param str related_id_field: the identifier fi...
Delete a relationship :param dict json_data: the request params :param str relationship_field: the model attribute used for relationship :param str related_id_field: the identifier field of the related model :param dict view_kwargs: kwargs from the resource view
def delete_relationship(self, json_data, relationship_field, related_id_field, view_kwargs): """Delete a relationship :param dict json_data: the request params :param str relationship_field: the model attribute used for relationship :param str related_id_field: the identifier field of t...
Get a related object :param Model related_model: an sqlalchemy model :param str related_id_field: the identifier field of the related model :param DeclarativeMeta obj: the sqlalchemy object to retrieve related objects from :return DeclarativeMeta: a related object
def get_related_object(self, related_model, related_id_field, obj): """Get a related object :param Model related_model: an sqlalchemy model :param str related_id_field: the identifier field of the related model :param DeclarativeMeta obj: the sqlalchemy object to retrieve related object...
Apply relationship provided by data to obj :param dict data: data provided by the client :param DeclarativeMeta obj: the sqlalchemy object to plug relationships to :return boolean: True if relationship have changed else False
def apply_relationships(self, data, obj): """Apply relationship provided by data to obj :param dict data: data provided by the client :param DeclarativeMeta obj: the sqlalchemy object to plug relationships to :return boolean: True if relationship have changed else False """ ...
Filter query according to jsonapi 1.0 :param Query query: sqlalchemy query to sort :param filter_info: filter information :type filter_info: dict or None :param DeclarativeMeta model: an sqlalchemy model :return Query: the sorted query
def filter_query(self, query, filter_info, model): """Filter query according to jsonapi 1.0 :param Query query: sqlalchemy query to sort :param filter_info: filter information :type filter_info: dict or None :param DeclarativeMeta model: an sqlalchemy model :return Query...
Sort query according to jsonapi 1.0 :param Query query: sqlalchemy query to sort :param list sort_info: sort information :return Query: the sorted query
def sort_query(self, query, sort_info): """Sort query according to jsonapi 1.0 :param Query query: sqlalchemy query to sort :param list sort_info: sort information :return Query: the sorted query """ for sort_opt in sort_info: field = sort_opt['field'] ...
Paginate query according to jsonapi 1.0 :param Query query: sqlalchemy queryset :param dict paginate_info: pagination information :return Query: the paginated query
def paginate_query(self, query, paginate_info): """Paginate query according to jsonapi 1.0 :param Query query: sqlalchemy queryset :param dict paginate_info: pagination information :return Query: the paginated query """ if int(paginate_info.get('size', 1)) == 0: ...
Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter :param Query query: sqlalchemy queryset :param QueryStringManager qs: a querystring manager to retrieve information from url :return Query: the query with includes eagerloaded
def eagerload_includes(self, query, qs): """Use eagerload feature of sqlalchemy to optimize data retrieval for include querystring parameter :param Query query: sqlalchemy queryset :param QueryStringManager qs: a querystring manager to retrieve information from url :return Query: the qu...
Build query to retrieve object :param dict view_kwargs: kwargs from the resource view :params sqlalchemy_field filter_field: the field to filter on :params filter_value: the value to filter with :return sqlalchemy query: a query from sqlalchemy
def retrieve_object_query(self, view_kwargs, filter_field, filter_value): """Build query to retrieve object :param dict view_kwargs: kwargs from the resource view :params sqlalchemy_field filter_field: the field to filter on :params filter_value: the value to filter with :return...
Add pagination links to result :param dict data: the result of the view :param int object_count: number of objects in result :param QueryStringManager querystring: the managed querystring fields and values :param str base_url: the base url for pagination
def add_pagination_links(data, object_count, querystring, base_url): """Add pagination links to result :param dict data: the result of the view :param int object_count: number of objects in result :param QueryStringManager querystring: the managed querystring fields and values :param str base_url: ...
Create and return a transaction sending amount from <from_> to <to>. The transaction will be signed with the given private key.
def new_transaction( vm: VM, from_: Address, to: Address, amount: int=0, private_key: PrivateKey=None, gas_price: int=10, gas: int=100000, data: bytes=b'') -> BaseTransaction: """ Create and return a transaction sending amount from <from_> to <to>....
Function for pytest to produce uniform names for fixtures.
def idfn(fixture_params: Iterable[Any]) -> str: """ Function for pytest to produce uniform names for fixtures. """ return ":".join((str(item) for item in fixture_params))
Returns the MD5 hash of the fixture files. Used for cache busting.
def get_fixtures_file_hash(all_fixture_paths: Iterable[str]) -> str: """ Returns the MD5 hash of the fixture files. Used for cache busting. """ hasher = hashlib.md5() for fixture_path in sorted(all_fixture_paths): with open(fixture_path, 'rb') as fixture_file: hasher.update(fixt...
Create an unsigned transaction.
def create_unsigned_transaction(cls, *, nonce: int, gas_price: int, gas: int, to: Address, value: int, ...
Initializes the chain from the genesis header.
def from_genesis_header(cls, base_db: BaseDB, genesis_header: BlockHeader) -> 'BaseHeaderChain': """ Initializes the chain from the genesis header. """ headerdb = cls.get_headerdb_class()(cast(BaseAtomicDB, base_db)) headerd...
Direct passthrough to `headerdb` Also updates the local `header` property to be the latest canonical head. Returns an iterable of headers representing the headers that are newly part of the canonical chain. - If the imported header is not part of the canonical chain then an ...
def import_header(self, header: BlockHeader ) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]: """ Direct passthrough to `headerdb` Also updates the local `header` property to be the latest canonical head. Returns an iterable of he...
Initialize a new block header with the `parent` header as the block's parent hash.
def from_parent(cls, parent: 'BlockHeader', gas_limit: int, difficulty: int, timestamp: int, coinbase: Address=ZERO_ADDRESS, nonce: bytes=None, extra_data: bytes=None, ...
Persist the given block's header and uncles. Assumes all block transactions have been persisted already.
def persist_block(self, block: 'BaseBlock' ) -> Tuple[Tuple[Hash32, ...], Tuple[Hash32, ...]]: """ Persist the given block's header and uncles. Assumes all block transactions have been persisted already. """ with self.db.atomic_batch()...
Returns an iterable of uncle headers specified by the given uncles_hash
def get_block_uncles(self, uncles_hash: Hash32) -> List[BlockHeader]: """ Returns an iterable of uncle headers specified by the given uncles_hash """ validate_word(uncles_hash, title="Uncles Hash") if uncles_hash == EMPTY_UNCLE_HASH: return [] try: ...
Persists the list of uncles to the database. Returns the uncles hash.
def persist_uncles(self, uncles: Tuple[BlockHeader]) -> Hash32: """ Persists the list of uncles to the database. Returns the uncles hash. """ return self._persist_uncles(self.db, uncles)
Adds the given receipt to the provided block header. Returns the updated `receipts_root` for updated block header.
def add_receipt(self, block_header: BlockHeader, index_key: int, receipt: Receipt) -> Hash32: """ Adds the given receipt to the provided block header. Returns the updated `receipts_root` for updated block header. """ receipt_db = HexaryTrie(db=self.db, root_hash=block_header.rec...
Adds the given transaction to the provided block header. Returns the updated `transactions_root` for updated block header.
def add_transaction(self, block_header: BlockHeader, index_key: int, transaction: 'BaseTransaction') -> Hash32: """ Adds the given transaction to the provided block header. Returns the updated `transactions_root` for update...
Returns an iterable of transactions for the block speficied by the given block header.
def get_block_transactions( self, header: BlockHeader, transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']: """ Returns an iterable of transactions for the block speficied by the given block header. """ return self._get_b...
Returns an iterable of the transaction hashes from the block specified by the given block header.
def get_block_transaction_hashes(self, block_header: BlockHeader) -> Iterable[Hash32]: """ Returns an iterable of the transaction hashes from the block specified by the given block header. """ return self._get_block_transaction_hashes(self.db, block_header)
Returns an iterable of receipts for the block specified by the given block header.
def get_receipts(self, header: BlockHeader, receipt_class: Type[Receipt]) -> Iterable[Receipt]: """ Returns an iterable of receipts for the block specified by the given block header. """ receipt_db = HexaryTrie(db=self.db, root_hash=heade...
Returns the transaction at the specified `transaction_index` from the block specified by `block_number` from the canonical chain. Raises TransactionNotFound if no block
def get_transaction_by_index( self, block_number: BlockNumber, transaction_index: int, transaction_class: Type['BaseTransaction']) -> 'BaseTransaction': """ Returns the transaction at the specified `transaction_index` from the block specified by `b...
Returns a 2-tuple of (block_number, transaction_index) indicating which block the given transaction can be found in and at what index in the block transactions. Raises TransactionNotFound if the transaction_hash is not found in the canonical chain.
def get_transaction_index(self, transaction_hash: Hash32) -> Tuple[BlockNumber, int]: """ Returns a 2-tuple of (block_number, transaction_index) indicating which block the given transaction can be found in and at what index in the block transactions. Raises TransactionNotFound i...
Returns the Receipt of the transaction at specified index for the block header obtained by the specified block number
def get_receipt_by_index(self, block_number: BlockNumber, receipt_index: int) -> Receipt: """ Returns the Receipt of the transaction at specified index for the block header obtained by the specified block number """ try: ...
Returns iterable of the encoded transactions for the given block header
def _get_block_transaction_data(db: BaseDB, transaction_root: Hash32) -> Iterable[Hash32]: """ Returns iterable of the encoded transactions for the given block header """ transaction_db = HexaryTrie(db, root_hash=transaction_root) for transaction_idx in itertools.count(): ...
Memoizable version of `get_block_transactions`
def _get_block_transactions( self, transaction_root: Hash32, transaction_class: Type['BaseTransaction']) -> Iterable['BaseTransaction']: """ Memoizable version of `get_block_transactions` """ for encoded_transaction in self._get_block_transaction_data(...
Removes the transaction specified by the given hash from the canonical chain.
def _remove_transaction_from_canonical_chain(db: BaseDB, transaction_hash: Hash32) -> None: """ Removes the transaction specified by the given hash from the canonical chain. """ db.delete(SchemaV1.make_transaction_hash_to_block_lookup_key(transaction_hash))
:param bytes transaction_hash: the hash of the transaction to add the lookup for :param block_header: The header of the block with the txn that is in the canonical chain :param int index: the position of the transaction in the block - add lookup from transaction hash to the block number and inde...
def _add_transaction_to_canonical_chain(db: BaseDB, transaction_hash: Hash32, block_header: BlockHeader, index: int) -> None: """ :param bytes transaction_hash: the hash of...
Store raw trie data to db from a dict
def persist_trie_data_dict(self, trie_data_dict: Dict[Hash32, bytes]) -> None: """ Store raw trie data to db from a dict """ with self.db.atomic_batch() as db: for key, value in trie_data_dict.items(): db[key] = value
Returns the block denoted by the given block header.
def from_header(cls, header: BlockHeader, chaindb: BaseChainDB) -> BaseBlock: """ Returns the block denoted by the given block header. """ if header.uncles_hash == EMPTY_UNCLE_HASH: uncles = [] # type: List[BlockHeader] else: uncles = chaindb.get_block_un...
Subtraction
def sub(computation: BaseComputation) -> None: """ Subtraction """ left, right = computation.stack_pop(num_items=2, type_hint=constants.UINT256) result = (left - right) & constants.UINT_256_MAX computation.stack_push(result)
Modulo
def mod(computation: BaseComputation) -> None: """ Modulo """ value, mod = computation.stack_pop(num_items=2, type_hint=constants.UINT256) if mod == 0: result = 0 else: result = value % mod computation.stack_push(result)
Signed Modulo
def smod(computation: BaseComputation) -> None: """ Signed Modulo """ value, mod = map( unsigned_to_signed, computation.stack_pop(num_items=2, type_hint=constants.UINT256), ) pos_or_neg = -1 if value < 0 else 1 if mod == 0: result = 0 else: result = (abs...
Modulo Multiplication
def mulmod(computation: BaseComputation) -> None: """ Modulo Multiplication """ left, right, mod = computation.stack_pop(num_items=3, type_hint=constants.UINT256) if mod == 0: result = 0 else: result = (left * right) % mod computation.stack_push(result)
Division
def div(computation: BaseComputation) -> None: """ Division """ numerator, denominator = computation.stack_pop(num_items=2, type_hint=constants.UINT256) if denominator == 0: result = 0 else: result = (numerator // denominator) & constants.UINT_256_MAX computation.stack_push...
Signed Division
def sdiv(computation: BaseComputation) -> None: """ Signed Division """ numerator, denominator = map( unsigned_to_signed, computation.stack_pop(num_items=2, type_hint=constants.UINT256), ) pos_or_neg = -1 if numerator * denominator < 0 else 1 if denominator == 0: re...
Exponentiation
def exp(computation: BaseComputation, gas_per_byte: int) -> None: """ Exponentiation """ base, exponent = computation.stack_pop(num_items=2, type_hint=constants.UINT256) bit_size = exponent.bit_length() byte_size = ceil8(bit_size) // 8 if exponent == 0: result = 1 elif base == ...
Signed Extend
def signextend(computation: BaseComputation) -> None: """ Signed Extend """ bits, value = computation.stack_pop(num_items=2, type_hint=constants.UINT256) if bits <= 31: testbit = bits * 8 + 7 sign_bit = (1 << testbit) if value & sign_bit: result = value | (consta...
Bitwise left shift
def shl(computation: BaseComputation) -> None: """ Bitwise left shift """ 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.sta...