_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q229600 | TxnStackManager._parse_pool_transaction_file | train | def _parse_pool_transaction_file(
ledger, nodeReg, cliNodeReg, nodeKeys, activeValidators,
ledger_size=None):
"""
helper function for parseLedgerForHaAndKeys
"""
for _, txn in ledger.getAllTxn(to=ledger_size):
if get_type(txn) == NODE:
... | python | {
"resource": ""
} |
q229601 | MerkleVerifier.verify_tree_consistency | train | def verify_tree_consistency(self, old_tree_size: int, new_tree_size: int,
old_root: bytes, new_root: bytes,
proof: Sequence[bytes]):
"""Verify the consistency between two root hashes.
old_tree_size must be <= new_tree_size.
Args:
... | python | {
"resource": ""
} |
q229602 | HasActionQueue._schedule | train | def _schedule(self, action: Callable, seconds: int=0) -> int:
"""
Schedule an action to be executed after `seconds` seconds.
:param action: a callable to be scheduled
:param seconds: the time in seconds after which the action must be executed
"""
self.aid += 1
if... | python | {
"resource": ""
} |
q229603 | HasActionQueue._cancel | train | def _cancel(self, action: Callable = None, aid: int = None):
"""
Cancel scheduled events
:param action: (optional) scheduled action. If specified, all
scheduled events for the action are cancelled.
:param aid: (options) scheduled event id. If specified,
... | python | {
"resource": ""
} |
q229604 | HasActionQueue._serviceActions | train | def _serviceActions(self) -> int:
"""
Run all pending actions in the action queue.
:return: number of actions executed.
"""
if self.aqStash:
tm = time.perf_counter()
if tm > self.aqNextCheck:
earliest = float('inf')
for d i... | python | {
"resource": ""
} |
q229605 | Node.execute_pool_txns | train | def execute_pool_txns(self, three_pc_batch) -> List:
"""
Execute a transaction that involves consensus pool management, like
adding a node, client or a steward.
:param ppTime: PrePrepare request time
:param reqs_keys: requests keys to be committed
"""
committed_t... | python | {
"resource": ""
} |
q229606 | Node.init_state_from_ledger | train | def init_state_from_ledger(self, state: State, ledger: Ledger, reqHandler):
"""
If the trie is empty then initialize it by applying
txns from ledger.
"""
if state.isEmpty:
logger.info('{} found state to be empty, recreating from '
'ledger'.form... | python | {
"resource": ""
} |
q229607 | Node.on_view_change_start | train | def on_view_change_start(self):
"""
Notifies node about the fact that view changed to let it
prepare for election
"""
self.view_changer.start_view_change_ts = self.utc_epoch()
for replica in self.replicas.values():
replica.on_view_change_start()
logge... | python | {
"resource": ""
} |
q229608 | Node.on_view_change_complete | train | def on_view_change_complete(self):
"""
View change completes for a replica when it has been decided which was
the last ppSeqNo and state and txn root for previous view
"""
self.future_primaries_handler.set_node_state()
if not self.replicas.all_instances_have_primary:
... | python | {
"resource": ""
} |
q229609 | Node.onStopping | train | def onStopping(self):
"""
Actions to be performed on stopping the node.
- Close the UDP socket of the nodestack
"""
# Log stats should happen before any kind of reset or clearing
if self.config.STACK_COMPANION == 1:
add_stop_time(self.ledger_dir, self.utc_epo... | python | {
"resource": ""
} |
q229610 | Node.prod | train | async def prod(self, limit: int = None) -> int:
""".opened
This function is executed by the node each time it gets its share of
CPU time from the event loop.
:param limit: the number of items to be serviced in this attempt
:return: total number of messages serviced by this node
... | python | {
"resource": ""
} |
q229611 | Node.serviceNodeMsgs | train | async def serviceNodeMsgs(self, limit: int) -> int:
"""
Process `limit` number of messages from the nodeInBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed
"""
with self.metrics.measure_time(MetricsName.SE... | python | {
"resource": ""
} |
q229612 | Node.serviceClientMsgs | train | async def serviceClientMsgs(self, limit: int) -> int:
"""
Process `limit` number of messages from the clientInBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed
"""
c = await self.clientstack.service(limit,... | python | {
"resource": ""
} |
q229613 | Node.serviceViewChanger | train | async def serviceViewChanger(self, limit) -> int:
"""
Service the view_changer's inBox, outBox and action queues.
:return: the number of messages successfully serviced
"""
if not self.isReady():
return 0
o = self.serviceViewChangerOutBox(limit)
i = aw... | python | {
"resource": ""
} |
q229614 | Node.service_observable | train | async def service_observable(self, limit) -> int:
"""
Service the observable's inBox and outBox
:return: the number of messages successfully serviced
"""
if not self.isReady():
return 0
o = self._service_observable_out_box(limit)
i = await self._obser... | python | {
"resource": ""
} |
q229615 | Node._service_observable_out_box | train | def _service_observable_out_box(self, limit: int = None) -> int:
"""
Service at most `limit` number of messages from the observable's outBox.
:return: the number of messages successfully serviced.
"""
msg_count = 0
while True:
if limit and msg_count >= limit:... | python | {
"resource": ""
} |
q229616 | Node.service_observer | train | async def service_observer(self, limit) -> int:
"""
Service the observer's inBox and outBox
:return: the number of messages successfully serviced
"""
if not self.isReady():
return 0
return await self._observer.serviceQueues(limit) | python | {
"resource": ""
} |
q229617 | Node._ask_for_ledger_status | train | def _ask_for_ledger_status(self, node_name: str, ledger_id):
"""
Ask other node for LedgerStatus
"""
self.request_msg(LEDGER_STATUS, {f.LEDGER_ID.nm: ledger_id},
[node_name, ])
logger.info("{} asking {} for ledger status of ledger {}".format(self, node_na... | python | {
"resource": ""
} |
q229618 | Node.checkInstances | train | def checkInstances(self) -> None:
# TODO: Is this method really needed?
"""
Check if this node has the minimum required number of protocol
instances, i.e. f+1. If not, add a replica. If no election is in
progress, this node will try to nominate one of its replicas as primary.
... | python | {
"resource": ""
} |
q229619 | Node.adjustReplicas | train | def adjustReplicas(self,
old_required_number_of_instances: int,
new_required_number_of_instances: int):
"""
Add or remove replicas depending on `f`
"""
# TODO: refactor this
replica_num = old_required_number_of_instances
while... | python | {
"resource": ""
} |
q229620 | Node._check_view_change_completed | train | def _check_view_change_completed(self):
"""
This thing checks whether new primary was elected.
If it was not - starts view change again
"""
logger.info('{} running the scheduled check for view change completion'.format(self))
if not self.view_changer.view_change_in_progre... | python | {
"resource": ""
} |
q229621 | Node.service_replicas_outbox | train | def service_replicas_outbox(self, limit: int = None) -> int:
"""
Process `limit` number of replica messages
"""
# TODO: rewrite this using Router
num_processed = 0
for message in self.replicas.get_output(limit):
num_processed += 1
if isinstance(me... | python | {
"resource": ""
} |
q229622 | Node.master_primary_name | train | def master_primary_name(self) -> Optional[str]:
"""
Return the name of the primary node of the master instance
"""
master_primary_name = self.master_replica.primaryName
if master_primary_name:
return self.master_replica.getNodeName(master_primary_name)
return... | python | {
"resource": ""
} |
q229623 | Node.msgHasAcceptableInstId | train | def msgHasAcceptableInstId(self, msg, frm) -> bool:
"""
Return true if the instance id of message corresponds to a correct
replica.
:param msg: the node message to validate
:return:
"""
# TODO: refactor this! this should not do anything except checking!
i... | python | {
"resource": ""
} |
q229624 | Node.sendToReplica | train | def sendToReplica(self, msg, frm):
"""
Send the message to the intended replica.
:param msg: the message to send
:param frm: the name of the node which sent this `msg`
"""
# TODO: discard or stash messages here instead of doing
# this in msgHas* methods!!!
... | python | {
"resource": ""
} |
q229625 | Node.sendToViewChanger | train | def sendToViewChanger(self, msg, frm):
"""
Send the message to the intended view changer.
:param msg: the message to send
:param frm: the name of the node which sent this `msg`
"""
if (isinstance(msg, InstanceChange) or
self.msgHasAcceptableViewNo(msg, fr... | python | {
"resource": ""
} |
q229626 | Node.send_to_observer | train | def send_to_observer(self, msg, frm):
"""
Send the message to the observer.
:param msg: the message to send
:param frm: the name of the node which sent this `msg`
"""
logger.debug("{} sending message to observer: {}".
format(self, (msg, frm)))
... | python | {
"resource": ""
} |
q229627 | Node.handleOneNodeMsg | train | def handleOneNodeMsg(self, wrappedMsg):
"""
Validate and process one message from a node.
:param wrappedMsg: Tuple of message and the name of the node that sent
the message
"""
try:
vmsg = self.validateNodeMsg(wrappedMsg)
if vmsg:
... | python | {
"resource": ""
} |
q229628 | Node.validateNodeMsg | train | def validateNodeMsg(self, wrappedMsg):
"""
Validate another node's message sent to this node.
:param wrappedMsg: Tuple of message and the name of the node that sent
the message
:return: Tuple of message from node and name of the node
"""
msg, frm = wrappedMsg
... | python | {
"resource": ""
} |
q229629 | Node.unpackNodeMsg | train | def unpackNodeMsg(self, msg, frm) -> None:
"""
If the message is a batch message validate each message in the batch,
otherwise add the message to the node's inbox.
:param msg: a node message
:param frm: the name of the node that sent this `msg`
"""
# TODO: why do... | python | {
"resource": ""
} |
q229630 | Node.postToNodeInBox | train | def postToNodeInBox(self, msg, frm):
"""
Append the message to the node inbox
:param msg: a node message
:param frm: the name of the node that sent this `msg`
"""
logger.trace("{} appending to nodeInbox {}".format(self, msg))
self.nodeInBox.append((msg, frm)) | python | {
"resource": ""
} |
q229631 | Node.processNodeInBox | train | async def processNodeInBox(self):
"""
Process the messages in the node inbox asynchronously.
"""
while self.nodeInBox:
m = self.nodeInBox.popleft()
await self.process_one_node_message(m) | python | {
"resource": ""
} |
q229632 | Node.handleOneClientMsg | train | def handleOneClientMsg(self, wrappedMsg):
"""
Validate and process a client message
:param wrappedMsg: a message from a client
"""
try:
vmsg = self.validateClientMsg(wrappedMsg)
if vmsg:
self.unpackClientMsg(*vmsg)
except BlowUp:
... | python | {
"resource": ""
} |
q229633 | Node.processClientInBox | train | async def processClientInBox(self):
"""
Process the messages in the node's clientInBox asynchronously.
All messages in the inBox have already been validated, including
signature check.
"""
while self.clientInBox:
m = self.clientInBox.popleft()
req,... | python | {
"resource": ""
} |
q229634 | Node.is_catchup_needed_during_view_change | train | def is_catchup_needed_during_view_change(self) -> bool:
"""
Check if received a quorum of view change done messages and if yes
check if caught up till the
Check if all requests ordered till last prepared certificate
Check if last catchup resulted in no txns
"""
if... | python | {
"resource": ""
} |
q229635 | Node.doDynamicValidation | train | def doDynamicValidation(self, request: Request):
"""
State based validation
"""
self.execute_hook(NodeHooks.PRE_DYNAMIC_VALIDATION, request=request)
# Digest validation
ledger_id, seq_no = self.seqNoDB.get_by_payload_digest(request.payload_digest)
if ledger_id is... | python | {
"resource": ""
} |
q229636 | Node.applyReq | train | def applyReq(self, request: Request, cons_time: int):
"""
Apply request to appropriate ledger and state. `cons_time` is the
UTC epoch at which consensus was reached.
"""
self.execute_hook(NodeHooks.PRE_REQUEST_APPLICATION, request=request,
cons_time=cons... | python | {
"resource": ""
} |
q229637 | Node.processRequest | train | def processRequest(self, request: Request, frm: str):
"""
Handle a REQUEST from the client.
If the request has already been executed, the node re-sends the reply to
the client. Otherwise, the node acknowledges the client request, adds it
to its list of client requests, and sends ... | python | {
"resource": ""
} |
q229638 | Node.processPropagate | train | def processPropagate(self, msg: Propagate, frm):
"""
Process one propagateRequest sent to this node asynchronously
- If this propagateRequest hasn't been seen by this node, then broadcast
it to all nodes after verifying the the signature.
- Add the client to blacklist if its sig... | python | {
"resource": ""
} |
q229639 | Node.handle_get_txn_req | train | def handle_get_txn_req(self, request: Request, frm: str):
"""
Handle GET_TXN request
"""
ledger_id = request.operation.get(f.LEDGER_ID.nm, DOMAIN_LEDGER_ID)
if ledger_id not in self.ledger_to_req_handler:
self.send_nack_to_client((request.identifier, request.reqId),
... | python | {
"resource": ""
} |
q229640 | Node.processOrdered | train | def processOrdered(self, ordered: Ordered):
"""
Execute ordered request
:param ordered: an ordered request
:return: whether executed
"""
if ordered.instId not in self.instances.ids:
logger.warning('{} got ordered request for instance {} which '
... | python | {
"resource": ""
} |
q229641 | Node.force_process_ordered | train | def force_process_ordered(self):
"""
Take any messages from replica that have been ordered and process
them, this should be done rarely, like before catchup starts
so a more current LedgerStatus can be sent.
can be called either
1. when node is participating, this happens... | python | {
"resource": ""
} |
q229642 | Node.processEscalatedException | train | def processEscalatedException(self, ex):
"""
Process an exception escalated from a Replica
"""
if isinstance(ex, SuspiciousNode):
self.reportSuspiciousNodeEx(ex)
else:
raise RuntimeError("unhandled replica-escalated exception") from ex | python | {
"resource": ""
} |
q229643 | Node.lost_master_primary | train | def lost_master_primary(self):
"""
Schedule an primary connection check which in turn can send a view
change message
"""
self.primaries_disconnection_times[self.master_replica.instId] = time.perf_counter()
self._schedule_view_change() | python | {
"resource": ""
} |
q229644 | Node.executeBatch | train | def executeBatch(self, three_pc_batch: ThreePcBatch,
valid_reqs_keys: List, invalid_reqs_keys: List,
audit_txn_root) -> None:
"""
Execute the REQUEST sent to this Node
:param view_no: the view number (See glossary)
:param pp_time: the time at wh... | python | {
"resource": ""
} |
q229645 | Node.addNewRole | train | def addNewRole(self, txn):
"""
Adds a new client or steward to this node based on transaction type.
"""
# If the client authenticator is a simple authenticator then add verkey.
# For a custom authenticator, handle appropriately.
# NOTE: The following code should not be u... | python | {
"resource": ""
} |
q229646 | Node.ensureKeysAreSetup | train | def ensureKeysAreSetup(self):
"""
Check whether the keys are setup in the local STP keep.
Raises KeysNotFoundException if not found.
"""
if not areKeysSetup(self.name, self.keys_dir):
raise REx(REx.reason.format(self.name) + self.keygenScript) | python | {
"resource": ""
} |
q229647 | Node.reportSuspiciousNodeEx | train | def reportSuspiciousNodeEx(self, ex: SuspiciousNode):
"""
Report suspicion on a node on the basis of an exception
"""
self.reportSuspiciousNode(ex.node, ex.reason, ex.code, ex.offendingMsg) | python | {
"resource": ""
} |
q229648 | Node.reportSuspiciousNode | train | def reportSuspiciousNode(self,
nodeName: str,
reason=None,
code: int = None,
offendingMsg=None):
"""
Report suspicion on a node and add it to this node's blacklist.
:param nodeNam... | python | {
"resource": ""
} |
q229649 | Node.reportSuspiciousClient | train | def reportSuspiciousClient(self, clientName: str, reason):
"""
Report suspicion on a client and add it to this node's blacklist.
:param clientName: name of the client to report suspicion on
:param reason: the reason for suspicion
"""
logger.warning("{} raised suspicion o... | python | {
"resource": ""
} |
q229650 | Node.blacklistClient | train | def blacklistClient(self, clientName: str,
reason: str = None, code: int = None):
"""
Add the client specified by `clientName` to this node's blacklist
"""
msg = "{} blacklisting client {}".format(self, clientName)
if reason:
msg += " for reaso... | python | {
"resource": ""
} |
q229651 | Node.blacklistNode | train | def blacklistNode(self, nodeName: str, reason: str = None, code: int = None):
"""
Add the node specified by `nodeName` to this node's blacklist
"""
msg = "{} blacklisting node {}".format(self, nodeName)
if reason:
msg += " for reason {}".format(reason)
if code... | python | {
"resource": ""
} |
q229652 | Node.logstats | train | def logstats(self):
"""
Print the node's current statistics to log.
"""
lines = [
"node {} current stats".format(self),
"--------------------------------------------------------",
"node inbox size : {}".format(len(self.nodeInBox)),
... | python | {
"resource": ""
} |
q229653 | Node.logNodeInfo | train | def logNodeInfo(self):
"""
Print the node's info to log for the REST backend to read.
"""
self.nodeInfo['data'] = self.collectNodeInfo()
with closing(open(os.path.join(self.ledger_dir, 'node_info'), 'w')) \
as logNodeInfoFile:
logNodeInfoFile.write(js... | python | {
"resource": ""
} |
q229654 | get_collection_sizes | train | def get_collection_sizes(obj, collections: Optional[Tuple]=None,
get_only_non_empty=False):
"""
Iterates over `collections` of the gives object and gives its byte size
and number of items in collection
"""
from pympler import asizeof
collections = collections or (list, d... | python | {
"resource": ""
} |
q229655 | returns_true_or_raises | train | def returns_true_or_raises(f):
"""A safety net.
Decorator for functions that are only allowed to return True or raise
an exception.
Args:
f: A function whose only expected return value is True.
Returns:
A wrapped functions whose guaranteed only return value is True.
"""
@f... | python | {
"resource": ""
} |
q229656 | Instances.backupIds | train | def backupIds(self) -> Sequence[int]:
"""
Return the list of replicas that don't belong to the master protocol
instance
"""
return [id for id in self.started.keys() if id != 0] | python | {
"resource": ""
} |
q229657 | ViewChanger._hasViewChangeQuorum | train | def _hasViewChangeQuorum(self):
# This method should just be present for master instance.
"""
Checks whether n-f nodes completed view change and whether one
of them is the next primary
"""
num_of_ready_nodes = len(self._view_change_done)
diff = self.quorum - num_o... | python | {
"resource": ""
} |
q229658 | ViewChanger.process_instance_change_msg | train | def process_instance_change_msg(self, instChg: InstanceChange, frm: str) -> None:
"""
Validate and process an instance change request.
:param instChg: the instance change request
:param frm: the name of the node that sent this `msg`
"""
if frm not in self.provider.connec... | python | {
"resource": ""
} |
q229659 | ViewChanger.process_vchd_msg | train | def process_vchd_msg(self, msg: ViewChangeDone, sender: str) -> bool:
"""
Processes ViewChangeDone messages. Once n-f messages have been
received, decides on a primary for specific replica.
:param msg: ViewChangeDone message
:param sender: the name of the node from which this me... | python | {
"resource": ""
} |
q229660 | ViewChanger.sendInstanceChange | train | def sendInstanceChange(self, view_no: int,
suspicion=Suspicions.PRIMARY_DEGRADED):
"""
Broadcast an instance change request to all the remaining nodes
:param view_no: the view number when the instance change is requested
"""
# If not found any sent in... | python | {
"resource": ""
} |
q229661 | ViewChanger._canViewChange | train | def _canViewChange(self, proposedViewNo: int) -> (bool, str):
"""
Return whether there's quorum for view change for the proposed view
number and its view is less than or equal to the proposed view
"""
msg = None
quorum = self.quorums.view_change.value
if not self.... | python | {
"resource": ""
} |
q229662 | ViewChanger.start_view_change | train | def start_view_change(self, proposed_view_no: int, continue_vc=False):
"""
Trigger the view change process.
:param proposed_view_no: the new view number after view change.
"""
# TODO: consider moving this to pool manager
# TODO: view change is a special case, which can h... | python | {
"resource": ""
} |
q229663 | ViewChanger._verify_primary | train | def _verify_primary(self, new_primary, ledger_info):
"""
This method is called when sufficient number of ViewChangeDone
received and makes steps to switch to the new primary
"""
expected_primary = self.provider.next_primary_name()
if new_primary != expected_primary:
... | python | {
"resource": ""
} |
q229664 | ViewChanger._send_view_change_done_message | train | def _send_view_change_done_message(self):
"""
Sends ViewChangeDone message to other protocol participants
"""
new_primary_name = self.provider.next_primary_name()
ledger_summary = self.provider.ledger_summary()
message = ViewChangeDone(self.view_no,
... | python | {
"resource": ""
} |
q229665 | ViewChanger.get_msgs_for_lagged_nodes | train | def get_msgs_for_lagged_nodes(self) -> List[ViewChangeDone]:
# Should not return a list, only done for compatibility with interface
"""
Returns the last accepted `ViewChangeDone` message.
If no view change has happened returns ViewChangeDone
with view no 0 to a newly joined node
... | python | {
"resource": ""
} |
q229666 | FieldBase.validate | train | def validate(self, val):
"""
Performs basic validation of field value and then passes it for
specific validation.
:param val: field value to validate
:return: error message or None
"""
if self.nullable and val is None:
return
type_er = self._... | python | {
"resource": ""
} |
q229667 | DidSigner.sign | train | def sign(self, msg: Dict) -> Dict:
"""
Return a signature for the given message.
"""
ser = serialize_msg_for_signing(msg, topLevelKeysToIgnore=[f.SIG.nm])
bsig = self.naclSigner.signature(ser)
sig = base58.b58encode(bsig).decode("utf-8")
return sig | python | {
"resource": ""
} |
q229668 | Replica.lastPrePrepareSeqNo | train | def lastPrePrepareSeqNo(self, n):
"""
This will _lastPrePrepareSeqNo to values greater than its previous
values else it will not. To forcefully override as in case of `revert`,
directly set `self._lastPrePrepareSeqNo`
"""
if n > self._lastPrePrepareSeqNo:
self... | python | {
"resource": ""
} |
q229669 | Replica.primaryName | train | def primaryName(self, value: Optional[str]) -> None:
"""
Set the value of isPrimary.
:param value: the value to set isPrimary to
"""
if value is not None:
self.warned_no_primary = False
self.primaryNames[self.viewNo] = value
self.compact_primary_names... | python | {
"resource": ""
} |
q229670 | Replica.get_lowest_probable_prepared_certificate_in_view | train | def get_lowest_probable_prepared_certificate_in_view(
self, view_no) -> Optional[int]:
"""
Return lowest pp_seq_no of the view for which can be prepared but
choose from unprocessed PRE-PREPAREs and PREPAREs.
"""
# TODO: Naive implementation, dont need to iterate over ... | python | {
"resource": ""
} |
q229671 | Replica.is_primary_in_view | train | def is_primary_in_view(self, viewNo: int) -> Optional[bool]:
"""
Return whether this replica was primary in the given view
"""
if viewNo not in self.primaryNames:
return False
return self.primaryNames[viewNo] == self.name | python | {
"resource": ""
} |
q229672 | Replica.processReqDuringBatch | train | def processReqDuringBatch(
self,
req: Request,
cons_time: int):
"""
This method will do dynamic validation and apply requests.
If there is any errors during validation it would be raised
"""
if self.isMaster:
self.node.doDynamicVali... | python | {
"resource": ""
} |
q229673 | Replica.serviceQueues | train | def serviceQueues(self, limit=None):
"""
Process `limit` number of messages in the inBox.
:param limit: the maximum number of messages to process
:return: the number of messages successfully processed
"""
# TODO should handle SuspiciousNode here
r = self.dequeue_... | python | {
"resource": ""
} |
q229674 | Replica.tryPrepare | train | def tryPrepare(self, pp: PrePrepare):
"""
Try to send the Prepare message if the PrePrepare message is ready to
be passed into the Prepare phase.
"""
rv, msg = self.canPrepare(pp)
if rv:
self.doPrepare(pp)
else:
self.logger.debug("{} cannot... | python | {
"resource": ""
} |
q229675 | Replica.processPrepare | train | def processPrepare(self, prepare: Prepare, sender: str) -> None:
"""
Validate and process the PREPARE specified.
If validation is successful, create a COMMIT and broadcast it.
:param prepare: a PREPARE msg
:param sender: name of the node that sent the PREPARE
"""
... | python | {
"resource": ""
} |
q229676 | Replica.processCommit | train | def processCommit(self, commit: Commit, sender: str) -> None:
"""
Validate and process the COMMIT specified.
If validation is successful, return the message to the node.
:param commit: an incoming COMMIT message
:param sender: name of the node that sent the COMMIT
"""
... | python | {
"resource": ""
} |
q229677 | Replica.tryCommit | train | def tryCommit(self, prepare: Prepare):
"""
Try to commit if the Prepare message is ready to be passed into the
commit phase.
"""
rv, reason = self.canCommit(prepare)
if rv:
self.doCommit(prepare)
else:
self.logger.debug("{} cannot send COMM... | python | {
"resource": ""
} |
q229678 | Replica.tryOrder | train | def tryOrder(self, commit: Commit):
"""
Try to order if the Commit message is ready to be ordered.
"""
canOrder, reason = self.canOrder(commit)
if canOrder:
self.logger.trace("{} returning request to node".format(self))
self.doOrder(commit)
else:
... | python | {
"resource": ""
} |
q229679 | Replica.nonFinalisedReqs | train | def nonFinalisedReqs(self, reqKeys: List[Tuple[str, int]]):
"""
Check if there are any requests which are not finalised, i.e for
which there are not enough PROPAGATEs
"""
return {key for key in reqKeys if not self.requests.is_finalised(key)} | python | {
"resource": ""
} |
q229680 | Replica._can_process_pre_prepare | train | def _can_process_pre_prepare(self, pre_prepare: PrePrepare, sender: str) -> Optional[int]:
"""
Decide whether this replica is eligible to process a PRE-PREPARE.
:param pre_prepare: a PRE-PREPARE msg to process
:param sender: the name of the node that sent the PRE-PREPARE msg
"""... | python | {
"resource": ""
} |
q229681 | Replica.addToPrePrepares | train | def addToPrePrepares(self, pp: PrePrepare) -> None:
"""
Add the specified PRE-PREPARE to this replica's list of received
PRE-PREPAREs and try sending PREPARE
:param pp: the PRE-PREPARE to add to the list
"""
key = (pp.viewNo, pp.ppSeqNo)
self.prePrepares[key] = p... | python | {
"resource": ""
} |
q229682 | Replica.canPrepare | train | def canPrepare(self, ppReq) -> (bool, str):
"""
Return whether the batch of requests in the PRE-PREPARE can
proceed to the PREPARE step.
:param ppReq: any object with identifier and requestId attributes
"""
if self.has_sent_prepare(ppReq):
return False, 'has ... | python | {
"resource": ""
} |
q229683 | Replica.validatePrepare | train | def validatePrepare(self, prepare: Prepare, sender: str) -> bool:
"""
Return whether the PREPARE specified is valid.
:param prepare: the PREPARE to validate
:param sender: the name of the node that sent the PREPARE
:return: True if PREPARE is valid, False otherwise
"""
... | python | {
"resource": ""
} |
q229684 | Replica.addToPrepares | train | def addToPrepares(self, prepare: Prepare, sender: str):
"""
Add the specified PREPARE to this replica's list of received
PREPAREs and try sending COMMIT
:param prepare: the PREPARE to add to the list
"""
# BLS multi-sig:
self._bls_bft_replica.process_prepare(prep... | python | {
"resource": ""
} |
q229685 | Replica.canCommit | train | def canCommit(self, prepare: Prepare) -> (bool, str):
"""
Return whether the specified PREPARE can proceed to the Commit
step.
Decision criteria:
- If this replica has got just n-f-1 PREPARE requests then commit request.
- If less than n-f-1 PREPARE requests then probab... | python | {
"resource": ""
} |
q229686 | Replica.validateCommit | train | def validateCommit(self, commit: Commit, sender: str) -> bool:
"""
Return whether the COMMIT specified is valid.
:param commit: the COMMIT to validate
:return: True if `request` is valid, False otherwise
"""
key = (commit.viewNo, commit.ppSeqNo)
if not self.has_p... | python | {
"resource": ""
} |
q229687 | Replica.addToCommits | train | def addToCommits(self, commit: Commit, sender: str):
"""
Add the specified COMMIT to this replica's list of received
commit requests.
:param commit: the COMMIT to add to the list
:param sender: the name of the node that sent the COMMIT
"""
# BLS multi-sig:
... | python | {
"resource": ""
} |
q229688 | Replica.canOrder | train | def canOrder(self, commit: Commit) -> Tuple[bool, Optional[str]]:
"""
Return whether the specified commitRequest can be returned to the node.
Decision criteria:
- If have got just n-f Commit requests then return request to node
- If less than n-f of commit requests then probabl... | python | {
"resource": ""
} |
q229689 | Replica.all_prev_ordered | train | def all_prev_ordered(self, commit: Commit):
"""
Return True if all previous COMMITs have been ordered
"""
# TODO: This method does a lot of work, choose correct data
# structures to make it efficient.
viewNo, ppSeqNo = commit.viewNo, commit.ppSeqNo
if self.last_... | python | {
"resource": ""
} |
q229690 | Replica.process_checkpoint | train | def process_checkpoint(self, msg: Checkpoint, sender: str) -> bool:
"""
Process checkpoint messages
:return: whether processed (True) or stashed (False)
"""
self.logger.info('{} processing checkpoint {} from {}'.format(self, msg, sender))
result, reason = self.validator.... | python | {
"resource": ""
} |
q229691 | Replica._process_stashed_pre_prepare_for_time_if_possible | train | def _process_stashed_pre_prepare_for_time_if_possible(
self, key: Tuple[int, int]):
"""
Check if any PRE-PREPAREs that were stashed since their time was not
acceptable, can now be accepted since enough PREPAREs are received
"""
self.logger.debug('{} going to process s... | python | {
"resource": ""
} |
q229692 | Replica._remove_till_caught_up_3pc | train | def _remove_till_caught_up_3pc(self, last_caught_up_3PC):
"""
Remove any 3 phase messages till the last ordered key and also remove
any corresponding request keys
"""
outdated_pre_prepares = {}
for key, pp in self.prePrepares.items():
if compare_3PC_keys(key, ... | python | {
"resource": ""
} |
q229693 | Replica._remove_ordered_from_queue | train | def _remove_ordered_from_queue(self, last_caught_up_3PC=None):
"""
Remove any Ordered that the replica might be sending to node which is
less than or equal to `last_caught_up_3PC` if `last_caught_up_3PC` is
passed else remove all ordered, needed in catchup
"""
to_remove =... | python | {
"resource": ""
} |
q229694 | Replica._remove_stashed_checkpoints | train | def _remove_stashed_checkpoints(self, till_3pc_key=None):
"""
Remove stashed received checkpoints up to `till_3pc_key` if provided,
otherwise remove all stashed received checkpoints
"""
if till_3pc_key is None:
self.stashedRecvdCheckpoints.clear()
self.log... | python | {
"resource": ""
} |
q229695 | checkPortAvailable | train | def checkPortAvailable(ha):
"""Checks whether the given port is available"""
# Not sure why OS would allow binding to one type and not other.
# Checking for port available for TCP and UDP.
sockTypes = (socket.SOCK_DGRAM, socket.SOCK_STREAM)
for typ in sockTypes:
sock = socket.socket(socket.A... | python | {
"resource": ""
} |
q229696 | evenCompare | train | def evenCompare(a: str, b: str) -> bool:
"""
A deterministic but more evenly distributed comparator than simple alphabetical.
Useful when comparing consecutive strings and an even distribution is needed.
Provides an even chance of returning true as often as false
"""
ab = a.encode('utf-8')
b... | python | {
"resource": ""
} |
q229697 | center_band | train | def center_band(close_data, high_data, low_data, period):
"""
Center Band.
Formula:
CB = SMA(TP)
"""
tp = typical_price(close_data, high_data, low_data)
cb = sma(tp, period)
return cb | python | {
"resource": ""
} |
q229698 | simple_moving_average | train | def simple_moving_average(data, period):
"""
Simple Moving Average.
Formula:
SUM(data / N)
"""
catch_errors.check_for_period_error(data, period)
# Mean of Empty Slice RuntimeWarning doesn't affect output so it is
# supressed
with warnings.catch_warnings():
warnings.simplefil... | python | {
"resource": ""
} |
q229699 | average_true_range_percent | train | def average_true_range_percent(close_data, period):
"""
Average True Range Percent.
Formula:
ATRP = (ATR / CLOSE) * 100
"""
catch_errors.check_for_period_error(close_data, period)
atrp = (atr(close_data, period) / np.array(close_data)) * 100
return atrp | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.