id int64 0 190k | prompt stringlengths 21 13.4M | docstring stringlengths 1 12k ⌀ |
|---|---|---|
177,673 | from _pydevd_bundle.pydevd_constants import DebugInfoHolder, SHOW_COMPILE_CYTHON_COMMAND_LINE, NULL, LOG_TIME, \
ForkSafeLock
from contextlib import contextmanager
import traceback
import os
import sys
import time
def error_once(msg, *args):
try:
if args:
message = msg % args
else:
message = str(msg)
except:
message = '%s - %s' % (msg, args)
if message not in _LoggingGlobals._warn_once_map:
_LoggingGlobals._warn_once_map[message] = True
critical(message)
SHOW_COMPILE_CYTHON_COMMAND_LINE = is_true_in_env('PYDEVD_SHOW_COMPILE_CYTHON_COMMAND_LINE')
def show_compile_cython_command_line():
if SHOW_COMPILE_CYTHON_COMMAND_LINE:
dirname = os.path.dirname(os.path.dirname(__file__))
error_once("warning: Debugger speedups using cython not found. Run '\"%s\" \"%s\" build_ext --inplace' to build.",
sys.executable, os.path.join(dirname, 'setup_pydevd_cython.py')) | null |
177,674 | import sys
import os
def find_in_pythonpath(module_name):
# Check all the occurrences where we could match the given module/package in the PYTHONPATH.
#
# This is a simplistic approach, but probably covers most of the cases we're interested in
# (i.e.: this may fail in more elaborate cases of import customization or .zip imports, but
# this should be rare in general).
found_at = []
parts = module_name.split('.') # split because we need to convert mod.name to mod/name
for path in sys.path:
target = os.path.join(path, *parts)
target_py = target + '.py'
if os.path.isdir(target):
found_at.append(target)
if os.path.exists(target_py):
found_at.append(target_py)
return found_at | null |
177,675 | import traceback
from io import StringIO
from java.lang import StringBuffer
from java.lang import String
import java.lang
import sys
from _pydev_bundle._pydev_tipper_common import do_find
from org.python.core import PyReflectedFunction
from org.python import core
from org.python.core import PyClass
import java.util
def Find(name):
f = None
if name.startswith('__builtin__'):
if name == '__builtin__.str':
name = 'org.python.core.PyString'
elif name == '__builtin__.dict':
name = 'org.python.core.PyDictionary'
mod = _imp(name)
parent = mod
foundAs = ''
try:
f = getattr(mod, '__file__', None)
except:
f = None
components = name.split('.')
old_comp = None
for comp in components[1:]:
try:
# this happens in the following case:
# we have mx.DateTime.mxDateTime.mxDateTime.pyd
# but after importing it, mx.DateTime.mxDateTime does shadows access to mxDateTime.pyd
mod = getattr(mod, comp)
except AttributeError:
if old_comp != comp:
raise
if hasattr(mod, '__file__'):
f = mod.__file__
else:
if len(foundAs) > 0:
foundAs = foundAs + '.'
foundAs = foundAs + comp
old_comp = comp
if f is None and name.startswith('java.lang'):
# Hack: java.lang.__file__ is None on Jython 2.7 (whereas it pointed to rt.jar on Jython 2.5).
f = _java_rt_file
if f is not None:
if f.endswith('.pyc'):
f = f[:-1]
elif f.endswith('$py.class'):
f = f[:-len('$py.class')] + '.py'
return f, mod, parent, foundAs
def generate_imports_tip_for_module(obj_to_complete, dir_comps=None, getattr=getattr, filter=lambda name:True):
'''
name, doc, args, type (from the TYPE_* constants)
'''
ret = []
if dir_comps is None:
dir_comps = dir_obj(obj_to_complete)
for d in dir_comps:
if d is None:
continue
if not filter(d):
continue
args = ''
doc = ''
retType = TYPE_BUILTIN
try:
obj = getattr(obj_to_complete, d)
except (AttributeError, java.lang.NoClassDefFoundError):
# jython has a bug in its custom classloader that prevents some things from working correctly, so, let's see if
# we can fix that... (maybe fixing it in jython itself would be a better idea, as this is clearly a bug)
# for that we need a custom classloader... we have references from it in the below places:
#
# http://mindprod.com/jgloss/classloader.html
# http://www.javaworld.com/javaworld/jw-03-2000/jw-03-classload-p2.html
# http://freshmeat.net/articles/view/1643/
#
# note: this only happens when we add things to the sys.path at runtime, if they are added to the classpath
# before the run, everything goes fine.
#
# The code below ilustrates what I mean...
#
# import sys
# sys.path.insert(1, r"C:\bin\eclipse310\plugins\org.junit_3.8.1\junit.jar" )
#
# import junit.framework
# print_ dir(junit.framework) #shows the TestCase class here
#
# import junit.framework.TestCase
#
# raises the error:
# Traceback (innermost last):
# File "<console>", line 1, in ?
# ImportError: No module named TestCase
#
# whereas if we had added the jar to the classpath before, everything would be fine by now...
ret.append((d, '', '', retType))
# that's ok, private things cannot be gotten...
continue
else:
isMet = ismethod(obj)
if isMet[0] and isMet[1]:
info = isMet[1][0]
try:
args, vargs, kwargs = info.args, info.varargs, info.kwargs
doc = info.get_as_doc()
r = ''
for a in (args):
if len(r) > 0:
r += ', '
r += format_arg(a)
args = '(%s)' % (r)
except TypeError:
traceback.print_exc()
args = '()'
retType = TYPE_FUNCTION
elif isclass(obj):
retType = TYPE_CLASS
elif ismodule(obj):
retType = TYPE_IMPORT
# add token and doc to return - assure only strings.
ret.append((d, doc, args, retType))
return ret
def generate_tip(data, log=None):
data = data.replace('\n', '')
if data.endswith('.'):
data = data.rstrip('.')
f, mod, parent, foundAs = Find(data)
tips = generate_imports_tip_for_module(mod)
return f, tips | null |
177,676 | import traceback
from io import StringIO
from java.lang import StringBuffer
from java.lang import String
import java.lang
import sys
from _pydev_bundle._pydev_tipper_common import do_find
from org.python.core import PyReflectedFunction
from org.python import core
from org.python.core import PyClass
import java.util
def Find(name):
f = None
if name.startswith('__builtin__'):
if name == '__builtin__.str':
name = 'org.python.core.PyString'
elif name == '__builtin__.dict':
name = 'org.python.core.PyDictionary'
mod = _imp(name)
parent = mod
foundAs = ''
try:
f = getattr(mod, '__file__', None)
except:
f = None
components = name.split('.')
old_comp = None
for comp in components[1:]:
try:
# this happens in the following case:
# we have mx.DateTime.mxDateTime.mxDateTime.pyd
# but after importing it, mx.DateTime.mxDateTime does shadows access to mxDateTime.pyd
mod = getattr(mod, comp)
except AttributeError:
if old_comp != comp:
raise
if hasattr(mod, '__file__'):
f = mod.__file__
else:
if len(foundAs) > 0:
foundAs = foundAs + '.'
foundAs = foundAs + comp
old_comp = comp
if f is None and name.startswith('java.lang'):
# Hack: java.lang.__file__ is None on Jython 2.7 (whereas it pointed to rt.jar on Jython 2.5).
f = _java_rt_file
if f is not None:
if f.endswith('.pyc'):
f = f[:-1]
elif f.endswith('$py.class'):
f = f[:-len('$py.class')] + '.py'
return f, mod, parent, foundAs
def do_find(f, mod):
import linecache
if inspect.ismodule(mod):
return f, 0, 0
lines = linecache.getlines(f)
if inspect.isclass(mod):
name = mod.__name__
pat = re.compile(r'^\s*class\s*' + name + r'\b')
for i in range(len(lines)):
if pat.match(lines[i]):
return f, i, 0
return f, 0, 0
if inspect.ismethod(mod):
mod = mod.im_func
if inspect.isfunction(mod):
try:
mod = mod.func_code
except AttributeError:
mod = mod.__code__ # python 3k
if inspect.istraceback(mod):
mod = mod.tb_frame
if inspect.isframe(mod):
mod = mod.f_code
if inspect.iscode(mod):
if not hasattr(mod, 'co_filename'):
return None, 0, 0
if not hasattr(mod, 'co_firstlineno'):
return mod.co_filename, 0, 0
lnum = mod.co_firstlineno
pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
while lnum > 0:
if pat.match(lines[lnum]):
break
lnum -= 1
return f, lnum, 0
raise RuntimeError('Do not know about: ' + f + ' ' + str(mod))
The provided code snippet includes necessary dependencies for implementing the `search_definition` function. Write a Python function `def search_definition(data)` to solve the following problem:
@return file, line, col
Here is the function:
def search_definition(data):
'''@return file, line, col
'''
data = data.replace('\n', '')
if data.endswith('.'):
data = data.rstrip('.')
f, mod, parent, foundAs = Find(data)
try:
return do_find(f, mod), foundAs
except:
return do_find(f, parent), foundAs | @return file, line, col |
177,677 | import sys
import os
from _pydev_bundle._pydev_execfile import execfile
class UserModuleDeleter:
"""
User Module Deleter (UMD) aims at deleting user modules
to force Python to deeply reload them during import
pathlist [list]: ignore list in terms of module path
namelist [list]: ignore list in terms of module name
"""
def __init__(self, namelist=None, pathlist=None):
if namelist is None:
namelist = []
self.namelist = namelist
if pathlist is None:
pathlist = []
self.pathlist = pathlist
try:
# ignore all files in org.python.pydev/pysrc
import pydev_pysrc, inspect
self.pathlist.append(os.path.dirname(pydev_pysrc.__file__))
except:
pass
self.previous_modules = list(sys.modules.keys())
def is_module_ignored(self, modname, modpath):
for path in [sys.prefix] + self.pathlist:
if modpath.startswith(path):
return True
else:
return set(modname.split('.')) & set(self.namelist)
def run(self, verbose=False):
"""
Del user modules to force Python to deeply reload them
Do not del modules which are considered as system modules, i.e.
modules installed in subdirectories of Python interpreter's binary
Do not del C modules
"""
log = []
modules_copy = dict(sys.modules)
for modname, module in modules_copy.items():
if modname == 'aaaaa':
print(modname, module)
print(self.previous_modules)
if modname not in self.previous_modules:
modpath = getattr(module, '__file__', None)
if modpath is None:
# *module* is a C module that is statically linked into the
# interpreter. There is no way to know its path, so we
# choose to ignore it.
continue
if not self.is_module_ignored(modname, modpath):
log.append(modname)
del sys.modules[modname]
if verbose and log:
print("\x1b[4;33m%s\x1b[24m%s\x1b[0m" % ("UMD has deleted",
": " + ", ".join(log)))
__umd__ = None
def _get_globals():
"""Return current Python interpreter globals namespace"""
if _get_globals_callback is not None:
return _get_globals_callback()
else:
try:
from __main__ import __dict__ as namespace
except ImportError:
try:
# The import fails on IronPython
import __main__
namespace = __main__.__dict__
except:
namespace
shell = namespace.get('__ipythonshell__')
if shell is not None and hasattr(shell, 'user_ns'):
# IPython 0.12+ kernel
return shell.user_ns
else:
# Python interpreter
return namespace
return namespace
def execfile(file, glob=None, loc=None):
if glob is None:
import sys
glob = sys._getframe().f_back.f_globals
if loc is None:
loc = glob
import tokenize
with tokenize.open(file) as stream:
contents = stream.read()
# execute the script (note: it's important to compile first to have the filename set in debug mode)
exec(compile(contents + "\n", file, 'exec'), glob, loc)
The provided code snippet includes necessary dependencies for implementing the `runfile` function. Write a Python function `def runfile(filename, args=None, wdir=None, namespace=None)` to solve the following problem:
Run filename args: command line arguments (string) wdir: working directory
Here is the function:
def runfile(filename, args=None, wdir=None, namespace=None):
"""
Run filename
args: command line arguments (string)
wdir: working directory
"""
try:
if hasattr(filename, 'decode'):
filename = filename.decode('utf-8')
except (UnicodeError, TypeError):
pass
global __umd__
if os.environ.get("PYDEV_UMD_ENABLED", "").lower() == "true":
if __umd__ is None:
namelist = os.environ.get("PYDEV_UMD_NAMELIST", None)
if namelist is not None:
namelist = namelist.split(',')
__umd__ = UserModuleDeleter(namelist=namelist)
else:
verbose = os.environ.get("PYDEV_UMD_VERBOSE", "").lower() == "true"
__umd__.run(verbose=verbose)
if args is not None and not isinstance(args, (bytes, str)):
raise TypeError("expected a character buffer object")
if namespace is None:
namespace = _get_globals()
if '__file__' in namespace:
old_file = namespace['__file__']
else:
old_file = None
namespace['__file__'] = filename
sys.argv = [filename]
if args is not None:
for arg in args.split():
sys.argv.append(arg)
if wdir is not None:
try:
if hasattr(wdir, 'decode'):
wdir = wdir.decode('utf-8')
except (UnicodeError, TypeError):
pass
os.chdir(wdir)
execfile(filename, namespace)
sys.argv = ['']
if old_file is None:
del namespace['__file__']
else:
namespace['__file__'] = old_file | Run filename args: command line arguments (string) wdir: working directory |
177,678 | import os
import re
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import get_global_debugger, IS_WINDOWS, IS_JYTHON, get_current_thread_id, \
sorted_dict_repr, set_global_debugger, DebugInfoHolder
from _pydev_bundle import pydev_log
from contextlib import contextmanager
from _pydevd_bundle import pydevd_constants, pydevd_defaults
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
import ast
_arg_patch = threading.local()
def skip_subprocess_arg_patch():
_arg_patch.apply_arg_patching = False
try:
yield
finally:
_arg_patch.apply_arg_patching = True | null |
177,679 | import os
import re
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import get_global_debugger, IS_WINDOWS, IS_JYTHON, get_current_thread_id, \
sorted_dict_repr, set_global_debugger, DebugInfoHolder
from _pydev_bundle import pydev_log
from contextlib import contextmanager
from _pydevd_bundle import pydevd_constants, pydevd_defaults
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
import ast
def _on_set_trace_for_new_thread(global_debugger):
if global_debugger is not None:
global_debugger.enable_tracing() | null |
177,680 | import os
import re
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import get_global_debugger, IS_WINDOWS, IS_JYTHON, get_current_thread_id, \
sorted_dict_repr, set_global_debugger, DebugInfoHolder
from _pydev_bundle import pydev_log
from contextlib import contextmanager
from _pydevd_bundle import pydevd_constants, pydevd_defaults
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
import ast
def monkey_patch_module(module, funcname, create_func):
if hasattr(module, funcname):
original_name = 'original_' + funcname
if not hasattr(module, original_name):
setattr(module, original_name, getattr(module, funcname))
setattr(module, funcname, create_func(original_name))
def monkey_patch_os(funcname, create_func):
monkey_patch_module(os, funcname, create_func)
def create_warn_multiproc(original_name):
def new_warn_multiproc(*args, **kwargs):
import os
warn_multiproc()
return getattr(os, original_name)(*args, **kwargs)
return new_warn_multiproc
def create_warn_fork_exec(original_name):
"""
_posixsubprocess.fork_exec(args, executable_list, close_fds, ... (13 more))
"""
def new_warn_fork_exec(*args):
try:
import _posixsubprocess
warn_multiproc()
return getattr(_posixsubprocess, original_name)(*args)
except:
pass
return new_warn_fork_exec
def create_subprocess_warn_fork_exec(original_name):
"""
subprocess._fork_exec(args, executable_list, close_fds, ... (13 more))
"""
def new_warn_fork_exec(*args):
try:
import subprocess
warn_multiproc()
return getattr(subprocess, original_name)(*args)
except:
pass
return new_warn_fork_exec
def create_CreateProcessWarnMultiproc(original_name):
"""
CreateProcess(*args, **kwargs)
"""
def new_CreateProcess(*args):
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
warn_multiproc()
return getattr(_subprocess, original_name)(*args)
return new_CreateProcess
IS_WINDOWS = sys.platform == 'win32'
IS_JYTHON = pydevd_vm_type.get_vm_type() == pydevd_vm_type.PydevdVmType.JYTHON
if IS_JYTHON:
import java.lang.System # @UnresolvedImport
IS_WINDOWS = java.lang.System.getProperty("os.name").lower().startswith("windows")
if IS_JYTHON:
def ForkSafeLock(rlock=False):
if rlock:
return threading.RLock()
else:
return threading.Lock()
else:
class ForkSafeLock(object):
'''
A lock which is fork-safe (when a fork is done, `pydevd_constants.after_fork()`
should be called to reset the locks in the new process to avoid deadlocks
from a lock which was locked during the fork).
Note:
Unlike `threading.Lock` this class is not completely atomic, so, doing:
lock = ForkSafeLock()
with lock:
...
is different than using `threading.Lock` directly because the tracing may
find an additional function call on `__enter__` and on `__exit__`, so, it's
not recommended to use this in all places, only where the forking may be important
(so, for instance, the locks on PyDB should not be changed to this lock because
of that -- and those should all be collected in the new process because PyDB itself
should be completely cleared anyways).
It's possible to overcome this limitation by using `ForkSafeLock.acquire` and
`ForkSafeLock.release` instead of the context manager (as acquire/release are
bound to the original implementation, whereas __enter__/__exit__ is not due to Python
limitations).
'''
def __init__(self, rlock=False):
self._rlock = rlock
self._init()
_fork_safe_locks.append(weakref.ref(self))
def __enter__(self):
return self._lock.__enter__()
def __exit__(self, exc_type, exc_val, exc_tb):
return self._lock.__exit__(exc_type, exc_val, exc_tb)
def _init(self):
if self._rlock:
self._lock = threading.RLock()
else:
self._lock = thread.allocate_lock()
self.acquire = self._lock.acquire
self.release = self._lock.release
_fork_safe_locks.append(weakref.ref(self))
if IS_JYTHON:
def NO_FTRACE(frame, event, arg):
return None
else:
_curr_trace = sys.gettrace()
# Set a temporary trace which does nothing for us to test (otherwise setting frame.f_trace has no
# effect).
def _temp_trace(frame, event, arg):
return None
sys.settrace(_temp_trace)
def _check_ftrace_set_none():
'''
Will throw an error when executing a line event
'''
sys._getframe().f_trace = None
_line_event = 1
_line_event = 2
try:
_check_ftrace_set_none()
def NO_FTRACE(frame, event, arg):
frame.f_trace = None
return None
except TypeError:
def NO_FTRACE(frame, event, arg):
# In Python <= 2.6 and <= 3.4, if we're tracing a method, frame.f_trace may not be set
# to None, it must always be set to a tracing function.
# See: tests_python.test_tracing_gotchas.test_tracing_gotchas
#
# Note: Python 2.7 sometimes works and sometimes it doesn't depending on the minor
# version because of https://bugs.python.org/issue20041 (although bug reports didn't
# include the minor version, so, mark for any Python 2.7 as I'm not completely sure
# the fix in later 2.7 versions is the same one we're dealing with).
return None
sys.settrace(_curr_trace)
def patch_new_process_functions_with_warning():
monkey_patch_os('execl', create_warn_multiproc)
monkey_patch_os('execle', create_warn_multiproc)
monkey_patch_os('execlp', create_warn_multiproc)
monkey_patch_os('execlpe', create_warn_multiproc)
monkey_patch_os('execv', create_warn_multiproc)
monkey_patch_os('execve', create_warn_multiproc)
monkey_patch_os('execvp', create_warn_multiproc)
monkey_patch_os('execvpe', create_warn_multiproc)
monkey_patch_os('spawnl', create_warn_multiproc)
monkey_patch_os('spawnle', create_warn_multiproc)
monkey_patch_os('spawnlp', create_warn_multiproc)
monkey_patch_os('spawnlpe', create_warn_multiproc)
monkey_patch_os('spawnv', create_warn_multiproc)
monkey_patch_os('spawnve', create_warn_multiproc)
monkey_patch_os('spawnvp', create_warn_multiproc)
monkey_patch_os('spawnvpe', create_warn_multiproc)
monkey_patch_os('posix_spawn', create_warn_multiproc)
if not IS_JYTHON:
if not IS_WINDOWS:
monkey_patch_os('fork', create_warn_multiproc)
try:
import _posixsubprocess
monkey_patch_module(_posixsubprocess, 'fork_exec', create_warn_fork_exec)
except ImportError:
pass
try:
import subprocess
monkey_patch_module(subprocess, '_fork_exec', create_subprocess_warn_fork_exec)
except AttributeError:
pass
else:
# Windows
try:
import _subprocess
except ImportError:
import _winapi as _subprocess
monkey_patch_module(_subprocess, 'CreateProcess', create_CreateProcessWarnMultiproc) | null |
177,681 | import os
import re
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import get_global_debugger, IS_WINDOWS, IS_JYTHON, get_current_thread_id, \
sorted_dict_repr, set_global_debugger, DebugInfoHolder
from _pydev_bundle import pydev_log
from contextlib import contextmanager
from _pydevd_bundle import pydevd_constants, pydevd_defaults
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
import ast
threading_modules_to_patch = _get_threading_modules_to_patch()
def _get_threading_modules_to_patch():
threading_modules_to_patch = []
try:
import thread as _thread
except:
import _thread
threading_modules_to_patch.append(_thread)
threading_modules_to_patch.append(threading)
return threading_modules_to_patch | null |
177,682 | import os
import re
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import get_global_debugger, IS_WINDOWS, IS_JYTHON, get_current_thread_id, \
sorted_dict_repr, set_global_debugger, DebugInfoHolder
from _pydev_bundle import pydev_log
from contextlib import contextmanager
from _pydevd_bundle import pydevd_constants, pydevd_defaults
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
import ast
threading_modules_to_patch = _get_threading_modules_to_patch()
def patch_thread_module(thread_module):
if getattr(thread_module, '_original_start_new_thread', None) is None:
if thread_module is threading:
if not hasattr(thread_module, '_start_new_thread'):
return # Jython doesn't have it.
_original_start_new_thread = thread_module._original_start_new_thread = thread_module._start_new_thread
else:
_original_start_new_thread = thread_module._original_start_new_thread = thread_module.start_new_thread
else:
_original_start_new_thread = thread_module._original_start_new_thread
class ClassWithPydevStartNewThread:
def pydev_start_new_thread(self, function, args=(), kwargs={}):
'''
We need to replace the original thread_module.start_new_thread with this function so that threads started
through it and not through the threading module are properly traced.
'''
return _original_start_new_thread(_UseNewThreadStartup(function, args, kwargs), ())
# This is a hack for the situation where the thread_module.start_new_thread is declared inside a class, such as the one below
# class F(object):
# start_new_thread = thread_module.start_new_thread
#
# def start_it(self):
# self.start_new_thread(self.function, args, kwargs)
# So, if it's an already bound method, calling self.start_new_thread won't really receive a different 'self' -- it
# does work in the default case because in builtins self isn't passed either.
pydev_start_new_thread = ClassWithPydevStartNewThread().pydev_start_new_thread
try:
# We need to replace the original thread_module.start_new_thread with this function so that threads started through
# it and not through the threading module are properly traced.
if thread_module is threading:
thread_module._start_new_thread = pydev_start_new_thread
else:
thread_module.start_new_thread = pydev_start_new_thread
thread_module.start_new = pydev_start_new_thread
except:
pass
def patch_thread_modules():
for t in threading_modules_to_patch:
patch_thread_module(t) | null |
177,683 | import os
import re
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import get_global_debugger, IS_WINDOWS, IS_JYTHON, get_current_thread_id, \
sorted_dict_repr, set_global_debugger, DebugInfoHolder
from _pydev_bundle import pydev_log
from contextlib import contextmanager
from _pydevd_bundle import pydevd_constants, pydevd_defaults
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
import ast
class _NewThreadStartupWithoutTrace:
def __init__(self, original_func, args, kwargs):
self.original_func = original_func
self.args = args
self.kwargs = kwargs
def __call__(self):
return self.original_func(*self.args, **self.kwargs)
_UseNewThreadStartup = _NewThreadStartupWithTrace
The provided code snippet includes necessary dependencies for implementing the `disable_trace_thread_modules` function. Write a Python function `def disable_trace_thread_modules()` to solve the following problem:
Can be used to temporarily stop tracing threads created with thread.start_new_thread.
Here is the function:
def disable_trace_thread_modules():
'''
Can be used to temporarily stop tracing threads created with thread.start_new_thread.
'''
global _UseNewThreadStartup
_UseNewThreadStartup = _NewThreadStartupWithoutTrace | Can be used to temporarily stop tracing threads created with thread.start_new_thread. |
177,684 | import os
import re
import sys
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import get_global_debugger, IS_WINDOWS, IS_JYTHON, get_current_thread_id, \
sorted_dict_repr, set_global_debugger, DebugInfoHolder
from _pydev_bundle import pydev_log
from contextlib import contextmanager
from _pydevd_bundle import pydevd_constants, pydevd_defaults
from _pydevd_bundle.pydevd_defaults import PydevdCustomization
import ast
class _NewThreadStartupWithTrace:
def __init__(self, original_func, args, kwargs):
self.original_func = original_func
self.args = args
self.kwargs = kwargs
def __call__(self):
# We monkey-patch the thread creation so that this function is called in the new thread. At this point
# we notify of its creation and start tracing it.
py_db = get_global_debugger()
thread_id = None
if py_db is not None:
# Note: if this is a thread from threading.py, we're too early in the boostrap process (because we mocked
# the start_new_thread internal machinery and thread._bootstrap has not finished), so, the code below needs
# to make sure that we use the current thread bound to the original function and not use
# threading.current_thread() unless we're sure it's a dummy thread.
t = getattr(self.original_func, '__self__', getattr(self.original_func, 'im_self', None))
if not isinstance(t, threading.Thread):
# This is not a threading.Thread but a Dummy thread (so, get it as a dummy thread using
# currentThread).
t = threading.current_thread()
if not getattr(t, 'is_pydev_daemon_thread', False):
thread_id = get_current_thread_id(t)
py_db.notify_thread_created(thread_id, t)
_on_set_trace_for_new_thread(py_db)
if getattr(py_db, 'thread_analyser', None) is not None:
try:
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_concurrency_logger import log_new_thread
log_new_thread(py_db, t)
except:
sys.stderr.write("Failed to detect new thread for visualization")
try:
ret = self.original_func(*self.args, **self.kwargs)
finally:
if thread_id is not None:
if py_db is not None:
# At thread shutdown we only have pydevd-related code running (which shouldn't
# be tracked).
py_db.disable_tracing()
py_db.notify_thread_not_alive(thread_id)
return ret
_UseNewThreadStartup = _NewThreadStartupWithTrace
The provided code snippet includes necessary dependencies for implementing the `enable_trace_thread_modules` function. Write a Python function `def enable_trace_thread_modules()` to solve the following problem:
Can be used to start tracing threads created with thread.start_new_thread again.
Here is the function:
def enable_trace_thread_modules():
'''
Can be used to start tracing threads created with thread.start_new_thread again.
'''
global _UseNewThreadStartup
_UseNewThreadStartup = _NewThreadStartupWithTrace | Can be used to start tracing threads created with thread.start_new_thread again. |
177,685 | from __future__ import print_function
import os
import sys
import codeop
import traceback
from IPython.core.error import UsageError
from IPython.core.completer import IPCompleter
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
from IPython.core.usage import default_banner_parts
from IPython.utils.strdispatch import StrDispatch
import IPython.core.release as IPythonRelease
from IPython.terminal.interactiveshell import TerminalInteractiveShell
from IPython.core import release
from _pydev_bundle.pydev_imports import xmlrpclib
The provided code snippet includes necessary dependencies for implementing the `show_in_pager` function. Write a Python function `def show_in_pager(self, strng, *args, **kwargs)` to solve the following problem:
Run a string through pager
Here is the function:
def show_in_pager(self, strng, *args, **kwargs):
""" Run a string through pager """
# On PyDev we just output the string, there are scroll bars in the console
# to handle "paging". This is the same behaviour as when TERM==dump (see
# page.py)
# for compatibility with mime-bundle form:
if isinstance(strng, dict):
strng = strng.get('text/plain', strng)
print(strng) | Run a string through pager |
177,686 | from __future__ import print_function
import os
import sys
import codeop
import traceback
from IPython.core.error import UsageError
from IPython.core.completer import IPCompleter
from IPython.core.interactiveshell import InteractiveShell, InteractiveShellABC
from IPython.core.usage import default_banner_parts
from IPython.utils.strdispatch import StrDispatch
import IPython.core.release as IPythonRelease
from IPython.terminal.interactiveshell import TerminalInteractiveShell
from IPython.core import release
from _pydev_bundle.pydev_imports import xmlrpclib
def create_editor_hook(pydev_host, pydev_client_port):
class _PyDevFrontEnd:
def __init__(self):
def show_banner(self):
def update(self, globals, locals):
def complete(self, string):
def is_complete(self, string):
def getCompletions(self, text, act_tok):
def get_namespace(self):
def clear_buffer(self):
def add_exec(self, line):
def is_automagic(self):
def get_greeting_msg(self):
class _PyDevFrontEndContainer:
def get_pydev_frontend(pydev_host, pydev_client_port):
if _PyDevFrontEndContainer._instance is None:
_PyDevFrontEndContainer._instance = _PyDevFrontEnd()
if _PyDevFrontEndContainer._last_host_port != (pydev_host, pydev_client_port):
_PyDevFrontEndContainer._last_host_port = pydev_host, pydev_client_port
# Back channel to PyDev to open editors (in the future other
# info may go back this way. This is the same channel that is
# used to get stdin, see StdIn in pydev_console_utils)
_PyDevFrontEndContainer._instance.ipython.hooks['editor'] = create_editor_hook(pydev_host, pydev_client_port)
# Note: setting the callback directly because setting it with set_hook would actually create a chain instead
# of ovewriting at each new call).
# _PyDevFrontEndContainer._instance.ipython.set_hook('editor', create_editor_hook(pydev_host, pydev_client_port))
return _PyDevFrontEndContainer._instance | null |
177,687 | from _pydev_bundle._pydev_saved_modules import socket
import sys
def get_socket_names(n_sockets, close=False):
socket_names = []
sockets = []
for _ in range(n_sockets):
if IS_JYTHON:
# Although the option which would be pure java *should* work for Jython, the socket being returned is still 0
# (i.e.: it doesn't give the local port bound, only the original port, which was 0).
from java.net import ServerSocket
sock = ServerSocket(0)
socket_name = get_localhost(), sock.getLocalPort()
else:
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
sock.bind((get_localhost(), 0))
socket_name = sock.getsockname()
sockets.append(sock)
socket_names.append(socket_name)
if close:
for s in sockets:
s.close()
return socket_names
def get_socket_name(close=False):
return get_socket_names(1, close)[0] | null |
177,688 | import inspect
import os.path
import sys
from _pydev_bundle._pydev_tipper_common import do_find
from _pydevd_bundle.pydevd_utils import hasattr_checked, dir_checked
from inspect import getfullargspec
def Find(name, log=None):
f = None
mod = _imp(name, log)
parent = mod
foundAs = ''
if inspect.ismodule(mod):
f = get_file(mod)
components = name.split('.')
old_comp = None
for comp in components[1:]:
try:
# this happens in the following case:
# we have mx.DateTime.mxDateTime.mxDateTime.pyd
# but after importing it, mx.DateTime.mxDateTime shadows access to mxDateTime.pyd
mod = getattr(mod, comp)
except AttributeError:
if old_comp != comp:
raise
if inspect.ismodule(mod):
f = get_file(mod)
else:
if len(foundAs) > 0:
foundAs = foundAs + '.'
foundAs = foundAs + comp
old_comp = comp
return f, mod, parent, foundAs
def do_find(f, mod):
import linecache
if inspect.ismodule(mod):
return f, 0, 0
lines = linecache.getlines(f)
if inspect.isclass(mod):
name = mod.__name__
pat = re.compile(r'^\s*class\s*' + name + r'\b')
for i in range(len(lines)):
if pat.match(lines[i]):
return f, i, 0
return f, 0, 0
if inspect.ismethod(mod):
mod = mod.im_func
if inspect.isfunction(mod):
try:
mod = mod.func_code
except AttributeError:
mod = mod.__code__ # python 3k
if inspect.istraceback(mod):
mod = mod.tb_frame
if inspect.isframe(mod):
mod = mod.f_code
if inspect.iscode(mod):
if not hasattr(mod, 'co_filename'):
return None, 0, 0
if not hasattr(mod, 'co_firstlineno'):
return mod.co_filename, 0, 0
lnum = mod.co_firstlineno
pat = re.compile(r'^(\s*def\s)|(.*(?<!\w)lambda(:|\s))|^(\s*@)')
while lnum > 0:
if pat.match(lines[lnum]):
break
lnum -= 1
return f, lnum, 0
raise RuntimeError('Do not know about: ' + f + ' ' + str(mod))
The provided code snippet includes necessary dependencies for implementing the `search_definition` function. Write a Python function `def search_definition(data)` to solve the following problem:
@return file, line, col
Here is the function:
def search_definition(data):
'''@return file, line, col
'''
data = data.replace('\n', '')
if data.endswith('.'):
data = data.rstrip('.')
f, mod, parent, foundAs = Find(data)
try:
return do_find(f, mod), foundAs
except:
return do_find(f, parent), foundAs | @return file, line, col |
177,689 | import inspect
import os.path
import sys
from _pydev_bundle._pydev_tipper_common import do_find
from _pydevd_bundle.pydevd_utils import hasattr_checked, dir_checked
from inspect import getfullargspec
def Find(name, log=None):
f = None
mod = _imp(name, log)
parent = mod
foundAs = ''
if inspect.ismodule(mod):
f = get_file(mod)
components = name.split('.')
old_comp = None
for comp in components[1:]:
try:
# this happens in the following case:
# we have mx.DateTime.mxDateTime.mxDateTime.pyd
# but after importing it, mx.DateTime.mxDateTime shadows access to mxDateTime.pyd
mod = getattr(mod, comp)
except AttributeError:
if old_comp != comp:
raise
if inspect.ismodule(mod):
f = get_file(mod)
else:
if len(foundAs) > 0:
foundAs = foundAs + '.'
foundAs = foundAs + comp
old_comp = comp
return f, mod, parent, foundAs
def generate_imports_tip_for_module(obj_to_complete, dir_comps=None, getattr=getattr, filter=lambda name:True):
'''
name, doc, args, type (from the TYPE_* constants)
'''
ret = []
if dir_comps is None:
dir_comps = dir_checked(obj_to_complete)
if hasattr_checked(obj_to_complete, '__dict__'):
dir_comps.append('__dict__')
if hasattr_checked(obj_to_complete, '__class__'):
dir_comps.append('__class__')
get_complete_info = True
if len(dir_comps) > 1000:
# ok, we don't want to let our users wait forever...
# no complete info for you...
get_complete_info = False
dontGetDocsOn = (float, int, str, tuple, list, dict)
dontGetattrOn = (dict, list, set, tuple)
for d in dir_comps:
if d is None:
continue
if not filter(d):
continue
args = ''
try:
try:
if isinstance(obj_to_complete, dontGetattrOn):
raise Exception('Since python 3.9, e.g. "dict[str]" will return'
" a dict that's only supposed to take strings. "
'Interestingly, e.g. dict["val"] is also valid '
'and presumably represents a dict that only takes '
'keys that are "val". This breaks our check for '
'class attributes.')
obj = getattr(obj_to_complete.__class__, d)
except:
obj = getattr(obj_to_complete, d)
except: # just ignore and get it without additional info
ret.append((d, '', args, TYPE_BUILTIN))
else:
if get_complete_info:
try:
retType = TYPE_BUILTIN
# check if we have to get docs
getDoc = True
for class_ in dontGetDocsOn:
if isinstance(obj, class_):
getDoc = False
break
doc = ''
if getDoc:
# no need to get this info... too many constants are defined and
# makes things much slower (passing all that through sockets takes quite some time)
try:
doc = inspect.getdoc(obj)
if doc is None:
doc = ''
except: # may happen on jython when checking java classes (so, just ignore it)
doc = ''
if inspect.ismethod(obj) or inspect.isbuiltin(obj) or inspect.isfunction(obj) or inspect.isroutine(obj):
try:
args, vargs, kwargs, defaults, kwonly_args, kwonly_defaults = getargspec(obj)
args = args[:]
for kwonly_arg in kwonly_args:
default = kwonly_defaults.get(kwonly_arg, _SENTINEL)
if default is not _SENTINEL:
args.append('%s=%s' % (kwonly_arg, default))
else:
args.append(str(kwonly_arg))
args = '(%s)' % (', '.join(args))
except TypeError:
# ok, let's see if we can get the arguments from the doc
args, doc = signature_from_docstring(doc, getattr(obj, '__name__', None))
retType = TYPE_FUNCTION
elif inspect.isclass(obj):
retType = TYPE_CLASS
elif inspect.ismodule(obj):
retType = TYPE_IMPORT
else:
retType = TYPE_ATTR
# add token and doc to return - assure only strings.
ret.append((d, doc, args, retType))
except: # just ignore and get it without aditional info
ret.append((d, '', args, TYPE_BUILTIN))
else: # get_complete_info == False
if inspect.ismethod(obj) or inspect.isbuiltin(obj) or inspect.isfunction(obj) or inspect.isroutine(obj):
retType = TYPE_FUNCTION
elif inspect.isclass(obj):
retType = TYPE_CLASS
elif inspect.ismodule(obj):
retType = TYPE_IMPORT
else:
retType = TYPE_ATTR
# ok, no complete info, let's try to do this as fast and clean as possible
# so, no docs for this kind of information, only the signatures
ret.append((d, '', str(args), retType))
return ret
def generate_tip(data, log=None):
data = data.replace('\n', '')
if data.endswith('.'):
data = data.rstrip('.')
f, mod, parent, foundAs = Find(data, log)
# print_ >> open('temp.txt', 'w'), f
tips = generate_imports_tip_for_module(mod)
return f, tips | null |
177,690 | import linecache
import os.path
import re
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_dont_trace
from _pydevd_bundle.pydevd_constants import (RETURN_VALUES_DICT, NO_FTRACE,
EXCEPTION_TYPE_HANDLED, EXCEPTION_TYPE_USER_UNHANDLED, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, just_raised, remove_exception_from_frame, ignore_exception_trace
from _pydevd_bundle.pydevd_utils import get_clsname_for_code
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame
from _pydevd_bundle.pydevd_comm_constants import constant_to_str, CMD_SET_FUNCTION_BREAK
import sys
import dis
def get_smart_step_into_variant_from_frame_offset(*args, **kwargs):
return None | null |
177,691 | import linecache
import os.path
import re
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_dont_trace
from _pydevd_bundle.pydevd_constants import (RETURN_VALUES_DICT, NO_FTRACE,
EXCEPTION_TYPE_HANDLED, EXCEPTION_TYPE_USER_UNHANDLED, PYDEVD_IPYTHON_CONTEXT)
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame, just_raised, remove_exception_from_frame, ignore_exception_trace
from _pydevd_bundle.pydevd_utils import get_clsname_for_code
from pydevd_file_utils import get_abs_path_real_path_and_base_from_frame
from _pydevd_bundle.pydevd_comm_constants import constant_to_str, CMD_SET_FUNCTION_BREAK
import sys
import dis
def is_unhandled_exception(container_obj, py_db, frame, last_raise_line, raise_lines):
# ENDIF
if frame.f_lineno in raise_lines:
return True
else:
try_except_infos = container_obj.try_except_infos
if try_except_infos is None:
container_obj.try_except_infos = try_except_infos = py_db.collect_try_except_info(frame.f_code)
if not try_except_infos:
# Consider the last exception as unhandled because there's no try..except in it.
return True
else:
# Now, consider only the try..except for the raise
valid_try_except_infos = []
for try_except_info in try_except_infos:
if try_except_info.is_line_in_try_block(last_raise_line):
valid_try_except_infos.append(try_except_info)
if not valid_try_except_infos:
return True
else:
# Note: check all, not only the "valid" ones to cover the case
# in "tests_python.test_tracing_on_top_level.raise_unhandled10"
# where one try..except is inside the other with only a raise
# and it's gotten in the except line.
for try_except_info in try_except_infos:
if try_except_info.is_line_in_except_block(frame.f_lineno):
if (
frame.f_lineno == try_except_info.except_line or
frame.f_lineno in try_except_info.raise_lines_in_except
):
# In a raise inside a try..except block or some except which doesn't
# match the raised exception.
return True
return False | null |
177,692 | from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_utils import hasattr_checked, DAPGrouper, Timer
from io import StringIO
import traceback
from os.path import basename
from functools import partial
from _pydevd_bundle.pydevd_constants import IS_PY36_OR_GREATER, \
MethodWrapperType, RETURN_VALUES_DICT, DebugInfoHolder, IS_PYPY, GENERATED_LEN_ATTR_NAME
from _pydevd_bundle.pydevd_safe_repr import SafeRepr
from _pydevd_bundle import pydevd_constants
_basic_immutable_types = (int, float, complex, str, bytes, type(None), bool, frozenset)
The provided code snippet includes necessary dependencies for implementing the `_does_obj_repr_evaluate_to_obj` function. Write a Python function `def _does_obj_repr_evaluate_to_obj(obj)` to solve the following problem:
If obj is an object where evaluating its representation leads to the same object, return True, otherwise, return False.
Here is the function:
def _does_obj_repr_evaluate_to_obj(obj):
'''
If obj is an object where evaluating its representation leads to
the same object, return True, otherwise, return False.
'''
try:
if isinstance(obj, tuple):
for o in obj:
if not _does_obj_repr_evaluate_to_obj(o):
return False
return True
else:
return isinstance(obj, _basic_immutable_types)
except:
return False | If obj is an object where evaluating its representation leads to the same object, return True, otherwise, return False. |
177,693 | from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_utils import hasattr_checked, DAPGrouper, Timer
from io import StringIO
import traceback
from os.path import basename
from functools import partial
from _pydevd_bundle.pydevd_constants import IS_PY36_OR_GREATER, \
MethodWrapperType, RETURN_VALUES_DICT, DebugInfoHolder, IS_PYPY, GENERATED_LEN_ATTR_NAME
from _pydevd_bundle.pydevd_safe_repr import SafeRepr
from _pydevd_bundle import pydevd_constants
def _apply_evaluate_name(parent_name, evaluate_name):
return evaluate_name % (parent_name,) | null |
177,694 | import time
from _pydev_bundle._pydev_filesystem_encoding import getfilesystemencoding
from _pydev_bundle._pydev_saved_modules import threading
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle.pydevd_constants import GlobalDebuggerHolder
from _pydevd_bundle.pydevd_constants import get_thread_id
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_concurrency_analyser.pydevd_thread_wrappers import ObjectWrapper, wrap_attr
import pydevd_file_utils
from _pydev_bundle import pydev_log
import sys
from urllib.parse import quote
cur_time = lambda: int(round(time.time() * 1000000))
def send_concurrency_message(event_class, time, name, thread_id, type, event, file, line, frame, lock_id=0, parent=None):
def get_thread_id(thread):
def log_new_thread(global_debugger, t):
event_time = cur_time() - global_debugger.thread_analyser.start_time
send_concurrency_message("threading_event", event_time, t.name, get_thread_id(t), "thread",
"start", "code_name", 0, None, parent=get_thread_id(t)) | null |
177,695 | from _pydev_bundle._pydev_saved_modules import threading
def wrapper(fun):
def pydev_after_run_call():
pass
def inner(*args, **kwargs):
fun(*args, **kwargs)
pydev_after_run_call()
return inner
def wrap_attr(obj, attr):
t_save_start = getattr(obj, attr)
setattr(obj, attr, wrapper(t_save_start))
obj._pydev_run_patched = True | null |
177,696 | from _pydev_bundle._pydev_saved_modules import threading
def factory_wrapper(fun):
def inner(*args, **kwargs):
obj = fun(*args, **kwargs)
return ObjectWrapper(obj)
return inner
def wrap_threads():
# TODO: add wrappers for thread and _thread
# import _thread as mod
# print("Thread imported")
# mod.start_new_thread = wrapper(mod.start_new_thread)
threading.Lock = factory_wrapper(threading.Lock)
threading.RLock = factory_wrapper(threading.RLock)
# queue patching
import queue # @UnresolvedImport
queue.Queue = factory_wrapper(queue.Queue) | null |
177,697 | from _pydev_bundle.pydev_imports import execfile
from _pydevd_bundle import pydevd_dont_trace
import types
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import get_global_debugger
def write_err(*args):
py_db = get_global_debugger()
if py_db is not None:
new_lst = []
for a in args:
new_lst.append(str(a))
msg = ' '.join(new_lst)
s = 'code reload: %s\n' % (msg,)
cmd = py_db.cmd_factory.make_io_message(s, 2)
if py_db.writer is not None:
py_db.writer.add_command(cmd)
def notify_info0(*args):
write_err(*args) | null |
177,698 | from _pydev_bundle.pydev_imports import execfile
from _pydevd_bundle import pydevd_dont_trace
import types
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import get_global_debugger
LEVEL1 = 1
DEBUG = NO_DEBUG
def write_err(*args):
py_db = get_global_debugger()
if py_db is not None:
new_lst = []
for a in args:
new_lst.append(str(a))
msg = ' '.join(new_lst)
s = 'code reload: %s\n' % (msg,)
cmd = py_db.cmd_factory.make_io_message(s, 2)
if py_db.writer is not None:
py_db.writer.add_command(cmd)
def notify_info(*args):
if DEBUG >= LEVEL1:
write_err(*args) | null |
177,699 | from _pydev_bundle.pydev_imports import execfile
from _pydevd_bundle import pydevd_dont_trace
import types
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import get_global_debugger
LEVEL2 = 2
DEBUG = NO_DEBUG
def write_err(*args):
py_db = get_global_debugger()
if py_db is not None:
new_lst = []
for a in args:
new_lst.append(str(a))
msg = ' '.join(new_lst)
s = 'code reload: %s\n' % (msg,)
cmd = py_db.cmd_factory.make_io_message(s, 2)
if py_db.writer is not None:
py_db.writer.add_command(cmd)
def notify_info2(*args):
if DEBUG >= LEVEL2:
write_err(*args) | null |
177,700 | from _pydev_bundle.pydev_imports import execfile
from _pydevd_bundle import pydevd_dont_trace
import types
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import get_global_debugger
def write_err(*args):
py_db = get_global_debugger()
if py_db is not None:
new_lst = []
for a in args:
new_lst.append(str(a))
msg = ' '.join(new_lst)
s = 'code reload: %s\n' % (msg,)
cmd = py_db.cmd_factory.make_io_message(s, 2)
if py_db.writer is not None:
py_db.writer.add_command(cmd)
def notify_error(*args):
write_err(*args) | null |
177,701 | from _pydev_bundle.pydev_imports import execfile
from _pydevd_bundle import pydevd_dont_trace
import types
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_constants import get_global_debugger
def code_objects_equal(code0, code1):
for d in dir(code0):
if d.startswith('_') or 'line' in d or d in ('replace', 'co_positions', 'co_qualname'):
continue
if getattr(code0, d) != getattr(code1, d):
return False
return True | null |
177,702 | from contextlib import contextmanager
import sys
from _pydevd_bundle.pydevd_constants import get_frame, RETURN_VALUES_DICT, \
ForkSafeLock, GENERATED_LEN_ATTR_NAME, silence_warnings_decorator
from _pydevd_bundle.pydevd_xml import get_variable_details, get_type
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle.pydevd_resolver import sorted_attributes_key, TOO_LARGE_ATTR, get_var_scope
from _pydevd_bundle.pydevd_safe_repr import SafeRepr
from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_vars
from _pydev_bundle.pydev_imports import Exec
from _pydevd_bundle.pydevd_frame_utils import FramesList
from _pydevd_bundle.pydevd_utils import ScopeRequest, DAPGrouper, Timer
from typing import Optional
def sorted_attributes_key(attr_name):
if attr_name.startswith('__'):
if attr_name.endswith('__'):
# __ double under before and after __
return (3, attr_name)
else:
# __ double under before
return (2, attr_name)
elif attr_name.startswith('_'):
# _ single under
return (1, attr_name)
else:
# Regular (Before anything)
return (0, attr_name)
def sorted_variables_key(obj):
return sorted_attributes_key(obj.name) | null |
177,703 | from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_import_class
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame
from _pydev_bundle._pydev_saved_modules import threading
def get_exception_breakpoint(exctype, exceptions):
def add_exception_to_frame(frame, exception_info):
def stop_on_unhandled_exception(py_db, thread, additional_info, arg):
exctype, value, tb = arg
break_on_uncaught_exceptions = py_db.break_on_uncaught_exceptions
if break_on_uncaught_exceptions:
exception_breakpoint = py_db.get_exception_breakpoint(exctype, break_on_uncaught_exceptions)
else:
exception_breakpoint = None
if not exception_breakpoint:
return
if tb is None: # sometimes it can be None, e.g. with GTK
return
if exctype is KeyboardInterrupt:
return
if exctype is SystemExit and py_db.ignore_system_exit_code(value):
return
frames = []
user_frame = None
while tb is not None:
if not py_db.exclude_exception_by_filter(exception_breakpoint, tb):
user_frame = tb.tb_frame
frames.append(tb.tb_frame)
tb = tb.tb_next
if user_frame is None:
return
frames_byid = dict([(id(frame), frame) for frame in frames])
add_exception_to_frame(user_frame, arg)
if exception_breakpoint.condition is not None:
eval_result = py_db.handle_breakpoint_condition(additional_info, exception_breakpoint, user_frame)
if not eval_result:
return
if exception_breakpoint.expression is not None:
py_db.handle_breakpoint_expression(exception_breakpoint, additional_info, user_frame)
try:
additional_info.pydev_message = exception_breakpoint.qname
except:
additional_info.pydev_message = exception_breakpoint.qname.encode('utf-8')
pydev_log.debug('Handling post-mortem stop on exception breakpoint %s' % (exception_breakpoint.qname,))
py_db.do_stop_on_unhandled_exception(thread, user_frame, frames_byid, arg) | null |
177,704 | from _pydev_bundle import pydev_log
from _pydevd_bundle import pydevd_import_class
from _pydevd_bundle.pydevd_frame_utils import add_exception_to_frame
from _pydev_bundle._pydev_saved_modules import threading
def get_exception_class(kls):
try:
return eval(kls)
except:
return pydevd_import_class.import_name(kls) | null |
177,705 |
def add_line_breakpoint(plugin, pydb, type, canonical_normalized_filename, breakpoint_id, line, condition, expression, func_name, hit_condition=None, is_logpoint=False, add_breakpoint_result=None, on_changed_breakpoint_state=None):
return None | null |
177,706 |
def after_breakpoints_consolidated(py_db, canonical_normalized_filename, id_to_pybreakpoint, file_to_line_to_breakpoints):
return None | null |
177,707 |
def add_exception_breakpoint(plugin, pydb, type, exception):
return False | null |
177,708 |
def remove_exception_breakpoint(plugin, pydb, type, exception):
return False | null |
177,709 |
def remove_all_exception_breakpoints(plugin, pydb):
return False | null |
177,710 |
def get_breakpoints(plugin, pydb):
return None | null |
177,711 |
def can_skip(plugin, pydb, frame):
return True | null |
177,712 |
def has_exception_breaks(plugin):
return False | null |
177,713 |
def has_line_breaks(plugin):
return False | null |
177,714 |
def cmd_step_into(plugin, pydb, frame, event, args, stop_info, stop):
return False | null |
177,715 |
def cmd_step_over(plugin, pydb, frame, event, args, stop_info, stop):
return False | null |
177,716 |
def stop(plugin, pydb, frame, event, args, stop_info, arg, step_cmd):
return False | null |
177,717 |
def get_breakpoint(plugin, pydb, pydb_frame, frame, event, args):
return None | null |
177,718 |
def suspend(plugin, pydb, thread, frame):
return None | null |
177,719 |
def exception_break(plugin, pydb, pydb_frame, frame, args, arg):
return None | null |
177,720 |
def change_variable(plugin, frame, attr, expression):
return False | null |
177,721 | import sys
from _pydevd_bundle import pydevd_xml
from os.path import basename
from _pydev_bundle import pydev_log
from urllib.parse import unquote_plus
from _pydevd_bundle.pydevd_constants import IS_PY311_OR_GREATER
def print_var_node(xml_node, stream):
def get_referrer_info(searched_obj):
def print_referrers(obj, stream=None):
if stream is None:
stream = sys.stdout
result = get_referrer_info(obj)
from xml.dom.minidom import parseString
dom = parseString(result)
xml = dom.getElementsByTagName('xml')[0]
for node in xml.childNodes:
if node.nodeType == node.TEXT_NODE:
continue
if node.localName == 'for':
stream.write('Searching references for: ')
for child in node.childNodes:
if child.nodeType == node.TEXT_NODE:
continue
print_var_node(child, stream)
elif node.localName == 'var':
stream.write('Referrer found: ')
print_var_node(node, stream)
else:
sys.stderr.write('Unhandled node: %s\n' % (node,))
return result | null |
177,722 | import sys
import traceback
from _pydevd_bundle.pydevconsole_code import InteractiveConsole, _EvalAwaitInNewEventLoop
from _pydev_bundle import _pydev_completer
from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn
from _pydev_bundle.pydev_imports import Exec
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle import pydevd_save_locals
from _pydevd_bundle.pydevd_io import IOBuf
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle.pydevd_xml import make_valid_xml_value
import inspect
from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals
class InteractiveConsoleCache:
thread_id = None
frame_id = None
interactive_console_instance = None
def clear_interactive_console():
InteractiveConsoleCache.thread_id = None
InteractiveConsoleCache.frame_id = None
InteractiveConsoleCache.interactive_console_instance = None | null |
177,723 | import sys
import traceback
from _pydevd_bundle.pydevconsole_code import InteractiveConsole, _EvalAwaitInNewEventLoop
from _pydev_bundle import _pydev_completer
from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn
from _pydev_bundle.pydev_imports import Exec
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle import pydevd_save_locals
from _pydevd_bundle.pydevd_io import IOBuf
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle.pydevd_xml import make_valid_xml_value
import inspect
from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals
CONSOLE_OUTPUT = "output"
CONSOLE_ERROR = "error"
class ConsoleMessage:
"""Console Messages
"""
def __init__(self):
self.more = False
# List of tuple [('error', 'error_message'), ('message_list', 'output_message')]
self.console_messages = []
def add_console_message(self, message_type, message):
"""add messages in the console_messages list
"""
for m in message.split("\n"):
if m.strip():
self.console_messages.append((message_type, m))
def update_more(self, more):
"""more is set to true if further input is required from the user
else more is set to false
"""
self.more = more
def to_xml(self):
"""Create an XML for console message_list, error and more (true/false)
<xml>
<message_list>console message_list</message_list>
<error>console error</error>
<more>true/false</more>
</xml>
"""
makeValid = make_valid_xml_value
xml = '<xml><more>%s</more>' % (self.more)
for message_type, message in self.console_messages:
xml += '<%s message="%s"></%s>' % (message_type, makeValid(message), message_type)
xml += '</xml>'
return xml
def get_interactive_console(thread_id, frame_id, frame, console_message):
"""returns the global interactive console.
interactive console should have been initialized by this time
:rtype: DebugConsole
"""
if InteractiveConsoleCache.thread_id == thread_id and InteractiveConsoleCache.frame_id == frame_id:
return InteractiveConsoleCache.interactive_console_instance
InteractiveConsoleCache.interactive_console_instance = DebugConsole()
InteractiveConsoleCache.thread_id = thread_id
InteractiveConsoleCache.frame_id = frame_id
console_stacktrace = traceback.extract_stack(frame, limit=1)
if console_stacktrace:
current_context = console_stacktrace[0] # top entry from stacktrace
context_message = 'File "%s", line %s, in %s' % (current_context[0], current_context[1], current_context[2])
console_message.add_console_message(CONSOLE_OUTPUT, "[Current context]: %s" % (context_message,))
return InteractiveConsoleCache.interactive_console_instance
The provided code snippet includes necessary dependencies for implementing the `execute_console_command` function. Write a Python function `def execute_console_command(frame, thread_id, frame_id, line, buffer_output=True)` to solve the following problem:
fetch an interactive console instance from the cache and push the received command to the console. create and return an instance of console_message
Here is the function:
def execute_console_command(frame, thread_id, frame_id, line, buffer_output=True):
"""fetch an interactive console instance from the cache and
push the received command to the console.
create and return an instance of console_message
"""
console_message = ConsoleMessage()
interpreter = get_interactive_console(thread_id, frame_id, frame, console_message)
more, output_messages, error_messages = interpreter.push(line, frame, buffer_output)
console_message.update_more(more)
for message in output_messages:
console_message.add_console_message(CONSOLE_OUTPUT, message)
for message in error_messages:
console_message.add_console_message(CONSOLE_ERROR, message)
return console_message | fetch an interactive console instance from the cache and push the received command to the console. create and return an instance of console_message |
177,724 | import sys
import traceback
from _pydevd_bundle.pydevconsole_code import InteractiveConsole, _EvalAwaitInNewEventLoop
from _pydev_bundle import _pydev_completer
from _pydev_bundle.pydev_console_utils import BaseInterpreterInterface, BaseStdIn
from _pydev_bundle.pydev_imports import Exec
from _pydev_bundle.pydev_override import overrides
from _pydevd_bundle import pydevd_save_locals
from _pydevd_bundle.pydevd_io import IOBuf
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle.pydevd_xml import make_valid_xml_value
import inspect
from _pydevd_bundle.pydevd_save_locals import update_globals_and_locals
The provided code snippet includes necessary dependencies for implementing the `get_completions` function. Write a Python function `def get_completions(frame, act_tok)` to solve the following problem:
fetch all completions, create xml for the same return the completions xml
Here is the function:
def get_completions(frame, act_tok):
""" fetch all completions, create xml for the same
return the completions xml
"""
return _pydev_completer.generate_completions_as_xml(frame, act_tok) | fetch all completions, create xml for the same return the completions xml |
177,725 | import dis
from _pydevd_bundle.pydevd_collect_bytecode_info import iter_instructions
from _pydev_bundle import pydev_log
import sys
import inspect
from io import StringIO
_op_name_to_handler = {}
def _register(cls):
_op_name_to_handler[cls.opname] = cls
return cls | null |
177,726 | import dis
from _pydevd_bundle.pydevd_collect_bytecode_info import iter_instructions
from _pydev_bundle import pydev_log
import sys
import inspect
from io import StringIO
def _print_after_info(line_contents, stream=None):
if stream is None:
stream = sys.stdout
for token in line_contents:
after_tokens = token.get_after_tokens()
if after_tokens:
s = '%s after: %s\n' % (
repr(token.tok),
('"' + '", "'.join(t.tok for t in token.get_after_tokens()) + '"'))
stream.write(s)
else:
stream.write('%s (NO REQUISITES)' % repr(token.tok))
class StringIO(TextIOWrapper):
def __init__(self, initial_value: Optional[str] = ..., newline: Optional[str] = ...) -> None: ...
# StringIO does not contain a "name" field. This workaround is necessary
# to allow StringIO sub-classes to add this field, as it is defined
# as a read-only property on IO[].
name: Any
def getvalue(self) -> str: ...
def _compose_line_contents(line_contents, previous_line_tokens):
lst = []
handled = set()
add_to_end_of_line = []
delete_indexes = []
for i, token in enumerate(line_contents):
if token.end_of_line:
add_to_end_of_line.append(token)
delete_indexes.append(i)
for i in reversed(delete_indexes):
del line_contents[i]
del delete_indexes
while line_contents:
added = False
delete_indexes = []
for i, token in enumerate(line_contents):
after_tokens = token.get_after_tokens()
for after in after_tokens:
if after not in handled and after not in previous_line_tokens:
break
else:
added = True
previous_line_tokens.add(token)
handled.add(token)
lst.append(token.tok)
delete_indexes.append(i)
for i in reversed(delete_indexes):
del line_contents[i]
if not added:
if add_to_end_of_line:
line_contents.extend(add_to_end_of_line)
del add_to_end_of_line[:]
continue
# Something is off, let's just add as is.
for token in line_contents:
if token not in handled:
lst.append(token.tok)
stream = StringIO()
_print_after_info(line_contents, stream)
pydev_log.critical('Error. After markers are not correct:\n%s', stream.getvalue())
break
return ''.join(lst) | null |
177,727 | import dis
from _pydevd_bundle.pydevd_collect_bytecode_info import iter_instructions
from _pydev_bundle import pydev_log
import sys
import inspect
from io import StringIO
DEBUG = False
class _PyCodeToSource(object):
def __init__(self, co, memo=None):
if memo is None:
memo = {}
self.memo = memo
self.co = co
self.instructions = list(iter_instructions(co))
self.stack = _Stack()
self.writer = _Writer()
def _process_next(self, i_line):
instruction = self.instructions.pop(0)
handler_class = _op_name_to_handler.get(instruction.opname)
if handler_class is not None:
s = handler_class(i_line, instruction, self.stack, self.writer, self)
if DEBUG:
print(s)
else:
if DEBUG:
print("UNHANDLED", instruction)
def build_line_to_contents(self):
co = self.co
op_offset_to_line = dict(dis.findlinestarts(co))
curr_line_index = 0
instructions = self.instructions
while instructions:
instruction = instructions[0]
new_line_index = op_offset_to_line.get(instruction.offset)
if new_line_index is not None:
if new_line_index is not None:
curr_line_index = new_line_index
self._process_next(curr_line_index)
return self.writer.line_to_contents
def merge_code(self, code):
if DEBUG:
print('merge code ----')
# for d in dir(code):
# if not d.startswith('_'):
# print(d, getattr(code, d))
line_to_contents = _PyCodeToSource(code, self.memo).build_line_to_contents()
lines = []
for line, contents in sorted(line_to_contents.items()):
lines.append(line)
self.writer.get_line(line).extend(contents)
if DEBUG:
print('end merge code ----')
return lines
def disassemble(self):
show_lines = False
line_to_contents = self.build_line_to_contents()
stream = StringIO()
last_line = 0
indent = ''
previous_line_tokens = set()
for i_line, contents in sorted(line_to_contents.items()):
while last_line < i_line - 1:
if show_lines:
stream.write(u"%s.\n" % (last_line + 1,))
else:
stream.write(u"\n")
last_line += 1
line_contents = []
dedents_found = 0
for part in contents:
if part is INDENT_MARKER:
if DEBUG:
print('found indent', i_line)
indent += ' '
continue
if part is DEDENT_MARKER:
if DEBUG:
print('found dedent', i_line)
dedents_found += 1
continue
line_contents.append(part)
s = indent + _compose_line_contents(line_contents, previous_line_tokens)
if show_lines:
stream.write(u"%s. %s\n" % (i_line, s))
else:
stream.write(u"%s\n" % s)
if dedents_found:
indent = indent[:-(4 * dedents_found)]
last_line = i_line
return stream.getvalue()
The provided code snippet includes necessary dependencies for implementing the `code_obj_to_source` function. Write a Python function `def code_obj_to_source(co)` to solve the following problem:
Converts a code object to source code to provide a suitable representation for the compiler when the actual source code is not found. This is a work in progress / proof of concept / not ready to be used.
Here is the function:
def code_obj_to_source(co):
"""
Converts a code object to source code to provide a suitable representation for the compiler when
the actual source code is not found.
This is a work in progress / proof of concept / not ready to be used.
"""
ret = _PyCodeToSource(co).disassemble()
if DEBUG:
print(ret)
return ret | Converts a code object to source code to provide a suitable representation for the compiler when the actual source code is not found. This is a work in progress / proof of concept / not ready to be used. |
177,728 | from _pydevd_bundle._debug_adapter.pydevd_schema_log import debug_exception
import json
import itertools
from functools import partial
_all_messages = {}
def register(cls):
_all_messages[cls.__name__] = cls
return cls | null |
177,729 | from _pydevd_bundle._debug_adapter.pydevd_schema_log import debug_exception
import json
import itertools
from functools import partial
_requests_to_types = {}
def register_request(command):
def do_register(cls):
_requests_to_types[command] = cls
return cls
return do_register | null |
177,730 | from _pydevd_bundle._debug_adapter.pydevd_schema_log import debug_exception
import json
import itertools
from functools import partial
_responses_to_types = {}
def register_response(command):
def do_register(cls):
_responses_to_types[command] = cls
return cls
return do_register | null |
177,731 | from _pydevd_bundle._debug_adapter.pydevd_schema_log import debug_exception
import json
import itertools
from functools import partial
_event_to_types = {}
def register_event(event):
def do_register(cls):
_event_to_types[event] = cls
return cls
return do_register | null |
177,732 | from _pydevd_bundle._debug_adapter.pydevd_schema_log import debug_exception
import json
import itertools
from functools import partial
_all_messages = {}
def from_dict(dct, update_ids_from_dap=False):
def from_json(json_msg, update_ids_from_dap=False, on_dict_loaded=lambda dct:None):
if isinstance(json_msg, bytes):
json_msg = json_msg.decode('utf-8')
as_dict = json.loads(json_msg)
on_dict_loaded(as_dict)
try:
return from_dict(as_dict, update_ids_from_dap=update_ids_from_dap)
except:
if as_dict.get('type') == 'response' and not as_dict.get('success'):
# Error messages may not have required body (return as a generic Response).
Response = _all_messages['Response']
return Response(**as_dict)
else:
raise | null |
177,733 | from _pydevd_bundle._debug_adapter.pydevd_schema_log import debug_exception
import json
import itertools
from functools import partial
_responses_to_types = {}
def get_response_class(request):
if request.__class__ == dict:
return _responses_to_types[request['command']]
return _responses_to_types[request.command] | null |
177,734 | def load_schema_data():
import os.path
import json
json_file = os.path.join(os.path.dirname(__file__), 'debugProtocol.json')
if not os.path.exists(json_file):
import requests
req = requests.get('https://raw.githubusercontent.com/microsoft/debug-adapter-protocol/gh-pages/debugAdapterProtocol.json')
assert req.status_code == 200
with open(json_file, 'wb') as stream:
stream.write(req.content)
with open(json_file, 'rb') as json_contents:
json_schema_data = json.loads(json_contents.read())
return json_schema_data
def load_custom_schema_data():
import os.path
import json
json_file = os.path.join(os.path.dirname(__file__), 'debugProtocolCustom.json')
with open(json_file, 'rb') as json_contents:
json_schema_data = json.loads(json_contents.read())
return json_schema_data
def create_classes_to_generate_structure(json_schema_data):
definitions = json_schema_data['definitions']
class_to_generatees = {}
for name, definition in definitions.items():
all_of = definition.get('allOf')
description = definition.get('description')
is_enum = definition.get('type') == 'string' and 'enum' in definition
enum_values = None
if is_enum:
enum_values = definition['enum']
properties = {}
properties.update(definition.get('properties', {}))
required = _OrderedSet(definition.get('required', _OrderedSet()))
base_definitions = []
if all_of is not None:
for definition in all_of:
ref = definition.get('$ref')
if ref is not None:
assert ref.startswith('#/definitions/')
ref = ref[len('#/definitions/'):]
base_definitions.append(ref)
else:
if not description:
description = definition.get('description')
properties.update(definition.get('properties', {}))
required.update(_OrderedSet(definition.get('required', _OrderedSet())))
if isinstance(description, (list, tuple)):
description = '\n'.join(description)
if name == 'ModulesRequest': # Hack to accept modules request without arguments (ptvsd: 2050).
required.discard('arguments')
class_to_generatees[name] = dict(
name=name,
properties=properties,
base_definitions=base_definitions,
description=description,
required=required,
is_enum=is_enum,
enum_values=enum_values
)
return class_to_generatees
def fill_properties_and_required_from_base(classes_to_generate):
# Now, resolve properties based on refs
for class_to_generate in classes_to_generate.values():
dct = {}
s = _OrderedSet()
for base_definition in reversed(collect_bases(class_to_generate, classes_to_generate)):
# Note: go from base to current so that the initial order of the properties has that
# same order.
dct.update(classes_to_generate[base_definition].get('properties', {}))
s.update(classes_to_generate[base_definition].get('required', _OrderedSet()))
dct.update(class_to_generate['properties'])
class_to_generate['properties'] = dct
s.update(class_to_generate['required'])
class_to_generate['required'] = s
return class_to_generate
def update_class_to_generate_description(class_to_generate):
import textwrap
description = class_to_generate['description']
lines = []
for line in description.splitlines():
wrapped = textwrap.wrap(line.strip(), 100)
lines.extend(wrapped)
lines.append('')
while lines and lines[-1] == '':
lines = lines[:-1]
class_to_generate['description'] = ' ' + ('\n '.join(lines))
def update_class_to_generate_type(classes_to_generate, class_to_generate):
properties = class_to_generate.get('properties')
for _prop_name, prop_val in properties.items():
prop_type = prop_val.get('type', '')
if not prop_type:
prop_type = prop_val.pop('$ref', '')
if prop_type:
assert prop_type.startswith('#/definitions/')
prop_type = prop_type[len('#/definitions/'):]
prop_val['type'] = Ref(prop_type, classes_to_generate[prop_type])
def update_class_to_generate_register_dec(classes_to_generate, class_to_generate):
# Default
class_to_generate['register_request'] = ''
class_to_generate['register_dec'] = '@register'
properties = class_to_generate.get('properties')
enum_type = properties.get('type', {}).get('enum')
command = None
event = None
if enum_type and len(enum_type) == 1 and next(iter(enum_type)) in ("request", "response", "event"):
msg_type = next(iter(enum_type))
if msg_type == 'response':
# The actual command is typed in the request
response_name = class_to_generate['name']
request_name = response_name[:-len('Response')] + 'Request'
if request_name in classes_to_generate:
command = classes_to_generate[request_name]['properties'].get('command')
else:
if response_name == 'ErrorResponse':
command = {'enum': ['error']}
else:
raise AssertionError('Unhandled: %s' % (response_name,))
elif msg_type == 'request':
command = properties.get('command')
elif msg_type == 'event':
command = properties.get('event')
else:
raise AssertionError('Unexpected condition.')
if command:
enum = command.get('enum')
if enum and len(enum) == 1:
class_to_generate['register_request'] = '@register_%s(%r)\n' % (msg_type, enum[0])
def update_class_to_generate_to_json(class_to_generate):
required = _OrderedSet(class_to_generate.get('required', _OrderedSet()))
prop_name_and_prop = extract_prop_name_and_prop(class_to_generate)
to_dict_body = ['def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused)']
translate_prop_names = []
for prop_name, prop in prop_name_and_prop:
if is_variable_to_translate(class_to_generate['name'], prop_name):
translate_prop_names.append(prop_name)
for prop_name, prop in prop_name_and_prop:
namespace = dict(prop_name=prop_name, noqa=_get_noqa_for_var(prop_name))
to_dict_body.append(' %(prop_name)s = self.%(prop_name)s%(noqa)s' % namespace)
if prop.get('type') == 'array':
to_dict_body.append(' if %(prop_name)s and hasattr(%(prop_name)s[0], "to_dict"):' % namespace)
to_dict_body.append(' %(prop_name)s = [x.to_dict() for x in %(prop_name)s]' % namespace)
if translate_prop_names:
to_dict_body.append(' if update_ids_to_dap:')
for prop_name in translate_prop_names:
namespace = dict(prop_name=prop_name, noqa=_get_noqa_for_var(prop_name))
to_dict_body.append(' if %(prop_name)s is not None:' % namespace)
to_dict_body.append(' %(prop_name)s = self._translate_id_to_dap(%(prop_name)s)%(noqa)s' % namespace)
if not translate_prop_names:
update_dict_ids_from_dap_body = []
else:
update_dict_ids_from_dap_body = ['', '', '@classmethod', 'def update_dict_ids_from_dap(cls, dct):']
for prop_name in translate_prop_names:
namespace = dict(prop_name=prop_name)
update_dict_ids_from_dap_body.append(' if %(prop_name)r in dct:' % namespace)
update_dict_ids_from_dap_body.append(' dct[%(prop_name)r] = cls._translate_id_from_dap(dct[%(prop_name)r])' % namespace)
update_dict_ids_from_dap_body.append(' return dct')
class_to_generate['update_dict_ids_from_dap'] = _indent_lines('\n'.join(update_dict_ids_from_dap_body))
to_dict_body.append(' dct = {')
first_not_required = False
for prop_name, prop in prop_name_and_prop:
use_to_dict = prop['type'].__class__ == Ref and not prop['type'].ref_data.get('is_enum', False)
is_array = prop['type'] == 'array'
ref_array_cls_name = ''
if is_array:
ref = prop['items'].get('$ref')
if ref is not None:
ref_array_cls_name = ref.split('/')[-1]
namespace = dict(prop_name=prop_name, ref_array_cls_name=ref_array_cls_name)
if prop_name in required:
if use_to_dict:
to_dict_body.append(' %(prop_name)r: %(prop_name)s.to_dict(update_ids_to_dap=update_ids_to_dap),' % namespace)
else:
if ref_array_cls_name:
to_dict_body.append(' %(prop_name)r: [%(ref_array_cls_name)s.update_dict_ids_to_dap(o) for o in %(prop_name)s] if (update_ids_to_dap and %(prop_name)s) else %(prop_name)s,' % namespace)
else:
to_dict_body.append(' %(prop_name)r: %(prop_name)s,' % namespace)
else:
if not first_not_required:
first_not_required = True
to_dict_body.append(' }')
to_dict_body.append(' if %(prop_name)s is not None:' % namespace)
if use_to_dict:
to_dict_body.append(' dct[%(prop_name)r] = %(prop_name)s.to_dict(update_ids_to_dap=update_ids_to_dap)' % namespace)
else:
if ref_array_cls_name:
to_dict_body.append(' dct[%(prop_name)r] = [%(ref_array_cls_name)s.update_dict_ids_to_dap(o) for o in %(prop_name)s] if (update_ids_to_dap and %(prop_name)s) else %(prop_name)s' % namespace)
else:
to_dict_body.append(' dct[%(prop_name)r] = %(prop_name)s' % namespace)
if not first_not_required:
first_not_required = True
to_dict_body.append(' }')
to_dict_body.append(' dct.update(self.kwargs)')
to_dict_body.append(' return dct')
class_to_generate['to_dict'] = _indent_lines('\n'.join(to_dict_body))
if not translate_prop_names:
update_dict_ids_to_dap_body = []
else:
update_dict_ids_to_dap_body = ['', '', '@classmethod', 'def update_dict_ids_to_dap(cls, dct):']
for prop_name in translate_prop_names:
namespace = dict(prop_name=prop_name)
update_dict_ids_to_dap_body.append(' if %(prop_name)r in dct:' % namespace)
update_dict_ids_to_dap_body.append(' dct[%(prop_name)r] = cls._translate_id_to_dap(dct[%(prop_name)r])' % namespace)
update_dict_ids_to_dap_body.append(' return dct')
class_to_generate['update_dict_ids_to_dap'] = _indent_lines('\n'.join(update_dict_ids_to_dap_body))
def update_class_to_generate_init(class_to_generate):
args = []
init_body = []
docstring = []
required = _OrderedSet(class_to_generate.get('required', _OrderedSet()))
prop_name_and_prop = extract_prop_name_and_prop(class_to_generate)
translate_prop_names = []
for prop_name, prop in prop_name_and_prop:
if is_variable_to_translate(class_to_generate['name'], prop_name):
translate_prop_names.append(prop_name)
enum = prop.get('enum')
if enum and len(enum) == 1:
init_body.append(' self.%(prop_name)s = %(enum)r' % dict(prop_name=prop_name, enum=next(iter(enum))))
else:
if prop_name in required:
if prop_name == 'seq':
args.append(prop_name + '=-1')
else:
args.append(prop_name)
else:
args.append(prop_name + '=None')
if prop['type'].__class__ == Ref:
ref = prop['type']
ref_data = ref.ref_data
if ref_data.get('is_enum', False):
init_body.append(' if %s is not None:' % (prop_name,))
init_body.append(' assert %s in %s.VALID_VALUES' % (prop_name, str(ref)))
init_body.append(' self.%(prop_name)s = %(prop_name)s' % dict(
prop_name=prop_name))
else:
namespace = dict(
prop_name=prop_name,
ref_name=str(ref)
)
init_body.append(' if %(prop_name)s is None:' % namespace)
init_body.append(' self.%(prop_name)s = %(ref_name)s()' % namespace)
init_body.append(' else:')
init_body.append(' self.%(prop_name)s = %(ref_name)s(update_ids_from_dap=update_ids_from_dap, **%(prop_name)s) if %(prop_name)s.__class__ != %(ref_name)s else %(prop_name)s' % namespace
)
else:
init_body.append(' self.%(prop_name)s = %(prop_name)s' % dict(prop_name=prop_name))
if prop['type'] == 'array':
ref = prop['items'].get('$ref')
if ref is not None:
ref_array_cls_name = ref.split('/')[-1]
init_body.append(' if update_ids_from_dap and self.%(prop_name)s:' % dict(prop_name=prop_name))
init_body.append(' for o in self.%(prop_name)s:' % dict(prop_name=prop_name))
init_body.append(' %(ref_array_cls_name)s.update_dict_ids_from_dap(o)' % dict(ref_array_cls_name=ref_array_cls_name))
prop_type = prop['type']
prop_description = prop.get('description', '')
if isinstance(prop_description, (list, tuple)):
prop_description = '\n '.join(prop_description)
docstring.append(':param %(prop_type)s %(prop_name)s: %(prop_description)s' % dict(
prop_type=prop_type, prop_name=prop_name, prop_description=prop_description))
if translate_prop_names:
init_body.append(' if update_ids_from_dap:')
for prop_name in translate_prop_names:
init_body.append(' self.%(prop_name)s = self._translate_id_from_dap(self.%(prop_name)s)' % dict(prop_name=prop_name))
docstring = _indent_lines('\n'.join(docstring))
init_body = '\n'.join(init_body)
# Actually bundle the whole __init__ from the parts.
args = ', '.join(args)
if args:
args = ', ' + args
# Note: added kwargs because some messages are expected to be extended by the user (so, we'll actually
# make all extendable so that we don't have to worry about which ones -- we loose a little on typing,
# but may be better than doing a allow list based on something only pointed out in the documentation).
class_to_generate['init'] = '''def __init__(self%(args)s, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused)
"""
%(docstring)s
"""
%(init_body)s
self.kwargs = kwargs
''' % dict(args=args, init_body=init_body, docstring=docstring)
class_to_generate['init'] = _indent_lines(class_to_generate['init'])
def update_class_to_generate_props(class_to_generate):
import json
def default(o):
if isinstance(o, Ref):
return o.ref
raise AssertionError('Unhandled: %s' % (o,))
properties = class_to_generate['properties']
class_to_generate['props'] = ' __props__ = %s' % _indent_lines(
json.dumps(properties, indent=4, default=default)).strip()
def update_class_to_generate_refs(class_to_generate):
properties = class_to_generate['properties']
class_to_generate['refs'] = ' __refs__ = %s' % _OrderedSet(
key for (key, val) in properties.items() if val['type'].__class__ == Ref).set_repr()
def update_class_to_generate_enums(class_to_generate):
class_to_generate['enums'] = ''
if class_to_generate.get('is_enum', False):
enums = ''
for enum in class_to_generate['enum_values']:
enums += ' %s = %r\n' % (enum.upper(), enum)
enums += '\n'
enums += ' VALID_VALUES = %s\n\n' % _OrderedSet(class_to_generate['enum_values']).set_repr()
class_to_generate['enums'] = enums
def update_class_to_generate_objects(classes_to_generate, class_to_generate):
properties = class_to_generate['properties']
for key, val in properties.items():
if 'type' not in val:
val['type'] = 'TypeNA'
continue
if val['type'] == 'object':
create_new = val.copy()
create_new.update({
'name': '%s%s' % (class_to_generate['name'], key.title()),
'description': ' "%s" of %s' % (key, class_to_generate['name'])
})
if 'properties' not in create_new:
create_new['properties'] = {}
assert create_new['name'] not in classes_to_generate
classes_to_generate[create_new['name']] = create_new
update_class_to_generate_type(classes_to_generate, create_new)
update_class_to_generate_props(create_new)
# Update nested object types
update_class_to_generate_objects(classes_to_generate, create_new)
val['type'] = Ref(create_new['name'], classes_to_generate[create_new['name']])
val.pop('properties', None)
def gen_debugger_protocol():
import os.path
import sys
if sys.version_info[:2] < (3, 6):
raise AssertionError('Must be run with Python 3.6 onwards (to keep dict order).')
classes_to_generate = create_classes_to_generate_structure(load_schema_data())
classes_to_generate.update(create_classes_to_generate_structure(load_custom_schema_data()))
class_to_generate = fill_properties_and_required_from_base(classes_to_generate)
for class_to_generate in list(classes_to_generate.values()):
update_class_to_generate_description(class_to_generate)
update_class_to_generate_type(classes_to_generate, class_to_generate)
update_class_to_generate_props(class_to_generate)
update_class_to_generate_objects(classes_to_generate, class_to_generate)
for class_to_generate in classes_to_generate.values():
update_class_to_generate_refs(class_to_generate)
update_class_to_generate_init(class_to_generate)
update_class_to_generate_enums(class_to_generate)
update_class_to_generate_to_json(class_to_generate)
update_class_to_generate_register_dec(classes_to_generate, class_to_generate)
class_template = '''
%(register_request)s%(register_dec)s
class %(name)s(BaseSchema):
"""
%(description)s
Note: automatically generated code. Do not edit manually.
"""
%(enums)s%(props)s
%(refs)s
__slots__ = list(__props__.keys()) + ['kwargs']
%(init)s%(update_dict_ids_from_dap)s
%(to_dict)s%(update_dict_ids_to_dap)s
'''
contents = []
contents.append('# coding: utf-8')
contents.append('# Automatically generated code.')
contents.append('# Do not edit manually.')
contents.append('# Generated by running: %s' % os.path.basename(__file__))
contents.append('from .pydevd_base_schema import BaseSchema, register, register_request, register_response, register_event')
contents.append('')
for class_to_generate in classes_to_generate.values():
contents.append(class_template % class_to_generate)
parent_dir = os.path.dirname(__file__)
schema = os.path.join(parent_dir, 'pydevd_schema.py')
with open(schema, 'w', encoding='utf-8') as stream:
stream.write('\n'.join(contents)) | null |
177,735 | from __future__ import nested_scopes
import traceback
import warnings
from _pydev_bundle import pydev_log
from _pydev_bundle._pydev_saved_modules import thread, threading
from _pydev_bundle import _pydev_saved_modules
import signal
import os
import ctypes
from importlib import import_module
from urllib.parse import quote
import time
import inspect
import sys
from _pydevd_bundle.pydevd_constants import USE_CUSTOM_SYS_CURRENT_FRAMES, IS_PYPY, SUPPORT_GEVENT, \
GEVENT_SUPPORT_NOT_SET_MSG, GENERATED_LEN_ATTR_NAME, PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT, \
get_global_debugger
def get_main_thread():
if hasattr(threading, 'main_thread'):
return threading.main_thread()
else:
for t in threading.enumerate():
if isinstance(t, threading._MainThread):
return t
return None | null |
177,736 | from __future__ import nested_scopes
import traceback
import warnings
from _pydev_bundle import pydev_log
from _pydev_bundle._pydev_saved_modules import thread, threading
from _pydev_bundle import _pydev_saved_modules
import signal
import os
import ctypes
from importlib import import_module
from urllib.parse import quote
import time
import inspect
import sys
from _pydevd_bundle.pydevd_constants import USE_CUSTOM_SYS_CURRENT_FRAMES, IS_PYPY, SUPPORT_GEVENT, \
GEVENT_SUPPORT_NOT_SET_MSG, GENERATED_LEN_ATTR_NAME, PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT, \
get_global_debugger
def to_number(x):
if is_string(x):
try:
n = float(x)
return n
except ValueError:
pass
l = x.find('(')
if l != -1:
y = x[0:l - 1]
# print y
try:
n = float(y)
return n
except ValueError:
pass
return None
def to_string(x):
if isinstance(x, str):
return x
else:
return str(x)
GENERATED_LEN_ATTR_NAME = 'len()'
def compare_object_attrs_key(x):
if GENERATED_LEN_ATTR_NAME == x:
as_number = to_number(x)
if as_number is None:
as_number = 99999999
# len() should appear after other attributes in a list.
return (1, as_number)
else:
return (-1, to_string(x)) | null |
177,737 | from __future__ import nested_scopes
import traceback
import warnings
from _pydev_bundle import pydev_log
from _pydev_bundle._pydev_saved_modules import thread, threading
from _pydev_bundle import _pydev_saved_modules
import signal
import os
import ctypes
from importlib import import_module
from urllib.parse import quote
import time
import inspect
import sys
from _pydevd_bundle.pydevd_constants import USE_CUSTOM_SYS_CURRENT_FRAMES, IS_PYPY, SUPPORT_GEVENT, \
GEVENT_SUPPORT_NOT_SET_MSG, GENERATED_LEN_ATTR_NAME, PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT, \
get_global_debugger
def quote_smart(s, safe='/'):
return quote(s, safe) | null |
177,738 | from __future__ import nested_scopes
import traceback
import warnings
from _pydev_bundle import pydev_log
from _pydev_bundle._pydev_saved_modules import thread, threading
from _pydev_bundle import _pydev_saved_modules
import signal
import os
import ctypes
from importlib import import_module
from urllib.parse import quote
import time
import inspect
import sys
from _pydevd_bundle.pydevd_constants import USE_CUSTOM_SYS_CURRENT_FRAMES, IS_PYPY, SUPPORT_GEVENT, \
GEVENT_SUPPORT_NOT_SET_MSG, GENERATED_LEN_ATTR_NAME, PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT, \
get_global_debugger
def get_clsname_for_code(code, frame):
clsname = None
if len(code.co_varnames) > 0:
# We are checking the first argument of the function
# (`self` or `cls` for methods).
first_arg_name = code.co_varnames[0]
if first_arg_name in frame.f_locals:
first_arg_obj = frame.f_locals[first_arg_name]
if inspect.isclass(first_arg_obj): # class method
first_arg_class = first_arg_obj
else: # instance method
if hasattr(first_arg_obj, "__class__"):
first_arg_class = first_arg_obj.__class__
else: # old style class, fall back on type
first_arg_class = type(first_arg_obj)
func_name = code.co_name
if hasattr(first_arg_class, func_name):
method = getattr(first_arg_class, func_name)
func_code = None
if hasattr(method, 'func_code'): # Python2
func_code = method.func_code
elif hasattr(method, '__code__'): # Python3
func_code = method.__code__
if func_code and func_code == code:
clsname = first_arg_class.__name__
return clsname | null |
177,739 | from __future__ import nested_scopes
import traceback
import warnings
from _pydev_bundle import pydev_log
from _pydev_bundle._pydev_saved_modules import thread, threading
from _pydev_bundle import _pydev_saved_modules
import signal
import os
import ctypes
from importlib import import_module
from urllib.parse import quote
import time
import inspect
import sys
from _pydevd_bundle.pydevd_constants import USE_CUSTOM_SYS_CURRENT_FRAMES, IS_PYPY, SUPPORT_GEVENT, \
GEVENT_SUPPORT_NOT_SET_MSG, GENERATED_LEN_ATTR_NAME, PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT, \
get_global_debugger
def _extract_expression_list(log_message):
# Note: not using re because of nested braces.
expression = []
expression_vars = []
char_iter = iter(log_message)
for c in char_iter:
if c == '{':
expression_var = _extract_variable_nested_braces(char_iter)
if expression_var:
expression.append('%s')
expression_vars.append(expression_var)
else:
expression.append(c)
expression = ''.join(expression)
return expression, expression_vars
def convert_dap_log_message_to_expression(log_message):
try:
expression, expression_vars = _extract_expression_list(log_message)
except SyntaxError:
return repr('Unbalanced braces in: %s' % (log_message))
if not expression_vars:
return repr(expression)
# Note: use '%' to be compatible with Python 2.6.
return repr(expression) + ' % (' + ', '.join(str(x) for x in expression_vars) + ',)' | null |
177,740 | from __future__ import nested_scopes
import traceback
import warnings
from _pydev_bundle import pydev_log
from _pydev_bundle._pydev_saved_modules import thread, threading
from _pydev_bundle import _pydev_saved_modules
import signal
import os
import ctypes
from importlib import import_module
from urllib.parse import quote
import time
import inspect
import sys
from _pydevd_bundle.pydevd_constants import USE_CUSTOM_SYS_CURRENT_FRAMES, IS_PYPY, SUPPORT_GEVENT, \
GEVENT_SUPPORT_NOT_SET_MSG, GENERATED_LEN_ATTR_NAME, PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT, \
get_global_debugger
SUPPORT_GEVENT = is_true_in_env('GEVENT_SUPPORT')
GEVENT_SUPPORT_NOT_SET_MSG = os.getenv(
'GEVENT_SUPPORT_NOT_SET_MSG',
'It seems that the gevent monkey-patching is being used.\n'
'Please set an environment variable with:\n'
'GEVENT_SUPPORT=True\n'
'to enable gevent support in the debugger.'
)
The provided code snippet includes necessary dependencies for implementing the `notify_about_gevent_if_needed` function. Write a Python function `def notify_about_gevent_if_needed(stream=None)` to solve the following problem:
When debugging with gevent check that the gevent flag is used if the user uses the gevent monkey-patching. :return bool: Returns True if a message had to be shown to the user and False otherwise.
Here is the function:
def notify_about_gevent_if_needed(stream=None):
'''
When debugging with gevent check that the gevent flag is used if the user uses the gevent
monkey-patching.
:return bool:
Returns True if a message had to be shown to the user and False otherwise.
'''
stream = stream if stream is not None else sys.stderr
if not SUPPORT_GEVENT:
gevent_monkey = sys.modules.get('gevent.monkey')
if gevent_monkey is not None:
try:
saved = gevent_monkey.saved
except AttributeError:
pydev_log.exception_once('Error checking for gevent monkey-patching.')
return False
if saved:
# Note: print to stderr as it may deadlock the debugger.
sys.stderr.write('%s\n' % (GEVENT_SUPPORT_NOT_SET_MSG,))
return True
return False | When debugging with gevent check that the gevent flag is used if the user uses the gevent monkey-patching. :return bool: Returns True if a message had to be shown to the user and False otherwise. |
177,741 | from __future__ import nested_scopes
import traceback
import warnings
from _pydev_bundle import pydev_log
from _pydev_bundle._pydev_saved_modules import thread, threading
from _pydev_bundle import _pydev_saved_modules
import signal
import os
import ctypes
from importlib import import_module
from urllib.parse import quote
import time
import inspect
import sys
from _pydevd_bundle.pydevd_constants import USE_CUSTOM_SYS_CURRENT_FRAMES, IS_PYPY, SUPPORT_GEVENT, \
GEVENT_SUPPORT_NOT_SET_MSG, GENERATED_LEN_ATTR_NAME, PYDEVD_WARN_SLOW_RESOLVE_TIMEOUT, \
get_global_debugger
def import_module(name: Text, package: Optional[Text] = ...) -> types.ModuleType: ...
def import_attr_from_module(import_with_attr_access):
if '.' not in import_with_attr_access:
# We need at least one '.' (we don't support just the module import, we need the attribute access too).
raise ImportError('Unable to import module with attr access: %s' % (import_with_attr_access,))
module_name, attr_name = import_with_attr_access.rsplit('.', 1)
while True:
try:
mod = import_module(module_name)
except ImportError:
if '.' not in module_name:
raise ImportError('Unable to import module with attr access: %s' % (import_with_attr_access,))
module_name, new_attr_part = module_name.rsplit('.', 1)
attr_name = new_attr_part + '.' + attr_name
else:
# Ok, we got the base module, now, get the attribute we need.
try:
for attr in attr_name.split('.'):
mod = getattr(mod, attr)
return mod
except:
raise ImportError('Unable to import module with attr access: %s' % (import_with_attr_access,)) | null |
177,742 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
def create_server_socket(host, port):
try:
server = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP)
if IS_WINDOWS and not IS_JYTHON:
server.setsockopt(SOL_SOCKET, SO_EXCLUSIVEADDRUSE, 1)
elif not IS_WASM:
server.setsockopt(SOL_SOCKET, SO_REUSEADDR, 1)
server.bind((host, port))
server.settimeout(None)
except Exception:
server.close()
raise
return server
def exception(msg='', *args):
try:
_pydevd_log_exception(msg, *args)
except:
pass # Should never fail (even at interpreter shutdown).
The provided code snippet includes necessary dependencies for implementing the `start_server` function. Write a Python function `def start_server(port)` to solve the following problem:
binds to a port, waits for the debugger to connect
Here is the function:
def start_server(port):
''' binds to a port, waits for the debugger to connect '''
s = create_server_socket(host='', port=port)
try:
s.listen(1)
new_socket, _addr = s.accept()
pydev_log.info("Connection accepted")
# closing server socket is not necessary but we don't need it
s.close()
return new_socket
except:
pydev_log.exception("Could not bind to port: %s\n", port)
raise | binds to a port, waits for the debugger to connect |
177,743 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
AF_INET, SOCK_STREAM, SHUT_WR, SOL_SOCKET, IPPROTO_TCP, socket = (
socket_module.AF_INET,
socket_module.SOCK_STREAM,
socket_module.SHUT_WR,
socket_module.SOL_SOCKET,
socket_module.IPPROTO_TCP,
socket_module.socket,
)
def exception(msg='', *args):
try:
_pydevd_log_exception(msg, *args)
except:
pass # Should never fail (even at interpreter shutdown).
The provided code snippet includes necessary dependencies for implementing the `start_client` function. Write a Python function `def start_client(host, port)` to solve the following problem:
connects to a host/port
Here is the function:
def start_client(host, port):
''' connects to a host/port '''
pydev_log.info("Connecting to %s:%s", host, port)
s = socket(AF_INET, SOCK_STREAM)
# Set TCP keepalive on an open socket.
# It activates after 1 second (TCP_KEEPIDLE,) of idleness,
# then sends a keepalive ping once every 3 seconds (TCP_KEEPINTVL),
# and closes the connection after 5 failed ping (TCP_KEEPCNT), or 15 seconds
try:
s.setsockopt(SOL_SOCKET, socket_module.SO_KEEPALIVE, 1)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
s.setsockopt(socket_module.IPPROTO_TCP, socket_module.TCP_KEEPIDLE, 1)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
s.setsockopt(socket_module.IPPROTO_TCP, socket_module.TCP_KEEPINTVL, 3)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
s.setsockopt(socket_module.IPPROTO_TCP, socket_module.TCP_KEEPCNT, 5)
except (AttributeError, OSError):
pass # May not be available everywhere.
try:
# 10 seconds default timeout
timeout = int(os.environ.get('PYDEVD_CONNECT_TIMEOUT', 10))
s.settimeout(timeout)
s.connect((host, port))
s.settimeout(None) # no timeout after connected
pydev_log.info("Connected.")
return s
except:
pydev_log.exception("Could not connect to %s: %s", host, port)
raise | connects to a host/port |
177,744 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
def _send_io_message(py_db, s):
cmd = py_db.cmd_factory.make_io_message(s, 2)
if py_db.writer is not None:
py_db.writer.add_command(cmd)
def exception(msg='', *args):
try:
_pydevd_log_exception(msg, *args)
except:
pass # Should never fail (even at interpreter shutdown).
def internal_reload_code(dbg, seq, module_name, filename):
try:
found_module_to_reload = False
if module_name is not None:
module_name = module_name
if module_name not in sys.modules:
if '.' in module_name:
new_module_name = module_name.split('.')[-1]
if new_module_name in sys.modules:
module_name = new_module_name
modules_to_reload = {}
module = sys.modules.get(module_name)
if module is not None:
modules_to_reload[id(module)] = (module, module_name)
if filename:
filename = pydevd_file_utils.normcase(filename)
for module_name, module in sys.modules.copy().items():
f = getattr_checked(module, '__file__')
if f is not None:
if f.endswith(('.pyc', '.pyo')):
f = f[:-1]
if pydevd_file_utils.normcase(f) == filename:
modules_to_reload[id(module)] = (module, module_name)
if not modules_to_reload:
if filename and module_name:
_send_io_message(dbg, 'code reload: Unable to find module %s to reload for path: %s\n' % (module_name, filename))
elif filename:
_send_io_message(dbg, 'code reload: Unable to find module to reload for path: %s\n' % (filename,))
elif module_name:
_send_io_message(dbg, 'code reload: Unable to find module to reload: %s\n' % (module_name,))
else:
# Too much info...
# _send_io_message(dbg, 'code reload: This usually means you are trying to reload the __main__ module (which cannot be reloaded).\n')
for module, module_name in modules_to_reload.values():
_send_io_message(dbg, 'code reload: Start reloading module: "' + module_name + '" ... \n')
found_module_to_reload = True
if pydevd_reload.xreload(module):
_send_io_message(dbg, 'code reload: reload finished\n')
else:
_send_io_message(dbg, 'code reload: reload finished without applying any change\n')
cmd = dbg.cmd_factory.make_reloaded_code_message(seq, found_module_to_reload)
dbg.writer.add_command(cmd)
except:
pydev_log.exception('Error reloading code') | null |
177,745 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
STATE_RUN = 1
def pydevd_find_thread_by_id(thread_id):
try:
threads = threading.enumerate()
for i in threads:
tid = get_thread_id(i)
if thread_id == tid or thread_id.endswith('|' + tid):
return i
# This can happen when a request comes for a thread which was previously removed.
pydev_log.info("Could not find thread %s.", thread_id)
pydev_log.info("Available: %s.", ([get_thread_id(t) for t in threads],))
except:
pydev_log.exception()
return None
def resume_threads(thread_id, except_thread=None):
pydev_log.info('Resuming threads: %s (except thread: %s)', thread_id, except_thread)
threads = []
if thread_id == '*':
threads = pydevd_utils.get_non_pydevd_threads()
elif thread_id.startswith('__frame__:'):
pydev_log.critical("Can't make tasklet run: %s", thread_id)
else:
threads = [pydevd_find_thread_by_id(thread_id)]
for t in threads:
if t is None or t is except_thread:
pydev_log.info('Skipped resuming thread: %s', t)
continue
internal_run_thread(t, set_additional_thread_info=set_additional_thread_info)
def internal_step_in_thread(py_db, thread_id, cmd_id, set_additional_thread_info):
thread_to_step = pydevd_find_thread_by_id(thread_id)
if thread_to_step is not None:
info = set_additional_thread_info(thread_to_step)
info.pydev_original_step_cmd = cmd_id
info.pydev_step_cmd = cmd_id
info.pydev_step_stop = None
info.pydev_state = STATE_RUN
if py_db.stepping_resumes_all_threads:
resume_threads('*', except_thread=thread_to_step) | null |
177,746 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
STATE_RUN = 1
def pydevd_find_thread_by_id(thread_id):
def resume_threads(thread_id, except_thread=None):
def internal_smart_step_into(py_db, thread_id, offset, child_offset, set_additional_thread_info):
thread_to_step = pydevd_find_thread_by_id(thread_id)
if thread_to_step is not None:
info = set_additional_thread_info(thread_to_step)
info.pydev_original_step_cmd = CMD_SMART_STEP_INTO
info.pydev_step_cmd = CMD_SMART_STEP_INTO
info.pydev_step_stop = None
info.pydev_smart_parent_offset = int(offset)
info.pydev_smart_child_offset = int(child_offset)
info.pydev_state = STATE_RUN
if py_db.stepping_resumes_all_threads:
resume_threads('*', except_thread=thread_to_step) | null |
177,747 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
class VariablesResponseBody(BaseSchema):
"""
"body" of VariablesResponse
Note: automatically generated code. Do not edit manually.
"""
__props__ = {
"variables": {
"type": "array",
"items": {
"$ref": "#/definitions/Variable"
},
"description": "All (or a range) of variables for the given variable reference."
}
}
__refs__ = set()
__slots__ = list(__props__.keys()) + ['kwargs']
def __init__(self, variables, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused)
"""
:param array variables: All (or a range) of variables for the given variable reference.
"""
self.variables = variables
if update_ids_from_dap and self.variables:
for o in self.variables:
Variable.update_dict_ids_from_dap(o)
self.kwargs = kwargs
def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused)
variables = self.variables
if variables and hasattr(variables[0], "to_dict"):
variables = [x.to_dict() for x in variables]
dct = {
'variables': [Variable.update_dict_ids_to_dap(o) for o in variables] if (update_ids_to_dap and variables) else variables,
}
dct.update(self.kwargs)
return dct
class NetCommand(_BaseNetCommand):
"""
Commands received/sent over the network.
Command can represent command received from the debugger,
or one to be sent by daemon.
"""
next_seq = 0 # sequence numbers
_showing_debug_info = 0
_show_debug_info_lock = ForkSafeLock(rlock=True)
_after_send = None
def __init__(self, cmd_id, seq, text, is_json=False):
"""
If sequence is 0, new sequence will be generated (otherwise, this was the response
to a command from the client).
"""
protocol = get_protocol()
self.id = cmd_id
if seq == 0:
NetCommand.next_seq += 2
seq = NetCommand.next_seq
self.seq = seq
if is_json:
if hasattr(text, 'to_dict'):
as_dict = text.to_dict(update_ids_to_dap=True)
else:
assert isinstance(text, dict)
as_dict = text
as_dict['pydevd_cmd_id'] = cmd_id
as_dict['seq'] = seq
self.as_dict = as_dict
text = json.dumps(as_dict)
assert isinstance(text, str)
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
self._show_debug_info(cmd_id, seq, text)
if is_json:
msg = text
else:
if protocol not in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
encoded = quote(to_string(text), '/<>_=" \t')
msg = '%s\t%s\t%s\n' % (cmd_id, seq, encoded)
else:
msg = '%s\t%s\t%s' % (cmd_id, seq, text)
if isinstance(msg, str):
msg = msg.encode('utf-8')
assert isinstance(msg, bytes)
as_bytes = msg
self._as_bytes = as_bytes
def send(self, sock):
as_bytes = self._as_bytes
try:
if get_protocol() in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
sock.sendall(('Content-Length: %s\r\n\r\n' % len(as_bytes)).encode('ascii'))
sock.sendall(as_bytes)
if self._after_send:
for method in self._after_send:
method(sock)
except:
if IS_JYTHON:
# Ignore errors in sock.sendall in Jython (seems to be common for Jython to
# give spurious exceptions at interpreter shutdown here).
pass
else:
raise
def call_after_send(self, callback):
if not self._after_send:
self._after_send = [callback]
else:
self._after_send.append(callback)
def _show_debug_info(cls, cmd_id, seq, text):
with cls._show_debug_info_lock:
# Only one thread each time (rlock).
if cls._showing_debug_info:
# avoid recursing in the same thread (just printing could create
# a new command when redirecting output).
return
cls._showing_debug_info += 1
try:
out_message = 'sending cmd (%s) --> ' % (get_protocol(),)
out_message += "%20s" % ID_TO_MEANING.get(str(cmd_id), 'UNKNOWN')
out_message += ' '
out_message += text.replace('\n', ' ')
try:
pydev_log.critical('%s\n', out_message)
except:
pass
finally:
cls._showing_debug_info -= 1
def exception(msg='', *args):
try:
_pydevd_log_exception(msg, *args)
except:
pass # Should never fail (even at interpreter shutdown).
The provided code snippet includes necessary dependencies for implementing the `internal_get_variable_json` function. Write a Python function `def internal_get_variable_json(py_db, request)` to solve the following problem:
:param VariablesRequest request:
Here is the function:
def internal_get_variable_json(py_db, request):
'''
:param VariablesRequest request:
'''
arguments = request.arguments # : :type arguments: VariablesArguments
variables_reference = arguments.variablesReference
scope = None
if isinstance_checked(variables_reference, ScopeRequest):
scope = variables_reference
variables_reference = variables_reference.variable_reference
fmt = arguments.format
if hasattr(fmt, 'to_dict'):
fmt = fmt.to_dict()
variables = []
try:
try:
variable = py_db.suspended_frames_manager.get_variable(variables_reference)
except KeyError:
pass
else:
for child_var in variable.get_children_variables(fmt=fmt, scope=scope):
variables.append(child_var.get_var_data(fmt=fmt))
except:
try:
exc, exc_type, tb = sys.exc_info()
err = ''.join(traceback.format_exception(exc, exc_type, tb))
variables = [{
'name': '<error>',
'value': err,
'type': '<error>',
'variablesReference': 0
}]
except:
err = '<Internal error - unable to get traceback when getting variables>'
pydev_log.exception(err)
variables = []
body = VariablesResponseBody(variables)
variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body})
py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) | :param VariablesRequest request: |
177,748 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
def get_exception_traceback_str():
exc_info = sys.exc_info()
s = StringIO()
traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=s)
return s.getvalue()
The provided code snippet includes necessary dependencies for implementing the `internal_change_variable` function. Write a Python function `def internal_change_variable(dbg, seq, thread_id, frame_id, scope, attr, value)` to solve the following problem:
Changes the value of a variable
Here is the function:
def internal_change_variable(dbg, seq, thread_id, frame_id, scope, attr, value):
''' Changes the value of a variable '''
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
result = pydevd_vars.change_attr_expression(frame, attr, value, dbg)
else:
result = None
xml = "<xml>"
xml += pydevd_xml.var_to_xml(result, "")
xml += "</xml>"
cmd = dbg.cmd_factory.make_variable_changed_message(seq, xml)
dbg.writer.add_command(cmd)
except Exception:
cmd = dbg.cmd_factory.make_error_message(seq, "Error changing variable attr:%s expression:%s traceback:%s" % (attr, value, get_exception_traceback_str()))
dbg.writer.add_command(cmd) | Changes the value of a variable |
177,749 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
def _write_variable_response(py_db, request, value, success, message):
body = SetVariableResponseBody('')
variables_response = pydevd_base_schema.build_response(
request,
kwargs={
'body':body,
'success': False,
'message': message
})
cmd = NetCommand(CMD_RETURN, 0, variables_response, is_json=True)
py_db.writer.add_command(cmd)
class SetVariableResponseBody(BaseSchema):
"""
"body" of SetVariableResponse
Note: automatically generated code. Do not edit manually.
"""
__props__ = {
"value": {
"type": "string",
"description": "The new value of the variable."
},
"type": {
"type": "string",
"description": "The type of the new value. Typically shown in the UI when hovering over the value."
},
"variablesReference": {
"type": "integer",
"description": "If variablesReference is > 0, the new value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest.\nThe value should be less than or equal to 2147483647 (2^31-1)."
},
"namedVariables": {
"type": "integer",
"description": "The number of named child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks.\nThe value should be less than or equal to 2147483647 (2^31-1)."
},
"indexedVariables": {
"type": "integer",
"description": "The number of indexed child variables.\nThe client can use this optional information to present the variables in a paged UI and fetch them in chunks.\nThe value should be less than or equal to 2147483647 (2^31-1)."
}
}
__refs__ = set()
__slots__ = list(__props__.keys()) + ['kwargs']
def __init__(self, value, type=None, variablesReference=None, namedVariables=None, indexedVariables=None, update_ids_from_dap=False, **kwargs): # noqa (update_ids_from_dap may be unused)
"""
:param string value: The new value of the variable.
:param string type: The type of the new value. Typically shown in the UI when hovering over the value.
:param integer variablesReference: If variablesReference is > 0, the new value is structured and its children can be retrieved by passing variablesReference to the VariablesRequest.
The value should be less than or equal to 2147483647 (2^31-1).
:param integer namedVariables: The number of named child variables.
The client can use this optional information to present the variables in a paged UI and fetch them in chunks.
The value should be less than or equal to 2147483647 (2^31-1).
:param integer indexedVariables: The number of indexed child variables.
The client can use this optional information to present the variables in a paged UI and fetch them in chunks.
The value should be less than or equal to 2147483647 (2^31-1).
"""
self.value = value
self.type = type
self.variablesReference = variablesReference
self.namedVariables = namedVariables
self.indexedVariables = indexedVariables
if update_ids_from_dap:
self.variablesReference = self._translate_id_from_dap(self.variablesReference)
self.kwargs = kwargs
def update_dict_ids_from_dap(cls, dct):
if 'variablesReference' in dct:
dct['variablesReference'] = cls._translate_id_from_dap(dct['variablesReference'])
return dct
def to_dict(self, update_ids_to_dap=False): # noqa (update_ids_to_dap may be unused)
value = self.value
type = self.type # noqa (assign to builtin)
variablesReference = self.variablesReference
namedVariables = self.namedVariables
indexedVariables = self.indexedVariables
if update_ids_to_dap:
if variablesReference is not None:
variablesReference = self._translate_id_to_dap(variablesReference)
dct = {
'value': value,
}
if type is not None:
dct['type'] = type
if variablesReference is not None:
dct['variablesReference'] = variablesReference
if namedVariables is not None:
dct['namedVariables'] = namedVariables
if indexedVariables is not None:
dct['indexedVariables'] = indexedVariables
dct.update(self.kwargs)
return dct
def update_dict_ids_to_dap(cls, dct):
if 'variablesReference' in dct:
dct['variablesReference'] = cls._translate_id_to_dap(dct['variablesReference'])
return dct
class NetCommand(_BaseNetCommand):
"""
Commands received/sent over the network.
Command can represent command received from the debugger,
or one to be sent by daemon.
"""
next_seq = 0 # sequence numbers
_showing_debug_info = 0
_show_debug_info_lock = ForkSafeLock(rlock=True)
_after_send = None
def __init__(self, cmd_id, seq, text, is_json=False):
"""
If sequence is 0, new sequence will be generated (otherwise, this was the response
to a command from the client).
"""
protocol = get_protocol()
self.id = cmd_id
if seq == 0:
NetCommand.next_seq += 2
seq = NetCommand.next_seq
self.seq = seq
if is_json:
if hasattr(text, 'to_dict'):
as_dict = text.to_dict(update_ids_to_dap=True)
else:
assert isinstance(text, dict)
as_dict = text
as_dict['pydevd_cmd_id'] = cmd_id
as_dict['seq'] = seq
self.as_dict = as_dict
text = json.dumps(as_dict)
assert isinstance(text, str)
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
self._show_debug_info(cmd_id, seq, text)
if is_json:
msg = text
else:
if protocol not in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
encoded = quote(to_string(text), '/<>_=" \t')
msg = '%s\t%s\t%s\n' % (cmd_id, seq, encoded)
else:
msg = '%s\t%s\t%s' % (cmd_id, seq, text)
if isinstance(msg, str):
msg = msg.encode('utf-8')
assert isinstance(msg, bytes)
as_bytes = msg
self._as_bytes = as_bytes
def send(self, sock):
as_bytes = self._as_bytes
try:
if get_protocol() in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
sock.sendall(('Content-Length: %s\r\n\r\n' % len(as_bytes)).encode('ascii'))
sock.sendall(as_bytes)
if self._after_send:
for method in self._after_send:
method(sock)
except:
if IS_JYTHON:
# Ignore errors in sock.sendall in Jython (seems to be common for Jython to
# give spurious exceptions at interpreter shutdown here).
pass
else:
raise
def call_after_send(self, callback):
if not self._after_send:
self._after_send = [callback]
else:
self._after_send.append(callback)
def _show_debug_info(cls, cmd_id, seq, text):
with cls._show_debug_info_lock:
# Only one thread each time (rlock).
if cls._showing_debug_info:
# avoid recursing in the same thread (just printing could create
# a new command when redirecting output).
return
cls._showing_debug_info += 1
try:
out_message = 'sending cmd (%s) --> ' % (get_protocol(),)
out_message += "%20s" % ID_TO_MEANING.get(str(cmd_id), 'UNKNOWN')
out_message += ' '
out_message += text.replace('\n', ' ')
try:
pydev_log.critical('%s\n', out_message)
except:
pass
finally:
cls._showing_debug_info -= 1
The provided code snippet includes necessary dependencies for implementing the `internal_change_variable_json` function. Write a Python function `def internal_change_variable_json(py_db, request)` to solve the following problem:
The pydevd_vars.change_attr_expression(thread_id, frame_id, attr, value, dbg) can only deal with changing at a frame level, so, currently changing the contents of something in a different scope is currently not supported. :param SetVariableRequest request:
Here is the function:
def internal_change_variable_json(py_db, request):
'''
The pydevd_vars.change_attr_expression(thread_id, frame_id, attr, value, dbg) can only
deal with changing at a frame level, so, currently changing the contents of something
in a different scope is currently not supported.
:param SetVariableRequest request:
'''
# : :type arguments: SetVariableArguments
arguments = request.arguments
variables_reference = arguments.variablesReference
scope = None
if isinstance_checked(variables_reference, ScopeRequest):
scope = variables_reference
variables_reference = variables_reference.variable_reference
fmt = arguments.format
if hasattr(fmt, 'to_dict'):
fmt = fmt.to_dict()
try:
variable = py_db.suspended_frames_manager.get_variable(variables_reference)
except KeyError:
variable = None
if variable is None:
_write_variable_response(
py_db, request, value='', success=False, message='Unable to find variable container to change: %s.' % (variables_reference,))
return
child_var = variable.change_variable(arguments.name, arguments.value, py_db, fmt=fmt)
if child_var is None:
_write_variable_response(
py_db, request, value='', success=False, message='Unable to change: %s.' % (arguments.name,))
return
var_data = child_var.get_var_data(fmt=fmt)
body = SetVariableResponseBody(
value=var_data['value'],
type=var_data['type'],
variablesReference=var_data.get('variablesReference'),
namedVariables=var_data.get('namedVariables'),
indexedVariables=var_data.get('indexedVariables'),
)
variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body})
py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) | The pydevd_vars.change_attr_expression(thread_id, frame_id, attr, value, dbg) can only deal with changing at a frame level, so, currently changing the contents of something in a different scope is currently not supported. :param SetVariableRequest request: |
177,750 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
The provided code snippet includes necessary dependencies for implementing the `internal_get_frame` function. Write a Python function `def internal_get_frame(dbg, seq, thread_id, frame_id)` to solve the following problem:
Converts request into python variable
Here is the function:
def internal_get_frame(dbg, seq, thread_id, frame_id):
''' Converts request into python variable '''
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
hidden_ns = pydevconsole.get_ipython_hidden_vars()
xml = "<xml>"
xml += pydevd_xml.frame_vars_to_xml(frame.f_locals, hidden_ns)
del frame
xml += "</xml>"
cmd = dbg.cmd_factory.make_get_frame_message(seq, xml)
dbg.writer.add_command(cmd)
else:
# pydevd_vars.dump_frames(thread_id)
# don't print this error: frame not found: means that the client is not synchronized (but that's ok)
cmd = dbg.cmd_factory.make_error_message(seq, "Frame not found: %s from thread: %s" % (frame_id, thread_id))
dbg.writer.add_command(cmd)
except:
cmd = dbg.cmd_factory.make_error_message(seq, "Error resolving frame: %s from thread: %s" % (frame_id, thread_id))
dbg.writer.add_command(cmd) | Converts request into python variable |
177,751 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
class NetCommand(_BaseNetCommand):
def __init__(self, cmd_id, seq, text, is_json=False):
def send(self, sock):
def call_after_send(self, callback):
def _show_debug_info(cls, cmd_id, seq, text):
def pydevd_find_thread_by_id(thread_id):
def exception(msg='', *args): # Should never fail (even at interpreter shutdown).
def internal_get_smart_step_into_variants(dbg, seq, thread_id, frame_id, start_line, end_line, set_additional_thread_info):
try:
thread = pydevd_find_thread_by_id(thread_id)
frame = dbg.find_frame(thread_id, frame_id)
if thread is None or frame is None:
cmd = dbg.cmd_factory.make_error_message(seq, "Frame not found: %s from thread: %s" % (frame_id, thread_id))
dbg.writer.add_command(cmd)
return
if pydevd_bytecode_utils is None:
variants = []
else:
variants = pydevd_bytecode_utils.calculate_smart_step_into_variants(frame, int(start_line), int(end_line))
info = set_additional_thread_info(thread)
# Store the last request (may be used afterwards when stepping).
info.pydev_smart_step_into_variants = tuple(variants)
xml = "<xml>"
for variant in variants:
if variant.children_variants:
for child_variant in variant.children_variants:
# If there are child variants, the current one is just an intermediary, so,
# just create variants for the child (notifying properly about the parent too).
xml += '<variant name="%s" isVisited="%s" line="%s" offset="%s" childOffset="%s" callOrder="%s"/>' % (
quote(child_variant.name),
str(child_variant.is_visited).lower(),
child_variant.line,
variant.offset,
child_variant.offset,
child_variant.call_order,
)
else:
xml += '<variant name="%s" isVisited="%s" line="%s" offset="%s" childOffset="-1" callOrder="%s"/>' % (
quote(variant.name),
str(variant.is_visited).lower(),
variant.line,
variant.offset,
variant.call_order,
)
xml += "</xml>"
cmd = NetCommand(CMD_GET_SMART_STEP_INTO_VARIANTS, seq, xml)
dbg.writer.add_command(cmd)
except:
# Error is expected (if `dis` module cannot be used -- i.e.: Jython).
pydev_log.exception('Error calculating Smart Step Into Variants.')
cmd = dbg.cmd_factory.make_error_message(
seq, "Error getting smart step into variants for frame: %s from thread: %s"
% (frame_id, thread_id))
dbg.writer.add_command(cmd) | null |
177,752 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
class StepInTarget(BaseSchema):
def __init__(self, id, label, update_ids_from_dap=False, **kwargs):
def to_dict(self, update_ids_to_dap=False):
class StepInTargetsResponseBody(BaseSchema):
def __init__(self, targets, update_ids_from_dap=False, **kwargs):
def to_dict(self, update_ids_to_dap=False):
class NetCommand(_BaseNetCommand):
def __init__(self, cmd_id, seq, text, is_json=False):
def send(self, sock):
def call_after_send(self, callback):
def _show_debug_info(cls, cmd_id, seq, text):
def pydevd_find_thread_by_id(thread_id):
def exception(msg='', *args): # Should never fail (even at interpreter shutdown).
def internal_get_step_in_targets_json(dbg, seq, thread_id, frame_id, request, set_additional_thread_info):
try:
thread = pydevd_find_thread_by_id(thread_id)
frame = dbg.find_frame(thread_id, frame_id)
if thread is None or frame is None:
body = StepInTargetsResponseBody([])
variables_response = pydevd_base_schema.build_response(
request,
kwargs={
'body': body,
'success': False,
'message': 'Thread to get step in targets seems to have resumed already.'
})
cmd = NetCommand(CMD_RETURN, 0, variables_response, is_json=True)
dbg.writer.add_command(cmd)
return
start_line = 0
end_line = 99999999
if pydevd_bytecode_utils is None:
variants = []
else:
variants = pydevd_bytecode_utils.calculate_smart_step_into_variants(frame, start_line, end_line)
info = set_additional_thread_info(thread)
targets = []
counter = itertools.count(0)
target_id_to_variant = {}
for variant in variants:
if not variant.is_visited:
if variant.children_variants:
for child_variant in variant.children_variants:
target_id = next(counter)
if child_variant.call_order > 1:
targets.append(StepInTarget(id=target_id, label='%s (call %s)' % (child_variant.name, child_variant.call_order),))
else:
targets.append(StepInTarget(id=target_id, label=child_variant.name))
target_id_to_variant[target_id] = child_variant
if len(targets) >= 15: # Show at most 15 targets.
break
else:
target_id = next(counter)
if variant.call_order > 1:
targets.append(StepInTarget(id=target_id, label='%s (call %s)' % (variant.name, variant.call_order),))
else:
targets.append(StepInTarget(id=target_id, label=variant.name))
target_id_to_variant[target_id] = variant
if len(targets) >= 15: # Show at most 15 targets.
break
# Store the last request (may be used afterwards when stepping).
info.pydev_smart_step_into_variants = tuple(variants)
info.target_id_to_smart_step_into_variant = target_id_to_variant
body = StepInTargetsResponseBody(targets=targets)
response = pydevd_base_schema.build_response(request, kwargs={'body': body})
cmd = NetCommand(CMD_RETURN, 0, response, is_json=True)
dbg.writer.add_command(cmd)
except Exception as e:
# Error is expected (if `dis` module cannot be used -- i.e.: Jython).
pydev_log.exception('Error calculating Smart Step Into Variants.')
body = StepInTargetsResponseBody([])
variables_response = pydevd_base_schema.build_response(
request,
kwargs={
'body': body,
'success': False,
'message': str(e)
})
cmd = NetCommand(CMD_RETURN, 0, variables_response, is_json=True)
dbg.writer.add_command(cmd) | null |
177,753 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
The provided code snippet includes necessary dependencies for implementing the `internal_get_next_statement_targets` function. Write a Python function `def internal_get_next_statement_targets(dbg, seq, thread_id, frame_id)` to solve the following problem:
gets the valid line numbers for use with set next statement
Here is the function:
def internal_get_next_statement_targets(dbg, seq, thread_id, frame_id):
''' gets the valid line numbers for use with set next statement '''
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
code = frame.f_code
xml = "<xml>"
try:
linestarts = dis.findlinestarts(code)
except:
# i.e.: jython doesn't provide co_lnotab, so, we can only keep at the current line.
xml += "<line>%d</line>" % (frame.f_lineno,)
else:
for _, line in linestarts:
xml += "<line>%d</line>" % (line,)
del frame
xml += "</xml>"
cmd = dbg.cmd_factory.make_get_next_statement_targets_message(seq, xml)
dbg.writer.add_command(cmd)
else:
cmd = dbg.cmd_factory.make_error_message(seq, "Frame not found: %s from thread: %s" % (frame_id, thread_id))
dbg.writer.add_command(cmd)
except:
cmd = dbg.cmd_factory.make_error_message(seq, "Error resolving frame: %s from thread: %s" % (frame_id, thread_id))
dbg.writer.add_command(cmd) | gets the valid line numbers for use with set next statement |
177,754 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
def _evaluate_response(py_db, request, result, error_message=''):
is_error = isinstance(result, ExceptionOnEvaluate)
if is_error:
result = result.result
if not error_message:
body = pydevd_schema.EvaluateResponseBody(result=result, variablesReference=0)
variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body})
py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True))
else:
body = pydevd_schema.EvaluateResponseBody(result=result, variablesReference=0)
variables_response = pydevd_base_schema.build_response(request, kwargs={
'body':body, 'success':False, 'message': error_message})
py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True))
_global_frame = None
def _evaluate_response_return_exception(py_db, request, exc_type, exc, initial_tb):
try:
tb = initial_tb
# Show the traceback without pydevd frames.
temp_tb = tb
while temp_tb:
if py_db.get_file_type(temp_tb.tb_frame) == PYDEV_FILE:
tb = temp_tb.tb_next
temp_tb = temp_tb.tb_next
if tb is None:
tb = initial_tb
err = ''.join(traceback.format_exception(exc_type, exc, tb))
# Make sure we don't keep references to them.
exc = None
exc_type = None
tb = None
temp_tb = None
initial_tb = None
except:
err = '<Internal error - unable to get traceback when evaluating expression>'
pydev_log.exception(err)
# Currently there is an issue in VSC where returning success=false for an
# eval request, in repl context, VSC does not show the error response in
# the debug console. So return the error message in result as well.
_evaluate_response(py_db, request, result=err, error_message=err)
def filter_all_warnings():
with warnings.catch_warnings():
warnings.filterwarnings("ignore")
yield
NULL = Null()
class NetCommand(_BaseNetCommand):
"""
Commands received/sent over the network.
Command can represent command received from the debugger,
or one to be sent by daemon.
"""
next_seq = 0 # sequence numbers
_showing_debug_info = 0
_show_debug_info_lock = ForkSafeLock(rlock=True)
_after_send = None
def __init__(self, cmd_id, seq, text, is_json=False):
"""
If sequence is 0, new sequence will be generated (otherwise, this was the response
to a command from the client).
"""
protocol = get_protocol()
self.id = cmd_id
if seq == 0:
NetCommand.next_seq += 2
seq = NetCommand.next_seq
self.seq = seq
if is_json:
if hasattr(text, 'to_dict'):
as_dict = text.to_dict(update_ids_to_dap=True)
else:
assert isinstance(text, dict)
as_dict = text
as_dict['pydevd_cmd_id'] = cmd_id
as_dict['seq'] = seq
self.as_dict = as_dict
text = json.dumps(as_dict)
assert isinstance(text, str)
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
self._show_debug_info(cmd_id, seq, text)
if is_json:
msg = text
else:
if protocol not in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
encoded = quote(to_string(text), '/<>_=" \t')
msg = '%s\t%s\t%s\n' % (cmd_id, seq, encoded)
else:
msg = '%s\t%s\t%s' % (cmd_id, seq, text)
if isinstance(msg, str):
msg = msg.encode('utf-8')
assert isinstance(msg, bytes)
as_bytes = msg
self._as_bytes = as_bytes
def send(self, sock):
as_bytes = self._as_bytes
try:
if get_protocol() in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
sock.sendall(('Content-Length: %s\r\n\r\n' % len(as_bytes)).encode('ascii'))
sock.sendall(as_bytes)
if self._after_send:
for method in self._after_send:
method(sock)
except:
if IS_JYTHON:
# Ignore errors in sock.sendall in Jython (seems to be common for Jython to
# give spurious exceptions at interpreter shutdown here).
pass
else:
raise
def call_after_send(self, callback):
if not self._after_send:
self._after_send = [callback]
else:
self._after_send.append(callback)
def _show_debug_info(cls, cmd_id, seq, text):
with cls._show_debug_info_lock:
# Only one thread each time (rlock).
if cls._showing_debug_info:
# avoid recursing in the same thread (just printing could create
# a new command when redirecting output).
return
cls._showing_debug_info += 1
try:
out_message = 'sending cmd (%s) --> ' % (get_protocol(),)
out_message += "%20s" % ID_TO_MEANING.get(str(cmd_id), 'UNKNOWN')
out_message += ' '
out_message += text.replace('\n', ' ')
try:
pydev_log.critical('%s\n', out_message)
except:
pass
finally:
cls._showing_debug_info -= 1
class ExceptionOnEvaluate:
def __init__(self, result, etype, tb):
self.result = result
self.etype = etype
self.tb = tb
The provided code snippet includes necessary dependencies for implementing the `internal_evaluate_expression_json` function. Write a Python function `def internal_evaluate_expression_json(py_db, request, thread_id)` to solve the following problem:
:param EvaluateRequest request:
Here is the function:
def internal_evaluate_expression_json(py_db, request, thread_id):
'''
:param EvaluateRequest request:
'''
global _global_frame
# : :type arguments: EvaluateArguments
arguments = request.arguments
expression = arguments.expression
frame_id = arguments.frameId
context = arguments.context
fmt = arguments.format
if hasattr(fmt, 'to_dict'):
fmt = fmt.to_dict()
ctx = NULL
if context == 'repl':
if not py_db.is_output_redirected:
ctx = pydevd_io.redirect_stream_to_pydb_io_messages_context()
else:
# If we're not in a repl (watch, hover, ...) don't show warnings.
ctx = filter_all_warnings()
with ctx:
try_exec = False
if frame_id is None:
if _global_frame is None:
# Lazily create a frame to be used for evaluation with no frame id.
def __create_frame():
yield sys._getframe()
_global_frame = next(__create_frame())
frame = _global_frame
try_exec = True # Always exec in this case
eval_result = None
else:
frame = py_db.find_frame(thread_id, frame_id)
eval_result = pydevd_vars.evaluate_expression(py_db, frame, expression, is_exec=False)
is_error = isinstance_checked(eval_result, ExceptionOnEvaluate)
if is_error:
if context == 'hover': # In a hover it doesn't make sense to do an exec.
_evaluate_response(py_db, request, result='', error_message='Exception occurred during evaluation.')
return
elif context == 'watch':
# If it's a watch, don't show it as an exception object, rather, format
# it and show it as a string (with success=False).
msg = '%s: %s' % (
eval_result.result.__class__.__name__, eval_result.result,)
_evaluate_response(py_db, request, result=msg, error_message=msg)
return
else:
# We only try the exec if the failure we had was due to not being able
# to evaluate the expression.
try:
pydevd_vars.compile_as_eval(expression)
except Exception:
try_exec = context == 'repl'
else:
try_exec = False
if context == 'repl':
# In the repl we should show the exception to the user.
_evaluate_response_return_exception(py_db, request, eval_result.etype, eval_result.result, eval_result.tb)
return
if try_exec:
try:
pydevd_vars.evaluate_expression(py_db, frame, expression, is_exec=True)
except (Exception, KeyboardInterrupt):
_evaluate_response_return_exception(py_db, request, *sys.exc_info())
return
# No result on exec.
_evaluate_response(py_db, request, result='')
return
# Ok, we have the result (could be an error), let's put it into the saved variables.
frame_tracker = py_db.suspended_frames_manager.get_frame_tracker(thread_id)
if frame_tracker is None:
# This is not really expected.
_evaluate_response(py_db, request, result='', error_message='Thread id: %s is not current thread id.' % (thread_id,))
return
safe_repr_custom_attrs = {}
if context == 'clipboard':
safe_repr_custom_attrs = dict(
maxstring_outer=2 ** 64,
maxstring_inner=2 ** 64,
maxother_outer=2 ** 64,
maxother_inner=2 ** 64,
)
if context == 'repl' and eval_result is None:
# We don't want "None" to appear when typing in the repl.
body = pydevd_schema.EvaluateResponseBody(
result='',
variablesReference=0,
)
else:
variable = frame_tracker.obtain_as_variable(expression, eval_result, frame=frame)
var_data = variable.get_var_data(fmt=fmt, context=context, **safe_repr_custom_attrs)
body = pydevd_schema.EvaluateResponseBody(
result=var_data['value'],
variablesReference=var_data.get('variablesReference', 0),
type=var_data.get('type'),
presentationHint=var_data.get('presentationHint'),
namedVariables=var_data.get('namedVariables'),
indexedVariables=var_data.get('indexedVariables'),
)
variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body})
py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) | :param EvaluateRequest request: |
177,755 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
def get_exception_traceback_str():
exc_info = sys.exc_info()
s = StringIO()
traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=s)
return s.getvalue()
The provided code snippet includes necessary dependencies for implementing the `internal_evaluate_expression` function. Write a Python function `def internal_evaluate_expression(dbg, seq, thread_id, frame_id, expression, is_exec, trim_if_too_big, attr_to_set_result)` to solve the following problem:
gets the value of a variable
Here is the function:
def internal_evaluate_expression(dbg, seq, thread_id, frame_id, expression, is_exec, trim_if_too_big, attr_to_set_result):
''' gets the value of a variable '''
try:
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
result = pydevd_vars.evaluate_expression(dbg, frame, expression, is_exec)
if attr_to_set_result != "":
pydevd_vars.change_attr_expression(frame, attr_to_set_result, expression, dbg, result)
else:
result = None
xml = "<xml>"
xml += pydevd_xml.var_to_xml(result, expression, trim_if_too_big)
xml += "</xml>"
cmd = dbg.cmd_factory.make_evaluate_expression_message(seq, xml)
dbg.writer.add_command(cmd)
except:
exc = get_exception_traceback_str()
cmd = dbg.cmd_factory.make_error_message(seq, "Error evaluating expression " + exc)
dbg.writer.add_command(cmd) | gets the value of a variable |
177,756 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
def _set_expression_response(py_db, request, result, error_message):
body = pydevd_schema.SetExpressionResponseBody(result='', variablesReference=0)
variables_response = pydevd_base_schema.build_response(request, kwargs={
'body':body, 'success':False, 'message': error_message})
py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True))
class NetCommand(_BaseNetCommand):
"""
Commands received/sent over the network.
Command can represent command received from the debugger,
or one to be sent by daemon.
"""
next_seq = 0 # sequence numbers
_showing_debug_info = 0
_show_debug_info_lock = ForkSafeLock(rlock=True)
_after_send = None
def __init__(self, cmd_id, seq, text, is_json=False):
"""
If sequence is 0, new sequence will be generated (otherwise, this was the response
to a command from the client).
"""
protocol = get_protocol()
self.id = cmd_id
if seq == 0:
NetCommand.next_seq += 2
seq = NetCommand.next_seq
self.seq = seq
if is_json:
if hasattr(text, 'to_dict'):
as_dict = text.to_dict(update_ids_to_dap=True)
else:
assert isinstance(text, dict)
as_dict = text
as_dict['pydevd_cmd_id'] = cmd_id
as_dict['seq'] = seq
self.as_dict = as_dict
text = json.dumps(as_dict)
assert isinstance(text, str)
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
self._show_debug_info(cmd_id, seq, text)
if is_json:
msg = text
else:
if protocol not in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
encoded = quote(to_string(text), '/<>_=" \t')
msg = '%s\t%s\t%s\n' % (cmd_id, seq, encoded)
else:
msg = '%s\t%s\t%s' % (cmd_id, seq, text)
if isinstance(msg, str):
msg = msg.encode('utf-8')
assert isinstance(msg, bytes)
as_bytes = msg
self._as_bytes = as_bytes
def send(self, sock):
as_bytes = self._as_bytes
try:
if get_protocol() in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
sock.sendall(('Content-Length: %s\r\n\r\n' % len(as_bytes)).encode('ascii'))
sock.sendall(as_bytes)
if self._after_send:
for method in self._after_send:
method(sock)
except:
if IS_JYTHON:
# Ignore errors in sock.sendall in Jython (seems to be common for Jython to
# give spurious exceptions at interpreter shutdown here).
pass
else:
raise
def call_after_send(self, callback):
if not self._after_send:
self._after_send = [callback]
else:
self._after_send.append(callback)
def _show_debug_info(cls, cmd_id, seq, text):
with cls._show_debug_info_lock:
# Only one thread each time (rlock).
if cls._showing_debug_info:
# avoid recursing in the same thread (just printing could create
# a new command when redirecting output).
return
cls._showing_debug_info += 1
try:
out_message = 'sending cmd (%s) --> ' % (get_protocol(),)
out_message += "%20s" % ID_TO_MEANING.get(str(cmd_id), 'UNKNOWN')
out_message += ' '
out_message += text.replace('\n', ' ')
try:
pydev_log.critical('%s\n', out_message)
except:
pass
finally:
cls._showing_debug_info -= 1
class ExceptionOnEvaluate:
def __init__(self, result, etype, tb):
self.result = result
self.etype = etype
self.tb = tb
def internal_set_expression_json(py_db, request, thread_id):
# : :type arguments: SetExpressionArguments
arguments = request.arguments
expression = arguments.expression
frame_id = arguments.frameId
value = arguments.value
fmt = arguments.format
if hasattr(fmt, 'to_dict'):
fmt = fmt.to_dict()
frame = py_db.find_frame(thread_id, frame_id)
exec_code = '%s = (%s)' % (expression, value)
result = pydevd_vars.evaluate_expression(py_db, frame, exec_code, is_exec=True)
is_error = isinstance(result, ExceptionOnEvaluate)
if is_error:
_set_expression_response(py_db, request, result, error_message='Error executing: %s' % (exec_code,))
return
# Ok, we have the result (could be an error), let's put it into the saved variables.
frame_tracker = py_db.suspended_frames_manager.get_frame_tracker(thread_id)
if frame_tracker is None:
# This is not really expected.
_set_expression_response(py_db, request, result, error_message='Thread id: %s is not current thread id.' % (thread_id,))
return
# Now that the exec is done, get the actual value changed to return.
result = pydevd_vars.evaluate_expression(py_db, frame, expression, is_exec=False)
variable = frame_tracker.obtain_as_variable(expression, result, frame=frame)
var_data = variable.get_var_data(fmt=fmt)
body = pydevd_schema.SetExpressionResponseBody(
value=var_data['value'],
variablesReference=var_data.get('variablesReference', 0),
type=var_data.get('type'),
presentationHint=var_data.get('presentationHint'),
namedVariables=var_data.get('namedVariables'),
indexedVariables=var_data.get('indexedVariables'),
)
variables_response = pydevd_base_schema.build_response(request, kwargs={'body':body})
py_db.writer.add_command(NetCommand(CMD_RETURN, 0, variables_response, is_json=True)) | null |
177,757 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
def extract_token_and_qualifier(text, line=0, column=0):
'''
Extracts the token a qualifier from the text given the line/colum
(see test_extract_token_and_qualifier for examples).
:param unicode text:
:param int line: 0-based
:param int column: 0-based
'''
# Note: not using the tokenize module because text should be unicode and
# line/column refer to the unicode text (otherwise we'd have to know
# those ranges after converted to bytes).
if line < 0:
line = 0
if column < 0:
column = 0
if isinstance(text, bytes):
text = text.decode('utf-8')
lines = text.splitlines()
try:
text = lines[line]
except IndexError:
return TokenAndQualifier(u'', u'')
if column >= len(text):
column = len(text)
text = text[:column]
token = u''
qualifier = u''
temp_token = []
for i in range(column - 1, -1, -1):
c = text[i]
if c in identifier_part or isidentifier(c) or c == u'.':
temp_token.append(c)
else:
break
temp_token = u''.join(reversed(temp_token))
if u'.' in temp_token:
temp_token = temp_token.split(u'.')
token = u'.'.join(temp_token[:-1])
qualifier = temp_token[-1]
else:
qualifier = temp_token
return TokenAndQualifier(token, qualifier)
def get_exception_traceback_str():
exc_info = sys.exc_info()
s = StringIO()
traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=s)
return s.getvalue()
The provided code snippet includes necessary dependencies for implementing the `internal_get_completions` function. Write a Python function `def internal_get_completions(dbg, seq, thread_id, frame_id, act_tok, line=-1, column=-1)` to solve the following problem:
Note that if the column is >= 0, the act_tok is considered text and the actual activation token/qualifier is computed in this command.
Here is the function:
def internal_get_completions(dbg, seq, thread_id, frame_id, act_tok, line=-1, column=-1):
'''
Note that if the column is >= 0, the act_tok is considered text and the actual
activation token/qualifier is computed in this command.
'''
try:
remove_path = None
try:
qualifier = ''
if column >= 0:
token_and_qualifier = extract_token_and_qualifier(act_tok, line, column)
act_tok = token_and_qualifier[0]
if act_tok:
act_tok += '.'
qualifier = token_and_qualifier[1]
frame = dbg.find_frame(thread_id, frame_id)
if frame is not None:
completions = _pydev_completer.generate_completions(frame, act_tok)
# Note that qualifier and start are only actually valid for the
# Debug Adapter Protocol (for the line-based protocol, the IDE
# is required to filter the completions returned).
cmd = dbg.cmd_factory.make_get_completions_message(
seq, completions, qualifier, start=column - len(qualifier))
dbg.writer.add_command(cmd)
else:
cmd = dbg.cmd_factory.make_error_message(seq, "internal_get_completions: Frame not found: %s from thread: %s" % (frame_id, thread_id))
dbg.writer.add_command(cmd)
finally:
if remove_path is not None:
sys.path.remove(remove_path)
except:
exc = get_exception_traceback_str()
sys.stderr.write('%s\n' % (exc,))
cmd = dbg.cmd_factory.make_error_message(seq, "Error evaluating expression " + exc)
dbg.writer.add_command(cmd) | Note that if the column is >= 0, the act_tok is considered text and the actual activation token/qualifier is computed in this command. |
177,758 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
def get_exception_traceback_str():
exc_info = sys.exc_info()
s = StringIO()
traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=s)
return s.getvalue()
The provided code snippet includes necessary dependencies for implementing the `internal_get_description` function. Write a Python function `def internal_get_description(dbg, seq, thread_id, frame_id, expression)` to solve the following problem:
Fetch the variable description stub from the debug console
Here is the function:
def internal_get_description(dbg, seq, thread_id, frame_id, expression):
''' Fetch the variable description stub from the debug console
'''
try:
frame = dbg.find_frame(thread_id, frame_id)
description = pydevd_console.get_description(frame, thread_id, frame_id, expression)
description = pydevd_xml.make_valid_xml_value(quote(description, '/>_= \t'))
description_xml = '<xml><var name="" type="" value="%s"/></xml>' % description
cmd = dbg.cmd_factory.make_get_description_message(seq, description_xml)
dbg.writer.add_command(cmd)
except:
exc = get_exception_traceback_str()
cmd = dbg.cmd_factory.make_error_message(seq, "Error in fetching description" + exc)
dbg.writer.add_command(cmd) | Fetch the variable description stub from the debug console |
177,759 | import linecache
import os
from _pydev_bundle.pydev_imports import _queue
from _pydev_bundle._pydev_saved_modules import time
from _pydev_bundle._pydev_saved_modules import threading
from _pydev_bundle._pydev_saved_modules import socket as socket_module
from _pydevd_bundle.pydevd_constants import (DebugInfoHolder, IS_WINDOWS, IS_JYTHON, IS_WASM,
IS_PY36_OR_GREATER, STATE_RUN, ASYNC_EVAL_TIMEOUT_SEC,
get_global_debugger, GetGlobalDebugger, set_global_debugger, # Keep for backward compatibility @UnusedImport
silence_warnings_decorator, filter_all_warnings, IS_PY311_OR_GREATER)
from _pydev_bundle.pydev_override import overrides
import weakref
from _pydev_bundle._pydev_completer import extract_token_and_qualifier
from _pydevd_bundle._debug_adapter.pydevd_schema import VariablesResponseBody, \
SetVariableResponseBody, StepInTarget, StepInTargetsResponseBody
from _pydevd_bundle._debug_adapter import pydevd_base_schema, pydevd_schema
from _pydevd_bundle.pydevd_net_command import NetCommand
from _pydevd_bundle.pydevd_xml import ExceptionOnEvaluate
from _pydevd_bundle.pydevd_constants import ForkSafeLock, NULL
from _pydevd_bundle.pydevd_daemon_thread import PyDBDaemonThread
from _pydevd_bundle.pydevd_thread_lifecycle import pydevd_find_thread_by_id, resume_threads
from _pydevd_bundle.pydevd_dont_trace_files import PYDEV_FILE
import dis
import pydevd_file_utils
import itertools
from urllib.parse import quote_plus, unquote_plus
import pydevconsole
from _pydevd_bundle import pydevd_vars, pydevd_io, pydevd_reload
from _pydevd_bundle import pydevd_bytecode_utils
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle import pydevd_vm_type
import sys
import traceback
from _pydevd_bundle.pydevd_utils import quote_smart as quote, compare_object_attrs_key, \
notify_about_gevent_if_needed, isinstance_checked, ScopeRequest, getattr_checked, Timer
from _pydev_bundle import pydev_log, fsnotify
from _pydev_bundle.pydev_log import exception as pydev_log_exception
from _pydev_bundle import _pydev_completer
from pydevd_tracing import get_exception_traceback_str
from _pydevd_bundle import pydevd_console
from _pydev_bundle.pydev_monkey import disable_trace_thread_modules, enable_trace_thread_modules
from io import StringIO
from _pydevd_bundle.pydevd_comm_constants import *
def build_exception_info_response(dbg, thread_id, thread, request_seq, set_additional_thread_info, iter_visible_frames_info, max_frames):
'''
:return ExceptionInfoResponse
'''
additional_info = set_additional_thread_info(thread)
topmost_frame = additional_info.get_topmost_frame(thread)
current_paused_frame_name = ''
source_path = '' # This is an extra bit of data used by Visual Studio
stack_str_lst = []
name = None
description = None
if topmost_frame is not None:
try:
try:
frames_list = dbg.suspended_frames_manager.get_frames_list(thread_id)
while frames_list is not None and len(frames_list):
frames = []
frame = None
if not name:
exc_type = frames_list.exc_type
if exc_type is not None:
try:
name = exc_type.__qualname__
except:
try:
name = exc_type.__name__
except:
try:
name = str(exc_type)
except:
pass
if not description:
exc_desc = frames_list.exc_desc
if exc_desc is not None:
try:
description = str(exc_desc)
except:
pass
for frame_id, frame, method_name, original_filename, filename_in_utf8, lineno, _applied_mapping, show_as_current_frame, line_col_info in \
iter_visible_frames_info(dbg, frames_list):
line_text = linecache.getline(original_filename, lineno)
# Never filter out plugin frames!
if not getattr(frame, 'IS_PLUGIN_FRAME', False):
if dbg.is_files_filter_enabled and dbg.apply_files_filter(frame, original_filename, False):
continue
if show_as_current_frame:
current_paused_frame_name = method_name
method_name += ' (Current frame)'
frames.append((filename_in_utf8, lineno, method_name, line_text, line_col_info))
if not source_path and frames:
source_path = frames[0][0]
if IS_PY311_OR_GREATER:
stack_summary = traceback.StackSummary()
for filename_in_utf8, lineno, method_name, line_text, line_col_info in frames[-max_frames:]:
frame_summary = traceback.FrameSummary(filename_in_utf8, lineno, method_name, line=line_text)
if line_col_info is not None:
frame_summary.end_lineno = line_col_info.end_lineno
frame_summary.colno = line_col_info.colno
frame_summary.end_colno = line_col_info.end_colno
stack_summary.append(frame_summary)
stack_str = ''.join(stack_summary.format())
else:
# Note: remove col info (just used in 3.11).
stack_str = ''.join(traceback.format_list((x[:-1] for x in frames[-max_frames:])))
try:
stype = frames_list.exc_type.__qualname__
smod = frames_list.exc_type.__module__
if smod not in ("__main__", "builtins"):
if not isinstance(smod, str):
smod = "<unknown>"
stype = smod + '.' + stype
except Exception:
stype = '<unable to get exception type>'
pydev_log.exception('Error getting exception type.')
stack_str += '%s: %s\n' % (stype, frames_list.exc_desc)
stack_str += frames_list.exc_context_msg
stack_str_lst.append(stack_str)
frames_list = frames_list.chained_frames_list
if frames_list is None or not frames_list:
break
except:
pydev_log.exception('Error on build_exception_info_response.')
finally:
topmost_frame = None
full_stack_str = ''.join(reversed(stack_str_lst))
if not name:
name = 'exception: type unknown'
if not description:
description = 'exception: no description'
if current_paused_frame_name:
name += ' (note: full exception trace is shown but execution is paused at: %s)' % (current_paused_frame_name,)
if thread.stop_reason == CMD_STEP_CAUGHT_EXCEPTION:
break_mode = pydevd_schema.ExceptionBreakMode.ALWAYS
else:
break_mode = pydevd_schema.ExceptionBreakMode.UNHANDLED
response = pydevd_schema.ExceptionInfoResponse(
request_seq=request_seq,
success=True,
command='exceptionInfo',
body=pydevd_schema.ExceptionInfoResponseBody(
exceptionId=name,
description=description,
breakMode=break_mode,
details=pydevd_schema.ExceptionDetails(
message=description,
typeName=name,
stackTrace=full_stack_str,
source=source_path,
# Note: ExceptionDetails actually accepts an 'innerException', but
# when passing it, VSCode is not showing the stack trace at all.
)
)
)
return response
class NetCommand(_BaseNetCommand):
"""
Commands received/sent over the network.
Command can represent command received from the debugger,
or one to be sent by daemon.
"""
next_seq = 0 # sequence numbers
_showing_debug_info = 0
_show_debug_info_lock = ForkSafeLock(rlock=True)
_after_send = None
def __init__(self, cmd_id, seq, text, is_json=False):
"""
If sequence is 0, new sequence will be generated (otherwise, this was the response
to a command from the client).
"""
protocol = get_protocol()
self.id = cmd_id
if seq == 0:
NetCommand.next_seq += 2
seq = NetCommand.next_seq
self.seq = seq
if is_json:
if hasattr(text, 'to_dict'):
as_dict = text.to_dict(update_ids_to_dap=True)
else:
assert isinstance(text, dict)
as_dict = text
as_dict['pydevd_cmd_id'] = cmd_id
as_dict['seq'] = seq
self.as_dict = as_dict
text = json.dumps(as_dict)
assert isinstance(text, str)
if DebugInfoHolder.DEBUG_TRACE_LEVEL >= 1:
self._show_debug_info(cmd_id, seq, text)
if is_json:
msg = text
else:
if protocol not in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
encoded = quote(to_string(text), '/<>_=" \t')
msg = '%s\t%s\t%s\n' % (cmd_id, seq, encoded)
else:
msg = '%s\t%s\t%s' % (cmd_id, seq, text)
if isinstance(msg, str):
msg = msg.encode('utf-8')
assert isinstance(msg, bytes)
as_bytes = msg
self._as_bytes = as_bytes
def send(self, sock):
as_bytes = self._as_bytes
try:
if get_protocol() in (HTTP_PROTOCOL, HTTP_JSON_PROTOCOL):
sock.sendall(('Content-Length: %s\r\n\r\n' % len(as_bytes)).encode('ascii'))
sock.sendall(as_bytes)
if self._after_send:
for method in self._after_send:
method(sock)
except:
if IS_JYTHON:
# Ignore errors in sock.sendall in Jython (seems to be common for Jython to
# give spurious exceptions at interpreter shutdown here).
pass
else:
raise
def call_after_send(self, callback):
if not self._after_send:
self._after_send = [callback]
else:
self._after_send.append(callback)
def _show_debug_info(cls, cmd_id, seq, text):
with cls._show_debug_info_lock:
# Only one thread each time (rlock).
if cls._showing_debug_info:
# avoid recursing in the same thread (just printing could create
# a new command when redirecting output).
return
cls._showing_debug_info += 1
try:
out_message = 'sending cmd (%s) --> ' % (get_protocol(),)
out_message += "%20s" % ID_TO_MEANING.get(str(cmd_id), 'UNKNOWN')
out_message += ' '
out_message += text.replace('\n', ' ')
try:
pydev_log.critical('%s\n', out_message)
except:
pass
finally:
cls._showing_debug_info -= 1
def get_exception_traceback_str():
exc_info = sys.exc_info()
s = StringIO()
traceback.print_exception(exc_info[0], exc_info[1], exc_info[2], file=s)
return s.getvalue()
The provided code snippet includes necessary dependencies for implementing the `internal_get_exception_details_json` function. Write a Python function `def internal_get_exception_details_json(dbg, request, thread_id, thread, max_frames, set_additional_thread_info=None, iter_visible_frames_info=None)` to solve the following problem:
Fetch exception details
Here is the function:
def internal_get_exception_details_json(dbg, request, thread_id, thread, max_frames, set_additional_thread_info=None, iter_visible_frames_info=None):
''' Fetch exception details
'''
try:
response = build_exception_info_response(dbg, thread_id, thread, request.seq, set_additional_thread_info, iter_visible_frames_info, max_frames)
except:
exc = get_exception_traceback_str()
response = pydevd_base_schema.build_response(request, kwargs={
'success': False,
'message': exc,
'body':{}
})
dbg.writer.add_command(NetCommand(CMD_RETURN, 0, response, is_json=True)) | Fetch exception details |
177,760 | from _pydev_bundle import pydev_log
import os
from _pydevd_bundle.pydevd_comm import CMD_SIGNATURE_CALL_TRACE, NetCommand
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle.pydevd_utils import get_clsname_for_code
The provided code snippet includes necessary dependencies for implementing the `_modname` function. Write a Python function `def _modname(path)` to solve the following problem:
Return a plausible module name for the path
Here is the function:
def _modname(path):
"""Return a plausible module name for the path"""
base = os.path.basename(path)
filename, ext = os.path.splitext(base)
return filename | Return a plausible module name for the path |
177,761 | from _pydev_bundle import pydev_log
import os
from _pydevd_bundle.pydevd_comm import CMD_SIGNATURE_CALL_TRACE, NetCommand
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle.pydevd_utils import get_clsname_for_code
def get_signature_info(signature):
return signature.file, signature.name, ' '.join([arg[1] for arg in signature.args]) | null |
177,762 | from _pydev_bundle import pydev_log
import os
from _pydevd_bundle.pydevd_comm import CMD_SIGNATURE_CALL_TRACE, NetCommand
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle.pydevd_utils import get_clsname_for_code
def get_frame_info(frame):
co = frame.f_code
return co.co_name, frame.f_lineno, co.co_filename | null |
177,763 | from _pydev_bundle import pydev_log
import os
from _pydevd_bundle.pydevd_comm import CMD_SIGNATURE_CALL_TRACE, NetCommand
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle.pydevd_utils import get_clsname_for_code
def create_signature_message(signature):
cmdTextList = ["<xml>"]
cmdTextList.append('<call_signature file="%s" name="%s">' % (pydevd_xml.make_valid_xml_value(signature.file), pydevd_xml.make_valid_xml_value(signature.name)))
for arg in signature.args:
cmdTextList.append('<arg name="%s" type="%s"></arg>' % (pydevd_xml.make_valid_xml_value(arg[0]), pydevd_xml.make_valid_xml_value(arg[1])))
if signature.return_type is not None:
cmdTextList.append('<return type="%s"></return>' % (pydevd_xml.make_valid_xml_value(signature.return_type)))
cmdTextList.append("</call_signature></xml>")
cmdText = ''.join(cmdTextList)
return NetCommand(CMD_SIGNATURE_CALL_TRACE, 0, cmdText)
def send_signature_call_trace(dbg, frame, filename):
if dbg.signature_factory and dbg.in_project_scope(frame):
signature = dbg.signature_factory.create_signature(frame, filename)
if signature is not None:
if dbg.signature_factory.cache is not None:
if not dbg.signature_factory.cache.is_in_cache(signature):
dbg.signature_factory.cache.add(signature)
dbg.writer.add_command(create_signature_message(signature))
return True
else:
# we don't send signature if it is cached
return False
else:
dbg.writer.add_command(create_signature_message(signature))
return True
return False | null |
177,764 | from _pydev_bundle import pydev_log
import os
from _pydevd_bundle.pydevd_comm import CMD_SIGNATURE_CALL_TRACE, NetCommand
from _pydevd_bundle import pydevd_xml
from _pydevd_bundle.pydevd_utils import get_clsname_for_code
def get_type_of_value(value, ignore_module_name=('__main__', '__builtin__', 'builtins'), recursive=False):
def create_signature_message(signature):
def send_signature_return_trace(dbg, frame, filename, return_value):
if dbg.signature_factory and dbg.in_project_scope(frame):
signature = dbg.signature_factory.create_signature(frame, filename, with_args=False)
signature.return_type = get_type_of_value(return_value, recursive=True)
dbg.writer.add_command(create_signature_message(signature))
return True
return False | null |
177,765 | import abc
from typing import Any
The provided code snippet includes necessary dependencies for implementing the `_with_metaclass` function. Write a Python function `def _with_metaclass(meta, *bases)` to solve the following problem:
Create a base class with a metaclass.
Here is the function:
def _with_metaclass(meta, *bases):
"""Create a base class with a metaclass."""
class metaclass(meta):
def __new__(cls, name, this_bases, d):
return meta(name, bases, d)
return type.__new__(metaclass, 'temporary_class', (), {}) | Create a base class with a metaclass. |
177,766 | import pkgutil
import sys
from _pydev_bundle import pydev_log
EXTENSION_MANAGER_INSTANCE = ExtensionManager()
The provided code snippet includes necessary dependencies for implementing the `extensions_of_type` function. Write a Python function `def extensions_of_type(extension_type)` to solve the following problem:
:param T extension_type: The type of the extension hook :rtype: list[T]
Here is the function:
def extensions_of_type(extension_type):
"""
:param T extension_type: The type of the extension hook
:rtype: list[T]
"""
return EXTENSION_MANAGER_INSTANCE.get_extension_classes(extension_type) | :param T extension_type: The type of the extension hook :rtype: list[T] |
177,767 | from _pydevd_bundle.pydevd_constants import (STATE_RUN, PYTHON_SUSPEND, SUPPORT_GEVENT, ForkSafeLock,
_current_frames)
from _pydev_bundle import pydev_log
from _pydevd_bundle.pydevd_frame import PyDBFrame
class PyDBAdditionalThreadInfo(object):
# ENDIF
# Note: the params in cython are declared in pydevd_cython.pxd.
# IFDEF CYTHON
# ELSE
__slots__ = [
'pydev_state',
'pydev_step_stop',
'pydev_original_step_cmd',
'pydev_step_cmd',
'pydev_notify_kill',
'pydev_django_resolve_frame',
'pydev_call_from_jinja2',
'pydev_call_inside_jinja2',
'is_tracing',
'conditional_breakpoint_exception',
'pydev_message',
'suspend_type',
'pydev_next_line',
'pydev_func_name',
'suspended_at_unhandled',
'trace_suspend_type',
'top_level_thread_tracer_no_back_frames',
'top_level_thread_tracer_unhandled',
'thread_tracer',
'step_in_initial_location',
# Used for CMD_SMART_STEP_INTO (to know which smart step into variant to use)
'pydev_smart_parent_offset',
'pydev_smart_child_offset',
# Used for CMD_SMART_STEP_INTO (list[_pydevd_bundle.pydevd_bytecode_utils.Variant])
# Filled when the cmd_get_smart_step_into_variants is requested (so, this is a copy
# of the last request for a given thread and pydev_smart_parent_offset/pydev_smart_child_offset relies on it).
'pydev_smart_step_into_variants',
'target_id_to_smart_step_into_variant',
'pydev_use_scoped_step_frame',
]
# ENDIF
def __init__(self):
self.pydev_state = STATE_RUN # STATE_RUN or STATE_SUSPEND
self.pydev_step_stop = None
# Note: we have `pydev_original_step_cmd` and `pydev_step_cmd` because the original is to
# say the action that started it and the other is to say what's the current tracing behavior
# (because it's possible that we start with a step over but may have to switch to a
# different step strategy -- for instance, if a step over is done and we return the current
# method the strategy is changed to a step in).
self.pydev_original_step_cmd = -1 # Something as CMD_STEP_INTO, CMD_STEP_OVER, etc.
self.pydev_step_cmd = -1 # Something as CMD_STEP_INTO, CMD_STEP_OVER, etc.
self.pydev_notify_kill = False
self.pydev_django_resolve_frame = False
self.pydev_call_from_jinja2 = None
self.pydev_call_inside_jinja2 = None
self.is_tracing = 0
self.conditional_breakpoint_exception = None
self.pydev_message = ''
self.suspend_type = PYTHON_SUSPEND
self.pydev_next_line = -1
self.pydev_func_name = '.invalid.' # Must match the type in cython
self.suspended_at_unhandled = False
self.trace_suspend_type = 'trace' # 'trace' or 'frame_eval'
self.top_level_thread_tracer_no_back_frames = []
self.top_level_thread_tracer_unhandled = None
self.thread_tracer = None
self.step_in_initial_location = None
self.pydev_smart_parent_offset = -1
self.pydev_smart_child_offset = -1
self.pydev_smart_step_into_variants = ()
self.target_id_to_smart_step_into_variant = {}
# Flag to indicate ipython use-case where each line will be executed as a call/line/return
# in a new new frame but in practice we want to consider each new frame as if it was all
# part of the same frame.
#
# In practice this means that a step over shouldn't revert to a step in and we need some
# special logic to know when we should stop in a step over as we need to consider 2
# different frames as being equal if they're logically the continuation of a frame
# being executed by ipython line by line.
#
# See: https://github.com/microsoft/debugpy/issues/869#issuecomment-1132141003
self.pydev_use_scoped_step_frame = False
def get_topmost_frame(self, thread):
'''
Gets the topmost frame for the given thread. Note that it may be None
and callers should remove the reference to the frame as soon as possible
to avoid disturbing user code.
'''
# sys._current_frames(): dictionary with thread id -> topmost frame
current_frames = _current_frames()
topmost_frame = current_frames.get(thread.ident)
if topmost_frame is None:
# Note: this is expected for dummy threads (so, getting the topmost frame should be
# treated as optional).
pydev_log.info(
'Unable to get topmost frame for thread: %s, thread.ident: %s, id(thread): %s\nCurrent frames: %s.\n'
'GEVENT_SUPPORT: %s',
thread,
thread.ident,
id(thread),
current_frames,
SUPPORT_GEVENT,
)
return topmost_frame
def __str__(self):
return 'State:%s Stop:%s Cmd: %s Kill:%s' % (
self.pydev_state, self.pydev_step_stop, self.pydev_step_cmd, self.pydev_notify_kill)
_set_additional_thread_info_lock = ForkSafeLock()
def set_additional_thread_info(thread):
try:
additional_info = thread.additional_info
if additional_info is None:
raise AttributeError()
except:
with _set_additional_thread_info_lock:
# If it's not there, set it within a lock to avoid any racing
# conditions.
additional_info = getattr(thread, 'additional_info', None)
if additional_info is None:
additional_info = PyDBAdditionalThreadInfo()
thread.additional_info = additional_info
return additional_info | null |
177,768 | import os
import sys
def convert_ppid(ppid):
ret = int(ppid)
if ret != 0:
if ret == os.getpid():
raise AssertionError(
'ppid passed is the same as the current process pid (%s)!' % (ret,))
return ret | null |
177,769 | import os
import sys
ACCEPTED_ARG_HANDLERS = [
ArgHandlerWithParam('port', int, 0),
ArgHandlerWithParam('ppid', convert_ppid, 0),
ArgHandlerWithParam('vm_type'),
ArgHandlerWithParam('client'),
ArgHandlerWithParam('access-token'),
ArgHandlerWithParam('client-access-token'),
ArgHandlerWithParam('debug-mode'),
ArgHandlerWithParam('preimport'),
# Logging
ArgHandlerWithParam('log-file'),
ArgHandlerWithParam('log-level', int, None),
ArgHandlerBool('server'),
ArgHandlerBool('multiproc'), # Used by PyCharm (reuses connection: ssh tunneling)
ArgHandlerBool('multiprocess'), # Used by PyDev (creates new connection to ide)
ArgHandlerBool('save-signatures'),
ArgHandlerBool('save-threading'),
ArgHandlerBool('save-asyncio'),
ArgHandlerBool('print-in-debugger-startup'),
ArgHandlerBool('cmd-line'),
ArgHandlerBool('module'),
ArgHandlerBool('skip-notify-stdin'),
# The ones below should've been just one setting to specify the protocol, but for compatibility
# reasons they're passed as a flag but are mutually exclusive.
ArgHandlerBool('json-dap'), # Protocol used by ptvsd to communicate with pydevd (a single json message in each read)
ArgHandlerBool('json-dap-http'), # Actual DAP (json messages over http protocol).
ArgHandlerBool('protocol-quoted-line'), # Custom protocol with quoted lines.
ArgHandlerBool('protocol-http'), # Custom protocol with http.
]
ARGV_REP_TO_HANDLER = {}
for handler in ACCEPTED_ARG_HANDLERS:
ARGV_REP_TO_HANDLER[handler.arg_v_rep] = handler
The provided code snippet includes necessary dependencies for implementing the `process_command_line` function. Write a Python function `def process_command_line(argv)` to solve the following problem:
parses the arguments. removes our arguments from the command line
Here is the function:
def process_command_line(argv):
""" parses the arguments.
removes our arguments from the command line """
setup = {}
for handler in ACCEPTED_ARG_HANDLERS:
setup[handler.arg_name] = handler.default_val
setup['file'] = ''
setup['qt-support'] = ''
initial_argv = tuple(argv)
i = 0
del argv[0]
while i < len(argv):
handler = ARGV_REP_TO_HANDLER.get(argv[i])
if handler is not None:
handler.handle_argv(argv, i, setup)
elif argv[i].startswith('--qt-support'):
# The --qt-support is special because we want to keep backward compatibility:
# Previously, just passing '--qt-support' meant that we should use the auto-discovery mode
# whereas now, if --qt-support is passed, it should be passed as --qt-support=<mode>, where
# mode can be one of 'auto', 'none', 'pyqt5', 'pyqt4', 'pyside', 'pyside2'.
if argv[i] == '--qt-support':
setup['qt-support'] = 'auto'
elif argv[i].startswith('--qt-support='):
qt_support = argv[i][len('--qt-support='):]
valid_modes = ('none', 'auto', 'pyqt5', 'pyqt4', 'pyside', 'pyside2')
if qt_support not in valid_modes:
raise ValueError("qt-support mode invalid: " + qt_support)
if qt_support == 'none':
# On none, actually set an empty string to evaluate to False.
setup['qt-support'] = ''
else:
setup['qt-support'] = qt_support
else:
raise ValueError("Unexpected definition for qt-support flag: " + argv[i])
del argv[i]
elif argv[i] == '--file':
# --file is special because it's the last one (so, no handler for it).
del argv[i]
setup['file'] = argv[i]
i = len(argv) # pop out, file is our last argument
elif argv[i] == '--DEBUG':
sys.stderr.write('pydevd: --DEBUG parameter deprecated. Use `--debug-level=3` instead.\n')
else:
raise ValueError("Unexpected option: %s when processing: %s" % (argv[i], initial_argv))
return setup | parses the arguments. removes our arguments from the command line |
177,770 | import os
from _pydevd_bundle.pydevd_constants import USE_CYTHON_FLAG, ENV_TRUE_LOWER_VALUES, \
ENV_FALSE_LOWER_VALUES
from _pydev_bundle import pydev_log
dirname = os.path.dirname(os.path.dirname(__file__))
def delete_old_compiled_extensions():
import _pydevd_bundle
cython_extensions_dir = os.path.dirname(os.path.dirname(_pydevd_bundle.__file__))
_pydevd_bundle_ext_dir = os.path.dirname(_pydevd_bundle.__file__)
_pydevd_frame_eval_ext_dir = os.path.join(cython_extensions_dir, '_pydevd_frame_eval_ext')
try:
import shutil
for file in os.listdir(_pydevd_bundle_ext_dir):
if file.startswith("pydevd") and file.endswith(".so"):
os.remove(os.path.join(_pydevd_bundle_ext_dir, file))
for file in os.listdir(_pydevd_frame_eval_ext_dir):
if file.startswith("pydevd") and file.endswith(".so"):
os.remove(os.path.join(_pydevd_frame_eval_ext_dir, file))
build_dir = os.path.join(cython_extensions_dir, "build")
if os.path.exists(build_dir):
shutil.rmtree(os.path.join(cython_extensions_dir, "build"))
except OSError:
pydev_log.error_once("warning: failed to delete old cython speedups. Please delete all *.so files from the directories "
"\"%s\" and \"%s\"" % (_pydevd_bundle_ext_dir, _pydevd_frame_eval_ext_dir)) | null |
177,771 | from _pydevd_bundle.pydevd_constants import QUOTED_LINE_PROTOCOL
from _pydev_bundle import pydev_log
import sys
class PydevdCustomization(object):
def on_pydb_init(py_db):
if PydevdCustomization.DEBUG_MODE == 'debugpy-dap':
pydev_log.debug('Apply debug mode: debugpy-dap')
py_db.skip_suspend_on_breakpoint_exception = (BaseException,)
py_db.skip_print_breakpoint_exception = (NameError,)
py_db.multi_threads_single_notification = True
elif not PydevdCustomization.DEBUG_MODE:
pydev_log.debug('Apply debug mode: default')
else:
pydev_log.debug('WARNING: unknown debug mode: %s', PydevdCustomization.DEBUG_MODE)
if PydevdCustomization.PREIMPORT:
pydev_log.debug('Preimport: %s', PydevdCustomization.PREIMPORT)
try:
sys_path_entry, module_name = PydevdCustomization.PREIMPORT.rsplit(';', maxsplit=1)
except Exception:
pydev_log.exception("Expected ';' in %s" % (PydevdCustomization.PREIMPORT,))
else:
try:
sys.path.insert(0, sys_path_entry)
try:
__import__(module_name)
finally:
sys.path.remove(sys_path_entry)
except Exception:
pydev_log.exception(
"Error importing %s (with sys.path entry: %s)" % (module_name, sys_path_entry)) | null |
177,772 | import sys
class PydevdVmType:
def set_vm_type(vm_type):
PydevdVmType.vm_type = vm_type | null |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.