_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q229500 | TransactionStore.addToProcessedTxns | train | def addToProcessedTxns(self,
identifier: str,
txnId: str,
reply: Reply) -> None:
"""
Add a client request to the transaction store's list of processed
requests.
"""
self.transactions[txnId] = reply
... | python | {
"resource": ""
} |
q229501 | TransactionStore.append | train | async def append(self, reply: Reply) \
-> None:
"""
Add the given Reply to this transaction store's list of responses.
Also add to processedRequests if not added previously.
"""
result = reply.result
identifier = result.get(f.IDENTIFIER.nm)
txnId = res... | python | {
"resource": ""
} |
q229502 | TransactionStore._isNewTxn | train | def _isNewTxn(self, identifier, reply, txnId) -> bool:
"""
If client is not in `processedRequests` or requestId is not there in
processed requests and txnId is present then its a new reply
"""
return (identifier not in self.processedRequests or
reply.reqId not in ... | python | {
"resource": ""
} |
q229503 | Requests.add | train | def add(self, req: Request):
"""
Add the specified request to this request store.
"""
key = req.key
if key not in self:
self[key] = ReqState(req)
return self[key] | python | {
"resource": ""
} |
q229504 | Requests.ordered_by_replica | train | def ordered_by_replica(self, request_key):
"""
Should be called by each replica when request is ordered or replica is removed.
"""
state = self.get(request_key)
if not state:
return
state.unordered_by_replicas_num -= 1 | python | {
"resource": ""
} |
q229505 | Requests.mark_as_forwarded | train | def mark_as_forwarded(self, req: Request, to: int):
"""
Works together with 'mark_as_executed' and 'free' methods.
It marks request as forwarded to 'to' replicas.
To let request be removed, it should be marked as executed and each of
'to' replicas should call 'free'.
"""... | python | {
"resource": ""
} |
q229506 | Requests.add_propagate | train | def add_propagate(self, req: Request, sender: str):
"""
Add the specified request to the list of received
PROPAGATEs.
:param req: the REQUEST to add
:param sender: the name of the node sending the msg
"""
data = self.add(req)
data.propagates[sender] = req | python | {
"resource": ""
} |
q229507 | Requests.votes | train | def votes(self, req) -> int:
"""
Get the number of propagates for a given reqId and identifier.
"""
try:
votes = len(self[req.key].propagates)
except KeyError:
votes = 0
return votes | python | {
"resource": ""
} |
q229508 | Requests.mark_as_executed | train | def mark_as_executed(self, req: Request):
"""
Works together with 'mark_as_forwarded' and 'free' methods.
It makes request to be removed if all replicas request was
forwarded to freed it.
"""
state = self[req.key]
state.executed = True
self._clean(state) | python | {
"resource": ""
} |
q229509 | Requests.free | train | def free(self, request_key):
"""
Works together with 'mark_as_forwarded' and
'mark_as_executed' methods.
It makes request to be removed if all replicas request was
forwarded to freed it and if request executor marked it as executed.
"""
state = self.get(request_k... | python | {
"resource": ""
} |
q229510 | Requests.has_propagated | train | def has_propagated(self, req: Request, sender: str) -> bool:
"""
Check whether the request specified has already been propagated.
"""
return req.key in self and sender in self[req.key].propagates | python | {
"resource": ""
} |
q229511 | Propagator.propagate | train | def propagate(self, request: Request, clientName):
"""
Broadcast a PROPAGATE to all other nodes
:param request: the REQUEST to propagate
"""
if self.requests.has_propagated(request, self.name):
logger.trace("{} already propagated {}".format(self, request))
el... | python | {
"resource": ""
} |
q229512 | Propagator.createPropagate | train | def createPropagate(
request: Union[Request, dict], client_name) -> Propagate:
"""
Create a new PROPAGATE for the given REQUEST.
:param request: the client REQUEST
:return: a new PROPAGATE msg
"""
if not isinstance(request, (Request, dict)):
logge... | python | {
"resource": ""
} |
q229513 | Propagator.forward | train | def forward(self, request: Request):
"""
Forward the specified client REQUEST to the other replicas on this node
:param request: the REQUEST to propagate
"""
key = request.key
num_replicas = self.replicas.num_replicas
logger.debug('{} forwarding request {} to {} ... | python | {
"resource": ""
} |
q229514 | Propagator.recordAndPropagate | train | def recordAndPropagate(self, request: Request, clientName):
"""
Record the request in the list of requests and propagate.
:param request:
:param clientName:
"""
self.requests.add(request)
self.propagate(request, clientName)
self.tryForwarding(request) | python | {
"resource": ""
} |
q229515 | Propagator.tryForwarding | train | def tryForwarding(self, request: Request):
"""
Try to forward the request if the required conditions are met.
See the method `canForward` for the conditions to check before
forwarding a request.
"""
cannot_reason_msg = self.canForward(request)
if cannot_reason_msg... | python | {
"resource": ""
} |
q229516 | ZStack.removeRemote | train | def removeRemote(self, remote: Remote, clear=True):
"""
Currently not using clear
"""
name = remote.name
pkey = remote.publicKey
vkey = remote.verKey
if name in self.remotes:
self.remotes.pop(name)
self.remotesByKeys.pop(pkey, None)
... | python | {
"resource": ""
} |
q229517 | ZStack.service | train | async def service(self, limit=None, quota: Optional[Quota] = None) -> int:
"""
Service `limit` number of received messages in this stack.
:param limit: the maximum number of messages to be processed. If None,
processes all of the messages in rxMsgs.
:return: the number of messag... | python | {
"resource": ""
} |
q229518 | ZStack.connect | train | def connect(self,
name=None,
remoteId=None,
ha=None,
verKeyRaw=None,
publicKeyRaw=None):
"""
Connect to the node specified by name.
"""
if not name:
raise ValueError('Remote name should be specifi... | python | {
"resource": ""
} |
q229519 | ZStack.reconnectRemote | train | def reconnectRemote(self, remote):
"""
Disconnect remote and connect to it again
:param remote: instance of Remote from self.remotes
:param remoteName: name of remote
:return:
"""
if not isinstance(remote, Remote):
raise PlenumTypeError('remote', remo... | python | {
"resource": ""
} |
q229520 | DbHashStore._readMultiple | train | def _readMultiple(self, start, end, db):
"""
Returns a list of hashes with serial numbers between start
and end, both inclusive.
"""
self._validatePos(start, end)
# Converting any bytearray to bytes
return [bytes(db.get(str(pos))) for pos in range(start, end + 1... | python | {
"resource": ""
} |
q229521 | pack_nibbles | train | def pack_nibbles(nibbles):
"""pack nibbles to binary
:param nibbles: a nibbles sequence. may have a terminator
"""
if nibbles[-1] == NIBBLE_TERMINATOR:
flags = 2
nibbles = nibbles[:-1]
else:
flags = 0
oddlen = len(nibbles) % 2
flags |= oddlen # set lowest bit if ... | python | {
"resource": ""
} |
q229522 | Trie._get_last_node_for_prfx | train | def _get_last_node_for_prfx(self, node, key_prfx, seen_prfx):
""" get last node for the given prefix, also update `seen_prfx` to track the path already traversed
:param node: node in form of list, or BLANK_NODE
:param key_prfx: prefix to look for
:param seen_prfx: prefix already seen, u... | python | {
"resource": ""
} |
q229523 | Monitor.metrics | train | def metrics(self):
"""
Calculate and return the metrics.
"""
masterThrp, backupThrp = self.getThroughputs(self.instances.masterId)
r = self.instance_throughput_ratio(self.instances.masterId)
m = [
("{} Monitor metrics:".format(self), None),
("Delta... | python | {
"resource": ""
} |
q229524 | Monitor.prettymetrics | train | def prettymetrics(self) -> str:
"""
Pretty printing for metrics
"""
rendered = ["{}: {}".format(*m) for m in self.metrics()]
return "\n ".join(rendered) | python | {
"resource": ""
} |
q229525 | Monitor.reset | train | def reset(self):
"""
Reset the monitor. Sets all monitored values to defaults.
"""
logger.debug("{}'s Monitor being reset".format(self))
instances_ids = self.instances.started.keys()
self.numOrderedRequests = {inst_id: (0, 0) for inst_id in instances_ids}
self.req... | python | {
"resource": ""
} |
q229526 | Monitor.addInstance | train | def addInstance(self, inst_id):
"""
Add one protocol instance for monitoring.
"""
self.instances.add(inst_id)
self.requestTracker.add_instance(inst_id)
self.numOrderedRequests[inst_id] = (0, 0)
rm = self.create_throughput_measurement(self.config)
self.thr... | python | {
"resource": ""
} |
q229527 | Monitor.requestOrdered | train | def requestOrdered(self, reqIdrs: List[str], instId: int,
requests, byMaster: bool = False) -> Dict:
"""
Measure the time taken for ordering of a request and return it. Monitor
might have been reset due to view change due to which this method
returns None
"... | python | {
"resource": ""
} |
q229528 | Monitor.requestUnOrdered | train | def requestUnOrdered(self, key: str):
"""
Record the time at which request ordering started.
"""
now = time.perf_counter()
if self.acc_monitor:
self.acc_monitor.update_time(now)
self.acc_monitor.request_received(key)
self.requestTracker.start(key, ... | python | {
"resource": ""
} |
q229529 | Monitor.isMasterDegraded | train | def isMasterDegraded(self):
"""
Return whether the master instance is slow.
"""
if self.acc_monitor:
self.acc_monitor.update_time(time.perf_counter())
return self.acc_monitor.is_master_degraded()
else:
return (self.instances.masterId is not Non... | python | {
"resource": ""
} |
q229530 | Monitor.areBackupsDegraded | train | def areBackupsDegraded(self):
"""
Return slow instance.
"""
slow_instances = []
if self.acc_monitor:
for instance in self.instances.backupIds:
if self.acc_monitor.is_instance_degraded(instance):
slow_instances.append(instance)
... | python | {
"resource": ""
} |
q229531 | Monitor.instance_throughput_ratio | train | def instance_throughput_ratio(self, inst_id):
"""
The relative throughput of an instance compared to the backup
instances.
"""
inst_thrp, otherThrp = self.getThroughputs(inst_id)
# Backup throughput may be 0 so moving ahead only if it is not 0
r = inst_thrp / oth... | python | {
"resource": ""
} |
q229532 | Monitor.is_instance_throughput_too_low | train | def is_instance_throughput_too_low(self, inst_id):
"""
Return whether the throughput of the master instance is greater than the
acceptable threshold
"""
r = self.instance_throughput_ratio(inst_id)
if r is None:
logger.debug("{} instance {} throughput is not "
... | python | {
"resource": ""
} |
q229533 | Monitor.isMasterReqLatencyTooHigh | train | def isMasterReqLatencyTooHigh(self):
"""
Return whether the request latency of the master instance is greater
than the acceptable threshold
"""
# TODO for now, view_change procedure can take more that 15 minutes
# (5 minutes for catchup and 10 minutes for primary's answer... | python | {
"resource": ""
} |
q229534 | Monitor.is_instance_avg_req_latency_too_high | train | def is_instance_avg_req_latency_too_high(self, inst_id):
"""
Return whether the average request latency of an instance is
greater than the acceptable threshold
"""
avg_lat, avg_lat_others = self.getLatencies()
if not avg_lat or not avg_lat_others:
return False... | python | {
"resource": ""
} |
q229535 | Monitor.getThroughputs | train | def getThroughputs(self, desired_inst_id: int):
"""
Return a tuple of the throughput of the given instance and the average
throughput of the remaining instances.
:param instId: the id of the protocol instance
"""
instance_thrp = self.getThroughput(desired_inst_id)
... | python | {
"resource": ""
} |
q229536 | Monitor.getThroughput | train | def getThroughput(self, instId: int) -> float:
"""
Return the throughput of the specified instance.
:param instId: the id of the protocol instance
"""
# We are using the instanceStarted time in the denominator instead of
# a time interval. This is alright for now as all ... | python | {
"resource": ""
} |
q229537 | Monitor.getInstanceMetrics | train | def getInstanceMetrics(
self, forAllExcept: int) -> Tuple[Optional[int], Optional[float]]:
"""
Calculate and return the average throughput of all the instances except
the one specified as `forAllExcept`.
"""
m = [(reqs, tm) for i, (reqs, tm)
in self.numOr... | python | {
"resource": ""
} |
q229538 | Monitor.getLatency | train | def getLatency(self, instId: int) -> float:
"""
Return a dict with client identifier as a key and calculated latency as a value
"""
if len(self.clientAvgReqLatencies) == 0:
return 0.0
return self.clientAvgReqLatencies[instId].get_avg_latency() | python | {
"resource": ""
} |
q229539 | Batched._enqueue | train | def _enqueue(self, msg: Any, rid: int, signer: Signer) -> None:
"""
Enqueue the message into the remote's queue.
:param msg: the message to enqueue
:param rid: the id of the remote node
"""
if rid not in self.outBoxes:
self.outBoxes[rid] = deque()
sel... | python | {
"resource": ""
} |
q229540 | Batched._enqueueIntoAllRemotes | train | def _enqueueIntoAllRemotes(self, msg: Any, signer: Signer) -> None:
"""
Enqueue the specified message into all the remotes in the nodestack.
:param msg: the message to enqueue
"""
for rid in self.remotes.keys():
self._enqueue(msg, rid, signer) | python | {
"resource": ""
} |
q229541 | Batched.send | train | def send(self,
msg: Any, *
rids: Iterable[int],
signer: Signer = None,
message_splitter=None) -> None:
"""
Enqueue the given message into the outBoxes of the specified remotes
or into the outBoxes of all the remotes if rids is None
:pa... | python | {
"resource": ""
} |
q229542 | Batched.flushOutBoxes | train | def flushOutBoxes(self) -> None:
"""
Clear the outBoxes and transmit batched messages to remotes.
"""
removedRemotes = []
for rid, msgs in self.outBoxes.items():
try:
dest = self.remotes[rid].name
except KeyError:
removedRem... | python | {
"resource": ""
} |
q229543 | Looper.prodAllOnce | train | async def prodAllOnce(self):
"""
Call `prod` once for each Prodable in this Looper
:return: the sum of the number of events executed successfully
"""
# TODO: looks like limit is always None???
limit = None
s = 0
for n in self.prodables:
s += a... | python | {
"resource": ""
} |
q229544 | Looper.add | train | def add(self, prodable: Prodable) -> None:
"""
Add one Prodable object to this Looper's list of Prodables
:param prodable: the Prodable object to add
"""
if prodable.name in [p.name for p in self.prodables]:
raise ProdableAlreadyAdded("Prodable {} already added.".
... | python | {
"resource": ""
} |
q229545 | Looper.removeProdable | train | def removeProdable(self, prodable: Prodable=None, name: str=None) -> Optional[Prodable]:
"""
Remove the specified Prodable object from this Looper's list of Prodables
:param prodable: the Prodable to remove
"""
if prodable:
self.prodables.remove(prodable)
... | python | {
"resource": ""
} |
q229546 | Looper.runOnceNicely | train | async def runOnceNicely(self):
"""
Execute `runOnce` with a small tolerance of 0.01 seconds so that the Prodables
can complete their other asynchronous tasks not running on the event-loop.
"""
start = time.perf_counter()
msgsProcessed = await self.prodAllOnce()
if... | python | {
"resource": ""
} |
q229547 | Looper.run | train | def run(self, *coros: CoroWrapper):
"""
Runs an arbitrary list of coroutines in order and then quits the loop,
if not running as a context manager.
"""
if not self.running:
raise RuntimeError("not running!")
async def wrapper():
results = []
... | python | {
"resource": ""
} |
q229548 | Looper.shutdown | train | async def shutdown(self):
"""
Shut down this Looper.
"""
logger.display("Looper shutting down now...", extra={"cli": False})
self.running = False
start = time.perf_counter()
if not self.runFut.done():
await self.runFut
self.stopall()
lo... | python | {
"resource": ""
} |
q229549 | create_default_bls_bft_factory | train | def create_default_bls_bft_factory(node):
'''
Creates a default BLS factory to instantiate BLS BFT classes.
:param node: Node instance
:return: BLS factory instance
'''
bls_keys_dir = os.path.join(node.keys_dir, node.name)
bls_crypto_factory = create_default_bls_crypto_factory(bls_keys_dir)... | python | {
"resource": ""
} |
q229550 | SigningKey.sign | train | def sign(self, message, encoder=encoding.RawEncoder):
"""
Sign a message using this key.
:param message: [:class:`bytes`] The data to be signed.
:param encoder: A class that is used to encode the signed message.
:rtype: :class:`~SignedMessage`
"""
raw_signed = li... | python | {
"resource": ""
} |
q229551 | Verifier.verify | train | def verify(self, signature, msg):
'''
Verify the message
'''
if not self.key:
return False
try:
self.key.verify(signature + msg)
except ValueError:
return False
return True | python | {
"resource": ""
} |
q229552 | Box.encrypt | train | def encrypt(self, plaintext, nonce, encoder=encoding.RawEncoder):
"""
Encrypts the plaintext message using the given `nonce` and returns
the ciphertext encoded with the encoder.
.. warning:: It is **VITALLY** important that the nonce is a nonce,
i.e. it is a number used only... | python | {
"resource": ""
} |
q229553 | Box.decrypt | train | def decrypt(self, ciphertext, nonce=None, encoder=encoding.RawEncoder):
"""
Decrypts the ciphertext using the given nonce and returns the
plaintext message.
:param ciphertext: [:class:`bytes`] The encrypted message to decrypt
:param nonce: [:class:`bytes`] The nonce used when en... | python | {
"resource": ""
} |
q229554 | Privateer.decrypt | train | def decrypt(self, cipher, nonce, pubkey, dehex=False):
'''
Return decrypted msg contained in cypher using nonce and shared key
generated from .key and pubkey.
If pubkey is hex encoded it is converted first
If dehex is True then use HexEncoder otherwise use RawEncoder
Int... | python | {
"resource": ""
} |
q229555 | getInstalledConfig | train | def getInstalledConfig(installDir, configFile):
"""
Reads config from the installation directory of Plenum.
:param installDir: installation directory of Plenum
:param configFile: name of the configuration file
:raises: FileNotFoundError
:return: the configuration as a python object
"""
... | python | {
"resource": ""
} |
q229556 | _getConfig | train | def _getConfig(general_config_dir: str = None):
"""
Reads a file called config.py in the project directory
:raises: FileNotFoundError
:return: the configuration as a python object
"""
stp_config = STPConfig()
plenum_config = import_module("plenum.config")
config = stp_config
config.... | python | {
"resource": ""
} |
q229557 | Router.getFunc | train | def getFunc(self, o: Any) -> Callable:
"""
Get the next function from the list of routes that is capable of
processing o's type.
:param o: the object to process
:return: the next function
"""
for cls, func in self.routes.items():
if isinstance(o, cls)... | python | {
"resource": ""
} |
q229558 | Router.handleSync | train | def handleSync(self, msg: Any) -> Any:
"""
Pass the message as an argument to the function defined in `routes`.
If the msg is a tuple, pass the values as multiple arguments to the function.
:param msg: tuple of object and callable
"""
# If a plain python tuple and not a ... | python | {
"resource": ""
} |
q229559 | Router.handle | train | async def handle(self, msg: Any) -> Any:
"""
Handle both sync and async functions.
:param msg: a message
:return: the result of execution of the function corresponding to this message's type
"""
res = self.handleSync(msg)
if isawaitable(res):
return a... | python | {
"resource": ""
} |
q229560 | Router.handleAll | train | async def handleAll(self, deq: deque, limit=None) -> int:
"""
Handle all items in a deque. Can call asynchronous handlers.
:param deq: a deque of items to be handled by this router
:param limit: the number of items in the deque to the handled
:return: the number of items handled... | python | {
"resource": ""
} |
q229561 | Router.handleAllSync | train | def handleAllSync(self, deq: deque, limit=None) -> int:
"""
Synchronously handle all items in a deque.
:param deq: a deque of items to be handled by this router
:param limit: the number of items in the deque to the handled
:return: the number of items handled successfully
... | python | {
"resource": ""
} |
q229562 | CompactMerkleTree.load | train | def load(self, other: merkle_tree.MerkleTree):
"""Load this tree from a dumb data object for serialisation.
The object must have attributes tree_size:int and hashes:list.
"""
self._update(other.tree_size, other.hashes) | python | {
"resource": ""
} |
q229563 | CompactMerkleTree.save | train | def save(self, other: merkle_tree.MerkleTree):
"""Save this tree into a dumb data object for serialisation.
The object must have attributes tree_size:int and hashes:list.
"""
other.__tree_size = self.__tree_size
other.__hashes = self.__hashes | python | {
"resource": ""
} |
q229564 | CompactMerkleTree.append | train | def append(self, new_leaf: bytes) -> List[bytes]:
"""Append a new leaf onto the end of this tree and return the
audit path"""
auditPath = list(reversed(self.__hashes))
self._push_subtree([new_leaf])
return auditPath | python | {
"resource": ""
} |
q229565 | CompactMerkleTree.extend | train | def extend(self, new_leaves: List[bytes]):
"""Extend this tree with new_leaves on the end.
The algorithm works by using _push_subtree() as a primitive, calling
it with the maximum number of allowed leaves until we can add the
remaining leaves as a valid entire (non-full) subtree in one ... | python | {
"resource": ""
} |
q229566 | CompactMerkleTree.extended | train | def extended(self, new_leaves: List[bytes]):
"""Returns a new tree equal to this tree extended with new_leaves."""
new_tree = self.__copy__()
new_tree.extend(new_leaves)
return new_tree | python | {
"resource": ""
} |
q229567 | CompactMerkleTree.verify_consistency | train | def verify_consistency(self, expected_leaf_count) -> bool:
"""
Check that the tree has same leaf count as expected and the
number of nodes are also as expected
"""
if expected_leaf_count != self.leafCount:
raise ConsistencyVerificationFailed()
if self.get_expe... | python | {
"resource": ""
} |
q229568 | isHex | train | def isHex(val: str) -> bool:
"""
Return whether the given str represents a hex value or not
:param val: the string to check
:return: whether the given str represents a hex value
"""
if isinstance(val, bytes):
# only decodes utf-8 string
try:
val = val.decode()
... | python | {
"resource": ""
} |
q229569 | EMALatencyMeasurementForEachClient._accumulate | train | def _accumulate(self, old_accum, next_val):
"""
Implement exponential moving average
"""
return old_accum * (1 - self.alpha) + next_val * self.alpha | python | {
"resource": ""
} |
q229570 | HashStore.getNodePosition | train | def getNodePosition(cls, start, height=None) -> int:
"""
Calculates node position based on start and height
:param start: The sequence number of the first leaf under this tree.
:param height: Height of this node in the merkle tree
:return: the node's position
"""
... | python | {
"resource": ""
} |
q229571 | HashStore.getPath | train | def getPath(cls, seqNo, offset=0):
"""
Get the audit path of the leaf at the position specified by serNo.
:param seqNo: sequence number of the leaf to calculate the path for
:param offset: the sequence number of the node from where the path
should begin.
:return: tuple ... | python | {
"resource": ""
} |
q229572 | HashStore.readNodeByTree | train | def readNodeByTree(self, start, height=None):
"""
Fetches nodeHash based on start leaf and height of the node in the tree.
:return: the nodeHash
"""
pos = self.getNodePosition(start, height)
return self.readNode(pos) | python | {
"resource": ""
} |
q229573 | HashStore.is_consistent | train | def is_consistent(self) -> bool:
"""
Returns True if number of nodes are consistent with number of leaves
"""
from ledger.compact_merkle_tree import CompactMerkleTree
return self.nodeCount == CompactMerkleTree.get_expected_node_count(
self.leafCount) | python | {
"resource": ""
} |
q229574 | ChunkedFileStore._startNextChunk | train | def _startNextChunk(self) -> None:
"""
Close current and start next chunk
"""
if self.currentChunk is None:
self._useLatestChunk()
else:
self._useChunk(self.currentChunkIndex + self.chunkSize) | python | {
"resource": ""
} |
q229575 | ChunkedFileStore.get | train | def get(self, key) -> str:
"""
Determines the file to retrieve the data from and retrieves the data.
:return: value corresponding to specified key
"""
# TODO: get is creating files when a key is given which is more than
# the store size
chunk_no, offset = self._g... | python | {
"resource": ""
} |
q229576 | ChunkedFileStore.reset | train | def reset(self) -> None:
"""
Clear all data in file storage.
"""
self.close()
for f in os.listdir(self.dataDir):
os.remove(os.path.join(self.dataDir, f))
self._useLatestChunk() | python | {
"resource": ""
} |
q229577 | ChunkedFileStore._listChunks | train | def _listChunks(self):
"""
Lists stored chunks
:return: sorted list of available chunk indices
"""
chunks = []
for fileName in os.listdir(self.dataDir):
index = ChunkedFileStore._fileNameToChunkIndex(fileName)
if index is not None:
... | python | {
"resource": ""
} |
q229578 | PrimaryDecider.filterMsgs | train | def filterMsgs(self, wrappedMsgs: deque) -> deque:
"""
Filters messages by view number so that only the messages that have the
current view number are retained.
:param wrappedMsgs: the messages to filter
"""
filtered = deque()
while wrappedMsgs:
wrapp... | python | {
"resource": ""
} |
q229579 | PluginLoader.get | train | def get(self, name):
"""Retrieve a plugin by name."""
try:
return self.plugins[name]
except KeyError:
raise RuntimeError("plugin {} does not exist".format(name)) | python | {
"resource": ""
} |
q229580 | VersionBase.cmp | train | def cmp(cls, v1: 'VersionBase', v2: 'VersionBase') -> int:
""" Compares two instances. """
# TODO types checking
if v1._version > v2._version:
return 1
elif v1._version == v2._version:
return 0
else:
return -1 | python | {
"resource": ""
} |
q229581 | KITZStack.maintainConnections | train | def maintainConnections(self, force=False):
"""
Ensure appropriate connections.
"""
now = time.perf_counter()
if now < self.nextCheck and not force:
return False
self.nextCheck = now + (self.config.RETRY_TIMEOUT_NOT_RESTRICTED
... | python | {
"resource": ""
} |
q229582 | KITZStack.connectToMissing | train | def connectToMissing(self) -> set:
"""
Try to connect to the missing nodes
"""
missing = self.reconcileNodeReg()
if not missing:
return missing
logger.info("{}{} found the following missing connections: {}".
format(CONNECTION_PREFIX, self... | python | {
"resource": ""
} |
q229583 | CallbackHandler.emit | train | def emit(self, record):
"""
Passes the log record back to the CLI for rendering
"""
should_cb = None
attr_val = None
if hasattr(record, self.typestr):
attr_val = getattr(record, self.typestr)
should_cb = bool(attr_val)
if should_cb is None ... | python | {
"resource": ""
} |
q229584 | KITNetworkInterface.conns | train | def conns(self, value: Set[str]) -> None:
"""
Updates the connection count of this node if not already done.
"""
if not self._conns == value:
old = self._conns
self._conns = value
ins = value - old
outs = old - value
logger.disp... | python | {
"resource": ""
} |
q229585 | KITNetworkInterface.findInNodeRegByHA | train | def findInNodeRegByHA(self, remoteHa):
"""
Returns the name of the remote by HA if found in the node registry, else
returns None
"""
regName = [nm for nm, ha in self.registry.items()
if self.sameAddr(ha, remoteHa)]
if len(regName) > 1:
raise... | python | {
"resource": ""
} |
q229586 | KITNetworkInterface.getRemoteName | train | def getRemoteName(self, remote):
"""
Returns the name of the remote object if found in node registry.
:param remote: the remote object
"""
if remote.name not in self.registry:
find = [name for name, ha in self.registry.items()
if ha == remote.ha]
... | python | {
"resource": ""
} |
q229587 | KITNetworkInterface.notConnectedNodes | train | def notConnectedNodes(self) -> Set[str]:
"""
Returns the names of nodes in the registry this node is NOT connected
to.
"""
return set(self.registry.keys()) - self.conns | python | {
"resource": ""
} |
q229588 | MultiZapAuthenticator.start | train | def start(self):
"""Create and bind the ZAP socket"""
self.zap_socket = self.context.socket(zmq.REP)
self.zap_socket.linger = 1
zapLoc = 'inproc://zeromq.zap.{}'.format(MultiZapAuthenticator.count)
self.zap_socket.bind(zapLoc)
self.log.debug('Starting ZAP at {}'.format(za... | python | {
"resource": ""
} |
q229589 | MultiZapAuthenticator.stop | train | def stop(self):
"""Close the ZAP socket"""
if self.zap_socket:
self.log.debug(
'Stopping ZAP at {}'.format(self.zap_socket.LAST_ENDPOINT))
super().stop() | python | {
"resource": ""
} |
q229590 | AsyncioAuthenticator.start | train | def start(self):
"""Start ZAP authentication"""
super().start()
self.__poller = zmq.asyncio.Poller()
self.__poller.register(self.zap_socket, zmq.POLLIN)
self.__task = asyncio.ensure_future(self.__handle_zap()) | python | {
"resource": ""
} |
q229591 | AsyncioAuthenticator.stop | train | def stop(self):
"""Stop ZAP authentication"""
if self.__task:
self.__task.cancel()
if self.__poller:
self.__poller.unregister(self.zap_socket)
self.__poller = None
super().stop() | python | {
"resource": ""
} |
q229592 | randomString | train | def randomString(size: int = 20) -> str:
"""
Generate a random string in hex of the specified size
DO NOT use python provided random class its a Pseudo Random Number Generator
and not secure enough for our needs
:param size: size of the random string to generate
:return: the hexadecimal random... | python | {
"resource": ""
} |
q229593 | mostCommonElement | train | def mostCommonElement(elements: Iterable[T], to_hashable_f: Callable=None):
"""
Find the most frequent element of a collection.
:param elements: An iterable of elements
:param to_hashable_f: (optional) if defined will be used to get
hashable presentation for non-hashable elements. Otherwise jso... | python | {
"resource": ""
} |
q229594 | objSearchReplace | train | def objSearchReplace(obj: Any,
toFrom: Dict[Any, Any],
checked: Set[Any]=None,
logMsg: str=None,
deepLevel: int=None) -> None:
"""
Search for an attribute in an object and replace it with another.
:param obj: the object to ... | python | {
"resource": ""
} |
q229595 | runall | train | async def runall(corogen):
"""
Run an array of coroutines
:param corogen: a generator that generates coroutines
:return: list or returns of the coroutines
"""
results = []
for c in corogen:
result = await c
results.append(result)
return results | python | {
"resource": ""
} |
q229596 | prime_gen | train | def prime_gen() -> int:
# credit to David Eppstein, Wolfgang Beneicke, Paul Hofstra
"""
A generator for prime numbers starting from 2.
"""
D = {}
yield 2
for q in itertools.islice(itertools.count(3), 0, None, 2):
p = D.pop(q, None)
if p is None:
D[q * q] = 2 * q
... | python | {
"resource": ""
} |
q229597 | untilTrue | train | async def untilTrue(condition, *args, timeout=5) -> bool:
"""
Keep checking the condition till it is true or a timeout is reached
:param condition: the condition to check (a function that returns bool)
:param args: the arguments to the condition
:return: True if the condition is met in the given ti... | python | {
"resource": ""
} |
q229598 | ClientZStack.transmitToClient | train | def transmitToClient(self, msg: Any, remoteName: str):
"""
Transmit the specified message to the remote client specified by `remoteName`.
:param msg: a message
:param remoteName: the name of the remote
"""
payload = self.prepForSending(msg)
try:
if is... | python | {
"resource": ""
} |
q229599 | CatchupRepService._has_valid_catchup_replies | train | def _has_valid_catchup_replies(self, seq_no: int, txns_to_process: List[Tuple[int, Any]]) -> Tuple[bool, str, int]:
"""
Transforms transactions for ledger!
Returns:
Whether catchup reply corresponding to seq_no
Name of node from which txns came
Number of tran... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.