_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q229400 | Resource.close | train | def close(self):
"""Closes the VISA session and marks the handle as invalid.
"""
try:
logger.debug('%s - closing', self._resource_name,
extra=self._logging_extra)
self.before_close()
self.visalib.close(self.session)
logger.... | python | {
"resource": ""
} |
q229401 | Resource.install_handler | train | def install_handler(self, event_type, handler, user_handle=None):
"""Installs handlers for event callbacks in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be installed by a client application.
:param user_ha... | python | {
"resource": ""
} |
q229402 | Resource.uninstall_handler | train | def uninstall_handler(self, event_type, handler, user_handle=None):
"""Uninstalls handlers for events in this resource.
:param event_type: Logical event identifier.
:param handler: Interpreted as a valid reference to a handler to be uninstalled by a client application.
:param user_handl... | python | {
"resource": ""
} |
q229403 | Resource.discard_events | train | def discard_events(self, event_type, mechanism):
"""Discards event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be dicarded.
(Constants.VI_QU... | python | {
"resource": ""
} |
q229404 | Resource.enable_event | train | def enable_event(self, event_type, mechanism, context=None):
"""Enable event occurrences for specified event types and mechanisms in this resource.
:param event_type: Logical event identifier.
:param mechanism: Specifies event handling mechanisms to be enabled.
(Consta... | python | {
"resource": ""
} |
q229405 | Resource.wait_on_event | train | def wait_on_event(self, in_event_type, timeout, capture_timeout=False):
"""Waits for an occurrence of the specified event in this resource.
:param in_event_type: Logical identifier of the event(s) to wait for.
:param timeout: Absolute time period in time units that the resource shall wait for a... | python | {
"resource": ""
} |
q229406 | Resource.lock | train | def lock(self, timeout='default', requested_key=None):
"""Establish a shared lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to ... | python | {
"resource": ""
} |
q229407 | Resource.lock_excl | train | def lock_excl(self, timeout='default'):
"""Establish an exclusive lock to the resource.
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.timeou... | python | {
"resource": ""
} |
q229408 | Resource.lock_context | train | def lock_context(self, timeout='default', requested_key='exclusive'):
"""A context that locks
:param timeout: Absolute time period (in milliseconds) that a resource
waits to get unlocked by the locking session before
returning an error. (Defaults to self.... | python | {
"resource": ""
} |
q229409 | PrettyTable.del_row | train | def del_row(self, row_index):
"""Delete a row to the table
Arguments:
row_index - The index of the row you want to delete. Indexing starts at 0."""
if row_index > len(self._rows)-1:
raise Exception("Cant delete row at index %d, table only has %d rows!" % (row_index, len(... | python | {
"resource": ""
} |
q229410 | PrettyTable.get_html_string | train | def get_html_string(self, **kwargs):
"""Return string representation of HTML formatted version of table in current state.
Arguments:
start - index of first data row to include in output
end - index of last data row to include in output PLUS ONE (list slice style)
fields - name... | python | {
"resource": ""
} |
q229411 | TableHandler.make_fields_unique | train | def make_fields_unique(self, fields):
"""
iterates over the row and make each field unique
"""
for i in range(0, len(fields)):
for j in range(i+1, len(fields)):
if fields[i] == fields[j]:
fields[j] += "'" | python | {
"resource": ""
} |
q229412 | meta_request | train | def meta_request(func):
""" Handles parsing response structure and translating API Exceptions """
def inner(self, resource, *args, **kwargs):
serialize_response = kwargs.pop('serialize', True)
try:
resp = func(self, resource, *args, **kwargs)
except ApiException as e:
... | python | {
"resource": ""
} |
q229413 | DynamicClient.watch | train | def watch(self, resource, namespace=None, name=None, label_selector=None, field_selector=None, resource_version=None, timeout=None):
"""
Stream events for a resource from the Kubernetes API
:param resource: The API resource object that will be used to query the API
:param namespace: The... | python | {
"resource": ""
} |
q229414 | DynamicClient.validate | train | def validate(self, definition, version=None, strict=False):
"""validate checks a kubernetes resource definition
Args:
definition (dict): resource definition
version (str): version of kubernetes to validate against
strict (bool): whether unexpected additional properti... | python | {
"resource": ""
} |
q229415 | Discoverer.parse_api_groups | train | def parse_api_groups(self, request_resources=False, update=False):
""" Discovers all API groups present in the cluster """
if not self._cache.get('resources') or update:
self._cache['resources'] = self._cache.get('resources', {})
groups_response = load_json(self.client.request('G... | python | {
"resource": ""
} |
q229416 | Discoverer.get | train | def get(self, **kwargs):
""" Same as search, but will throw an error if there are multiple or no
results. If there are multiple results and only one is an exact match
on api_version, that resource will be returned.
"""
results = self.search(**kwargs)
# If there ar... | python | {
"resource": ""
} |
q229417 | add_device | train | def add_device(dev):
"""Adds a device to the list of devices we know about."""
global DEV_IDX, DEFAULT_DEV
with DEV_LOCK:
for idx in range(len(DEVS)):
test_dev = DEVS[idx]
if test_dev.dev_name_short == dev.dev_name_short:
# This device is already in our list. ... | python | {
"resource": ""
} |
q229418 | find_device_by_name | train | def find_device_by_name(name):
"""Tries to find a board by board name."""
if not name:
return DEFAULT_DEV
with DEV_LOCK:
for dev in DEVS:
if dev.name == name:
return dev
return None | python | {
"resource": ""
} |
q229419 | is_micropython_usb_device | train | def is_micropython_usb_device(port):
"""Checks a USB device to see if it looks like a MicroPython device.
"""
if type(port).__name__ == 'Device':
# Assume its a pyudev.device.Device
if ('ID_BUS' not in port or port['ID_BUS'] != 'usb' or
'SUBSYSTEM' not in port or port['SUBSYSTEM'... | python | {
"resource": ""
} |
q229420 | is_micropython_usb_port | train | def is_micropython_usb_port(portName):
"""Checks to see if the indicated portname is a MicroPython device
or not.
"""
for port in serial.tools.list_ports.comports():
if port.device == portName:
return is_micropython_usb_device(port)
return False | python | {
"resource": ""
} |
q229421 | autoconnect | train | def autoconnect():
"""Sets up a thread to detect when USB devices are plugged and unplugged.
If the device looks like a MicroPython board, then it will automatically
connect to it.
"""
if not USE_AUTOCONNECT:
return
try:
import pyudev
except ImportError:
return
... | python | {
"resource": ""
} |
q229422 | autoconnect_thread | train | def autoconnect_thread(monitor):
"""Thread which detects USB Serial devices connecting and disconnecting."""
monitor.start()
monitor.filter_by('tty')
epoll = select.epoll()
epoll.register(monitor.fileno(), select.POLLIN)
while True:
try:
events = epoll.poll()
except... | python | {
"resource": ""
} |
q229423 | extra_info | train | def extra_info(port):
"""Collects the serial nunber and manufacturer into a string, if
the fields are available."""
extra_items = []
if port.manufacturer:
extra_items.append("vendor '{}'".format(port.manufacturer))
if port.serial_number:
extra_items.append("serial '{}'".format(por... | python | {
"resource": ""
} |
q229424 | listports | train | def listports():
"""listports will display a list of all of the serial ports.
"""
detected = False
for port in serial.tools.list_ports.comports():
detected = True
if port.vid:
micropythonPort = ''
if is_micropython_usb_device(port):
micropythonPort... | python | {
"resource": ""
} |
q229425 | escape | train | def escape(str):
"""Precede all special characters with a backslash."""
out = ''
for char in str:
if char in '\\ ':
out += '\\'
out += char
return out | python | {
"resource": ""
} |
q229426 | align_cell | train | def align_cell(fmt, elem, width):
"""Returns an aligned element."""
if fmt == "<":
return elem + ' ' * (width - len(elem))
if fmt == ">":
return ' ' * (width - len(elem)) + elem
return elem | python | {
"resource": ""
} |
q229427 | print_err | train | def print_err(*args, end='\n'):
"""Similar to print, but prints to stderr.
"""
print(*args, end=end, file=sys.stderr)
sys.stderr.flush() | python | {
"resource": ""
} |
q229428 | validate_pattern | train | 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... | python | {
"resource": ""
} |
q229429 | resolve_path | train | 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_... | python | {
"resource": ""
} |
q229430 | print_bytes | train | 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')) | python | {
"resource": ""
} |
q229431 | extra_funcs | train | 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... | python | {
"resource": ""
} |
q229432 | auto | train | 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] == '~':
... | python | {
"resource": ""
} |
q229433 | cat | train | 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:
... | python | {
"resource": ""
} |
q229434 | copy_file | train | 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:
... | python | {
"resource": ""
} |
q229435 | cp | train | 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... | python | {
"resource": ""
} |
q229436 | stat | train | 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... | python | {
"resource": ""
} |
q229437 | listdir_matches | train | 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 = '.'
... | python | {
"resource": ""
} |
q229438 | listdir_stat | train | 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:
... | python | {
"resource": ""
} |
q229439 | remove_file | train | 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... | python | {
"resource": ""
} |
q229440 | rm | train | def rm(filename, recursive=False, force=False):
"""Removes a file or directory tree."""
return auto(remove_file, filename, recursive, force) | python | {
"resource": ""
} |
q229441 | make_dir | train | 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... | python | {
"resource": ""
} |
q229442 | recv_file_from_host | train | 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:
... | python | {
"resource": ""
} |
q229443 | send_file_to_remote | train | 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 ... | python | {
"resource": ""
} |
q229444 | recv_file_from_remote | train | 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... | python | {
"resource": ""
} |
q229445 | send_file_to_host | train | 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:
... | python | {
"resource": ""
} |
q229446 | print_cols | train | 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... | python | {
"resource": ""
} |
q229447 | print_long | train | 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... | python | {
"resource": ""
} |
q229448 | connect | train | 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... | python | {
"resource": ""
} |
q229449 | connect_telnet | train | 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 == ... | python | {
"resource": ""
} |
q229450 | connect_serial | train | 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))... | python | {
"resource": ""
} |
q229451 | main | train | 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... | python | {
"resource": ""
} |
q229452 | Device.close | train | def close(self):
"""Closes the serial port."""
if self.pyb and self.pyb.serial:
self.pyb.serial.close()
self.pyb = None | python | {
"resource": ""
} |
q229453 | Device.is_root_path | train | 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 | python | {
"resource": ""
} |
q229454 | Device.read | train | 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... | python | {
"resource": ""
} |
q229455 | Device.remote | train | 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... | python | {
"resource": ""
} |
q229456 | Device.sync_time | train | 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 | python | {
"resource": ""
} |
q229457 | Device.write | train | 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
... | python | {
"resource": ""
} |
q229458 | DeviceSerial.timeout | train | 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 | python | {
"resource": ""
} |
q229459 | Shell.onecmd | train | 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 ==... | python | {
"resource": ""
} |
q229460 | Shell.print | train | 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) | python | {
"resource": ""
} |
q229461 | Shell.filename_complete | train | 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() | python | {
"resource": ""
} |
q229462 | Shell.real_filename_complete | train | 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... | python | {
"resource": ""
} |
q229463 | Shell.directory_complete | train | 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] == '/'] | python | {
"resource": ""
} |
q229464 | Shell.line_to_args | train | 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... | python | {
"resource": ""
} |
q229465 | Shell.do_cat | train | 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... | python | {
"resource": ""
} |
q229466 | Shell.do_echo | train | def do_echo(self, line):
"""echo TEXT...
Display a line of text.
"""
args = self.line_to_args(line)
self.print(*args) | python | {
"resource": ""
} |
q229467 | Shell.do_mkdir | train | 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... | python | {
"resource": ""
} |
q229468 | Shell.repl_serial_to_stdout | train | 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... | python | {
"resource": ""
} |
q229469 | Motor.set_status | train | 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... | python | {
"resource": ""
} |
q229470 | Motor.stop | train | 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:
... | python | {
"resource": ""
} |
q229471 | PrimarySelector.next_primary_replica_name_for_master | train | 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... | python | {
"resource": ""
} |
q229472 | PrimarySelector.next_primary_replica_name_for_backup | train | 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... | python | {
"resource": ""
} |
q229473 | PrimarySelector.process_selection | train | 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.
'''
... | python | {
"resource": ""
} |
q229474 | Replicas.take_ordereds_out_of_turn | train | 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() | python | {
"resource": ""
} |
q229475 | Replicas._new_replica | train | 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) | python | {
"resource": ""
} |
q229476 | Throttler.acquire | train | 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... | python | {
"resource": ""
} |
q229477 | lazy_field | train | 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... | python | {
"resource": ""
} |
q229478 | NetworkInterface.getRemote | train | 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 \
... | python | {
"resource": ""
} |
q229479 | NetworkInterface.findInRemotesByName | train | 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... | python | {
"resource": ""
} |
q229480 | NetworkInterface.removeRemoteByName | train | 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 | python | {
"resource": ""
} |
q229481 | NetworkInterface.sameAddr | train | 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 | python | {
"resource": ""
} |
q229482 | NetworkInterface.remotesByConnected | train | 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... | python | {
"resource": ""
} |
q229483 | Wallet.addIdentifier | train | 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... | python | {
"resource": ""
} |
q229484 | Wallet.requiredIdr | train | 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:... | python | {
"resource": ""
} |
q229485 | Wallet.signMsg | train | 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... | python | {
"resource": ""
} |
q229486 | Wallet.signRequest | train | 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 ... | python | {
"resource": ""
} |
q229487 | Wallet.signOp | train | 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
... | python | {
"resource": ""
} |
q229488 | Wallet.listIds | train | 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... | python | {
"resource": ""
} |
q229489 | WalletStorageHelper.saveWallet | train | 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... | python | {
"resource": ""
} |
q229490 | WalletStorageHelper.loadWallet | train | 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... | python | {
"resource": ""
} |
q229491 | Prepares.addVote | train | 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... | python | {
"resource": ""
} |
q229492 | Commits.addVote | train | 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... | python | {
"resource": ""
} |
q229493 | MessageProcessor.discard | train | 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... | python | {
"resource": ""
} |
q229494 | MessageProcessor.toDict | train | def toDict(self, msg: Dict) -> Dict:
"""
Return a dictionary form of the message
:param msg: the message to be sent
:raises: ValueError if msg cannot be converted to an appropriate format
for transmission
"""
if isinstance(msg, Request):
tmsg = m... | python | {
"resource": ""
} |
q229495 | FreshnessChecker.update_freshness | train | def update_freshness(self, ledger_id, ts):
'''
Updates the time at which the ledger was updated.
Should be called whenever a txn for the ledger is ordered.
:param ledger_id: the ID of the ledgers a txn was ordered for
:param ts: the current time
:return: None
'''... | python | {
"resource": ""
} |
q229496 | FreshnessChecker.get_last_update_time | train | def get_last_update_time(self):
'''
Gets the time at which each ledger was updated.
Can be called at any time to get this information.
:return: an ordered dict of outdated ledgers sorted by last update time (from old to new)
and then by ledger ID (in case of equal update time)
... | python | {
"resource": ""
} |
q229497 | SigningSerializer.serialize | train | def serialize(self, obj, level=0, objname=None, topLevelKeysToIgnore=None,
toBytes=True):
"""
Create a string representation of the given object.
Examples:
::
>>> serialize("str")
'str'
>>> serialize([1,2,3,4,5])
'1,2,3,4,5'
>>> ... | python | {
"resource": ""
} |
q229498 | TransactionStore.reset | train | def reset(self):
"""
Clear the values of all attributes of the transaction store.
"""
self.getsCounter = 0
# dictionary of processed requests for each client. Value for each
# client is a dictionary with request id as key and transaction id as
# value
sel... | python | {
"resource": ""
} |
q229499 | TransactionStore.stop | train | def stop(self, timeout: int = 5) -> None:
"""
Try to stop the transaction store in the given timeout or raise an
exception.
"""
self.running = False
start = time.perf_counter()
while True:
if self.getsCounter == 0:
return True
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.