body
stringlengths 26
98.2k
| body_hash
int64 -9,222,864,604,528,158,000
9,221,803,474B
| docstring
stringlengths 1
16.8k
| path
stringlengths 5
230
| name
stringlengths 1
96
| repository_name
stringlengths 7
89
| lang
stringclasses 1
value | body_without_docstring
stringlengths 20
98.2k
|
|---|---|---|---|---|---|---|---|
def push(self, variables, interactive=True):
"Inject a group of variables into the IPython user namespace.\n\n Parameters\n ----------\n variables : dict, str or list/tuple of str\n The variables to inject into the user's namespace. If a dict, a\n simple update is done. If a str, the string is assumed to have\n variable names separated by spaces. A list/tuple of str can also\n be used to give the variable names. If just the variable names are\n give (list/tuple/str) then the variable values looked up in the\n callers frame.\n interactive : bool\n If True (default), the variables will be listed with the ``who``\n magic.\n "
vdict = None
if isinstance(variables, dict):
vdict = variables
elif isinstance(variables, (str, list, tuple)):
if isinstance(variables, str):
vlist = variables.split()
else:
vlist = variables
vdict = {}
cf = sys._getframe(1)
for name in vlist:
try:
vdict[name] = eval(name, cf.f_globals, cf.f_locals)
except:
print(('Could not get variable %s from %s' % (name, cf.f_code.co_name)))
else:
raise ValueError('variables must be a dict/str/list/tuple')
self.user_ns.update(vdict)
user_ns_hidden = self.user_ns_hidden
if interactive:
for name in vdict:
user_ns_hidden.pop(name, None)
else:
user_ns_hidden.update(vdict)
| -5,859,677,587,196,510,000
|
Inject a group of variables into the IPython user namespace.
Parameters
----------
variables : dict, str or list/tuple of str
The variables to inject into the user's namespace. If a dict, a
simple update is done. If a str, the string is assumed to have
variable names separated by spaces. A list/tuple of str can also
be used to give the variable names. If just the variable names are
give (list/tuple/str) then the variable values looked up in the
callers frame.
interactive : bool
If True (default), the variables will be listed with the ``who``
magic.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
push
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def push(self, variables, interactive=True):
"Inject a group of variables into the IPython user namespace.\n\n Parameters\n ----------\n variables : dict, str or list/tuple of str\n The variables to inject into the user's namespace. If a dict, a\n simple update is done. If a str, the string is assumed to have\n variable names separated by spaces. A list/tuple of str can also\n be used to give the variable names. If just the variable names are\n give (list/tuple/str) then the variable values looked up in the\n callers frame.\n interactive : bool\n If True (default), the variables will be listed with the ``who``\n magic.\n "
vdict = None
if isinstance(variables, dict):
vdict = variables
elif isinstance(variables, (str, list, tuple)):
if isinstance(variables, str):
vlist = variables.split()
else:
vlist = variables
vdict = {}
cf = sys._getframe(1)
for name in vlist:
try:
vdict[name] = eval(name, cf.f_globals, cf.f_locals)
except:
print(('Could not get variable %s from %s' % (name, cf.f_code.co_name)))
else:
raise ValueError('variables must be a dict/str/list/tuple')
self.user_ns.update(vdict)
user_ns_hidden = self.user_ns_hidden
if interactive:
for name in vdict:
user_ns_hidden.pop(name, None)
else:
user_ns_hidden.update(vdict)
|
def drop_by_id(self, variables):
"Remove a dict of variables from the user namespace, if they are the\n same as the values in the dictionary.\n\n This is intended for use by extensions: variables that they've added can\n be taken back out if they are unloaded, without removing any that the\n user has overwritten.\n\n Parameters\n ----------\n variables : dict\n A dictionary mapping object names (as strings) to the objects.\n "
for (name, obj) in variables.items():
if ((name in self.user_ns) and (self.user_ns[name] is obj)):
del self.user_ns[name]
self.user_ns_hidden.pop(name, None)
| -4,733,108,409,772,464,000
|
Remove a dict of variables from the user namespace, if they are the
same as the values in the dictionary.
This is intended for use by extensions: variables that they've added can
be taken back out if they are unloaded, without removing any that the
user has overwritten.
Parameters
----------
variables : dict
A dictionary mapping object names (as strings) to the objects.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
drop_by_id
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def drop_by_id(self, variables):
"Remove a dict of variables from the user namespace, if they are the\n same as the values in the dictionary.\n\n This is intended for use by extensions: variables that they've added can\n be taken back out if they are unloaded, without removing any that the\n user has overwritten.\n\n Parameters\n ----------\n variables : dict\n A dictionary mapping object names (as strings) to the objects.\n "
for (name, obj) in variables.items():
if ((name in self.user_ns) and (self.user_ns[name] is obj)):
del self.user_ns[name]
self.user_ns_hidden.pop(name, None)
|
def _ofind(self, oname, namespaces=None):
'Find an object in the available namespaces.\n\n self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic\n\n Has special code to detect magic functions.\n '
oname = oname.strip()
if ((not oname.startswith(ESC_MAGIC)) and (not oname.startswith(ESC_MAGIC2)) and (not all((a.isidentifier() for a in oname.split('.'))))):
return {'found': False}
if (namespaces is None):
namespaces = [('Interactive', self.user_ns), ('Interactive (global)', self.user_global_ns), ('Python builtin', builtin_mod.__dict__)]
ismagic = False
isalias = False
found = False
ospace = None
parent = None
obj = None
oname_parts = oname.split('.')
(oname_head, oname_rest) = (oname_parts[0], oname_parts[1:])
for (nsname, ns) in namespaces:
try:
obj = ns[oname_head]
except KeyError:
continue
else:
for (idx, part) in enumerate(oname_rest):
try:
parent = obj
if (idx == (len(oname_rest) - 1)):
obj = self._getattr_property(obj, part)
else:
obj = getattr(obj, part)
except:
break
else:
found = True
ospace = nsname
break
if (not found):
obj = None
if oname.startswith(ESC_MAGIC2):
oname = oname.lstrip(ESC_MAGIC2)
obj = self.find_cell_magic(oname)
elif oname.startswith(ESC_MAGIC):
oname = oname.lstrip(ESC_MAGIC)
obj = self.find_line_magic(oname)
else:
obj = self.find_line_magic(oname)
if (obj is None):
obj = self.find_cell_magic(oname)
if (obj is not None):
found = True
ospace = 'IPython internal'
ismagic = True
isalias = isinstance(obj, Alias)
if ((not found) and (oname_head in ["''", '""', '[]', '{}', '()'])):
obj = eval(oname_head)
found = True
ospace = 'Interactive'
return {'obj': obj, 'found': found, 'parent': parent, 'ismagic': ismagic, 'isalias': isalias, 'namespace': ospace}
| 2,287,905,833,163,156,000
|
Find an object in the available namespaces.
self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic
Has special code to detect magic functions.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_ofind
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _ofind(self, oname, namespaces=None):
'Find an object in the available namespaces.\n\n self._ofind(oname) -> dict with keys: found,obj,ospace,ismagic\n\n Has special code to detect magic functions.\n '
oname = oname.strip()
if ((not oname.startswith(ESC_MAGIC)) and (not oname.startswith(ESC_MAGIC2)) and (not all((a.isidentifier() for a in oname.split('.'))))):
return {'found': False}
if (namespaces is None):
namespaces = [('Interactive', self.user_ns), ('Interactive (global)', self.user_global_ns), ('Python builtin', builtin_mod.__dict__)]
ismagic = False
isalias = False
found = False
ospace = None
parent = None
obj = None
oname_parts = oname.split('.')
(oname_head, oname_rest) = (oname_parts[0], oname_parts[1:])
for (nsname, ns) in namespaces:
try:
obj = ns[oname_head]
except KeyError:
continue
else:
for (idx, part) in enumerate(oname_rest):
try:
parent = obj
if (idx == (len(oname_rest) - 1)):
obj = self._getattr_property(obj, part)
else:
obj = getattr(obj, part)
except:
break
else:
found = True
ospace = nsname
break
if (not found):
obj = None
if oname.startswith(ESC_MAGIC2):
oname = oname.lstrip(ESC_MAGIC2)
obj = self.find_cell_magic(oname)
elif oname.startswith(ESC_MAGIC):
oname = oname.lstrip(ESC_MAGIC)
obj = self.find_line_magic(oname)
else:
obj = self.find_line_magic(oname)
if (obj is None):
obj = self.find_cell_magic(oname)
if (obj is not None):
found = True
ospace = 'IPython internal'
ismagic = True
isalias = isinstance(obj, Alias)
if ((not found) and (oname_head in [, '', '[]', '{}', '()'])):
obj = eval(oname_head)
found = True
ospace = 'Interactive'
return {'obj': obj, 'found': found, 'parent': parent, 'ismagic': ismagic, 'isalias': isalias, 'namespace': ospace}
|
@staticmethod
def _getattr_property(obj, attrname):
'Property-aware getattr to use in object finding.\n\n If attrname represents a property, return it unevaluated (in case it has\n side effects or raises an error.\n\n '
if (not isinstance(obj, type)):
try:
attr = getattr(type(obj), attrname)
except AttributeError:
pass
else:
if isinstance(attr, property):
return attr
return getattr(obj, attrname)
| 2,330,575,836,765,874,700
|
Property-aware getattr to use in object finding.
If attrname represents a property, return it unevaluated (in case it has
side effects or raises an error.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_getattr_property
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
@staticmethod
def _getattr_property(obj, attrname):
'Property-aware getattr to use in object finding.\n\n If attrname represents a property, return it unevaluated (in case it has\n side effects or raises an error.\n\n '
if (not isinstance(obj, type)):
try:
attr = getattr(type(obj), attrname)
except AttributeError:
pass
else:
if isinstance(attr, property):
return attr
return getattr(obj, attrname)
|
def _object_find(self, oname, namespaces=None):
'Find an object and return a struct with info about it.'
return Struct(self._ofind(oname, namespaces))
| 4,210,069,206,462,534,700
|
Find an object and return a struct with info about it.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_object_find
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _object_find(self, oname, namespaces=None):
return Struct(self._ofind(oname, namespaces))
|
def _inspect(self, meth, oname, namespaces=None, **kw):
'Generic interface to the inspector system.\n\n This function is meant to be called by pdef, pdoc & friends.\n '
info = self._object_find(oname, namespaces)
docformat = (sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None)
if info.found:
pmethod = getattr(self.inspector, meth)
formatter = (format_screen if info.ismagic else docformat)
if (meth == 'pdoc'):
pmethod(info.obj, oname, formatter)
elif (meth == 'pinfo'):
pmethod(info.obj, oname, formatter, info, enable_html_pager=self.enable_html_pager, **kw)
else:
pmethod(info.obj, oname)
else:
print(('Object `%s` not found.' % oname))
return 'not found'
| -3,827,416,137,922,348,500
|
Generic interface to the inspector system.
This function is meant to be called by pdef, pdoc & friends.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_inspect
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _inspect(self, meth, oname, namespaces=None, **kw):
'Generic interface to the inspector system.\n\n This function is meant to be called by pdef, pdoc & friends.\n '
info = self._object_find(oname, namespaces)
docformat = (sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None)
if info.found:
pmethod = getattr(self.inspector, meth)
formatter = (format_screen if info.ismagic else docformat)
if (meth == 'pdoc'):
pmethod(info.obj, oname, formatter)
elif (meth == 'pinfo'):
pmethod(info.obj, oname, formatter, info, enable_html_pager=self.enable_html_pager, **kw)
else:
pmethod(info.obj, oname)
else:
print(('Object `%s` not found.' % oname))
return 'not found'
|
def object_inspect(self, oname, detail_level=0):
'Get object info about oname'
with self.builtin_trap:
info = self._object_find(oname)
if info.found:
return self.inspector.info(info.obj, oname, info=info, detail_level=detail_level)
else:
return oinspect.object_info(name=oname, found=False)
| 2,894,528,283,749,319,000
|
Get object info about oname
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
object_inspect
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def object_inspect(self, oname, detail_level=0):
with self.builtin_trap:
info = self._object_find(oname)
if info.found:
return self.inspector.info(info.obj, oname, info=info, detail_level=detail_level)
else:
return oinspect.object_info(name=oname, found=False)
|
def object_inspect_text(self, oname, detail_level=0):
'Get object info as formatted text'
return self.object_inspect_mime(oname, detail_level)['text/plain']
| 1,974,518,146,682,276,600
|
Get object info as formatted text
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
object_inspect_text
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def object_inspect_text(self, oname, detail_level=0):
return self.object_inspect_mime(oname, detail_level)['text/plain']
|
def object_inspect_mime(self, oname, detail_level=0, omit_sections=()):
"Get object info as a mimebundle of formatted representations.\n\n A mimebundle is a dictionary, keyed by mime-type.\n It must always have the key `'text/plain'`.\n "
with self.builtin_trap:
info = self._object_find(oname)
if info.found:
docformat = (sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None)
return self.inspector._get_info(info.obj, oname, info=info, detail_level=detail_level, formatter=docformat, omit_sections=omit_sections)
else:
raise KeyError(oname)
| 82,545,009,748,315,410
|
Get object info as a mimebundle of formatted representations.
A mimebundle is a dictionary, keyed by mime-type.
It must always have the key `'text/plain'`.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
object_inspect_mime
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def object_inspect_mime(self, oname, detail_level=0, omit_sections=()):
"Get object info as a mimebundle of formatted representations.\n\n A mimebundle is a dictionary, keyed by mime-type.\n It must always have the key `'text/plain'`.\n "
with self.builtin_trap:
info = self._object_find(oname)
if info.found:
docformat = (sphinxify(self.object_inspect(oname)) if self.sphinxify_docstring else None)
return self.inspector._get_info(info.obj, oname, info=info, detail_level=detail_level, formatter=docformat, omit_sections=omit_sections)
else:
raise KeyError(oname)
|
def init_history(self):
'Sets up the command history, and starts regular autosaves.'
self.history_manager = HistoryManager(shell=self, parent=self)
self.configurables.append(self.history_manager)
| -4,752,207,031,469,613,000
|
Sets up the command history, and starts regular autosaves.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
init_history
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def init_history(self):
self.history_manager = HistoryManager(shell=self, parent=self)
self.configurables.append(self.history_manager)
|
def set_custom_exc(self, exc_tuple, handler):
"set_custom_exc(exc_tuple, handler)\n\n Set a custom exception handler, which will be called if any of the\n exceptions in exc_tuple occur in the mainloop (specifically, in the\n run_code() method).\n\n Parameters\n ----------\n exc_tuple : tuple of exception classes\n A *tuple* of exception classes, for which to call the defined\n handler. It is very important that you use a tuple, and NOT A\n LIST here, because of the way Python's except statement works. If\n you only want to trap a single exception, use a singleton tuple::\n\n exc_tuple == (MyCustomException,)\n\n handler : callable\n handler must have the following signature::\n\n def my_handler(self, etype, value, tb, tb_offset=None):\n ...\n return structured_traceback\n\n Your handler must return a structured traceback (a list of strings),\n or None.\n\n This will be made into an instance method (via types.MethodType)\n of IPython itself, and it will be called if any of the exceptions\n listed in the exc_tuple are caught. If the handler is None, an\n internal basic one is used, which just prints basic info.\n\n To protect IPython from crashes, if your handler ever raises an\n exception or returns an invalid result, it will be immediately\n disabled.\n\n Notes\n -----\n WARNING: by putting in your own exception handler into IPython's main\n execution loop, you run a very good chance of nasty crashes. This\n facility should only be used if you really know what you are doing.\n "
if (not isinstance(exc_tuple, tuple)):
raise TypeError('The custom exceptions must be given as a tuple.')
def dummy_handler(self, etype, value, tb, tb_offset=None):
print('*** Simple custom exception handler ***')
print('Exception type :', etype)
print('Exception value:', value)
print('Traceback :', tb)
def validate_stb(stb):
'validate structured traceback return type\n\n return type of CustomTB *should* be a list of strings, but allow\n single strings or None, which are harmless.\n\n This function will *always* return a list of strings,\n and will raise a TypeError if stb is inappropriate.\n '
msg = ('CustomTB must return list of strings, not %r' % stb)
if (stb is None):
return []
elif isinstance(stb, str):
return [stb]
elif (not isinstance(stb, list)):
raise TypeError(msg)
for line in stb:
if (not isinstance(line, str)):
raise TypeError(msg)
return stb
if (handler is None):
wrapped = dummy_handler
else:
def wrapped(self, etype, value, tb, tb_offset=None):
'wrap CustomTB handler, to protect IPython from user code\n\n This makes it harder (but not impossible) for custom exception\n handlers to crash IPython.\n '
try:
stb = handler(self, etype, value, tb, tb_offset=tb_offset)
return validate_stb(stb)
except:
self.set_custom_exc((), None)
print('Custom TB Handler failed, unregistering', file=sys.stderr)
stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
print(self.InteractiveTB.stb2text(stb))
print('The original exception:')
stb = self.InteractiveTB.structured_traceback((etype, value, tb), tb_offset=tb_offset)
return stb
self.CustomTB = types.MethodType(wrapped, self)
self.custom_exceptions = exc_tuple
| 1,156,029,581,014,879,000
|
set_custom_exc(exc_tuple, handler)
Set a custom exception handler, which will be called if any of the
exceptions in exc_tuple occur in the mainloop (specifically, in the
run_code() method).
Parameters
----------
exc_tuple : tuple of exception classes
A *tuple* of exception classes, for which to call the defined
handler. It is very important that you use a tuple, and NOT A
LIST here, because of the way Python's except statement works. If
you only want to trap a single exception, use a singleton tuple::
exc_tuple == (MyCustomException,)
handler : callable
handler must have the following signature::
def my_handler(self, etype, value, tb, tb_offset=None):
...
return structured_traceback
Your handler must return a structured traceback (a list of strings),
or None.
This will be made into an instance method (via types.MethodType)
of IPython itself, and it will be called if any of the exceptions
listed in the exc_tuple are caught. If the handler is None, an
internal basic one is used, which just prints basic info.
To protect IPython from crashes, if your handler ever raises an
exception or returns an invalid result, it will be immediately
disabled.
Notes
-----
WARNING: by putting in your own exception handler into IPython's main
execution loop, you run a very good chance of nasty crashes. This
facility should only be used if you really know what you are doing.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
set_custom_exc
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def set_custom_exc(self, exc_tuple, handler):
"set_custom_exc(exc_tuple, handler)\n\n Set a custom exception handler, which will be called if any of the\n exceptions in exc_tuple occur in the mainloop (specifically, in the\n run_code() method).\n\n Parameters\n ----------\n exc_tuple : tuple of exception classes\n A *tuple* of exception classes, for which to call the defined\n handler. It is very important that you use a tuple, and NOT A\n LIST here, because of the way Python's except statement works. If\n you only want to trap a single exception, use a singleton tuple::\n\n exc_tuple == (MyCustomException,)\n\n handler : callable\n handler must have the following signature::\n\n def my_handler(self, etype, value, tb, tb_offset=None):\n ...\n return structured_traceback\n\n Your handler must return a structured traceback (a list of strings),\n or None.\n\n This will be made into an instance method (via types.MethodType)\n of IPython itself, and it will be called if any of the exceptions\n listed in the exc_tuple are caught. If the handler is None, an\n internal basic one is used, which just prints basic info.\n\n To protect IPython from crashes, if your handler ever raises an\n exception or returns an invalid result, it will be immediately\n disabled.\n\n Notes\n -----\n WARNING: by putting in your own exception handler into IPython's main\n execution loop, you run a very good chance of nasty crashes. This\n facility should only be used if you really know what you are doing.\n "
if (not isinstance(exc_tuple, tuple)):
raise TypeError('The custom exceptions must be given as a tuple.')
def dummy_handler(self, etype, value, tb, tb_offset=None):
print('*** Simple custom exception handler ***')
print('Exception type :', etype)
print('Exception value:', value)
print('Traceback :', tb)
def validate_stb(stb):
'validate structured traceback return type\n\n return type of CustomTB *should* be a list of strings, but allow\n single strings or None, which are harmless.\n\n This function will *always* return a list of strings,\n and will raise a TypeError if stb is inappropriate.\n '
msg = ('CustomTB must return list of strings, not %r' % stb)
if (stb is None):
return []
elif isinstance(stb, str):
return [stb]
elif (not isinstance(stb, list)):
raise TypeError(msg)
for line in stb:
if (not isinstance(line, str)):
raise TypeError(msg)
return stb
if (handler is None):
wrapped = dummy_handler
else:
def wrapped(self, etype, value, tb, tb_offset=None):
'wrap CustomTB handler, to protect IPython from user code\n\n This makes it harder (but not impossible) for custom exception\n handlers to crash IPython.\n '
try:
stb = handler(self, etype, value, tb, tb_offset=tb_offset)
return validate_stb(stb)
except:
self.set_custom_exc((), None)
print('Custom TB Handler failed, unregistering', file=sys.stderr)
stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
print(self.InteractiveTB.stb2text(stb))
print('The original exception:')
stb = self.InteractiveTB.structured_traceback((etype, value, tb), tb_offset=tb_offset)
return stb
self.CustomTB = types.MethodType(wrapped, self)
self.custom_exceptions = exc_tuple
|
def excepthook(self, etype, value, tb):
'One more defense for GUI apps that call sys.excepthook.\n\n GUI frameworks like wxPython trap exceptions and call\n sys.excepthook themselves. I guess this is a feature that\n enables them to keep running after exceptions that would\n otherwise kill their mainloop. This is a bother for IPython\n which expects to catch all of the program exceptions with a try:\n except: statement.\n\n Normally, IPython sets sys.excepthook to a CrashHandler instance, so if\n any app directly invokes sys.excepthook, it will look to the user like\n IPython crashed. In order to work around this, we can disable the\n CrashHandler and replace it with this excepthook instead, which prints a\n regular traceback using our InteractiveTB. In this fashion, apps which\n call sys.excepthook will generate a regular-looking exception from\n IPython, and the CrashHandler will only be triggered by real IPython\n crashes.\n\n This hook should be used sparingly, only in places which are not likely\n to be true IPython errors.\n '
self.showtraceback((etype, value, tb), tb_offset=0)
| -2,784,476,946,396,066,300
|
One more defense for GUI apps that call sys.excepthook.
GUI frameworks like wxPython trap exceptions and call
sys.excepthook themselves. I guess this is a feature that
enables them to keep running after exceptions that would
otherwise kill their mainloop. This is a bother for IPython
which expects to catch all of the program exceptions with a try:
except: statement.
Normally, IPython sets sys.excepthook to a CrashHandler instance, so if
any app directly invokes sys.excepthook, it will look to the user like
IPython crashed. In order to work around this, we can disable the
CrashHandler and replace it with this excepthook instead, which prints a
regular traceback using our InteractiveTB. In this fashion, apps which
call sys.excepthook will generate a regular-looking exception from
IPython, and the CrashHandler will only be triggered by real IPython
crashes.
This hook should be used sparingly, only in places which are not likely
to be true IPython errors.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
excepthook
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def excepthook(self, etype, value, tb):
'One more defense for GUI apps that call sys.excepthook.\n\n GUI frameworks like wxPython trap exceptions and call\n sys.excepthook themselves. I guess this is a feature that\n enables them to keep running after exceptions that would\n otherwise kill their mainloop. This is a bother for IPython\n which expects to catch all of the program exceptions with a try:\n except: statement.\n\n Normally, IPython sets sys.excepthook to a CrashHandler instance, so if\n any app directly invokes sys.excepthook, it will look to the user like\n IPython crashed. In order to work around this, we can disable the\n CrashHandler and replace it with this excepthook instead, which prints a\n regular traceback using our InteractiveTB. In this fashion, apps which\n call sys.excepthook will generate a regular-looking exception from\n IPython, and the CrashHandler will only be triggered by real IPython\n crashes.\n\n This hook should be used sparingly, only in places which are not likely\n to be true IPython errors.\n '
self.showtraceback((etype, value, tb), tb_offset=0)
|
def _get_exc_info(self, exc_tuple=None):
'get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.\n\n Ensures sys.last_type,value,traceback hold the exc_info we found,\n from whichever source.\n\n raises ValueError if none of these contain any information\n '
if (exc_tuple is None):
(etype, value, tb) = sys.exc_info()
else:
(etype, value, tb) = exc_tuple
if (etype is None):
if hasattr(sys, 'last_type'):
(etype, value, tb) = (sys.last_type, sys.last_value, sys.last_traceback)
if (etype is None):
raise ValueError('No exception to find')
sys.last_type = etype
sys.last_value = value
sys.last_traceback = tb
return (etype, value, tb)
| -1,581,550,018,166,260,500
|
get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.
Ensures sys.last_type,value,traceback hold the exc_info we found,
from whichever source.
raises ValueError if none of these contain any information
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_get_exc_info
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _get_exc_info(self, exc_tuple=None):
'get exc_info from a given tuple, sys.exc_info() or sys.last_type etc.\n\n Ensures sys.last_type,value,traceback hold the exc_info we found,\n from whichever source.\n\n raises ValueError if none of these contain any information\n '
if (exc_tuple is None):
(etype, value, tb) = sys.exc_info()
else:
(etype, value, tb) = exc_tuple
if (etype is None):
if hasattr(sys, 'last_type'):
(etype, value, tb) = (sys.last_type, sys.last_value, sys.last_traceback)
if (etype is None):
raise ValueError('No exception to find')
sys.last_type = etype
sys.last_value = value
sys.last_traceback = tb
return (etype, value, tb)
|
def show_usage_error(self, exc):
"Show a short message for UsageErrors\n\n These are special exceptions that shouldn't show a traceback.\n "
print(('UsageError: %s' % exc), file=sys.stderr)
| -1,353,149,073,228,894,000
|
Show a short message for UsageErrors
These are special exceptions that shouldn't show a traceback.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
show_usage_error
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def show_usage_error(self, exc):
"Show a short message for UsageErrors\n\n These are special exceptions that shouldn't show a traceback.\n "
print(('UsageError: %s' % exc), file=sys.stderr)
|
def get_exception_only(self, exc_tuple=None):
'\n Return as a string (ending with a newline) the exception that\n just occurred, without any traceback.\n '
(etype, value, tb) = self._get_exc_info(exc_tuple)
msg = traceback.format_exception_only(etype, value)
return ''.join(msg)
| 8,831,226,790,187,812,000
|
Return as a string (ending with a newline) the exception that
just occurred, without any traceback.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
get_exception_only
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def get_exception_only(self, exc_tuple=None):
'\n Return as a string (ending with a newline) the exception that\n just occurred, without any traceback.\n '
(etype, value, tb) = self._get_exc_info(exc_tuple)
msg = traceback.format_exception_only(etype, value)
return .join(msg)
|
def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, exception_only=False, running_compiled_code=False):
"Display the exception that just occurred.\n\n If nothing is known about the exception, this is the method which\n should be used throughout the code for presenting user tracebacks,\n rather than directly invoking the InteractiveTB object.\n\n A specific showsyntaxerror() also exists, but this method can take\n care of calling it if needed, so unless you are explicitly catching a\n SyntaxError exception, don't try to analyze the stack manually and\n simply call this method."
try:
try:
(etype, value, tb) = self._get_exc_info(exc_tuple)
except ValueError:
print('No traceback available to show.', file=sys.stderr)
return
if issubclass(etype, SyntaxError):
self.showsyntaxerror(filename, running_compiled_code)
elif (etype is UsageError):
self.show_usage_error(value)
else:
if exception_only:
stb = ['An exception has occurred, use %tb to see the full traceback.\n']
stb.extend(self.InteractiveTB.get_exception_only(etype, value))
else:
try:
if hasattr(value, '_render_traceback_'):
stb = value._render_traceback_()
else:
stb = self.InteractiveTB.structured_traceback(etype, value, tb, tb_offset=tb_offset)
except Exception:
print('Unexpected exception formatting exception. Falling back to standard exception')
traceback.print_exc()
return None
self._showtraceback(etype, value, stb)
if self.call_pdb:
self.debugger(force=True)
return
self._showtraceback(etype, value, stb)
except KeyboardInterrupt:
print(('\n' + self.get_exception_only()), file=sys.stderr)
| 6,559,754,494,067,826,000
|
Display the exception that just occurred.
If nothing is known about the exception, this is the method which
should be used throughout the code for presenting user tracebacks,
rather than directly invoking the InteractiveTB object.
A specific showsyntaxerror() also exists, but this method can take
care of calling it if needed, so unless you are explicitly catching a
SyntaxError exception, don't try to analyze the stack manually and
simply call this method.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
showtraceback
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def showtraceback(self, exc_tuple=None, filename=None, tb_offset=None, exception_only=False, running_compiled_code=False):
"Display the exception that just occurred.\n\n If nothing is known about the exception, this is the method which\n should be used throughout the code for presenting user tracebacks,\n rather than directly invoking the InteractiveTB object.\n\n A specific showsyntaxerror() also exists, but this method can take\n care of calling it if needed, so unless you are explicitly catching a\n SyntaxError exception, don't try to analyze the stack manually and\n simply call this method."
try:
try:
(etype, value, tb) = self._get_exc_info(exc_tuple)
except ValueError:
print('No traceback available to show.', file=sys.stderr)
return
if issubclass(etype, SyntaxError):
self.showsyntaxerror(filename, running_compiled_code)
elif (etype is UsageError):
self.show_usage_error(value)
else:
if exception_only:
stb = ['An exception has occurred, use %tb to see the full traceback.\n']
stb.extend(self.InteractiveTB.get_exception_only(etype, value))
else:
try:
if hasattr(value, '_render_traceback_'):
stb = value._render_traceback_()
else:
stb = self.InteractiveTB.structured_traceback(etype, value, tb, tb_offset=tb_offset)
except Exception:
print('Unexpected exception formatting exception. Falling back to standard exception')
traceback.print_exc()
return None
self._showtraceback(etype, value, stb)
if self.call_pdb:
self.debugger(force=True)
return
self._showtraceback(etype, value, stb)
except KeyboardInterrupt:
print(('\n' + self.get_exception_only()), file=sys.stderr)
|
def _showtraceback(self, etype, evalue, stb: str):
'Actually show a traceback.\n\n Subclasses may override this method to put the traceback on a different\n place, like a side channel.\n '
val = self.InteractiveTB.stb2text(stb)
try:
print(val)
except UnicodeEncodeError:
print(val.encode('utf-8', 'backslashreplace').decode())
| 7,881,107,553,504,608,000
|
Actually show a traceback.
Subclasses may override this method to put the traceback on a different
place, like a side channel.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_showtraceback
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _showtraceback(self, etype, evalue, stb: str):
'Actually show a traceback.\n\n Subclasses may override this method to put the traceback on a different\n place, like a side channel.\n '
val = self.InteractiveTB.stb2text(stb)
try:
print(val)
except UnicodeEncodeError:
print(val.encode('utf-8', 'backslashreplace').decode())
|
def showsyntaxerror(self, filename=None, running_compiled_code=False):
'Display the syntax error that just occurred.\n\n This doesn\'t display a stack trace because there isn\'t one.\n\n If a filename is given, it is stuffed in the exception instead\n of what was there before (because Python\'s parser always uses\n "<string>" when reading from a string).\n\n If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),\n longer stack trace will be displayed.\n '
(etype, value, last_traceback) = self._get_exc_info()
if (filename and issubclass(etype, SyntaxError)):
try:
value.filename = filename
except:
pass
elist = (traceback.extract_tb(last_traceback) if running_compiled_code else [])
stb = self.SyntaxTB.structured_traceback(etype, value, elist)
self._showtraceback(etype, value, stb)
| -400,972,847,223,385,660
|
Display the syntax error that just occurred.
This doesn't display a stack trace because there isn't one.
If a filename is given, it is stuffed in the exception instead
of what was there before (because Python's parser always uses
"<string>" when reading from a string).
If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),
longer stack trace will be displayed.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
showsyntaxerror
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def showsyntaxerror(self, filename=None, running_compiled_code=False):
'Display the syntax error that just occurred.\n\n This doesn\'t display a stack trace because there isn\'t one.\n\n If a filename is given, it is stuffed in the exception instead\n of what was there before (because Python\'s parser always uses\n "<string>" when reading from a string).\n\n If the syntax error occurred when running a compiled code (i.e. running_compile_code=True),\n longer stack trace will be displayed.\n '
(etype, value, last_traceback) = self._get_exc_info()
if (filename and issubclass(etype, SyntaxError)):
try:
value.filename = filename
except:
pass
elist = (traceback.extract_tb(last_traceback) if running_compiled_code else [])
stb = self.SyntaxTB.structured_traceback(etype, value, elist)
self._showtraceback(etype, value, stb)
|
def showindentationerror(self):
"Called by _run_cell when there's an IndentationError in code entered\n at the prompt.\n\n This is overridden in TerminalInteractiveShell to show a message about\n the %paste magic."
self.showsyntaxerror()
| -2,445,171,455,265,809,000
|
Called by _run_cell when there's an IndentationError in code entered
at the prompt.
This is overridden in TerminalInteractiveShell to show a message about
the %paste magic.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
showindentationerror
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def showindentationerror(self):
"Called by _run_cell when there's an IndentationError in code entered\n at the prompt.\n\n This is overridden in TerminalInteractiveShell to show a message about\n the %paste magic."
self.showsyntaxerror()
|
@skip_doctest
def set_next_input(self, s, replace=False):
' Sets the \'default\' input string for the next command line.\n\n Example::\n\n In [1]: _ip.set_next_input("Hello Word")\n In [2]: Hello Word_ # cursor is here\n '
self.rl_next_input = s
| -5,104,023,393,772,409,000
|
Sets the 'default' input string for the next command line.
Example::
In [1]: _ip.set_next_input("Hello Word")
In [2]: Hello Word_ # cursor is here
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
set_next_input
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
@skip_doctest
def set_next_input(self, s, replace=False):
' Sets the \'default\' input string for the next command line.\n\n Example::\n\n In [1]: _ip.set_next_input("Hello Word")\n In [2]: Hello Word_ # cursor is here\n '
self.rl_next_input = s
|
def _indent_current_str(self):
'return the current level of indentation as a string'
return (self.input_splitter.get_indent_spaces() * ' ')
| -2,322,617,927,592,505,300
|
return the current level of indentation as a string
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_indent_current_str
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _indent_current_str(self):
return (self.input_splitter.get_indent_spaces() * ' ')
|
def init_completer(self):
'Initialize the completion machinery.\n\n This creates completion machinery that can be used by client code,\n either interactively in-process (typically triggered by the readline\n library), programmatically (such as in test suites) or out-of-process\n (typically over the network by remote frontends).\n '
from IPython.core.completer import IPCompleter
from IPython.core.completerlib import cd_completer, magic_run_completer, module_completer, reset_completer
self.Completer = IPCompleter(shell=self, namespace=self.user_ns, global_namespace=self.user_global_ns, parent=self)
self.configurables.append(self.Completer)
sdisp = self.strdispatchers.get('complete_command', StrDispatch())
self.strdispatchers['complete_command'] = sdisp
self.Completer.custom_completers = sdisp
self.set_hook('complete_command', module_completer, str_key='import')
self.set_hook('complete_command', module_completer, str_key='from')
self.set_hook('complete_command', module_completer, str_key='%aimport')
self.set_hook('complete_command', magic_run_completer, str_key='%run')
self.set_hook('complete_command', cd_completer, str_key='%cd')
self.set_hook('complete_command', reset_completer, str_key='%reset')
| -7,401,544,314,293,828,000
|
Initialize the completion machinery.
This creates completion machinery that can be used by client code,
either interactively in-process (typically triggered by the readline
library), programmatically (such as in test suites) or out-of-process
(typically over the network by remote frontends).
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
init_completer
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def init_completer(self):
'Initialize the completion machinery.\n\n This creates completion machinery that can be used by client code,\n either interactively in-process (typically triggered by the readline\n library), programmatically (such as in test suites) or out-of-process\n (typically over the network by remote frontends).\n '
from IPython.core.completer import IPCompleter
from IPython.core.completerlib import cd_completer, magic_run_completer, module_completer, reset_completer
self.Completer = IPCompleter(shell=self, namespace=self.user_ns, global_namespace=self.user_global_ns, parent=self)
self.configurables.append(self.Completer)
sdisp = self.strdispatchers.get('complete_command', StrDispatch())
self.strdispatchers['complete_command'] = sdisp
self.Completer.custom_completers = sdisp
self.set_hook('complete_command', module_completer, str_key='import')
self.set_hook('complete_command', module_completer, str_key='from')
self.set_hook('complete_command', module_completer, str_key='%aimport')
self.set_hook('complete_command', magic_run_completer, str_key='%run')
self.set_hook('complete_command', cd_completer, str_key='%cd')
self.set_hook('complete_command', reset_completer, str_key='%reset')
|
@skip_doctest
def complete(self, text, line=None, cursor_pos=None):
"Return the completed text and a list of completions.\n\n Parameters\n ----------\n text : string\n A string of text to be completed on. It can be given as empty and\n instead a line/position pair are given. In this case, the\n completer itself will split the line like readline does.\n line : string, optional\n The complete line that text is part of.\n cursor_pos : int, optional\n The position of the cursor on the input line.\n\n Returns\n -------\n text : string\n The actual text that was completed.\n matches : list\n A sorted list with all possible completions.\n\n Notes\n -----\n The optional arguments allow the completion to take more context into\n account, and are part of the low-level completion API.\n\n This is a wrapper around the completion mechanism, similar to what\n readline does at the command line when the TAB key is hit. By\n exposing it as a method, it can be used by other non-readline\n environments (such as GUIs) for text completion.\n\n Examples\n --------\n In [1]: x = 'hello'\n\n In [2]: _ip.complete('x.l')\n Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])\n "
with self.builtin_trap:
return self.Completer.complete(text, line, cursor_pos)
| 7,560,008,023,491,622,000
|
Return the completed text and a list of completions.
Parameters
----------
text : string
A string of text to be completed on. It can be given as empty and
instead a line/position pair are given. In this case, the
completer itself will split the line like readline does.
line : string, optional
The complete line that text is part of.
cursor_pos : int, optional
The position of the cursor on the input line.
Returns
-------
text : string
The actual text that was completed.
matches : list
A sorted list with all possible completions.
Notes
-----
The optional arguments allow the completion to take more context into
account, and are part of the low-level completion API.
This is a wrapper around the completion mechanism, similar to what
readline does at the command line when the TAB key is hit. By
exposing it as a method, it can be used by other non-readline
environments (such as GUIs) for text completion.
Examples
--------
In [1]: x = 'hello'
In [2]: _ip.complete('x.l')
Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
complete
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
@skip_doctest
def complete(self, text, line=None, cursor_pos=None):
"Return the completed text and a list of completions.\n\n Parameters\n ----------\n text : string\n A string of text to be completed on. It can be given as empty and\n instead a line/position pair are given. In this case, the\n completer itself will split the line like readline does.\n line : string, optional\n The complete line that text is part of.\n cursor_pos : int, optional\n The position of the cursor on the input line.\n\n Returns\n -------\n text : string\n The actual text that was completed.\n matches : list\n A sorted list with all possible completions.\n\n Notes\n -----\n The optional arguments allow the completion to take more context into\n account, and are part of the low-level completion API.\n\n This is a wrapper around the completion mechanism, similar to what\n readline does at the command line when the TAB key is hit. By\n exposing it as a method, it can be used by other non-readline\n environments (such as GUIs) for text completion.\n\n Examples\n --------\n In [1]: x = 'hello'\n\n In [2]: _ip.complete('x.l')\n Out[2]: ('x.l', ['x.ljust', 'x.lower', 'x.lstrip'])\n "
with self.builtin_trap:
return self.Completer.complete(text, line, cursor_pos)
|
def set_custom_completer(self, completer, pos=0) -> None:
'Adds a new custom completer function.\n\n The position argument (defaults to 0) is the index in the completers\n list where you want the completer to be inserted.\n\n `completer` should have the following signature::\n\n def completion(self: Completer, text: string) -> List[str]:\n raise NotImplementedError\n\n It will be bound to the current Completer instance and pass some text\n and return a list with current completions to suggest to the user.\n '
newcomp = types.MethodType(completer, self.Completer)
self.Completer.custom_matchers.insert(pos, newcomp)
| 1,712,199,540,969,657,000
|
Adds a new custom completer function.
The position argument (defaults to 0) is the index in the completers
list where you want the completer to be inserted.
`completer` should have the following signature::
def completion(self: Completer, text: string) -> List[str]:
raise NotImplementedError
It will be bound to the current Completer instance and pass some text
and return a list with current completions to suggest to the user.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
set_custom_completer
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def set_custom_completer(self, completer, pos=0) -> None:
'Adds a new custom completer function.\n\n The position argument (defaults to 0) is the index in the completers\n list where you want the completer to be inserted.\n\n `completer` should have the following signature::\n\n def completion(self: Completer, text: string) -> List[str]:\n raise NotImplementedError\n\n It will be bound to the current Completer instance and pass some text\n and return a list with current completions to suggest to the user.\n '
newcomp = types.MethodType(completer, self.Completer)
self.Completer.custom_matchers.insert(pos, newcomp)
|
def set_completer_frame(self, frame=None):
'Set the frame of the completer.'
if frame:
self.Completer.namespace = frame.f_locals
self.Completer.global_namespace = frame.f_globals
else:
self.Completer.namespace = self.user_ns
self.Completer.global_namespace = self.user_global_ns
| 8,642,129,015,974,338,000
|
Set the frame of the completer.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
set_completer_frame
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def set_completer_frame(self, frame=None):
if frame:
self.Completer.namespace = frame.f_locals
self.Completer.global_namespace = frame.f_globals
else:
self.Completer.namespace = self.user_ns
self.Completer.global_namespace = self.user_global_ns
|
def _find_with_lazy_load(self, /, type_, magic_name: str):
'\n Try to find a magic potentially lazy-loading it.\n\n Parameters\n ----------\n\n type_: "line"|"cell"\n the type of magics we are trying to find/lazy load.\n magic_name: str\n The name of the magic we are trying to find/lazy load\n\n\n Note that this may have any side effects\n '
finder = {'line': self.find_line_magic, 'cell': self.find_cell_magic}[type_]
fn = finder(magic_name)
if (fn is not None):
return fn
lazy = self.magics_manager.lazy_magics.get(magic_name)
if (lazy is None):
return None
self.run_line_magic('load_ext', lazy)
res = finder(magic_name)
return res
| 8,904,485,724,808,844,000
|
Try to find a magic potentially lazy-loading it.
Parameters
----------
type_: "line"|"cell"
the type of magics we are trying to find/lazy load.
magic_name: str
The name of the magic we are trying to find/lazy load
Note that this may have any side effects
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_find_with_lazy_load
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _find_with_lazy_load(self, /, type_, magic_name: str):
'\n Try to find a magic potentially lazy-loading it.\n\n Parameters\n ----------\n\n type_: "line"|"cell"\n the type of magics we are trying to find/lazy load.\n magic_name: str\n The name of the magic we are trying to find/lazy load\n\n\n Note that this may have any side effects\n '
finder = {'line': self.find_line_magic, 'cell': self.find_cell_magic}[type_]
fn = finder(magic_name)
if (fn is not None):
return fn
lazy = self.magics_manager.lazy_magics.get(magic_name)
if (lazy is None):
return None
self.run_line_magic('load_ext', lazy)
res = finder(magic_name)
return res
|
def run_line_magic(self, magic_name: str, line, _stack_depth=1):
"Execute the given line magic.\n\n Parameters\n ----------\n magic_name : str\n Name of the desired magic function, without '%' prefix.\n line : str\n The rest of the input line as a single string.\n _stack_depth : int\n If run_line_magic() is called from magic() then _stack_depth=2.\n This is added to ensure backward compatibility for use of 'get_ipython().magic()'\n "
fn = self._find_with_lazy_load('line', magic_name)
if (fn is None):
lazy = self.magics_manager.lazy_magics.get(magic_name)
if lazy:
self.run_line_magic('load_ext', lazy)
fn = self.find_line_magic(magic_name)
if (fn is None):
cm = self.find_cell_magic(magic_name)
etpl = 'Line magic function `%%%s` not found%s.'
extra = ('' if (cm is None) else (' (But cell magic `%%%%%s` exists, did you mean that instead?)' % magic_name))
raise UsageError((etpl % (magic_name, extra)))
else:
stack_depth = _stack_depth
if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
magic_arg_s = line
else:
magic_arg_s = self.var_expand(line, stack_depth)
args = [magic_arg_s]
kwargs = {}
if getattr(fn, 'needs_local_scope', False):
kwargs['local_ns'] = self.get_local_scope(stack_depth)
with self.builtin_trap:
result = fn(*args, **kwargs)
return result
| -1,421,345,955,084,087,300
|
Execute the given line magic.
Parameters
----------
magic_name : str
Name of the desired magic function, without '%' prefix.
line : str
The rest of the input line as a single string.
_stack_depth : int
If run_line_magic() is called from magic() then _stack_depth=2.
This is added to ensure backward compatibility for use of 'get_ipython().magic()'
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
run_line_magic
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def run_line_magic(self, magic_name: str, line, _stack_depth=1):
"Execute the given line magic.\n\n Parameters\n ----------\n magic_name : str\n Name of the desired magic function, without '%' prefix.\n line : str\n The rest of the input line as a single string.\n _stack_depth : int\n If run_line_magic() is called from magic() then _stack_depth=2.\n This is added to ensure backward compatibility for use of 'get_ipython().magic()'\n "
fn = self._find_with_lazy_load('line', magic_name)
if (fn is None):
lazy = self.magics_manager.lazy_magics.get(magic_name)
if lazy:
self.run_line_magic('load_ext', lazy)
fn = self.find_line_magic(magic_name)
if (fn is None):
cm = self.find_cell_magic(magic_name)
etpl = 'Line magic function `%%%s` not found%s.'
extra = ( if (cm is None) else (' (But cell magic `%%%%%s` exists, did you mean that instead?)' % magic_name))
raise UsageError((etpl % (magic_name, extra)))
else:
stack_depth = _stack_depth
if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
magic_arg_s = line
else:
magic_arg_s = self.var_expand(line, stack_depth)
args = [magic_arg_s]
kwargs = {}
if getattr(fn, 'needs_local_scope', False):
kwargs['local_ns'] = self.get_local_scope(stack_depth)
with self.builtin_trap:
result = fn(*args, **kwargs)
return result
|
def get_local_scope(self, stack_depth):
'Get local scope at given stack depth.\n\n Parameters\n ----------\n stack_depth : int\n Depth relative to calling frame\n '
return sys._getframe((stack_depth + 1)).f_locals
| -7,622,405,648,547,966,000
|
Get local scope at given stack depth.
Parameters
----------
stack_depth : int
Depth relative to calling frame
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
get_local_scope
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def get_local_scope(self, stack_depth):
'Get local scope at given stack depth.\n\n Parameters\n ----------\n stack_depth : int\n Depth relative to calling frame\n '
return sys._getframe((stack_depth + 1)).f_locals
|
def run_cell_magic(self, magic_name, line, cell):
"Execute the given cell magic.\n\n Parameters\n ----------\n magic_name : str\n Name of the desired magic function, without '%' prefix.\n line : str\n The rest of the first input line as a single string.\n cell : str\n The body of the cell as a (possibly multiline) string.\n "
fn = self._find_with_lazy_load('cell', magic_name)
if (fn is None):
lm = self.find_line_magic(magic_name)
etpl = 'Cell magic `%%{0}` not found{1}.'
extra = ('' if (lm is None) else ' (But line magic `%{0}` exists, did you mean that instead?)'.format(magic_name))
raise UsageError(etpl.format(magic_name, extra))
elif (cell == ''):
message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
if (self.find_line_magic(magic_name) is not None):
message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
raise UsageError(message)
else:
stack_depth = 2
if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
magic_arg_s = line
else:
magic_arg_s = self.var_expand(line, stack_depth)
kwargs = {}
if getattr(fn, 'needs_local_scope', False):
kwargs['local_ns'] = self.user_ns
with self.builtin_trap:
args = (magic_arg_s, cell)
result = fn(*args, **kwargs)
return result
| -2,436,769,280,446,700,500
|
Execute the given cell magic.
Parameters
----------
magic_name : str
Name of the desired magic function, without '%' prefix.
line : str
The rest of the first input line as a single string.
cell : str
The body of the cell as a (possibly multiline) string.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
run_cell_magic
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def run_cell_magic(self, magic_name, line, cell):
"Execute the given cell magic.\n\n Parameters\n ----------\n magic_name : str\n Name of the desired magic function, without '%' prefix.\n line : str\n The rest of the first input line as a single string.\n cell : str\n The body of the cell as a (possibly multiline) string.\n "
fn = self._find_with_lazy_load('cell', magic_name)
if (fn is None):
lm = self.find_line_magic(magic_name)
etpl = 'Cell magic `%%{0}` not found{1}.'
extra = ( if (lm is None) else ' (But line magic `%{0}` exists, did you mean that instead?)'.format(magic_name))
raise UsageError(etpl.format(magic_name, extra))
elif (cell == ):
message = '%%{0} is a cell magic, but the cell body is empty.'.format(magic_name)
if (self.find_line_magic(magic_name) is not None):
message += ' Did you mean the line magic %{0} (single %)?'.format(magic_name)
raise UsageError(message)
else:
stack_depth = 2
if getattr(fn, magic.MAGIC_NO_VAR_EXPAND_ATTR, False):
magic_arg_s = line
else:
magic_arg_s = self.var_expand(line, stack_depth)
kwargs = {}
if getattr(fn, 'needs_local_scope', False):
kwargs['local_ns'] = self.user_ns
with self.builtin_trap:
args = (magic_arg_s, cell)
result = fn(*args, **kwargs)
return result
|
def find_line_magic(self, magic_name):
"Find and return a line magic by name.\n\n Returns None if the magic isn't found."
return self.magics_manager.magics['line'].get(magic_name)
| -1,560,656,864,380,957,700
|
Find and return a line magic by name.
Returns None if the magic isn't found.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
find_line_magic
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def find_line_magic(self, magic_name):
"Find and return a line magic by name.\n\n Returns None if the magic isn't found."
return self.magics_manager.magics['line'].get(magic_name)
|
def find_cell_magic(self, magic_name):
"Find and return a cell magic by name.\n\n Returns None if the magic isn't found."
return self.magics_manager.magics['cell'].get(magic_name)
| -8,217,593,389,607,089,000
|
Find and return a cell magic by name.
Returns None if the magic isn't found.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
find_cell_magic
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def find_cell_magic(self, magic_name):
"Find and return a cell magic by name.\n\n Returns None if the magic isn't found."
return self.magics_manager.magics['cell'].get(magic_name)
|
def find_magic(self, magic_name, magic_kind='line'):
"Find and return a magic of the given type by name.\n\n Returns None if the magic isn't found."
return self.magics_manager.magics[magic_kind].get(magic_name)
| -6,144,807,989,137,011,000
|
Find and return a magic of the given type by name.
Returns None if the magic isn't found.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
find_magic
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def find_magic(self, magic_name, magic_kind='line'):
"Find and return a magic of the given type by name.\n\n Returns None if the magic isn't found."
return self.magics_manager.magics[magic_kind].get(magic_name)
|
def magic(self, arg_s):
"\n DEPRECATED\n\n Deprecated since IPython 0.13 (warning added in\n 8.1), use run_line_magic(magic_name, parameter_s).\n\n Call a magic function by name.\n\n Input: a string containing the name of the magic function to call and\n any additional arguments to be passed to the magic.\n\n magic('name -opt foo bar') is equivalent to typing at the ipython\n prompt:\n\n In[1]: %name -opt foo bar\n\n To call a magic without arguments, simply use magic('name').\n\n This provides a proper Python function to call IPython's magics in any\n valid Python code you can type at the interpreter, including loops and\n compound statements.\n "
warnings.warn('`magic(...)` is deprecated since IPython 0.13 (warning added in 8.1), use run_line_magic(magic_name, parameter_s).', DeprecationWarning, stacklevel=2)
(magic_name, _, magic_arg_s) = arg_s.partition(' ')
magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
| -2,321,915,023,604,814,000
|
DEPRECATED
Deprecated since IPython 0.13 (warning added in
8.1), use run_line_magic(magic_name, parameter_s).
Call a magic function by name.
Input: a string containing the name of the magic function to call and
any additional arguments to be passed to the magic.
magic('name -opt foo bar') is equivalent to typing at the ipython
prompt:
In[1]: %name -opt foo bar
To call a magic without arguments, simply use magic('name').
This provides a proper Python function to call IPython's magics in any
valid Python code you can type at the interpreter, including loops and
compound statements.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
magic
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def magic(self, arg_s):
"\n DEPRECATED\n\n Deprecated since IPython 0.13 (warning added in\n 8.1), use run_line_magic(magic_name, parameter_s).\n\n Call a magic function by name.\n\n Input: a string containing the name of the magic function to call and\n any additional arguments to be passed to the magic.\n\n magic('name -opt foo bar') is equivalent to typing at the ipython\n prompt:\n\n In[1]: %name -opt foo bar\n\n To call a magic without arguments, simply use magic('name').\n\n This provides a proper Python function to call IPython's magics in any\n valid Python code you can type at the interpreter, including loops and\n compound statements.\n "
warnings.warn('`magic(...)` is deprecated since IPython 0.13 (warning added in 8.1), use run_line_magic(magic_name, parameter_s).', DeprecationWarning, stacklevel=2)
(magic_name, _, magic_arg_s) = arg_s.partition(' ')
magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
return self.run_line_magic(magic_name, magic_arg_s, _stack_depth=2)
|
def define_macro(self, name, themacro):
'Define a new macro\n\n Parameters\n ----------\n name : str\n The name of the macro.\n themacro : str or Macro\n The action to do upon invoking the macro. If a string, a new\n Macro object is created by passing the string to it.\n '
from IPython.core import macro
if isinstance(themacro, str):
themacro = macro.Macro(themacro)
if (not isinstance(themacro, macro.Macro)):
raise ValueError('A macro must be a string or a Macro instance.')
self.user_ns[name] = themacro
| 2,617,882,264,026,802,700
|
Define a new macro
Parameters
----------
name : str
The name of the macro.
themacro : str or Macro
The action to do upon invoking the macro. If a string, a new
Macro object is created by passing the string to it.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
define_macro
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def define_macro(self, name, themacro):
'Define a new macro\n\n Parameters\n ----------\n name : str\n The name of the macro.\n themacro : str or Macro\n The action to do upon invoking the macro. If a string, a new\n Macro object is created by passing the string to it.\n '
from IPython.core import macro
if isinstance(themacro, str):
themacro = macro.Macro(themacro)
if (not isinstance(themacro, macro.Macro)):
raise ValueError('A macro must be a string or a Macro instance.')
self.user_ns[name] = themacro
|
def system_piped(self, cmd):
"Call the given cmd in a subprocess, piping stdout/err\n\n Parameters\n ----------\n cmd : str\n Command to execute (can not end in '&', as background processes are\n not supported. Should not be a command that expects input\n other than simple text.\n "
if cmd.rstrip().endswith('&'):
raise OSError('Background processes not supported.')
self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
| 5,190,823,872,524,154,000
|
Call the given cmd in a subprocess, piping stdout/err
Parameters
----------
cmd : str
Command to execute (can not end in '&', as background processes are
not supported. Should not be a command that expects input
other than simple text.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
system_piped
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def system_piped(self, cmd):
"Call the given cmd in a subprocess, piping stdout/err\n\n Parameters\n ----------\n cmd : str\n Command to execute (can not end in '&', as background processes are\n not supported. Should not be a command that expects input\n other than simple text.\n "
if cmd.rstrip().endswith('&'):
raise OSError('Background processes not supported.')
self.user_ns['_exit_code'] = system(self.var_expand(cmd, depth=1))
|
def system_raw(self, cmd):
'Call the given cmd in a subprocess using os.system on Windows or\n subprocess.call using the system shell on other platforms.\n\n Parameters\n ----------\n cmd : str\n Command to execute.\n '
cmd = self.var_expand(cmd, depth=1)
main_cmd = cmd.split()[0]
has_magic_alternatives = ('pip', 'conda', 'cd')
if (main_cmd in has_magic_alternatives):
warnings.warn('You executed the system command !{0} which may not work as expected. Try the IPython magic %{0} instead.'.format(main_cmd))
if (sys.platform == 'win32'):
from IPython.utils._process_win32 import AvoidUNCPath
with AvoidUNCPath() as path:
if (path is not None):
cmd = ('"pushd %s &&"%s' % (path, cmd))
try:
ec = os.system(cmd)
except KeyboardInterrupt:
print(('\n' + self.get_exception_only()), file=sys.stderr)
ec = (- 2)
else:
executable = os.environ.get('SHELL', None)
try:
ec = subprocess.call(cmd, shell=True, executable=executable)
except KeyboardInterrupt:
print(('\n' + self.get_exception_only()), file=sys.stderr)
ec = 130
if (ec > 128):
ec = (- (ec - 128))
self.user_ns['_exit_code'] = ec
| -315,671,862,176,692,400
|
Call the given cmd in a subprocess using os.system on Windows or
subprocess.call using the system shell on other platforms.
Parameters
----------
cmd : str
Command to execute.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
system_raw
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def system_raw(self, cmd):
'Call the given cmd in a subprocess using os.system on Windows or\n subprocess.call using the system shell on other platforms.\n\n Parameters\n ----------\n cmd : str\n Command to execute.\n '
cmd = self.var_expand(cmd, depth=1)
main_cmd = cmd.split()[0]
has_magic_alternatives = ('pip', 'conda', 'cd')
if (main_cmd in has_magic_alternatives):
warnings.warn('You executed the system command !{0} which may not work as expected. Try the IPython magic %{0} instead.'.format(main_cmd))
if (sys.platform == 'win32'):
from IPython.utils._process_win32 import AvoidUNCPath
with AvoidUNCPath() as path:
if (path is not None):
cmd = ('"pushd %s &&"%s' % (path, cmd))
try:
ec = os.system(cmd)
except KeyboardInterrupt:
print(('\n' + self.get_exception_only()), file=sys.stderr)
ec = (- 2)
else:
executable = os.environ.get('SHELL', None)
try:
ec = subprocess.call(cmd, shell=True, executable=executable)
except KeyboardInterrupt:
print(('\n' + self.get_exception_only()), file=sys.stderr)
ec = 130
if (ec > 128):
ec = (- (ec - 128))
self.user_ns['_exit_code'] = ec
|
def getoutput(self, cmd, split=True, depth=0):
"Get output (possibly including stderr) from a subprocess.\n\n Parameters\n ----------\n cmd : str\n Command to execute (can not end in '&', as background processes are\n not supported.\n split : bool, optional\n If True, split the output into an IPython SList. Otherwise, an\n IPython LSString is returned. These are objects similar to normal\n lists and strings, with a few convenience attributes for easier\n manipulation of line-based output. You can use '?' on them for\n details.\n depth : int, optional\n How many frames above the caller are the local variables which should\n be expanded in the command string? The default (0) assumes that the\n expansion variables are in the stack frame calling this function.\n "
if cmd.rstrip().endswith('&'):
raise OSError('Background processes not supported.')
out = getoutput(self.var_expand(cmd, depth=(depth + 1)))
if split:
out = SList(out.splitlines())
else:
out = LSString(out)
return out
| 4,511,267,334,332,850,700
|
Get output (possibly including stderr) from a subprocess.
Parameters
----------
cmd : str
Command to execute (can not end in '&', as background processes are
not supported.
split : bool, optional
If True, split the output into an IPython SList. Otherwise, an
IPython LSString is returned. These are objects similar to normal
lists and strings, with a few convenience attributes for easier
manipulation of line-based output. You can use '?' on them for
details.
depth : int, optional
How many frames above the caller are the local variables which should
be expanded in the command string? The default (0) assumes that the
expansion variables are in the stack frame calling this function.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
getoutput
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def getoutput(self, cmd, split=True, depth=0):
"Get output (possibly including stderr) from a subprocess.\n\n Parameters\n ----------\n cmd : str\n Command to execute (can not end in '&', as background processes are\n not supported.\n split : bool, optional\n If True, split the output into an IPython SList. Otherwise, an\n IPython LSString is returned. These are objects similar to normal\n lists and strings, with a few convenience attributes for easier\n manipulation of line-based output. You can use '?' on them for\n details.\n depth : int, optional\n How many frames above the caller are the local variables which should\n be expanded in the command string? The default (0) assumes that the\n expansion variables are in the stack frame calling this function.\n "
if cmd.rstrip().endswith('&'):
raise OSError('Background processes not supported.')
out = getoutput(self.var_expand(cmd, depth=(depth + 1)))
if split:
out = SList(out.splitlines())
else:
out = LSString(out)
return out
|
def auto_rewrite_input(self, cmd):
"Print to the screen the rewritten form of the user's command.\n\n This shows visual feedback by rewriting input lines that cause\n automatic calling to kick in, like::\n\n /f x\n\n into::\n\n ------> f(x)\n\n after the user's input prompt. This helps the user understand that the\n input line was transformed automatically by IPython.\n "
if (not self.show_rewritten_input):
return
print(('------> ' + cmd))
| -1,554,820,592,618,844,000
|
Print to the screen the rewritten form of the user's command.
This shows visual feedback by rewriting input lines that cause
automatic calling to kick in, like::
/f x
into::
------> f(x)
after the user's input prompt. This helps the user understand that the
input line was transformed automatically by IPython.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
auto_rewrite_input
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def auto_rewrite_input(self, cmd):
"Print to the screen the rewritten form of the user's command.\n\n This shows visual feedback by rewriting input lines that cause\n automatic calling to kick in, like::\n\n /f x\n\n into::\n\n ------> f(x)\n\n after the user's input prompt. This helps the user understand that the\n input line was transformed automatically by IPython.\n "
if (not self.show_rewritten_input):
return
print(('------> ' + cmd))
|
def _user_obj_error(self):
'return simple exception dict\n\n for use in user_expressions\n '
(etype, evalue, tb) = self._get_exc_info()
stb = self.InteractiveTB.get_exception_only(etype, evalue)
exc_info = {'status': 'error', 'traceback': stb, 'ename': etype.__name__, 'evalue': py3compat.safe_unicode(evalue)}
return exc_info
| 2,699,344,948,278,257,700
|
return simple exception dict
for use in user_expressions
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_user_obj_error
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _user_obj_error(self):
'return simple exception dict\n\n for use in user_expressions\n '
(etype, evalue, tb) = self._get_exc_info()
stb = self.InteractiveTB.get_exception_only(etype, evalue)
exc_info = {'status': 'error', 'traceback': stb, 'ename': etype.__name__, 'evalue': py3compat.safe_unicode(evalue)}
return exc_info
|
def _format_user_obj(self, obj):
'format a user object to display dict\n\n for use in user_expressions\n '
(data, md) = self.display_formatter.format(obj)
value = {'status': 'ok', 'data': data, 'metadata': md}
return value
| 3,523,793,102,233,199,600
|
format a user object to display dict
for use in user_expressions
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_format_user_obj
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _format_user_obj(self, obj):
'format a user object to display dict\n\n for use in user_expressions\n '
(data, md) = self.display_formatter.format(obj)
value = {'status': 'ok', 'data': data, 'metadata': md}
return value
|
def user_expressions(self, expressions):
"Evaluate a dict of expressions in the user's namespace.\n\n Parameters\n ----------\n expressions : dict\n A dict with string keys and string values. The expression values\n should be valid Python expressions, each of which will be evaluated\n in the user namespace.\n\n Returns\n -------\n A dict, keyed like the input expressions dict, with the rich mime-typed\n display_data of each value.\n "
out = {}
user_ns = self.user_ns
global_ns = self.user_global_ns
for (key, expr) in expressions.items():
try:
value = self._format_user_obj(eval(expr, global_ns, user_ns))
except:
value = self._user_obj_error()
out[key] = value
return out
| 7,821,608,805,693,288,000
|
Evaluate a dict of expressions in the user's namespace.
Parameters
----------
expressions : dict
A dict with string keys and string values. The expression values
should be valid Python expressions, each of which will be evaluated
in the user namespace.
Returns
-------
A dict, keyed like the input expressions dict, with the rich mime-typed
display_data of each value.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
user_expressions
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def user_expressions(self, expressions):
"Evaluate a dict of expressions in the user's namespace.\n\n Parameters\n ----------\n expressions : dict\n A dict with string keys and string values. The expression values\n should be valid Python expressions, each of which will be evaluated\n in the user namespace.\n\n Returns\n -------\n A dict, keyed like the input expressions dict, with the rich mime-typed\n display_data of each value.\n "
out = {}
user_ns = self.user_ns
global_ns = self.user_global_ns
for (key, expr) in expressions.items():
try:
value = self._format_user_obj(eval(expr, global_ns, user_ns))
except:
value = self._user_obj_error()
out[key] = value
return out
|
def ex(self, cmd):
'Execute a normal python statement in user namespace.'
with self.builtin_trap:
exec(cmd, self.user_global_ns, self.user_ns)
| -8,521,159,763,174,122,000
|
Execute a normal python statement in user namespace.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
ex
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def ex(self, cmd):
with self.builtin_trap:
exec(cmd, self.user_global_ns, self.user_ns)
|
def ev(self, expr):
'Evaluate python expression expr in user namespace.\n\n Returns the result of evaluation\n '
with self.builtin_trap:
return eval(expr, self.user_global_ns, self.user_ns)
| 1,279,435,246,166,427,000
|
Evaluate python expression expr in user namespace.
Returns the result of evaluation
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
ev
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def ev(self, expr):
'Evaluate python expression expr in user namespace.\n\n Returns the result of evaluation\n '
with self.builtin_trap:
return eval(expr, self.user_global_ns, self.user_ns)
|
def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
'A safe version of the builtin execfile().\n\n This version will never throw an exception, but instead print\n helpful error messages to the screen. This only works on pure\n Python files with the .py extension.\n\n Parameters\n ----------\n fname : string\n The name of the file to be executed.\n *where : tuple\n One or two namespaces, passed to execfile() as (globals,locals).\n If only one is given, it is passed as both.\n exit_ignore : bool (False)\n If True, then silence SystemExit for non-zero status (it is always\n silenced for zero status, as it is so common).\n raise_exceptions : bool (False)\n If True raise exceptions everywhere. Meant for testing.\n shell_futures : bool (False)\n If True, the code will share future statements with the interactive\n shell. It will both be affected by previous __future__ imports, and\n any __future__ imports in the code will affect the shell. If False,\n __future__ imports are not shared in either direction.\n\n '
fname = Path(fname).expanduser().resolve()
try:
with fname.open('rb'):
pass
except:
warn(('Could not open file <%s> for safe execution.' % fname))
return
dname = str(fname.parent)
with prepended_to_syspath(dname), self.builtin_trap:
try:
(glob, loc) = (where + (None,))[:2]
py3compat.execfile(fname, glob, loc, (self.compile if shell_futures else None))
except SystemExit as status:
if status.code:
if raise_exceptions:
raise
if (not exit_ignore):
self.showtraceback(exception_only=True)
except:
if raise_exceptions:
raise
self.showtraceback(tb_offset=2)
| -7,730,719,002,565,649,000
|
A safe version of the builtin execfile().
This version will never throw an exception, but instead print
helpful error messages to the screen. This only works on pure
Python files with the .py extension.
Parameters
----------
fname : string
The name of the file to be executed.
*where : tuple
One or two namespaces, passed to execfile() as (globals,locals).
If only one is given, it is passed as both.
exit_ignore : bool (False)
If True, then silence SystemExit for non-zero status (it is always
silenced for zero status, as it is so common).
raise_exceptions : bool (False)
If True raise exceptions everywhere. Meant for testing.
shell_futures : bool (False)
If True, the code will share future statements with the interactive
shell. It will both be affected by previous __future__ imports, and
any __future__ imports in the code will affect the shell. If False,
__future__ imports are not shared in either direction.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
safe_execfile
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def safe_execfile(self, fname, *where, exit_ignore=False, raise_exceptions=False, shell_futures=False):
'A safe version of the builtin execfile().\n\n This version will never throw an exception, but instead print\n helpful error messages to the screen. This only works on pure\n Python files with the .py extension.\n\n Parameters\n ----------\n fname : string\n The name of the file to be executed.\n *where : tuple\n One or two namespaces, passed to execfile() as (globals,locals).\n If only one is given, it is passed as both.\n exit_ignore : bool (False)\n If True, then silence SystemExit for non-zero status (it is always\n silenced for zero status, as it is so common).\n raise_exceptions : bool (False)\n If True raise exceptions everywhere. Meant for testing.\n shell_futures : bool (False)\n If True, the code will share future statements with the interactive\n shell. It will both be affected by previous __future__ imports, and\n any __future__ imports in the code will affect the shell. If False,\n __future__ imports are not shared in either direction.\n\n '
fname = Path(fname).expanduser().resolve()
try:
with fname.open('rb'):
pass
except:
warn(('Could not open file <%s> for safe execution.' % fname))
return
dname = str(fname.parent)
with prepended_to_syspath(dname), self.builtin_trap:
try:
(glob, loc) = (where + (None,))[:2]
py3compat.execfile(fname, glob, loc, (self.compile if shell_futures else None))
except SystemExit as status:
if status.code:
if raise_exceptions:
raise
if (not exit_ignore):
self.showtraceback(exception_only=True)
except:
if raise_exceptions:
raise
self.showtraceback(tb_offset=2)
|
def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
'Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.\n\n Parameters\n ----------\n fname : str\n The name of the file to execute. The filename must have a\n .ipy or .ipynb extension.\n shell_futures : bool (False)\n If True, the code will share future statements with the interactive\n shell. It will both be affected by previous __future__ imports, and\n any __future__ imports in the code will affect the shell. If False,\n __future__ imports are not shared in either direction.\n raise_exceptions : bool (False)\n If True raise exceptions everywhere. Meant for testing.\n '
fname = Path(fname).expanduser().resolve()
try:
with fname.open('rb'):
pass
except:
warn(('Could not open file <%s> for safe execution.' % fname))
return
dname = str(fname.parent)
def get_cells():
'generator for sequence of code blocks to run'
if (fname.suffix == '.ipynb'):
from nbformat import read
nb = read(fname, as_version=4)
if (not nb.cells):
return
for cell in nb.cells:
if (cell.cell_type == 'code'):
(yield cell.source)
else:
(yield fname.read_text(encoding='utf-8'))
with prepended_to_syspath(dname):
try:
for cell in get_cells():
result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
if raise_exceptions:
result.raise_error()
elif (not result.success):
break
except:
if raise_exceptions:
raise
self.showtraceback()
warn(('Unknown failure executing file: <%s>' % fname))
| 3,980,181,048,136,969,000
|
Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.
Parameters
----------
fname : str
The name of the file to execute. The filename must have a
.ipy or .ipynb extension.
shell_futures : bool (False)
If True, the code will share future statements with the interactive
shell. It will both be affected by previous __future__ imports, and
any __future__ imports in the code will affect the shell. If False,
__future__ imports are not shared in either direction.
raise_exceptions : bool (False)
If True raise exceptions everywhere. Meant for testing.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
safe_execfile_ipy
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def safe_execfile_ipy(self, fname, shell_futures=False, raise_exceptions=False):
'Like safe_execfile, but for .ipy or .ipynb files with IPython syntax.\n\n Parameters\n ----------\n fname : str\n The name of the file to execute. The filename must have a\n .ipy or .ipynb extension.\n shell_futures : bool (False)\n If True, the code will share future statements with the interactive\n shell. It will both be affected by previous __future__ imports, and\n any __future__ imports in the code will affect the shell. If False,\n __future__ imports are not shared in either direction.\n raise_exceptions : bool (False)\n If True raise exceptions everywhere. Meant for testing.\n '
fname = Path(fname).expanduser().resolve()
try:
with fname.open('rb'):
pass
except:
warn(('Could not open file <%s> for safe execution.' % fname))
return
dname = str(fname.parent)
def get_cells():
'generator for sequence of code blocks to run'
if (fname.suffix == '.ipynb'):
from nbformat import read
nb = read(fname, as_version=4)
if (not nb.cells):
return
for cell in nb.cells:
if (cell.cell_type == 'code'):
(yield cell.source)
else:
(yield fname.read_text(encoding='utf-8'))
with prepended_to_syspath(dname):
try:
for cell in get_cells():
result = self.run_cell(cell, silent=True, shell_futures=shell_futures)
if raise_exceptions:
result.raise_error()
elif (not result.success):
break
except:
if raise_exceptions:
raise
self.showtraceback()
warn(('Unknown failure executing file: <%s>' % fname))
|
def safe_run_module(self, mod_name, where):
'A safe version of runpy.run_module().\n\n This version will never throw an exception, but instead print\n helpful error messages to the screen.\n\n `SystemExit` exceptions with status code 0 or None are ignored.\n\n Parameters\n ----------\n mod_name : string\n The name of the module to be executed.\n where : dict\n The globals namespace.\n '
try:
try:
where.update(runpy.run_module(str(mod_name), run_name='__main__', alter_sys=True))
except SystemExit as status:
if status.code:
raise
except:
self.showtraceback()
warn(('Unknown failure executing module: <%s>' % mod_name))
| -3,417,527,296,892,662,300
|
A safe version of runpy.run_module().
This version will never throw an exception, but instead print
helpful error messages to the screen.
`SystemExit` exceptions with status code 0 or None are ignored.
Parameters
----------
mod_name : string
The name of the module to be executed.
where : dict
The globals namespace.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
safe_run_module
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def safe_run_module(self, mod_name, where):
'A safe version of runpy.run_module().\n\n This version will never throw an exception, but instead print\n helpful error messages to the screen.\n\n `SystemExit` exceptions with status code 0 or None are ignored.\n\n Parameters\n ----------\n mod_name : string\n The name of the module to be executed.\n where : dict\n The globals namespace.\n '
try:
try:
where.update(runpy.run_module(str(mod_name), run_name='__main__', alter_sys=True))
except SystemExit as status:
if status.code:
raise
except:
self.showtraceback()
warn(('Unknown failure executing module: <%s>' % mod_name))
|
def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
"Run a complete IPython cell.\n\n Parameters\n ----------\n raw_cell : str\n The code (including IPython code such as %magic functions) to run.\n store_history : bool\n If True, the raw and translated cell will be stored in IPython's\n history. For user code calling back into IPython's machinery, this\n should be set to False.\n silent : bool\n If True, avoid side-effects, such as implicit displayhooks and\n and logging. silent=True forces store_history=False.\n shell_futures : bool\n If True, the code will share future statements with the interactive\n shell. It will both be affected by previous __future__ imports, and\n any __future__ imports in the code will affect the shell. If False,\n __future__ imports are not shared in either direction.\n\n Returns\n -------\n result : :class:`ExecutionResult`\n "
result = None
try:
result = self._run_cell(raw_cell, store_history, silent, shell_futures)
finally:
self.events.trigger('post_execute')
if (not silent):
self.events.trigger('post_run_cell', result)
return result
| 2,433,717,764,190,113,300
|
Run a complete IPython cell.
Parameters
----------
raw_cell : str
The code (including IPython code such as %magic functions) to run.
store_history : bool
If True, the raw and translated cell will be stored in IPython's
history. For user code calling back into IPython's machinery, this
should be set to False.
silent : bool
If True, avoid side-effects, such as implicit displayhooks and
and logging. silent=True forces store_history=False.
shell_futures : bool
If True, the code will share future statements with the interactive
shell. It will both be affected by previous __future__ imports, and
any __future__ imports in the code will affect the shell. If False,
__future__ imports are not shared in either direction.
Returns
-------
result : :class:`ExecutionResult`
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
run_cell
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def run_cell(self, raw_cell, store_history=False, silent=False, shell_futures=True):
"Run a complete IPython cell.\n\n Parameters\n ----------\n raw_cell : str\n The code (including IPython code such as %magic functions) to run.\n store_history : bool\n If True, the raw and translated cell will be stored in IPython's\n history. For user code calling back into IPython's machinery, this\n should be set to False.\n silent : bool\n If True, avoid side-effects, such as implicit displayhooks and\n and logging. silent=True forces store_history=False.\n shell_futures : bool\n If True, the code will share future statements with the interactive\n shell. It will both be affected by previous __future__ imports, and\n any __future__ imports in the code will affect the shell. If False,\n __future__ imports are not shared in either direction.\n\n Returns\n -------\n result : :class:`ExecutionResult`\n "
result = None
try:
result = self._run_cell(raw_cell, store_history, silent, shell_futures)
finally:
self.events.trigger('post_execute')
if (not silent):
self.events.trigger('post_run_cell', result)
return result
|
def _run_cell(self, raw_cell: str, store_history: bool, silent: bool, shell_futures: bool) -> ExecutionResult:
'Internal method to run a complete IPython cell.'
preprocessing_exc_tuple = None
try:
transformed_cell = self.transform_cell(raw_cell)
except Exception:
transformed_cell = raw_cell
preprocessing_exc_tuple = sys.exc_info()
assert (transformed_cell is not None)
coro = self.run_cell_async(raw_cell, store_history=store_history, silent=silent, shell_futures=shell_futures, transformed_cell=transformed_cell, preprocessing_exc_tuple=preprocessing_exc_tuple)
if self.trio_runner:
runner = self.trio_runner
elif self.should_run_async(raw_cell, transformed_cell=transformed_cell, preprocessing_exc_tuple=preprocessing_exc_tuple):
runner = self.loop_runner
else:
runner = _pseudo_sync_runner
try:
return runner(coro)
except BaseException as e:
info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
result = ExecutionResult(info)
result.error_in_exec = e
self.showtraceback(running_compiled_code=True)
return result
| -2,686,586,060,926,013,000
|
Internal method to run a complete IPython cell.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_run_cell
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _run_cell(self, raw_cell: str, store_history: bool, silent: bool, shell_futures: bool) -> ExecutionResult:
preprocessing_exc_tuple = None
try:
transformed_cell = self.transform_cell(raw_cell)
except Exception:
transformed_cell = raw_cell
preprocessing_exc_tuple = sys.exc_info()
assert (transformed_cell is not None)
coro = self.run_cell_async(raw_cell, store_history=store_history, silent=silent, shell_futures=shell_futures, transformed_cell=transformed_cell, preprocessing_exc_tuple=preprocessing_exc_tuple)
if self.trio_runner:
runner = self.trio_runner
elif self.should_run_async(raw_cell, transformed_cell=transformed_cell, preprocessing_exc_tuple=preprocessing_exc_tuple):
runner = self.loop_runner
else:
runner = _pseudo_sync_runner
try:
return runner(coro)
except BaseException as e:
info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
result = ExecutionResult(info)
result.error_in_exec = e
self.showtraceback(running_compiled_code=True)
return result
|
def should_run_async(self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None) -> bool:
'Return whether a cell should be run asynchronously via a coroutine runner\n\n Parameters\n ----------\n raw_cell : str\n The code to be executed\n\n Returns\n -------\n result: bool\n Whether the code needs to be run with a coroutine runner or not\n .. versionadded:: 7.0\n '
if (not self.autoawait):
return False
if (preprocessing_exc_tuple is not None):
return False
assert (preprocessing_exc_tuple is None)
if (transformed_cell is None):
warnings.warn('`should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.', DeprecationWarning, stacklevel=2)
try:
cell = self.transform_cell(raw_cell)
except Exception:
return False
else:
cell = transformed_cell
return _should_be_async(cell)
| 6,896,903,336,297,241,000
|
Return whether a cell should be run asynchronously via a coroutine runner
Parameters
----------
raw_cell : str
The code to be executed
Returns
-------
result: bool
Whether the code needs to be run with a coroutine runner or not
.. versionadded:: 7.0
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
should_run_async
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def should_run_async(self, raw_cell: str, *, transformed_cell=None, preprocessing_exc_tuple=None) -> bool:
'Return whether a cell should be run asynchronously via a coroutine runner\n\n Parameters\n ----------\n raw_cell : str\n The code to be executed\n\n Returns\n -------\n result: bool\n Whether the code needs to be run with a coroutine runner or not\n .. versionadded:: 7.0\n '
if (not self.autoawait):
return False
if (preprocessing_exc_tuple is not None):
return False
assert (preprocessing_exc_tuple is None)
if (transformed_cell is None):
warnings.warn('`should_run_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.', DeprecationWarning, stacklevel=2)
try:
cell = self.transform_cell(raw_cell)
except Exception:
return False
else:
cell = transformed_cell
return _should_be_async(cell)
|
async def run_cell_async(self, raw_cell: str, store_history=False, silent=False, shell_futures=True, *, transformed_cell: Optional[str]=None, preprocessing_exc_tuple: Optional[Any]=None) -> ExecutionResult:
"Run a complete IPython cell asynchronously.\n\n Parameters\n ----------\n raw_cell : str\n The code (including IPython code such as %magic functions) to run.\n store_history : bool\n If True, the raw and translated cell will be stored in IPython's\n history. For user code calling back into IPython's machinery, this\n should be set to False.\n silent : bool\n If True, avoid side-effects, such as implicit displayhooks and\n and logging. silent=True forces store_history=False.\n shell_futures : bool\n If True, the code will share future statements with the interactive\n shell. It will both be affected by previous __future__ imports, and\n any __future__ imports in the code will affect the shell. If False,\n __future__ imports are not shared in either direction.\n transformed_cell: str\n cell that was passed through transformers\n preprocessing_exc_tuple:\n trace if the transformation failed.\n\n Returns\n -------\n result : :class:`ExecutionResult`\n\n .. versionadded:: 7.0\n "
info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
result = ExecutionResult(info)
if ((not raw_cell) or raw_cell.isspace()):
self.last_execution_succeeded = True
self.last_execution_result = result
return result
if silent:
store_history = False
if store_history:
result.execution_count = self.execution_count
def error_before_exec(value):
if store_history:
self.execution_count += 1
result.error_before_exec = value
self.last_execution_succeeded = False
self.last_execution_result = result
return result
self.events.trigger('pre_execute')
if (not silent):
self.events.trigger('pre_run_cell', info)
if (transformed_cell is None):
warnings.warn('`run_cell_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.', DeprecationWarning, stacklevel=2)
try:
cell = self.transform_cell(raw_cell)
except Exception:
preprocessing_exc_tuple = sys.exc_info()
cell = raw_cell
else:
preprocessing_exc_tuple = None
elif (preprocessing_exc_tuple is None):
cell = transformed_cell
else:
cell = raw_cell
if (store_history and (raw_cell.strip(' %') != 'paste')):
self.history_manager.store_inputs(self.execution_count, cell, raw_cell)
if (not silent):
self.logger.log(cell, raw_cell)
if (preprocessing_exc_tuple is not None):
self.showtraceback(preprocessing_exc_tuple)
if store_history:
self.execution_count += 1
return error_before_exec(preprocessing_exc_tuple[1])
compiler = (self.compile if shell_futures else self.compiler_class())
_run_async = False
with self.builtin_trap:
cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
with self.display_trap:
try:
code_ast = compiler.ast_parse(cell, filename=cell_name)
except self.custom_exceptions as e:
(etype, value, tb) = sys.exc_info()
self.CustomTB(etype, value, tb)
return error_before_exec(e)
except IndentationError as e:
self.showindentationerror()
return error_before_exec(e)
except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError) as e:
self.showsyntaxerror()
return error_before_exec(e)
try:
code_ast = self.transform_ast(code_ast)
except InputRejected as e:
self.showtraceback()
return error_before_exec(e)
self.displayhook.exec_result = result
interactivity = ('none' if silent else self.ast_node_interactivity)
has_raised = (await self.run_ast_nodes(code_ast.body, cell_name, interactivity=interactivity, compiler=compiler, result=result))
self.last_execution_succeeded = (not has_raised)
self.last_execution_result = result
self.displayhook.exec_result = None
if store_history:
self.history_manager.store_output(self.execution_count)
self.execution_count += 1
return result
| 5,430,472,186,216,697,000
|
Run a complete IPython cell asynchronously.
Parameters
----------
raw_cell : str
The code (including IPython code such as %magic functions) to run.
store_history : bool
If True, the raw and translated cell will be stored in IPython's
history. For user code calling back into IPython's machinery, this
should be set to False.
silent : bool
If True, avoid side-effects, such as implicit displayhooks and
and logging. silent=True forces store_history=False.
shell_futures : bool
If True, the code will share future statements with the interactive
shell. It will both be affected by previous __future__ imports, and
any __future__ imports in the code will affect the shell. If False,
__future__ imports are not shared in either direction.
transformed_cell: str
cell that was passed through transformers
preprocessing_exc_tuple:
trace if the transformation failed.
Returns
-------
result : :class:`ExecutionResult`
.. versionadded:: 7.0
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
run_cell_async
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
async def run_cell_async(self, raw_cell: str, store_history=False, silent=False, shell_futures=True, *, transformed_cell: Optional[str]=None, preprocessing_exc_tuple: Optional[Any]=None) -> ExecutionResult:
"Run a complete IPython cell asynchronously.\n\n Parameters\n ----------\n raw_cell : str\n The code (including IPython code such as %magic functions) to run.\n store_history : bool\n If True, the raw and translated cell will be stored in IPython's\n history. For user code calling back into IPython's machinery, this\n should be set to False.\n silent : bool\n If True, avoid side-effects, such as implicit displayhooks and\n and logging. silent=True forces store_history=False.\n shell_futures : bool\n If True, the code will share future statements with the interactive\n shell. It will both be affected by previous __future__ imports, and\n any __future__ imports in the code will affect the shell. If False,\n __future__ imports are not shared in either direction.\n transformed_cell: str\n cell that was passed through transformers\n preprocessing_exc_tuple:\n trace if the transformation failed.\n\n Returns\n -------\n result : :class:`ExecutionResult`\n\n .. versionadded:: 7.0\n "
info = ExecutionInfo(raw_cell, store_history, silent, shell_futures)
result = ExecutionResult(info)
if ((not raw_cell) or raw_cell.isspace()):
self.last_execution_succeeded = True
self.last_execution_result = result
return result
if silent:
store_history = False
if store_history:
result.execution_count = self.execution_count
def error_before_exec(value):
if store_history:
self.execution_count += 1
result.error_before_exec = value
self.last_execution_succeeded = False
self.last_execution_result = result
return result
self.events.trigger('pre_execute')
if (not silent):
self.events.trigger('pre_run_cell', info)
if (transformed_cell is None):
warnings.warn('`run_cell_async` will not call `transform_cell` automatically in the future. Please pass the result to `transformed_cell` argument and any exception that happen during thetransform in `preprocessing_exc_tuple` in IPython 7.17 and above.', DeprecationWarning, stacklevel=2)
try:
cell = self.transform_cell(raw_cell)
except Exception:
preprocessing_exc_tuple = sys.exc_info()
cell = raw_cell
else:
preprocessing_exc_tuple = None
elif (preprocessing_exc_tuple is None):
cell = transformed_cell
else:
cell = raw_cell
if (store_history and (raw_cell.strip(' %') != 'paste')):
self.history_manager.store_inputs(self.execution_count, cell, raw_cell)
if (not silent):
self.logger.log(cell, raw_cell)
if (preprocessing_exc_tuple is not None):
self.showtraceback(preprocessing_exc_tuple)
if store_history:
self.execution_count += 1
return error_before_exec(preprocessing_exc_tuple[1])
compiler = (self.compile if shell_futures else self.compiler_class())
_run_async = False
with self.builtin_trap:
cell_name = compiler.cache(cell, self.execution_count, raw_code=raw_cell)
with self.display_trap:
try:
code_ast = compiler.ast_parse(cell, filename=cell_name)
except self.custom_exceptions as e:
(etype, value, tb) = sys.exc_info()
self.CustomTB(etype, value, tb)
return error_before_exec(e)
except IndentationError as e:
self.showindentationerror()
return error_before_exec(e)
except (OverflowError, SyntaxError, ValueError, TypeError, MemoryError) as e:
self.showsyntaxerror()
return error_before_exec(e)
try:
code_ast = self.transform_ast(code_ast)
except InputRejected as e:
self.showtraceback()
return error_before_exec(e)
self.displayhook.exec_result = result
interactivity = ('none' if silent else self.ast_node_interactivity)
has_raised = (await self.run_ast_nodes(code_ast.body, cell_name, interactivity=interactivity, compiler=compiler, result=result))
self.last_execution_succeeded = (not has_raised)
self.last_execution_result = result
self.displayhook.exec_result = None
if store_history:
self.history_manager.store_output(self.execution_count)
self.execution_count += 1
return result
|
def transform_cell(self, raw_cell):
'Transform an input cell before parsing it.\n\n Static transformations, implemented in IPython.core.inputtransformer2,\n deal with things like ``%magic`` and ``!system`` commands.\n These run on all input.\n Dynamic transformations, for things like unescaped magics and the exit\n autocall, depend on the state of the interpreter.\n These only apply to single line inputs.\n\n These string-based transformations are followed by AST transformations;\n see :meth:`transform_ast`.\n '
cell = self.input_transformer_manager.transform_cell(raw_cell)
if (len(cell.splitlines()) == 1):
with self.builtin_trap:
cell = (self.prefilter_manager.prefilter_lines(cell) + '\n')
lines = cell.splitlines(keepends=True)
for transform in self.input_transformers_post:
lines = transform(lines)
cell = ''.join(lines)
return cell
| -6,800,214,030,907,054,000
|
Transform an input cell before parsing it.
Static transformations, implemented in IPython.core.inputtransformer2,
deal with things like ``%magic`` and ``!system`` commands.
These run on all input.
Dynamic transformations, for things like unescaped magics and the exit
autocall, depend on the state of the interpreter.
These only apply to single line inputs.
These string-based transformations are followed by AST transformations;
see :meth:`transform_ast`.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
transform_cell
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def transform_cell(self, raw_cell):
'Transform an input cell before parsing it.\n\n Static transformations, implemented in IPython.core.inputtransformer2,\n deal with things like ``%magic`` and ``!system`` commands.\n These run on all input.\n Dynamic transformations, for things like unescaped magics and the exit\n autocall, depend on the state of the interpreter.\n These only apply to single line inputs.\n\n These string-based transformations are followed by AST transformations;\n see :meth:`transform_ast`.\n '
cell = self.input_transformer_manager.transform_cell(raw_cell)
if (len(cell.splitlines()) == 1):
with self.builtin_trap:
cell = (self.prefilter_manager.prefilter_lines(cell) + '\n')
lines = cell.splitlines(keepends=True)
for transform in self.input_transformers_post:
lines = transform(lines)
cell = .join(lines)
return cell
|
def transform_ast(self, node):
"Apply the AST transformations from self.ast_transformers\n\n Parameters\n ----------\n node : ast.Node\n The root node to be transformed. Typically called with the ast.Module\n produced by parsing user input.\n\n Returns\n -------\n An ast.Node corresponding to the node it was called with. Note that it\n may also modify the passed object, so don't rely on references to the\n original AST.\n "
for transformer in self.ast_transformers:
try:
node = transformer.visit(node)
except InputRejected:
raise
except Exception:
warn(('AST transformer %r threw an error. It will be unregistered.' % transformer))
self.ast_transformers.remove(transformer)
if self.ast_transformers:
ast.fix_missing_locations(node)
return node
| -477,017,728,517,736,260
|
Apply the AST transformations from self.ast_transformers
Parameters
----------
node : ast.Node
The root node to be transformed. Typically called with the ast.Module
produced by parsing user input.
Returns
-------
An ast.Node corresponding to the node it was called with. Note that it
may also modify the passed object, so don't rely on references to the
original AST.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
transform_ast
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def transform_ast(self, node):
"Apply the AST transformations from self.ast_transformers\n\n Parameters\n ----------\n node : ast.Node\n The root node to be transformed. Typically called with the ast.Module\n produced by parsing user input.\n\n Returns\n -------\n An ast.Node corresponding to the node it was called with. Note that it\n may also modify the passed object, so don't rely on references to the\n original AST.\n "
for transformer in self.ast_transformers:
try:
node = transformer.visit(node)
except InputRejected:
raise
except Exception:
warn(('AST transformer %r threw an error. It will be unregistered.' % transformer))
self.ast_transformers.remove(transformer)
if self.ast_transformers:
ast.fix_missing_locations(node)
return node
|
def _update_code_co_name(self, code):
"Python 3.10 changed the behaviour so that whenever a code object\n is assembled in the compile(ast) the co_firstlineno would be == 1.\n\n This makes pydevd/debugpy think that all cells invoked are the same\n since it caches information based on (co_firstlineno, co_name, co_filename).\n\n Given that, this function changes the code 'co_name' to be unique\n based on the first real lineno of the code (which also has a nice\n side effect of customizing the name so that it's not always <module>).\n\n See: https://github.com/ipython/ipykernel/issues/841\n "
if (not hasattr(code, 'replace')):
return code
try:
first_real_line = next(dis.findlinestarts(code))[1]
except StopIteration:
return code
return code.replace(co_name=('<cell line: %s>' % (first_real_line,)))
| -621,209,993,117,818,800
|
Python 3.10 changed the behaviour so that whenever a code object
is assembled in the compile(ast) the co_firstlineno would be == 1.
This makes pydevd/debugpy think that all cells invoked are the same
since it caches information based on (co_firstlineno, co_name, co_filename).
Given that, this function changes the code 'co_name' to be unique
based on the first real lineno of the code (which also has a nice
side effect of customizing the name so that it's not always <module>).
See: https://github.com/ipython/ipykernel/issues/841
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_update_code_co_name
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _update_code_co_name(self, code):
"Python 3.10 changed the behaviour so that whenever a code object\n is assembled in the compile(ast) the co_firstlineno would be == 1.\n\n This makes pydevd/debugpy think that all cells invoked are the same\n since it caches information based on (co_firstlineno, co_name, co_filename).\n\n Given that, this function changes the code 'co_name' to be unique\n based on the first real lineno of the code (which also has a nice\n side effect of customizing the name so that it's not always <module>).\n\n See: https://github.com/ipython/ipykernel/issues/841\n "
if (not hasattr(code, 'replace')):
return code
try:
first_real_line = next(dis.findlinestarts(code))[1]
except StopIteration:
return code
return code.replace(co_name=('<cell line: %s>' % (first_real_line,)))
|
async def run_ast_nodes(self, nodelist: ListType[stmt], cell_name: str, interactivity='last_expr', compiler=compile, result=None):
"Run a sequence of AST nodes. The execution mode depends on the\n interactivity parameter.\n\n Parameters\n ----------\n nodelist : list\n A sequence of AST nodes to run.\n cell_name : str\n Will be passed to the compiler as the filename of the cell. Typically\n the value returned by ip.compile.cache(cell).\n interactivity : str\n 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',\n specifying which nodes should be run interactively (displaying output\n from expressions). 'last_expr' will run the last node interactively\n only if it is an expression (i.e. expressions in loops or other blocks\n are not displayed) 'last_expr_or_assign' will run the last expression\n or the last assignment. Other values for this parameter will raise a\n ValueError.\n\n compiler : callable\n A function with the same interface as the built-in compile(), to turn\n the AST nodes into code objects. Default is the built-in compile().\n result : ExecutionResult, optional\n An object to store exceptions that occur during execution.\n\n Returns\n -------\n True if an exception occurred while running code, False if it finished\n running.\n "
if (not nodelist):
return
if (interactivity == 'last_expr_or_assign'):
if isinstance(nodelist[(- 1)], _assign_nodes):
asg = nodelist[(- 1)]
if (isinstance(asg, ast.Assign) and (len(asg.targets) == 1)):
target = asg.targets[0]
elif isinstance(asg, _single_targets_nodes):
target = asg.target
else:
target = None
if isinstance(target, ast.Name):
nnode = ast.Expr(ast.Name(target.id, ast.Load()))
ast.fix_missing_locations(nnode)
nodelist.append(nnode)
interactivity = 'last_expr'
_async = False
if (interactivity == 'last_expr'):
if isinstance(nodelist[(- 1)], ast.Expr):
interactivity = 'last'
else:
interactivity = 'none'
if (interactivity == 'none'):
(to_run_exec, to_run_interactive) = (nodelist, [])
elif (interactivity == 'last'):
(to_run_exec, to_run_interactive) = (nodelist[:(- 1)], nodelist[(- 1):])
elif (interactivity == 'all'):
(to_run_exec, to_run_interactive) = ([], nodelist)
else:
raise ValueError(('Interactivity was %r' % interactivity))
try:
def compare(code):
is_async = ((inspect.CO_COROUTINE & code.co_flags) == inspect.CO_COROUTINE)
return is_async
to_run = []
for node in to_run_exec:
to_run.append((node, 'exec'))
for node in to_run_interactive:
to_run.append((node, 'single'))
for (node, mode) in to_run:
if (mode == 'exec'):
mod = Module([node], [])
elif (mode == 'single'):
mod = ast.Interactive([node])
with compiler.extra_flags((getattr(ast, 'PyCF_ALLOW_TOP_LEVEL_AWAIT', 0) if self.autoawait else 0)):
code = compiler(mod, cell_name, mode)
code = self._update_code_co_name(code)
asy = compare(code)
if (await self.run_code(code, result, async_=asy)):
return True
if softspace(sys.stdout, 0):
print()
except:
if result:
result.error_before_exec = sys.exc_info()[1]
self.showtraceback()
return True
return False
| -5,708,423,101,167,578,000
|
Run a sequence of AST nodes. The execution mode depends on the
interactivity parameter.
Parameters
----------
nodelist : list
A sequence of AST nodes to run.
cell_name : str
Will be passed to the compiler as the filename of the cell. Typically
the value returned by ip.compile.cache(cell).
interactivity : str
'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',
specifying which nodes should be run interactively (displaying output
from expressions). 'last_expr' will run the last node interactively
only if it is an expression (i.e. expressions in loops or other blocks
are not displayed) 'last_expr_or_assign' will run the last expression
or the last assignment. Other values for this parameter will raise a
ValueError.
compiler : callable
A function with the same interface as the built-in compile(), to turn
the AST nodes into code objects. Default is the built-in compile().
result : ExecutionResult, optional
An object to store exceptions that occur during execution.
Returns
-------
True if an exception occurred while running code, False if it finished
running.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
run_ast_nodes
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
async def run_ast_nodes(self, nodelist: ListType[stmt], cell_name: str, interactivity='last_expr', compiler=compile, result=None):
"Run a sequence of AST nodes. The execution mode depends on the\n interactivity parameter.\n\n Parameters\n ----------\n nodelist : list\n A sequence of AST nodes to run.\n cell_name : str\n Will be passed to the compiler as the filename of the cell. Typically\n the value returned by ip.compile.cache(cell).\n interactivity : str\n 'all', 'last', 'last_expr' , 'last_expr_or_assign' or 'none',\n specifying which nodes should be run interactively (displaying output\n from expressions). 'last_expr' will run the last node interactively\n only if it is an expression (i.e. expressions in loops or other blocks\n are not displayed) 'last_expr_or_assign' will run the last expression\n or the last assignment. Other values for this parameter will raise a\n ValueError.\n\n compiler : callable\n A function with the same interface as the built-in compile(), to turn\n the AST nodes into code objects. Default is the built-in compile().\n result : ExecutionResult, optional\n An object to store exceptions that occur during execution.\n\n Returns\n -------\n True if an exception occurred while running code, False if it finished\n running.\n "
if (not nodelist):
return
if (interactivity == 'last_expr_or_assign'):
if isinstance(nodelist[(- 1)], _assign_nodes):
asg = nodelist[(- 1)]
if (isinstance(asg, ast.Assign) and (len(asg.targets) == 1)):
target = asg.targets[0]
elif isinstance(asg, _single_targets_nodes):
target = asg.target
else:
target = None
if isinstance(target, ast.Name):
nnode = ast.Expr(ast.Name(target.id, ast.Load()))
ast.fix_missing_locations(nnode)
nodelist.append(nnode)
interactivity = 'last_expr'
_async = False
if (interactivity == 'last_expr'):
if isinstance(nodelist[(- 1)], ast.Expr):
interactivity = 'last'
else:
interactivity = 'none'
if (interactivity == 'none'):
(to_run_exec, to_run_interactive) = (nodelist, [])
elif (interactivity == 'last'):
(to_run_exec, to_run_interactive) = (nodelist[:(- 1)], nodelist[(- 1):])
elif (interactivity == 'all'):
(to_run_exec, to_run_interactive) = ([], nodelist)
else:
raise ValueError(('Interactivity was %r' % interactivity))
try:
def compare(code):
is_async = ((inspect.CO_COROUTINE & code.co_flags) == inspect.CO_COROUTINE)
return is_async
to_run = []
for node in to_run_exec:
to_run.append((node, 'exec'))
for node in to_run_interactive:
to_run.append((node, 'single'))
for (node, mode) in to_run:
if (mode == 'exec'):
mod = Module([node], [])
elif (mode == 'single'):
mod = ast.Interactive([node])
with compiler.extra_flags((getattr(ast, 'PyCF_ALLOW_TOP_LEVEL_AWAIT', 0) if self.autoawait else 0)):
code = compiler(mod, cell_name, mode)
code = self._update_code_co_name(code)
asy = compare(code)
if (await self.run_code(code, result, async_=asy)):
return True
if softspace(sys.stdout, 0):
print()
except:
if result:
result.error_before_exec = sys.exc_info()[1]
self.showtraceback()
return True
return False
|
async def run_code(self, code_obj, result=None, *, async_=False):
'Execute a code object.\n\n When an exception occurs, self.showtraceback() is called to display a\n traceback.\n\n Parameters\n ----------\n code_obj : code object\n A compiled code object, to be executed\n result : ExecutionResult, optional\n An object to store exceptions that occur during execution.\n async_ : Bool (Experimental)\n Attempt to run top-level asynchronous code in a default loop.\n\n Returns\n -------\n False : successful execution.\n True : an error occurred.\n '
__tracebackhide__ = '__ipython_bottom__'
(old_excepthook, sys.excepthook) = (sys.excepthook, self.excepthook)
self.sys_excepthook = old_excepthook
outflag = True
try:
try:
if async_:
(await eval(code_obj, self.user_global_ns, self.user_ns))
else:
exec(code_obj, self.user_global_ns, self.user_ns)
finally:
sys.excepthook = old_excepthook
except SystemExit as e:
if (result is not None):
result.error_in_exec = e
self.showtraceback(exception_only=True)
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
except self.custom_exceptions:
(etype, value, tb) = sys.exc_info()
if (result is not None):
result.error_in_exec = value
self.CustomTB(etype, value, tb)
except:
if (result is not None):
result.error_in_exec = sys.exc_info()[1]
self.showtraceback(running_compiled_code=True)
else:
outflag = False
return outflag
| -3,119,642,127,492,501,500
|
Execute a code object.
When an exception occurs, self.showtraceback() is called to display a
traceback.
Parameters
----------
code_obj : code object
A compiled code object, to be executed
result : ExecutionResult, optional
An object to store exceptions that occur during execution.
async_ : Bool (Experimental)
Attempt to run top-level asynchronous code in a default loop.
Returns
-------
False : successful execution.
True : an error occurred.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
run_code
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
async def run_code(self, code_obj, result=None, *, async_=False):
'Execute a code object.\n\n When an exception occurs, self.showtraceback() is called to display a\n traceback.\n\n Parameters\n ----------\n code_obj : code object\n A compiled code object, to be executed\n result : ExecutionResult, optional\n An object to store exceptions that occur during execution.\n async_ : Bool (Experimental)\n Attempt to run top-level asynchronous code in a default loop.\n\n Returns\n -------\n False : successful execution.\n True : an error occurred.\n '
__tracebackhide__ = '__ipython_bottom__'
(old_excepthook, sys.excepthook) = (sys.excepthook, self.excepthook)
self.sys_excepthook = old_excepthook
outflag = True
try:
try:
if async_:
(await eval(code_obj, self.user_global_ns, self.user_ns))
else:
exec(code_obj, self.user_global_ns, self.user_ns)
finally:
sys.excepthook = old_excepthook
except SystemExit as e:
if (result is not None):
result.error_in_exec = e
self.showtraceback(exception_only=True)
warn("To exit: use 'exit', 'quit', or Ctrl-D.", stacklevel=1)
except self.custom_exceptions:
(etype, value, tb) = sys.exc_info()
if (result is not None):
result.error_in_exec = value
self.CustomTB(etype, value, tb)
except:
if (result is not None):
result.error_in_exec = sys.exc_info()[1]
self.showtraceback(running_compiled_code=True)
else:
outflag = False
return outflag
|
def check_complete(self, code: str) -> Tuple[(str, str)]:
"Return whether a block of code is ready to execute, or should be continued\n\n Parameters\n ----------\n code : string\n Python input code, which can be multiline.\n\n Returns\n -------\n status : str\n One of 'complete', 'incomplete', or 'invalid' if source is not a\n prefix of valid code.\n indent : str\n When status is 'incomplete', this is some whitespace to insert on\n the next line of the prompt.\n "
(status, nspaces) = self.input_transformer_manager.check_complete(code)
return (status, (' ' * (nspaces or 0)))
| 5,624,002,090,772,154,000
|
Return whether a block of code is ready to execute, or should be continued
Parameters
----------
code : string
Python input code, which can be multiline.
Returns
-------
status : str
One of 'complete', 'incomplete', or 'invalid' if source is not a
prefix of valid code.
indent : str
When status is 'incomplete', this is some whitespace to insert on
the next line of the prompt.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
check_complete
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def check_complete(self, code: str) -> Tuple[(str, str)]:
"Return whether a block of code is ready to execute, or should be continued\n\n Parameters\n ----------\n code : string\n Python input code, which can be multiline.\n\n Returns\n -------\n status : str\n One of 'complete', 'incomplete', or 'invalid' if source is not a\n prefix of valid code.\n indent : str\n When status is 'incomplete', this is some whitespace to insert on\n the next line of the prompt.\n "
(status, nspaces) = self.input_transformer_manager.check_complete(code)
return (status, (' ' * (nspaces or 0)))
|
def enable_matplotlib(self, gui=None):
"Enable interactive matplotlib and inline figure support.\n\n This takes the following steps:\n\n 1. select the appropriate eventloop and matplotlib backend\n 2. set up matplotlib for interactive use with that backend\n 3. configure formatters for inline figure display\n 4. enable the selected gui eventloop\n\n Parameters\n ----------\n gui : optional, string\n If given, dictates the choice of matplotlib GUI backend to use\n (should be one of IPython's supported backends, 'qt', 'osx', 'tk',\n 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by\n matplotlib (as dictated by the matplotlib build-time options plus the\n user's matplotlibrc configuration file). Note that not all backends\n make sense in all contexts, for example a terminal ipython can't\n display figures inline.\n "
from matplotlib_inline.backend_inline import configure_inline_support
from IPython.core import pylabtools as pt
(gui, backend) = pt.find_gui_and_backend(gui, self.pylab_gui_select)
if (gui != 'inline'):
if (self.pylab_gui_select is None):
self.pylab_gui_select = gui
elif (gui != self.pylab_gui_select):
print(('Warning: Cannot change to a different GUI toolkit: %s. Using %s instead.' % (gui, self.pylab_gui_select)))
(gui, backend) = pt.find_gui_and_backend(self.pylab_gui_select)
pt.activate_matplotlib(backend)
configure_inline_support(self, backend)
self.enable_gui(gui)
self.magics_manager.registry['ExecutionMagics'].default_runner = pt.mpl_runner(self.safe_execfile)
return (gui, backend)
| -6,350,230,283,851,679,000
|
Enable interactive matplotlib and inline figure support.
This takes the following steps:
1. select the appropriate eventloop and matplotlib backend
2. set up matplotlib for interactive use with that backend
3. configure formatters for inline figure display
4. enable the selected gui eventloop
Parameters
----------
gui : optional, string
If given, dictates the choice of matplotlib GUI backend to use
(should be one of IPython's supported backends, 'qt', 'osx', 'tk',
'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
matplotlib (as dictated by the matplotlib build-time options plus the
user's matplotlibrc configuration file). Note that not all backends
make sense in all contexts, for example a terminal ipython can't
display figures inline.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
enable_matplotlib
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def enable_matplotlib(self, gui=None):
"Enable interactive matplotlib and inline figure support.\n\n This takes the following steps:\n\n 1. select the appropriate eventloop and matplotlib backend\n 2. set up matplotlib for interactive use with that backend\n 3. configure formatters for inline figure display\n 4. enable the selected gui eventloop\n\n Parameters\n ----------\n gui : optional, string\n If given, dictates the choice of matplotlib GUI backend to use\n (should be one of IPython's supported backends, 'qt', 'osx', 'tk',\n 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by\n matplotlib (as dictated by the matplotlib build-time options plus the\n user's matplotlibrc configuration file). Note that not all backends\n make sense in all contexts, for example a terminal ipython can't\n display figures inline.\n "
from matplotlib_inline.backend_inline import configure_inline_support
from IPython.core import pylabtools as pt
(gui, backend) = pt.find_gui_and_backend(gui, self.pylab_gui_select)
if (gui != 'inline'):
if (self.pylab_gui_select is None):
self.pylab_gui_select = gui
elif (gui != self.pylab_gui_select):
print(('Warning: Cannot change to a different GUI toolkit: %s. Using %s instead.' % (gui, self.pylab_gui_select)))
(gui, backend) = pt.find_gui_and_backend(self.pylab_gui_select)
pt.activate_matplotlib(backend)
configure_inline_support(self, backend)
self.enable_gui(gui)
self.magics_manager.registry['ExecutionMagics'].default_runner = pt.mpl_runner(self.safe_execfile)
return (gui, backend)
|
def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
"Activate pylab support at runtime.\n\n This turns on support for matplotlib, preloads into the interactive\n namespace all of numpy and pylab, and configures IPython to correctly\n interact with the GUI event loop. The GUI backend to be used can be\n optionally selected with the optional ``gui`` argument.\n\n This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.\n\n Parameters\n ----------\n gui : optional, string\n If given, dictates the choice of matplotlib GUI backend to use\n (should be one of IPython's supported backends, 'qt', 'osx', 'tk',\n 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by\n matplotlib (as dictated by the matplotlib build-time options plus the\n user's matplotlibrc configuration file). Note that not all backends\n make sense in all contexts, for example a terminal ipython can't\n display figures inline.\n import_all : optional, bool, default: True\n Whether to do `from numpy import *` and `from pylab import *`\n in addition to module imports.\n welcome_message : deprecated\n This argument is ignored, no welcome message will be displayed.\n "
from IPython.core.pylabtools import import_pylab
(gui, backend) = self.enable_matplotlib(gui)
ns = {}
import_pylab(ns, import_all)
ignored = {'__builtins__'}
both = set(ns).intersection(self.user_ns).difference(ignored)
clobbered = [name for name in both if (self.user_ns[name] is not ns[name])]
self.user_ns.update(ns)
self.user_ns_hidden.update(ns)
return (gui, backend, clobbered)
| -5,059,836,458,887,207,000
|
Activate pylab support at runtime.
This turns on support for matplotlib, preloads into the interactive
namespace all of numpy and pylab, and configures IPython to correctly
interact with the GUI event loop. The GUI backend to be used can be
optionally selected with the optional ``gui`` argument.
This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.
Parameters
----------
gui : optional, string
If given, dictates the choice of matplotlib GUI backend to use
(should be one of IPython's supported backends, 'qt', 'osx', 'tk',
'gtk', 'wx' or 'inline'), otherwise we use the default chosen by
matplotlib (as dictated by the matplotlib build-time options plus the
user's matplotlibrc configuration file). Note that not all backends
make sense in all contexts, for example a terminal ipython can't
display figures inline.
import_all : optional, bool, default: True
Whether to do `from numpy import *` and `from pylab import *`
in addition to module imports.
welcome_message : deprecated
This argument is ignored, no welcome message will be displayed.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
enable_pylab
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def enable_pylab(self, gui=None, import_all=True, welcome_message=False):
"Activate pylab support at runtime.\n\n This turns on support for matplotlib, preloads into the interactive\n namespace all of numpy and pylab, and configures IPython to correctly\n interact with the GUI event loop. The GUI backend to be used can be\n optionally selected with the optional ``gui`` argument.\n\n This method only adds preloading the namespace to InteractiveShell.enable_matplotlib.\n\n Parameters\n ----------\n gui : optional, string\n If given, dictates the choice of matplotlib GUI backend to use\n (should be one of IPython's supported backends, 'qt', 'osx', 'tk',\n 'gtk', 'wx' or 'inline'), otherwise we use the default chosen by\n matplotlib (as dictated by the matplotlib build-time options plus the\n user's matplotlibrc configuration file). Note that not all backends\n make sense in all contexts, for example a terminal ipython can't\n display figures inline.\n import_all : optional, bool, default: True\n Whether to do `from numpy import *` and `from pylab import *`\n in addition to module imports.\n welcome_message : deprecated\n This argument is ignored, no welcome message will be displayed.\n "
from IPython.core.pylabtools import import_pylab
(gui, backend) = self.enable_matplotlib(gui)
ns = {}
import_pylab(ns, import_all)
ignored = {'__builtins__'}
both = set(ns).intersection(self.user_ns).difference(ignored)
clobbered = [name for name in both if (self.user_ns[name] is not ns[name])]
self.user_ns.update(ns)
self.user_ns_hidden.update(ns)
return (gui, backend, clobbered)
|
def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
"Expand python variables in a string.\n\n The depth argument indicates how many frames above the caller should\n be walked to look for the local namespace where to expand variables.\n\n The global namespace for expansion is always the user's interactive\n namespace.\n "
ns = self.user_ns.copy()
try:
frame = sys._getframe((depth + 1))
except ValueError:
pass
else:
ns.update(frame.f_locals)
try:
cmd = formatter.vformat(cmd, args=[], kwargs=ns)
except Exception:
pass
return cmd
| 1,565,111,268,002,081,500
|
Expand python variables in a string.
The depth argument indicates how many frames above the caller should
be walked to look for the local namespace where to expand variables.
The global namespace for expansion is always the user's interactive
namespace.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
var_expand
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def var_expand(self, cmd, depth=0, formatter=DollarFormatter()):
"Expand python variables in a string.\n\n The depth argument indicates how many frames above the caller should\n be walked to look for the local namespace where to expand variables.\n\n The global namespace for expansion is always the user's interactive\n namespace.\n "
ns = self.user_ns.copy()
try:
frame = sys._getframe((depth + 1))
except ValueError:
pass
else:
ns.update(frame.f_locals)
try:
cmd = formatter.vformat(cmd, args=[], kwargs=ns)
except Exception:
pass
return cmd
|
def mktempfile(self, data=None, prefix='ipython_edit_'):
'Make a new tempfile and return its filename.\n\n This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),\n but it registers the created filename internally so ipython cleans it up\n at exit time.\n\n Optional inputs:\n\n - data(None): if data is given, it gets written out to the temp file\n immediately, and the file is closed again.'
dir_path = Path(tempfile.mkdtemp(prefix=prefix))
self.tempdirs.append(dir_path)
(handle, filename) = tempfile.mkstemp('.py', prefix, dir=str(dir_path))
os.close(handle)
file_path = Path(filename)
self.tempfiles.append(file_path)
if data:
file_path.write_text(data, encoding='utf-8')
return filename
| -2,235,922,384,923,393,000
|
Make a new tempfile and return its filename.
This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),
but it registers the created filename internally so ipython cleans it up
at exit time.
Optional inputs:
- data(None): if data is given, it gets written out to the temp file
immediately, and the file is closed again.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
mktempfile
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def mktempfile(self, data=None, prefix='ipython_edit_'):
'Make a new tempfile and return its filename.\n\n This makes a call to tempfile.mkstemp (created in a tempfile.mkdtemp),\n but it registers the created filename internally so ipython cleans it up\n at exit time.\n\n Optional inputs:\n\n - data(None): if data is given, it gets written out to the temp file\n immediately, and the file is closed again.'
dir_path = Path(tempfile.mkdtemp(prefix=prefix))
self.tempdirs.append(dir_path)
(handle, filename) = tempfile.mkstemp('.py', prefix, dir=str(dir_path))
os.close(handle)
file_path = Path(filename)
self.tempfiles.append(file_path)
if data:
file_path.write_text(data, encoding='utf-8')
return filename
|
def show_usage(self):
'Show a usage message'
page.page(IPython.core.usage.interactive_usage)
| -3,046,370,155,828,512,000
|
Show a usage message
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
show_usage
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def show_usage(self):
page.page(IPython.core.usage.interactive_usage)
|
def extract_input_lines(self, range_str, raw=False):
'Return as a string a set of input history slices.\n\n Parameters\n ----------\n range_str : str\n The set of slices is given as a string, like "~5/6-~4/2 4:8 9",\n since this function is for use by magic functions which get their\n arguments as strings. The number before the / is the session\n number: ~n goes n back from the current session.\n\n If empty string is given, returns history of current session\n without the last input.\n\n raw : bool, optional\n By default, the processed input is used. If this is true, the raw\n input history is used instead.\n\n Notes\n -----\n Slices can be described with two notations:\n\n * ``N:M`` -> standard python form, means including items N...(M-1).\n * ``N-M`` -> include items N..M (closed endpoint).\n '
lines = self.history_manager.get_range_by_str(range_str, raw=raw)
text = '\n'.join((x for (_, _, x) in lines))
if (not range_str):
if ('\n' not in text):
text = ''
else:
text = text[:text.rfind('\n')]
return text
| -6,934,557,352,905,842,000
|
Return as a string a set of input history slices.
Parameters
----------
range_str : str
The set of slices is given as a string, like "~5/6-~4/2 4:8 9",
since this function is for use by magic functions which get their
arguments as strings. The number before the / is the session
number: ~n goes n back from the current session.
If empty string is given, returns history of current session
without the last input.
raw : bool, optional
By default, the processed input is used. If this is true, the raw
input history is used instead.
Notes
-----
Slices can be described with two notations:
* ``N:M`` -> standard python form, means including items N...(M-1).
* ``N-M`` -> include items N..M (closed endpoint).
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
extract_input_lines
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def extract_input_lines(self, range_str, raw=False):
'Return as a string a set of input history slices.\n\n Parameters\n ----------\n range_str : str\n The set of slices is given as a string, like "~5/6-~4/2 4:8 9",\n since this function is for use by magic functions which get their\n arguments as strings. The number before the / is the session\n number: ~n goes n back from the current session.\n\n If empty string is given, returns history of current session\n without the last input.\n\n raw : bool, optional\n By default, the processed input is used. If this is true, the raw\n input history is used instead.\n\n Notes\n -----\n Slices can be described with two notations:\n\n * ``N:M`` -> standard python form, means including items N...(M-1).\n * ``N-M`` -> include items N..M (closed endpoint).\n '
lines = self.history_manager.get_range_by_str(range_str, raw=raw)
text = '\n'.join((x for (_, _, x) in lines))
if (not range_str):
if ('\n' not in text):
text =
else:
text = text[:text.rfind('\n')]
return text
|
def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
'Get a code string from history, file, url, or a string or macro.\n\n This is mainly used by magic functions.\n\n Parameters\n ----------\n target : str\n A string specifying code to retrieve. This will be tried respectively\n as: ranges of input history (see %history for syntax), url,\n corresponding .py file, filename, or an expression evaluating to a\n string or Macro in the user namespace.\n\n If empty string is given, returns complete history of current\n session, without the last line.\n\n raw : bool\n If true (default), retrieve raw history. Has no effect on the other\n retrieval mechanisms.\n\n py_only : bool (default False)\n Only try to fetch python code, do not try alternative methods to decode file\n if unicode fails.\n\n Returns\n -------\n A string of code.\n ValueError is raised if nothing is found, and TypeError if it evaluates\n to an object of another type. In each case, .args[0] is a printable\n message.\n '
code = self.extract_input_lines(target, raw=raw)
if code:
return code
try:
if target.startswith(('http://', 'https://')):
return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
except UnicodeDecodeError as e:
if (not py_only):
from urllib.request import urlopen
response = urlopen(target)
return response.read().decode('latin1')
raise ValueError(("'%s' seem to be unreadable." % target)) from e
potential_target = [target]
try:
potential_target.insert(0, get_py_filename(target))
except IOError:
pass
for tgt in potential_target:
if os.path.isfile(tgt):
try:
return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
except UnicodeDecodeError as e:
if (not py_only):
with io_open(tgt, 'r', encoding='latin1') as f:
return f.read()
raise ValueError(("'%s' seem to be unreadable." % target)) from e
elif os.path.isdir(os.path.expanduser(tgt)):
raise ValueError(("'%s' is a directory, not a regular file." % target))
if search_ns:
object_info = self.object_inspect(target, detail_level=1)
if (object_info['found'] and object_info['source']):
return object_info['source']
try:
codeobj = eval(target, self.user_ns)
except Exception as e:
raise ValueError(("'%s' was not found in history, as a file, url, nor in the user namespace." % target)) from e
if isinstance(codeobj, str):
return codeobj
elif isinstance(codeobj, Macro):
return codeobj.value
raise TypeError(('%s is neither a string nor a macro.' % target), codeobj)
| 3,588,001,781,120,213,500
|
Get a code string from history, file, url, or a string or macro.
This is mainly used by magic functions.
Parameters
----------
target : str
A string specifying code to retrieve. This will be tried respectively
as: ranges of input history (see %history for syntax), url,
corresponding .py file, filename, or an expression evaluating to a
string or Macro in the user namespace.
If empty string is given, returns complete history of current
session, without the last line.
raw : bool
If true (default), retrieve raw history. Has no effect on the other
retrieval mechanisms.
py_only : bool (default False)
Only try to fetch python code, do not try alternative methods to decode file
if unicode fails.
Returns
-------
A string of code.
ValueError is raised if nothing is found, and TypeError if it evaluates
to an object of another type. In each case, .args[0] is a printable
message.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
find_user_code
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def find_user_code(self, target, raw=True, py_only=False, skip_encoding_cookie=True, search_ns=False):
'Get a code string from history, file, url, or a string or macro.\n\n This is mainly used by magic functions.\n\n Parameters\n ----------\n target : str\n A string specifying code to retrieve. This will be tried respectively\n as: ranges of input history (see %history for syntax), url,\n corresponding .py file, filename, or an expression evaluating to a\n string or Macro in the user namespace.\n\n If empty string is given, returns complete history of current\n session, without the last line.\n\n raw : bool\n If true (default), retrieve raw history. Has no effect on the other\n retrieval mechanisms.\n\n py_only : bool (default False)\n Only try to fetch python code, do not try alternative methods to decode file\n if unicode fails.\n\n Returns\n -------\n A string of code.\n ValueError is raised if nothing is found, and TypeError if it evaluates\n to an object of another type. In each case, .args[0] is a printable\n message.\n '
code = self.extract_input_lines(target, raw=raw)
if code:
return code
try:
if target.startswith(('http://', 'https://')):
return openpy.read_py_url(target, skip_encoding_cookie=skip_encoding_cookie)
except UnicodeDecodeError as e:
if (not py_only):
from urllib.request import urlopen
response = urlopen(target)
return response.read().decode('latin1')
raise ValueError(("'%s' seem to be unreadable." % target)) from e
potential_target = [target]
try:
potential_target.insert(0, get_py_filename(target))
except IOError:
pass
for tgt in potential_target:
if os.path.isfile(tgt):
try:
return openpy.read_py_file(tgt, skip_encoding_cookie=skip_encoding_cookie)
except UnicodeDecodeError as e:
if (not py_only):
with io_open(tgt, 'r', encoding='latin1') as f:
return f.read()
raise ValueError(("'%s' seem to be unreadable." % target)) from e
elif os.path.isdir(os.path.expanduser(tgt)):
raise ValueError(("'%s' is a directory, not a regular file." % target))
if search_ns:
object_info = self.object_inspect(target, detail_level=1)
if (object_info['found'] and object_info['source']):
return object_info['source']
try:
codeobj = eval(target, self.user_ns)
except Exception as e:
raise ValueError(("'%s' was not found in history, as a file, url, nor in the user namespace." % target)) from e
if isinstance(codeobj, str):
return codeobj
elif isinstance(codeobj, Macro):
return codeobj.value
raise TypeError(('%s is neither a string nor a macro.' % target), codeobj)
|
def _atexit_once(self):
'\n At exist operation that need to be called at most once.\n Second call to this function per instance will do nothing.\n '
if (not getattr(self, '_atexit_once_called', False)):
self._atexit_once_called = True
self.reset(new_session=False)
self.history_manager.end_session()
self.history_manager = None
| -8,122,510,988,338,416,000
|
At exist operation that need to be called at most once.
Second call to this function per instance will do nothing.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
_atexit_once
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def _atexit_once(self):
'\n At exist operation that need to be called at most once.\n Second call to this function per instance will do nothing.\n '
if (not getattr(self, '_atexit_once_called', False)):
self._atexit_once_called = True
self.reset(new_session=False)
self.history_manager.end_session()
self.history_manager = None
|
def atexit_operations(self):
'This will be executed at the time of exit.\n\n Cleanup operations and saving of persistent data that is done\n unconditionally by IPython should be performed here.\n\n For things that may depend on startup flags or platform specifics (such\n as having readline or not), register a separate atexit function in the\n code that has the appropriate information, rather than trying to\n clutter\n '
self._atexit_once()
for tfile in self.tempfiles:
try:
tfile.unlink()
self.tempfiles.remove(tfile)
except FileNotFoundError:
pass
del self.tempfiles
for tdir in self.tempdirs:
try:
tdir.rmdir()
self.tempdirs.remove(tdir)
except FileNotFoundError:
pass
del self.tempdirs
if (hasattr(self, 'editing_mode') and (self.editing_mode == 'vi')):
sys.stdout.write('\x1b[0 q')
sys.stdout.flush()
| -6,097,225,120,271,981,000
|
This will be executed at the time of exit.
Cleanup operations and saving of persistent data that is done
unconditionally by IPython should be performed here.
For things that may depend on startup flags or platform specifics (such
as having readline or not), register a separate atexit function in the
code that has the appropriate information, rather than trying to
clutter
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
atexit_operations
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def atexit_operations(self):
'This will be executed at the time of exit.\n\n Cleanup operations and saving of persistent data that is done\n unconditionally by IPython should be performed here.\n\n For things that may depend on startup flags or platform specifics (such\n as having readline or not), register a separate atexit function in the\n code that has the appropriate information, rather than trying to\n clutter\n '
self._atexit_once()
for tfile in self.tempfiles:
try:
tfile.unlink()
self.tempfiles.remove(tfile)
except FileNotFoundError:
pass
del self.tempfiles
for tdir in self.tempdirs:
try:
tdir.rmdir()
self.tempdirs.remove(tdir)
except FileNotFoundError:
pass
del self.tempdirs
if (hasattr(self, 'editing_mode') and (self.editing_mode == 'vi')):
sys.stdout.write('\x1b[0 q')
sys.stdout.flush()
|
def validate_stb(stb):
'validate structured traceback return type\n\n return type of CustomTB *should* be a list of strings, but allow\n single strings or None, which are harmless.\n\n This function will *always* return a list of strings,\n and will raise a TypeError if stb is inappropriate.\n '
msg = ('CustomTB must return list of strings, not %r' % stb)
if (stb is None):
return []
elif isinstance(stb, str):
return [stb]
elif (not isinstance(stb, list)):
raise TypeError(msg)
for line in stb:
if (not isinstance(line, str)):
raise TypeError(msg)
return stb
| 486,469,157,839,067,000
|
validate structured traceback return type
return type of CustomTB *should* be a list of strings, but allow
single strings or None, which are harmless.
This function will *always* return a list of strings,
and will raise a TypeError if stb is inappropriate.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
validate_stb
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def validate_stb(stb):
'validate structured traceback return type\n\n return type of CustomTB *should* be a list of strings, but allow\n single strings or None, which are harmless.\n\n This function will *always* return a list of strings,\n and will raise a TypeError if stb is inappropriate.\n '
msg = ('CustomTB must return list of strings, not %r' % stb)
if (stb is None):
return []
elif isinstance(stb, str):
return [stb]
elif (not isinstance(stb, list)):
raise TypeError(msg)
for line in stb:
if (not isinstance(line, str)):
raise TypeError(msg)
return stb
|
def get_cells():
'generator for sequence of code blocks to run'
if (fname.suffix == '.ipynb'):
from nbformat import read
nb = read(fname, as_version=4)
if (not nb.cells):
return
for cell in nb.cells:
if (cell.cell_type == 'code'):
(yield cell.source)
else:
(yield fname.read_text(encoding='utf-8'))
| -549,812,894,118,021,060
|
generator for sequence of code blocks to run
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
get_cells
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def get_cells():
if (fname.suffix == '.ipynb'):
from nbformat import read
nb = read(fname, as_version=4)
if (not nb.cells):
return
for cell in nb.cells:
if (cell.cell_type == 'code'):
(yield cell.source)
else:
(yield fname.read_text(encoding='utf-8'))
|
def wrapped(self, etype, value, tb, tb_offset=None):
'wrap CustomTB handler, to protect IPython from user code\n\n This makes it harder (but not impossible) for custom exception\n handlers to crash IPython.\n '
try:
stb = handler(self, etype, value, tb, tb_offset=tb_offset)
return validate_stb(stb)
except:
self.set_custom_exc((), None)
print('Custom TB Handler failed, unregistering', file=sys.stderr)
stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
print(self.InteractiveTB.stb2text(stb))
print('The original exception:')
stb = self.InteractiveTB.structured_traceback((etype, value, tb), tb_offset=tb_offset)
return stb
| -5,198,393,339,466,821,000
|
wrap CustomTB handler, to protect IPython from user code
This makes it harder (but not impossible) for custom exception
handlers to crash IPython.
|
venv/lib/python3.9/site-packages/IPython/core/interactiveshell.py
|
wrapped
|
CMU-IDS-2022/final-project-the-evaluators
|
python
|
def wrapped(self, etype, value, tb, tb_offset=None):
'wrap CustomTB handler, to protect IPython from user code\n\n This makes it harder (but not impossible) for custom exception\n handlers to crash IPython.\n '
try:
stb = handler(self, etype, value, tb, tb_offset=tb_offset)
return validate_stb(stb)
except:
self.set_custom_exc((), None)
print('Custom TB Handler failed, unregistering', file=sys.stderr)
stb = self.InteractiveTB.structured_traceback(*sys.exc_info())
print(self.InteractiveTB.stb2text(stb))
print('The original exception:')
stb = self.InteractiveTB.structured_traceback((etype, value, tb), tb_offset=tb_offset)
return stb
|
def __init__(self, **kwargs):
'\n Initializes a new CreateDeploymentDetails object with values from keyword arguments. This class has the following subclasses and if you are using this class as input\n to a service operations then you should favor using a subclass over the base class:\n\n * :class:`~oci.devops.models.CreateDeployPipelineRedeploymentDetails`\n * :class:`~oci.devops.models.CreateDeployPipelineDeploymentDetails`\n * :class:`~oci.devops.models.CreateSingleDeployStageDeploymentDetails`\n\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param deploy_pipeline_id:\n The value to assign to the deploy_pipeline_id property of this CreateDeploymentDetails.\n :type deploy_pipeline_id: str\n\n :param deployment_type:\n The value to assign to the deployment_type property of this CreateDeploymentDetails.\n :type deployment_type: str\n\n :param display_name:\n The value to assign to the display_name property of this CreateDeploymentDetails.\n :type display_name: str\n\n :param freeform_tags:\n The value to assign to the freeform_tags property of this CreateDeploymentDetails.\n :type freeform_tags: dict(str, str)\n\n :param defined_tags:\n The value to assign to the defined_tags property of this CreateDeploymentDetails.\n :type defined_tags: dict(str, dict(str, object))\n\n '
self.swagger_types = {'deploy_pipeline_id': 'str', 'deployment_type': 'str', 'display_name': 'str', 'freeform_tags': 'dict(str, str)', 'defined_tags': 'dict(str, dict(str, object))'}
self.attribute_map = {'deploy_pipeline_id': 'deployPipelineId', 'deployment_type': 'deploymentType', 'display_name': 'displayName', 'freeform_tags': 'freeformTags', 'defined_tags': 'definedTags'}
self._deploy_pipeline_id = None
self._deployment_type = None
self._display_name = None
self._freeform_tags = None
self._defined_tags = None
| -309,434,075,974,912,200
|
Initializes a new CreateDeploymentDetails object with values from keyword arguments. This class has the following subclasses and if you are using this class as input
to a service operations then you should favor using a subclass over the base class:
* :class:`~oci.devops.models.CreateDeployPipelineRedeploymentDetails`
* :class:`~oci.devops.models.CreateDeployPipelineDeploymentDetails`
* :class:`~oci.devops.models.CreateSingleDeployStageDeploymentDetails`
The following keyword arguments are supported (corresponding to the getters/setters of this class):
:param deploy_pipeline_id:
The value to assign to the deploy_pipeline_id property of this CreateDeploymentDetails.
:type deploy_pipeline_id: str
:param deployment_type:
The value to assign to the deployment_type property of this CreateDeploymentDetails.
:type deployment_type: str
:param display_name:
The value to assign to the display_name property of this CreateDeploymentDetails.
:type display_name: str
:param freeform_tags:
The value to assign to the freeform_tags property of this CreateDeploymentDetails.
:type freeform_tags: dict(str, str)
:param defined_tags:
The value to assign to the defined_tags property of this CreateDeploymentDetails.
:type defined_tags: dict(str, dict(str, object))
|
src/oci/devops/models/create_deployment_details.py
|
__init__
|
LaudateCorpus1/oci-python-sdk
|
python
|
def __init__(self, **kwargs):
'\n Initializes a new CreateDeploymentDetails object with values from keyword arguments. This class has the following subclasses and if you are using this class as input\n to a service operations then you should favor using a subclass over the base class:\n\n * :class:`~oci.devops.models.CreateDeployPipelineRedeploymentDetails`\n * :class:`~oci.devops.models.CreateDeployPipelineDeploymentDetails`\n * :class:`~oci.devops.models.CreateSingleDeployStageDeploymentDetails`\n\n The following keyword arguments are supported (corresponding to the getters/setters of this class):\n\n :param deploy_pipeline_id:\n The value to assign to the deploy_pipeline_id property of this CreateDeploymentDetails.\n :type deploy_pipeline_id: str\n\n :param deployment_type:\n The value to assign to the deployment_type property of this CreateDeploymentDetails.\n :type deployment_type: str\n\n :param display_name:\n The value to assign to the display_name property of this CreateDeploymentDetails.\n :type display_name: str\n\n :param freeform_tags:\n The value to assign to the freeform_tags property of this CreateDeploymentDetails.\n :type freeform_tags: dict(str, str)\n\n :param defined_tags:\n The value to assign to the defined_tags property of this CreateDeploymentDetails.\n :type defined_tags: dict(str, dict(str, object))\n\n '
self.swagger_types = {'deploy_pipeline_id': 'str', 'deployment_type': 'str', 'display_name': 'str', 'freeform_tags': 'dict(str, str)', 'defined_tags': 'dict(str, dict(str, object))'}
self.attribute_map = {'deploy_pipeline_id': 'deployPipelineId', 'deployment_type': 'deploymentType', 'display_name': 'displayName', 'freeform_tags': 'freeformTags', 'defined_tags': 'definedTags'}
self._deploy_pipeline_id = None
self._deployment_type = None
self._display_name = None
self._freeform_tags = None
self._defined_tags = None
|
@staticmethod
def get_subtype(object_dictionary):
'\n Given the hash representation of a subtype of this class,\n use the info in the hash to return the class of the subtype.\n '
type = object_dictionary['deploymentType']
if (type == 'PIPELINE_REDEPLOYMENT'):
return 'CreateDeployPipelineRedeploymentDetails'
if (type == 'PIPELINE_DEPLOYMENT'):
return 'CreateDeployPipelineDeploymentDetails'
if (type == 'SINGLE_STAGE_DEPLOYMENT'):
return 'CreateSingleDeployStageDeploymentDetails'
else:
return 'CreateDeploymentDetails'
| -6,539,959,657,786,444,000
|
Given the hash representation of a subtype of this class,
use the info in the hash to return the class of the subtype.
|
src/oci/devops/models/create_deployment_details.py
|
get_subtype
|
LaudateCorpus1/oci-python-sdk
|
python
|
@staticmethod
def get_subtype(object_dictionary):
'\n Given the hash representation of a subtype of this class,\n use the info in the hash to return the class of the subtype.\n '
type = object_dictionary['deploymentType']
if (type == 'PIPELINE_REDEPLOYMENT'):
return 'CreateDeployPipelineRedeploymentDetails'
if (type == 'PIPELINE_DEPLOYMENT'):
return 'CreateDeployPipelineDeploymentDetails'
if (type == 'SINGLE_STAGE_DEPLOYMENT'):
return 'CreateSingleDeployStageDeploymentDetails'
else:
return 'CreateDeploymentDetails'
|
@property
def deploy_pipeline_id(self):
'\n **[Required]** Gets the deploy_pipeline_id of this CreateDeploymentDetails.\n The OCID of a pipeline.\n\n\n :return: The deploy_pipeline_id of this CreateDeploymentDetails.\n :rtype: str\n '
return self._deploy_pipeline_id
| 2,970,132,885,694,584,300
|
**[Required]** Gets the deploy_pipeline_id of this CreateDeploymentDetails.
The OCID of a pipeline.
:return: The deploy_pipeline_id of this CreateDeploymentDetails.
:rtype: str
|
src/oci/devops/models/create_deployment_details.py
|
deploy_pipeline_id
|
LaudateCorpus1/oci-python-sdk
|
python
|
@property
def deploy_pipeline_id(self):
'\n **[Required]** Gets the deploy_pipeline_id of this CreateDeploymentDetails.\n The OCID of a pipeline.\n\n\n :return: The deploy_pipeline_id of this CreateDeploymentDetails.\n :rtype: str\n '
return self._deploy_pipeline_id
|
@deploy_pipeline_id.setter
def deploy_pipeline_id(self, deploy_pipeline_id):
'\n Sets the deploy_pipeline_id of this CreateDeploymentDetails.\n The OCID of a pipeline.\n\n\n :param deploy_pipeline_id: The deploy_pipeline_id of this CreateDeploymentDetails.\n :type: str\n '
self._deploy_pipeline_id = deploy_pipeline_id
| 4,832,613,191,838,614,000
|
Sets the deploy_pipeline_id of this CreateDeploymentDetails.
The OCID of a pipeline.
:param deploy_pipeline_id: The deploy_pipeline_id of this CreateDeploymentDetails.
:type: str
|
src/oci/devops/models/create_deployment_details.py
|
deploy_pipeline_id
|
LaudateCorpus1/oci-python-sdk
|
python
|
@deploy_pipeline_id.setter
def deploy_pipeline_id(self, deploy_pipeline_id):
'\n Sets the deploy_pipeline_id of this CreateDeploymentDetails.\n The OCID of a pipeline.\n\n\n :param deploy_pipeline_id: The deploy_pipeline_id of this CreateDeploymentDetails.\n :type: str\n '
self._deploy_pipeline_id = deploy_pipeline_id
|
@property
def deployment_type(self):
'\n **[Required]** Gets the deployment_type of this CreateDeploymentDetails.\n Specifies type for this deployment.\n\n\n :return: The deployment_type of this CreateDeploymentDetails.\n :rtype: str\n '
return self._deployment_type
| -6,515,815,640,178,701,000
|
**[Required]** Gets the deployment_type of this CreateDeploymentDetails.
Specifies type for this deployment.
:return: The deployment_type of this CreateDeploymentDetails.
:rtype: str
|
src/oci/devops/models/create_deployment_details.py
|
deployment_type
|
LaudateCorpus1/oci-python-sdk
|
python
|
@property
def deployment_type(self):
'\n **[Required]** Gets the deployment_type of this CreateDeploymentDetails.\n Specifies type for this deployment.\n\n\n :return: The deployment_type of this CreateDeploymentDetails.\n :rtype: str\n '
return self._deployment_type
|
@deployment_type.setter
def deployment_type(self, deployment_type):
'\n Sets the deployment_type of this CreateDeploymentDetails.\n Specifies type for this deployment.\n\n\n :param deployment_type: The deployment_type of this CreateDeploymentDetails.\n :type: str\n '
self._deployment_type = deployment_type
| -7,926,560,362,652,776,000
|
Sets the deployment_type of this CreateDeploymentDetails.
Specifies type for this deployment.
:param deployment_type: The deployment_type of this CreateDeploymentDetails.
:type: str
|
src/oci/devops/models/create_deployment_details.py
|
deployment_type
|
LaudateCorpus1/oci-python-sdk
|
python
|
@deployment_type.setter
def deployment_type(self, deployment_type):
'\n Sets the deployment_type of this CreateDeploymentDetails.\n Specifies type for this deployment.\n\n\n :param deployment_type: The deployment_type of this CreateDeploymentDetails.\n :type: str\n '
self._deployment_type = deployment_type
|
@property
def display_name(self):
'\n Gets the display_name of this CreateDeploymentDetails.\n Deployment display name. Avoid entering confidential information.\n\n\n :return: The display_name of this CreateDeploymentDetails.\n :rtype: str\n '
return self._display_name
| 7,800,112,571,215,726,000
|
Gets the display_name of this CreateDeploymentDetails.
Deployment display name. Avoid entering confidential information.
:return: The display_name of this CreateDeploymentDetails.
:rtype: str
|
src/oci/devops/models/create_deployment_details.py
|
display_name
|
LaudateCorpus1/oci-python-sdk
|
python
|
@property
def display_name(self):
'\n Gets the display_name of this CreateDeploymentDetails.\n Deployment display name. Avoid entering confidential information.\n\n\n :return: The display_name of this CreateDeploymentDetails.\n :rtype: str\n '
return self._display_name
|
@display_name.setter
def display_name(self, display_name):
'\n Sets the display_name of this CreateDeploymentDetails.\n Deployment display name. Avoid entering confidential information.\n\n\n :param display_name: The display_name of this CreateDeploymentDetails.\n :type: str\n '
self._display_name = display_name
| -526,943,438,164,516,160
|
Sets the display_name of this CreateDeploymentDetails.
Deployment display name. Avoid entering confidential information.
:param display_name: The display_name of this CreateDeploymentDetails.
:type: str
|
src/oci/devops/models/create_deployment_details.py
|
display_name
|
LaudateCorpus1/oci-python-sdk
|
python
|
@display_name.setter
def display_name(self, display_name):
'\n Sets the display_name of this CreateDeploymentDetails.\n Deployment display name. Avoid entering confidential information.\n\n\n :param display_name: The display_name of this CreateDeploymentDetails.\n :type: str\n '
self._display_name = display_name
|
@property
def freeform_tags(self):
'\n Gets the freeform_tags of this CreateDeploymentDetails.\n Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. See `Resource Tags`__. Example: `{"bar-key": "value"}`\n\n __ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm\n\n\n :return: The freeform_tags of this CreateDeploymentDetails.\n :rtype: dict(str, str)\n '
return self._freeform_tags
| -8,385,194,850,335,849,000
|
Gets the freeform_tags of this CreateDeploymentDetails.
Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. See `Resource Tags`__. Example: `{"bar-key": "value"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The freeform_tags of this CreateDeploymentDetails.
:rtype: dict(str, str)
|
src/oci/devops/models/create_deployment_details.py
|
freeform_tags
|
LaudateCorpus1/oci-python-sdk
|
python
|
@property
def freeform_tags(self):
'\n Gets the freeform_tags of this CreateDeploymentDetails.\n Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. See `Resource Tags`__. Example: `{"bar-key": "value"}`\n\n __ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm\n\n\n :return: The freeform_tags of this CreateDeploymentDetails.\n :rtype: dict(str, str)\n '
return self._freeform_tags
|
@freeform_tags.setter
def freeform_tags(self, freeform_tags):
'\n Sets the freeform_tags of this CreateDeploymentDetails.\n Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. See `Resource Tags`__. Example: `{"bar-key": "value"}`\n\n __ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm\n\n\n :param freeform_tags: The freeform_tags of this CreateDeploymentDetails.\n :type: dict(str, str)\n '
self._freeform_tags = freeform_tags
| 2,248,745,989,496,237,000
|
Sets the freeform_tags of this CreateDeploymentDetails.
Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. See `Resource Tags`__. Example: `{"bar-key": "value"}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param freeform_tags: The freeform_tags of this CreateDeploymentDetails.
:type: dict(str, str)
|
src/oci/devops/models/create_deployment_details.py
|
freeform_tags
|
LaudateCorpus1/oci-python-sdk
|
python
|
@freeform_tags.setter
def freeform_tags(self, freeform_tags):
'\n Sets the freeform_tags of this CreateDeploymentDetails.\n Simple key-value pair that is applied without any predefined name, type or scope. Exists for cross-compatibility only. See `Resource Tags`__. Example: `{"bar-key": "value"}`\n\n __ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm\n\n\n :param freeform_tags: The freeform_tags of this CreateDeploymentDetails.\n :type: dict(str, str)\n '
self._freeform_tags = freeform_tags
|
@property
def defined_tags(self):
'\n Gets the defined_tags of this CreateDeploymentDetails.\n Defined tags for this resource. Each key is predefined and scoped to a namespace. See `Resource Tags`__. Example: `{"foo-namespace": {"bar-key": "value"}}`\n\n __ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm\n\n\n :return: The defined_tags of this CreateDeploymentDetails.\n :rtype: dict(str, dict(str, object))\n '
return self._defined_tags
| -6,455,408,403,173,762,000
|
Gets the defined_tags of this CreateDeploymentDetails.
Defined tags for this resource. Each key is predefined and scoped to a namespace. See `Resource Tags`__. Example: `{"foo-namespace": {"bar-key": "value"}}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:return: The defined_tags of this CreateDeploymentDetails.
:rtype: dict(str, dict(str, object))
|
src/oci/devops/models/create_deployment_details.py
|
defined_tags
|
LaudateCorpus1/oci-python-sdk
|
python
|
@property
def defined_tags(self):
'\n Gets the defined_tags of this CreateDeploymentDetails.\n Defined tags for this resource. Each key is predefined and scoped to a namespace. See `Resource Tags`__. Example: `{"foo-namespace": {"bar-key": "value"}}`\n\n __ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm\n\n\n :return: The defined_tags of this CreateDeploymentDetails.\n :rtype: dict(str, dict(str, object))\n '
return self._defined_tags
|
@defined_tags.setter
def defined_tags(self, defined_tags):
'\n Sets the defined_tags of this CreateDeploymentDetails.\n Defined tags for this resource. Each key is predefined and scoped to a namespace. See `Resource Tags`__. Example: `{"foo-namespace": {"bar-key": "value"}}`\n\n __ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm\n\n\n :param defined_tags: The defined_tags of this CreateDeploymentDetails.\n :type: dict(str, dict(str, object))\n '
self._defined_tags = defined_tags
| 4,476,609,121,983,142,400
|
Sets the defined_tags of this CreateDeploymentDetails.
Defined tags for this resource. Each key is predefined and scoped to a namespace. See `Resource Tags`__. Example: `{"foo-namespace": {"bar-key": "value"}}`
__ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm
:param defined_tags: The defined_tags of this CreateDeploymentDetails.
:type: dict(str, dict(str, object))
|
src/oci/devops/models/create_deployment_details.py
|
defined_tags
|
LaudateCorpus1/oci-python-sdk
|
python
|
@defined_tags.setter
def defined_tags(self, defined_tags):
'\n Sets the defined_tags of this CreateDeploymentDetails.\n Defined tags for this resource. Each key is predefined and scoped to a namespace. See `Resource Tags`__. Example: `{"foo-namespace": {"bar-key": "value"}}`\n\n __ https://docs.cloud.oracle.com/Content/General/Concepts/resourcetags.htm\n\n\n :param defined_tags: The defined_tags of this CreateDeploymentDetails.\n :type: dict(str, dict(str, object))\n '
self._defined_tags = defined_tags
|
def run(self):
'\n This function will the operator\n :return:\n '
try:
self.train()
except KeyboardInterrupt:
self.logger.info('You have entered CTRL+C.. Wait to finalize')
| 7,356,136,057,099,459,000
|
This function will the operator
:return:
|
agents/dqn.py
|
run
|
Cheng-XJTU/Pytorch-Project-Template
|
python
|
def run(self):
'\n This function will the operator\n :return:\n '
try:
self.train()
except KeyboardInterrupt:
self.logger.info('You have entered CTRL+C.. Wait to finalize')
|
def select_action(self, state):
'\n The action selection function, it either uses the model to choose an action or samples one uniformly.\n :param state: current state of the model\n :return:\n '
if self.cuda:
state = state.cuda()
sample = random.random()
eps_threshold = (self.config.eps_start + ((self.config.eps_start - self.config.eps_end) * math.exp((((- 1.0) * self.current_iteration) / self.config.eps_decay))))
self.current_iteration += 1
if (sample > eps_threshold):
with torch.no_grad():
return self.policy_model(state).max(1)[1].view(1, 1)
else:
return torch.tensor([[random.randrange(2)]], device=self.device, dtype=torch.long)
| 7,905,057,826,998,764,000
|
The action selection function, it either uses the model to choose an action or samples one uniformly.
:param state: current state of the model
:return:
|
agents/dqn.py
|
select_action
|
Cheng-XJTU/Pytorch-Project-Template
|
python
|
def select_action(self, state):
'\n The action selection function, it either uses the model to choose an action or samples one uniformly.\n :param state: current state of the model\n :return:\n '
if self.cuda:
state = state.cuda()
sample = random.random()
eps_threshold = (self.config.eps_start + ((self.config.eps_start - self.config.eps_end) * math.exp((((- 1.0) * self.current_iteration) / self.config.eps_decay))))
self.current_iteration += 1
if (sample > eps_threshold):
with torch.no_grad():
return self.policy_model(state).max(1)[1].view(1, 1)
else:
return torch.tensor([[random.randrange(2)]], device=self.device, dtype=torch.long)
|
def optimize_policy_model(self):
'\n performs a single step of optimization for the policy model\n :return:\n '
if (self.memory.length() < self.config.batch_size):
return
transitions = self.memory.sample_batch(self.config.batch_size)
one_batch = Transition(*zip(*transitions))
non_final_mask = torch.tensor(tuple(map((lambda s: (s is not None)), one_batch.next_state)), device=self.device, dtype=torch.uint8)
non_final_next_states = torch.cat([s for s in one_batch.next_state if (s is not None)])
state_batch = torch.cat(one_batch.state)
action_batch = torch.cat(one_batch.action)
reward_batch = torch.cat(one_batch.reward)
state_batch = state_batch.to(self.device)
non_final_next_states = non_final_next_states.to(self.device)
curr_state_values = self.policy_model(state_batch)
curr_state_action_values = curr_state_values.gather(1, action_batch)
next_state_values = torch.zeros(self.config.batch_size, device=self.device)
next_state_values[non_final_mask] = self.target_model(non_final_next_states).max(1)[0].detach()
expected_state_action_values = ((next_state_values * self.config.gamma) + reward_batch)
loss = self.loss(curr_state_action_values, expected_state_action_values.unsqueeze(1))
self.optim.zero_grad()
loss.backward()
for param in self.policy_model.parameters():
param.grad.data.clamp_((- 1), 1)
self.optim.step()
return loss
| -4,843,540,720,220,526,000
|
performs a single step of optimization for the policy model
:return:
|
agents/dqn.py
|
optimize_policy_model
|
Cheng-XJTU/Pytorch-Project-Template
|
python
|
def optimize_policy_model(self):
'\n performs a single step of optimization for the policy model\n :return:\n '
if (self.memory.length() < self.config.batch_size):
return
transitions = self.memory.sample_batch(self.config.batch_size)
one_batch = Transition(*zip(*transitions))
non_final_mask = torch.tensor(tuple(map((lambda s: (s is not None)), one_batch.next_state)), device=self.device, dtype=torch.uint8)
non_final_next_states = torch.cat([s for s in one_batch.next_state if (s is not None)])
state_batch = torch.cat(one_batch.state)
action_batch = torch.cat(one_batch.action)
reward_batch = torch.cat(one_batch.reward)
state_batch = state_batch.to(self.device)
non_final_next_states = non_final_next_states.to(self.device)
curr_state_values = self.policy_model(state_batch)
curr_state_action_values = curr_state_values.gather(1, action_batch)
next_state_values = torch.zeros(self.config.batch_size, device=self.device)
next_state_values[non_final_mask] = self.target_model(non_final_next_states).max(1)[0].detach()
expected_state_action_values = ((next_state_values * self.config.gamma) + reward_batch)
loss = self.loss(curr_state_action_values, expected_state_action_values.unsqueeze(1))
self.optim.zero_grad()
loss.backward()
for param in self.policy_model.parameters():
param.grad.data.clamp_((- 1), 1)
self.optim.step()
return loss
|
def train(self):
'\n Training loop based on the number of episodes\n :return:\n '
for episode in tqdm(range(self.current_episode, self.config.num_episodes)):
self.current_episode = episode
self.env.reset()
self.train_one_epoch()
if ((self.current_episode % self.config.target_update) == 0):
self.target_model.load_state_dict(self.policy_model.state_dict())
self.env.render()
self.env.close()
| 2,446,242,519,018,561,500
|
Training loop based on the number of episodes
:return:
|
agents/dqn.py
|
train
|
Cheng-XJTU/Pytorch-Project-Template
|
python
|
def train(self):
'\n Training loop based on the number of episodes\n :return:\n '
for episode in tqdm(range(self.current_episode, self.config.num_episodes)):
self.current_episode = episode
self.env.reset()
self.train_one_epoch()
if ((self.current_episode % self.config.target_update) == 0):
self.target_model.load_state_dict(self.policy_model.state_dict())
self.env.render()
self.env.close()
|
def train_one_epoch(self):
'\n One episode of training; it samples an action, observe next screen and optimize the model once\n :return:\n '
episode_duration = 0
prev_frame = self.cartpole.get_screen(self.env)
curr_frame = self.cartpole.get_screen(self.env)
curr_state = (curr_frame - prev_frame)
while 1:
episode_duration += 1
action = self.select_action(curr_state)
(_, reward, done, _) = self.env.step(action.item())
if self.cuda:
reward = torch.Tensor([reward]).to(self.device)
else:
reward = torch.Tensor([reward]).to(self.device)
prev_frame = curr_frame
curr_frame = self.cartpole.get_screen(self.env)
if done:
next_state = None
else:
next_state = (curr_frame - prev_frame)
self.memory.push_transition(curr_state, action, next_state, reward)
curr_state = next_state
curr_loss = self.optimize_policy_model()
if (curr_loss is not None):
if self.cuda:
curr_loss = curr_loss.cpu()
self.summary_writer.add_scalar('Temporal_Difference_Loss', curr_loss.detach().numpy(), self.current_iteration)
if done:
break
self.summary_writer.add_scalar('Training_Episode_Duration', episode_duration, self.current_episode)
| -4,751,008,977,623,283,000
|
One episode of training; it samples an action, observe next screen and optimize the model once
:return:
|
agents/dqn.py
|
train_one_epoch
|
Cheng-XJTU/Pytorch-Project-Template
|
python
|
def train_one_epoch(self):
'\n One episode of training; it samples an action, observe next screen and optimize the model once\n :return:\n '
episode_duration = 0
prev_frame = self.cartpole.get_screen(self.env)
curr_frame = self.cartpole.get_screen(self.env)
curr_state = (curr_frame - prev_frame)
while 1:
episode_duration += 1
action = self.select_action(curr_state)
(_, reward, done, _) = self.env.step(action.item())
if self.cuda:
reward = torch.Tensor([reward]).to(self.device)
else:
reward = torch.Tensor([reward]).to(self.device)
prev_frame = curr_frame
curr_frame = self.cartpole.get_screen(self.env)
if done:
next_state = None
else:
next_state = (curr_frame - prev_frame)
self.memory.push_transition(curr_state, action, next_state, reward)
curr_state = next_state
curr_loss = self.optimize_policy_model()
if (curr_loss is not None):
if self.cuda:
curr_loss = curr_loss.cpu()
self.summary_writer.add_scalar('Temporal_Difference_Loss', curr_loss.detach().numpy(), self.current_iteration)
if done:
break
self.summary_writer.add_scalar('Training_Episode_Duration', episode_duration, self.current_episode)
|
def finalize(self):
'\n Finalize all the operations of the 2 Main classes of the process the operator and the data loader\n :return:\n '
self.logger.info('Please wait while finalizing the operation.. Thank you')
self.save_checkpoint()
self.summary_writer.export_scalars_to_json('{}all_scalars.json'.format(self.config.summary_dir))
self.summary_writer.close()
| -6,417,006,202,863,603,000
|
Finalize all the operations of the 2 Main classes of the process the operator and the data loader
:return:
|
agents/dqn.py
|
finalize
|
Cheng-XJTU/Pytorch-Project-Template
|
python
|
def finalize(self):
'\n Finalize all the operations of the 2 Main classes of the process the operator and the data loader\n :return:\n '
self.logger.info('Please wait while finalizing the operation.. Thank you')
self.save_checkpoint()
self.summary_writer.export_scalars_to_json('{}all_scalars.json'.format(self.config.summary_dir))
self.summary_writer.close()
|
def yaml_format(obj, indent=0):
'\n Pretty formats the given object as a YAML string which is returned.\n (based on TLObject.pretty_format)\n '
result = []
if isinstance(obj, TLObject):
obj = obj.to_dict()
if isinstance(obj, dict):
result.append((obj.get('_', 'dict') + ':'))
if obj:
items = obj.items()
has_multiple_items = (len(items) > 2)
if has_multiple_items:
result.append('\n')
indent += 2
for (k, v) in items:
if ((k == '_') or (v is None)):
continue
formatted = yaml_format(v, indent)
if (not formatted.strip()):
continue
result.append((' ' * (indent if has_multiple_items else 1)))
result.append(f'{k}: {formatted}')
result.append('\n')
result.pop()
indent -= 2
result.append((' ' * indent))
elif isinstance(obj, str):
result.append(repr(obj[:STR_LEN_MAX]))
if (len(obj) > STR_LEN_MAX):
result.append('…')
elif isinstance(obj, bytes):
if all(((c in PRINTABLE_SET) for c in obj)):
result.append(repr(obj))
elif (len(obj) > BYTE_LEN_MAX):
result.append('<…>')
else:
result.append(' '.join((f'{b:02X}' for b in obj)))
elif isinstance(obj, datetime.datetime):
result.append(obj.strftime('%Y-%m-%d %H:%M:%S'))
elif hasattr(obj, '__iter__'):
result.append('\n')
indent += 2
for x in obj:
result.append((' ' * indent))
result.append(yaml_format(x, indent))
result.append('\n')
result.pop()
indent -= 2
result.append((' ' * indent))
else:
result.append(repr(obj))
return ''.join(result)
| -3,753,146,974,282,035,000
|
Pretty formats the given object as a YAML string which is returned.
(based on TLObject.pretty_format)
|
userbot/plugins/new.py
|
yaml_format
|
Abhiramabr/weaponx
|
python
|
def yaml_format(obj, indent=0):
'\n Pretty formats the given object as a YAML string which is returned.\n (based on TLObject.pretty_format)\n '
result = []
if isinstance(obj, TLObject):
obj = obj.to_dict()
if isinstance(obj, dict):
result.append((obj.get('_', 'dict') + ':'))
if obj:
items = obj.items()
has_multiple_items = (len(items) > 2)
if has_multiple_items:
result.append('\n')
indent += 2
for (k, v) in items:
if ((k == '_') or (v is None)):
continue
formatted = yaml_format(v, indent)
if (not formatted.strip()):
continue
result.append((' ' * (indent if has_multiple_items else 1)))
result.append(f'{k}: {formatted}')
result.append('\n')
result.pop()
indent -= 2
result.append((' ' * indent))
elif isinstance(obj, str):
result.append(repr(obj[:STR_LEN_MAX]))
if (len(obj) > STR_LEN_MAX):
result.append('…')
elif isinstance(obj, bytes):
if all(((c in PRINTABLE_SET) for c in obj)):
result.append(repr(obj))
elif (len(obj) > BYTE_LEN_MAX):
result.append('<…>')
else:
result.append(' '.join((f'{b:02X}' for b in obj)))
elif isinstance(obj, datetime.datetime):
result.append(obj.strftime('%Y-%m-%d %H:%M:%S'))
elif hasattr(obj, '__iter__'):
result.append('\n')
indent += 2
for x in obj:
result.append((' ' * indent))
result.append(yaml_format(x, indent))
result.append('\n')
result.pop()
indent -= 2
result.append((' ' * indent))
else:
result.append(repr(obj))
return .join(result)
|
def __init__(self, client=None, **kwargs):
'\n Initialize new LabelBinarizer instance\n\n Parameters\n ----------\n client : dask.Client optional client to use\n kwargs : dict of arguments to proxy to underlying single-process\n LabelBinarizer\n '
self.client_ = (client if (client is not None) else default_client())
self.kwargs = kwargs
if (('sparse_output' in self.kwargs) and (self.kwargs['sparse_output'] is True)):
raise ValueError('Sparse output not yet supported in distributed mode')
| -5,744,651,490,407,949,000
|
Initialize new LabelBinarizer instance
Parameters
----------
client : dask.Client optional client to use
kwargs : dict of arguments to proxy to underlying single-process
LabelBinarizer
|
python/cuml/dask/preprocessing/label.py
|
__init__
|
Chetank99/cuml
|
python
|
def __init__(self, client=None, **kwargs):
'\n Initialize new LabelBinarizer instance\n\n Parameters\n ----------\n client : dask.Client optional client to use\n kwargs : dict of arguments to proxy to underlying single-process\n LabelBinarizer\n '
self.client_ = (client if (client is not None) else default_client())
self.kwargs = kwargs
if (('sparse_output' in self.kwargs) and (self.kwargs['sparse_output'] is True)):
raise ValueError('Sparse output not yet supported in distributed mode')
|
def fit(self, y):
'Fit label binarizer\n\n Parameters\n ----------\n y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]\n chunked by row.\n Target values. The 2-d matrix should only contain 0 and 1,\n represents multilabel classification.\n\n Returns\n -------\n self : returns an instance of self.\n '
futures = self.client_.sync(_extract_partitions, y)
unique = [self.client_.submit(LabelBinarizer._func_unique_classes, f) for (w, f) in futures]
classes = self.client_.compute(unique, True)
self.classes_ = rmm_cupy_ary(cp.unique, rmm_cupy_ary(cp.stack, classes, axis=0))
self.model = LB(**self.kwargs).fit(self.classes_)
return self
| 4,554,579,472,936,627,700
|
Fit label binarizer
Parameters
----------
y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]
chunked by row.
Target values. The 2-d matrix should only contain 0 and 1,
represents multilabel classification.
Returns
-------
self : returns an instance of self.
|
python/cuml/dask/preprocessing/label.py
|
fit
|
Chetank99/cuml
|
python
|
def fit(self, y):
'Fit label binarizer\n\n Parameters\n ----------\n y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]\n chunked by row.\n Target values. The 2-d matrix should only contain 0 and 1,\n represents multilabel classification.\n\n Returns\n -------\n self : returns an instance of self.\n '
futures = self.client_.sync(_extract_partitions, y)
unique = [self.client_.submit(LabelBinarizer._func_unique_classes, f) for (w, f) in futures]
classes = self.client_.compute(unique, True)
self.classes_ = rmm_cupy_ary(cp.unique, rmm_cupy_ary(cp.stack, classes, axis=0))
self.model = LB(**self.kwargs).fit(self.classes_)
return self
|
def fit_transform(self, y):
'\n Fit the label encoder and return transformed labels\n\n Parameters\n ----------\n y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]\n target values. The 2-d matrix should only contain 0 and 1,\n represents multilabel classification.\n\n Returns\n -------\n\n arr : Dask.Array backed by CuPy arrays containing encoded labels\n '
return self.fit(y).transform(y)
| 3,604,221,344,484,529,000
|
Fit the label encoder and return transformed labels
Parameters
----------
y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]
target values. The 2-d matrix should only contain 0 and 1,
represents multilabel classification.
Returns
-------
arr : Dask.Array backed by CuPy arrays containing encoded labels
|
python/cuml/dask/preprocessing/label.py
|
fit_transform
|
Chetank99/cuml
|
python
|
def fit_transform(self, y):
'\n Fit the label encoder and return transformed labels\n\n Parameters\n ----------\n y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]\n target values. The 2-d matrix should only contain 0 and 1,\n represents multilabel classification.\n\n Returns\n -------\n\n arr : Dask.Array backed by CuPy arrays containing encoded labels\n '
return self.fit(y).transform(y)
|
def transform(self, y):
'\n Transform and return encoded labels\n\n Parameters\n ----------\n y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]\n\n Returns\n -------\n\n arr : Dask.Array backed by CuPy arrays containing encoded labels\n '
parts = self.client_.sync(_extract_partitions, y)
xform_func = dask.delayed(LabelBinarizer._func_xform)
meta = rmm_cupy_ary(cp.zeros, 1)
if self.model.sparse_output:
meta = cp.sparse.csr_matrix(meta)
f = [dask.array.from_delayed(xform_func(self.model, part), meta=meta, dtype=cp.float32, shape=(len(y), len(self.classes_))) for (w, part) in parts]
arr = dask.array.asarray(f)
return arr.reshape(arr.shape[1:])
| -3,579,742,699,241,133,000
|
Transform and return encoded labels
Parameters
----------
y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]
Returns
-------
arr : Dask.Array backed by CuPy arrays containing encoded labels
|
python/cuml/dask/preprocessing/label.py
|
transform
|
Chetank99/cuml
|
python
|
def transform(self, y):
'\n Transform and return encoded labels\n\n Parameters\n ----------\n y : Dask.Array of shape [n_samples,] or [n_samples, n_classes]\n\n Returns\n -------\n\n arr : Dask.Array backed by CuPy arrays containing encoded labels\n '
parts = self.client_.sync(_extract_partitions, y)
xform_func = dask.delayed(LabelBinarizer._func_xform)
meta = rmm_cupy_ary(cp.zeros, 1)
if self.model.sparse_output:
meta = cp.sparse.csr_matrix(meta)
f = [dask.array.from_delayed(xform_func(self.model, part), meta=meta, dtype=cp.float32, shape=(len(y), len(self.classes_))) for (w, part) in parts]
arr = dask.array.asarray(f)
return arr.reshape(arr.shape[1:])
|
def inverse_transform(self, y, threshold=None):
'\n Invert a set of encoded labels back to original labels\n\n Parameters\n ----------\n\n y : Dask.Array of shape [n_samples, n_classes] containing encoded\n labels\n\n threshold : float This value is currently ignored\n\n Returns\n -------\n\n arr : Dask.Array backed by CuPy arrays containing original labels\n '
parts = self.client_.sync(_extract_partitions, y)
inv_func = dask.delayed(LabelBinarizer._func_inv_xform)
dtype = self.classes_.dtype
meta = rmm_cupy_ary(cp.zeros, 1, dtype=dtype)
f = [dask.array.from_delayed(inv_func(self.model, part, threshold), dtype=dtype, shape=(y.shape[0],), meta=meta) for (w, part) in parts]
ret = dask.array.stack(f, axis=0)
return ret.reshape(ret.shape[1:])
| 1,216,885,461,147,947,500
|
Invert a set of encoded labels back to original labels
Parameters
----------
y : Dask.Array of shape [n_samples, n_classes] containing encoded
labels
threshold : float This value is currently ignored
Returns
-------
arr : Dask.Array backed by CuPy arrays containing original labels
|
python/cuml/dask/preprocessing/label.py
|
inverse_transform
|
Chetank99/cuml
|
python
|
def inverse_transform(self, y, threshold=None):
'\n Invert a set of encoded labels back to original labels\n\n Parameters\n ----------\n\n y : Dask.Array of shape [n_samples, n_classes] containing encoded\n labels\n\n threshold : float This value is currently ignored\n\n Returns\n -------\n\n arr : Dask.Array backed by CuPy arrays containing original labels\n '
parts = self.client_.sync(_extract_partitions, y)
inv_func = dask.delayed(LabelBinarizer._func_inv_xform)
dtype = self.classes_.dtype
meta = rmm_cupy_ary(cp.zeros, 1, dtype=dtype)
f = [dask.array.from_delayed(inv_func(self.model, part, threshold), dtype=dtype, shape=(y.shape[0],), meta=meta) for (w, part) in parts]
ret = dask.array.stack(f, axis=0)
return ret.reshape(ret.shape[1:])
|
def CheckVintfFromExtractedTargetFiles(input_tmp, info_dict=None):
'\n Checks VINTF metadata of an extracted target files directory.\n\n Args:\n inp: path to the directory that contains the extracted target files archive.\n info_dict: The build-time info dict. If None, it will be loaded from inp.\n\n Returns:\n True if VINTF check is skipped or compatible, False if incompatible. Raise\n a RuntimeError if any error occurs.\n '
if (info_dict is None):
info_dict = common.LoadInfoDict(input_tmp)
if (info_dict.get('vintf_enforce') != 'true'):
logger.warning('PRODUCT_ENFORCE_VINTF_MANIFEST is not set, skipping checks')
return True
dirmap = GetDirmap(input_tmp)
args_for_skus = GetArgsForSkus(info_dict)
shipping_api_level_args = GetArgsForShippingApiLevel(info_dict)
kernel_args = GetArgsForKernel(input_tmp)
common_command = ['checkvintf', '--check-compat']
for (device_path, real_path) in dirmap.items():
common_command += ['--dirmap', '{}:{}'.format(device_path, real_path)]
common_command += kernel_args
common_command += shipping_api_level_args
success = True
for sku_args in args_for_skus:
command = (common_command + sku_args)
proc = common.Run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = proc.communicate()
if (proc.returncode == 0):
logger.info("Command `%s` returns 'compatible'", ' '.join(command))
elif (out.strip() == 'INCOMPATIBLE'):
logger.info("Command `%s` returns 'incompatible'", ' '.join(command))
success = False
else:
raise common.ExternalError("Failed to run command '{}' (exit code {}):\nstdout:{}\nstderr:{}".format(' '.join(command), proc.returncode, out, err))
logger.info('stdout: %s', out)
logger.info('stderr: %s', err)
return success
| 4,769,477,838,048,067,000
|
Checks VINTF metadata of an extracted target files directory.
Args:
inp: path to the directory that contains the extracted target files archive.
info_dict: The build-time info dict. If None, it will be loaded from inp.
Returns:
True if VINTF check is skipped or compatible, False if incompatible. Raise
a RuntimeError if any error occurs.
|
tools/check_target_files_vintf.py
|
CheckVintfFromExtractedTargetFiles
|
FabriSC/Alioth-SC
|
python
|
def CheckVintfFromExtractedTargetFiles(input_tmp, info_dict=None):
'\n Checks VINTF metadata of an extracted target files directory.\n\n Args:\n inp: path to the directory that contains the extracted target files archive.\n info_dict: The build-time info dict. If None, it will be loaded from inp.\n\n Returns:\n True if VINTF check is skipped or compatible, False if incompatible. Raise\n a RuntimeError if any error occurs.\n '
if (info_dict is None):
info_dict = common.LoadInfoDict(input_tmp)
if (info_dict.get('vintf_enforce') != 'true'):
logger.warning('PRODUCT_ENFORCE_VINTF_MANIFEST is not set, skipping checks')
return True
dirmap = GetDirmap(input_tmp)
args_for_skus = GetArgsForSkus(info_dict)
shipping_api_level_args = GetArgsForShippingApiLevel(info_dict)
kernel_args = GetArgsForKernel(input_tmp)
common_command = ['checkvintf', '--check-compat']
for (device_path, real_path) in dirmap.items():
common_command += ['--dirmap', '{}:{}'.format(device_path, real_path)]
common_command += kernel_args
common_command += shipping_api_level_args
success = True
for sku_args in args_for_skus:
command = (common_command + sku_args)
proc = common.Run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
(out, err) = proc.communicate()
if (proc.returncode == 0):
logger.info("Command `%s` returns 'compatible'", ' '.join(command))
elif (out.strip() == 'INCOMPATIBLE'):
logger.info("Command `%s` returns 'incompatible'", ' '.join(command))
success = False
else:
raise common.ExternalError("Failed to run command '{}' (exit code {}):\nstdout:{}\nstderr:{}".format(' '.join(command), proc.returncode, out, err))
logger.info('stdout: %s', out)
logger.info('stderr: %s', err)
return success
|
def GetVintfFileList():
'\n Returns a list of VINTF metadata files that should be read from a target files\n package before executing checkvintf.\n '
def PathToPatterns(path):
if (path[(- 1)] == '/'):
path += '*'
for (device_path, target_files_rel_paths) in DIR_SEARCH_PATHS.items():
if path.startswith(device_path):
suffix = path[len(device_path):]
return [(rel_path + suffix) for rel_path in target_files_rel_paths]
raise RuntimeError(('Unrecognized path from checkvintf --dump-file-list: ' + path))
out = common.RunAndCheckOutput(['checkvintf', '--dump-file-list'])
paths = out.strip().split('\n')
paths = sum((PathToPatterns(path) for path in paths if path), [])
return paths
| -5,216,986,879,498,238,000
|
Returns a list of VINTF metadata files that should be read from a target files
package before executing checkvintf.
|
tools/check_target_files_vintf.py
|
GetVintfFileList
|
FabriSC/Alioth-SC
|
python
|
def GetVintfFileList():
'\n Returns a list of VINTF metadata files that should be read from a target files\n package before executing checkvintf.\n '
def PathToPatterns(path):
if (path[(- 1)] == '/'):
path += '*'
for (device_path, target_files_rel_paths) in DIR_SEARCH_PATHS.items():
if path.startswith(device_path):
suffix = path[len(device_path):]
return [(rel_path + suffix) for rel_path in target_files_rel_paths]
raise RuntimeError(('Unrecognized path from checkvintf --dump-file-list: ' + path))
out = common.RunAndCheckOutput(['checkvintf', '--dump-file-list'])
paths = out.strip().split('\n')
paths = sum((PathToPatterns(path) for path in paths if path), [])
return paths
|
def CheckVintfFromTargetFiles(inp, info_dict=None):
'\n Checks VINTF metadata of a target files zip.\n\n Args:\n inp: path to the target files archive.\n info_dict: The build-time info dict. If None, it will be loaded from inp.\n\n Returns:\n True if VINTF check is skipped or compatible, False if incompatible. Raise\n a RuntimeError if any error occurs.\n '
input_tmp = common.UnzipTemp(inp, (GetVintfFileList() + UNZIP_PATTERN))
return CheckVintfFromExtractedTargetFiles(input_tmp, info_dict)
| -2,080,881,480,362,148,600
|
Checks VINTF metadata of a target files zip.
Args:
inp: path to the target files archive.
info_dict: The build-time info dict. If None, it will be loaded from inp.
Returns:
True if VINTF check is skipped or compatible, False if incompatible. Raise
a RuntimeError if any error occurs.
|
tools/check_target_files_vintf.py
|
CheckVintfFromTargetFiles
|
FabriSC/Alioth-SC
|
python
|
def CheckVintfFromTargetFiles(inp, info_dict=None):
'\n Checks VINTF metadata of a target files zip.\n\n Args:\n inp: path to the target files archive.\n info_dict: The build-time info dict. If None, it will be loaded from inp.\n\n Returns:\n True if VINTF check is skipped or compatible, False if incompatible. Raise\n a RuntimeError if any error occurs.\n '
input_tmp = common.UnzipTemp(inp, (GetVintfFileList() + UNZIP_PATTERN))
return CheckVintfFromExtractedTargetFiles(input_tmp, info_dict)
|
def CheckVintf(inp, info_dict=None):
'\n Checks VINTF metadata of a target files zip or extracted target files\n directory.\n\n Args:\n inp: path to the (possibly extracted) target files archive.\n info_dict: The build-time info dict. If None, it will be loaded from inp.\n\n Returns:\n True if VINTF check is skipped or compatible, False if incompatible. Raise\n a RuntimeError if any error occurs.\n '
if os.path.isdir(inp):
logger.info('Checking VINTF compatibility extracted target files...')
return CheckVintfFromExtractedTargetFiles(inp, info_dict)
if zipfile.is_zipfile(inp):
logger.info('Checking VINTF compatibility target files...')
return CheckVintfFromTargetFiles(inp, info_dict)
raise ValueError('{} is not a valid directory or zip file'.format(inp))
| -9,148,898,699,179,064,000
|
Checks VINTF metadata of a target files zip or extracted target files
directory.
Args:
inp: path to the (possibly extracted) target files archive.
info_dict: The build-time info dict. If None, it will be loaded from inp.
Returns:
True if VINTF check is skipped or compatible, False if incompatible. Raise
a RuntimeError if any error occurs.
|
tools/check_target_files_vintf.py
|
CheckVintf
|
FabriSC/Alioth-SC
|
python
|
def CheckVintf(inp, info_dict=None):
'\n Checks VINTF metadata of a target files zip or extracted target files\n directory.\n\n Args:\n inp: path to the (possibly extracted) target files archive.\n info_dict: The build-time info dict. If None, it will be loaded from inp.\n\n Returns:\n True if VINTF check is skipped or compatible, False if incompatible. Raise\n a RuntimeError if any error occurs.\n '
if os.path.isdir(inp):
logger.info('Checking VINTF compatibility extracted target files...')
return CheckVintfFromExtractedTargetFiles(inp, info_dict)
if zipfile.is_zipfile(inp):
logger.info('Checking VINTF compatibility target files...')
return CheckVintfFromTargetFiles(inp, info_dict)
raise ValueError('{} is not a valid directory or zip file'.format(inp))
|
def test_default_reflection(self):
'Test reflection of column defaults.'
from sqlalchemy.dialects.mysql import VARCHAR
def_table = Table('mysql_def', MetaData(testing.db), Column('c1', VARCHAR(10, collation='utf8_unicode_ci'), DefaultClause(''), nullable=False), Column('c2', String(10), DefaultClause('0')), Column('c3', String(10), DefaultClause('abc')), Column('c4', TIMESTAMP, DefaultClause('2009-04-05 12:00:00')), Column('c5', TIMESTAMP), Column('c6', TIMESTAMP, DefaultClause(sql.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'))))
def_table.create()
try:
reflected = Table('mysql_def', MetaData(testing.db), autoload=True)
finally:
def_table.drop()
assert (def_table.c.c1.server_default.arg == '')
assert (def_table.c.c2.server_default.arg == '0')
assert (def_table.c.c3.server_default.arg == 'abc')
assert (def_table.c.c4.server_default.arg == '2009-04-05 12:00:00')
assert (str(reflected.c.c1.server_default.arg) == "''")
assert (str(reflected.c.c2.server_default.arg) == "'0'")
assert (str(reflected.c.c3.server_default.arg) == "'abc'")
assert (str(reflected.c.c4.server_default.arg) == "'2009-04-05 12:00:00'")
assert (reflected.c.c5.default is None)
assert (reflected.c.c5.server_default is None)
assert (reflected.c.c6.default is None)
assert re.match('CURRENT_TIMESTAMP(\\(\\))? ON UPDATE CURRENT_TIMESTAMP(\\(\\))?', str(reflected.c.c6.server_default.arg).upper())
reflected.create()
try:
reflected2 = Table('mysql_def', MetaData(testing.db), autoload=True)
finally:
reflected.drop()
assert (str(reflected2.c.c1.server_default.arg) == "''")
assert (str(reflected2.c.c2.server_default.arg) == "'0'")
assert (str(reflected2.c.c3.server_default.arg) == "'abc'")
assert (str(reflected2.c.c4.server_default.arg) == "'2009-04-05 12:00:00'")
assert (reflected.c.c5.default is None)
assert (reflected.c.c5.server_default is None)
assert (reflected.c.c6.default is None)
assert re.match('CURRENT_TIMESTAMP(\\(\\))? ON UPDATE CURRENT_TIMESTAMP(\\(\\))?', str(reflected.c.c6.server_default.arg).upper())
| -936,220,668,374,197,800
|
Test reflection of column defaults.
|
test/dialect/mysql/test_reflection.py
|
test_default_reflection
|
AngelLiang/hacking-sqlalchemy
|
python
|
def test_default_reflection(self):
from sqlalchemy.dialects.mysql import VARCHAR
def_table = Table('mysql_def', MetaData(testing.db), Column('c1', VARCHAR(10, collation='utf8_unicode_ci'), DefaultClause(), nullable=False), Column('c2', String(10), DefaultClause('0')), Column('c3', String(10), DefaultClause('abc')), Column('c4', TIMESTAMP, DefaultClause('2009-04-05 12:00:00')), Column('c5', TIMESTAMP), Column('c6', TIMESTAMP, DefaultClause(sql.text('CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP'))))
def_table.create()
try:
reflected = Table('mysql_def', MetaData(testing.db), autoload=True)
finally:
def_table.drop()
assert (def_table.c.c1.server_default.arg == )
assert (def_table.c.c2.server_default.arg == '0')
assert (def_table.c.c3.server_default.arg == 'abc')
assert (def_table.c.c4.server_default.arg == '2009-04-05 12:00:00')
assert (str(reflected.c.c1.server_default.arg) == )
assert (str(reflected.c.c2.server_default.arg) == "'0'")
assert (str(reflected.c.c3.server_default.arg) == "'abc'")
assert (str(reflected.c.c4.server_default.arg) == "'2009-04-05 12:00:00'")
assert (reflected.c.c5.default is None)
assert (reflected.c.c5.server_default is None)
assert (reflected.c.c6.default is None)
assert re.match('CURRENT_TIMESTAMP(\\(\\))? ON UPDATE CURRENT_TIMESTAMP(\\(\\))?', str(reflected.c.c6.server_default.arg).upper())
reflected.create()
try:
reflected2 = Table('mysql_def', MetaData(testing.db), autoload=True)
finally:
reflected.drop()
assert (str(reflected2.c.c1.server_default.arg) == )
assert (str(reflected2.c.c2.server_default.arg) == "'0'")
assert (str(reflected2.c.c3.server_default.arg) == "'abc'")
assert (str(reflected2.c.c4.server_default.arg) == "'2009-04-05 12:00:00'")
assert (reflected.c.c5.default is None)
assert (reflected.c.c5.server_default is None)
assert (reflected.c.c6.default is None)
assert re.match('CURRENT_TIMESTAMP(\\(\\))? ON UPDATE CURRENT_TIMESTAMP(\\(\\))?', str(reflected.c.c6.server_default.arg).upper())
|
def test_reflection_on_include_columns(self):
'Test reflection of include_columns to be sure they respect case.'
case_table = Table('mysql_case', MetaData(testing.db), Column('c1', String(10)), Column('C2', String(10)), Column('C3', String(10)))
try:
case_table.create()
reflected = Table('mysql_case', MetaData(testing.db), autoload=True, include_columns=['c1', 'C2'])
for t in (case_table, reflected):
assert ('c1' in t.c.keys())
assert ('C2' in t.c.keys())
reflected2 = Table('mysql_case', MetaData(testing.db), autoload=True, include_columns=['c1', 'c2'])
assert ('c1' in reflected2.c.keys())
for c in ['c2', 'C2', 'C3']:
assert (c not in reflected2.c.keys())
finally:
case_table.drop()
| -1,292,383,123,117,734,400
|
Test reflection of include_columns to be sure they respect case.
|
test/dialect/mysql/test_reflection.py
|
test_reflection_on_include_columns
|
AngelLiang/hacking-sqlalchemy
|
python
|
def test_reflection_on_include_columns(self):
case_table = Table('mysql_case', MetaData(testing.db), Column('c1', String(10)), Column('C2', String(10)), Column('C3', String(10)))
try:
case_table.create()
reflected = Table('mysql_case', MetaData(testing.db), autoload=True, include_columns=['c1', 'C2'])
for t in (case_table, reflected):
assert ('c1' in t.c.keys())
assert ('C2' in t.c.keys())
reflected2 = Table('mysql_case', MetaData(testing.db), autoload=True, include_columns=['c1', 'c2'])
assert ('c1' in reflected2.c.keys())
for c in ['c2', 'C2', 'C3']:
assert (c not in reflected2.c.keys())
finally:
case_table.drop()
|
@testing.provide_metadata
def test_nullable_reflection(self):
'test reflection of NULL/NOT NULL, in particular with TIMESTAMP\n defaults where MySQL is inconsistent in how it reports CREATE TABLE.\n\n '
meta = self.metadata
row = testing.db.execute("show variables like '%%explicit_defaults_for_timestamp%%'").first()
explicit_defaults_for_timestamp = (row[1].lower() in ('on', '1', 'true'))
reflected = []
for (idx, cols) in enumerate([['x INTEGER NULL', 'y INTEGER NOT NULL', 'z INTEGER', 'q TIMESTAMP NULL'], ['p TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP'], ['r TIMESTAMP NOT NULL'], ['s TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'], ['t TIMESTAMP'], ['u TIMESTAMP DEFAULT CURRENT_TIMESTAMP']]):
Table(('nn_t%d' % idx), meta)
testing.db.execute(('\n CREATE TABLE nn_t%d (\n %s\n )\n ' % (idx, ', \n'.join(cols))))
reflected.extend(({'name': d['name'], 'nullable': d['nullable'], 'default': d['default']} for d in inspect(testing.db).get_columns(('nn_t%d' % idx))))
if testing.db.dialect._is_mariadb_102:
current_timestamp = 'current_timestamp()'
else:
current_timestamp = 'CURRENT_TIMESTAMP'
eq_(reflected, [{'name': 'x', 'nullable': True, 'default': None}, {'name': 'y', 'nullable': False, 'default': None}, {'name': 'z', 'nullable': True, 'default': None}, {'name': 'q', 'nullable': True, 'default': None}, {'name': 'p', 'nullable': True, 'default': current_timestamp}, {'name': 'r', 'nullable': False, 'default': (None if explicit_defaults_for_timestamp else ('%(current_timestamp)s ON UPDATE %(current_timestamp)s' % {'current_timestamp': current_timestamp}))}, {'name': 's', 'nullable': False, 'default': current_timestamp}, {'name': 't', 'nullable': (True if explicit_defaults_for_timestamp else False), 'default': (None if explicit_defaults_for_timestamp else ('%(current_timestamp)s ON UPDATE %(current_timestamp)s' % {'current_timestamp': current_timestamp}))}, {'name': 'u', 'nullable': (True if explicit_defaults_for_timestamp else False), 'default': current_timestamp}])
| -7,641,466,202,760,821,000
|
test reflection of NULL/NOT NULL, in particular with TIMESTAMP
defaults where MySQL is inconsistent in how it reports CREATE TABLE.
|
test/dialect/mysql/test_reflection.py
|
test_nullable_reflection
|
AngelLiang/hacking-sqlalchemy
|
python
|
@testing.provide_metadata
def test_nullable_reflection(self):
'test reflection of NULL/NOT NULL, in particular with TIMESTAMP\n defaults where MySQL is inconsistent in how it reports CREATE TABLE.\n\n '
meta = self.metadata
row = testing.db.execute("show variables like '%%explicit_defaults_for_timestamp%%'").first()
explicit_defaults_for_timestamp = (row[1].lower() in ('on', '1', 'true'))
reflected = []
for (idx, cols) in enumerate([['x INTEGER NULL', 'y INTEGER NOT NULL', 'z INTEGER', 'q TIMESTAMP NULL'], ['p TIMESTAMP NULL DEFAULT CURRENT_TIMESTAMP'], ['r TIMESTAMP NOT NULL'], ['s TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP'], ['t TIMESTAMP'], ['u TIMESTAMP DEFAULT CURRENT_TIMESTAMP']]):
Table(('nn_t%d' % idx), meta)
testing.db.execute(('\n CREATE TABLE nn_t%d (\n %s\n )\n ' % (idx, ', \n'.join(cols))))
reflected.extend(({'name': d['name'], 'nullable': d['nullable'], 'default': d['default']} for d in inspect(testing.db).get_columns(('nn_t%d' % idx))))
if testing.db.dialect._is_mariadb_102:
current_timestamp = 'current_timestamp()'
else:
current_timestamp = 'CURRENT_TIMESTAMP'
eq_(reflected, [{'name': 'x', 'nullable': True, 'default': None}, {'name': 'y', 'nullable': False, 'default': None}, {'name': 'z', 'nullable': True, 'default': None}, {'name': 'q', 'nullable': True, 'default': None}, {'name': 'p', 'nullable': True, 'default': current_timestamp}, {'name': 'r', 'nullable': False, 'default': (None if explicit_defaults_for_timestamp else ('%(current_timestamp)s ON UPDATE %(current_timestamp)s' % {'current_timestamp': current_timestamp}))}, {'name': 's', 'nullable': False, 'default': current_timestamp}, {'name': 't', 'nullable': (True if explicit_defaults_for_timestamp else False), 'default': (None if explicit_defaults_for_timestamp else ('%(current_timestamp)s ON UPDATE %(current_timestamp)s' % {'current_timestamp': current_timestamp}))}, {'name': 'u', 'nullable': (True if explicit_defaults_for_timestamp else False), 'default': current_timestamp}])
|
def register(linter: PyLinter) -> None:
'Register the plugin'
register_checkers(linter)
suppress_warnings(linter)
| -1,476,581,473,740,617,000
|
Register the plugin
|
pylint_django_translations/plugin.py
|
register
|
troyjfarrell/pylint_django_translations
|
python
|
def register(linter: PyLinter) -> None:
register_checkers(linter)
suppress_warnings(linter)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.