INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Parse a string such as 'foo/bar/*.py'
Assumes is_pattern(s) has been called and returned True
1. directory to process
2. pattern to match | def parse_pattern(s):
"""Parse a string such as 'foo/bar/*.py'
Assumes is_pattern(s) has been called and returned True
1. directory to process
2. pattern to match"""
if '{' in s:
return None, None # Unsupported by fnmatch
if s and s[0] == '~':
s = os.path.expanduser(s)
parts... |
On success return an absolute path and a pattern.
Otherwise print a message and return None, None | def validate_pattern(fn):
"""On success return an absolute path and a pattern.
Otherwise print a message and return None, None
"""
directory, pattern = parse_pattern(fn)
if directory is None:
print_err("Invalid pattern {}.".format(fn))
return None, None
target = resolve_path(dire... |
Return a list of paths matching a pattern (or None on error). | def process_pattern(fn):
"""Return a list of paths matching a pattern (or None on error).
"""
directory, pattern = validate_pattern(fn)
if directory is not None:
filenames = fnmatch.filter(auto(listdir, directory), pattern)
if filenames:
return [directory + '/' + sfn for sfn ... |
Resolves path and converts it into an absolute path. | def resolve_path(path):
"""Resolves path and converts it into an absolute path."""
if path[0] == '~':
# ~ or ~user
path = os.path.expanduser(path)
if path[0] != '/':
# Relative path
if cur_dir[-1] == '/':
path = cur_dir + path
else:
path = cur_... |
Determines if a given file is located locally or remotely. We assume
that any directories from the pyboard take precedence over local
directories of the same name. /flash and /sdcard are associated with
the default device. /dev_name/path where dev_name is the name of a
given device is also c... | def get_dev_and_path(filename):
"""Determines if a given file is located locally or remotely. We assume
that any directories from the pyboard take precedence over local
directories of the same name. /flash and /sdcard are associated with
the default device. /dev_name/path where dev_name is the ... |
Prints a string or converts bytes to a string and then prints. | def print_bytes(byte_str):
"""Prints a string or converts bytes to a string and then prints."""
if isinstance(byte_str, str):
print(byte_str)
else:
print(str(byte_str, encoding='utf8')) |
Decorator which adds extra functions to be downloaded to the pyboard. | def extra_funcs(*funcs):
"""Decorator which adds extra functions to be downloaded to the pyboard."""
def extra_funcs_decorator(real_func):
def wrapper(*args, **kwargs):
return real_func(*args, **kwargs)
wrapper.extra_funcs = list(funcs)
wrapper.source = inspect.getsource(real_func)
wrapper.nam... |
If `filename` is a remote file, then this function calls func on the
micropython board, otherwise it calls it locally. | def auto(func, filename, *args, **kwargs):
"""If `filename` is a remote file, then this function calls func on the
micropython board, otherwise it calls it locally.
"""
dev, dev_filename = get_dev_and_path(filename)
if dev is None:
if len(dev_filename) > 0 and dev_filename[0] == '~':
... |
Returns the boards name (if available). | def board_name(default):
"""Returns the boards name (if available)."""
try:
import board
try:
name = board.name
except AttributeError:
# There was a board.py file, but it didn't have an name attribute
# We also ignore this as an error
name ... |
Copies the contents of the indicated file to an already opened file. | def cat(src_filename, dst_file):
"""Copies the contents of the indicated file to an already opened file."""
(dev, dev_filename) = get_dev_and_path(src_filename)
if dev is None:
with open(dev_filename, 'rb') as txtfile:
for line in txtfile:
dst_file.write(line)
else:
... |
Copies a file from one place to another. Both the source and destination
files must exist on the same machine. | def copy_file(src_filename, dst_filename):
"""Copies a file from one place to another. Both the source and destination
files must exist on the same machine.
"""
try:
with open(src_filename, 'rb') as src_file:
with open(dst_filename, 'wb') as dst_file:
while True:
... |
Copies one file to another. The source file may be local or remote and
the destination file may be local or remote. | def cp(src_filename, dst_filename):
"""Copies one file to another. The source file may be local or remote and
the destination file may be local or remote.
"""
src_dev, src_dev_filename = get_dev_and_path(src_filename)
dst_dev, dst_dev_filename = get_dev_and_path(dst_filename)
if src_dev is ds... |
Returns os.stat for a given file, adjusting the timestamps as appropriate. | def stat(filename):
"""Returns os.stat for a given file, adjusting the timestamps as appropriate."""
import os
try:
# on the host, lstat won't try to follow symlinks
rstat = os.lstat(filename)
except:
rstat = os.stat(filename)
return rstat[:7] + tuple(tim + TIME_OFFSET for ti... |
Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash. | def listdir_matches(match):
"""Returns a list of filenames contained in the named directory.
Only filenames which start with `match` will be returned.
Directories will have a trailing slash.
"""
import os
last_slash = match.rfind('/')
if last_slash == -1:
dirname = '.'
... |
Returns a list of tuples for each file contained in the named
directory, or None if the directory does not exist. Each tuple
contains the filename, followed by the tuple returned by
calling os.stat on the filename. | def listdir_stat(dirname, show_hidden=True):
"""Returns a list of tuples for each file contained in the named
directory, or None if the directory does not exist. Each tuple
contains the filename, followed by the tuple returned by
calling os.stat on the filename.
"""
import os
try:
... |
Removes a file or directory. | def remove_file(filename, recursive=False, force=False):
"""Removes a file or directory."""
import os
try:
mode = os.stat(filename)[0]
if mode & 0x4000 != 0:
# directory
if recursive:
for file in os.listdir(filename):
success = remo... |
Removes a file or directory tree. | def rm(filename, recursive=False, force=False):
"""Removes a file or directory tree."""
return auto(remove_file, filename, recursive, force) |
Creates a directory. Produces information in case of dry run.
Issues error where necessary. | def make_dir(dst_dir, dry_run, print_func, recursed):
"""Creates a directory. Produces information in case of dry run.
Issues error where necessary.
"""
parent = os.path.split(dst_dir.rstrip('/'))[0] # Check for nonexistent parent
parent_files = auto(listdir_stat, parent) if parent else True # Relat... |
Synchronizes 2 directory trees. | def rsync(src_dir, dst_dir, mirror, dry_run, print_func, recursed, sync_hidden):
"""Synchronizes 2 directory trees."""
# This test is a hack to avoid errors when accessing /flash. When the
# cache synchronisation issue is solved it should be removed
if not isinstance(src_dir, str) or not len(src_dir):
... |
Function which runs on the pyboard. Matches up with send_file_to_remote. | def recv_file_from_host(src_file, dst_filename, filesize, dst_mode='wb'):
"""Function which runs on the pyboard. Matches up with send_file_to_remote."""
import sys
import ubinascii
if HAS_BUFFER:
try:
import pyb
usb = pyb.USB_VCP()
except:
try:
... |
Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with recv_file_from_host. | def send_file_to_remote(dev, src_file, dst_filename, filesize, dst_mode='wb'):
"""Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with recv_file_from_host.
"""
bytes_remaining = filesize
save_timeout = dev.timeout
dev.timeout = 1
while bytes_remaining ... |
Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with send_file_to_host. | def recv_file_from_remote(dev, src_filename, dst_file, filesize):
"""Intended to be passed to the `remote` function as the xfer_func argument.
Matches up with send_file_to_host.
"""
bytes_remaining = filesize
if not HAS_BUFFER:
bytes_remaining *= 2 # hexlify makes each byte into 2
bu... |
Function which runs on the pyboard. Matches up with recv_file_from_remote. | def send_file_to_host(src_filename, dst_file, filesize):
"""Function which runs on the pyboard. Matches up with recv_file_from_remote."""
import sys
import ubinascii
try:
with open(src_filename, 'rb') as src_file:
bytes_remaining = filesize
if HAS_BUFFER:
... |
Takes a single column of words, and prints it as multiple columns that
will fit in termwidth columns. | def print_cols(words, print_func, termwidth=79):
"""Takes a single column of words, and prints it as multiple columns that
will fit in termwidth columns.
"""
width = max([word_len(word) for word in words])
nwords = len(words)
ncols = max(1, (termwidth + 1) // (width + 1))
nrows = (nwords + n... |
Takes a filename and the stat info and returns the decorated filename.
The decoration takes the form of a single character which follows
the filename. Currently, the only decoration is '/' for directories. | def decorated_filename(filename, stat):
"""Takes a filename and the stat info and returns the decorated filename.
The decoration takes the form of a single character which follows
the filename. Currently, the only decoration is '/' for directories.
"""
mode = stat[0]
if mode_isdir(mode):
... |
Prints detailed information about the file passed in. | def print_long(filename, stat, print_func):
"""Prints detailed information about the file passed in."""
size = stat_size(stat)
mtime = stat_mtime(stat)
file_mtime = time.localtime(mtime)
curr_time = time.time()
if mtime > (curr_time + SIX_MONTHS) or mtime < (curr_time - SIX_MONTHS):
prin... |
Tries to connect automagically via network or serial. | def connect(port, baud=115200, user='micro', password='python', wait=0):
"""Tries to connect automagically via network or serial."""
try:
ip_address = socket.gethostbyname(port)
#print('Connecting to ip', ip_address)
connect_telnet(port, ip_address, user=user, password=password)
exce... |
Connect to a MicroPython board via telnet. | def connect_telnet(name, ip_address=None, user='micro', password='python'):
"""Connect to a MicroPython board via telnet."""
if ip_address is None:
try:
ip_address = socket.gethostbyname(name)
except socket.gaierror:
ip_address = name
if not QUIET:
if name == ... |
Connect to a MicroPython board via a serial port. | def connect_serial(port, baud=115200, wait=0):
"""Connect to a MicroPython board via a serial port."""
if not QUIET:
print('Connecting to %s (buffer-size %d)...' % (port, BUFFER_SIZE))
try:
dev = DeviceSerial(port, baud, wait)
except DeviceError as err:
sys.stderr.write(str(err))... |
The main program. | def real_main():
"""The main program."""
global RTS
global DTR
try:
default_baud = int(os.getenv('RSHELL_BAUD'))
except:
default_baud = 115200
default_port = os.getenv('RSHELL_PORT')
default_rts = os.getenv('RSHELL_RTS') or RTS
default_dtr = os.getenv('RSHELL_DTR') or DTR... |
This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns. | def main():
"""This main function saves the stdin termios settings, calls real_main,
and restores stdin termios settings when it returns.
"""
save_settings = None
stdin_fd = -1
try:
import termios
stdin_fd = sys.stdin.fileno()
save_settings = termios.tcgetattr(stdin_fd... |
Closes the serial port. | def close(self):
"""Closes the serial port."""
if self.pyb and self.pyb.serial:
self.pyb.serial.close()
self.pyb = None |
Determines if 'filename' corresponds to a directory on this device. | def is_root_path(self, filename):
"""Determines if 'filename' corresponds to a directory on this device."""
test_filename = filename + '/'
for root_dir in self.root_dirs:
if test_filename.startswith(root_dir):
return True
return False |
Reads data from the pyboard over the serial port. | def read(self, num_bytes):
"""Reads data from the pyboard over the serial port."""
self.check_pyb()
try:
return self.pyb.serial.read(num_bytes)
except (serial.serialutil.SerialException, TypeError):
# Write failed - assume that we got disconnected
self... |
Calls func with the indicated args on the micropython board. | def remote(self, func, *args, xfer_func=None, **kwargs):
"""Calls func with the indicated args on the micropython board."""
global HAS_BUFFER
HAS_BUFFER = self.has_buffer
if hasattr(func, 'extra_funcs'):
func_name = func.name
func_lines = []
for extra_func i... |
Calls func with the indicated args on the micropython board, and
converts the response back into python by using eval. | def remote_eval(self, func, *args, **kwargs):
"""Calls func with the indicated args on the micropython board, and
converts the response back into python by using eval.
"""
return eval(self.remote(func, *args, **kwargs)) |
Calls func with the indicated args on the micropython board, and
converts the response back into python by using eval. | def remote_eval_last(self, func, *args, **kwargs):
"""Calls func with the indicated args on the micropython board, and
converts the response back into python by using eval.
"""
result = self.remote(func, *args, **kwargs).split(b'\r\n')
messages = result[0:-2]
messages ... |
Sets the time on the pyboard to match the time on the host. | def sync_time(self):
"""Sets the time on the pyboard to match the time on the host."""
now = time.localtime(time.time())
self.remote(set_time, (now.tm_year, now.tm_mon, now.tm_mday, now.tm_wday + 1,
now.tm_hour, now.tm_min, now.tm_sec, 0))
return now |
Writes data to the pyboard over the serial port. | def write(self, buf):
"""Writes data to the pyboard over the serial port."""
self.check_pyb()
try:
return self.pyb.serial.write(buf)
except (serial.serialutil.SerialException, BrokenPipeError, TypeError):
# Write failed - assume that we got disconnected
... |
Sets the timeout associated with the serial port. | def timeout(self, value):
"""Sets the timeout associated with the serial port."""
self.check_pyb()
try:
self.pyb.serial.timeout = value
except:
# timeout is a property so it calls code, and that can fail
# if the serial port is closed.
pass |
Override onecmd.
1 - So we don't have to have a do_EOF method.
2 - So we can strip comments
3 - So we can track line numbers | def onecmd(self, line):
"""Override onecmd.
1 - So we don't have to have a do_EOF method.
2 - So we can strip comments
3 - So we can track line numbers
"""
if DEBUG:
print('Executing "%s"' % line)
self.line_num += 1
if line == "EOF" or line ==... |
Convenience function so you don't need to remember to put the \n
at the end of the line. | def print(self, *args, end='\n', file=None):
"""Convenience function so you don't need to remember to put the \n
at the end of the line.
"""
if file is None:
file = self.stdout
s = ' '.join(str(arg) for arg in args) + end
file.write(s) |
Wrapper for catching exceptions since cmd seems to silently
absorb them. | def filename_complete(self, text, line, begidx, endidx):
"""Wrapper for catching exceptions since cmd seems to silently
absorb them.
"""
try:
return self.real_filename_complete(text, line, begidx, endidx)
except:
traceback.print_exc() |
Figure out what filenames match the completion. | def real_filename_complete(self, text, line, begidx, endidx):
"""Figure out what filenames match the completion."""
# line contains the full command line that's been entered so far.
# text contains the portion of the line that readline is trying to complete
# text should correspond to l... |
Figure out what directories match the completion. | def directory_complete(self, text, line, begidx, endidx):
"""Figure out what directories match the completion."""
return [filename for filename in self.filename_complete(text, line, begidx, endidx) if filename[-1] == '/'] |
This will convert the line passed into the do_xxx functions into
an array of arguments and handle the Output Redirection Operator. | def line_to_args(self, line):
"""This will convert the line passed into the do_xxx functions into
an array of arguments and handle the Output Redirection Operator.
"""
# Note: using shlex.split causes quoted substrings to stay together.
args = shlex.split(line)
self.redir... |
args [arguments...]
Debug function for verifying argument parsing. This function just
prints out each argument that it receives. | def do_args(self, line):
"""args [arguments...]
Debug function for verifying argument parsing. This function just
prints out each argument that it receives.
"""
args = self.line_to_args(line)
for idx in range(len(args)):
self.print("arg[%d] = '%s'" % (i... |
boards
Lists the boards that rshell is currently connected to. | def do_boards(self, _):
"""boards
Lists the boards that rshell is currently connected to.
"""
rows = []
with DEV_LOCK:
for dev in DEVS:
if dev is DEFAULT_DEV:
dirs = [dir[:-1] for dir in dev.root_dirs]
else:
... |
cat FILENAME...
Concatenates files and sends to stdout. | def do_cat(self, line):
"""cat FILENAME...
Concatenates files and sends to stdout.
"""
# note: when we get around to supporting cat from stdin, we'll need
# to write stdin to a temp file, and then copy the file
# since we need to know the filesize when cop... |
cd DIRECTORY
Changes the current directory. ~ expansion is supported, and cd -
goes to the previous directory. | def do_cd(self, line):
"""cd DIRECTORY
Changes the current directory. ~ expansion is supported, and cd -
goes to the previous directory.
"""
args = self.line_to_args(line)
if len(args) == 0:
dirname = '~'
else:
if args[0] == '-':
... |
connect TYPE TYPE_PARAMS
connect serial port [baud]
connect telnet ip-address-or-name
Connects a pyboard to rshell. | def do_connect(self, line):
"""connect TYPE TYPE_PARAMS
connect serial port [baud]
connect telnet ip-address-or-name
Connects a pyboard to rshell.
"""
args = self.line_to_args(line)
num_args = len(args)
if num_args < 1:
print_err('Mis... |
cp SOURCE DEST Copy a single SOURCE file to DEST file.
cp SOURCE... DIRECTORY Copy multiple SOURCE files to a directory.
cp [-r|--recursive] [SOURCE|SOURCE_DIR]... DIRECTORY
cp [-r] PATTERN DIRECTORY Copy matching files to DIRECTORY.
The destination must be a dire... | def do_cp(self, line):
"""cp SOURCE DEST Copy a single SOURCE file to DEST file.
cp SOURCE... DIRECTORY Copy multiple SOURCE files to a directory.
cp [-r|--recursive] [SOURCE|SOURCE_DIR]... DIRECTORY
cp [-r] PATTERN DIRECTORY Copy matching files to DIRECTORY.
... |
echo TEXT...
Display a line of text. | def do_echo(self, line):
"""echo TEXT...
Display a line of text.
"""
args = self.line_to_args(line)
self.print(*args) |
edit FILE
Copies the file locally, launches an editor to edit the file.
When the editor exits, if the file was modified then its copied
back.
You can specify the editor used with the --editor command line
option when you start rshell, or by using the VISUAL or ED... | def do_edit(self, line):
"""edit FILE
Copies the file locally, launches an editor to edit the file.
When the editor exits, if the file was modified then its copied
back.
You can specify the editor used with the --editor command line
option when you start ... |
filesize FILE
Prints the size of the file, in bytes. This function is primarily
for testing. | def do_filesize(self, line):
"""filesize FILE
Prints the size of the file, in bytes. This function is primarily
for testing.
"""
if len(line) == 0:
print_err("Must provide a filename")
return
filename = resolve_path(line)
self.print(... |
filetype FILE
Prints the type of file (dir or file). This function is primarily
for testing. | def do_filetype(self, line):
"""filetype FILE
Prints the type of file (dir or file). This function is primarily
for testing.
"""
if len(line) == 0:
print_err("Must provide a filename")
return
filename = resolve_path(line)
mode = auto... |
help [COMMAND]
List available commands with no arguments, or detailed help when
a command is provided. | def do_help(self, line):
"""help [COMMAND]
List available commands with no arguments, or detailed help when
a command is provided.
"""
# We provide a help function so that we can trim the leading spaces
# from the docstrings. The builtin help function doesn't do th... |
ls [-a] [-l] [FILE|DIRECTORY|PATTERN]...
PATTERN supports * ? [seq] [!seq] Unix filename matching
List directory contents. | def do_ls(self, line):
"""ls [-a] [-l] [FILE|DIRECTORY|PATTERN]...
PATTERN supports * ? [seq] [!seq] Unix filename matching
List directory contents.
"""
args = self.line_to_args(line)
if len(args.filenames) == 0:
args.filenames = ['.']
for idx, fn i... |
mkdir DIRECTORY...
Creates one or more directories. | def do_mkdir(self, line):
"""mkdir DIRECTORY...
Creates one or more directories.
"""
args = self.line_to_args(line)
for filename in args:
filename = resolve_path(filename)
if not mkdir(filename):
print_err('Unable to create %s' % filena... |
Runs as a thread which has a sole purpose of readding bytes from
the serial port and writing them to stdout. Used by do_repl. | def repl_serial_to_stdout(self, dev):
"""Runs as a thread which has a sole purpose of readding bytes from
the serial port and writing them to stdout. Used by do_repl.
"""
with self.serial_reader_running:
try:
save_timeout = dev.timeout
# Set... |
repl [board-name] [~ line [~]]
Enters into the regular REPL with the MicroPython board.
Use Control-X to exit REPL mode and return the shell. It may take
a second or two before the REPL exits.
If you provide a line to the REPL command, then that will be executed.
... | def do_repl(self, line):
"""repl [board-name] [~ line [~]]
Enters into the regular REPL with the MicroPython board.
Use Control-X to exit REPL mode and return the shell. It may take
a second or two before the REPL exits.
If you provide a line to the REPL command, th... |
rm [-f|--force] FILE... Remove one or more files
rm [-f|--force] PATTERN Remove multiple files
rm -r [-f|--force] [FILE|DIRECTORY]... Files and/or directories
rm -r [-f|--force] PATTERN Multiple files and/or directories
Removes files or directories. To remo... | def do_rm(self, line):
"""rm [-f|--force] FILE... Remove one or more files
rm [-f|--force] PATTERN Remove multiple files
rm -r [-f|--force] [FILE|DIRECTORY]... Files and/or directories
rm -r [-f|--force] PATTERN Multiple files and/or directories
Rem... |
rsync [-m|--mirror] [-n|--dry-run] [-q|--quiet] SRC_DIR DEST_DIR
Synchronizes a destination directory tree with a source directory tree. | def do_rsync(self, line):
"""rsync [-m|--mirror] [-n|--dry-run] [-q|--quiet] SRC_DIR DEST_DIR
Synchronizes a destination directory tree with a source directory tree.
"""
args = self.line_to_args(line)
src_dir = resolve_path(args.src_dir)
dst_dir = resolve_path(args.ds... |
Set the status of the motor to the specified value if not already set. | def set_status(self, value):
"""
Set the status of the motor to the specified value if not already set.
"""
if not self._status == value:
old = self._status
self._status = value
logger.info("{} changing status from {} to {}".format(self, old.name, valu... |
Set the status to Status.stopping and also call `onStopping`
with the provided args and kwargs. | def stop(self, *args, **kwargs):
"""
Set the status to Status.stopping and also call `onStopping`
with the provided args and kwargs.
"""
if self.status in (Status.stopping, Status.stopped):
logger.debug("{} is already {}".format(self, self.status.name))
else:
... |
Returns name and corresponding instance name of the next node which
is supposed to be a new Primary for backup instance in round-robin
fashion starting from primary of master instance. | def next_primary_replica_name_for_backup(self, instance_id, master_primary_rank,
primaries, node_reg, node_ids):
"""
Returns name and corresponding instance name of the next node which
is supposed to be a new Primary for backup instance in round-robin... |
Returns name and corresponding instance name of the next node which
is supposed to be a new Primary. In fact it is not round-robin on
this abstraction layer as currently the primary of master instance is
pointed directly depending on view number, instance id and total
number of nodes.
... | def next_primary_replica_name_for_master(self, node_reg, node_ids):
"""
Returns name and corresponding instance name of the next node which
is supposed to be a new Primary. In fact it is not round-robin on
this abstraction layer as currently the primary of master instance is
poin... |
Build a set of names of primaries, it is needed to avoid
duplicates of primary nodes for different replicas. | def process_selection(self, instance_count, node_reg, node_ids):
# Select primaries for current view_no
if instance_count == 0:
return []
'''
Build a set of names of primaries, it is needed to avoid
duplicates of primary nodes for different replicas.
'''
... |
Count the number of stewards added to the pool transaction store
Note: This is inefficient, a production use case of this function
should require an efficient storage mechanism | def countStewards(self) -> int:
"""
Count the number of stewards added to the pool transaction store
Note: This is inefficient, a production use case of this function
should require an efficient storage mechanism
"""
# THIS SHOULD NOT BE DONE FOR PRODUCTION
return... |
Get a value (and proof optionally)for the given path in state trie.
Does not return the proof is there is no aggregate signature for it.
:param path: the path generate a state proof for
:param head_hash: the root to create the proof against
:param get_value: whether to return the value
... | def get_value_from_state(self, path, head_hash=None, with_proof=False, multi_sig=None):
'''
Get a value (and proof optionally)for the given path in state trie.
Does not return the proof is there is no aggregate signature for it.
:param path: the path generate a state proof for
:p... |
Takes all Ordered messages from outbox out of turn | def take_ordereds_out_of_turn(self) -> tuple:
"""
Takes all Ordered messages from outbox out of turn
"""
for replica in self._replicas.values():
yield replica.instId, replica._remove_ordered_from_queue() |
Create a new replica with the specified parameters. | def _new_replica(self, instance_id: int, is_master: bool, bls_bft: BlsBft) -> Replica:
"""
Create a new replica with the specified parameters.
"""
return self._replica_class(self._node, instance_id, self._config, is_master, bls_bft, self._metrics) |
Restore removed replicas to requiredNumberOfInstances
:return: | def restore_replicas(self) -> None:
'''
Restore removed replicas to requiredNumberOfInstances
:return:
'''
self.backup_instances_faulty.clear()
for inst_id in range(self.node.requiredNumberOfInstances):
if inst_id not in self.node.replicas.keys():
... |
The method for sending BackupInstanceFaulty messages
if backups instances performance were degraded
:param degraded_backups: list of backup instances
ids which performance were degraded
:return: | def on_backup_degradation(self, degraded_backups) -> None:
'''
The method for sending BackupInstanceFaulty messages
if backups instances performance were degraded
:param degraded_backups: list of backup instances
ids which performance were degraded
:return:
'''
... |
The method for sending BackupInstanceFaulty messages
if backup primary disconnected
:param degraded_backups: list of backup instances
ids which performance were degraded
:return: | def on_backup_primary_disconnected(self, degraded_backups) -> None:
'''
The method for sending BackupInstanceFaulty messages
if backup primary disconnected
:param degraded_backups: list of backup instances
ids which performance were degraded
:return:
'''
s... |
The method for processing BackupInstanceFaulty from nodes
and removing replicas with performance were degraded
:param backup_faulty: BackupInstanceFaulty message with instances for removing
:param frm:
:return: | def process_backup_instance_faulty_msg(self,
backup_faulty: BackupInstanceFaulty,
frm: str) -> None:
'''
The method for processing BackupInstanceFaulty from nodes
and removing replicas with performance were deg... |
Return value of the the following polynomial.
.. math::
(a * e^(b*steps) - 1) / (e^b - 1)
:param a: multiplier
:param b: exponent multiplier
:param steps: the number of steps | def _sumSeries(a: float, b: float, steps: int) -> float:
"""
Return value of the the following polynomial.
.. math::
(a * e^(b*steps) - 1) / (e^b - 1)
:param a: multiplier
:param b: exponent multiplier
:param steps: the number of steps
"""
retu... |
Finds a b-value (common ratio) that satisfies a total duration within
1 millisecond. Not terribly efficient, so using lru_cache. Don't know
a way to compute the common ratio when the sum of a finite geometric
series is known. Found myself needing to factor polynomials with an
arbitrarily... | def goalDuration(start: float, steps: int, total: float) -> float:
"""
Finds a b-value (common ratio) that satisfies a total duration within
1 millisecond. Not terribly efficient, so using lru_cache. Don't know
a way to compute the common ratio when the sum of a finite geometric
... |
Acquires lock for action.
:return: True and 0.0 if lock successfully acquired or False and number of seconds to wait before the next try | def acquire(self):
"""
Acquires lock for action.
:return: True and 0.0 if lock successfully acquired or False and number of seconds to wait before the next try
"""
now = self.get_current_time()
logger.debug("now: {}, len(actionsLog): {}".format(
now, len(self... |
Decorator which helps in creating lazy properties | def lazy_field(prop):
"""
Decorator which helps in creating lazy properties
"""
@property
def wrapper(self):
if self not in _lazy_value_cache:
_lazy_value_cache[self] = {}
self_cache = _lazy_value_cache[self]
if prop in self_cache:
return self_cache[pr... |
Transform a client request such that it can be stored in the ledger.
Also this is what will be returned to the client in the reply
:param req:
:return: | def reqToTxn(req):
"""
Transform a client request such that it can be stored in the ledger.
Also this is what will be returned to the client in the reply
:param req:
:return:
"""
if isinstance(req, str):
req = json.loads(req)
if isinstance(req, dict):
kwargs = dict(
... |
Return the names of the remote nodes this node is connected to.
Not all of these nodes may be used for communication
(as opposed to conns property) | def connecteds(self) -> Set[str]:
"""
Return the names of the remote nodes this node is connected to.
Not all of these nodes may be used for communication
(as opposed to conns property)
"""
return {r.name for r in self.remotes.values()
if self.isRemoteCon... |
Find the remote by name or ha.
:param name: the name of the remote to find
:param ha: host address pair the remote to find
:raises: RemoteNotFound | def getRemote(self, name: str = None, ha: HA = None):
"""
Find the remote by name or ha.
:param name: the name of the remote to find
:param ha: host address pair the remote to find
:raises: RemoteNotFound
"""
return self.findInRemotesByName(name) if name else \
... |
Find the remote by name.
:param name: the name of the remote to find
:raises: RemoteNotFound | def findInRemotesByName(self, name: str):
"""
Find the remote by name.
:param name: the name of the remote to find
:raises: RemoteNotFound
"""
remotes = [r for r in self.remotes.values()
if r.name == name]
if len(remotes) > 1:
raise... |
Remove the remote by name.
:param name: the name of the remote to remove
:raises: RemoteNotFound | def removeRemoteByName(self, name: str) -> int:
"""
Remove the remote by name.
:param name: the name of the remote to remove
:raises: RemoteNotFound
"""
remote = self.getRemote(name)
rid = remote.uid
self.removeRemote(remote)
return rid |
Check whether the two arguments correspond to the same address | def sameAddr(self, ha, ha2) -> bool:
"""
Check whether the two arguments correspond to the same address
"""
if ha == ha2:
return True
if ha[1] != ha2[1]:
return False
return ha[0] in self.localips and ha2[0] in self.localips |
Partitions the remotes into connected and disconnected
:return: tuple(connected remotes, disconnected remotes) | def remotesByConnected(self):
"""
Partitions the remotes into connected and disconnected
:return: tuple(connected remotes, disconnected remotes)
"""
conns, disconns = [], []
for r in self.remotes.values():
array = conns if self.isRemoteConnected(r) else disco... |
Service at most `limit` messages from the inBox.
:param limit: the maximum number of messages to service
:return: the number of messages successfully processed | async def serviceQueues(self, limit=None) -> int:
"""
Service at most `limit` messages from the inBox.
:param limit: the maximum number of messages to service
:return: the number of messages successfully processed
"""
return await self._inbox_router.handleAll(self._inbox... |
Adds signer to the wallet.
Requires complete signer, identifier or seed.
:param identifier: signer identifier or None to use random one
:param seed: signer key seed or None to use random one
:param signer: signer to add
:param alias: a friendly readable name for the signer
... | def addIdentifier(self,
identifier=None,
seed=None,
signer=None,
alias=None,
didMethodName=None):
"""
Adds signer to the wallet.
Requires complete signer, identifier or seed.
:p... |
Update signer for an already present identifier. The passed signer
should have the same identifier as `identifier` or an error is raised.
Also if the existing identifier has an alias in the wallet then the
passed signer is given the same alias
:param identifier: existing identifier in th... | def updateSigner(self, identifier, signer):
"""
Update signer for an already present identifier. The passed signer
should have the same identifier as `identifier` or an error is raised.
Also if the existing identifier has an alias in the wallet then the
passed signer is given the... |
Checks whether signer identifier specified, or can it be
inferred from alias or can be default used instead
:param idr:
:param alias:
:param other:
:return: signer identifier | def requiredIdr(self,
idr: Identifier=None,
alias: str=None):
"""
Checks whether signer identifier specified, or can it be
inferred from alias or can be default used instead
:param idr:
:param alias:
:param other:
:return:... |
Creates signature for message using specified signer
:param msg: message to sign
:param identifier: signer identifier
:param otherIdentifier:
:return: signature that then can be assigned to request | def signMsg(self,
msg: Dict,
identifier: Identifier=None,
otherIdentifier: Identifier=None):
"""
Creates signature for message using specified signer
:param msg: message to sign
:param identifier: signer identifier
:param otherIden... |
Signs request. Modifies reqId and signature. May modify identifier.
:param req: request
:param requestIdStore: request id generator
:param identifier: signer identifier
:return: signed request | def signRequest(self,
req: Request,
identifier: Identifier=None) -> Request:
"""
Signs request. Modifies reqId and signature. May modify identifier.
:param req: request
:param requestIdStore: request id generator
:param identifier: signer ... |
Signs the message if a signer is configured
:param identifier: signing identifier; if not supplied the default for
the wallet is used.
:param op: Operation to be signed
:return: a signed Request object | def signOp(self,
op: Dict,
identifier: Identifier=None) -> Request:
"""
Signs the message if a signer is configured
:param identifier: signing identifier; if not supplied the default for
the wallet is used.
:param op: Operation to be signed
... |
For each signer in this wallet, return its alias if present else
return its identifier.
:param exclude:
:return: List of identifiers/aliases. | def listIds(self, exclude=list()):
"""
For each signer in this wallet, return its alias if present else
return its identifier.
:param exclude:
:return: List of identifiers/aliases.
"""
lst = list(self.aliasesToIds.keys())
others = set(self.idsToSigners.ke... |
Save wallet into specified localtion.
Returns the canonical path for the ``fpath`` where ``wallet``
has been stored.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- directory part of ``fpath`` exists and it's not a directory -
... | def saveWallet(self, wallet, fpath):
"""Save wallet into specified localtion.
Returns the canonical path for the ``fpath`` where ``wallet``
has been stored.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- directory part of ``fp... |
Load wallet from specified localtion.
Returns loaded wallet.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- ``fpath`` exists and it's a directory - IsADirectoryError raised
:param fpath: wallet file path, absolute or relative to
... | def loadWallet(self, fpath):
"""Load wallet from specified localtion.
Returns loaded wallet.
Error cases:
- ``fpath`` is not inside the keyrings base dir - ValueError raised
- ``fpath`` exists and it's a directory - IsADirectoryError raised
:param fpath: wallet... |
Add the specified PREPARE to this replica's list of received
PREPAREs.
:param prepare: the PREPARE to add to the list
:param voter: the name of the node who sent the PREPARE | def addVote(self, prepare: Prepare, voter: str) -> None:
"""
Add the specified PREPARE to this replica's list of received
PREPAREs.
:param prepare: the PREPARE to add to the list
:param voter: the name of the node who sent the PREPARE
"""
self._add_msg(prepare, v... |
Add the specified COMMIT to this replica's list of received
COMMITs.
:param commit: the COMMIT to add to the list
:param voter: the name of the replica who sent the COMMIT | def addVote(self, commit: Commit, voter: str) -> None:
"""
Add the specified COMMIT to this replica's list of received
COMMITs.
:param commit: the COMMIT to add to the list
:param voter: the name of the replica who sent the COMMIT
"""
super()._add_msg(commit, vot... |
Discard a message and log a reason using the specified `logMethod`.
:param msg: the message to discard
:param reason: the reason why this message is being discarded
:param logMethod: the logging function to be used
:param cliOutput: if truthy, informs a CLI that the logged msg should
... | def discard(self, msg, reason, logMethod=logging.error, cliOutput=False):
"""
Discard a message and log a reason using the specified `logMethod`.
:param msg: the message to discard
:param reason: the reason why this message is being discarded
:param logMethod: the logging functi... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.