_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q270800
join_lines
test
def join_lines(string, strip=Strip.BOTH): ''' Join strings together and strip whitespace in between if needed ''' lines = [] for line in string.splitlines(): if strip & Strip.RIGHT: line = line.rstrip() if strip & Strip.LEFT: line = line.lstrip() li...
python
{ "resource": "" }
q270801
json_or_text
test
async def json_or_text(response): """Turns response into a properly formatted json or text object""" text = await response.text() if response.headers['Content-Type'] == 'application/json; charset=utf-8': return json.loads(text) return text
python
{ "resource": "" }
q270802
limited
test
async def limited(until): """Handles the message shown when we are ratelimited""" duration = int(round(until - time.time())) mins = duration / 60 fmt = 'We have exhausted a ratelimit quota. Retrying in %.2f seconds (%.3f minutes).' log.warn(fmt, duration, mins)
python
{ "resource": "" }
q270803
HTTPClient.request
test
async def request(self, method, url, **kwargs): """Handles requests to the API""" rate_limiter = RateLimiter(max_calls=59, period=60, callback=limited) # handles ratelimits. max_calls is set to 59 because current implementation will retry in 60s after 60 calls is reached. DBL has a 1h block so o...
python
{ "resource": "" }
q270804
HTTPClient.get_bot_info
test
async def get_bot_info(self, bot_id): '''Gets the information of the given Bot ID''' resp = await self.request('GET', '{}/bots/{}'.format(self.BASE, bot_id)) resp['date'] = datetime.strptime(resp['date'], '%Y-%m-%dT%H:%M:%S.%fZ') for k in resp: if resp[k] == '': ...
python
{ "resource": "" }
q270805
HTTPClient.get_bots
test
async def get_bots(self, limit, offset): '''Gets an object of bots on DBL''' if limit > 500: limit = 50 return await self.request('GET', '{}/bots?limit={}&offset={}'.format(self.BASE, limit, offset))
python
{ "resource": "" }
q270806
Port.read
test
def read(self): """Read incoming message.""" packet = self.packet with self.__read_lock: buffer = self.__buffer while len(buffer) < packet: buffer += self._read_data() length = self.__unpack(buffer[:packet])[0] + packet while len(bu...
python
{ "resource": "" }
q270807
Port.write
test
def write(self, message): """Write outgoing message.""" data = encode(message, compressed=self.compressed) length = len(data) data = self.__pack(length) + data with self.__write_lock: while data: try: n = os.write(self.out_d, data) ...
python
{ "resource": "" }
q270808
Port.close
test
def close(self): """Close port.""" os.close(self.in_d) os.close(self.out_d)
python
{ "resource": "" }
q270809
decode
test
def decode(string): """Decode Erlang external term.""" if not string: raise IncompleteData(string) if string[0] != 131: raise ValueError("unknown protocol version: %r" % string[0]) if string[1:2] == b'P': # compressed term if len(string) < 16: raise Incomplete...
python
{ "resource": "" }
q270810
encode
test
def encode(term, compressed=False): """Encode Erlang external term.""" encoded_term = encode_term(term) # False and 0 do not attempt compression. if compressed: if compressed is True: # default compression level of 6 compressed = 6 elif compressed < 0 or compresse...
python
{ "resource": "" }
q270811
NetworkingThread.addSourceAddr
test
def addSourceAddr(self, addr): """None means 'system default'""" try: self._multiInSocket.setsockopt(socket.IPPROTO_IP, socket.IP_ADD_MEMBERSHIP, self._makeMreq(addr)) except socket.error: # if 1 interface has more than 1 address, exception is raised for the second pass ...
python
{ "resource": "" }
q270812
NetworkingThread._sendPendingMessages
test
def _sendPendingMessages(self): """Method sleeps, if nothing to do""" if len(self._queue) == 0: time.sleep(0.1) return msg = self._queue.pop(0) if msg.canSend(): self._sendMsg(msg) msg.refresh() if not (msg.isFinished()): ...
python
{ "resource": "" }
q270813
WSDiscovery.setRemoteServiceHelloCallback
test
def setRemoteServiceHelloCallback(self, cb, types=None, scopes=None): """Set callback, which will be called when new service appeared online and sent Hi message typesFilter and scopesFilter might be list of types and scopes. If filter is set, callback is called only for Hello messages, ...
python
{ "resource": "" }
q270814
WSDiscovery.stop
test
def stop(self): 'cleans up and stops the discovery server' self.clearRemoteServices() self.clearLocalServices() self._stopThreads() self._serverStarted = False
python
{ "resource": "" }
q270815
WSDiscovery.clearLocalServices
test
def clearLocalServices(self): 'send Bye messages for the services and remove them' for service in list(self._localServices.values()): self._sendBye(service) self._localServices.clear()
python
{ "resource": "" }
q270816
WSDiscovery.searchServices
test
def searchServices(self, types=None, scopes=None, timeout=3): 'search for services given the TYPES and SCOPES in a given TIMEOUT' if not self._serverStarted: raise Exception("Server not started") self._sendProbe(types, scopes) time.sleep(timeout) return self._filt...
python
{ "resource": "" }
q270817
createSOAPMessage
test
def createSOAPMessage(env): "construct a a raw SOAP XML string, given a prepared SoapEnvelope object" if env.getAction() == ACTION_PROBE: return createProbeMessage(env) if env.getAction() == ACTION_PROBE_MATCH: return createProbeMatchMessage(env) if env.getAction() == ACTION_RESOLVE: ...
python
{ "resource": "" }
q270818
discover
test
def discover(scope, loglevel, capture): "Discover systems using WS-Discovery" if loglevel: level = getattr(logging, loglevel, None) if not level: print("Invalid log level '%s'" % loglevel) return logger.setLevel(level) run(scope=scope, capture=capture)
python
{ "resource": "" }
q270819
_ClusterTaggableManager.get_tagged_item_manager
test
def get_tagged_item_manager(self): """Return the manager that handles the relation from this instance to the tagged_item class. If content_object on the tagged_item class is defined as a ParentalKey, this will be a DeferringRelatedManager which allows writing related objects without committing t...
python
{ "resource": "" }
q270820
get_all_child_relations
test
def get_all_child_relations(model): """ Return a list of RelatedObject records for child relations of the given model, including ones attached to ancestors of the model """ return [ field for field in model._meta.get_fields() if isinstance(field.remote_field, ParentalKey) ]
python
{ "resource": "" }
q270821
get_all_child_m2m_relations
test
def get_all_child_m2m_relations(model): """ Return a list of ParentalManyToManyFields on the given model, including ones attached to ancestors of the model """ return [ field for field in model._meta.get_fields() if isinstance(field, ParentalManyToManyField) ]
python
{ "resource": "" }
q270822
ClusterableModel.save
test
def save(self, **kwargs): """ Save the model and commit all child relations. """ child_relation_names = [rel.get_accessor_name() for rel in get_all_child_relations(self)] child_m2m_field_names = [field.name for field in get_all_child_m2m_relations(self)] update_fields = ...
python
{ "resource": "" }
q270823
ClusterableModel.from_serializable_data
test
def from_serializable_data(cls, data, check_fks=True, strict_fks=False): """ Build an instance of this model from the JSON-like structure passed in, recursing into related objects as required. If check_fks is true, it will check whether referenced foreign keys still exist in the ...
python
{ "resource": "" }
q270824
BaseChildFormSet.validate_unique
test
def validate_unique(self): '''This clean method will check for unique_together condition''' # Collect unique_checks and to run from all the forms. all_unique_checks = set() all_date_checks = set() forms_to_delete = self.deleted_forms valid_forms = [form for form in self.f...
python
{ "resource": "" }
q270825
ClusterForm.has_changed
test
def has_changed(self): """Return True if data differs from initial.""" # Need to recurse over nested formsets so that the form is saved if there are changes # to child forms but not the parent if self.formsets: for formset in self.formsets.values(): for form ...
python
{ "resource": "" }
q270826
Address.with_valid_checksum
test
def with_valid_checksum(self): # type: () -> Address """ Returns the address with a valid checksum attached. """ return Address( trytes=self.address + self._generate_checksum(), # Make sure to copy all of the ancillary attributes, too! balance...
python
{ "resource": "" }
q270827
Address._generate_checksum
test
def _generate_checksum(self): # type: () -> AddressChecksum """ Generates the correct checksum for this address. """ checksum_trits = [] # type: MutableSequence[int] sponge = Kerl() sponge.absorb(self.address.as_trits()) sponge.squeeze(checksum_trits) ...
python
{ "resource": "" }
q270828
IotaCommandLineApp.parse_argv
test
def parse_argv(self, argv=None): # type: (Optional[tuple]) -> dict """ Parses arguments for the command. :param argv: Arguments to pass to the argument parser. If ``None``, defaults to ``sys.argv[1:]``. """ arguments = vars(self.create_argument_pa...
python
{ "resource": "" }
q270829
IotaCommandLineApp.create_argument_parser
test
def create_argument_parser(self): # type: () -> ArgumentParser """ Returns the argument parser that will be used to interpret arguments and options from argv. """ parser = ArgumentParser( description=self.__doc__, epilog='PyOTA v{version}'.format(v...
python
{ "resource": "" }
q270830
IotaCommandLineApp.prompt_for_seed
test
def prompt_for_seed(): # type: () -> Seed """ Prompts the user to enter their seed via stdin. """ seed = secure_input( 'Enter seed and press return (typing will not be shown).\n' 'If no seed is specified, a random one will be used instead.\n' ) ...
python
{ "resource": "" }
q270831
validate_signature_fragments
test
def validate_signature_fragments( fragments, hash_, public_key, sponge_type=Kerl, ): # type: (Sequence[TryteString], Hash, TryteString, type) -> bool """ Returns whether a sequence of signature fragments is valid. :param fragments: Sequence of signature fragments (...
python
{ "resource": "" }
q270832
KeyGenerator.get_key
test
def get_key(self, index, iterations): # type: (int, int) -> PrivateKey """ Generates a single key. :param index: The key index. :param iterations: Number of transform iterations to apply to the key, also known as security level. M...
python
{ "resource": "" }
q270833
KeyGenerator.get_key_for
test
def get_key_for(self, address): """ Generates the key associated with the specified address. Note that this method will generate the wrong key if the input address was generated from a different key! """ return self.get_key( index=address.key_index, ...
python
{ "resource": "" }
q270834
KeyGenerator.create_iterator
test
def create_iterator(self, start=0, step=1, security_level=1): # type: (int, int, int) -> KeyIterator """ Creates a generator that can be used to progressively generate new keys. :param start: Starting index. Warning: This method may take awhile to reset ...
python
{ "resource": "" }
q270835
KeyIterator._create_sponge
test
def _create_sponge(self, index): # type: (int) -> Kerl """ Prepares the hash sponge for the generator. """ seed = self.seed_as_trits[:] sponge = Kerl() sponge.absorb(add_trits(seed, trits_from_int(index))) # Squeeze all of the trits out of the sponge and...
python
{ "resource": "" }
q270836
Curl.absorb
test
def absorb(self, trits, offset=0, length=None): # type: (Sequence[int], Optional[int], Optional[int]) -> None """ Absorb trits into the sponge. :param trits: Sequence of trits to absorb. :param offset: Starting offset in ``trits``. :param length...
python
{ "resource": "" }
q270837
Curl.squeeze
test
def squeeze(self, trits, offset=0, length=HASH_LENGTH): # type: (MutableSequence[int], Optional[int], Optional[int]) -> None """ Squeeze trits from the sponge. :param trits: Sequence that the squeezed trits will be copied to. Note: this object will be modified! ...
python
{ "resource": "" }
q270838
Curl._transform
test
def _transform(self): # type: () -> None """ Transforms internal state. """ # Copy some values locally so we can avoid global lookups in the # inner loop. # # References: # # - https://wiki.python.org/moin/PythonSpeed/PerformanceTips#Local_...
python
{ "resource": "" }
q270839
MultisigIota.get_digests
test
def get_digests( self, index=0, count=1, security_level=AddressGenerator.DEFAULT_SECURITY_LEVEL, ): # type: (int, int, int) -> dict """ Generates one or more key digests from the seed. Digests are safe to share; use them to generate mu...
python
{ "resource": "" }
q270840
MultisigIota.get_private_keys
test
def get_private_keys( self, index=0, count=1, security_level=AddressGenerator.DEFAULT_SECURITY_LEVEL, ): # type: (int, int, int) -> dict """ Generates one or more private keys from the seed. As the name implies, private keys should not...
python
{ "resource": "" }
q270841
MultisigIota.prepare_multisig_transfer
test
def prepare_multisig_transfer( self, transfers, # type: Iterable[ProposedTransaction] multisig_input, # type: MultisigAddress change_address=None, # type: Optional[Address] ): # type: (...) -> dict """ Prepares a bundle that authorizes the s...
python
{ "resource": "" }
q270842
add_trits
test
def add_trits(left, right): # type: (Sequence[int], Sequence[int]) -> List[int] """ Adds two sequences of trits together. The result is a list of trits equal in length to the longer of the two sequences. .. note:: Overflow is possible. For example, ``add_trits([1], [1])`` retu...
python
{ "resource": "" }
q270843
trits_from_int
test
def trits_from_int(n, pad=1): # type: (int, Optional[int]) -> List[int] """ Returns a trit representation of an integer value. :param n: Integer value to convert. :param pad: Ensure the result has at least this many trits. References: - https://dev.to/buntine/the-balanced...
python
{ "resource": "" }
q270844
_add_trits
test
def _add_trits(left, right): # type: (int, int) -> int """ Adds two individual trits together. The result is always a single trit. """ res = left + right return res if -2 < res < 2 else (res < 0) - (res > 0)
python
{ "resource": "" }
q270845
_full_add_trits
test
def _full_add_trits(left, right, carry): # type: (int, int, int) -> Tuple[int, int] """ Adds two trits together, with support for a carry trit. """ sum_both = _add_trits(left, right) cons_left = _cons_trits(left, right) cons_right = _cons_trits(sum_both, carry) return _add_trits(sum_bot...
python
{ "resource": "" }
q270846
output_seed
test
def output_seed(seed): # type: (Seed) -> None """ Outputs the user's seed to stdout, along with lots of warnings about security. """ print( 'WARNING: Anyone who has your seed can spend your IOTAs! ' 'Clear the screen after recording your seed!' ) compat.input('') prin...
python
{ "resource": "" }
q270847
StrictIota.find_transactions
test
def find_transactions( self, bundles=None, # type: Optional[Iterable[BundleHash]] addresses=None, # type: Optional[Iterable[Address]] tags=None, # type: Optional[Iterable[Tag]] approvees=None, # type: Optional[Iterable[TransactionHash]] ): # ty...
python
{ "resource": "" }
q270848
Iota.get_inputs
test
def get_inputs( self, start=0, stop=None, threshold=None, security_level=None, ): # type: (int, Optional[int], Optional[int], Optional[int]) -> dict """ Gets all possible inputs of a seed and returns them, along with the tot...
python
{ "resource": "" }
q270849
Iota.get_new_addresses
test
def get_new_addresses( self, index=0, count=1, security_level=AddressGenerator.DEFAULT_SECURITY_LEVEL, checksum=False, ): # type: (int, Optional[int], int, bool) -> dict """ Generates one or more new addresses from the seed. ...
python
{ "resource": "" }
q270850
Iota.get_transfers
test
def get_transfers(self, start=0, stop=None, inclusion_states=False): # type: (int, Optional[int], bool) -> dict """ Returns all transfers associated with the seed. :param start: Starting key index. :param stop: Stop before this index. Note t...
python
{ "resource": "" }
q270851
Iota.promote_transaction
test
def promote_transaction( self, transaction, depth=3, min_weight_magnitude=None, ): # type: (TransactionHash, int, Optional[int]) -> dict """ Promotes a transaction by adding spam on top of it. :return: Dict with the followi...
python
{ "resource": "" }
q270852
Iota.replay_bundle
test
def replay_bundle( self, transaction, depth=3, min_weight_magnitude=None, ): # type: (TransactionHash, int, Optional[int]) -> dict """ Takes a tail transaction hash as input, gets the bundle associated with the transaction and then repl...
python
{ "resource": "" }
q270853
Iota.send_transfer
test
def send_transfer( self, transfers, # type: Iterable[ProposedTransaction] depth=3, # type: int inputs=None, # type: Optional[Iterable[Address]] change_address=None, # type: Optional[Address] min_weight_magnitude=None, # type: Optional[int] ...
python
{ "resource": "" }
q270854
Iota.send_trytes
test
def send_trytes(self, trytes, depth=3, min_weight_magnitude=None): # type: (Iterable[TransactionTrytes], int, Optional[int]) -> dict """ Attaches transaction trytes to the Tangle, then broadcasts and stores them. :param trytes: Transaction encoded as a tryte sequence...
python
{ "resource": "" }
q270855
resolve_adapter
test
def resolve_adapter(uri): # type: (AdapterSpec) -> BaseAdapter """ Given a URI, returns a properly-configured adapter instance. """ if isinstance(uri, BaseAdapter): return uri parsed = compat.urllib_parse.urlsplit(uri) # type: SplitResult if not parsed.scheme: raise with_c...
python
{ "resource": "" }
q270856
BaseAdapter.send_request
test
def send_request(self, payload, **kwargs): # type: (dict, dict) -> dict """ Sends an API request to the node. :param payload: JSON payload. :param kwargs: Additional keyword arguments for the adapter. :return: Decoded response from t...
python
{ "resource": "" }
q270857
BaseAdapter._log
test
def _log(self, level, message, context=None): # type: (int, Text, Optional[dict]) -> None """ Sends a message to the instance's logger, if configured. """ if self._logger: self._logger.log(level, message, extra={'context': context or {}})
python
{ "resource": "" }
q270858
HttpAdapter._send_http_request
test
def _send_http_request(self, url, payload, method='post', **kwargs): # type: (Text, Optional[Text], Text, dict) -> Response """ Sends the actual HTTP request. Split into its own method so that it can be mocked during unit tests. """ kwargs.setdefault( ...
python
{ "resource": "" }
q270859
HttpAdapter._interpret_response
test
def _interpret_response(self, response, payload, expected_status): # type: (Response, dict, Container[int]) -> dict """ Interprets the HTTP response from the node. :param response: The response object received from :py:meth:`_send_http_request`. :param p...
python
{ "resource": "" }
q270860
MockAdapter.seed_response
test
def seed_response(self, command, response): # type: (Text, dict) -> MockAdapter """ Sets the response that the adapter will return for the specified command. You can seed multiple responses per command; the adapter will put them into a FIFO queue. When a request comes i...
python
{ "resource": "" }
q270861
MultisigAddressBuilder.add_digest
test
def add_digest(self, digest): # type: (Digest) -> None """ Absorbs a digest into the sponge. .. important:: Keep track of the order that digests are added! To spend inputs from a multisig address, you must provide the private keys in the same order! ...
python
{ "resource": "" }
q270862
MultisigAddressBuilder.get_address
test
def get_address(self): # type: () -> MultisigAddress """ Returns the new multisig address. Note that you can continue to add digests after extracting an address; the next address will use *all* of the digests that have been added so far. """ if not self._...
python
{ "resource": "" }
q270863
AddressGenerator.create_iterator
test
def create_iterator(self, start=0, step=1): # type: (int, int) -> Generator[Address, None, None] """ Creates an iterator that can be used to progressively generate new addresses. :param start: Starting index. Warning: This method may take awhile to reset...
python
{ "resource": "" }
q270864
AddressGenerator.address_from_digest
test
def address_from_digest(digest): # type: (Digest) -> Address """ Generates an address from a private key digest. """ address_trits = [0] * (Address.LEN * TRITS_PER_TRYTE) # type: List[int] sponge = Kerl() sponge.absorb(digest.as_trits()) sponge.squeeze(a...
python
{ "resource": "" }
q270865
AddressGenerator._generate_address
test
def _generate_address(self, key_iterator): # type: (KeyIterator) -> Address """ Generates a new address. Used in the event of a cache miss. """ if self.checksum: return ( self.address_from_digest( digest=self._get_digest(ke...
python
{ "resource": "" }
q270866
find_transaction_objects
test
def find_transaction_objects(adapter, **kwargs): # type: (BaseAdapter, **Iterable) -> List[Transaction] """ Finds transactions matching the specified criteria, fetches the corresponding trytes and converts them into Transaction objects. """ ft_response = FindTransactionsCommand(adapter)(**kwargs...
python
{ "resource": "" }
q270867
iter_used_addresses
test
def iter_used_addresses( adapter, # type: BaseAdapter seed, # type: Seed start, # type: int security_level=None, # type: Optional[int] ): # type: (...) -> Generator[Tuple[Address, List[TransactionHash]], None, None] """ Scans the Tangle for used addresses. This is ba...
python
{ "resource": "" }
q270868
get_bundles_from_transaction_hashes
test
def get_bundles_from_transaction_hashes( adapter, transaction_hashes, inclusion_states, ): # type: (BaseAdapter, Iterable[TransactionHash], bool) -> List[Bundle] """ Given a set of transaction hashes, returns the corresponding bundles, sorted by tail transaction timestamp. ""...
python
{ "resource": "" }
q270869
check_trytes_codec
test
def check_trytes_codec(encoding): """ Determines which codec to use for the specified encoding. References: - https://docs.python.org/3/library/codecs.html#codecs.register """ if encoding == AsciiTrytesCodec.name: return AsciiTrytesCodec.get_codec_info() elif encoding == AsciiTryt...
python
{ "resource": "" }
q270870
AsciiTrytesCodec.get_codec_info
test
def get_codec_info(cls): """ Returns information used by the codecs library to configure the codec for use. """ codec = cls() codec_info = { 'encode': codec.encode, 'decode': codec.decode, } # In Python 2, all codecs are made equa...
python
{ "resource": "" }
q270871
AsciiTrytesCodec.encode
test
def encode(self, input, errors='strict'): """ Encodes a byte string into trytes. """ if isinstance(input, memoryview): input = input.tobytes() if not isinstance(input, (binary_type, bytearray)): raise with_context( exc=TypeError( ...
python
{ "resource": "" }
q270872
AsciiTrytesCodec.decode
test
def decode(self, input, errors='strict'): """ Decodes a tryte string into bytes. """ if isinstance(input, memoryview): input = input.tobytes() if not isinstance(input, (binary_type, bytearray)): raise with_context( exc=TypeError( ...
python
{ "resource": "" }
q270873
GetNewAddressesCommand._find_addresses
test
def _find_addresses(self, seed, index, count, security_level, checksum): # type: (Seed, int, Optional[int], int, bool) -> List[Address] """ Find addresses matching the command parameters. """ generator = AddressGenerator(seed, security_level, checksum) if count is None: ...
python
{ "resource": "" }
q270874
RoutingWrapper.add_route
test
def add_route(self, command, adapter): # type: (Text, AdapterSpec) -> RoutingWrapper """ Adds a route to the wrapper. :param command: The name of the command to route (e.g., "attachToTangle"). :param adapter: The adapter object or URI to route requests t...
python
{ "resource": "" }
q270875
Transaction.from_tryte_string
test
def from_tryte_string(cls, trytes, hash_=None): # type: (TrytesCompatible, Optional[TransactionHash]) -> Transaction """ Creates a Transaction object from a sequence of trytes. :param trytes: Raw trytes. Should be exactly 2673 trytes long. :param hash_: ...
python
{ "resource": "" }
q270876
Transaction.as_json_compatible
test
def as_json_compatible(self): # type: () -> dict """ Returns a JSON-compatible representation of the object. References: - :py:class:`iota.json.JsonEncoder`. """ return { 'hash_': self.hash, 'signature_message_fragment': self.signature_me...
python
{ "resource": "" }
q270877
Transaction.get_signature_validation_trytes
test
def get_signature_validation_trytes(self): # type: () -> TryteString """ Returns the values needed to validate the transaction's ``signature_message_fragment`` value. """ return ( self.address.address + self.value_as_trytes ...
python
{ "resource": "" }
q270878
Bundle.is_confirmed
test
def is_confirmed(self, new_is_confirmed): # type: (bool) -> None """ Sets the ``is_confirmed`` for the bundle. """ self._is_confirmed = new_is_confirmed for txn in self: txn.is_confirmed = new_is_confirmed
python
{ "resource": "" }
q270879
Bundle.get_messages
test
def get_messages(self, errors='drop'): # type: (Text) -> List[Text] """ Attempts to decipher encoded messages from the transactions in the bundle. :param errors: How to handle trytes that can't be converted, or bytes that can't be decoded using UTF-8: ...
python
{ "resource": "" }
q270880
Bundle.as_tryte_strings
test
def as_tryte_strings(self, head_to_tail=False): # type: (bool) -> List[TransactionTrytes] """ Returns TryteString representations of the transactions in this bundle. :param head_to_tail: Determines the order of the transactions: - ``True``: head txn firs...
python
{ "resource": "" }
q270881
Bundle.group_transactions
test
def group_transactions(self): # type: () -> List[List[Transaction]] """ Groups transactions in the bundle by address. """ groups = [] if self: last_txn = self.tail_transaction current_group = [last_txn] for current_txn in self.transact...
python
{ "resource": "" }
q270882
discover_commands
test
def discover_commands(package, recursively=True): # type: (Union[ModuleType, Text], bool) -> Dict[Text, 'CommandMeta'] """ Automatically discover commands in the specified package. :param package: Package path or reference. :param recursively: If True, will descend recursively into sub-packages. ...
python
{ "resource": "" }
q270883
BaseCommand._execute
test
def _execute(self, request): # type: (dict) -> dict """ Sends the request object to the adapter and returns the response. The command name will be automatically injected into the request before it is sent (note: this will modify the request object). """ request['command'] = self.command ...
python
{ "resource": "" }
q270884
FilterCommand._apply_filter
test
def _apply_filter(value, filter_, failure_message): # type: (dict, Optional[f.BaseFilter], Text) -> dict """ Applies a filter to a value. If the value does not pass the filter, an exception will be raised with lots of contextual info attached to it. """ if filter_: runner = f.FilterRu...
python
{ "resource": "" }
q270885
SandboxAdapter.get_jobs_url
test
def get_jobs_url(self, job_id): # type: (Text) -> Text """ Returns the URL to check job status. :param job_id: The ID of the job to check. """ return compat.urllib_parse.urlunsplit(( self.uri.scheme, self.uri.netloc, self.u...
python
{ "resource": "" }
q270886
BundleValidator.errors
test
def errors(self): # type: () -> List[Text] """ Returns all errors found with the bundle. """ try: self._errors.extend(self._validator) # type: List[Text] except StopIteration: pass return self._errors
python
{ "resource": "" }
q270887
BundleValidator.is_valid
test
def is_valid(self): # type: () -> bool """ Returns whether the bundle is valid. """ if not self._errors: try: # We only have to check for a single error to determine # if the bundle is valid or not. self._errors.append(n...
python
{ "resource": "" }
q270888
BundleValidator._create_validator
test
def _create_validator(self): # type: () -> Generator[Text, None, None] """ Creates a generator that does all the work. """ # Group transactions by address to make it easier to iterate # over inputs. grouped_transactions = self.bundle.group_transactions() ...
python
{ "resource": "" }
q270889
BundleValidator._get_bundle_signature_errors
test
def _get_bundle_signature_errors(self, groups): # type: (List[List[Transaction]]) -> List[Text] """ Validates the signature fragments in the bundle. :return: List of error messages. If empty, signature fragments are valid. """ # Start with the cur...
python
{ "resource": "" }
q270890
BundleValidator._get_group_signature_error
test
def _get_group_signature_error(group, sponge_type): # type: (List[Transaction], type) -> Optional[Text] """ Validates the signature fragments for a group of transactions using the specified sponge type. Note: this method assumes that the transactions in the group have al...
python
{ "resource": "" }
q270891
GetBundlesCommand._traverse_bundle
test
def _traverse_bundle(self, txn_hash, target_bundle_hash=None): # type: (TransactionHash, Optional[BundleHash]) -> List[Transaction] """ Recursively traverse the Tangle, collecting transactions until we hit a new bundle. This method is (usually) faster than ``findTransactions``, ...
python
{ "resource": "" }
q270892
IotaReplCommandLineApp._start_repl
test
def _start_repl(api): # type: (Iota) -> None """ Starts the REPL. """ banner = ( 'IOTA API client for {uri} ({testnet}) ' 'initialized as variable `api`.\n' 'Type `help(api)` for list of API commands.'.format( testnet='testnet' ...
python
{ "resource": "" }
q270893
Seed.random
test
def random(cls, length=Hash.LEN): """ Generates a random seed using a CSPRNG. :param length: Length of seed, in trytes. For maximum security, this should always be set to 81, but you can change it if you're 110% sure you know what you're doing. ...
python
{ "resource": "" }
q270894
PrivateKey.get_digest
test
def get_digest(self): # type: () -> Digest """ Generates the digest used to do the actual signing. Signing keys can have variable length and tend to be quite long, which makes them not-well-suited for use in crypto algorithms. The digest is essentially the result of run...
python
{ "resource": "" }
q270895
PrivateKey.sign_input_transactions
test
def sign_input_transactions(self, bundle, start_index): # type: (Bundle, int) -> None """ Signs the inputs starting at the specified index. :param bundle: The bundle that contains the input transactions to sign. :param start_index: The index of the first...
python
{ "resource": "" }
q270896
JsonSerializable._repr_pretty_
test
def _repr_pretty_(self, p, cycle): """ Makes JSON-serializable objects play nice with IPython's default pretty-printer. Sadly, :py:func:`pprint.pprint` does not have a similar mechanism. References: - http://ipython.readthedocs.io/en/stable/api/generated/IPytho...
python
{ "resource": "" }
q270897
Kerl.absorb
test
def absorb(self, trits, offset=0, length=None): # type: (MutableSequence[int], int, Optional[int]) -> None """ Absorb trits into the sponge from a buffer. :param trits: Buffer that contains the trits to absorb. :param offset: Starting offset in ``trits``...
python
{ "resource": "" }
q270898
Kerl.squeeze
test
def squeeze(self, trits, offset=0, length=None): # type: (MutableSequence[int], int, Optional[int]) -> None """ Squeeze trits from the sponge into a buffer. :param trits: Buffer that will hold the squeezed trits. IMPORTANT: If ``trits`` is too small, it will be...
python
{ "resource": "" }
q270899
with_context
test
def with_context(exc, context): # type: (Exception, dict) -> Exception """ Attaches a ``context`` value to an Exception. Before: .. code-block:: python exc = Exception('Frog blast the vent core!') exc.context = { ... } raise exc After: .. code-block:: python ...
python
{ "resource": "" }