_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
75
19.8k
language
stringclasses
1 value
meta_information
dict
q10900
_construct_new_key
train
def _construct_new_key(name, units=None): """Construct an MDF safe key from the name and units""" to_replace = ["/", "\\", "*", "^", "#", " ", "\n", "\t", ",", ".", ")", "(", "'", "`", "-"] to_remove = ["$", "{", "}"] cat = name if units: cat = "_".join([name, units]) for c in to_replac...
python
{ "resource": "" }
q10901
_extract_key_value
train
def _extract_key_value(obj): """Extract the value from the object and make a descriptive key""" key = None; value = None # Parse a Value object, which includes Properties if isinstance(obj, Value): key = _construct_new_key(obj.name, obj.units) value = [] if obj.scalars: ...
python
{ "resource": "" }
q10902
process_input_buffer
train
def process_input_buffer(): """Send the content of the input buffer to all remote processes, this must be called in the main thread""" from polysh.control_commands_helpers import handle_control_command data = the_stdin_thread.input_buffer.get() remote_dispatcher.log(b'> ' + data) if data.starts...
python
{ "resource": "" }
q10903
write_main_socket
train
def write_main_socket(c): """Synchronous write to the main socket, wait for ACK""" the_stdin_thread.socket_write.send(c) while True: try: the_stdin_thread.socket_write.recv(1) except socket.error as e: if e.errno != errno.EINTR: raise else: ...
python
{ "resource": "" }
q10904
get_stdin_pid
train
def get_stdin_pid(cached_result=None): """Try to get the PID of the stdin thread, otherwise get the whole process ID""" if cached_result is None: try: tasks = os.listdir('/proc/self/task') except OSError as e: if e.errno != errno.ENOENT: raise ...
python
{ "resource": "" }
q10905
InputBuffer.add
train
def add(self, data): """Add data to the buffer""" assert isinstance(data, bytes) with self.lock: self.buf += data
python
{ "resource": "" }
q10906
InputBuffer.get
train
def get(self): """Get the content of the buffer""" data = b'' with self.lock: data, self.buf = self.buf, b'' return data
python
{ "resource": "" }
q10907
SocketNotificationReader.handle_read
train
def handle_read(self): """Handle all the available character commands in the socket""" while True: try: c = self.recv(1) except socket.error as e: if e.errno == errno.EWOULDBLOCK: return else: ...
python
{ "resource": "" }
q10908
knuth_sum
train
def knuth_sum(a, b): """Error-free transformation of the sum of two floating point numbers according to D.E. Knuth. The Art of Computer Programming: Seminumerical Algorithms, volume 2. Addison Wesley, Reading, Massachusetts, second edition, 1981. The underlying problem is that the exact sum a+...
python
{ "resource": "" }
q10909
distill
train
def distill(p, K): """Algorithm 4.3. Error-free vector transformation for summation. The vector p is transformed without changing the sum, and p_n is replaced by float(sum(p)). Kahan [21] calls this a 'distillation algorithm.' """ q = p.reshape(p.shape[0], -1) for _ in range(K): _accupy...
python
{ "resource": "" }
q10910
toggle_shells
train
def toggle_shells(command, enable): """Enable or disable the specified shells. If the command would have no effect, it changes all other shells to the inverse enable value.""" selection = list(selected_shells(command)) if command and command != '*' and selection: for i in selection: ...
python
{ "resource": "" }
q10911
selected_shells
train
def selected_shells(command): """Iterator over the shells with names matching the patterns. An empty patterns matches all the shells""" if not command or command == '*': for i in dispatchers.all_instances(): yield i return selected = set() instance_found = False for p...
python
{ "resource": "" }
q10912
complete_shells
train
def complete_shells(line, text, predicate=lambda i: True): """Return the shell names to include in the completion""" res = [i.display_name + ' ' for i in dispatchers.all_instances() if i.display_name.startswith(text) and predicate(i) and ' ' + i.display_name + ' ' not in line] ...
python
{ "resource": "" }
q10913
kill_all
train
def kill_all(): """When polysh quits, we kill all the remote shells we started""" for i in dispatchers.all_instances(): try: os.kill(-i.pid, signal.SIGKILL) except OSError: # The process was already dead, no problem pass
python
{ "resource": "" }
q10914
BufferedDispatcher._handle_read_chunk
train
def _handle_read_chunk(self): """Some data can be read""" new_data = b'' buffer_length = len(self.read_buffer) try: while buffer_length < self.MAX_BUFFER_SIZE: try: piece = self.recv(4096) except OSError as e: ...
python
{ "resource": "" }
q10915
BufferedDispatcher.dispatch_write
train
def dispatch_write(self, buf): """Augment the buffer with stuff to write when possible""" self.write_buffer += buf if len(self.write_buffer) > self.MAX_BUFFER_SIZE: console_output('Buffer too big ({:d}) for {}\n'.format( len(self.write_buffer), str(self)).encode()) ...
python
{ "resource": "" }
q10916
safe_write
train
def safe_write(buf): """We can get a SIGWINCH when printing, which will cause write to raise an EINTR. That's not a reason to stop printing.""" assert isinstance(buf, bytes) while True: try: os.write(1, buf) break except IOError as e: if e.errno != err...
python
{ "resource": "" }
q10917
console_output
train
def console_output(msg, logging_msg=None): """Use instead of print, to clear the status information before printing""" assert isinstance(msg, bytes) assert isinstance(logging_msg, bytes) or logging_msg is None from polysh import remote_dispatcher remote_dispatcher.log(logging_msg or msg) if re...
python
{ "resource": "" }
q10918
expand_syntax
train
def expand_syntax(string): """Iterator over all the strings in the expansion of the argument""" match = syntax_pattern.search(string) if match: prefix = string[:match.start()] suffix = string[match.end():] intervals = match.group(1).split(',') for interval in intervals: ...
python
{ "resource": "" }
q10919
all_instances
train
def all_instances(): """Iterator over all the remote_dispatcher instances""" return sorted([i for i in asyncore.socket_map.values() if isinstance(i, remote_dispatcher.RemoteDispatcher)], key=lambda i: i.display_name or '')
python
{ "resource": "" }
q10920
count_awaited_processes
train
def count_awaited_processes(): """Return a tuple with the number of awaited processes and the total number""" awaited = 0 total = 0 for i in all_instances(): if i.enabled: total += 1 if i.state is not remote_dispatcher.STATE_IDLE: awaited += 1 retu...
python
{ "resource": "" }
q10921
all_terminated
train
def all_terminated(): """For each remote shell determine if its terminated""" instances_found = False for i in all_instances(): instances_found = True if i.state not in (remote_dispatcher.STATE_TERMINATED, remote_dispatcher.STATE_DEAD): return False ...
python
{ "resource": "" }
q10922
update_terminal_size
train
def update_terminal_size(): """Propagate the terminal size to the remote shells accounting for the place taken by the longest name""" w, h = terminal_size() w = max(w - display_names.max_display_name_length - 2, min(w, 10)) # python bug http://python.org/sf/1112949 on amd64 # from ajaxterm.py ...
python
{ "resource": "" }
q10923
format_info
train
def format_info(info_list): """Turn a 2-dimension list of bytes into a 1-dimension list of bytes with correct spacing""" max_lengths = [] if info_list: nr_columns = len(info_list[0]) else: nr_columns = 0 for i in range(nr_columns): max_lengths.append(max([len(info[i]) fo...
python
{ "resource": "" }
q10924
generate_ill_conditioned_dot_product
train
def generate_ill_conditioned_dot_product(n, c, dps=100): """n ... length of vector c ... target condition number """ # Algorithm 6.1 from # # ACCURATE SUM AND DOT PRODUCT, # TAKESHI OGITA, SIEGFRIED M. RUMP, AND SHIN'ICHI OISHI. assert n >= 6 n2 = round(n / 2) x = numpy.zeros(n) ...
python
{ "resource": "" }
q10925
RemoteDispatcher.launch_ssh
train
def launch_ssh(self, name, port): """Launch the ssh command in the child process""" if options.user: name = '%s@%s' % (options.user, name) evaluated = options.ssh % {'host': name, 'port': port} if evaluated == options.ssh: evaluated = '%s %s' % (evaluated, name) ...
python
{ "resource": "" }
q10926
RemoteDispatcher.change_state
train
def change_state(self, state): """Change the state of the remote process, logging the change""" if state is not self.state: if self.debug: self.print_debug(b'state => ' + STATE_NAMES[state].encode()) if self.state is STATE_NOT_STARTED: self.read_in...
python
{ "resource": "" }
q10927
RemoteDispatcher.disconnect
train
def disconnect(self): """We are no more interested in this remote process""" try: os.kill(-self.pid, signal.SIGKILL) except OSError: # The process was already dead, no problem pass self.read_buffer = b'' self.write_buffer = b'' self.set...
python
{ "resource": "" }
q10928
RemoteDispatcher.configure_tty
train
def configure_tty(self): """We don't want \n to be replaced with \r\n, and we disable the echo""" attr = termios.tcgetattr(self.fd) attr[1] &= ~termios.ONLCR # oflag attr[3] &= ~termios.ECHO # lflag termios.tcsetattr(self.fd, termios.TCSANOW, attr) # unsetopt zle preven...
python
{ "resource": "" }
q10929
RemoteDispatcher.set_prompt
train
def set_prompt(self): """The prompt is important because we detect the readyness of a process by waiting for its prompt.""" # No right prompt command_line = b'PS2=;RPS1=;RPROMPT=;' command_line += b'PROMPT_COMMAND=;' command_line += b'TERM=ansi;' command_line += b...
python
{ "resource": "" }
q10930
RemoteDispatcher.handle_read_fast_case
train
def handle_read_fast_case(self, data): """If we are in a fast case we'll avoid the long processing of each line""" if self.state is not STATE_RUNNING or callbacks.any_in(data): # Slow case :-( return False last_nl = data.rfind(b'\n') if last_nl == -1: ...
python
{ "resource": "" }
q10931
RemoteDispatcher.handle_read
train
def handle_read(self): """We got some output from a remote shell, this is one of the state machine""" if self.state == STATE_DEAD: return global nr_handle_read nr_handle_read += 1 new_data = self._handle_read_chunk() if self.debug: self.pri...
python
{ "resource": "" }
q10932
RemoteDispatcher.print_unfinished_line
train
def print_unfinished_line(self): """The unfinished line stayed long enough in the buffer to be printed""" if self.state is STATE_RUNNING: if not callbacks.process(self.read_buffer): self.print_lines(self.read_buffer) self.read_buffer = b''
python
{ "resource": "" }
q10933
RemoteDispatcher.handle_write
train
def handle_write(self): """Let's write as much as we can""" num_sent = self.send(self.write_buffer) if self.debug: if self.state is not STATE_NOT_STARTED or options.password is None: self.print_debug(b'<== ' + self.write_buffer[:num_sent]) self.write_buffer = ...
python
{ "resource": "" }
q10934
RemoteDispatcher.print_debug
train
def print_debug(self, msg): """Log some debugging information to the console""" assert isinstance(msg, bytes) state = STATE_NAMES[self.state].encode() console_output(b'[dbg] ' + self.display_name.encode() + b'[' + state + b']: ' + msg + b'\n')
python
{ "resource": "" }
q10935
RemoteDispatcher.get_info
train
def get_info(self): """Return a list with all information available about this process""" return [self.display_name.encode(), self.enabled and b'enabled' or b'disabled', STATE_NAMES[self.state].encode() + b':', self.last_printed_line.strip()]
python
{ "resource": "" }
q10936
RemoteDispatcher.dispatch_write
train
def dispatch_write(self, buf): """There is new stuff to write when possible""" if self.state != STATE_DEAD and self.enabled: super().dispatch_write(buf) return True return False
python
{ "resource": "" }
q10937
RemoteDispatcher.change_name
train
def change_name(self, new_name): """Change the name of the shell, possibly updating the maximum name length""" if not new_name: name = self.hostname else: name = new_name.decode() self.display_name = display_names.change( self.display_name, nam...
python
{ "resource": "" }
q10938
RemoteDispatcher.rename
train
def rename(self, name): """Send to the remote shell, its new name to be shell expanded""" if name: # defug callback add? rename1, rename2 = callbacks.add( b'rename', self.change_name, False) self.dispatch_command(b'/bin/echo "' + rename1 + b'""' + rena...
python
{ "resource": "" }
q10939
complete
train
def complete(text, state): """On tab press, return the next possible completion""" global completion_results if state == 0: line = readline.get_line_buffer() if line.startswith(':'): # Control command completion completion_results = complete_control_command(line, text...
python
{ "resource": "" }
q10940
Popen
train
def Popen(*args, **kwargs): """ Executes a command using subprocess.Popen and redirects output to AETROS and stdout. Parses stdout as well for stdout API calls. Use read_line argument to read stdout of command's stdout line by line. Use returned process stdin to communicate with the command. :...
python
{ "resource": "" }
q10941
JobBackend.on_sigint
train
def on_sigint(self, sig, frame): """ We got SIGINT signal. """ if self.stop_requested or self.stop_requested_force: # signal has already been sent or we force a shutdown. # handles the keystroke 2x CTRL+C to force an exit. self.stop_requested_force = ...
python
{ "resource": "" }
q10942
JobBackend.external_aborted
train
def external_aborted(self, params): """ Immediately abort the job by server. This runs in the Client:read() thread. """ self.ended = True self.running = False # When the server sends an abort signal, we really have to close immediately, # since for examp...
python
{ "resource": "" }
q10943
JobBackend.external_stop
train
def external_stop(self, force): """ Stop signal by server. """ # only the master processes handles the regular stop signal from the server, sending a SIGINT to # all its child (means to us, non-master process) if not self.is_master_process(): if force: ...
python
{ "resource": "" }
q10944
JobBackend.fail
train
def fail(self, message=None, force_exit=False): """ Marks the job as failed, saves the given error message and force exists the process when force_exit=True. """ global last_exit_code if not last_exit_code: last_exit_code = 1 with self.git.batch_commit('FAIL...
python
{ "resource": "" }
q10945
JobBackend.write_log
train
def write_log(self, message): """ Proxy method for GeneralLogger. """ if self.stream_log and not self.ended: # points to the Git stream write self.stream_log.write(message) return True
python
{ "resource": "" }
q10946
JobBackend.set_status
train
def set_status(self, status, add_section=True): """ Set an arbitrary status, visible in the big wheel of the job view. """ status = str(status) if add_section: self.section(status) self.job_add_status('status', status)
python
{ "resource": "" }
q10947
JobBackend.create
train
def create(self, create_info=None, hyperparameter=None, server='local', insights=False): """ Creates a new job in git and pushes it. :param create_info: from the api.create_job_info(id). Contains the config and job info (type, server) :param hyperparameter: simple nested dict with key->...
python
{ "resource": "" }
q10948
JobBackend.get_parameter
train
def get_parameter(self, path, default=None, return_group=False): """ Reads hyperparameter from job configuration. If nothing found use given default. :param path: str :param default: * :param return_group: If true and path is a choice_group, we return the dict instead of the gr...
python
{ "resource": "" }
q10949
JobBackend.load
train
def load(self, job_id): """ Loads job into index and work-tree, restart its ref and sets as current. :param job_id: int """ self.git.read_job(job_id, checkout=self.is_master_process()) self.load_job_from_ref()
python
{ "resource": "" }
q10950
JobBackend.load_job_from_ref
train
def load_job_from_ref(self): """ Loads the job.json into self.job """ if not self.job_id: raise Exception('Job not loaded yet. Use load(id) first.') if not os.path.exists(self.git.work_tree + '/aetros/job.json'): raise Exception('Could not load aetros/job...
python
{ "resource": "" }
q10951
JobBackend.file_list
train
def file_list(self): """ Lists all files in the working directory. """ blacklist = ['.git', 'aetros'] working_tree = self.git.work_tree def recursive(path='.'): if os.path.basename(path) in blacklist: return 0, 0 if os.path.isdir(...
python
{ "resource": "" }
q10952
ftpretty.get
train
def get(self, remote, local=None): """ Gets the file from FTP server local can be: a file: opened for writing, left open a string: path to output file None: contents are returned """ if isinstance(local, file_type): # open file, leave...
python
{ "resource": "" }
q10953
ftpretty.upload_tree
train
def upload_tree(self, src, dst, ignore=None): """Recursively upload a directory tree. Although similar to shutil.copytree we don't follow symlinks. """ names = os.listdir(src) if ignore is not None: ignored_names = ignore(src, names) else: ignored...
python
{ "resource": "" }
q10954
ftpretty.list
train
def list(self, remote='.', extra=False, remove_relative_paths=False): """ Return directory list """ if extra: self.tmp_output = [] self.conn.dir(remote, self._collector) directory_list = split_file_info(self.tmp_output) else: directory_list = self....
python
{ "resource": "" }
q10955
ftpretty.descend
train
def descend(self, remote, force=False): """ Descend, possibly creating directories as needed """ remote_dirs = remote.split('/') for directory in remote_dirs: try: self.conn.cwd(directory) except Exception: if force: sel...
python
{ "resource": "" }
q10956
ftpretty.delete
train
def delete(self, remote): """ Delete a file from server """ try: self.conn.delete(remote) except Exception: return False else: return True
python
{ "resource": "" }
q10957
ftpretty.cd
train
def cd(self, remote): """ Change working directory on server """ try: self.conn.cwd(remote) except Exception: return False else: return self.pwd()
python
{ "resource": "" }
q10958
start
train
def start(logger, full_id, fetch=True, env=None, volumes=None, cpus=None, memory=None, gpu_devices=None, offline=False): """ Starts the job with all logging of a job_id """ owner, name, id = unpack_full_job_id(full_id) if isinstance(sys.stdout, GeneralLogger): # we don't want to have stuff...
python
{ "resource": "" }
q10959
fromimage
train
def fromimage(im, flatten=False, mode=None): """ Return a copy of a PIL image as a numpy array. Parameters ---------- im : PIL image Input image. flatten : bool If true, convert the output to grey-scale. mode : str, optional Mode to convert image to, e.g. ``'RGB'``. ...
python
{ "resource": "" }
q10960
imresize
train
def imresize(arr, size, interp='bilinear', mode=None): """ Resize an image. Parameters ---------- arr : ndarray The array of image to be resized. size : int, float or tuple * int - Percentage of current size. * float - Fraction of current size. * tuple - Size ...
python
{ "resource": "" }
q10961
BackendClient._end_channel
train
def _end_channel(self, channel): """ Soft end of ssh channel. End the writing thread as soon as the message queue is empty. """ self.stop_on_empty_queue[channel] = True # by joining the we wait until its loop finishes. # it won't loop forever since we've set self.stop_on...
python
{ "resource": "" }
q10962
BackendClient.wait_sending_last_messages
train
def wait_sending_last_messages(self): """ Requests all channels to close and waits for it. """ if self.active and self.online is not False: self.logger.debug("client sends last %s messages ..." % ([str(i) + ':' + str(len(x)) for i, x in six.iteri...
python
{ "resource": "" }
q10963
BackendClient.wait_until_queue_empty
train
def wait_until_queue_empty(self, channels, report=True, clear_end=True): """ Waits until all queues of channels are empty. """ state = {'message': ''} self.logger.debug("wait_until_queue_empty: report=%s %s" % (str(report), str([channel+':'+str(len(self...
python
{ "resource": "" }
q10964
BackendClient.send_message
train
def send_message(self, message, channel): """ Internal. Sends the actual message from a queue entry. """ if not self.is_connected(channel): return False message['_sending'] = True if '_data' in message: data = message['_data'] else: ...
python
{ "resource": "" }
q10965
BackendClient.wait_for_at_least_one_message
train
def wait_for_at_least_one_message(self, channel): """ Reads until we receive at least one message we can unpack. Return all found messages. """ unpacker = msgpack.Unpacker(encoding='utf-8') while True: try: start = time.time() chunk =...
python
{ "resource": "" }
q10966
raise_sigint
train
def raise_sigint(): """ Raising the SIGINT signal in the current process and all sub-processes. os.kill() only issues a signal in the current process (without subprocesses). CTRL+C on the console sends the signal to the process group (which we need). """ if hasattr(signal, 'CTRL_C_EVENT'): ...
python
{ "resource": "" }
q10967
Git.read_job
train
def read_job(self, job_id, checkout=False): """ Reads head and reads the tree into index, and checkout the work-tree when checkout=True. This does not fetch the job from the actual server. It needs to be in the local git already. """ self.job_id = job_id commit ...
python
{ "resource": "" }
q10968
Git.start_push_sync
train
def start_push_sync(self): """ Starts the detection of unsynced Git data. """ self.active_thread = True self.active_push = True self.thread_push_instance = Thread(target=self.thread_push) self.thread_push_instance.daemon = True self.thread_push_instance.s...
python
{ "resource": "" }
q10969
Git.batch_commit
train
def batch_commit(self, message): """ Instead of committing a lot of small commits you can batch it together using this controller. Example: with git.batch_commit('BATCHED'): git.commit_file('my commit 1', 'path/to/file', 'content from file') git.commit_json_file...
python
{ "resource": "" }
q10970
Git.add_file_path_in_work_tree
train
def add_file_path_in_work_tree(self, path, work_tree, verbose=True): """ Add a new file as blob in the storage and add its tree entry into the index. """ args = ['--work-tree', work_tree, 'add', '-f'] if verbose: args.append('--verbose') args.append(path) ...
python
{ "resource": "" }
q10971
Git.commit_file
train
def commit_file(self, message, path, content): """ Add a new file as blob in the storage, add its tree entry into the index and commit the index. :param message: str :param path: str :param content: str :return: """ if self.git_batch_commit: ...
python
{ "resource": "" }
q10972
Git.contents
train
def contents(self, path): """ Reads the given path of current ref_head and returns its content as utf-8 """ try: out, code, err = self.command_exec(['cat-file', '-p', self.ref_head+':'+path]) if not code: return out.decode('utf-8') except E...
python
{ "resource": "" }
q10973
get_ordered_devices
train
def get_ordered_devices(): """ Default CUDA_DEVICE_ORDER is not compatible with nvidia-docker. Nvidia-Docker is using CUDA_DEVICE_ORDER=PCI_BUS_ID. https://github.com/NVIDIA/nvidia-docker/wiki/nvidia-docker#gpu-isolation """ libcudart = get_libcudart() devices = {} for i in range(0, g...
python
{ "resource": "" }
q10974
reduce_list_size
train
def reduce_list_size(li): """Return two lists - the last N items of li whose total size is less than MAX_SIZE - the rest of the original list li """ # sys.getsizeof is nearly useless. All our data is stringable so rather # use that as a measure of size. size = len(repr(li)) keep ...
python
{ "resource": "" }
q10975
AnchorSmith.least_role
train
def least_role() -> Role: """ Return the TRUSTEE indy-sdk role for an anchor acting in an AnchorSmith capacity. :return: TRUSTEE role """ LOGGER.debug('AnchorSmith.least_role >>>') rv = Role.TRUSTEE.token() LOGGER.debug('AnchorSmith.least_role <<< %s', rv) ...
python
{ "resource": "" }
q10976
usage
train
def usage() -> None: """ Print usage advice. """ print() print('Usage: setnym.py <config-ini>') print() print('where <config-ini> represents the path to the configuration file.') print() print('The operation submits a nym to a trustee anchor to send to the ledger,') print('if th...
python
{ "resource": "" }
q10977
_set_wallets
train
async def _set_wallets(an_data: dict) -> dict: """ Set wallets as configured for setnym operation. :param an_data: dict mapping profiles to anchor data :return: dict mapping anchor names to wallet objects """ w_mgr = WalletManager() rv = {} for profile in an_data: w_cfg = {'id'...
python
{ "resource": "" }
q10978
schema_id
train
def schema_id(origin_did: str, name: str, version: str) -> str: """ Return schema identifier for input origin DID, schema name, and schema version. :param origin_did: DID of schema originator :param name: schema name :param version: schema version :return: schema identifier """ return ...
python
{ "resource": "" }
q10979
ok_did
train
def ok_did(token: str) -> bool: """ Whether input token looks like a valid distributed identifier. :param token: candidate string :return: whether input token looks like a valid schema identifier """ return bool(re.match('[{}]{{21,22}}$'.format(B58), token or ''))
python
{ "resource": "" }
q10980
cred_def_id2seq_no
train
def cred_def_id2seq_no(cd_id: str) -> int: """ Given a credential definition identifier, return its schema sequence number. Raise BadIdentifier on input that is not a credential definition identifier. :param cd_id: credential definition identifier :return: sequence number """ if ok_cred_de...
python
{ "resource": "" }
q10981
rev_reg_id2cred_def_id
train
def rev_reg_id2cred_def_id(rr_id: str) -> str: """ Given a revocation registry identifier, return its corresponding credential definition identifier. Raise BadIdentifier if input is not a revocation registry identifier. :param rr_id: revocation registry identifier :return: credential definition ide...
python
{ "resource": "" }
q10982
prune_creds_json
train
def prune_creds_json(creds: dict, cred_ids: set) -> str: """ Strip all creds out of the input json structure that do not match any of the input credential identifiers. :param creds: indy-sdk creds structure :param cred_ids: the set of credential identifiers of interest :return: the reduced creds js...
python
{ "resource": "" }
q10983
proof_req2wql_all
train
def proof_req2wql_all(proof_req: dict, x_cd_ids: Union[str, Sequence[str]] = None) -> dict: """ Given a proof request and a list of cred def ids to omit, return an extra WQL query dict that will find all corresponding credentials in search. The proof request must have cred def id restrictions on all re...
python
{ "resource": "" }
q10984
proof_req_attr_referents
train
def proof_req_attr_referents(proof_req: dict) -> dict: """ Given a proof request with all requested attributes having cred def id restrictions, return its attribute referents by cred def id and attribute. The returned structure can be useful in populating the extra WQL query parameter in the creden...
python
{ "resource": "" }
q10985
proof_req_pred_referents
train
def proof_req_pred_referents(proof_req: dict) -> dict: """ Given a proof request with all requested predicates having cred def id restrictions, return its predicate referents by cred def id and attribute, mapping a predicate and a limit. The returned structure can be useful in downstream processing to ...
python
{ "resource": "" }
q10986
Verifier._build_rr_state_json
train
async def _build_rr_state_json(self, rr_id: str, timestamp: int) -> (str, int): """ Build rev reg state json at a given requested timestamp. Return rev reg state json and its transaction time on the distributed ledger, with upper bound at input timestamp of interest. Raise Abse...
python
{ "resource": "" }
q10987
Verifier.build_proof_req_json
train
async def build_proof_req_json(self, cd_id2spec: dict) -> str: """ Build and return indy-sdk proof request for input attributes and non-revocation intervals by cred def id. :param cd_id2spec: dict mapping cred def ids to: - (optionally) 'attrs': lists of names of attributes of inte...
python
{ "resource": "" }
q10988
Verifier.load_cache_for_verification
train
async def load_cache_for_verification(self, archive: bool = False) -> int: """ Load schema, cred def, revocation caches; optionally archive enough to go offline and be able to verify proof on content marked of interest in configuration. Return timestamp (epoch seconds) of cache load eve...
python
{ "resource": "" }
q10989
Verifier.check_encoding
train
def check_encoding(proof_req: dict, proof: dict) -> bool: """ Return whether the proof's raw values correspond to their encodings as cross-referenced against proof request. :param proof request: proof request :param proof: corresponding proof to check :return: True if OK...
python
{ "resource": "" }
q10990
PublicKey.to_dict
train
def to_dict(self): """ Return dict representation of public key to embed in DID document. """ return { 'id': self.id, 'type': str(self.type.ver_type), 'controller': canon_ref(self.did, self.controller), **self.type.specification(self.value...
python
{ "resource": "" }
q10991
main
train
async def main(wallet_name: str) -> None: """ Main line for revocation registry builder operating in external process on behalf of issuer agent. :param wallet_name: wallet name - must match that of issuer with existing wallet """ logging.basicConfig(level=logging.WARN, format='%(levelname)-8s | %(...
python
{ "resource": "" }
q10992
RevRegBuilder._start_data_json
train
def _start_data_json(self) -> str: """ Output json with start data to write for external revocation registry builder process pickup. :return: logging and wallet init data json """ rv = { 'logging': { 'paths': [] }, 'wallet': {...
python
{ "resource": "" }
q10993
RevRegBuilder._get_state
train
def _get_state(wallet_name: str) -> _STATE: """ Return current state of revocation registry builder process. :param wallet_name: name of wallet for corresponding Issuer :return: current process state as _STATE enum """ dir_sentinel = RevRegBuilder.dir_tails_sentinel(wal...
python
{ "resource": "" }
q10994
RevRegBuilder.dir_tails_top
train
def dir_tails_top(self, rr_id) -> str: """ Return top of tails tree for input rev reg id. :param rr_id: revocation registry identifier :return: top of tails tree """ return join(self.dir_tails_hopper, rr_id) if self.external else self.dir_tails
python
{ "resource": "" }
q10995
RevRegBuilder.dir_tails_target
train
def dir_tails_target(self, rr_id) -> str: """ Return target directory for revocation registry and tails file production. :param rr_id: revocation registry identifier :return: tails target directory """ return join(self.dir_tails_top(rr_id), rev_reg_id2cred_def_id(rr_id)...
python
{ "resource": "" }
q10996
RevRegBuilder.mark_in_progress
train
def mark_in_progress(self, rr_id: str, rr_size: int) -> None: """ Prepare sentinel directory for revocation registry construction. :param rr_id: revocation registry identifier :rr_size: size of revocation registry to build """ try: makedirs(join(self._dir_tai...
python
{ "resource": "" }
q10997
RevRegBuilder.serve
train
async def serve(self) -> None: """ Write pidfile to sentinel directory if need be, and wait for sentinels to shut down or build revocation registry and tails file. """ LOGGER.debug('RevRegBuilder.serve >>>') assert self.external file_pid = join(self._dir_tails_...
python
{ "resource": "" }
q10998
RevRegBuilder.stop
train
async def stop(wallet_name: str) -> None: """ Gracefully stop an external revocation registry builder, waiting for its current. The indy-sdk toolkit uses a temporary directory for tails file mustration, and shutting down the toolkit removes the directory, crashing the external t...
python
{ "resource": "" }
q10999
do_ultracache
train
def do_ultracache(parser, token): """Based on Django's default cache template tag""" nodelist = parser.parse(("endultracache",)) parser.delete_first_token() tokens = token.split_contents() if len(tokens) < 3: raise TemplateSyntaxError(""%r" tag requires at least 2 arguments." % tokens[0]) ...
python
{ "resource": "" }