_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q225400
SqlalchemyDataLayer.get_collection
train
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 ...
python
{ "resource": "" }
q225401
SqlalchemyDataLayer.update_object
train
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...
python
{ "resource": "" }
q225402
SqlalchemyDataLayer.delete_object
train
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') ...
python
{ "resource": "" }
q225403
SqlalchemyDataLayer.create_relationship
train
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...
python
{ "resource": "" }
q225404
SqlalchemyDataLayer.get_relationship
train
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...
python
{ "resource": "" }
q225405
SqlalchemyDataLayer.delete_relationship
train
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...
python
{ "resource": "" }
q225406
SqlalchemyDataLayer.get_related_object
train
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...
python
{ "resource": "" }
q225407
SqlalchemyDataLayer.apply_relationships
train
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 """ ...
python
{ "resource": "" }
q225408
SqlalchemyDataLayer.filter_query
train
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...
python
{ "resource": "" }
q225409
SqlalchemyDataLayer.sort_query
train
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'] ...
python
{ "resource": "" }
q225410
SqlalchemyDataLayer.paginate_query
train
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: ...
python
{ "resource": "" }
q225411
SqlalchemyDataLayer.eagerload_includes
train
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...
python
{ "resource": "" }
q225412
SqlalchemyDataLayer.retrieve_object_query
train
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...
python
{ "resource": "" }
q225413
add_pagination_links
train
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: ...
python
{ "resource": "" }
q225414
idfn
train
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))
python
{ "resource": "" }
q225415
get_fixtures_file_hash
train
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...
python
{ "resource": "" }
q225416
BaseTransaction.create_unsigned_transaction
train
def create_unsigned_transaction(cls, *, nonce: int, gas_price: int, gas: int, to: Address, value: int, ...
python
{ "resource": "" }
q225417
HeaderChain.import_header
train
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...
python
{ "resource": "" }
q225418
BlockHeader.from_parent
train
def from_parent(cls, parent: 'BlockHeader', gas_limit: int, difficulty: int, timestamp: int, coinbase: Address=ZERO_ADDRESS, nonce: bytes=None, extra_data: bytes=None, ...
python
{ "resource": "" }
q225419
ChainDB.get_block_uncles
train
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: ...
python
{ "resource": "" }
q225420
ChainDB.persist_block
train
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()...
python
{ "resource": "" }
q225421
ChainDB.persist_uncles
train
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)
python
{ "resource": "" }
q225422
ChainDB.add_receipt
train
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...
python
{ "resource": "" }
q225423
ChainDB.add_transaction
train
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...
python
{ "resource": "" }
q225424
ChainDB.get_block_transactions
train
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...
python
{ "resource": "" }
q225425
ChainDB.get_block_transaction_hashes
train
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)
python
{ "resource": "" }
q225426
ChainDB.get_receipts
train
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...
python
{ "resource": "" }
q225427
ChainDB.get_transaction_by_index
train
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...
python
{ "resource": "" }
q225428
ChainDB.get_receipt_by_index
train
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: ...
python
{ "resource": "" }
q225429
ChainDB._get_block_transaction_data
train
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(): ...
python
{ "resource": "" }
q225430
ChainDB._get_block_transactions
train
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(...
python
{ "resource": "" }
q225431
ChainDB._remove_transaction_from_canonical_chain
train
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))
python
{ "resource": "" }
q225432
ChainDB.persist_trie_data_dict
train
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
python
{ "resource": "" }
q225433
FrontierBlock.from_header
train
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...
python
{ "resource": "" }
q225434
shl
train
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...
python
{ "resource": "" }
q225435
sar
train
def sar(computation: BaseComputation) -> None: """ Arithmetic bitwise right shift """ 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...
python
{ "resource": "" }
q225436
compute_frontier_difficulty
train
def compute_frontier_difficulty(parent_header: BlockHeader, timestamp: int) -> int: """ Computes the difficulty for a frontier block based on the parent block. """ validate_gt(timestamp, parent_header.timestamp, title="Header timestamp") offset = parent_header.difficulty // DIFFICULTY_ADJUSTMENT_DE...
python
{ "resource": "" }
q225437
FrontierTransactionExecutor.build_computation
train
def build_computation(self, message: Message, transaction: BaseOrSpoofTransaction) -> BaseComputation: """Apply the message to the VM.""" transaction_context = self.vm_state.get_transaction_context(transaction) if message.is_create: ...
python
{ "resource": "" }
q225438
Stack.push
train
def push(self, value: Union[int, bytes]) -> None: """ Push an item onto the stack. """ if len(self.values) > 1023: raise FullStack('Stack limit reached') validate_stack_item(value) self.values.append(value)
python
{ "resource": "" }
q225439
Stack.pop
train
def pop(self, num_items: int, type_hint: str) -> Union[int, bytes, Tuple[Union[int, bytes], ...]]: """ Pop an item off the stack. Note: This function is optimized for speed over readability. """ try: if num_items == 1: return n...
python
{ "resource": "" }
q225440
Stack.swap
train
def swap(self, position: int) -> None: """ Perform a SWAP operation on the stack. """ idx = -1 * position - 1 try: self.values[-1], self.values[idx] = self.values[idx], self.values[-1] except IndexError: raise InsufficientStack("Insufficient stack ...
python
{ "resource": "" }
q225441
Stack.dup
train
def dup(self, position: int) -> None: """ Perform a DUP operation on the stack. """ idx = -1 * position try: self.push(self.values[idx]) except IndexError: raise InsufficientStack("Insufficient stack items for DUP{0}".format(position))
python
{ "resource": "" }
q225442
HeaderDB.get_canonical_block_hash
train
def get_canonical_block_hash(self, block_number: BlockNumber) -> Hash32: """ Returns the block hash for the canonical block at the given number. Raises BlockNotFound if there's no block header with the given number in the canonical chain. """ return self._get_canonical_b...
python
{ "resource": "" }
q225443
HeaderDB.get_canonical_block_header_by_number
train
def get_canonical_block_header_by_number(self, block_number: BlockNumber) -> BlockHeader: """ Returns the block header with the given number in the canonical chain. Raises BlockNotFound if there's no block header with the given number in the canonical chain. """ return s...
python
{ "resource": "" }
q225444
HeaderDB.persist_header_chain
train
def persist_header_chain(self, headers: Iterable[BlockHeader] ) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]: """ Return two iterable of headers, the first containing the new canonical headers, the second containing the old ...
python
{ "resource": "" }
q225445
HeaderDB._set_as_canonical_chain_head
train
def _set_as_canonical_chain_head(cls, db: BaseDB, block_hash: Hash32 ) -> Tuple[Tuple[BlockHeader, ...], Tuple[BlockHeader, ...]]: """ Sets the canonical chain HEAD to the block header as specified by the given block hash. :return: a tuple of the hea...
python
{ "resource": "" }
q225446
HeaderDB._add_block_number_to_hash_lookup
train
def _add_block_number_to_hash_lookup(db: BaseDB, header: BlockHeader) -> None: """ Sets a record in the database to allow looking up this header by its block number. """ block_number_to_hash_key = SchemaV1.make_block_number_to_hash_lookup_key( header.block_number ...
python
{ "resource": "" }
q225447
compute_gas_limit_bounds
train
def compute_gas_limit_bounds(parent: BlockHeader) -> Tuple[int, int]: """ Compute the boundaries for the block gas limit based on the parent block. """ boundary_range = parent.gas_limit // GAS_LIMIT_ADJUSTMENT_FACTOR upper_bound = parent.gas_limit + boundary_range lower_bound = max(GAS_LIMIT_MIN...
python
{ "resource": "" }
q225448
compute_gas_limit
train
def compute_gas_limit(parent_header: BlockHeader, gas_limit_floor: int) -> int: """ A simple strategy for adjusting the gas limit. For each block: - decrease by 1/1024th of the gas limit from the previous block - increase by 50% of the total gas used by the previous block If the value is less...
python
{ "resource": "" }
q225449
generate_header_from_parent_header
train
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: """ Generate BlockHeader from state_root and parent_h...
python
{ "resource": "" }
q225450
state_definition_to_dict
train
def state_definition_to_dict(state_definition: GeneralState) -> AccountState: """Convert a state definition to the canonical dict form. State can either be defined in the canonical form, or as a list of sub states that are then merged to one. Sub states can either be given as dictionaries themselves, or as...
python
{ "resource": "" }
q225451
Journal.record_changeset
train
def record_changeset(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID: """ Creates a new changeset. Changesets are referenced by a random uuid4 to prevent collisions between multiple changesets. """ if custom_changeset_id is not None: if custom_changeset_id i...
python
{ "resource": "" }
q225452
Journal.pop_changeset
train
def pop_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]: """ Returns all changes from the given changeset. This includes all of the changes from any subsequent changeset, giving precidence to later changesets. """ if changeset_id not i...
python
{ "resource": "" }
q225453
Journal.commit_changeset
train
def commit_changeset(self, changeset_id: uuid.UUID) -> Dict[bytes, Union[bytes, DeletedEntry]]: """ Collapses all changes for the given changeset into the previous changesets if it exists. """ does_clear = self.has_clear(changeset_id) changeset_data = self.pop_changeset(c...
python
{ "resource": "" }
q225454
JournalDB._validate_changeset
train
def _validate_changeset(self, changeset_id: uuid.UUID) -> None: """ Checks to be sure the changeset is known by the journal """ if not self.journal.has_changeset(changeset_id): raise ValidationError("Changeset not found in journal: {0}".format( str(changeset_i...
python
{ "resource": "" }
q225455
JournalDB.record
train
def record(self, custom_changeset_id: uuid.UUID = None) -> uuid.UUID: """ Starts a new recording and returns an id for the associated changeset """ return self.journal.record_changeset(custom_changeset_id)
python
{ "resource": "" }
q225456
JournalDB.discard
train
def discard(self, changeset_id: uuid.UUID) -> None: """ Throws away all journaled data starting at the given changeset """ self._validate_changeset(changeset_id) self.journal.pop_changeset(changeset_id)
python
{ "resource": "" }
q225457
JournalDB.commit
train
def commit(self, changeset_id: uuid.UUID) -> None: """ Commits a given changeset. This merges the given changeset and all subsequent changesets into the previous changeset giving precidence to later changesets in case of any conflicting keys. If this is the base changeset then a...
python
{ "resource": "" }
q225458
FQP_point_to_FQ2_point
train
def FQP_point_to_FQ2_point(pt: Tuple[FQP, FQP, FQP]) -> Tuple[FQ2, FQ2, FQ2]: """ Transform FQP to FQ2 for type hinting. """ return ( FQ2(pt[0].coeffs), FQ2(pt[1].coeffs), FQ2(pt[2].coeffs), )
python
{ "resource": "" }
q225459
Opcode.as_opcode
train
def as_opcode(cls: Type[T], logic_fn: Callable[..., Any], mnemonic: str, gas_cost: int) -> Type[T]: """ Class factory method for turning vanilla functions into Opcode classes. """ if gas_cost: @functools.wraps(logic_fn) ...
python
{ "resource": "" }
q225460
AccountDB._wipe_storage
train
def _wipe_storage(self, address: Address) -> None: """ Wipe out the storage, without explicitly handling the storage root update """ account_store = self._get_address_store(address) self._dirty_accounts.add(address) account_store.delete()
python
{ "resource": "" }
q225461
setup_main_filler
train
def setup_main_filler(name: str, environment: Dict[Any, Any]=None) -> Dict[str, Dict[str, Any]]: """ Kick off the filler generation process by creating the general filler scaffold with a test name and general information about the testing environment. For tests for the main chain, the `environment` par...
python
{ "resource": "" }
q225462
pre_state
train
def pre_state(*raw_state: GeneralState, filler: Dict[str, Any]) -> None: """ Specify the state prior to the test execution. Multiple invocations don't override the state but extend it instead. In general, the elements of `state_definitions` are nested dictionaries of the following form: .. code-bl...
python
{ "resource": "" }
q225463
expect
train
def expect(post_state: Dict[str, Any]=None, networks: Any=None, transaction: TransactionDict=None) -> Callable[..., Dict[str, Any]]: """ Specify the expected result for the test. For state tests, multiple expectations can be given, differing in the transaction data, gas limit, an...
python
{ "resource": "" }
q225464
calldataload
train
def calldataload(computation: BaseComputation) -> None: """ Load call data into memory. """ start_position = computation.stack_pop(type_hint=constants.UINT256) value = computation.msg.data_as_bytes[start_position:start_position + 32] padded_value = value.ljust(32, b'\x00') normalized_value ...
python
{ "resource": "" }
q225465
clamp
train
def clamp(inclusive_lower_bound: int, inclusive_upper_bound: int, value: int) -> int: """ Bound the given ``value`` between ``inclusive_lower_bound`` and ``inclusive_upper_bound``. """ if value <= inclusive_lower_bound: return inclusive_lower_bound elif value >= inclu...
python
{ "resource": "" }
q225466
integer_squareroot
train
def integer_squareroot(value: int) -> int: """ Return the integer square root of ``value``. Uses Python's decimal module to compute the square root of ``value`` with a precision of 128-bits. The value 128 is chosen since the largest square root of a 256-bit integer is a 128-bit integer. """ ...
python
{ "resource": "" }
q225467
AtomicDBWriteBatch._commit_unless_raises
train
def _commit_unless_raises(cls, write_target_db: BaseDB) -> Iterator['AtomicDBWriteBatch']: """ Commit all writes inside the context, unless an exception was raised. Although this is technically an external API, it (and this whole class) is only intended to be used by AtomicDB. "...
python
{ "resource": "" }
q225468
slt
train
def slt(computation: BaseComputation) -> None: """ Signed Lesser Comparison """ left, right = map( unsigned_to_signed, computation.stack_pop(num_items=2, type_hint=constants.UINT256), ) if left < right: result = 1 else: result = 0 computation.stack_push(...
python
{ "resource": "" }
q225469
build
train
def build(obj: Any, *applicators: Callable[..., Any]) -> Any: """ Run the provided object through the series of applicator functions. If ``obj`` is an instances of :class:`~eth.chains.base.BaseChain` the applicators will be run on a copy of the chain and thus will not mutate the provided chain inst...
python
{ "resource": "" }
q225470
name
train
def name(class_name: str, chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Assign the given name to the chain class. """ return chain_class.configure(__name__=class_name)
python
{ "resource": "" }
q225471
chain_id
train
def chain_id(chain_id: int, chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Set the ``chain_id`` for the chain class. """ return chain_class.configure(chain_id=chain_id)
python
{ "resource": "" }
q225472
fork_at
train
def fork_at(vm_class: Type[BaseVM], at_block: int, chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Adds the ``vm_class`` to the chain's ``vm_configuration``. .. code-block:: python from eth.chains.base import MiningChain from eth.tools.builder.chain import build, fork_at Fro...
python
{ "resource": "" }
q225473
enable_pow_mining
train
def enable_pow_mining(chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Inject on demand generation of the proof of work mining seal on newly mined blocks into each of the chain's vms. """ if not chain_class.vm_configuration: raise ValidationError("Chain class has no vm_configuration") ...
python
{ "resource": "" }
q225474
disable_pow_check
train
def disable_pow_check(chain_class: Type[BaseChain]) -> Type[BaseChain]: """ Disable the proof of work validation check for each of the chain's vms. This allows for block mining without generation of the proof of work seal. .. note:: blocks mined this way will not be importable on any chain tha...
python
{ "resource": "" }
q225475
genesis
train
def genesis(chain_class: BaseChain, db: BaseAtomicDB=None, params: Dict[str, HeaderParams]=None, state: GeneralState=None) -> BaseChain: """ Initialize the given chain class with the given genesis header parameters and chain state. """ if state is None: ge...
python
{ "resource": "" }
q225476
mine_block
train
def mine_block(chain: MiningChain, **kwargs: Any) -> MiningChain: """ Mine a new block on the chain. Header parameters for the new block can be overridden using keyword arguments. """ if not isinstance(chain, MiningChain): raise ValidationError('`mine_block` may only be used on MiningChain...
python
{ "resource": "" }
q225477
import_block
train
def import_block(block: BaseBlock, chain: BaseChain) -> BaseChain: """ Import the provided ``block`` into the chain. """ chain.import_block(block) return chain
python
{ "resource": "" }
q225478
copy
train
def copy(chain: MiningChain) -> MiningChain: """ Make a copy of the chain at the given state. Actions performed on the resulting chain will not affect the original chain. """ if not isinstance(chain, MiningChain): raise ValidationError("`at_block_number` may only be used with 'MiningChain")...
python
{ "resource": "" }
q225479
chain_split
train
def chain_split(*splits: Iterable[Callable[..., Any]]) -> Callable[[BaseChain], Iterable[BaseChain]]: # noqa: E501 """ Construct and execute multiple concurrent forks of the chain. Any number of forks may be executed. For each fork, provide an iterable of commands. Returns the resulting chain o...
python
{ "resource": "" }
q225480
at_block_number
train
def at_block_number(block_number: BlockNumber, chain: MiningChain) -> MiningChain: """ Rewind the chain back to the given block number. Calls to things like ``get_canonical_head`` will still return the canonical head of the chain, however, you can use ``mine_block`` to mine fork chains. """ if ...
python
{ "resource": "" }
q225481
load_json_fixture
train
def load_json_fixture(fixture_path: str) -> Dict[str, Any]: """ Loads a fixture file, caching the most recent files it loaded. """ with open(fixture_path) as fixture_file: file_fixtures = json.load(fixture_file) return file_fixtures
python
{ "resource": "" }
q225482
load_fixture
train
def load_fixture(fixture_path: str, fixture_key: str, normalize_fn: Callable[..., Any]=identity) -> Dict[str, Any]: """ Loads a specific fixture from a fixture file, optionally passing it through a normalization function. """ file_fixtures = load_json_fixture(fixtur...
python
{ "resource": "" }
q225483
construct_evm_runtime_identifier
train
def construct_evm_runtime_identifier() -> str: """ Constructs the EVM runtime identifier string e.g. 'Py-EVM/v1.2.3/darwin-amd64/python3.6.5' """ return "Py-EVM/{0}/{platform}/{imp.name}{v.major}.{v.minor}.{v.micro}".format( __version__, platform=sys.platform, v=sys.version_...
python
{ "resource": "" }
q225484
binary_gas_search
train
def binary_gas_search(state: BaseState, transaction: BaseTransaction, tolerance: int=1) -> int: """ Run the transaction with various gas limits, progressively approaching the minimum needed to succeed without an OutOfGas exception. The starting range of possible estimates is: [transaction.intrinsic...
python
{ "resource": "" }
q225485
StorageLookup.commit_to
train
def commit_to(self, db: BaseDB) -> None: """ Trying to commit changes when nothing has been written will raise a ValidationError """ self.logger.debug2('persist storage root to data store') if self._trie_nodes_batch is None: raise ValidationError( ...
python
{ "resource": "" }
q225486
AccountStorageDB._validate_flushed
train
def _validate_flushed(self) -> None: """ Will raise an exception if there are some changes made since the last persist. """ journal_diff = self._journal_storage.diff() if len(journal_diff) > 0: raise ValidationError( "StorageDB had a dirty journal when...
python
{ "resource": "" }
q225487
Memory.write
train
def write(self, start_position: int, size: int, value: bytes) -> None: """ Write `value` into memory. """ if size: validate_uint256(start_position) validate_uint256(size) validate_is_bytes(value) validate_length(value, length=size) ...
python
{ "resource": "" }
q225488
Memory.read
train
def read(self, start_position: int, size: int) -> memoryview: """ Return a view into the memory """ return memoryview(self._bytes)[start_position:start_position + size]
python
{ "resource": "" }
q225489
Memory.read_bytes
train
def read_bytes(self, start_position: int, size: int) -> bytes: """ Read a value from memory and return a fresh bytes instance """ return bytes(self._bytes[start_position:start_position + size])
python
{ "resource": "" }
q225490
BaseComputation.extend_memory
train
def extend_memory(self, start_position: int, size: int) -> None: """ Extend the size of the memory to be at minimum ``start_position + size`` bytes in length. Raise `eth.exceptions.OutOfGas` if there is not enough gas to pay for extending the memory. """ validate_uint256...
python
{ "resource": "" }
q225491
BaseComputation.memory_read
train
def memory_read(self, start_position: int, size: int) -> memoryview: """ Read and return a view of ``size`` bytes from memory starting at ``start_position``. """ return self._memory.read(start_position, size)
python
{ "resource": "" }
q225492
BaseComputation.memory_read_bytes
train
def memory_read_bytes(self, start_position: int, size: int) -> bytes: """ Read and return ``size`` bytes from memory starting at ``start_position``. """ return self._memory.read_bytes(start_position, size)
python
{ "resource": "" }
q225493
BaseComputation.consume_gas
train
def consume_gas(self, amount: int, reason: str) -> None: """ Consume ``amount`` of gas from the remaining gas. Raise `eth.exceptions.OutOfGas` if there is not enough gas remaining. """ return self._gas_meter.consume_gas(amount, reason)
python
{ "resource": "" }
q225494
BaseComputation.stack_pop
train
def stack_pop(self, num_items: int=1, type_hint: str=None) -> Any: # TODO: Needs to be replaced with # `Union[int, bytes, Tuple[Union[int, bytes], ...]]` if done properly """ Pop and return a number of items equal to ``num_items`` from the stack. ``type_hint`` can be either ``'ui...
python
{ "resource": "" }
q225495
BaseComputation.stack_push
train
def stack_push(self, value: Union[int, bytes]) -> None: """ Push ``value`` onto the stack. Raise `eth.exceptions.StackDepthLimit` if the stack is full. """ return self._stack.push(value)
python
{ "resource": "" }
q225496
BaseComputation.prepare_child_message
train
def prepare_child_message(self, gas: int, to: Address, value: int, data: BytesOrView, code: bytes, **kwargs: Any) -> Message: """ ...
python
{ "resource": "" }
q225497
BaseComputation.apply_child_computation
train
def apply_child_computation(self, child_msg: Message) -> 'BaseComputation': """ Apply the vm message ``child_msg`` as a child computation. """ child_computation = self.generate_child_computation(child_msg) self.add_child_computation(child_computation) return child_computa...
python
{ "resource": "" }
q225498
BaseComputation._get_log_entries
train
def _get_log_entries(self) -> List[Tuple[int, bytes, List[int], bytes]]: """ Return the log entries for this computation and its children. They are sorted in the same order they were emitted during the transaction processing, and include the sequential counter as the first element of th...
python
{ "resource": "" }
q225499
BaseComputation.apply_computation
train
def apply_computation(cls, state: BaseState, message: Message, transaction_context: BaseTransactionContext) -> 'BaseComputation': """ Perform the computation that would be triggered by the VM message. """ with ...
python
{ "resource": "" }