_id
stringlengths
2
7
title
stringlengths
1
88
partition
stringclasses
3 values
text
stringlengths
31
13.1k
language
stringclasses
1 value
meta_information
dict
q271700
Model.delete
test
def delete(self, **kwargs): ''' Deletes the entity immediately. Also performs any on_delete operations specified as part of column definitions. ''' if kwargs.get('skip_on_delete_i_really_mean_it') is not SKIP_ON_DELETE: # handle the pre-commit hook
python
{ "resource": "" }
q271701
Model.get
test
def get(cls, ids): ''' Will fetch one or more entities of this type from the session or Redis. Used like:: MyModel.get(5) MyModel.get([1, 6, 2, 4]) Passing a list or a tuple will return multiple entities, in the same order that the ids were passed. ''' conn = _connect(cls) # prepare the ids single = not isinstance(ids, (list, tuple, set, frozenset)) if single: ids = [ids] pks = ['%s:%s'%(cls._namespace, id) for id in map(int, ids)] # get from the session, if possible out = list(map(session.get, pks)) # if we couldn't get an instance from the session, load from Redis if None in out: pipe = conn.pipeline(True) idxs = [] # Fetch missing data for i, data in enumerate(out): if data is None:
python
{ "resource": "" }
q271702
_ReducerRegistry.register
test
def register(cls, type, reduce_func): """Attach a reducer function to a given type in the dispatch table.""" if sys.version_info < (3,): # Python 2 pickler dispatching is not explicitly customizable. # Let us use a closure to workaround this limitation. def dispatcher(cls,
python
{ "resource": "" }
q271703
_sem_open
test
def _sem_open(name, value=None): """ Construct or retrieve a semaphore with the given name If value is None, try to retrieve an existing named semaphore. Else create a new semaphore with the given value """ if value is None: handle = pthread.sem_open(ctypes.c_char_p(name), 0) else: handle = pthread.sem_open(ctypes.c_char_p(name), SEM_OFLAG, SEM_PERM, ctypes.c_int(value)) if handle == SEM_FAILURE: e = ctypes.get_errno() if e == errno.EEXIST:
python
{ "resource": "" }
q271704
cpu_count
test
def cpu_count(): """Return the number of CPUs the current process can use. The returned number of CPUs accounts for: * the number of CPUs in the system, as given by ``multiprocessing.cpu_count``; * the CPU affinity settings of the current process (available with Python 3.4+ on some Unix systems); * CFS scheduler CPU bandwidth limit (available on Linux only, typically set by docker and similar container orchestration systems); * the value of the LOKY_MAX_CPU_COUNT environment variable if defined. and is given as the minimum of these constraints. It is also always larger or equal to 1. """ import math try: cpu_count_mp = mp.cpu_count() except NotImplementedError: cpu_count_mp = 1 # Number of available CPUs given affinity settings cpu_count_affinity = cpu_count_mp if hasattr(os,
python
{ "resource": "" }
q271705
_sendback_result
test
def _sendback_result(result_queue, work_id, result=None, exception=None): """Safely send back the given result or exception""" try: result_queue.put(_ResultItem(work_id, result=result,
python
{ "resource": "" }
q271706
_process_worker
test
def _process_worker(call_queue, result_queue, initializer, initargs, processes_management_lock, timeout, worker_exit_lock, current_depth): """Evaluates calls from call_queue and places the results in result_queue. This worker is run in a separate process. Args: call_queue: A ctx.Queue of _CallItems that will be read and evaluated by the worker. result_queue: A ctx.Queue of _ResultItems that will written to by the worker. initializer: A callable initializer, or None initargs: A tuple of args for the initializer process_management_lock: A ctx.Lock avoiding worker timeout while some workers are being spawned. timeout: maximum time to wait for a new item in the call_queue. If that time is expired, the worker will shutdown. worker_exit_lock: Lock to avoid flagging the executor as broken on workers timeout. current_depth: Nested parallelism level, to avoid infinite spawning. """ if initializer is not None: try: initializer(*initargs) except BaseException: _base.LOGGER.critical('Exception in initializer:', exc_info=True) # The parent will notice that the process stopped and # mark the pool broken return # set the global _CURRENT_DEPTH mechanism to limit recursive call global _CURRENT_DEPTH _CURRENT_DEPTH = current_depth _process_reference_size = None _last_memory_leak_check = None pid = os.getpid() mp.util.debug('Worker started with timeout=%s' % timeout) while True: try: call_item = call_queue.get(block=True, timeout=timeout) if call_item is None: mp.util.info("Shutting down worker on sentinel") except queue.Empty: mp.util.info("Shutting down worker after timeout %0.3fs" % timeout) if processes_management_lock.acquire(block=False): processes_management_lock.release()
python
{ "resource": "" }
q271707
_add_call_item_to_queue
test
def _add_call_item_to_queue(pending_work_items, running_work_items, work_ids, call_queue): """Fills call_queue with _WorkItems from pending_work_items. This function never blocks. Args: pending_work_items: A dict mapping work ids to _WorkItems e.g. {5: <_WorkItem...>, 6: <_WorkItem...>, ...} work_ids: A queue.Queue of work ids e.g. Queue([5, 6, ...]). Work ids are consumed and the corresponding _WorkItems from pending_work_items are transformed into _CallItems and put in call_queue. call_queue: A ctx.Queue that will be filled with _CallItems derived from _WorkItems. """ while True: if call_queue.full(): return try: work_id = work_ids.get(block=False) except queue.Empty: return else:
python
{ "resource": "" }
q271708
ProcessPoolExecutor._ensure_executor_running
test
def _ensure_executor_running(self): """ensures all workers and management thread are running """ with self._processes_management_lock: if len(self._processes) != self._max_workers:
python
{ "resource": "" }
q271709
wrap_non_picklable_objects
test
def wrap_non_picklable_objects(obj, keep_wrapper=True): """Wrapper for non-picklable object to use cloudpickle to serialize them. Note that this wrapper tends to slow down the serialization process as it is done with cloudpickle which is typically slower compared to pickle. The proper way to solve serialization issues is to avoid defining functions and objects in the main scripts and to implement __reduce__ functions for complex classes. """ if not cloudpickle: raise ImportError("could not import cloudpickle. Please install " "cloudpickle to allow extended serialization. " "(`pip install cloudpickle`).") # If obj is
python
{ "resource": "" }
q271710
LokyManager.start
test
def start(self, initializer=None, initargs=()): '''Spawn a server process for this manager object''' assert self._state.value == State.INITIAL if (initializer is not None and not hasattr(initializer, '__call__')): raise TypeError('initializer must be a callable') # pipe over which we will retrieve address of server reader, writer = mp.Pipe(duplex=False) # spawn process which runs a server self._process = Process( target=type(self)._run_server, args=(self._registry, self._address, bytes(self._authkey), self._serializer, writer, initializer, initargs), ) ident = ':'.join(str(i) for i in self._process._identity)
python
{ "resource": "" }
q271711
DupFd
test
def DupFd(fd): '''Return a wrapper for an fd.''' popen_obj = get_spawning_popen() if popen_obj is not None: return popen_obj.DupFd(popen_obj.duplicate_for_child(fd)) elif HAVE_SEND_HANDLE and sys.version_info[:2] > (3, 3): from multiprocessing import resource_sharer return resource_sharer.DupFd(fd) else:
python
{ "resource": "" }
q271712
get_reusable_executor
test
def get_reusable_executor(max_workers=None, context=None, timeout=10, kill_workers=False, reuse="auto", job_reducers=None, result_reducers=None, initializer=None, initargs=()): """Return the current ReusableExectutor instance. Start a new instance if it has not been started already or if the previous instance was left in a broken state. If the previous instance does not have the requested number of workers, the executor is dynamically resized to adjust the number of workers prior to returning. Reusing a singleton instance spares the overhead of starting new worker processes and importing common python packages each time. ``max_workers`` controls the maximum number of tasks that can be running in parallel in worker processes. By default this is set to the number of CPUs on the host. Setting ``timeout`` (in seconds) makes idle workers automatically shutdown so as to release system resources. New workers are respawn upon submission of new tasks so that ``max_workers`` are available to accept the newly submitted tasks. Setting ``timeout`` to around 100 times the time required to spawn new processes and import packages in them (on the order of 100ms) ensures that the overhead of spawning workers is negligible. Setting ``kill_workers=True`` makes it possible to forcibly interrupt previously spawned jobs to get a new instance of the reusable executor with new constructor argument values. The ``job_reducers`` and ``result_reducers`` are used to customize the pickling of tasks and results send to the executor. When provided, the ``initializer`` is run first in newly spawned processes with argument ``initargs``. """ with _executor_lock: global _executor, _executor_kwargs executor = _executor if max_workers is None: if reuse is True and executor is not None: max_workers = executor._max_workers else: max_workers = cpu_count() elif max_workers <= 0: raise ValueError( "max_workers must be greater than 0, got {}." .format(max_workers)) if isinstance(context, STRING_TYPE): context = get_context(context) if context is not None and context.get_start_method() == "fork": raise ValueError("Cannot use reusable executor with the 'fork' " "context")
python
{ "resource": "" }
q271713
_ReusablePoolExecutor._wait_job_completion
test
def _wait_job_completion(self): """Wait for the cache to be empty before resizing the pool.""" # Issue a warning to the user about the bad effect of this usage. if len(self._pending_work_items) > 0: warnings.warn("Trying to resize an executor with running jobs: " "waiting for jobs completion before resizing.", UserWarning)
python
{ "resource": "" }
q271714
get_preparation_data
test
def get_preparation_data(name, init_main_module=True): ''' Return info about parent needed by child to unpickle process object ''' _check_not_importing_main() d = dict( log_to_stderr=util._log_to_stderr, authkey=bytes(process.current_process().authkey), ) if util._logger is not None: d['log_level'] = util._logger.getEffectiveLevel() if len(util._logger.handlers) > 0: h = util._logger.handlers[0] d['log_fmt'] = h.formatter._fmt sys_path = [p for p in sys.path] try: i = sys_path.index('') except ValueError: pass else: sys_path[i] = process.ORIGINAL_DIR d.update( name=name, sys_path=sys_path, sys_argv=sys.argv, orig_dir=process.ORIGINAL_DIR, dir=os.getcwd() ) if sys.platform != "win32": # Pass the semaphore_tracker pid to avoid re-spawning it in every child from . import semaphore_tracker semaphore_tracker.ensure_running() d['tracker_pid'] = semaphore_tracker._semaphore_tracker._pid # Figure out whether to initialise main in the subprocess as a module # or through direct execution (or to leave it alone entirely) if init_main_module: main_module = sys.modules['__main__'] try: main_mod_name = getattr(main_module.__spec__, "name", None) except BaseException:
python
{ "resource": "" }
q271715
prepare
test
def prepare(data): ''' Try to get current process ready to unpickle process object ''' if 'name' in data: process.current_process().name = data['name'] if 'authkey' in data: process.current_process().authkey = data['authkey'] if 'log_to_stderr' in data and data['log_to_stderr']: util.log_to_stderr() if 'log_level' in data: util.get_logger().setLevel(data['log_level']) if 'log_fmt' in data: import logging util.get_logger().handlers[0].setFormatter( logging.Formatter(data['log_fmt']) ) if 'sys_path' in data: sys.path = data['sys_path'] if 'sys_argv' in data: sys.argv = data['sys_argv']
python
{ "resource": "" }
q271716
close_fds
test
def close_fds(keep_fds): # pragma: no cover """Close all the file descriptors except those in keep_fds.""" # Make sure to keep stdout and stderr open for logging purpose keep_fds = set(keep_fds).union([1, 2]) # We try to retrieve all the open fds try: open_fds = set(int(fd) for fd in os.listdir('/proc/self/fd')) except FileNotFoundError: import resource
python
{ "resource": "" }
q271717
_recursive_terminate_without_psutil
test
def _recursive_terminate_without_psutil(process): """Terminate a process and its descendants. """ try: _recursive_terminate(process.pid) except OSError as e: warnings.warn("Failed to kill subprocesses on this platform. Please" "install psutil: https://github.com/giampaolo/psutil")
python
{ "resource": "" }
q271718
_recursive_terminate
test
def _recursive_terminate(pid): """Recursively kill the descendants of a process before killing it. """ if sys.platform == "win32": # On windows, the taskkill function with option `/T` terminate a given # process pid and its children. try: subprocess.check_output( ["taskkill", "/F", "/T", "/PID", str(pid)], stderr=None) except subprocess.CalledProcessError as e: # In windows, taskkill return 1 for permission denied and 128, 255 # for no process found. if e.returncode not in [1, 128, 255]: raise elif e.returncode == 1: # Try to kill the process without its descendants if taskkill # was denied permission. If this fails too, with an error # different from process not found, let the top level function # raise a warning and retry to kill the process. try: os.kill(pid, signal.SIGTERM) except OSError as e: if e.errno != errno.ESRCH: raise else: try: children_pids = subprocess.check_output( ["pgrep", "-P", str(pid)], stderr=None ) except subprocess.CalledProcessError as e: # `ps` returns 1 when no child process has been found if e.returncode == 1: children_pids = b''
python
{ "resource": "" }
q271719
get_exitcodes_terminated_worker
test
def get_exitcodes_terminated_worker(processes): """Return a formated string with the exitcodes of terminated workers. If necessary, wait (up to .25s) for the system to correctly set the exitcode of one terminated worker. """ patience = 5 # Catch the exitcode of the terminated workers. There should at least be
python
{ "resource": "" }
q271720
_format_exitcodes
test
def _format_exitcodes(exitcodes): """Format a list of exit code with names of the signals if possible""" str_exitcodes = ["{}({})".format(_get_exitcode_name(e), e)
python
{ "resource": "" }
q271721
main
test
def main(fd, verbose=0): '''Run semaphore tracker.''' # protect the process from ^C and "killall python" etc signal.signal(signal.SIGINT, signal.SIG_IGN) signal.signal(signal.SIGTERM, signal.SIG_IGN) if _HAVE_SIGMASK: signal.pthread_sigmask(signal.SIG_UNBLOCK, _IGNORED_SIGNALS) for f in (sys.stdin, sys.stdout): try: f.close() except Exception: pass if verbose: # pragma: no cover sys.stderr.write("Main semaphore tracker is running\n") sys.stderr.flush() cache = set() try: # keep track of registered/unregistered semaphores with os.fdopen(fd, 'rb') as f: for line in f: try: cmd, name = line.strip().split(b':') if cmd == b'REGISTER': name = name.decode('ascii') cache.add(name) if verbose: # pragma: no cover sys.stderr.write("[SemaphoreTracker] register {}\n" .format(name)) sys.stderr.flush() elif cmd == b'UNREGISTER': name = name.decode('ascii') cache.remove(name)
python
{ "resource": "" }
q271722
SemaphoreTracker.ensure_running
test
def ensure_running(self): '''Make sure that semaphore tracker process is running. This can be run from any process. Usually a child process will use the semaphore created by its parent.''' with self._lock: if self._fd is not None: # semaphore tracker was launched before, is it still running? if self._check_alive(): # => still alive return # => dead, launch it again os.close(self._fd) try: # Clean-up to avoid dangling processes. os.waitpid(self._pid, 0) except OSError: # The process was terminated or is a child from an ancestor # of the current process. pass self._fd = None self._pid = None warnings.warn('semaphore_tracker: process died unexpectedly, ' 'relaunching. Some semaphores might leak.') fds_to_pass = [] try: fds_to_pass.append(sys.stderr.fileno()) except Exception: pass r, w = os.pipe() cmd = 'from {} import main; main({}, {})'.format( main.__module__, r, VERBOSE) try: fds_to_pass.append(r) # process will out live us, so no need to wait on pid exe = spawn.get_executable() args = [exe] + util._args_from_interpreter_flags() # In python 3.3, there is a bug which put `-RRRRR..` instead of # `-R` in args. Replace it to get the correct flags. # See https://github.com/python/cpython/blob/3.3/Lib/subprocess.py#L488 if sys.version_info[:2] <= (3, 3): import re for i in range(1, len(args)): args[i] = re.sub("-R+", "-R", args[i])
python
{ "resource": "" }
q271723
PrintProcessor.event_processor
test
def event_processor(self, frame, event, arg): 'A simple event processor that prints out events.' out = self.debugger.intf[-1].output lineno = frame.f_lineno filename = self.core.canonic_filename(frame) filename = self.core.filename(filename)
python
{ "resource": "" }
q271724
InfoPC.run
test
def run(self, args): """Program counter.""" mainfile = self.core.filename(None) if self.core.is_running(): curframe = self.proc.curframe if curframe: line_no = inspect.getlineno(curframe) offset = curframe.f_lasti self.msg("PC offset is %d." % offset) offset = max(offset, 0) code = curframe.f_code co_code = code.co_code disassemble_bytes(self.msg, self.msg_nocr, co_code, offset, line_no, line_no-1, line_no+1, constants=code.co_consts, cells=code.co_cellvars, varnames=code.co_varnames, freevars=code.co_freevars, linestarts=dict(findlinestarts(code)), end_offset=offset+10)
python
{ "resource": "" }
q271725
interact
test
def interact(banner=None, readfunc=None, my_locals=None, my_globals=None): """Almost a copy of code.interact Closely emulate the interactive Python interpreter. This is a backwards compatible interface to the InteractiveConsole class. When readfunc is not specified, it attempts to import the readline module to enable GNU readline if it is available. Arguments (all optional, all default to None): banner -- passed to InteractiveConsole.interact() readfunc -- if not None, replaces InteractiveConsole.raw_input() local -- passed to InteractiveInterpreter.__init__()
python
{ "resource": "" }
q271726
arg_split
test
def arg_split(s, posix=False): """Split a command line's arguments in a shell-like manner returned as a list of lists. Use ';;' with white space to indicate separate commands. This is a modified version of the standard library's shlex.split() function, but with a default of posix=False for splitting, so that quotes in inputs are respected. """ args_list = [[]] if isinstance(s, bytes):
python
{ "resource": "" }
q271727
get_stack
test
def get_stack(f, t, botframe, proc_obj=None): """Return a stack of frames which the debugger will use for in showing backtraces and in frame switching. As such various frame that are really around may be excluded unless we are debugging the sebugger. Also we will add traceback frame on top if that exists.""" exclude_frame = lambda f: False if proc_obj: settings = proc_obj.debugger.settings if not settings['dbg_trepan']: exclude_frame = lambda f: \ proc_obj.core.ignore_filter.is_included(f) pass pass stack =
python
{ "resource": "" }
q271728
run_hooks
test
def run_hooks(obj, hooks, *args): """Run each function in `hooks' with args""" for hook in hooks: if
python
{ "resource": "" }
q271729
CommandProcessor.forget
test
def forget(self): """ Remove memory of state variables set in the command processor """ self.stack = [] self.curindex = 0 self.curframe = None
python
{ "resource": "" }
q271730
CommandProcessor.get_int_noerr
test
def get_int_noerr(self, arg): """Eval arg and it is an integer return the value. Otherwise return None""" if self.curframe: g = self.curframe.f_globals l = self.curframe.f_locals else: g = globals() l = locals() pass
python
{ "resource": "" }
q271731
CommandProcessor.get_int
test
def get_int(self, arg, min_value=0, default=1, cmdname=None, at_most=None): """If no argument use the default. If arg is a an integer between least min_value and at_most, use that. Otherwise report an error. If there's a stack frame use that in evaluation.""" if arg is None: return default default = self.get_int_noerr(arg) if default is None: if cmdname: self.errmsg(("Command '%s' expects an integer; " + "got: %s.") % (cmdname, str(arg))) else: self.errmsg('Expecting a positive integer, got: %s' % str(arg))
python
{ "resource": "" }
q271732
CommandProcessor.process_commands
test
def process_commands(self): """Handle debugger commands.""" if self.core.execution_status != 'No program': self.setup() self.location() pass leave_loop = run_hooks(self, self.preloop_hooks) self.continue_running = False while not leave_loop: try: run_hooks(self, self.precmd_hooks) # bdb had a True return to leave loop. # A more straight-forward way is to set # instance variable self.continue_running. leave_loop = self.process_command() if leave_loop or self.continue_running: break except EOFError: # If we have stacked interfaces, pop to the next # one. If this is the last one however, we'll # just stick with that. FIXME: Possibly we should # check to see if we are interactive. and not #
python
{ "resource": "" }
q271733
CommandProcessor.queue_startfile
test
def queue_startfile(self, cmdfile): """Arrange for file of debugger commands to get read in the process-command loop.""" expanded_cmdfile = os.path.expanduser(cmdfile) is_readable = Mfile.readable(expanded_cmdfile) if is_readable: self.cmd_queue.append('source ' + expanded_cmdfile) elif is_readable
python
{ "resource": "" }
q271734
next_token
test
def next_token(str, start_pos): """Find the next token in str string from start_pos, we return the token and the next blank position after the token or str.size if this is the last token. Tokens are delimited by white space.""" look_at = str[start_pos:] match = re.search('\S', look_at)
python
{ "resource": "" }
q271735
ScriptInterface.errmsg
test
def errmsg(self, msg, prefix="** "): """Common routine for reporting debugger error messages. """ # self.verbose shows lines so we don't have to duplicate info # here. Perhaps there should be a 'terse' mode to never show # position info. if not self.verbose: location = ("%s:%s: Error in source command file" % (self.script_name, self.input_lineno)) msg
python
{ "resource": "" }
q271736
ScriptInterface.read_command
test
def read_command(self, prompt=''): '''Script interface to read a command. `prompt' is a parameter for compatibilty and is ignored.''' self.input_lineno += 1 line = self.readline() if self.verbose: location
python
{ "resource": "" }
q271737
FIFOClient.close
test
def close(self): """ Closes both input and output """ self.state = 'closing' if self.input: self.input.close() pass if self.output:
python
{ "resource": "" }
q271738
disassemble
test
def disassemble(msg, msg_nocr, section, co, lasti=-1, start_line=-1, end_line=None, relative_pos=False, highlight='light', start_offset=0, end_offset=None): """Disassemble a code object.""" return disassemble_bytes(msg, msg_nocr, co.co_code, lasti, co.co_firstlineno,
python
{ "resource": "" }
q271739
disassemble_bytes
test
def disassemble_bytes(orig_msg, orig_msg_nocr, code, lasti=-1, cur_line=0, start_line=-1, end_line=None, relative_pos=False, varnames=(), names=(), constants=(), cells=(), freevars=(), linestarts={}, highlight='light', start_offset=0, end_offset=None): """Disassemble byte string of code. If end_line is negative it counts the number of statement linestarts to use.""" statement_count = 10000 if end_line is None: end_line = 10000 elif relative_pos: end_line += start_line -1 pass labels = findlabels(code) null_print = lambda x: None if start_line > cur_line: msg_nocr = null_print msg = null_print else: msg_nocr = orig_msg_nocr msg = orig_msg for instr in get_instructions_bytes(code, opc, varnames, names, constants, cells, linestarts): offset = instr.offset if end_offset and offset > end_offset: break if instr.starts_line: if offset: msg("") cur_line = instr.starts_line if (start_line and ((start_line > cur_line) or start_offset and start_offset > offset)) : msg_nocr = null_print msg = null_print else: statement_count -= 1 msg_nocr = orig_msg_nocr msg = orig_msg pass if ((cur_line > end_line) or (end_offset and offset > end_offset)): break msg_nocr(format_token(Mformat.LineNumber,
python
{ "resource": "" }
q271740
count_frames
test
def count_frames(frame, count_start=0): "Return a count of the number of frames" count = -count_start while frame:
python
{ "resource": "" }
q271741
get_call_function_name
test
def get_call_function_name(frame): """If f_back is looking at a call function, return the name for it. Otherwise return None""" f_back = frame.f_back if not f_back: return None if 'CALL_FUNCTION' != Mbytecode.op_at_frame(f_back): return None co = f_back.f_code code = co.co_code # labels = dis.findlabels(code) linestarts = dict(dis.findlinestarts(co)) offset = f_back.f_lasti while offset >= 0: if offset in linestarts: op = code[offset] offset += 1 arg = code[offset] # FIXME: put this code in xdis extended_arg = 0 while True: if PYTHON_VERSION >= 3.6: if op == opc.EXTENDED_ARG:
python
{ "resource": "" }
q271742
print_stack_trace
test
def print_stack_trace(proc_obj, count=None, color='plain', opts={}): "Print count entries of the stack trace" if count is None: n=len(proc_obj.stack) else: n=min(len(proc_obj.stack), count) try: for i in range(n):
python
{ "resource": "" }
q271743
Subcmd.lookup
test
def lookup(self, subcmd_prefix): """Find subcmd in self.subcmds""" for subcmd_name in list(self.subcmds.keys()): if subcmd_name.startswith(subcmd_prefix) \
python
{ "resource": "" }
q271744
Subcmd.short_help
test
def short_help(self, subcmd_cb, subcmd_name, label=False): """Show short help for a subcommand.""" entry = self.lookup(subcmd_name) if entry: if label: prefix = entry.name else: prefix = '' pass if hasattr(entry, 'short_help'): if
python
{ "resource": "" }
q271745
Subcmd.add
test
def add(self, subcmd_cb): """Add subcmd to the available subcommands for this object. It will have the supplied docstring, and subcmd_cb will be called when we want to run the command. min_len is the minimum length allowed to abbreviate the command. in_list indicates with the show command will be run when giving a list of all sub commands of this object. Some
python
{ "resource": "" }
q271746
Subcmd.run
test
def run(self, subcmd_name, arg): """Run subcmd_name with args using obj for the environent""" entry=self.lookup(subcmd_name) if entry: entry['callback'](arg) else:
python
{ "resource": "" }
q271747
debug
test
def debug(dbg_opts=None, start_opts=None, post_mortem=True, step_ignore=1, level=0): """ Enter the debugger. Parameters ---------- level : how many stack frames go back. Usually it will be the default 0. But sometimes though there may be calls in setup to the debugger that you may want to skip. step_ignore : how many line events to ignore after the debug() call. 0 means don't even wait for the debug() call to finish. param dbg_opts : is an optional "options" dictionary that gets fed trepan.Debugger(); `start_opts' are the optional "options" dictionary that gets fed to trepan.Debugger.core.start(). Use like this: .. code-block:: python ... # Possibly some Python code import trepan.api # Needed only once ... # Possibly some more Python code trepan.api.debug() # You can wrap inside conditional logic too pass # Stop will be here. # Below is code you want to use the debugger to do things. .... # more Python code # If you get to a place in the program where you aren't going # want to debug any more, but want to remove debugger trace overhead: trepan.api.stop() Parameter "level" specifies how many stack frames go back. Usually it will be the default 0. But sometimes though there may be calls in setup to the debugger that you may want to skip. Parameter "step_ignore" specifies how many line events to ignore after the debug() call. 0 means don't even wait for the debug() call to finish. In situations where you want an immediate stop in the "debug" call rather than the statement following it ("pass" above), add parameter step_ignore=0 to debug() like this:: import trepan.api # Needed only once # ... as before trepan.api.debug(step_ignore=0) # ... as before Module variable _debugger_obj_ from module trepan.debugger is used as the debugger instance variable; it can be subsequently used to change settings or alter behavior. It should be of type Debugger (found in module trepan). If not, it will get changed to that type:: $ python >>> from trepan.debugger import debugger_obj >>> type(debugger_obj) <type 'NoneType'> >>> import trepan.api >>> trepan.api.debug() ... (Trepan) c >>> from trepan.debugger import debugger_obj >>> debugger_obj <trepan.debugger.Debugger instance at 0x7fbcacd514d0>
python
{ "resource": "" }
q271748
HelpCommand.show_category
test
def show_category(self, category, args): """Show short help for all commands in `category'.""" n2cmd = self.proc.commands names = list(n2cmd.keys()) if len(args) == 1 and args[0] == '*': self.section("Commands in class %s:" % category) cmds = [cmd for cmd in names if category == n2cmd[cmd].category] cmds.sort() self.msg_nocr(self.columnize_commands(cmds)) return self.msg("%s.\n" % categories[category]) self.section("List of commands:")
python
{ "resource": "" }
q271749
InfoLine.run
test
def run(self, args): """Current line number in source file""" # info line identifier if not self.proc.curframe: self.errmsg("No line number information available.") return if len(args) == 3: # lineinfo returns (item, file, lineno) or (None,) answer = self.lineinfo(args[2]) if answer[0]: item, filename, lineno = answer if not os.path.isfile(filename): filename = Mclifns.search_file(filename, self.core.search_path, self.main_dirname) self.msg('Line %s of "%s" <%s>' % (lineno, filename, item)) return filename=self.core.canonic_filename(self.proc.curframe) if not os.path.isfile(filename):
python
{ "resource": "" }
q271750
find_debugged_frame
test
def find_debugged_frame(frame): """Find the first frame that is a debugged frame. We do this Generally we want traceback information without polluting it with debugger frames. We can tell these because those are frames on the top which don't have f_trace set. So we'll look back from the top to find the fist frame where f_trace is set. """ f_prev = f = frame while f is not None and f.f_trace is None: f_prev = f f = f.f_back pass
python
{ "resource": "" }
q271751
map_thread_names
test
def map_thread_names(): '''Invert threading._active''' name2id = {} for thread_id in list(threading._active.keys()): thread = threading._active[thread_id] name = thread.getName()
python
{ "resource": "" }
q271752
get_int
test
def get_int(errmsg, arg, default=1, cmdname=None): """If arg is an int, use that otherwise take default.""" if arg: try: # eval() is used so we will allow arithmetic expressions, # variables etc. default = int(eval(arg))
python
{ "resource": "" }
q271753
get_onoff
test
def get_onoff(errmsg, arg, default=None, print_error=True): """Return True if arg is 'on' or 1 and False arg is 'off' or 0. Any other value is raises ValueError.""" if not arg: if default is None: if print_error: errmsg("Expecting 'on', 1, 'off', or 0. Got nothing.") pass raise ValueError return default if arg == '1'
python
{ "resource": "" }
q271754
run_set_bool
test
def run_set_bool(obj, args): """set a Boolean-valued debugger setting. 'obj' is a generally a subcommand that has 'name' and 'debugger.settings' attributes""" try: if 0 == len(args):
python
{ "resource": "" }
q271755
run_set_int
test
def run_set_int(obj, arg, msg_on_error, min_value=None, max_value=None): """set an Integer-valued debugger setting. 'obj' is a generally a subcommand that has 'name' and 'debugger.settings' attributes""" if '' == arg.strip(): obj.errmsg("You need to supply a number.") return
python
{ "resource": "" }
q271756
run_show_bool
test
def run_show_bool(obj, what=None): """Generic subcommand showing a boolean-valued debugger setting. 'obj' is generally a subcommand that
python
{ "resource": "" }
q271757
run_show_int
test
def run_show_int(obj, what=None): """Generic subcommand integer value display""" val = obj.debugger.settings[obj.name]
python
{ "resource": "" }
q271758
run_show_val
test
def run_show_val(obj, name): """Generic subcommand value display""" val = obj.debugger.settings[obj.name] obj.msg("%s is %s."
python
{ "resource": "" }
q271759
is_def_stmt
test
def is_def_stmt(line, frame): """Return True if we are looking at a def statement""" # Should really also check that operand of 'LOAD_CONST' is a code object return (line and _re_def.match(line) and op_at_frame(frame)=='LOAD_CONST'
python
{ "resource": "" }
q271760
is_class_def
test
def is_class_def(line, frame): """Return True if we are looking at a class definition statement""" return
python
{ "resource": "" }
q271761
QuitCommand.threaded_quit
test
def threaded_quit(self, arg): """ quit command when several threads are involved. """ threading_list = threading.enumerate() mythread = threading.currentThread() for t in threading_list: if t != mythread:
python
{ "resource": "" }
q271762
set_default_bg
test
def set_default_bg(): """Get bacground from default values based on the TERM environment variable """ term = environ.get('TERM', None) if term: if
python
{ "resource": "" }
q271763
is_dark_rgb
test
def is_dark_rgb(r, g, b): """Pass as parameters R G B values in hex On return, variable is_dark_bg is set """ try: midpoint = int(environ.get('TERMINAL_COLOR_MIDPOINT', None)) except: pass if not midpoint: term = environ.get('TERM', None) # 117963 = (* .6 (+ 65535 65535 65535))
python
{ "resource": "" }
q271764
signature
test
def signature(frame): '''return suitable frame signature to key display expressions off
python
{ "resource": "" }
q271765
DisplayMgr.all
test
def all(self): """List all display items; return 0 if none""" found = False s = [] for display in self.list:
python
{ "resource": "" }
q271766
DisplayMgr.display
test
def display(self, frame): '''display any items that are active''' if not frame: return s = [] sig = signature(frame) for display in self.list:
python
{ "resource": "" }
q271767
Display.format
test
def format(self, show_enabled=True): '''format display item''' what = '' if show_enabled: if self.enabled: what += ' y ' else: what += ' n ' pass pass
python
{ "resource": "" }
q271768
TCPClient.read_msg
test
def read_msg(self): """Read one message unit. It's possible however that more than one message will be set in a receive, so we will have to buffer that for the next read. EOFError will be raised on EOF. """ if self.state == 'connected': if 0 == len(self.buf): self.buf = self.inout.recv(Mtcpfns.TCP_MAX_PACKET) if 0 == (self.buf):
python
{ "resource": "" }
q271769
debug
test
def debug(frame=None): """Set breakpoint at current location, or a specified frame""" # ??? if frame is None: frame = _frame().f_back dbg = RemoteCeleryTrepan()
python
{ "resource": "" }
q271770
SubcommandMgr.undefined_subcmd
test
def undefined_subcmd(self, cmd, subcmd): """Error message when subcommand asked for but doesn't exist""" self.proc.intf[-1].errmsg(('Undefined "%s" subcommand: "%s". ' +
python
{ "resource": "" }
q271771
FrameCommand.run
test
def run(self, args): '''Run a frame command. This routine is a little complex because we allow a number parameter variations.''' if len(args) == 1: # Form is: "frame" which means "frame 0" position_str = '0' elif len(args) == 2: # Form is: "frame {position | thread} name_or_id = args[1] frame, thread_id = self.get_from_thread_name_or_id(name_or_id, False) if frame is None: # Form should be: frame position position_str = name_or_id else: # Form should be: "frame thread" which means # "frame thread 0" position_str = '0' self.find_and_set_debugged_frame(frame, thread_id)
python
{ "resource": "" }
q271772
pprint_simple_array
test
def pprint_simple_array(val, displaywidth, msg_nocr, msg, lineprefix=''): '''Try to pretty print a simple case where a list is not nested. Return True if we can do it and False if not. ''' if type(val) != list: return False numeric = True for i in range(len(val)): if not (type(val[i]) in [bool, float, int]): numeric = False if not (type(val[i]) in [bool, float, int, bytes]): return False pass
python
{ "resource": "" }
q271773
lookup_signame
test
def lookup_signame(num): """Find the corresponding signal name for 'num'. Return None if 'num' is invalid.""" signames = signal.__dict__ num = abs(num) for signame in list(signames.keys()):
python
{ "resource": "" }
q271774
lookup_signum
test
def lookup_signum(name): """Find the corresponding signal number for 'name'. Return None if 'name' is invalid.""" uname = name.upper() if (uname.startswith('SIG') and hasattr(signal, uname)): return getattr(signal, uname)
python
{ "resource": "" }
q271775
canonic_signame
test
def canonic_signame(name_num): """Return a signal name for a signal name or signal number. Return None is name_num is an int but not a valid signal number and False if name_num is a not number. If name_num is a signal name or signal number, the canonic if name is returned.""" signum = lookup_signum(name_num) if signum is None: # Maybe signame is a number? try: num = int(name_num) signame = lookup_signame(num)
python
{ "resource": "" }
q271776
SignalManager.set_signal_replacement
test
def set_signal_replacement(self, signum, handle): """A replacement for signal.signal which chains the signal behind the debugger's handler""" signame = lookup_signame(signum) if signame is None: self.dbgr.intf[-1].errmsg(("%s is not a signal number" " I know about.") % signum) return False # Since the
python
{ "resource": "" }
q271777
SignalManager.check_and_adjust_sighandlers
test
def check_and_adjust_sighandlers(self): """Check to see if any of the signal handlers we are interested in have changed or is not initially set. Change
python
{ "resource": "" }
q271778
SignalManager.info_signal
test
def info_signal(self, args): """Print information about a signal""" if len(args) == 0: return None signame = args[0] if signame in ['handle', 'signal']: # This has come from dbgr's info command if len(args) == 1: # Show all signal handlers self.dbgr.core.processor.section(self.header) for signame in self.siglist: self.print_info_signal_entry(signame)
python
{ "resource": "" }
q271779
SignalManager.action
test
def action(self, arg): """Delegate the actions specified in 'arg' to another method. """ if not arg: self.info_signal(['handle']) return True args = arg.split() signame = args[0] signame = self.is_name_or_number(args[0]) if not signame: return if len(args) == 1: self.info_signal([signame]) return True # We can display information about 'fatal' signals, but not # change their actions. if signame in fatal_signals: return None if signame not in list(self.sigs.keys()): if not self.initialize_handler(signame): return None pass # multiple commands might be specified, i.e. 'nopass nostop' for attr in args[1:]: if attr.startswith('no'): on = False attr = attr[2:] else: on = True if
python
{ "resource": "" }
q271780
SignalManager.handle_print
test
def handle_print(self, signame, set_print): """Set whether we print or not when this signal is caught.""" if set_print: self.sigs[signame].print_method = self.dbgr.intf[-1].msg
python
{ "resource": "" }
q271781
SigHandler.handle
test
def handle(self, signum, frame): """This method is called when a signal is received.""" if self.print_method: self.print_method('\nProgram received signal %s.' % self.signame) if self.print_stack: import traceback strings = traceback.format_stack(frame) for s in strings: if s[-1] == '\n': s = s[0:-1] self.print_method(s) pass pass if self.b_stop: core = self.dbgr.core old_trace_hook_suspend = core.trace_hook_suspend core.trace_hook_suspend = True core.stop_reason = ('intercepting signal %s (%d)' % (self.signame, signum))
python
{ "resource": "" }
q271782
file2module
test
def file2module(filename): """Given a file name, extract the most likely module name. """ basename = osp.basename(filename) if '.' in basename: pos
python
{ "resource": "" }
q271783
search_file
test
def search_file(filename, directories, cdir): """Return a full pathname for filename if we can find one. path is a list of directories to prepend to filename. If no file is found we'll return None""" for trydir in directories: # Handle $cwd and $cdir if trydir =='$cwd': trydir='.'
python
{ "resource": "" }
q271784
whence_file
test
def whence_file(py_script, dirnames=None): """Do a shell-like path lookup for py_script and return the results. If we can't find anything return py_script""" if py_script.find(os.sep) != -1: # Don't search since this name has path separator components return py_script if dirnames is None: dirnames = os.environ['PATH'].split(os.pathsep)
python
{ "resource": "" }
q271785
pyfiles
test
def pyfiles(callername, level=2): "All python files caller's dir without the path and trailing .py" d = os.path.dirname(callername) # Get the name of our directory. # A glob pattern that will get all *.py files but not __init__.py
python
{ "resource": "" }
q271786
TrepanInterface.msg
test
def msg(self, msg): """ used to write to a debugger that is connected to this server; `str' written will have a newline added to it """ if hasattr(self.output, 'writeline'): self.output.writeline(msg)
python
{ "resource": "" }
q271787
InfoProgram.run
test
def run(self, args): """Execution status of the program.""" mainfile = self.core.filename(None) if self.core.is_running(): if mainfile: part1 = "Python program '%s' is stopped" % mainfile else: part1 = 'Program is stopped' pass if self.proc.event: msg = 'via a %s event.' % self.proc.event else: msg = '.' self.msg(Mmisc.wrapped_lines(part1, msg, self.settings['width'])) if self.proc.curframe: self.msg("PC offset is %d." % self.proc.curframe.f_lasti) if self.proc.event == 'return': val = self.proc.event_arg part1 = 'Return value is' self.msg(Mmisc.wrapped_lines(part1, self.proc._saferepr(val),
python
{ "resource": "" }
q271788
DebuggerCommand.columnize_commands
test
def columnize_commands(self, commands): """List commands arranged in an aligned columns""" commands.sort() width = self.debugger.settings['width']
python
{ "resource": "" }
q271789
post_mortem
test
def post_mortem(exc=None, frameno=1, dbg=None): """Enter debugger read loop after your program has crashed. exc is a triple like you get back from sys.exc_info. If no exc parameter, is supplied, the values from sys.last_type, sys.last_value, sys.last_traceback are used. And if these don't exist either we'll assume that sys.exc_info() contains what we want and frameno is the index location of where we want to start. 'frameno' specifies how many frames to ignore in the traceback. The default is 1, that is, we don't need to show the immediate call into post_mortem. If you have wrapper functions that call this one, you may want to increase frameno. """ if dbg is None: # Check for a global debugger object if Mdebugger.debugger_obj is None: Mdebugger.debugger_obj = Mdebugger.Trepan() pass dbg = Mdebugger.debugger_obj pass re_bogus_file = re.compile("^<.+>$") if exc[0] is None: # frameno+1 because we are about to add one more level of call # in get_last_or_frame_exception exc = get_last_or_frame_exception() if exc[0] is None: print("Can't find traceback for post_mortem " "in sys.last_traceback or sys.exec_info()") return pass exc_type, exc_value, exc_tb = exc dbg.core.execution_status = ('Terminated with unhandled exception %s' % exc_type) # tb has least-recent traceback entry first. We want the most-recent # entry. Also we'll pick out a mainpyfile name if it hasn't previously # been set. if exc_tb is not None: while exc_tb.tb_next is not None: filename = exc_tb.tb_frame.f_code.co_filename if (dbg.mainpyfile and 0 == len(dbg.mainpyfile) and not re_bogus_file.match(filename)): dbg.mainpyfile = filename pass exc_tb = exc_tb.tb_next pass dbg.core.processor.curframe = exc_tb.tb_frame pass if 0 == len(dbg.program_sys_argv): # Fake program (run command) args since we weren't called with any dbg.program_sys_argv = list(sys.argv[1:]) dbg.program_sys_argv[:0] = [dbg.mainpyfile]
python
{ "resource": "" }
q271790
TCPServer.close
test
def close(self): """ Closes both socket and server connection. """ self.state = 'closing' if self.inout: self.inout.close() pass self.state =
python
{ "resource": "" }
q271791
TCPServer.write
test
def write(self, msg): """ This method the debugger uses to write. In contrast to writeline, no newline is added to the end to `str'. Also msg doesn't have to be a string. """ if self.state != 'connected': self.wait_for_connect() pass
python
{ "resource": "" }
q271792
complete_identifier
test
def complete_identifier(cmd, prefix): '''Complete an arbitrary expression.''' if not cmd.proc.curframe: return [None] # Collect globals and locals. It is usually not really sensible to also # complete builtins, and they clutter the namespace quite heavily, so we # leave them out. ns = cmd.proc.curframe.f_globals.copy() ns.update(cmd.proc.curframe.f_locals) if '.' in prefix: # Walk an attribute chain up to the last part, similar to what # rlcompleter does. This will bail if any of the parts are not # simple attribute access, which is what we want. dotted = prefix.split('.') try:
python
{ "resource": "" }
q271793
PythonCommand.dbgr
test
def dbgr(self, string): '''Invoke a debugger command from inside a python shell called inside the debugger. ''' print('')
python
{ "resource": "" }
q271794
TrepanCore.add_ignore
test
def add_ignore(self, *frames_or_fns): """Add `frame_or_fn' to the list of functions that are not to
python
{ "resource": "" }
q271795
TrepanCore.canonic
test
def canonic(self, filename): """ Turns `filename' into its canonic representation and returns this string. This allows a user to refer to a given file in one of several equivalent ways. Relative filenames need to be fully resolved, since the current working directory might change over the course of execution. If filename is enclosed in < ... >, then we assume it is one of the bogus internal Python names like <string> which is seen for example when executing "exec cmd". """ if filename == "<" + filename[1:-1] + ">": return filename canonic = self.filename_cache.get(filename) if not canonic: lead_dir = filename.split(os.sep)[0] if lead_dir == os.curdir or lead_dir == os.pardir: # We may have invoked the program from a directory # other than where the program resides. filename is # relative to where the program resides. So make sure # to use that.
python
{ "resource": "" }
q271796
TrepanCore.filename
test
def filename(self, filename=None): """Return filename or the basename of that depending on the basename setting""" if filename is None: if self.debugger.mainpyfile: filename = self.debugger.mainpyfile
python
{ "resource": "" }
q271797
TrepanCore.is_started
test
def is_started(self): '''Return True if debugging is in progress.''' return (tracer.is_started() and
python
{ "resource": "" }
q271798
TrepanCore.is_stop_here
test
def is_stop_here(self, frame, event, arg): """ Does the magic to determine if we stop here and run a command processor or not. If so, return True and set self.stop_reason; if not, return False. Determining factors can be whether a breakpoint was encountered, whether we are stepping, next'ing, finish'ing, and, if so, whether there is an ignore counter. """ # Add an generic event filter here? # FIXME TODO: Check for # - thread switching (under set option) # Check for "next" and "finish" stopping via stop_level # Do we want a different line and if so, # do we have one? lineno = frame.f_lineno filename = frame.f_code.co_filename if self.different_line and event == 'line': if self.last_lineno == lineno and self.last_filename == filename: return False pass self.last_lineno = lineno self.last_filename = filename if self.stop_level is not None: if frame != self.last_frame: # Recompute stack_depth
python
{ "resource": "" }
q271799
TrepanCore.set_next
test
def set_next(self, frame, step_ignore=0, step_events=None): "Sets to stop on the next event that happens in frame 'frame'." self.step_events = None # Consider all events self.stop_level = Mstack.count_frames(frame) self.last_level = self.stop_level
python
{ "resource": "" }